I'm trying to find a library for running a Uno + W5100 shield as Modbus Slave . I need to use FC03 (read holding registers) and fc16( write multiple register) as this
I use Modbus TCP with my own functions, because two years ago when I wrote my project I could not find a working Modbus TCP library. From your post I discovered that Arduino created a modbus library last year.
So I tested it now. It is not good for AVR boards. It works, but it is large and uses dynamic memory allocation.
#include <Ethernet.h>
#include <ArduinoModbus.h>
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
EthernetClient ethClient;
ModbusTCPClient modbus(ethClient);
const IPAddress serverAddress(192,168,1,7);
const byte CONSUMPTION_METER_UID = 241;
unsigned int AC_POWER_REGISTER_ADDR = 40087;
unsigned int AC_POWER_SF_REGISTER_ADDR = 40091;
const byte AC_POWER_REQUEST_LENGTH = AC_POWER_SF_REGISTER_ADDR - AC_POWER_REGISTER_ADDR + 1;
void setup() {
Serial.begin(115200);
// start the Ethernet connection:
Serial.println("Initialize Ethernet with DHCP:");
Ethernet.init(10);
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
while (true) {
delay(1); // do nothing, no point running without Ethernet hardware
}
} else {
Serial.print(" DHCP assigned IP ");
Serial.println(Ethernet.localIP());
}
}
void loop() {
int err = modbusConnection();
if (err != 0) {
Serial.println(err);
} else {
int l = modbus.requestFrom(241, HOLDING_REGISTERS, AC_POWER_REGISTER_ADDR, AC_POWER_REQUEST_LENGTH);
if (l != AC_POWER_REQUEST_LENGTH) {
Serial.println(modbus.lastError());
} else {
short val = modbus.read();
for (int i = 0; i < AC_POWER_REQUEST_LENGTH - 2; i++) {
modbus.read();
}
short scaleFactor = modbus.read();
Serial.println(val * pow(10, scaleFactor));
}
}
delay(15000);
}
int modbusConnection() {
if (!modbus.connected()) {
modbus.stop();
if (!modbus.begin(serverAddress))
return -1;
}
return 0;
}
fleaplc:
Juray, is the code for running Arduino as Client?
yes, sorry you want a server. (modbus TCP has server and client, not slave and master). I missed that you want a server (slave).
but the library is not suitable for Uno.