簡體   English   中英

在 Arduino 上通過 MQTT 將 int 數組發布為字符串

[英]Publish array of int as string over MQTT on Arduino

作為新手,這讓我瘋狂了幾個小時:

我有:

int relayStates[] = {0,0,1,1,0,1,0,0};

稍后在我的代碼中,我想使用 PubSubClient MQTT 將狀態發布為 char[] 為:

00110100

client.publish(topic,<here char[]>);

我嘗試了我能想到的所有轉換,但沒有任何效果。 有人可以幫助我嗎?

最好的問候,奧斯卡

讓我們以手動方式來學習如何從 int arrays 構建字符串 定義一個足夠大的全局 char 數組:

char textToSend [9] = {'\0'}; // takes 8 chars and a terminator

在這里,我們從relayStates[]復制並“轉換”為 char (適用於所有個位數)

  textToSend [0] = '\0'; // we reset the char array
 for(int i = 0; i < 8; i++) {
   if (relayStates[i] == 0) textToSend [i] = '0'; // SINGLE quote as it is a char
   if (relayStates[i] == 1) textToSend [i] = '1'; // SINGLE quote as it is a char
 }
 textToSend [8] = '\0'; // we terminate the char array
 client.publish(topic, textToSend); // we transfer the array content to MQTT

這種方法是透明的,memory 高效,可用於穩定的生產環境。
您可以添加的改進:

  • 從 int 數組大小中獲取 for 循環的結束值
  • 使其適用於 0 和 1 以外的整數 - 使用輔助數組進行轉換
    • char numBuffer [9] = {'\0'}; // takes 8 chars and a terminator for converting ints
    • itoa(relayStates[i], numBuffer,10); // converts an int to a base 10 dec char array
    • strcat(textToSend, numBuffer);

抱歉,這個話題的問題遲到了。 我嘗試了發布整數數組(0和1除外)的解決方案。 但是數組中只寫入了一個 int。

for (int i = 0; i <= 2; i++) {
  for (int j = 0; j <= 2; j++) {
    digitalWrite(adressPins[j], bitRead(i, j));
    delayMicroseconds(50);
  }
  feuchteRoh[i] = analogRead(33);
}

for (int i = 0; i <= 2; i++) {
  trockenheit[i] = map(feuchteRoh[i], rohTief, rohHoch, 0, 100);
}

for (int i = 0; i <= 2; i++) {
  feuchtigkeit[i] = 100 - trockenheit[i];
  Serial.println(feuchtigkeit[i]);
}

for (int i = 0; i <= 2; i++) {
  
 itoa(feuchtigkeit[i], numBuffer, 10);
}
Serial.println(numBuffer);


msg[0] = '\0';
strcat(msg, numBuffer);
msg[10] = '\0';
client.publish("ESP32/ Test", msg);

變量的名稱是德語,我希望這不是問題。

感謝您的幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM