My Cart

RS-232 Module Tutorial for Arduino, Raspberry Pi and Intel Galileo

Difficulty Level: Intermediate -


The RS-232 standard was first introduced in 1962 by the Radio Sector of the EIA. The original DTEs (data terminal equipment) were electromechanical teletypewriters, and the original DCEs (data circuit-terminating equipment) were usually modems. For many years, an RS-232-compatible port was a standard feature for serial communications, such as modem connections, on many computers. The RS-232 standard is still used to connect industrial equipment (such as PLCs), console ports and special purpose equipment.

The IEEE RS-232 standard defines electrical, signal timing, and size connectors. Use of a common ground, limits RS-232 to applications with relatively short cables. RS-232 connection consisting only of transmit data, receive data, and ground. RS-232 protocol uses bipolar signal. Valid signals are ±3 to +15 volts, the ±3V range is not a valid RS-232 level. Data signals between -3V and -15V represents a logic 1. The logic 0 is represented by a voltage of between +3V and +15V.

RS-232
Standard TIA-232-F
Cabling Single ended
Connector DB9
Network Topology             Point-to-point
Maximum Speed 115200 bps
Signaling Unbalanced
Mark(1) -5...-15
Space(0) +5...+15
Signals Full Duplex (Rx, TX)              

This list includes some of the more common uses of the standard:

  • Dial-up modems
  • GPS receivers (typically NMEA 0183 at 4,800 bit/s)
  • Bar code scanners and other point of sale devices
  • LED and LCD text displays
  • Satellite phones, low-speed satellite modems and other satellite based transceiver devices
  • Flat-screen (LCD and Plasma) monitors to control screen functions by external computer, other AV components or remotes
  • Test and measuring equipment such as digital multimeters and weighing systems
  • Updating Firmware on various consumer devices
  • Some CNC controllers
  • Uninterruptible power supply
  • Stenography or Stenotype machines
  • Software debuggers that run on a 2nd computer
  • Industrial field buses

1. Features

The pack we are going to use in this tutorial includes the RS-232 module and the Multiprotocol Radio Shield. The Multiprotocol Radio Shield can be used to connect two modules in order to combine the existing cooking-hacks modules and make connections between platforms. The RS-232 module uses the SPI bus. The SPI port allows more speed communication and frees up the UART for other purposes like debugging or to connect communication modules.

Electrical Features

The RS-232 module can be powered by the PC or by an external power supply. Some of the USB ports on computers are not able to give all the current the module needs to work, if your module have problems when it work, you can use an external power supply (12V - 2A) on the Arduino/RasberryPi. The RS-232 module can be used also with the Arduino XBee Shield

2. The board

RS-232 PCB

RS-232 over Arduino

The Multiprotocol Radio Shield has two sockets. The RS-232 module must be connected as shown in the next figures. Please, see the Multiprotocol Radio Shield Tutorial for more information. The RS-232 module can be used also with the Arduino XBee Shield

Get Arduino
Get the RS-232 module
Get the Multiprotocol Radio Shield

RS-232 over Raspberry Pi

Get Raspberry Pi
Get the Raspberry Pi to Arduino shields connection bridge
Get the RS-232 module for Raspberry Pi
Warnings:
  • The RS-232 can be connected in the two sockets of the Multiprotocol Radio Shield
  • The RS-2322 module is compatible with the XBee shield.
  • The RS-232 module has been tested with several devices, but we don't ensure the compatibility with all commercial devices.

3. The Library

The RS-232 module can be programmed in C++ language that lets you manage the RS-232 module in a simple way.

In order to ensure the same code is compatible in both platforms (Arduino and Raspberry Pi) we use the ArduPi libraries which allows developers to use the same code. Detailed info can be found here:

Using the library with Arduino

The RS-232 module uses UART port so is no necessary an special library. It can be managed with the HardwareSerial library of Arduino. The next zip includes the examples for managing the RS-232 module with no protocol (only physical layer) and using the Modbus protocol.

Download the RS-232 library for Arduino.

Libraries are often distributed as a ZIP file or folder. The name of the folder is the name of the library. Inside the folder will be the .cpp files, .h files and a examples folder.

To install the library, first quit the Arduino application. Then uncompress the ZIP file containing the library. For installing libraries, uncompress zip file. Drag these folders into your libraries folder. Under Windows, it will likely be called "My Documents\Arduino\libraries". For Mac users, it will likely be called "Documents/Arduino/libraries". On Linux, it will be the "libraries" folder in your sketchbook.

The library won't work if you put the .cpp and .h files directly into the libraries folder or if they're tested in an extra folder. Restart the Arduino application. Make sure the new library appears in the Sketch->Import Library menu item of the software.

Using the library with Raspberry Pi

Download the RS-232 library for Raspberry Pi. (Important: Library valid if you use a Raspberry Pi Connection Bridge v1.)

Creating a program that uses the library is as simple as putting your code in this template where it says "your Arduino code here"

Code:
//Include RS-232 library (it includes arduPi)


/*********************************************************
 *  IF YOUR ARDUINO CODE HAS OTHER FUNCTIONS APART FROM  *
 *  setup() AND loop() YOU MUST DECLARE THEM HERE        *
 * *******************************************************/

/**************************
 * YOUR ARDUINO CODE HERE *
 * ************************/

int main (){
        setup();
        while(1){
                loop();
        }
        return (0);
}
    

Compilation of the program can be done in two ways:

  • Compiling separately RS-232 and arduPi, and using them for compiling the program in a second step:

g++ -c arduPi.cpp -o arduPi.o
g++ -c RS232.cpp -o RS232.o
g++ -lpthread -lrt user-RS232-app.cpp arduPi.o RS232.o -o user-RS232-app
    

  • Compiling everything in one step:

g++ -lpthread -lrt user-RS232-app.cpp arduPi.cpp RS232.cpp -o user-RS232-app
    

Executing your program is as simple as doing:

sudo ./user-RS232-app
    

Using the library with Intel Galileo

The RS-232 module uses UART port so is no necessary an special library. It can be managed with the HardwareSerial library of Arduino. The next zip includes the examples for managing the RS-232 module with no protocol (only physical layer) and using the Modbus protocol.

Download the RS-232 library for Intel Galileo

The folders ModbusMater232 and ModbusSlave232are the libraries to use Modbus protocol over RS-232 physical layer. Drag these folders into your libraries folder. Under Windows, it will likely be called "My Documents\Arduino\libraries". For Mac users, it will likely be called "Documents/Arduino/libraries". On Linux, it will be the "libraries" folder in your sketchbook.

The library won't work if you put the .cpp and .h files directly into the libraries folder or if they're nested in an extra folder. Restart the Arduino application. Make sure the new library appears in the Sketch->Import Library menu item of the software.

4. Connecting Devices

Sending data through RS-232 physical layer

The RS-232 standard does not specify or recommend any communications protocol, so it can be used to send data in a very simple way. In this section we are going to send the temperature from a sensor to our PC. The RS-232 protocol is very useful for prototyping and send data to a PC in a very simple way.

Materials:

1. Connect the Multiprotocol Radio Shield over the Arduino UNO and the RS-232 module as shown in the figure.

2. Connect the cable to the serial port of your computer or of your device.

3. Connect the temperature sensor TMP36. This sensor needs only three connections: VCC, GND and signal. Please, see the datasheet of the sensor.

4. Upload the example code. In your serial monitor you should receive the temperature data.

Arduino

Code:
/*  
 *  RS-232 Module
 *  
 *  Copyright (C) Libelium Comunicaciones Distribuidas S.L. 
 *  http://www.libelium.com 
 *  
 *  This program is free software: you can redistribute it and/or modify 
 *  it under the terms of the GNU General Public License as published by 
 *  the Free Software Foundation, either version 3 of the License, or 
 *  (at your option) any later version. 
 *  a
 *  This program is distributed in the hope that it will be useful, 
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License 
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *  
 *  Version:          0.2
 *  Design:           David Gascon
 *  Implementation:   Ahmad Saad, Rubén Martín
 */

#include <Wire.h>

// Cooking API libraries
#include <arduinoUART.h>
#include <arduinoUtils.h>

void setup() {

  // Configure the multiplexer select pin
  pinMode(5, OUTPUT);

  Serial.begin(9600);
  delay(100);

  // Hello message
  Serial.println("Hello this is RS-232 communication send example!");
  delay(100);

}

void loop() {
  // Using the SOCKET0
  Utils.setONSocket0();
  Utils.setMUXSocket0();

  // Reading the analog input 1
  int analog0 = analogRead(A0);
  // Temperature formula TMP36
  float temperature =  100.0 * (analog0 * 5.0) / 1023 - 50;


  // Send data through RS-232 line
  Serial.print("Temperature from TMP36 : ");
  Serial.print(temperature);
  Serial.println(" C");

  delay(1000);
}

    

Raspberry Pi

Code:
/*  
 *  RS-232 Module
 *  
 *  Copyright (C) Libelium Comunicaciones Distribuidas S.L. 
 *  http://www.libelium.com 
 *  
 *  This program is free software: you can redistribute it and/or modify 
 *  it under the terms of the GNU General Public License as published by 
 *  the Free Software Foundation, either version 3 of the License, or 
 *  (at your option) any later version. 
 *  a
 *  This program is distributed in the hope that it will be useful, 
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License 
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *  
 *  Version:           1.0
 *  Design:            David GascĂłn 
 *  Implementation:    Ahmad Saad
 */
#include "arduPi.h"

void setup() {

  Serial.begin(9600);
  delay(100);

  // Hello message
  Serial.println("Hello, this is RS-232 communication send example!");
  delay(100);
}

void loop() {

  // Reading the analog input 1
  int analog0 = analogRead(0);
  // Temperature formula TMP36
  float temperature = 100.0 * (analog0 * 5.0) / 1023 - 50;


  // Send data through RS-232 line
  Serial.print("Temperature from TMP36: ");
  Serial.print(temperature,3);
  Serial.println(" C");

  delay(1000);
}

int main (){
  setup();
  while(1){
    loop();
  }
  return (0);
}
    

Intel Galileo

Code:
/*  
 *  RS-232 Module
 *  
 *  Copyright (C) Libelium Comunicaciones Distribuidas S.L. 
 *  http://www.libelium.com 
 *  
 *  This program is free software: you can redistribute it and/or modify 
 *  it under the terms of the GNU General Public License as published by 
 *  the Free Software Foundation, either version 3 of the License, or 
 *  (at your option) any later version. 
 *  a
 *  This program is distributed in the hope that it will be useful, 
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License 
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *  
 *  Version:           1.0
 *  Design:            David GascĂłn 
 *  Implementation:    Ahmad Saad
 */


void setup() {

  // Configure the multiplexer select pin
  pinMode(5, OUTPUT);

  Serial.begin(9600);
  Serial1.begin(9600);
  delay(100);

  // Hello message
  Serial.println("Hello this is RS-232 communication send example!");
  delay(100);

}

void loop() {
  // Using the SOCKET1
  digitalWrite(5, HIGH);

  // Reading the analog input 1
  int analog0 = analogRead(A0);
  // Temperature formula TMP36
  float temperature =  100.0 * (analog0 * 5.0) / 1023 - 50;


  // Send data through RS-232 line
  Serial1.print("Temperature from TMP36 : ");
  Serial1.print(temperature);
  Serial1.println(" C");

  delay(1000);
}
    

Dual protocol connection with Multriprotocol Radio Shield

The Multiprotocol Radio Shield can be used to connect two communication modules at the same time and make interconnections between different systems and devices. In the next example we are going to interconnect the RS-232 module with wireless protocol using and XBee module.

NOTE:
  • In AP=0 all data send trough the UART will be send by the XBee module.
  • The XBee 802.15.4 modules must be connected using external pins. These pins must have the pin 4 of the XBee cut or disconnected to avoid interferences between modules.

Connect the RS-232 module and XBee modules in the corresponding sockets as shown in the next image

If you are using 802.15.4, use external pins with pin4 disconnected.

You should receive all data in your gateway device

Code:
/*  
 *  RS-232 Module
 *  
 *  Copyright (C) Libelium Comunicaciones Distribuidas S.L. 
 *  http://www.libelium.com 
 *  
 *  This program is free software: you can redistribute it and/or modify 
 *  it under the terms of the GNU General Public License as published by 
 *  the Free Software Foundation, either version 3 of the License, or 
 *  (at your option) any later version. 
 *  a
 *  This program is distributed in the hope that it will be useful, 
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License 
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *  
 *  Version:          0.2
 *  Design:           David Gascon
 *  Implementation:   Ahmad Saad, Rubén Martín
 */


#include <Wire.h>

// Cooking API libraries
#include <arduinoUART.h>
#include <arduinoUtils.h>

void setup() {

  // Note: For viewing data in the serial monitor, you should open
  // the Serial at the same speed
  Serial.begin(9600);
  delay(100);

  //Print hello message.
  Serial.println("Hello this is RS-232 communication receive data example.");
}



void loop() { 
  // Using the SOCKET0
  Utils.setONSocket0();
  Utils.setMUXSocket0();

  // If data in response buffer
  if (Serial.available())
  {
    while (Serial.available()) {
      // Read one byte from the buffer      
      // Print data received in the serial monitor    
      Serial.print(char(Serial.read()));
    }

    Serial.print("\n");
  }

  delay(100);

}


    

Modbus communication protocol over RS-232

Modbus is a serial communications protocol originally published by Schneider Electric in 1979 for use with its programmable logic controllers (PLCs). Modbus is located in the level 2 of the OSI model, and uses a master/slave (or client-server) architecture. Simple and robust, it has since become a de facto standard communication protocol, and it is now a commonly available means of connecting industrial electronic devices. Modbus communication protocol presents the follow features:

  • It has been developed with industrial applications in mind
  • Openly published and royalty-free
  • Easy development and maintain

Modbus allows communication between many devices connected to the same network, for example a system that measures temperature and humidity and communicates the results to a computer. Many of the data types are named from its use in driving relays: a single-bit physical output is called a coil, and a single-bit physical input is called a discrete input or a contact.

Many devices uses Modbus over the RS-232 physical layer. First of all, you must be sure that your device is compatible with Arduino and Raspberry. In the device manual will be described the communication parameters (device address, baud rate...). You also must check that the device uses RTU format. There are many variants of Modbus protocols, but the Arduino library implements the RTU format. Modbus RTU is the most common implementation available for Modbus.

Parameter Setting
Baud 19200
Parity N
Data bits 8
Stop bit 1
Flow control None

The next step is to know what Modbus commands uses the device. The supported commands should be listed in a table. In the next Figure you can see an example of the Modbus commands extracted from a data sheet. The Modbus library for Arduino is compatible with the majority of the Modbus commands.

Command Name Command Number
Read Holding Register 03
Write (Preset) Single Register 06
Return Slave ID 17

Use the DB9 connector to connect the RS-232 module with the Modbus device

In our example, we are going to read the temperature value from our device. We can see in the register map, that the temperature value is stored in the register 30011 and is accessible with the function readHoldingRegisters, and is stored in 16 bits format (2 bytes). So the necessary function to get the value of the temperature is shown in the next code example.

Arduino

Code:
/*  
 *  RS-232 Module
 *  
 *  Copyright (C) Libelium Comunicaciones Distribuidas S.L. 
 *  http://www.libelium.com 
 *  
 *  This program is free software: you can redistribute it and/or modify 
 *  it under the terms of the GNU General Public License as published by 
 *  the Free Software Foundation, either version 3 of the License, or 
 *  (at your option) any later version. 
 *  a
 *  This program is distributed in the hope that it will be useful, 
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License 
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *  
 *  Version:          0.2
 *  Design:           David Gascon
 *  Implementation:   Ahmad Saad, Rubén Martín
 */


#include <Wire.h>

// Cooking API libraries
#include <arduinoUART.h>
#include <arduinoUtils.h>

// Include always this library when you are using Modbus functions
#include <ModbusSlave232.h>

// Create new mbs instance
ModbusSlave232 mbs;

// Slave registers
enum {        
  MB_0,   // Register 0
  MB_1,   // Register 1
  MB_2,   // Register 2
  MB_3,   // Register 3  
  MB_4,   // Register 4  
  MB_REGS // Dummy register. using 0 offset to keep size of array
};

int regs[MB_REGS];

void setup(){
  // Using the SOCKET0
  Utils.setONSocket0();
  Utils.setMUXSocket0();

  // Modbus slave configuration parameters
  // SlaveId 
  const unsigned char SLAVE = 1;
  // Baud rate   
  const long BAUD = 9600;            
  const unsigned PARITY = 'n';

  // Configure msb with config settings
  mbs.configure(SLAVE, BAUD, PARITY );

}

void loop()
{
  // Pass current register values to mbs
  mbs.update(regs, MB_REGS);

  // Read all the analog Inputs, and store the values in
  // the Modbus registers.   
  regs[MB_0] = analogRead(A0);  // Analog 0 value
  regs[MB_1] = analogRead(A1);  // Analog 1 value
  regs[MB_2] = analogRead(A3);  // Analog 2 value
  regs[MB_3] = analogRead(A3);  // Analog 3 value

  delay(1000);

}

    

Raspberry Pi

Code:
/*  
 *  RS-232 Module
 *  
 *  Copyright (C) Libelium Comunicaciones Distribuidas S.L. 
 *  http://www.libelium.com 
 *  
 *  This program is free software: you can redistribute it and/or modify 
 *  it under the terms of the GNU General Public License as published by 
 *  the Free Software Foundation, either version 3 of the License, or 
 *  (at your option) any later version. 
 *  a
 *  This program is distributed in the hope that it will be useful, 
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License 
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *  
 *  Version:           1.0
 *  Design:            David GascĂłn 
 *  Implementation:    Ahmad Saad
 */


#include "ModbusMaster232.h"
#include "arduPi.h"

// Instantiate ModbusMaster object as slave ID 1
ModbusMaster232 node(1);

// Define one address for reading
#define address 1
// Define the number of bits to read
#define bitQty 1

void setup()
{
  // Initialize Modbus communication baud rate
  node.begin(9600);

  // Print hello message
  Serial.println("Modbus communication over RS-232");
  delay(100);
}


void loop()
{
  // This variable will store the result of the communication
  // result = 0: no errors
  // result = 1: error occurred
  int result = node.readHoldingRegisters(address, bitQty);

  if (result != 0) {
    // If no response from the slave, print an error message
    printf("Communication error\n");
    delay(1000);
  }
  else {

    // If all ok
    printf("Read value: %d ", node.getResponseBuffer(0));   
    delay(1000);
  }
  
  printf("\n");
  delay(1000);

  // Clear the response buffer
  node.clearResponseBuffer();

}

int main (){
  setup();
  while(1){
    loop();
  }
  return (0);
}
    

Intel Galileo

Code:
/*  
 *  RS-232 Module
 *  
 *  Copyright (C) Libelium Comunicaciones Distribuidas S.L. 
 *  http://www.libelium.com 
 *  
 *  This program is free software: you can redistribute it and/or modify 
 *  it under the terms of the GNU General Public License as published by 
 *  the Free Software Foundation, either version 3 of the License, or 
 *  (at your option) any later version. 
 *  a
 *  This program is distributed in the hope that it will be useful, 
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License 
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *  
 *  Version:           1.0
 *  Design:            David GascĂłn 
 *  Implementation:    Ahmad Saad
 */


#include <ModbusMaster232.h>

// Instantiate ModbusMaster object as slave ID 1
ModbusMaster232 node(1);

// Define one address for reading
#define address 1
// Define the number of bits to read
#define bitQty 1

void setup()
{
  // Initialize Modbus communication baud rate
  node.begin(9600);

  // Print hello message
  Serial.println("Modbus communication over RS-232");
  delay(100);
}


void loop()
{
  // This variable will store the result of the communication
  // result = 0 : no errors
  // result = 1 : error occurred
  int result =  node.readHoldingRegisters(address, bitQty);

  if (result != 0) {
    // If no response from the slave, print an error message
    Serial.println("Communication error");
    delay(1000);
  }
  else {

    // If all ok
    Serial.print("Read value : ");

    // Print the read data from the slave
    Serial.print(node.getResponseBuffer(0));
    delay(1000);
  }

  Serial.print("\n");
  delay(1000);

  // Clear the response buffer
  node.clearResponseBuffer();

}
    

You should receive the data in your serial monitor.

Device Compatibility

This shield is tested and fully compatible with the following boards:

Arduino Boards

  • Arduino Uno

Raspberry Pi Boards

  • Raspberry Pi
  • Raspberry Pi (Model B+)
  • Raspberry Pi 2
  • Raspberry Pi 3




If you are interested in Internet of Things (IoT) or M2M projects check our open source sensor platform Waspmote which counts with more than 100 sensors available to use 'off the shelf', a complete API with hundreds of ready to use codes and a low consumption mode of just 0.7µA to ensure years of battery life.

Know more at:

Get the Starter Kits at: