Pages: [1]   Go Down
Author Topic: bit to byte conversion 101  (Read 1094 times)
0 Members and 1 Guest are viewing this topic.
melbourne, AU
Offline Offline
Newbie
*
Karma: 1
Posts: 44
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

well, i'm pretty new to programming, so sorry if this seems really basic to some of you...

i want to receive 2 bytes of data from an external chip (Qprox QT300) in single bit pulses, then assemble the received bits into bytes, then send these 2 bytes on to the PC via the usb cable.

the method of getting the individual bits is quite straightforward:
1. set a clock pin output HIGH, the wait a few microseconds.
2. receive a HIGH or LOW bit on a digital pin, and store the value in a variable.
3. set the clock pin output LOW and wait a few microseconds.
4. repeat 16 times (with a short pause in between bytes).

so: now you have 16 zeros or ones, which you might store in an array, or as 16 individual integers, etc.
but how do you assemble them into 2 seperate bytes?
it seems really clumsy to write a function which steps through each bit in turn an adds them up according to the bit order value (ie 1,1,1,1,1,1,1,1 = 1+2+4+8+16+32+64+128 = 255).

is there an easier or at least more elegant way??  like, if they were stored in an array, is there some function that i'm unaware of that automatically sums the array as a byte value?

thanks,

jon.
Logged

Forum Administrator
Cambridge, MA
Offline Offline
Faraday Member
*****
Karma: 11
Posts: 3538
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Check out the bit math tutorial on the playground: http://www.arduino.cc/playground/Code/BitMath

You should be able to store all the bits directly into an unsigned int, which is exactly 16 bits (a regular int is only 15 bits, since the last bit is used to indicate whether it's positive or negative).  

You could try something like this:

Code:
unsigned int value = 0;
for (i = 0; i < 16; i++) {
  // trigger the clock pin and wait.
  if (digitalRead(pin))
    value |= (1 << i);
}

Though it depends which order the bits come (i.e. is the least significant one - the 1's bit - first or last?).
Logged

Pages: [1]   Go Up
Jump to: