Arduino Serial Communication Basics: Control LEDs from Your Computer
Arduino Serial Communication Basics: Control LEDs from Your Computer
Serial communication is the simplest way to exchange data between your computer and Arduino. In this lesson, you’ll learn how to receive commands from the computer to control Arduino.
Required Components
- Arduino UNO R3 with USB cable
- Red LED 5mm x3
- Resistor 330 Ohm x3
- Breadboard
- Jumper wires
Circuit Diagram
Connect each LED through a 330 Ohm resistor to digital pins:
| Arduino | Component |
|---|---|
| Pin 3 | LED1 |
| Pin 4 | LED2 |
| Pin 5 | LED3 |
| GND | Cathode (-) of all LEDs (shared) |
Basic Serial Commands
Serial.available()
Checks if data has been sent from the computer. Returns a number greater than 0 if data is available.
if (Serial.available() > 0) {
// Code here runs when computer sends data
}
Serial.read()
Reads the incoming byte from the computer and stores it in a variable.
char key = Serial.read();
Serial.print() and Serial.println()
Sends data back to display on the Serial Monitor.
Serial.print("key : ");
Serial.println(key); // println adds newline
Code to Control LEDs via Serial
char key; // Variable to store incoming data
void setup() {
Serial.begin(9600); // Start serial at 9600 baud
// Set LED pins as OUTPUT
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
}
void loop() {
if (Serial.available() > 0) {
// When computer sends data
key = Serial.read(); // Store value in key variable
Serial.print("key : ");
Serial.println(key); // Echo back to Serial Monitor
// Check conditions to control LEDs
if (key == '1') {
digitalWrite(3, HIGH); // LED1 on
} else if (key == '2') {
digitalWrite(4, HIGH); // LED2 on
} else if (key == '3') {
digitalWrite(5, HIGH); // LED3 on
} else if (key == '0') {
digitalWrite(3, LOW); // Turn off LED1
digitalWrite(4, LOW); // Turn off LED2
digitalWrite(5, LOW); // Turn off LED3
}
}
}
How to Use
- Upload the code above to your Arduino UNO
- Open Serial Monitor via Tools > Serial Monitor or press Ctrl+Shift+M
- Set Baud Rate to 9600 (must match the code)
- Type a number and press Send or Enter
Test Results
| Number Typed | Result |
|---|---|
| 1 | LED1 turns on |
| 2 | LED2 turns on |
| 3 | LED3 turns on |
| 0 | All 3 LEDs turn off |
[image: Results table showing LED states when typing 1, 2, 3, 0 with corresponding LED on/breadboard illustrations]
Summary
The program waits for input from the Serial Monitor. When you type a number, the code stores it in the key variable and checks conditions. If a condition matches, the corresponding LED turns on or off as defined.
Using Serial communication makes debugging easy - you can see values returned via Serial.println() and command Arduino directly from your computer.
อยากทำโปรเจคแบบนี้?
รับทำโปรเจค Arduino / IoT จบงานไว ส่งงานครบ พร้อมสอน
If you need Arduino project service or urgent IoT development, see full service details on the home page
จ้างทำโปรเจคเลย