MQTT pubSubClient callback(char* topic, byte* payload, unsigned int length) - How to handle payload.
HTML-код
- Опубликовано: 25 авг 2024
- Although numbers and text sent via MQTT may be in plain text, they arrive in a byte array. This byte array is easy to handle once you have changed the pointer type. Numbers formats such as 127, 3e2, 0x7F are supported. The latest updated code is shown below.
Please comment if this has helped you.
The original code is from the mqtt_esp8266.ino example supplied with the PubSubClient library by Nick Olleary ---- github.com/kno....
UPDATE - callback() function code is now modified to deal with negative numbers. Note also that for hexadecimal number use the atof() conversion.
if(isAlpha(charPointer[0])){
s =charPointer;
Serial.printf("Text as character string = %s, ", charPointer);
Serial.print("Text as a String object = ");
Serial.println(s); // For strings
}else{
f = atof(charPointer); // For floating point e.g. 12.345 and for hexadecimal numbers.
i = atoi(charPointer); // For integer numbers
Serial.printf("Float = %0.1f, int = %d
",f,i); // Display the result in float and int format.
}
That was brilliant! So may sketches have "handle message arrived" now I know how to handle it.
This was exactly what i needed to do in my code. Helpful video. Thank you!
You are most welcome, I'm gald to help.
Awesome, I've faffing about for the last 30 min trying to extract the numbers from that callback.
Cheers rich, It would be good to see what's happening live in the debugger. Makes it easier to follow
Thank you !
Thank you!!
You are very welcome!
I want to send a word, say left, right, up, down, stop. and write it to a global char variable to use.
This video is not about sending MQTT - there are plenty of videos already about this. However I suggest you just sendthe first letter (or numbers 1 to 4) and when the character is received use a switch/case statement to set your global. You may want to subscribe and hit the bell to be notified of a future video where I will cover this in my pixel cube code (see my much older pixelcube video).
@richardlangner i figured it out. Thank you for the videos though. I already subscribed.