from machine import Pin, SoftI2C
import oled, time
from time import sleep
from Rotary import Rotary
# Rotary encoder input pins
CLK_PIN = 25 # GPIO pin number for the CLK (A) signal
DT_PIN = 26 # GPIO pin number for the DT (B) signal
SW_PIN = 27
last_state_clk = -1 # Tracks the last state of the CLK signal
button_pressed = False
last_button_time_stamp = 0
start_time = time.time()
show_item_screen_state = False
# Initialize the Rotary encoder object
rotary = Rotary(CLK_PIN, DT_PIN, SW_PIN)
print("HMI using Rotary encoder")
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
oled = oled.I2C(128, 64, i2c)
selected_item = 1
def show_menu(item):
oled.clear()
oled.text('Menu', 0, 0)
oled.text(' 1. Item 1', 0, 1)
oled.text(' 2. Item 2', 0, 2)
oled.text(' 3. Item 3', 0, 3)
oled.text(' 4. Item 4', 0, 4)
oled.text(' 5. Item 5', 0, 5)
oled.text('>', 0, item)
oled.show()
def show_item_screen(item):
oled.clear()
oled.text('Item ' + str(item), 0, 0)
oled.text('This is menu ' + str(item), 0, 2)
oled.text('> Back', 0, 5)
oled.show()
show_menu(selected_item)
def rotary_change(pin):
"""
Interrupt handler for the rotary encoder.
Detects a falling edge on the CLK signal and determines the rotation direction.
"""
global selected_item
# Read the current state of the CLK pin
current_state_clk = rotary.clk.value()
# Check for a falling edge (HIGH to LOW transition)
if current_state_clk == 0:
# Determine rotation direction and display the count
direction = rotary.read_direction()
rotation = rotary.get_rotation_count()
if show_item_screen_state != True:
if direction == "CW":
if rotation > 5:
rotation = 5
rotary.set_rotation_count(5)
selected_item = rotation
elif direction == "CCW":
if rotation < 1:
rotation = 1
rotary.set_rotation_count(1)
selected_item = rotation
show_menu(selected_item)
# Handler for button press
def button_pressed(pin):
global last_button_time_stamp
global start_time, button_pressed
cur_button_ts = time.ticks_ms()
button_press_delta = cur_button_ts - last_button_time_stamp
if button_press_delta > 200:
start_time = time.time()
last_button_time_stamp = cur_button_ts
button_pressed = True
# Set up interrupts
rotary.set_interrupt(rotary_change)
rotary.set_button_interrupt(button_pressed)
def main():
"""
Main loop to keep the program running.
Adds a small delay to avoid high CPU usage.
"""
global selected_item, button_pressed
rotary.set_rotation_count(selected_item)
while True:
if button_pressed:
button_pressed = False
if show_item_screen_state:
show_item_screen_state = False
show_menu(selected_item)
else:
show_item_screen_state = True
show_item_screen(selected_item)
sleep(0.01)
if __name__ == "__main__":
main()