Converting A Binary Number Into A Decimal (Base-10) Form: Arduino 8 Bit Binary LED Counter
Converting A Binary Number Into A Decimal (Base-10) Form: Arduino 8 Bit Binary LED Counter
In today’s activity we will study how computers “count”, and we will dsicuss the idea of binary numbers
and binary counting.
We will then connect the Arduino board to 8 LEDs, and see how the computer can count.
BINARY COUNTING
Computers count in BINARY, i.e. using ones and zeros.
For example, the number 5 is binary 101. How does this work?
Here is a chart to explain how the computer uses 8 bits to represent thenubers from .. to ..
Decimal Binary
0 0
1 1
2 10
3 11
4 100
5 101
6 110
7 111
8 1000
9 1001
10 1010
11 1011
12 1100
13 1101
14 1110
15 1111
[1 × 32] + [0 × 16] + [0 × 8] + [1 × 4] + [0 × 2] + [1 × 1] = 37
NOW WE ARE READY TO GO!
Connect 8 LEDs in pins 5-12 of the Arduino as before, using 330 Ohm resistors for each LED.
void setup()
{
int pins[]={5,6,7,8,9,10,11,12};
int state;
String binNumber;
for(int x=5;x<=12;x++)
{pinMode(pins[x], OUTPUT);} /*this for-loop makes all 8 pins Output
int number=5;
binNumber = String(number, BIN); /* changes the number into BINARY form*/
int binLength = binNumber.length(); /* finds the length of the BINARY string */
for(int i = 0, x = 1; i < binLength; i++, x+=2) /* this for-loop turns ON the correct pins
{
if(binNumber[i] == '0') state = LOW;
if(binNumber[i] == '1') state = HIGH;
digitalWrite(pins[i] + binLength - x, state);
delay(200);
}
}
void loop()
{ }
We use an ARRAY called pins, so that we can turn all 8 pins ON/OFF easily.
When we want to turn ON the third pin in the list for example, we write
digitalWrite(pins[3],HIGH)
Since the array is pins[]={5,6,7,8,9,10,11,12}, the third pin for example will be pin[3] and it will be
connected to pin#7 on the RedBoard.
The command String(number,BIN) changes the number 5 into binary form, so that the number 5 will be
changed into the binary string 101.
The for-loop checks each digit on the binary number and lights up the appropriate LEDs .
For example, since the number 5 is binary 101, the program will light up the last pin and the third pin
from the end, as in te picture below.
Similary, the number 88 is binary 1011000 and the appropriate LEDs are shown in the figure.
YOUR TURN NOW!
1. Enter the code and run it, does it light up the correct LEDs?
Test the code with small number (10,16) and with large numbers (88, 128).
2. Modify the code so that the 8 LEDs are counting in binary from 1 to the maximum possible number.