Modbus TCP communication

I @abalalimoghaddam, yes I have been able to connect my arduino uno to the robot using this code in the arcuino board :

#include <SPI.h>
#include <Ethernet.h>
#include <ModbusEthernet.h>

const int analogInputPin = A0;
const unsigned long samplingInterval = 1;
const unsigned long windowDuration = 500;
//const unsigned long numSamples = windowDuration / samplingInterval;
int sampleCount = 0;
int totalValue = 0;

byte mac = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(10, 0, 0, 101);
IPAddress gateway(10, 0, 0, 1);
IPAddress subnet(255, 255, 255, 0);
const int MODBUS_PORT = 502;
const int MODBUS_SLAVE_ADDRESS = 231; // Choose a value between 1 and 247 (avoid 0 and 248)

ModbusEthernet mb;

//unsigned int samples[numSamples];
unsigned int currentIndex = 0; // Current index for inserting the sample
unsigned long lastSamplingTime = 0; // Time of the last sample
unsigned long lastSendTime = 0; // Time of the last sample

void setup() {
Ethernet.begin(mac, ip, gateway, gateway, subnet);
Serial.begin(9600);
Serial.begin(115200);
#if defined(AVR_LEONARDO)
while (!Serial) {}
#endif
Ethernet.init(5);

mb.connect((100,0,0,100),502); //Robot connection

delay(1000);
mb.server();

// Add a single Holding register to store the average value
mb.addIreg(30002);
}

void loop() {
unsigned long currentTime = millis();

// Perform sampling every ‘samplingInterval’ milliseconds
if (currentTime - lastSamplingTime >= samplingInterval) {
lastSamplingTime = currentTime;
unsigned int analogValue = analogRead(analogInputPin);

totalValue += analogValue;
sampleCount++;

}

if (currentTime - lastSendTime >= windowDuration) {
lastSendTime = currentTime;
if (sampleCount > 0) {

  unsigned int average = totalValue / sampleCount;

  // Write the average to the Modbus Holding register (Holding Register #100)
  mb.Ireg(30002,average);
  

  Serial.print("Average : ");
  Serial.println(average);

  sampleCount = 0;
  totalValue = 0;

}

}

mb.task(); // Handle Server Modbus TCP queries
delay(50);
}

2 Likes