Introduction
Serial communication is a fundamental way to exchange data between a microcontroller and a PC. This experiment demonstrates how to use Arduino to send and receive data via the serial port, enabling interaction with the PC through the Serial Monitor or a custom interface.
Components Needed
- Arduino (e.g., Uno, Nano)
- USB cable for programming and communication
- Breadboard and jumper wires (optional, for additional peripherals)
Circuit Setup
No additional hardware is needed for basic serial communication. Connect your Arduino to your PC using a USB cable.
If testing with additional hardware (e.g., LEDs or buttons), follow these steps:
- Connect an LED with a 220Ω resistor to a digital pin (e.g., pin 13).
- Connect a push button to a digital input pin with a pull-down resistor (e.g., pin 2).
Code for Serial Communication
Upload the following code to your Arduino to test serial communication:
// Basic Serial Communication Example
void setup() {
Serial.begin(9600); // Start serial communication at 9600 baud
pinMode(13, OUTPUT); // Optional: LED pin
pinMode(2, INPUT_PULLUP); // Optional: Button pin
}
void loop() {
// Check if data is available from the PC
if (Serial.available() > 0) {
char command = Serial.read(); // Read the incoming data
if (command == 'H') {
digitalWrite(13, HIGH); // Turn on LED
Serial.println("LED ON");
} else if (command == 'L') {
digitalWrite(13, LOW); // Turn off LED
Serial.println("LED OFF");
} else {
Serial.println("Unknown command. Use 'H' or 'L'.");
}
}
// Optional: Send button state to PC
if (digitalRead(2) == LOW) { // Button pressed
Serial.println("Button Pressed");
delay(200); // Debounce delay
}
}
Explanation
Serial.begin(9600)
: Initializes serial communication at a baud rate of 9600.Serial.read()
: Reads a character from the serial input buffer.Serial.println()
: Sends a message to the Serial Monitor for debugging or interaction.- In the loop:
- Commands 'H' and 'L' control an LED connected to pin 13.
- The button state is continuously checked and sent to the PC when pressed.
Using the Serial Monitor
- Open the Arduino IDE Serial Monitor (or any serial terminal).
- Set the baud rate to 9600.
- Enter 'H' to turn on the LED or 'L' to turn it off.
- Observe responses from the Arduino in the Serial Monitor.
Troubleshooting
- If no response is received, verify the USB connection and correct COM port in the Arduino IDE.
- Ensure the baud rate in the Serial Monitor matches the one in the code (9600).
- Test with a basic serial echo program to verify communication.