Reputation: 113
I'd like to convert
uint16_t status[8]; // change the values depend on the relay status: 0 or 1
to string containing a formatted representation of the eight status numbers seperated with commas e.g. status[0] = 0, status 1 = 0 ... so on, status[7] = 0 ---string--> "0, 0, 0, 0, 0, 0, 0, 0"
When I use snprintf function it returns me "1073670272" in debug mqtt in node in node-red. node-red debug message: 1073670272 value
// ...
uint16_t status[8];
char str[80];
long lastMsg = 0;
// ...
// loop ()
void loop() {
mb.task();
yield();
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 3000) {
lastMsg = now;
mb.readHreg(SLAVE_ID, 0x0001, status, 8, cbWrite);
sprintf(str, "%u", status);
client.publish("device1/relaysChannelStatus", str);
}
}
When I print out status table before converting it with sprintf function it returns eight 0: Serial port screenshot
for (int a=0; a<8; a++)
{
Serial.print(status[a]);
}
PubSub functions requirements:
boolean publish(const char* topic, const char* payload);
boolean publish(const char* topic, const char* payload, boolean retained);
boolean publish(const char* topic, const uint8_t * payload, unsigned int plength);
boolean publish(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained);
// @Ayxan Haqverdili
void loop() {
long now = millis();
if (now - lastMsg > 3000) {
lastMsg = now;
mb.readHreg(SLAVE_ID, 0x0001, status, 8, cbWrite);
auto const sz = 8;
uint16_t status[sz]; // uint16_t status[sz] = ...;
char str[sz * 7];
auto p = str;
auto off = sprintf(p, "%d", status[0]);
p+=off;
for (int i = 1; i < sz; ++i){
off = sprintf(p, ", %d", status[i]);
p += off;
}
client.publish("device1/relaysChannelStatus", p);
}
}
and it returns an empty string: "" empty string debug ""
@Barmak Shemirani
mb.readHreg(SLAVE_ID, 0x0001, status, 8, cbWrite);
Serial.println("BEFORE sprintf:");
for (int a=0; a<8; a++)
{
Serial.println(status[a]);
}
char statusString[20];
sprintf(statusString, "%d", status);
Serial.println("sprintf:");
for (int a=0; a<8; a++)
{
Serial.println(statusString[a]);
}
Serial.println(statusString);
Serial port: BEFORE sprintf: 0 0 0 0 0 0 0 0 sprintf: 1 0 7 3 6 7 0 2
1073670208
Upvotes: 0
Views: 743
Reputation: 30005
Here's how you do it:
#include <stdint.h>
#include <stdio.h>
int main() {
auto const sz = 8;
uint16_t status[sz] = { 1, 2, 3, 4, 5, 6, 7, 8 };
char str[sz * 7];
auto p = str;
p += sprintf(p, "%d", status[0]);
for (int i = 1; i < sz; ++i) {
p += sprintf(p, ", %d", status[i]);
}
puts(str);
}
Upvotes: 1