Arduino Uno provides serial communication functionality, allowing it to exchange data with a computer or other microcontrollers. Serial communication is a very common feature in Arduino projects, often used for debugging, data transfer, and interaction with other devices. Below is a detailed introduction on how to use the serial communication feature of Arduino Uno.
1. Hardware Connection
Arduino Uno has a built-in USB-to-Serial converter (based on ATmega16U2 or ATmega8U2) that converts USB signals to TTL serial signals. This means you can directly connect the Arduino to a computer via a USB cable and use serial communication to send and receive data.
Additionally, Arduino Uno has two dedicated digital pins for serial communication:
– 0 (RX): Receive data (from external devices to Arduino).
– 1 (TX): Send data (from Arduino to external devices).
If you need to communicate with other serial devices (such as sensors, Bluetooth modules, etc.), you can connect the TX pin of these devices to the RX pin of Arduino and the RX pin of these devices to the TX pin of Arduino. Don’t forget to ensure that the ground (GND) is also connected together.
2. Initialize Serial Communication
In Arduino, use the Serial
object to handle serial communication. First, you need to initialize serial communication in the setup()
function, specifying the baud rate (i.e., the number of bits transmitted per second). Common baud rates include 9600, 115200, etc.
void setup() {
Serial.begin(9600); // Initialize serial communication with a baud rate of 9600
}
3. Sending Data
Use Serial.print()
and Serial.println()
functions to send data to the serial monitor or external devices. Serial.print()
sends data without a newline, while Serial.println()
automatically adds a newline character after sending data.
Example: Sending a simple string
void loop() {
Serial.print(“Hello, World!”); // Send string without newline
Serial.println(” This is a new line.”); // Send string and newline
delay(1000); // Send once every second
}
Example: Sending variable values
int sensorValue = 0;
void loop() {
sensorValue = analogRead(A0); // Read the value from analog pin A0
Serial.print(“Sensor Value: “);
Serial.println(sensorValue); // Send sensor value and newline
delay(1000); // Send once every second
}
4. Receiving Data
Use Serial.available()
function to check if there is available data to read. If data is available, you can use Serial.read()
function to read one byte of data. Serial.read()
returns an integer representing the ASCII value of the received character.
Example: Receiving and echoing data
void loop() {
if (Serial.available() > 0) { // Check for available data
char receivedChar = Serial.read(); // Read one character
Serial.print(“Received: “); // Echo the received character
Serial.println(receivedChar);
}
}
Example: Receiving and processing commands
You can also perform different actions based on the received commands. For example, light up an LED when receiving character ‘L’ and turn off the LED when receiving character ‘H’.
const int ledPin = 13; // Built-in LED connected to digital pin 13
void setup() {
pinMode(ledPin, OUTPUT); // Set LED pin as output
Serial.begin(9600); // Initialize serial communication
}
void loop() {
if (Serial.available() > 0) { // Check for available data
char receivedChar = Serial.read(); // Read one character
if (receivedChar == ‘L’) {
digitalWrite(ledPin, HIGH); // Light up LED
} else if (receivedChar == ‘H’) {
digitalWrite(ledPin, LOW); // Turn off LED
}
}
}
5. Using the Serial Monitor
The Arduino IDE provides a built-in serial monitor that allows you to easily send and receive serial data. To open the serial monitor, click the magnifying glass icon in the upper right corner of the Arduino IDE, or select Tools > Serial Monitor
.
– Baud Rate: Ensure the baud rate of the serial monitor matches the Serial.begin()
setting in your code.
– Newline: You can choose whether to automatically add a newline character when sending data (NL
, CR
, or Both NL & CR
), depending on whether your code requires a newline.
6. Handling Multi-byte Data
If you need to send or receive multiple bytes of data (such as floating-point numbers or structures), you can use Serial.write()
and Serial.readBytes()
functions. Serial.write()
can send a byte array, while Serial.readBytes()
can read a specified number of bytes.
Example: Sending and receiving floating-point numbers
float temperature = 25.5;
void setup() {
Serial.begin(9600);
}
void loop() {
// Send floating-point number
byte *bytePointer = (byte *)(&temperature);
for (int i = 0; i < sizeof(float); i++) {
Serial.write(bytePointer[i]);
}
// Receive floating-point number
if (Serial.available() >= sizeof(float)) {
float receivedTemperature;
byte receivedBytes[sizeof(float)];
Serial.readBytes(receivedBytes, sizeof(float));
memcpy(&receivedTemperature, receivedBytes, sizeof(float));
Serial.print(“Received Temperature: “);
Serial.println(receivedTemperature);
}
delay(1000);
}
7. Avoid Blocking the Main Loop
Using delay()
function will block the main loop, preventing timely response to other events. To achieve more efficient serial communication, you can use millis()
function for non-blocking delays.
Example: Non-blocking delay
unsigned long lastTime = 0;
const unsigned long interval = 1000; // Send once every second
void loop() {
unsigned long currentTime = millis();
if (currentTime – lastTime >= interval) {
lastTime = currentTime;
Serial.println(“Hello, World!”);
}
// Other code can continue executing here
}
8. Using Software Serial
If you need more serial ports, you can use SoftwareSerial
library to create software serial ports. This allows you to implement serial communication on any digital pin, but please note that the performance of software serial may not be as stable as hardware serial.
Example: Using SoftwareSerial
library
#include
// Define software serial pins
SoftwareSerial mySerial(10, 11); // RX, TX
void setup() {
Serial.begin(9600); // Initialize hardware serial
mySerial.begin(9600); // Initialize software serial
}
void loop() {
if (mySerial.available()) {
Serial.write(mySerial.read()); // Forward data received from software serial to hardware serial
}
if (Serial.available()) {
mySerial.write(Serial.read()); // Forward data received from hardware serial to software serial
}
}
Through the methods above, you can easily implement serial communication on Arduino Uno, whether interacting with a computer or exchanging data with other devices. Serial communication is not only suitable for debugging and data transfer but can also be used to build complex control systems and IoT projects. If you have more specific questions or need further assistance, feel free to ask!