Hello Friends, in this blog we will be controlling digital output with serial monitor command.
First let’s understand the working of serial monitor.
Serial monitor in Arduino IDE is a tool which allows communication between the computer and Arduino board via a serial connection, normally we use USB cable for connection.
What are the features of Serial Monitor?
It shows the data sent from the Arduino board by using the functions like Serial.print() or Serial.println().
It allows to send text or numeric data to the Arduino board, which can be read by function like, Serial.read() or Serial.parseInt(), thereafter you can use this data for further analysis and action.
We can use this tool for debugging and monitoring the function of the sketch.
There is a procedure to use the serial monitor, below are the steps given.
First initialize the serial communication in the sketch as given below. Normally baud rate is set 9600.
Void setup(){
Serial.begin(9600);
}
Data can be printed on the serial monitor as the below way
Serial.print(“Arduino is Good”);
It prints the data to the monitor.
Serial.println(“Arduino is Good”);
It prints the data to the monitor with new line.
Reading of the data can be done like the following steps.
If(Serial.available()>0){
Char input = Serial.read();
Serial.print(“You typed: “);
Serial.print(input);
}
Serial Monitor window can be opened by clicking to the Serial Monitor Icon on the top-right side of the Arduino IDE or just go to Tool > Serial Monitor.
Check the baud rate, it should be as same as you set in the sketch during initialization of serial communication. (9600).
Now we will write the sketch for controlling one digital output and also print the status on serial monitor.
// It defines the pin for the digital output, pin 2 is used
const int outputPin = 2;
void setup() {
// Initializes the digital output pin
pinMode(outputPin, OUTPUT);
// Initialize the Serial Monitor
Serial.begin(9600);
Serial.println("Send OUT1_ON to turn ON, OUT1_OFF to turn OFF");
}
void loop() {
// Checks if data is available on the Serial Monitor
if (Serial.available() > 0) {
// Reads the incoming command
String command = Serial.readStringUntil('\n');
command.trim(); // Removes any whitespace or newline characters
// Handles the commands
if (command == "OUT1_ON") {
digitalWrite(outputPin, HIGH);
Serial.println("Output 1 turned ON");
}
else if (command == "OUT1_OFF") {
digitalWrite(outputPin, LOW);
Serial.println("Output 1 turned OFF");
}
else {
Serial.println("Invalid command. Use OUT1_ON or OUT1_OFF");
}
}
}
After writing the code and compilation, upload it to the Arduino board, (I am using Arduino UNO)
Test the code
Open the serial monitor, and ensure the baud rate is 9600.
Send the command OUT1_ON, "Output 1 turned ON") should be printed to the serial monitor.
Send the command OUT1_OFF, "Output 1 turned OFF") should be printed to the serial monitor.
Comments
Post a Comment