“MODBUS RTU Slave”
This example show the Slave mode of modbus, using the library of emelianov (is the best library that i found, most complete and working, tested on industrial field). Maybe the sintax or the order of code can be changed or improved, so play with that.
Copyright (C) 2019-2022 Alexander Emelianov ([email protected])
GitHub - emelianov/modbus-esp8266: Most complete Modbus library for Arduino. A library that allows your Arduino board to communicate via Modbus protocol, acting as a master, slave or both. Supports network transport (Modbus TCP) and Serial line/RS-485 (Modbus RTU). Supports Modbus TCP Security for ESP8266/ESP32.
#include <ModbusRTU.h>
#define RXPIN GPIO_NUM_18
#define TXPIN GPIO_NUM_17
#define REDEPIN GPIO_NUM_8
#define SLAVE_ID 10
ModbusRTU mb;
uint16_t p1,p2;
void setup() {
pinMode(DI0,INPUT);
pinMode(DO0,OUTPUT);
Serial1.begin(19200,SERIAL_8E1,RXPIN,TXPIN);
mb.begin(&Serial1,REDEPIN);
mb.slave(SLAVE_ID);
}
void loop() {
mb.addHreg(0); //Add Hold register 0
mb.Hreg(0,p1); // 40003 for PLC base 1 4x, only uint16 data (p1 and p2 are uint16 variables) when the master receive can change to signed
mb.addHreg(1); //Add Hold register 1
mb.Hreg(1,p2); // 40003 for PLC base 1 4x, only uint16 data
mb.addCoil(0,0,10); // Add 10 coils 0 to 10 with 0 value
mb.Coil(0,digitalRead(DI0)); // The input DI0 writes the coil 0 in the modbus protocl
digitalWrite(DO0,mb.Coil(5)); //The output DO0 was written by the coil 5 in the modbus protocol
mb.task(); //tasking of modbus
yield(); //logistics of modbus
//Pv=[(Pv high-Pv low)/(I high-I low)]*(I-I low)+Pv low
float Pressure= (((10.000-0.000)/(20.000-4.000))*(Process_mA-4.000)+0.000);
//Process_mA is from analog read example LOOK OUT
p1=Pressure*100; //Split the integers to send it on uint16 for the modbus
p2=Pressure/100; //Split the decimals to send it on uint16 for the modbus
}