我想改成
uint16_t status[8]; // change the values depend on the relay status: 0 or 1
到包含用逗号分隔的八个状态号的格式化表示形式的字符串,例如status = 0,status 1 =0 ...如此类推,status7 =0-string--> "0,0,0,0,0,0,0,0“
当我使用snprintf函数时,它在node-red的node中调试mqtt时返回"1073670272“。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);
}
}
在使用sprintf函数转换状态表之前,当我打印出状态表时,它返回八个0:Serial port screenshot
for (int a=0; a<8; a++)
{
Serial.print(status[a]);
}
PubSub函数要求:
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);
}
}
并返回一个空字符串:"“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);
串口:在sprintf之前:0 0 0 sprintf: 1 0 7 3 6 7 0 2
1073670208
发布于 2021-10-22 14:52:48
下面是你是如何做到这一点的:
#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);
}
https://stackoverflow.com/questions/69678203
复制相似问题