March 6, 2011

Random Arduino Bits 'n Bytes (part 2)

(This is a follow-up article. Read the first part here.)

Now the bit-level manipulation part of the code:

/*
 * randoms_seed.pde
 * -----------------
 * Generates a random number, then prints it
 * through the serial port in decimal and
 * binary format. Does not use an initial seed
 * so it prints the same set of random numbers
 * everytime it is reset.
 *
 *
 * http://spacetinkerer.blogspot.com
 */

long randNumber;



void setup(){
  Serial.begin(9600);
  Serial.println("RESET!");
  Serial.println();
 
}

void loop() {
 
  delay(1000);
 
  // generate and print a random number from 0 to 9
  randNumber = random(0,10);
  Serial.print("Integer: ");
  Serial.println(randNumber); 
  Serial.print("Binary: ");
  Serial.print(bitRead(randNumber,3));
  Serial.print(bitRead(randNumber,2));
  Serial.print(bitRead(randNumber,1));
  Serial.println(bitRead(randNumber,0));
  Serial.println();

}

We take a random number as explained in the previous post.  What we want to do with that is take the binary value of the number. There are two ways to do that (actually there are more, but two basic). 

The first is as shown at the code. We use the bitRead() function.
This function takes two numbers as input. The first is the number from which we will extract the bit, and the second number tells it which bit to extract. Bit #0 is the rightmost bit, #1 is the next on the right etc.
Then we parse this value in the print function and voila! You have the number in binary format on the Serial Monitor.

The second way is to use the byte() function. That function does the same thing but uses only as many digit as needed to show. For example a call like this 

byte(3);

will return 11, but not 0011. 
For input the number 8 

byte(8);

will return 1000. 

This method is easier and faster if you don't care about the format. But if you want control over all of the bits of the number you should use the bitRead() function.

If you have any question leave a comment below!
As I said I am preparing a fascinating project so stay tuned (via rss, or via e-mail).

Happy Tinkering!

If you liked this article then take a second to bookmark it with...


No comments:

Post a Comment