Serial Communication Between Two Microcontrollers

Serial Communication Between Two Microcontrollers

Difficulty Level: Intermediate

In this tutorial, you'll learn how to use UART (Universal Asynchronous Receiver-Transmitter) to establish serial communication between two Arduino boards. This is useful for projects requiring data exchange between microcontrollers.

1. Required Components

2. Connection Setup

Follow these steps to set up the wiring between two Arduino boards:

Note: Keep both boards connected to your computer via USB to power them and upload code.

3. Arduino Code for Sender (Arduino 1)

The following code sends data from Arduino 1 to Arduino 2:


// Sender Code for Arduino 1

void setup() {
  // Initialize serial communication at 9600 baud
  Serial.begin(9600);
}

void loop() {
  // Send a message to the other Arduino
  Serial.println("Hello from Arduino 1");
  
  // Delay for 1 second before sending the next message
  delay(1000);
}
            

4. Arduino Code for Receiver (Arduino 2)

The following code receives and displays the data from Arduino 1:


// Receiver Code for Arduino 2

void setup() {
  // Initialize serial communication at 9600 baud
  Serial.begin(9600);
}

void loop() {
  // Check if data is available to read
  if (Serial.available() > 0) {
    // Read the incoming data
    String receivedMessage = Serial.readString();
    
    // Display the received data on the Serial Monitor
    Serial.print("Received: ");
    Serial.println(receivedMessage);
  }
}
            

5. Steps to Upload and Test

  1. Connect both Arduino boards to your computer using USB cables.
  2. Upload the sender code to Arduino 1.
  3. Upload the receiver code to Arduino 2.
  4. Open the Serial Monitor in the Arduino IDE for Arduino 2 to view the received data.
  5. You should see the message "Hello from Arduino 1" printed every second in Arduino 2's Serial Monitor.

6. Additional Tips

7. Conclusion

Congratulations! You've successfully implemented serial communication between two Arduino boards using UART. This foundational technique is essential for building interconnected systems in robotics, data logging, and IoT projects.