Skip to content

Instantly share code, notes, and snippets.

@k4kfh
Created November 20, 2017 17:29
Show Gist options
  • Save k4kfh/94905bf882c982f958f1d179b6120b06 to your computer and use it in GitHub Desktop.
Save k4kfh/94905bf882c982f958f1d179b6120b06 to your computer and use it in GitHub Desktop.
Pi Binary Counter
# Binary counter
import RPi.GPIO as GPIO
import time
redPin = 27
greenPin = 17
bluePin = 22
yellowPin = 19
GPIO.setmode(GPIO.BCM)
GPIO.setup(redPin, GPIO.OUT)
GPIO.setup(yellowPin, GPIO.OUT)
GPIO.setup(greenPin, GPIO.OUT)
GPIO.setup(bluePin, GPIO.OUT)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
try:
GPIO.output(redPin, GPIO.LOW)
GPIO.output(yellowPin, GPIO.LOW)
GPIO.output(greenPin, GPIO.LOW)
GPIO.output(bluePin, GPIO.LOW)
counter = 0
print("Push the button!")
while True:
input_state = GPIO.input(18)
if True:
counter = counter + 1
print("--------")
print("Counter = " + str(counter))
counterBinary = bin(counter)[2:][::-1]
print("Counter Binary = " + str(counterBinary))
for index, bit in enumerate(counterBinary):
print("Index = " + str(index) + " and bit = " + bit)
if (index == 0):
if (int(bit) == 1):
GPIO.output(greenPin, GPIO.HIGH)
elif (int(bit) == 0):
GPIO.output(greenPin, GPIO.LOW)
elif (index == 1):
if (int(bit) == 1):
GPIO.output(yellowPin, GPIO.HIGH)
elif (int(bit) == 0):
GPIO.output(yellowPin, GPIO.LOW)
elif (index == 2):
if (int(bit) == 1):
GPIO.output(bluePin, GPIO.HIGH)
elif (int(bit) == 0):
GPIO.output(bluePin, GPIO.LOW)
elif (index == 3):
if (int(bit) == 1):
GPIO.output(redPin, GPIO.HIGH)
elif (int(bit) == 0):
GPIO.output(redPin, GPIO.LOW)
time.sleep(0.05)
if (counter == 16):
counter = 0
except KeyboardInterrupt:
GPIO.cleanup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment