How to transmit binary data from C++ over serial

I'm using libSerial in linux to send the arduino an 8x8 array of 1s and 0s to control an led matrix.

Currently I'm having to transmit a stream of 64 ASCII characters but this seems very inefficient as I'm transmitting a lot more data than I need to be and then converting each lot of eight ASCII characters into a byte to send to a row of the led matrix. If I could get it to go faster I could get better framerates on the led matrix.

What I want to know is how can I transmit the stream of 1s and 0s as binary data rather than ASCII and then how to I receive this on the arduino?


The Serial.write function allows you to send a byte, or array of bytes.

Each byte is 8 bits, which would be one row or one column of the 8x8 array.

The function only knows how to read bytes. It's up to you to interpret the byte. You are currently interpreting each byte as a char. When you are no longer sending the data as chars, you can change the type of variable that you store the data in, to byte.

If you need to deal with each bit, and are not comfortable with bit twiddling, you can use bitRead to extract the bits from each byte.

Ok that's great, but the part I'm more having difficultly with is forming the bytes on my computer to send to the arduino I can't find how to convert and send my string of ascii from my c++ program to the arduino.

Current I have a Stringstream of the chars (1s and 0s) I want to send then then when I get 64 chars of them sending them to the arduino.

On the linux side, you’ll need to use the bit shift operator (<<) and bit masking to form the bytes to send.

You can use the char variable type, which is one byte long. Treat it as though it was an int (but only one byte long).

Set the value to 0. Add the first bit (0 or 1, not ‘0’ or ‘1’). Then, shift it one bit left, and add the next bit.

Repeat shifting and adding until the 8th bit has been set. Then, send that byte, and repeat for the next row (or column).

That’s very helpful, I’ll give it a go. Thanks