I am pulling my hair out on this one...
I have written Modbus reader for an Arduino MEGA2560 board; and to see what I am reading, I Serial.print-ed some 106 values.
So far so good.
The values represent anything from single digit to uint16_t to float.
The MQTT publish function requires (const char *topic, const char *msg).
How do I convert these different values to the required char array?
For example a bunch of registers being read:
void read_ac_load ()
{
static uint8_t result = 1;
result = modbus.readHoldingRegisters(0x1f44, 4);
if (result == modbus.ku8MBSuccess)
{
Serial.print(F("AC_Load_Power...........: "));
Serial.println((int)modbus.getResponseBuffer(0x00) * 10);
Serial.print(F("AC_Load_Voltage.........: "));
Serial.println((int)modbus.getResponseBuffer(0x01) / 10.0, 1);
Serial.print(F("AC_Load_Frequency.......: "));
Serial.println((int)modbus.getResponseBuffer(0x02) / 10.0, 1);
Serial.print(F("AC_Load_Energy..........: "));
Serial.println((int)modbus.getResponseBuffer(0x03) / 10.0, 1);
}
else
{
display_error(result);
}
return;
}
I want to publish the topic (modbus1/data), the register address (8123), then the value (-350.4); like so:
modbus1/data/8123 -350.4
Do I really need to do (repeat) acrobatics like:
dtostrf(((int)modbus.getResponseBuffer(0x02) / 10.0, 1), 6, 1, g_tmp_buffer);
... and then copy the register to the topic, then the value..
This is cumbersome at best, more so for 106 registers.
I pondered over the Serial.print() function; it takes any data type. Can this be replicated?
In essence: now that I have tested that I get the values, I will get rid of the Serial.print() statements and replace these with MQTT publish commands. But building the strings, without using the String function, seems very cumbersome.
I thought I have one function and loop through the register. But this is not possible do to the different data conversions; e.g. some values need to be multiplied, others need to be divided.
Any hints appreciated.