You can use RS-485 connection between all arduinos using serial port of all. For a half duplex connection for 4 arduinos, the setup can be like this:
What Do You Need:
- 4 RS-485 line drivers (like max485). One for each arduino
- if the distance between arduinos are short (under 1 mt) these will br enough
- if the distance between arduinos are long (over 2mt) you'll need to use at least 24 AWG twisted pair cable between them and 2 120 ohm resistors. These resistors will be line terminators.
- You can check max485 datasheet to see how to connect them
Setting Up:
To use rs485 with arduino and half duplex, you'll need 3 pins. 2 pins for rx and tx. 1 pin for transmit-enable. In half duplex mode, normally all nodes are in listening mode. To configure transmit enable, connect "drive enable" and "receive enable" pins of rs485 driver together. This will be our "transmit-enable" pin.
Connection:
| |
c RX |------->|RO 4
p TX |------->|DI 8
u D13 |------->|TE&RE^ 5
| |
Software:
Download this library (Mertbus). This library implements a basic transport layer. It is in alpha stage but functional. There is sample code in it and also a .net library.
The logic is similar to TCP/IP. Give every node an address between 0 and 126. 127 is the broadcast id. Means if you send data to id 127 all nodes will receive it. If you send data to only one node (ex. 2 ...) only target node will receive.
Sample:
#include "MertBus.h" //include header
#define TXEN 13 //transmit-enable pin
#define SELF_ID 1 //id of this node
MertBus mb; //communicator class
void setup() {
Serial.begin(57600); //prepare the serial port as usual
Serial.println("Begin init");
//then initialize mertbus instance with port, pin and id
mb = MertBus(Serial,TXEN,SELF_ID);
}
void loop() {
if(mb.checkData()) { //check if and valid data received
// reply to sender char[] and length, 26 chars
mb.reply("Incoming Data (SendData): ",26);
// reply to sender the received data
mb.reply(mb.Buffer,mb.ReceiveCount);
} else {
digitalWrite(13,HIGH);
delay(400);
digitalWrite(13,LOW);
delay(400);
}
}
To be a master, to send data (without replying to a message, starting a new one):
//buffer data to send, to_addr is target node address
//buffer_size is the size of data to send.
mb.sendData(char * buffer, uint8_t to_addr, uint8_t buffer_size)