1

Working on making a controller for a haunted house prop. Trying to get it to interface with a device.

Was able to use a serial analyzer to see what commands and values are being sent.

the hex codes being sent over serial for manual control is " 40 4d 01" which translates to "@M[?]"

the third byte 01 is the configuration state you want to have it change to. I'm using a byte to store the value between 0-255.

I'm stumped at how to send 2 ASCII characters but in the same Serial.write() command send a raw value, or at how to send them all as hex. I'm sure this is straight forward and I'm just unaware of some simple function.

2
  • hex is just a human representation of binary ... it is easier to write 4d instead of 01001101 ... it is just a number ... decimal 77
    – jsotola
    Oct 19 at 16:29
  • If you see "@M[?]", which means your are reading it as ASCII. 40 hex in ASCII is '@'. You probably send the data correctly if you are using Serail.write() but when you read the data with uint8_t incomingByte = Serial.read(), the return would be in byte(i.e. uint8_t) instead of char, to see the correct HEX, use Serial.print(incomingByte, HEX);.
    – hcheung
    Oct 20 at 3:50
4

First of all, I will challenge your assumption that you have to send the three bytes in the same call to Serial.write(). There is no real advantage in doing so. Serial output is handled through a memory buffer that is consumed by the serial port within an interrupt service routine. Serial.write() only writes to that memory buffer. Thus, you can simply:

Serial.write("@M");
Serial.write(1);

and the receiver will not see the difference. There will be no gap between the 'M' and the 1. There is no notion of “messages” or “frames” on a serial link, unless an upper layer protocol adds its own framing, which is not the case here.

Next, if you really want to issue a single call (futile as this is), you could

Serial.write("@M\1");

This, however, will not work if the last byte is zero. The method shown by the busybee is more general ans is able to send a zero-valued byte.

2

You can use a byte array for this:

    // at the appropriate place in your code:
    byte message[] = { '@', 'M', 0x01 };
    Serial.write(message, sizeof message);

If you need, you can prepare the array and just assign the value:

byte message[] = { '@', 'M', 0 };

// ...

    byte value = 0x01; // or any other assignment

    // at the appropriate place in your code:
    message[2] = value;
    Serial.write(message, sizeof message);

Not the answer you're looking for? Browse other questions tagged or ask your own question.