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.
    }

Комментарии • 12

  • @russellvickery5586
    @russellvickery5586 5 месяцев назад

    That was brilliant! So may sketches have "handle message arrived" now I know how to handle it.

  • @Nowisthetime01
    @Nowisthetime01 Год назад

    This was exactly what i needed to do in my code. Helpful video. Thank you!

  • @evabaroni6693
    @evabaroni6693 3 года назад

    Awesome, I've faffing about for the last 30 min trying to extract the numbers from that callback.

  • @alexkelly757
    @alexkelly757 3 года назад

    Cheers rich, It would be good to see what's happening live in the debugger. Makes it easier to follow

  • @user-th1ou8lm9q
    @user-th1ou8lm9q 3 месяца назад

    Thank you !

  • @AndreasBlindheim
    @AndreasBlindheim Год назад

    Thank you!!

  • @MickeyToler-ye9ds
    @MickeyToler-ye9ds 24 дня назад

    I want to send a word, say left, right, up, down, stop. and write it to a global char variable to use.

    • @richardlangner
      @richardlangner  24 дня назад

      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).

    • @MickeyToler-ye9ds
      @MickeyToler-ye9ds 24 дня назад

      @richardlangner i figured it out. Thank you for the videos though. I already subscribed.