My Cart

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

Difficulty Level: Intermediate -


RS-485 is the most versatile communication standard. The RS-485 standard defines the electrical characteristics of drivers and receivers for use in digital systems. The standard is published by the Telecommunications Industry Association/Electronic Industries Alliance (TIA/EIA). RS-485 signals are used in a wide range of computer and automation systems and are used in programmable logic controllers and on factory floors. Since it is differential, it resists electromagnetic interference from motors and welding equipment. It may be used to control video surveillance systems or to interconnect security control panels and devices such as access control card readers. It does not specify or recommend any communications protocol. In the next table the electrical characteristics of the standard are defined.

The RS-485 module for Arduino and Raspberry allows users to perform industrial and domotic applications. The RS-485 is the most versatile communication standard in the standard. This a standard defining the electrical characteristics of drivers and receivers for use in digital systems. It does not specify or recommend any communications protocol. In the next table the electrical characteristics of the standart are defined.

RS-485
Standard EIA RS-485
Physical Media Twisted pair
Network Topology Point-to-point, Multi-dropped, Multi-point
Maximum Devices 32 drivers or receivers
Voltage Levels -7V to +12V
Mark(1) Positive Voltages (B-A > +200mV)
Space(0) Negative voltages (B-A < -200mV)
Available Signals Tx+/Rx+, Tx-/Rx-(Half Duplex)Tx+,Tx-,Rx+,Rx-(Full Duplex)

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

  • Industrial equipment
  • Machine to Machine (M2M) communications
  • Industrial Control Systems, including the most common versions of Modbus and Profibus
  • Programmable logic controllers
  • RS-485 is also used in building automation
  • Interconnect security control panels and devices

1. Features

The pack we are going to use in this tutorial includes the RS-485 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-485 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-485 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.

2. The board

RS-485 PCB

RS-485 over Arduino

The Multiprotocol Radio Shield has two sockets. The RS-485 module must be connected as shown in the next figures. Please, see the Multiprotocol Radio Shield Tutorial for more information.

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

RS-485 over Raspberry Pi

Get Raspberry Pi
Get the Raspberry Pi to Arduino shields connection bridge
Get the RS-485 module for Raspberry Pi
Warnings:
  • The RS-485 module must be connected in the corresponding socket as shown in this tutorial.
  • The RS-485 module is not compatible with the XBee shield. You have to use the Multiprotocol Radio Shield as shown in this tutorial.
  • The RS-485 module has been tested with several devices, but we don't ensure the compatibility with all commercial devices.

3. The Library

The RS-485 module counts with a C++ library that lets you manage the RS-485 module in a simple way. This library offers an simple-to-use open source system.

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-485 module includes a high level library functions for a easy manage. Before start using this functions you should download the library. The next zip includes all the files needed in several folders. These folders include the necessary file for using Modbus protocol in master and slave mode.

Download the RS-485 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

The RS-485 library for Raspberry Pi requires the ArduPi library and both libraries should be in the same path.

Download the RS-485 library for Raspberry Pi.

wget http://www.cooking-hacks.com/media/cooking/images/documentation/RS-485/arduPi_api_RS485_Modbus_v0_3.zip && unzip -u arduPi_api_RS485_Modbus_v0_3.zip && cd cooking/examples/RS485 && chmod +x cook.sh && cd ../../..  

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-485 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);
}
    

Follow the next steps to compile a sketch:

  • First, install ArduPi and SX1272 libraries.
    • ArduPi For Raspberry Pi:

      wget http://www.cooking-hacks.com/media/cooking/images/documentation/raspberry_arduino_shield/raspberrypi.zip && unzip raspberrypi.zip && cd cooking/arduPi && chmod +x install_arduPi && ./install_arduPi && rm install_arduPi && cd ../..
      

      ArduPi For Raspberry Pi 2:

      wget http://www.cooking-hacks.com/media/cooking/images/documentation/raspberry_arduino_shield/raspberrypi2.zip && unzip raspberrypi2.zip && cd cooking/arduPi && chmod +x install_arduPi && ./install_arduPi && rm install_arduPi && cd ../..
      		

      RS485 Library:

      wget http://www.cooking-hacks.com/media/cooking/images/documentation/RS-485/arduPi_api_RS485_Modbus_v0_3.zip && unzip -u arduPi_api_RS485_Modbus_v0_3.zip && cd cooking/examples/RS485 && chmod +x cook.sh && cd ../../..  
      
  • Go to examples:
    • cd cooking/examples/RS485/ 
      
  • Compile the example:
    • ./cook.sh my_example.cpp 
      
  • Run the sketch:
    • ./my_example.cpp_exe 
      

The script "cook.sh" compiles everything in their folders and the link in the examples foldes with the "_exe" executable.

  • Help: ./cook.sh
  • Clean: ./cook.sh -clean (It deletes all the "*.o" files. This is only necessary if you make changes in the libraries)

Using the library with Intel Galileo

The RS-485 module includes a high level library functions for a easy manage. Before start using this functions you should download the library. The next zip includes all the files needed in several folders. These folders include the necessary file for using Modbus protocol in master and slave mode.

Download the RS-485 library for Intel Galileo

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 often a keywords.txt file, examples folder, and other files required by the library.

To install the library, first quit the Arduino application. Then uncompress the ZIP file containing the library. For installing libraries , uncompress zip file. It should contain three folder called RS485, ModbusMaster485 and ModbusSlave. Drag these folders into this folder (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.

General RS-485 functions

Initialization functions

  baudRateConfig(unsigned long speed); // It sets the speed of communication   
  parityBit(bool state);               // Enables or disables the parity bit
  stopBitConfig(uint8_t numStopBits);  // Selects the number of stop bits  
  begin();                             // Powers the 485 module and opens the SPI
    

Send and receive functions

  uint8_t read(void);        // Receives data through the SPI
  send(uint8_t n);           // Sends data n through the SPI    
  send(int n);               // Sends data n through the SPI
  send(unsigned int n);      // Sends data n through the SPI   
  send(long n);              // Sends data n through the SPI 
  send(unsigned long n);     // Sends data n through the SPI 
  send(long n, uint8_t base);// Sends data n through the SPI
  send (const char *s);      // Sends data through the SPI. It sends a string s
    

Utile functions

  bool reset(void);       // All register bits are reset and all FIFOs are cleared
  flush(void);            // Clear both the receive and transmit FIFOs
  uint8_t available(void);// Returns true when the buffer is empty    
    

General Modbus function

Initialization functions

   ModbusMaster485();       // Creates class object using default Modbus slave ID 1
  ModbusMaster485(uint8_t);// Creates class object using specified Modbus slave ID
  begin();                 // Sets up the serial port using default 19200 baud rate
  begin(unsigned long );   // Sets up the serial port using specified baud rate  
    

Send and receive functions

uint8_t readCoils(uint16_t, uint16_t);             // Modbus function 0x01 Read Coils  
uint8_t readDiscreteInputs(uint16_t, uint16_t);    // Modbus function 0x02 Read Discrete Inputs
uint8_t readHoldingRegisters(uint16_t, uint16_t);  // Modbus function 0x03 Read Holding Registers
uint8_t readInputRegisters(uint16_t, uint8_t);     // Modbus function 0x04 Read Input Registers
uint8_t writeSingleCoil(uint16_t, uint8_t);        // Modbus function 0x05 Write Single Coil
uint8_t writeSingleRegister(uint16_t, uint16_t);   // Modbus function 0x06 Write Single Register
uint8_t writeMultipleCoils(uint16_t, uint16_t);    // Modbus function 0x0F Write Multiple Coils  
uint8_t writeMultipleRegisters(uint16_t, uint16_t);// Modbus function 0x10 Write Multiple Registers   
    

Utile functions

  void    setSlaveAddress(uint8_t);             // Changes the slave address
  uint8_t  available(void);                     // Returns the availbale data read
  uint16_t getResponseBuffer(uint8_t);          // Retrieve data from response buffer
  void     clearResponseBuffer();               // Clear Modbus response buffer
  uint8_t  setTransmitBuffer(uint8_t, uint16_t);// Place data in transmit buffer
  void     clearTransmitBuffer();               // Place data in transmit buffer     
    
NOTE:
  • More functions are included in the Modbus library.
  • For complete information and description of Modbus functions view the library files.

4. Connecting Devices

Sending data through RS-485 physical layer

The RS-485 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-485 protocol is very useful when you need to send data to medium distances.

Materials:

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

2. Connect the twisted pair cable observing proper polarity.

3. Connect the temperature sensor in a analog input.

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

Arduino / Intel Galileo

Code:
/*  
 *  RS-485 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 <arduinoUtils.h>

// Include always this library when you are using the RS-485 functions
#include <RS485.h>
//Include the SPI library
#include <SPI.h>
// Create an instance
RS485 myDevice = RS485();


void setup() {

  // Using the SOCKET0
  Utils.setONSocket0();
  Utils.setMUXSocket0();

  // Power on the USB for viewing data in the serial monitor
  Serial.begin(115200);
  delay(100);

  // Initializes the module and assigns the SPI
  if ( myDevice.begin() == 0) {
    Serial.println("RS-485 module started successfully");
  } else {
    Serial.println("RS-485 did not initialize correctly");
  }
  delay(100);

  // Configure the baud rate of the module
  myDevice.baudRateConfig(9600);
  // Configure the parity bit as disabled
  myDevice.parityBit(DISABLE);
  // Use one stop bit configuration
  myDevice.stopBitConfig(1);
  // Print hello message
  Serial.println("Hello this is RS-485 communication send data example.");
}



void loop() {
  // Reading the analog input 1
  int analog1 = analogRead(A1);
  //Reading the analog input 2
  int analog2 = analogRead(A2);

  // Send data through RS-485 line
  myDevice.send("Data from analog1 input : ");
  myDevice.send(analog1);
  myDevice.send("\n");

  myDevice.send("Data from analog2 input : ");
  myDevice.send(analog2);
  myDevice.send("\n");

  delay(1000);
}

    

Raspberry Pi

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

/*  
 *  RS-485 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 always this library when you are using the RS-485 functions
#include "RS485.h"
#include "arduPi.h"
// Create an instance
RS485 myDevice = RS485();




void setup() {


  // Initializes the module and assigns the SPI
  if (myDevice.begin() == 0) {
    printf("RS-485 module started successfully\n");
  } else {
    printf("RS-485 did not initialize correctly\n");
  } 

  // Configure the baud rate of the module
  myDevice.baudRateConfig(9600);
  // Configure the parity bit as disabled
  myDevice.parityBit(DISABLE);
  // Use one stop bit configuration
  myDevice.stopBitConfig(1);
  // Print hello message
  printf("Hello this is RS-485 communication send data example.\n");
}



void loop() {

  // Reading the analog input 1
  int analog1 = analogRead(1);
  //Reading the analog input 2
  int analog2 = analogRead(2);

  // Send data through RS-485 line
  myDevice.send("Data from analog1 input :");
  myDevice.send(analog1);
  myDevice.send("\n");

  myDevice.send("Data from analog2 input :");
  myDevice.send(analog2);
  myDevice.send("\n");
  

  delay(1000);
}

 

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

Modbus communication protocol over RS-485

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.

In this example we are going to show how to use th RS-485 module to connect Arduino and Raspbery Pi platforms to Modbus devices measurement devices.

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

Connect the signals A/B of the RS-485 module with the corresponding signal of the Modbus device. The name of these signal can change depending on the manufacturer. Usual names of these signal are A/B S+/S-, +/-, etc.

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 101 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.

Address Bytes Range Defaults
(°C /°F)
Register and Description
0 to 3 4 - - Serial Number -4 byte value. Read-only
4 to 5 2 - - Serial Version -2 byte value. Read-only
6 1 255 254 ADDRESS. Modbus device address
100 2 0-1000 - ROOM TEMPERATURE reading in DegF
101 2 0-600 - ROOM TEMPERATURE reading in DegC
304 2 0-1000 - Relative Humidity reading. Writing a humidity value to the register will do calibration.

Arduino / Intel Galileo

Code:
/*  
 *  RS-485 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 <arduinoUtils.h>

// Include always this library when you are using the RS-485 functions  
#include <RS485.h>
// Include the SPI library
#include <SPI.h>
// Create an instance
RS485 myDevice = RS485();

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

  // Initializes the serial for viewing data in the serial monitor 
  Serial.begin(115200);
  delay(100);

  // Initializes the module and assigns the SPI
  if ( myDevice.begin() == 0) {
     Serial.println("RS-485 module started successfully");
  } else {
     Serial.println("RS-485 did not initialize correctly");
  }
  delay(100);

  // Configure the baud rate of the module
  myDevice.baudRateConfig(115200);
  // Configure the parity bit as disabled 
  myDevice.parityBit(DISABLE);
  // Use one stop bit configuration 
  myDevice.stopBitConfig(1);  
  // Print hello message
  Serial.println("This is RS-485 communication receive data example.");
}


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

Raspberry Pi

g++ -c Modbusmaster485.cpp -o Modbusmaster485.o
g++ -lpthread -lrt Modbus_example.cpp arduPi.o RS485.o currentLoop.o -o  Modbus_example
    
Code:
/*  
 *  RS-485 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 these libraries for using the RS-485 and Modbus functions

#include "ModbusMaster485.h"
#include "arduPi.h"


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

// Define one addres for reading
#define address 101

// Define the number of bytes to read
#define bytesQty 2

void setup()
{
  pinMode(5, OUTPUT);
  digitalWrite(5, LOW);
  
  // Power on the USB for viewing data in the serial monitor
  Serial.begin(115200);
  delay(100);
  // Initialize Modbus communication baud rate
  node.begin(19200);

  // Print hello message
  printf("Modbus communication over RS-485\n");
  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, bytesQty);

  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 : \n");

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

  printf("\n");
  delay(2000);

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

}

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

You should receive the data in your serial monitor.

Dual protocol connection with Multriprotocol Radio Shield

The Multiprotocol Radio Shield can be used to connect two communication protocols at the same time and make interconnections between different systems and devices. In the next example we are going to interconnect a Modbus device over RS-485 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-485 module and XBee modules in the corresponding sockets as shown in the next image.

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

You should receive all data in your gateway device.

Arduino

Code:
/*  
 *  RS-485 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 these libraries for using the RS-485 and Modbus functions
#include <RS485.h>
#include <ModbusMaster485.h>
#include <SPI.h>

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

// Define one addres for reading
#define address 101

// Define the number of bytes to read
#define bytesQty 2

void setup()
{
  
  // XBee in SOCKET0
  pinMode(5, OUTPUT);
  digitalWrite(5, LOW);

  // Power on the USB for viewing data in the serial monitor
  Serial.begin(115200);
  delay(100);
  // Initialize Modbus communication baud rate
  node.begin(19200);

  // Print hello message
  Serial.println("Modbus communication over RS-485");
  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, bytesQty);

  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(2000);

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

}
    

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

Get the shields

Kits



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: