0

I'm using ESP32-C3 as hardware and Arduino IDE as my software core.

I receive a data from MQTT server and want to send it to another board using serial port as a hex number. However, it gets sent over serial port as ASCII characters.

Here is the code

unsigned char messageTemp; //data received from MQTT server
unsigned char cups_qty;    //data to be transferred to serial port

cups_qty = messageTemp; Serial.write(cups_qty);

For example if I receive messageTemp = 2 and send it to variable cups_qty and then send cups_qty to serial via Serial.write(cups_qty);, I receive the equivalent character not number.

For example :

msg from MQTT          >>>   messageTemp = 2   
                             cups_qty = messageTemp;   
send over serial port  >>>   Serial.write(cups_qty);

What I see on serial RealTerm terminal

(Display As Ascii)  >>>   2

(Display As Hex) >>> 32

(Display As int8) >>> 50

What I want to see on the terminal:

(Display As Ascii)  >>>   something unknown

(Display As Hex) >>> 02

(Display As int8) >>> 2

The confusing part is when I write something like Serial.write(2), it works just as expected.

jsotola
  • 1,554
  • 2
  • 12
  • 20

1 Answers1

1

You wrote:

if I receive messageTemp = 2 and send it to variable cups_qty and then send cups_qty to serial via Serial.write(cups_qty);, I receive the equivalent character not number.

This is incorrect. If you Serial.write(2) you will receive, at the other end, a byte with the numeric value 2. Try it!

The function Serial.write() transmits binary numbers as-is, without attempting any conversion. The following lines:

Serial.write('2');
Serial.write(0x32);
Serial.write(50);
Serial.print(2);

all do the same thing: transmit a byte with the numeric value 50. The three expressions '2', 0x32 and 50 are just three ways of writing the same number. Note that, unlike Serial.write(), Serial.print() formats the numbers in ASCII before transmitting.

It looks like your MQTT server sent you a number in ASCII, which you probably did not expect. If you know for sure that this is a single ASCII digit, you can convert it to binary by subtracting the ASCII code for '0', namely 48:

Serial.write(messageTemp - '0');  // send messageTemp in binary
Edgar Bonet
  • 45,094
  • 4
  • 42
  • 81