Arduino Serial Communication Experiment

Arduino Serial Communication

Difficulty Level: Beginner

In this experiment, you'll learn how to use serial communication to exchange data between an Arduino and your computer. This can be useful for debugging, displaying sensor values, or controlling the Arduino via a computer.

Needed Components with eBay Links

Understanding Serial Communication

Serial communication is a method of transmitting data one bit at a time. The Arduino has a built-in serial port that communicates over pins 0 (RX) and 1 (TX). When connected to your computer via USB, these pins allow the Arduino to send and receive data to and from the serial monitor in the Arduino IDE.

Key Functions

Arduino Code

Here’s the code to test serial communication:


// Serial Communication Experiment

void setup() {
  // Start serial communication at 9600 baud
  Serial.begin(9600);
  Serial.println("Serial communication started");
}

void loop() {
  // Check if there is data available to read
  if (Serial.available() > 0) {
    // Read the incoming data
    char incomingData = Serial.read();

    // Print the received data back to the serial monitor
    Serial.print("Received: ");
    Serial.println(incomingData);

    // Send a response based on the received data
    if (incomingData == 'H') {
      Serial.println("Hello!");
    } else if (incomingData == 'B') {
      Serial.println("Goodbye!");
    }
  }

  delay(100);
}
            

Upload & Test

  1. Connect your Arduino to your computer using a USB cable.
  2. Open the Arduino IDE and copy the code above into the editor.
  3. In the IDE, select your board and the correct port.
  4. Upload the code by clicking the upload button.
  5. Open the Serial Monitor in the Arduino IDE (Tools > Serial Monitor) and set the baud rate to 9600.
  6. Type 'H' or 'B' into the input field and send the data to the Arduino. You should see a response in the Serial Monitor.

Code Breakdown

In the setup() function, we initialize serial communication with Serial.begin(9600). The Serial.println() function sends a message to the serial monitor when the Arduino starts.

In the loop() function, the Arduino checks if any data has been sent using Serial.available(). If data is available, it reads it using Serial.read(), then prints the received character back to the serial monitor. Depending on the received character, it sends a specific response: 'H' for "Hello!" and 'B' for "Goodbye!"

Conclusion

This experiment introduces you to serial communication on the Arduino. Understanding serial communication is crucial for debugging, reading sensor values, and controlling your Arduino from a computer. Experiment with different inputs to expand your understanding of serial communication.