Skip to content

Instantly share code, notes, and snippets.

@SDSkyKlouD
Last active March 29, 2019 00:55
Show Gist options
  • Save SDSkyKlouD/53fc9e830811db8ad4d9d7f7a40840a8 to your computer and use it in GitHub Desktop.
Save SDSkyKlouD/53fc9e830811db8ad4d9d7f7a40840a8 to your computer and use it in GitHub Desktop.
Raspberry Pi - GPIO - Binary counter with LED and buttons
import RPi.GPIO as GPIO
from math import pow
# Definitions #
BINARY = 0b0
LED_PINS = [ 18, 23, 24, 25, 12, 16, 20, 21, 4, 17, 27, 22 ] # Change this to your LED PIN numbers. Left to right.
LED_PINS_LEN = len(LED_PINS)
INCREASE_PIN = 19 # Change this to your increase button PIN
DECREASE_PIN = 26 # Change this to your decrease button PIN
# --- #
# GPIO PIN mode setting #
GPIO.setmode(GPIO.BCM)
# --- #
# GPIO PIN setting #
for pin in LED_PINS:
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, GPIO.LOW) # Reset all LED signals
GPIO.setup(INCREASE_PIN, GPIO.IN)
GPIO.setup(DECREASE_PIN, GPIO.IN)
# --- #
# Functions #
def processBinary():
return [int(i) for i in str("{0:0" + str(LED_PINS_LEN) + "b}").format(BINARY)]
# --- #
# Program block #
inc_input_value = 0
dec_input_value = 0
try:
while(True):
inc_input_temp = GPIO.input(INCREASE_PIN)
dec_input_temp = GPIO.input(DECREASE_PIN)
if(inc_input_value != inc_input_temp or dec_input_value != dec_input_temp):
binary_changed = False
if(inc_input_value != inc_input_temp):
if(inc_input_temp == 1):
inc_input_value = inc_input_temp
if(BINARY < int(pow(2, LED_PINS_LEN)) - 1):
BINARY += 1
binary_changed = True
print("Increased. BINARY = " + str(bin(BINARY)) + " (dec : " + str(int(BINARY)) + ", hex : " + str(hex(BINARY)) + ")")
elif(inc_input_temp == 0):
inc_input_value = 0
if(dec_input_value != dec_input_temp):
if(dec_input_temp == 1):
dec_input_value = dec_input_temp
if(BINARY > 0):
BINARY -= 1
binary_changed = True
print("Decreased. BINARY = " + str(bin(BINARY)) + " (dec : " + str(int(BINARY)) + ", hex : " + str(hex(BINARY)) + ")")
elif(dec_input_temp == 0):
dec_input_value = 0
if(binary_changed):
binary = processBinary()
count = 0
for pin in LED_PINS:
GPIO.output(pin, binary[count])
count += 1
except KeyboardInterrupt:
print("\nCtrl+C pressed! the program is shutting down...")
finally:
GPIO.cleanup() # GPIO cleanup on exit
# --- #
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment