#include <SPI.h>
#include <Ethernet.h>
#include <ArduinoRS485.h> // ArduinoModbus depends on the ArduinoRS485 library
#include <ArduinoModbus.h>
#include "ACS712.h" // Library for ACS712
int x;
// Ethernet configuration
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
IPAddress ip(192, 168, 1, 111);
EthernetServer ethServer(502);
ModbusTCPServer modbusTCPServer;
// ACS712 configuration
const int numSensors = 16; // Total number of sensors
const int sensorPins[numSensors] = {A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15};
ACS712 sensors[numSensors] = { // Create an array of ACS712 objects
ACS712(A0, 5.0, 1023, 185), ACS712(A1, 5.0, 1023, 185), ACS712(A2, 5.0, 1023, 185),
ACS712(A3, 5.0, 1023, 185), ACS712(A4, 5.0, 1023, 185), ACS712(A5, 5.0, 1023, 185),
ACS712(A6, 5.0, 1023, 185), ACS712(A7, 5.0, 1023, 185), ACS712(A8, 5.0, 1023, 185),
ACS712(A9, 5.0, 1023, 185), ACS712(A10, 5.0, 1023, 185), ACS712(A11, 5.0, 1023, 185),
ACS712(A12, 5.0, 1023, 185), ACS712(A13, 5.0, 1023, 185), ACS712(A14, 5.0, 1023, 185),
ACS712(A15, 5.0, 1023, 185)
};
void setup() {
// Serial communication
Serial.begin(9600);
while (!Serial);
Serial.println("Ethernet Modbus TCP Server with ACS712 Sensors");
// Ethernet initialization
Ethernet.begin(mac, ip);
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println("Ethernet shield not found. Stopping.");
while (true) delay(100);
}
ethServer.begin();
// Modbus server initialization
if (!modbusTCPServer.begin()) {
Serial.println("Failed to start Modbus TCP Server!");
while (true);
}
// Configure 16 holding registers
modbusTCPServer.configureHoldingRegisters(0x00, numSensors);
// Initialize ACS712 sensors
for (int i = 0; i < numSensors; i++) {
sensors[i].autoMidPoint(); // Automatically calculate midpoint
}
Serial.println("Modbus TCP Server is running with ACS712 sensors.");
}
void loop() {
// Listen for Modbus clients
EthernetClient client = ethServer.available();
if (client) {
Serial.println("New client connected.");
modbusTCPServer.accept(client);
while (client.connected()) {
modbusTCPServer.poll(); // Handle Modbus requests
updateHoldingRegisters(); // Update sensor values in holding registers
}
Serial.println("Client disconnected.");
}
}
void updateHoldingRegisters() {
for (int i = 0; i < numSensors; i++) {
int mA = sensors[i].mA_AC(); // Read current in mA for each sensor
if(mA>=600){
x=4;
}
else{
x=6;
}
modbusTCPServer.holdingRegisterWrite(i, x); // Update the Modbus holding register
// Debug output
Serial.print("Sensor ");
Serial.print(i);
Serial.print(": Current = ");
Serial.print(mA);
Serial.print(" mA ");
Serial.println(x);
}
}
here is the full code