Arduino modbus master/slave communication

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/

Live example


 

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;

}

}

 

About andreapiovesan

Freelance software developer View all posts by andreapiovesan

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: