Go Down

Topic: Converting from Int to byte to send over Serial to Raspberry Pi (Read 510 times) previous topic - next topic


I've been looking through the forums and some lines of codes I've tried ended up not compiling or not working at all.

I know there's a way to convert an int to a byte. I'm not entirely sure how to do it and I've tried using serial.write(variable, 2) to send something over but doesn't work. Or maybe it is working but I'm not sure how to receive and decipher it through c++ on the raspberry pi. I've been stuck on this issue for 2 days now. I've tried downloading a couple of libraries to correct this issue with no avail.

I just need a method to convert from int into a byte and then send it over to the Pi, for now at least.


It would be much simpler just to send the data in human readable form with Serial.print()

It is not clear from your question if you are only interested in the low byte of the int or whether you want to send both bytes. It sounds like you just want to send the low byte which you can do like this
Code: [Select]
myByte = (byte) myInt;

Two or three hours spent thinking and reading documentation solves most programming problems.


Robin's example does the conversion as per your requirement.

I however doubt somewhat that that is what you want; an int in Arduino land is two bytes and Robin's code throws away half of that (per your requirement).

If you want to send the complete int, you can use lowByte() and highByte to split and send the two bytes. Or you can use an union with an int and a byte-array of two bytes (the size of the int).

You also need to be aware of endianness where the two bytes of an int can be swapped because processors store them differently; if you don't receive the correct data, the first thing to do is to print each byte in hex and see of swapping the bytes gives you the correct result. As Robin indicated, sending numbers as text might be a lot easier; at the Pi side, you can use atoi or strtol to convert back from text to integer (an not having to worry about endianness).
If you understand an example, use it.
If you don't understand an example, don't use it.

Electronics engineer by trade, software engineer by profession. Trying to get back into electronics after 15 years absence.


Regardless of whether he's using Python 3, or unicode in Python 2, whch I'll grand you, the underlying point was that you were suggesting a solution with strings when the function explicitly disliked. At least you've addressed that now, so your answer is good. While it's only a minor detail, your answer is somewhat unorthodox because it converts a number into a string and converts that to bytes. An integer with 5 digits will end up having 5 bytes. It's just more direct to translate a number straight to its bytes representation, but that's nitpickin

Go Up