Ascii Hex Strings -> Byte

Having bit of a nightmare here and no amount of forum searching and googling has managed to provide much of a helping hand.

I have a serial device connected, and when asked for data it sends back something like this $01 $00 $B1 $FF etc. etc.

So that's three ascii chars for each data byte (1 = '$', 2 = '0', 3 = '1' etc.), followed by a space.

I'm ok reading the data, but can I hell get the second and third characters combined and decoded into a bloody byte!?!?! Argh.

'$','B','1' needs to be decoded into byte with the value 177.


Does strtoi(string, null, base) not work on Arduinos?

Any other ideas?

There are at least two ways to do this.

Every time you encounter a $ in the incoming string, initialize a byte variable (val) to 0. For each character after that that is not a space, multiply val by 16 and add the new value (subtracting '0' if the character is in the range '0' to '9' or subtracting 'A' and adding 10 if the character is in the range 'A' to 'F'). The value is complete when you encounter a space or the end of the record.

Alternatively, you could replace the '$' with '0x' in the string of received characters, and then use sscanf with the %x format specifier to convert the strings to numbers.

You bloomin' little genius you. :D Good job you're not local or I'd have been forced to buy you a pint!

I used sscanf() since it was the easiest to adapt into my existing code and it worked perfectly.

Thank you very much.