How to send flowmeter sensor values from Arduino UNO (Slave) to CodeSys using Modbus TCP

74 Views Asked by At

I have a flowmeter (YF-S201) that is connected to the Arduino UNO with an ethernet shield. I already tested the flowmeter sensor in serial monitor so it works. Now I want to send these sensor values to the PLC in CodeSys using Modbus TCP. I have established a connection between PLC and Arduino UNO, however The PLC is not getting any values from the flowmeter sensor.

I tried 1,3 and 4 FC (function code) in CodeSys but non of them seem to receive the values.

For the Arduino UNO side, I tried 2 libraries but failed on both of them. The links for the libraries are:

andresarmento / modbus-arduino: https://github.com/andresarmento/modbus-arduino/tree/master

luizcantoni / mudbus: https://github.com/luizcantoni/mudbus/tree/master

Here is the code that I used to intergrate modbus-arduino by andresarmento library and the flowmeter code:

#include <SPI.h>
#include <Ethernet.h>
#include <Modbus.h>
#include <ModbusIP.h>

// Flowmeter and Modbus settings
const int FLOWMETER_SENSOR = 2; // Pin for flowmeter sensor
const int FLOWMETER_HREG = 100; // Holding register for flowmeter data

// ModbusIP object
ModbusIP mb;

// Flowmeter variables
volatile unsigned long pulse_freq = 0;
unsigned long lastTime;

void pulseCounter() {
    pulse_freq++;
}

void setup() {
    // Modbus TCP and Ethernet settings
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    byte ip[] = { 169, 254, 149, 2 }; 
    mb.config(mac, ip);

    // Flowmeter setup
    pinMode(FLOWMETER_SENSOR, INPUT);
    attachInterrupt(0, pulseCounter, RISING);
    mb.addHreg(FLOWMETER_HREG);
    lastTime = millis();
    Serial.begin(9600);
}

void loop() {
    mb.task();

    unsigned long currentTime = millis();
    if (currentTime - lastTime > 1000) { // Every second
        lastTime = currentTime;
        double flowRate = pulse_freq / 7.5; // Calculate flow rate
        mb.Hreg(FLOWMETER_HREG, flowRate); // Update Modbus register
        pulse_freq = 0; // Reset pulse count
        Serial.println(flowRate, DEC); 
    }
}

Can someone verify that the code is written correctly. I also would like to know FC 3 is the right function code for this sensor.

0

There are 0 best solutions below