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.
Other
534 stars 188 forks source link

How to read values from a hreg that contains 2 values #239

Closed Frans400 closed 2 years ago

Frans400 commented 2 years ago

Hi Thanks for this great library, this library the only liberty I got to work and understands as a non-programmer.

Hopefully someone can tell me how to solve an issue, most of the holding hreg on my power supply only have 1 value per hreg but a few have 2 values according to the user manual. If I try to read any of the hreg with 2 values my code returns 0. Can someone please fix my code if its even possible.

#include <ModbusRTU.h>
#include <SoftwareSerial.h>
ModbusRTU mb;
SoftwareSerial esp(25, 26);

bool bool_rtu(Modbus::ResultCode event, uint16_t transactionId, void* data) {
  return true;
}

int int_reading_10;     //this hreg holds 2 values(year and month)
int int_reading_243;     //this holding hreg only have one value

ModbusRTU mb;
SoftwareSerial esp(25, 26);

void TaskReadModbus( void * pvParameters ) {
  Serial2.begin(9600, SERIAL_8N1, 25, 26);
  mb.begin(&Serial2);
  mb.master();
  uint16_t uint16_t_reading_10;
  uint16_t uint16_t_reading_243;

  for (;;) {

    //this part is not working and returns a 0 value to int_reading_10
    if (!mb.slave()) {
      mb.readHreg(1, 10, &uint16_t_reading_10, 2,  bool_rtu);// slave address, hreg number , retuned value ,bool_rtu
    }
    mb.task();
    int_reading_10 = (int(uint16_t_reading_10));
    vTaskDelay(100);

    //this part is working and returns the correct value int_reading_243
    if (!mb.slave()) {
      mb.readHreg(1, 243, &uint16_t_reading_243, 1,  bool_rtu);
    }
    mb.task();
    int_reading_243 = (int(uint16_t_reading_243));
    vTaskDelay(100);

  }
}
emelianov commented 2 years ago
for (;;) {

    //this part is not working and returns a 0 value to int_reading_10
    if (!mb.slave()) {
      mb.readHreg(1, 10, &uint16_t_reading_10, 1,  bool_rtu);// slave address, hreg number , retuned value ,bool_rtu
//---------------------------------------------^
    }
    while(mb.slave()) // <--- Wait transaction to complete 
      mb.task();
    int_reading_10 = (int(uint16_t_reading_10));
    vTaskDelay(100);

    //this part is working and returns the correct value int_reading_243
    if (!mb.slave()) {
      mb.readHreg(1, 243, &uint16_t_reading_243, 1,  bool_rtu);
    }
    while(mb.slave()) // <--- Wait transaction to complete
      mb.task();
    int_reading_243 = (int(uint16_t_reading_243));
    vTaskDelay(100);

  }