Thursday 30 August 2012

Simple Stick User Guide - Building a 3-Bit Binary Counter

Simple Stick User Guide - Building a 3-Bit Binary Counter

Ensure you have gone through our Simple Stick Overview Page before you go ahead with the Programming Tutorials.

A Binary Counter is an interesting project for the beginner to get started right after blinking an LED. A Binary counter is a simple counter that displays the current counter value in binary format. we have 3 On-board LEDs connected to Pins 5,10 &13 on the Simple Stick, we can use these to build a 3-bit binary counter that will automati cally increment every second and reset once it reaches 7.

We can assume the LED connected to PIN 13 to be the LSB [Least Significant Bit] and the LED connected to PIN 5 as the MSB [Most Significant Bit] . We can have a counter variable that we can increment till 7 and reset to 0 on reaching 7.

Now Lets take a look at the logic

Heres how a Binary counter will work
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
0 0 0
...... and on

If you notice, the LSB is toggling every cycle, the Middle Bit is toggling every 2 cycles and the MSB is toggling every cycle, To achieve this effect, we can use the MOD operator (%)

Counter % 2 will produce an alternating output of '1' & '0' that changes every cycle

(Counter/2) % 2 will produce an alternating output of '1' & '0' that changes every 2 cycles(whatever you divide by!)

(Counter/4) % 2 will produce an alternating output of '1' & '0' that changes every 4 cycles

Heres a Demo Video of the same

Heres the code for this... 
Binary_Counter.ino
 /*   
 This sketch automatically increases a 3 bit number every second  
 and shows the output on 3 LEDs   
 */  
 void setup()  
 {  
  pinMode(5,OUTPUT);   // declare LED pins as output pins  
  pinMode(10,OUTPUT);  
  pinMode(13,OUTPUT);  
 }  
 void loop()  
 {  
  for(int i=0;i<8;i++)  // increment automatically from 0 to 7  
  {  
   int a=i%2;      // calculate LSB   
   int b=i/2 %2;     // calculate middle bit  
   int c=i/4 %2;     // calculate MSB   
   digitalWrite(5,c);  // write MSB  
   digitalWrite(10,b);  // write middle bit  
   digitalWrite(13,a);  // write LSB  
   delay(1000);     // wait for a second  
  }  
 }  


Enjoy... and feel free to drop us an email with questions you might have -> info@simplelabs.co.in

2 comments:

  1. Don't you have to either use HIGH or LOW for digitalWrite? How can the program interpret whats high and whats low in digitalWirte?

    ReplyDelete
  2. Don't you have to either use HIGH or LOW for digitalWrite? How can the program interpret whats high and whats low in digitalWirte?

    ReplyDelete