header banner
Default

Learning Arduino for Serial Communication


Serial Communications Signal Transmission

When working on large Arduino projects, it's quite common to run out of available pins to hook up components. Say you want to hook up multiple sensors/actuators with the urgent need to still preserve extra pins to feed a pin-hungry display module.

Unless you work some magic, it’s sometimes difficult to handle all these connections on a single Arduino board—especially when you decide to use smaller boards because you are pressed for space. That’s when serial communication comes into play.

Let’s explore what serial communication is and the ways in which you can set it up with Arduino for tasks such as distributed processing and general integration.

What Is Serial Communication?

Serial communication is a method of sending and receiving data between two or more electronic devices, one bit at a time over a single communication line. As the name suggests, data is being sent in "series".

Even just being able to upload sketches to your favorite Arduino board uses serial communication over USB.

Serial Communication Protocols on Arduino

Arduino connected to breadboard, sensor and LCD

Arduino boards are incredibly versatile and can communicate with a wide range of devices. They support four serial communication protocols: Soft Serial, SPI (Serial Peripheral Interface), standard UART (Universal Asynchronous Receiver-Transmitter), and I2C (Inter-Integrated Circuit). For more details, check out our comprehensive guide on how UART, SPI, and I2C serial communications work.

This tutorial uses basic sketches to show how you can set up a serial connection between two Arduino Uno boards using various protocols. Adapt the code to meet your specific requirements.

SPI (Serial Peripheral Interface)

SPI is a synchronous serial communication protocol that allows for high-speed communication between microcontrollers and peripheral devices. This protocol requires four wires for communication: SCK (Serial Clock), MOSI (Master Out Slave In), MISO (Master In Slave Out), and SS (Slave Select).

SPI-connection-diagram

The SPI.h library is very handy for this type of communication and must be included at the top of your sketch.

 #include <SPI.h> 

Here are the SPI pins on the Arduino Uno board:

Function

Pin Number (Digital)

Pin Number (ICSP Header)

MOS

11

4

MISO

12

1

SCK

13

3

SS

10 (Default)

1 (Alternative)

After initializing serial communication, you'll need to configure the communication pins.

 void setup() {
  SPI.begin(115200);
  // Set pin modes for SS, MOSI, MISO, and SCK
  pinMode(SS, OUTPUT);
  pinMode(MOSI, OUTPUT);
  pinMode(MISO, INPUT);
  pinMode(SCK, OUTPUT);

  // Set slave select (SS) pin high to disable the slave device
  digitalWrite(SS, HIGH);
}

The SS signal is used to tell the slave device when data is being transferred.

 // Select the slave
digitalWrite(SS, LOW);

// Send data to the slave device
SPI.transfer(data);

// Deselect the slave device
digitalWrite(SS, HIGH);

Here's how to connect two Arduino boards using SPI.

SPI communication 2 Arduino Uno boards wiring diagram

Code for the master board:

 #include <SPI.h>
const int slaveSelectPin = 10;
void setup() {
  SPI.begin(115200);
  pinMode(slaveSelectPin, OUTPUT);
}

void loop() {
  digitalWrite(slaveSelectPin, LOW);
  SPI.transfer('H');
  digitalWrite(slaveSelectPin, HIGH);
  delay(1000);
}

Code for the slave board:

 #include <SPI.h>
const int slaveSelectPin = 10;
void setup() {
  SPI.begin(115200);
  pinMode(slaveSelectPin, OUTPUT);
}

void loop() {
  if (digitalRead(slaveSelectPin) == LOW) {
    char receivedData = SPI.transfer('L');
    Serial.println(receivedData);
  }
}

Make sure that your devices share a common ground for proper configuration.

UART (Universal Asynchronous Receiver-Transmitter)

UART is an asynchronous serial communication protocol that allows communication between devices using only two wires: TX (Transmit) and RX (Receive). UART is commonly used for communication with devices such as GPS modules, Bluetooth modules, and other microcontrollers. Every Arduino board comes equipped with at least one port for UART.

UART connection diagram

The UART pins on popular Arduino boards include:

Board

Serial Pins

Serial1 Pins

Serial2 Pins

Serial3 Pins

Uno, Nano, Mini

0 (RX), 1 (TX)

N/A

N/A

N/A

Mega

0 (RX), 1 (TX)

19 (RX), 18 (TX)

17 (RX), 16 (TX)

15 (RX), 14 (TX)

You can get the full table from Arduino's online documentation about serial communication.

First, connect your boards like this:

UART/USART communication for 2 Arduino Uno boards wiring diagram

Then use this code for the sender board:

 void setup() {
   Serial.begin(9600);
}

void loop() {
  // Send a message over serial every second
  Serial.println("Hello from the sender board!");
  delay(1000);
}

Code for the receiver board:

 void setup() {
    Serial.begin(9600);
}

void loop() {
  // Check if there is any incoming data
  if (Serial.available() > 0) {
    // Read the incoming data and print it to the serial monitor
    String incomingData = Serial.readString();
    Serial.println(incomingData);
  }
}

The Arduino Uno operates on a 5V logic level while a computer's RS232 port uses a +/-12V logic level.

Directly connecting an Arduino Uno to an RS232 port can and will damage your board.

I2C (Inter-Integrated Circuit)

I2C is a synchronous serial communication protocol that allows communication between multiple devices using only two wires: SDA (Serial Data) and SCL (Serial Clock). I2C is commonly used for communication with sensors, EEPROMs, and other devices that need to transfer data over short distances.

I2C pins on the Arduino Uno are SDA (A4) and SCL (A5).

I2C-connection-diagram

We will create a simple program to establish a connection between two Arduino boards using I2C communication. But first, connect your boards like this:

Arduino_I2C connection on a breadboard

Code for the master board:

 #include <Wire.h>
void setup() {
  Wire.begin(); // join I2C bus as master
  Serial.begin(9600);
}

void loop() {
  Wire.beginTransmission(9); // transmit to slave device with address 9
  Wire.write('a'); // sends 'a' byte to slave device
  Wire.endTransmission(); // stop transmitting

  delay(500);
}

Code for the slave board:

 #include <Wire.h>
void setup() {
  Wire.begin(9); // join I2C bus as a slave with address 9
  Wire.onReceive(receiveEvent);
  Serial.begin(9600);
}

void loop() {
  delay(100);
}

void receiveEvent(int bytes) {
  while(Wire.available()) { // loop through all received bytes
    char receivedByte = Wire.read(); // read each byte received
    Serial.println(receivedByte); // print received byte on serial monitor
  }
}

What is SoftwareSerial?

The Arduino SoftwareSerial library was developed to emulate UART communication, allowing serial communication through any two digital pins on Arduino boards. It's useful when the hardware UART is already in use by other devices.

To set up SoftwareSerial, first include the SoftwareSerial library in the sketch.

 #include <SoftwareSerial.h> 

Then create an instance of the SoftwareSerial object by specifying the RX and TX pins to be used for communication.

 SoftwareSerial mySerial(2, 3); // RX, TX pins 

Here is an example code for Arduino that demonstrates the use of SoftwareSerial:

 #include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3); // RX, TX pins
void setup() {
  Serial.begin(9600); // start hardware serial
  mySerial.begin(9600); // start soft serial
}

void loop() {
  if (mySerial.available()) {
    Serial.write(mySerial.read()); // send received data to hardware serial
  }
  if (Serial.available()) {
    mySerial.write(Serial.read()); // send data from hardware serial to soft serial
  }
}

The Serial Library

The Serial library is a powerful tool in Arduino that allows communication between the microcontroller and a computer or other devices via a serial connection. Some common functions include:

Function

Description

Serial.begin(speed)

Initializes serial communication with a specified data rate.

Serial.print(data)

Sends data to the serial port for transmission as ASCII text.

Serial.write(data)

Sends raw binary data over the serial port.

Serial.available()

Returns the number of bytes available to read from the serial buffer.

Serial.flush()

Waits for outgoing serial data to complete transmission before continuing.

Serial.read()

Reads the first byte of incoming serial data and returns it as an integer.

Baud Rate and Serial Data Format

graphic of blue cube network with internet binary logos in each

Baud rate refers to the speed at which data is transferred over the serial connection. It represents the number of bits that are transmitted per second. The baud rate must be set the same on both the sender and receiver devices, otherwise the communication may be garbled or not work at all. Common baud rates for Arduino include 9600, 19200, 38400, and 115200.

Serial data format refers to the structure of the data being sent over the serial connection. There are three main components to serial data format: start bits, data bits, and stop bits.

  • Data Bits: The number of bits used to represent a single data byte.
  • Parity: An optional bit used for error checking. It can be set to none, even, or odd parity, depending on the requirements of the communication channel.
  • Stop Bits: The number of bits used to signal the end of a data byte.

The data format needs to be the same on both the transmitting and receiving devices to ensure proper communication. Here is an example of how you can set specific data formats:

 void setup() {
  // Set up serial communication with 9600 baud rate, 8 data bits, no parity, and 1 stop bit
  Serial.begin(9600, SERIAL_8N1);
}

Here, SERIAL_8N1 represents the data format with 8 data bits, no parity, and 1 stop bit. Other options such as SERIAL_7E1, SERIAL_8O2, etc., can be used depending on the specific requirements of the project.

Serial Talk

Arduino boards provide various serial communication options that allow for efficient and reliable data exchange between devices. By understanding how to set up serial communication protocols on the Arduino IDE, you can leverage the power of distributed processing or greatly reduce the number of wires used in your projects.

Sources


Article information

Author: Carla Solis

Last Updated: 1703684762

Views: 528

Rating: 3.8 / 5 (112 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Carla Solis

Birthday: 1975-11-18

Address: 343 Erica Mountains, Collinborough, GA 40303

Phone: +4356199841259053

Job: Dental Hygienist

Hobby: Meditation, Crochet, Board Games, Swimming, Aquarium Keeping, Calligraphy, Skateboarding

Introduction: My name is Carla Solis, I am a enterprising, tenacious, honest, steadfast, talented, exquisite, courageous person who loves writing and wants to share my knowledge and understanding with you.