Untitled
unknown
plain_text
a year ago
3.4 kB
18
Indexable
import machine
from machine import Pin, SPI
from utime import sleep
# Pin assignments for 7-segment display
RCLK = 9 # Register clock pin
SCK = 10 # SPI clock pin
MOSI = 11 # SPI MOSI pin
# LED segment definitions (for CCW and CW)
LED_1 = 0xFE # CCW tens
LED_2 = 0xFD # CCW ones
LED_3 = 0xFB # CW tens
LED_4 = 0xF7 # CW ones
# Segment codes for digits 0-9 (7-segment encoding)
SEG8codes = [
0x3F, # 0
0x06, # 1
0x5B, # 2
0x4F, # 3
0x66, # 4
0x6D, # 5
0x7D, # 6
0x07, # 7
0x7F, # 8
0x6F, # 9
]
class LED_8SEG_DISPLAY:
def __init__(self):
self.rclk = Pin(RCLK, Pin.OUT)
self.rclk(1) # Initialize register clock (RCLK)
self.spi = SPI(1, baudrate=1000000, polarity=0, phase=0, sck=Pin(SCK), mosi=Pin(MOSI), miso=None)
def write_cmd(self, Num, Seg):
"""Write command to a specific LED segment."""
self.rclk(1) # Set RCLK high
self.spi.write(bytearray([Num])) # Send digit number (LED address)
self.spi.write(bytearray([Seg])) # Send the segment data (digit code)
self.rclk(0) # Set RCLK low (latch data)
sleep(0.002) # Wait briefly
self.rclk(1) # Set RCLK high again
# Create the display object
DISPLAY = LED_8SEG_DISPLAY()
# Helper functions to extract tens and ones digits
def get_tens(num):
return (num // 10) % 10
def get_ones(num):
return num % 10
# Pin setup for rotary encoder
A_PIN = machine.Pin(0, machine.Pin.IN, machine.Pin.PULL_UP)
B_PIN = machine.Pin(1, machine.Pin.IN, machine.Pin.PULL_UP)
# Initialize rotation counters
total_ccw = 0
total_cw = 0
# Interrupt handler for the rotary encoder
def rotary_encoder_irq(pin):
global total_cw, total_ccw
A_STATE = A_PIN.value()
B_STATE = B_PIN.value()
if A_STATE == 0 and B_STATE == 1:
# Clockwise rotation
total_cw += 1
elif A_STATE == 1 and B_STATE == 0:
# Counter-clockwise rotation
total_ccw += 1
# Set up interrupt handlers for rotary encoder
A_PIN.irq(trigger=machine.Pin.IRQ_RISING, handler=rotary_encoder_irq)
B_PIN.irq(trigger=machine.Pin.IRQ_RISING, handler=rotary_encoder_irq)
# Main loop to display CW and CCW on the LED display and send data to PC
time_elapsed = 0
debounce_interval = 0.05
try:
while True:
# Debounce the rotary encoder
sleep(debounce_interval)
# Every 10 seconds, print the total CW and CCW rotations to the PC
time_elapsed += debounce_interval
if time_elapsed >= 10:
print(f"Total CWs: {total_cw}, Total CCWs: {total_ccw}")
time_elapsed = 0
# Display the CCW count (tens and ones) on LED 1 and LED 2
DISPLAY.write_cmd(LED_1, SEG8codes[get_tens(total_ccw)]) # Tens digit of CCW
sleep(0.001)
DISPLAY.write_cmd(LED_2, SEG8codes[get_ones(total_ccw)]) # Ones digit of CCW
sleep(0.001)
# Display the CW count (tens and ones) on LED 3 and LED 4
DISPLAY.write_cmd(LED_3, SEG8codes[get_tens(total_cw)]) # Tens digit of CW
sleep(0.001)
DISPLAY.write_cmd(LED_4, SEG8codes[get_ones(total_cw)]) # Ones digit of CW
sleep(0.001)
except KeyboardInterrupt:
pass # Gracefully exit on keyboard interrupt
Editor is loading...
Leave a Comment