Code No. 1 = Arduino + UART
String command = "";
void setup() {
Serial.begin(9600); // Initialize UART at 9600 baud
pinMode(13, OUTPUT); // Set pin 13 as an output (LED)
Serial.println("Send 'ON' or 'OFF' to control the LED");
}
void loop() {
if (Serial.available()) { // Check if data is available
char c = Serial.read(); // Read a character from Serial
if (c == '\n') { // Check for newline
command.trim(); // Clean up the command
if (command == "ON") {
digitalWrite(13, HIGH); // Turn the LED on
Serial.println("LED is ON");
} else if (command == "OFF") {
digitalWrite(13, LOW); // Turn the LED off
Serial.println("LED is OFF");
} else {
Serial.println("Unknown command");
}
command = ""; // Clear command for next input
} else {
command += c; // Add character to the command
}
}
}
Practice makes perfect.
Serial.begin(9600);
This line initializes the UART at 9600 baud rate.pinMode(13, OUTPUT);
Here we are setting a pin as the output, which we picked up the LED pin which is pin 13.Serial.println("")
This line prints inside the terminal or arduino's interfaceif (Serial.available()) {}
Why we use this line? Because we must be sure the user typed any message (ON or OFF), otherwise it won't function.char c = Serial.read()
After checking it's available, read the data and save inside the c characterif (c == '\n') { // Check for newline
command.trim(); // Clean up the command
if (command == "ON") {
digitalWrite(13, HIGH); // Turn the LED on
Serial.println("LED is ON");
} else if (command == "OFF") {
digitalWrite(13, LOW); // Turn the LED off
Serial.println("LED is OFF");
} else {
Serial.println("Unknown command");
}
command = ""; // Clear command for next input
} else {
command += c; // Add character to the command
}
Here is the core of the work. which is obvious except like
if (c == '\n') {
command.trim();
which is about checking and cleaning the line for typing inside the terminal
and command += c;
which is for typing more commands, not just one command