Serial LED Control
Type 1 or 0 into the serial monitor to switch an LED on and off from your keyboard.
- Intermediate
- Communication
- 4 parts
Opens in your browser with the parts, wiring and code already in place. Press Run to watch it work, then change anything you like.
How it works
An LED with a resistor is on pin 13. There is no button: the input is your keyboard. The Serial tab has a box at the bottom, and whatever you type there is sent to the Arduino as if it had arrived down the USB cable.
In loop(), Serial.available() says how many characters are waiting. When there is at least one, Serial.read() takes it. If it is ‘1’ the sketch turns the LED on and replies “LED on”; if it is ‘0’ it turns the LED off and replies “LED off”; any other character is ignored. loop() has no delay, so it checks for new characters thousands of times a second. The pin number lives in a constant, ledPin, so there is only one place to change it.
Parts
- Arduino Uno
- Resistor
- LED
- GND
Wiring
- Arduino Uno D13 → Resistor A
- Resistor B → LED Anode (+)
- LED Cathode (-) → GND
Arduino code
// Serial LED Control
// Press Run, open the Serial tab, type 1 or 0 in the box at the bottom and
// press Enter. Your sketch reads each character with Serial.read().
const int ledPin = 13;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
Serial.println("Type 1 to turn the LED on, 0 to turn it off");
}
void loop() {
if (Serial.available() > 0) {
char command = Serial.read();
if (command == '1') {
digitalWrite(ledPin, HIGH);
Serial.println("LED on");
} else if (command == '0') {
digitalWrite(ledPin, LOW);
Serial.println("LED off");
}
}
}
Try changing it
- Add a third command: make ‘t’ toggle the LED. You will need a variable that remembers whether it is on.
- Reply to characters it does not understand: add a final else branch that prints “Unknown command”.