-->
Page 1 of 1

PubSubClient data type publish

PostPosted: Tue Sep 19, 2017 9:38 am
by DTesla
Hi all,

newbie question: :shock:

I'm using an ESP8266 with Arduino core, I get from the Serial monitor "0FF022333232FF", do a publish but this is what I receive on the broker "00FF 0002 0233 0302 32FF ".

I have to remove the '0' before the byte I need.

Code: Select all#include <PubSubClient.h>   
PubSubClient client(client);

uint8_t charIndex = 0;
uint8_t numChars = 39;
uint32_t lastCharMillis = 0;
uint8_t waitSerial = 25;
bool okPrint;
uint8_t manageIndex;
unsigned char msg[40];
byte bufferCounter = 0;
void setup()
{
  // put your setup code here, to run once:
  Serial.begin(115200);
//  Serial1.begin(115200);
}

void loop()
{
  // put your main code here, to run repeatedly:
  while (Serial.available())
  {
    byte incomingByte = Serial.read();
    char inChar = (char)incomingByte;
    Serial.print("I received: ");
    Serial.println(inChar, HEX);
    msg[charIndex] = inChar;     
    charIndex++;
    bufferCounter++;
    lastCharMillis = millis();
    okPrint = true;
    if (charIndex >= numChars) charIndex = numChars - 1;
  }
  if (millis() - lastCharMillis >= waitSerial && okPrint == true)
  {
    msg[charIndex] = '\0';
    manageIndex = charIndex;
    charIndex = 0;
   
    Serial.println("");
    Serial.print("Size of buffer ");
    Serial.println(bufferCounter);
    Serial.println("");   
    // Allocate the correct amount of memory for the payload copy
    byte* p = (byte*)malloc(bufferCounter);
    // Copy the payload to the new buffer
   
    memcpy(p, msg, bufferCounter);
    Serial.println("");
    Serial.print("Message: ");
    for (int u = 0; u < bufferCounter; u++)
    {
      Serial.print(p[u],HEX);
    }
    Serial.println("");   
    client.publish("myTopic", p, bufferCounter);   
    // Free the memory
    free(p);
    okPrint = false;
    bufferCounter = 0;
  }
}


Is it possible, or is it due to the library classes/sources ?

Thanks

Re: PubSubClient data type publish

PostPosted: Wed Sep 20, 2017 10:16 am
by tele_player
The problem is caused by the HEX format output not adding a leading 0.
printf() is much more flexible and powerful.

Line 27:
//Serial.println(inChar, HEX);
Serial.printf("%02X\n", inChar);

Line 54
//Serial.print(p[u],HEX);
Serial.printf("%02X", p[u]);