Hi-
This might be a really obvious question and/or indicate some fundamental flaw in my understanding- so maybe someone can help me clear things up!
I have a plotter type application/project; I send position info from a host program to the arduino and it controls the motors, encoders, etc. It is mostly working but now instead of sending one x/y position at a time, I want to send an entire row of data.
For speed (and to work around the 128 byte serial buffer) instead of sending numeric position data for an entire row, I am thinking that sending binary data would work quite well. I know the step size- so if I sent 11101111 my plotter would step 3x and print after each step, then step, not print, then step four times, printing each time, etc.
If that makes sense- then my question: how do I convert bytes sent over the serial port to a binary representation that I can then test (if nth bit = 1 then print). I need to accommodate about 110 steps per row - so say 128 bits (16 bytes) would be sent for each row.
If you want to check if the nth bit of a byte is set (where n ranges from 0 - 7, and 0 is the LSB), you would bitwise AND (&) the byte with a bitmask for bit n and check to see if the result is zero or not:
if (byte & (1 << n)) // n ranges from 0 - 7
// bit n is set
else
// bit n is cleared
If you want to look at the bits of a number sequentially, you can do something like:
unsigned long lotsofbits = SOME_NUMBER;
int i;
for (i = 0; i < NUM_BITS; i++)
{
if (lotsofbits & 1)
// bit i is set
else
// bit i is cleared
lotsofbits >>= 1; // shift the bits in lotsofbits right by one bit (equivalent to dividing by 2)
}
How do I convert bytes sent over the serial port to a binary representation that I can then test (if nth bit = 1 then print). I need to accommodate about 110 steps per row - so say 128 bits (16 bytes) would be sent for each row.
The thing to remember is that all integer variables are in binary already, there is no need to convert them in order to test the bits. It's only when it comes to outputting that it is converted to something else. Therefore to test if bit 4 is set in a variable N:-
if( (N & 0x10) == 0) { // bit is not set}
else
{ // bit is set}
note there is only one & making it a logic bit wise AND and not && which would be a logic AND