Binary Counter on LEDs
Part of the Outputs section of Coddy's Arduino journey. Lesson 19 of 24.
Four LEDs can show any number from 0 to 15 in binary, the way computers store numbers. Each LED is a place worth twice the one before it: 1, 2, 4 and 8. A lit LED adds its value:
- 5 is 4 + 1: the LEDs worth 4 and 1 are lit
- 10 is 8 + 2
- 15 is all four
Each place is called a bit, numbered from 0, the one worth 1. bitRead(number, n) gives bit n of a number, 1 or 0:
bitRead(5, 0); // 1: 5 has the 1
bitRead(5, 1); // 0: 5 has no 2
bitRead(5, 2); // 1: 5 has the 4Since 1 is HIGH and 0 is LOW, bit i can go straight to LED i:
for (int i = 0; i < 4; i++) {
digitalWrite(ledPins[i], bitRead(count, i));
}Here ledPins[0], pin 2, is the LED on the right, worth 1, like the last digit of a number.
Challenge
MediumMake the four LEDs count in binary:
- start
countat 0 - show it on the LEDs with
bitRead(), bitionledPins[i] - wait 250 ms, add 1, and after 15 start again at 0
Press Run, then Check.
Try it yourself
int ledPins[] = {2, 3, 4, 5}; // worth 1, 2, 4, 8
int count = 0;
void setup() {
for (int i = 0; i < 4; i++) {
pinMode(ledPins[i], OUTPUT);
}
}
void loop() {
// show count in binary, wait 250 ms, then count up (back to 0 after 15)
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Outputs
4Loops and Arrays
Repeat With a for LoopAn Array of LED PinsFive-LED ChaserKnob Bar GraphBinary Counter on LEDsPractice on your own: Arduino playground