Advertisement
belrey10

6 – Binary LED Counter

Nov 7th, 2024
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.40 KB | None | 0 0
  1. import machine
  2. import time
  3.  
  4. # Define GPIO pins for the 4 LEDs
  5. led_pins = [
  6.     machine.Pin(0, machine.Pin.OUT),
  7.     machine.Pin(1, machine.Pin.OUT),
  8.     machine.Pin(2, machine.Pin.OUT),
  9.     machine.Pin(3, machine.Pin.OUT)
  10. ]
  11. button_pin = machine.Pin(8, machine.Pin.IN, machine.Pin.PULL_DOWN)
  12.  
  13. # Initialize LED states for 4 LEDs
  14. led_states = [0] * len(led_pins)
  15.  
  16. # Function to update LED states
  17. def update_led_states():
  18.     for i, led in enumerate(led_pins):
  19.         if led_states[i] == 1:
  20.             led.on()
  21.         else:
  22.             led.off()
  23.  
  24. # Function to create a padded binary string
  25. def padded_binary_string(value, length):
  26.     binary_str = bin(value).replace("0b", "")
  27.     while len(binary_str) < length:
  28.         binary_str = '0' + binary_str
  29.     return binary_str
  30.  
  31. # Function to increment binary counter
  32. def increment_counter():
  33.     # Convert LED states to integer
  34.     binary_value = int(''.join(map(str, led_states)), 2)
  35.     binary_value += 1
  36.     # If value is 16 (10000 in binary), reset to 0
  37.     if binary_value >= 16:
  38.         binary_value = 0
  39.     binary_string = padded_binary_string(binary_value, len(led_pins))
  40.  
  41.     # Update LED states
  42.     for i, bit in enumerate(binary_string):
  43.         led_states[i] = int(bit)
  44.  
  45. # Main loop
  46. while True:
  47.     if button_pin.value() == 1:
  48.         increment_counter()
  49.         update_led_states()
  50.         time.sleep(0.2)  # Button debounce delay
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement