bertmelis / esp32ModbusRTU

modbus RTU client for ESP32
MIT License
70 stars 44 forks source link

cast value #16

Closed buddhafragt closed 4 years ago

buddhafragt commented 4 years ago

Hello, I try to get a PZEM-003 working, the data value I receive is 2 x byte. I try it with this code:

modbus.readInputRegisters(0x02, 0x0000, 1);

modbus.onData([](uint8_t serverAddress, esp32Modbus::FunctionCode fc, uint16_t address, uint8_t* data, size_t length) {
 ValueRead = 0;
  Serial.printf("received data: id: %u, fc %u\ndata: 0x", serverAddress, fc);
for (size_t i = 0; i < length; ++i) {
  Serial.printf("%02x", data[i]);
}
Serial.print("\n");
ValueRead = *reinterpret_cast<uint8_t*>(data);
  });

The data value I recive is "0x04cf" and this is right. But with "reinterpret_cast" it is not working. Someone have a hint for me?

Greetings, Michael

bertmelis commented 4 years ago

You cast it to an uint8_t pointer. So dereferencing that returns the 8 bit value.

What type is ValueRead?

buddhafragt commented 4 years ago

Oh, how stupid, I change to uint16_t and it is working, thank you!

I have another problem now: I have 2 devices on the Modbus, 1 with SERIAL_8N2 and other with SERIAL_8N1 So I try to change the serial parameter on the fly in the code. But no sucess. I try to change like this:

Serial1.flush();
  Serial1.begin(9600, SERIAL_8N2, 17, 4, false);  // Modbus connection: SERIAL_8N2 für PZEM-003
     delay(1000);
  modbus.readInputRegisters(0x02, 0x0000, 1); 

But now no values coming in again.....

bertmelis commented 4 years ago

Can you confirm it works if you connect the separately?

buddhafragt commented 4 years ago

Yes, booth work with different serial parameters: SERIAL_8N2 and SERIAL_8N1.

bertmelis commented 4 years ago

There's nothing this lib can do for your problem but I would do some experiments: -try both separately on different buses

Are you sure you can't change you device's settings?

buddhafragt commented 4 years ago

Can I run 2 instances from the library? Maybe this is a solution, 2 serial ports with 2 different instances?

bertmelis commented 4 years ago

That should be possible.

bertmelis commented 4 years ago

An idea:

Can you just make the firmware print messages via Serial to your computer with 2 different baudrates. And monitor on your PC once with the first baudrate and again with the second. You should see first garbage + text and second text + garbage.

buddhafragt commented 4 years ago

switching between 2 different baudrates in Loop dont work!

bertmelis commented 4 years ago

Do you have the latest version of the Arduino core? Do you use Arduino IDE or something else (like VSCode + Platformio)?

I'm happy to support if it doesn't take too much of my time. But there's no apparent issue with this code. You might have better luck creating an issue in the Arduino for esp32 repo.

buddhafragt commented 4 years ago

Thanks for your time, I solve the problem with 2 different ports for the devices and 2 instances.