Introduction
This article offers a simple implementation of the binary counter powered by Raspberry PI3 and 8 LEDs. It is very similar to what was done before for Arduino board in the previous article Connecting an Arduino to a Breadboard to Light Up LEDs. In this project, we will be using Python to program the board.
For this project, we will need a Raspberry PI kit (I'm using one of these CanaKits), a breadboard, 8 LEDs, 8 220 Ohm resistors (can be different, e.g., 330, etc.) and 9 male-to-female jumper wires. If you decide not to remote to Raspberry, then you will also need a monitor with HDMI cable, mouse and keyboard.
Setting Up Work Environment
I'm using a default installation of Raspberry PI 3 which comes with Raspbian OS and Python pre-installed. Make sure you have the latest GPIO module installed as the code uses it to write to GPIO pins.
$ sudo apt-get update
$ sudo apt-get install python-rpi.gpio python3-rpi.gpio
I enabled Wi-Fi on my Raspberry and also configured Secure Shell (SSH), so I can remote to it from my Windows machine using Putty. This way, we won't need a monitor, mouse, keyboard and Ethernet cable to communicate with the device. The only cable that we need is a power cord.
After installing Samba on Raspberry, we can access working files from Windows machine and edit them in our favorite text editors. Alternatively, we still can use nano editor in terminal window which comes with the distribution.
Connecting Wires
We will need 8 wires to connect GPIO pins to corresponding LEDs via their individual resistors (plus 1 wire for the ground). Here, I decided to use pin 33 for bit 0, pin 37 for bit 1, etc (see the code). The layout below shows which pins are available.
Using the Code
In the code, we first set 8 selected pins into output mode. Then in a loop, we extract current value of each bit of the counter by applying corresponding bit mask and set individual GPIO pin mapped to that bit.
import RPi.GPIO as GPIO
import time
print "=== Binary counter ==="
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(33, GPIO.OUT)
GPIO.setup(37, GPIO.OUT)
GPIO.setup(7, GPIO.OUT)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
GPIO.setup(19, GPIO.OUT)
GPIO.setup(21, GPIO.OUT)
cnt = 0
print "Press Ctrl-C to exit"
try:
while True:
GPIO.output(33, cnt & 0x01)
GPIO.output(37, cnt & 0x02)
GPIO.output(7, cnt & 0x04)
GPIO.output(11, cnt & 0x08)
GPIO.output(13, cnt & 0x10)
GPIO.output(15, cnt & 0x20)
GPIO.output(19, cnt & 0x40)
GPIO.output(21, cnt & 0x80)
time.sleep(0.1)
cnt += 1 % 256
except KeyboardInterrupt:
GPIO.cleanup()
If you saved the code in counter.py file, just run this command to start the counter:
python counter.py
And that's it. Happy coding!