You are on page 1of 3

Arduino modbus

master/slave communication
By andreapiovesan

Hi, everybody this is the code I use on my application to exchange data between two Arduino
Uno r3 using a MAX 485 chip on RS485 network.

Arduino Modbus library download site:


http://code.google.com/p/simple-modbus/

Modbus slave code


#include <SimpleModbusSlave.h>

#define RXPin 0
#define TXPin 1
#define PTTPin 2

enum {

PARAM1,
PARAM2,
PARAM3, // add params as you want, here!
// leave this one
TOTAL_REGS_SIZE
// total number of registers for function 3 and 16 share the same register
array

};

unsigned int registers[TOTAL_REGS_SIZE];

void setup() {

// Modbus init
modbus_configure(9600, 2, 2, TOTAL_REGS_SIZE);

void loop() {

modbus_update(registers);

}
Modbus master code
#include <SimpleModbusMaster.h>

#define baud 9600


#define timeout 1000
#define polling 250
#define retry_count 10
#define TxEnablePin 8 // Pay attention! Use 3 if you want...

enum {

READ_P,
// leave this one
TOTAL_NO_OF_PACKETS
// total number of registers for function 3 and 16 share the same register
array

};

enum {

PARAM1,
PARAM2,
PARAM3, // add params as you want, here!
// leave this one
TOTAL_REGS_SIZE
// total number of registers for function 3 and 16 share the same register
array

};

Packet packets[TOTAL_NO_OF_PACKETS];
packetPointer readPacket = &packets[READ_P];

unsigned int slavedata[TOTAL_REGS_SIZE];

void setup()
{

// read 3 registers starting at address 0


readPacket->id = 2;
readPacket->function = READ_HOLDING_REGISTERS;
readPacket->address = 0;
readPacket->no_of_registers = TOTAL_REGS_SIZE;
readPacket->register_array = slavedata;

modbus_configure(baud, timeout, polling, retry_count, TxEnablePin, packets,


TOTAL_NO_OF_PACKETS);

}
int loop()
{

unsigned int connection_status = modbus_update(packets);

if (connection_status != TOTAL_NO_OF_PACKETS)
{

// You could re-enable the connection by:


packets[connection_status].connection = true;