Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mb.readHreg function sometimes does not get a value from the slave device #373

Open
arimukhlas opened this issue Nov 25, 2024 · 1 comment

Comments

@arimukhlas
Copy link

Hi @emelianov thanks for sharing great modbus library

mb.readHreg function sometimes does not get a value from the slave device,
How can I make it so that when it fails to get a value, it will call the function again several times, to ensure that the function always gets a value?

this is some of my sketch

void loop() {
  if ((unsigned long)(millis() - previousMillisSendData) >= 5000) {   
    reg32bit(); 
    previousMillisSendData = millis();
}

bool cbWriteTotalizer(Modbus::ResultCode event, uint16_t transactionId, void* data) {
  if (event != Modbus::EX_SUCCESS) {
    Serial.print("Fail Totz : 0x");
    Serial.println(event, HEX);
    buffTotalizer = 0;
    Serial.println(buffTotalizer);
  }
  else  {
    buffTotalizer = reunite32(regBuff3[0],regBuff3[1]);
    Serial.println(buffTotalizer);
  }
  return true;
}

void reg32bit(){
  uint16_t regBuff[2];
  if (!mb.slave()) {
    mb.readHreg(1, 3017, regBuff, 2, cbWriteTotalizer);
    while(mb.slave()) {
      mb.task();
      delay(20);
    }
    regBuff3[0] = regBuff[0];
    regBuff3[1] = regBuff[1];
  }
}

uint32_t reunite32 (uint16_t i, uint16_t j){
  uint32_t m = (uint32_t)(i & 0xFFFF)<<16|j;
  return m;
}

and this is the result
image

give me some hint to get rid of the error reading that appears uncertainly, thanks

@hacesoft
Copy link

Personally, I would call the mb.task() function about 100ms and once per second or as you need to read the data once per second using readHreg...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants