From b62dd11dd60cf1ffe0ce83c504d986314b16c19e Mon Sep 17 00:00:00 2001 From: Duckida <61168649+duckida@users.noreply.github.com> Date: Wed, 29 Oct 2025 16:40:14 +0000 Subject: [PATCH 1/2] Adds motor encoder demo code --- sampleCode/encoder_demo.py | 58 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 sampleCode/encoder_demo.py diff --git a/sampleCode/encoder_demo.py b/sampleCode/encoder_demo.py new file mode 100644 index 0000000..1a8cf9b --- /dev/null +++ b/sampleCode/encoder_demo.py @@ -0,0 +1,58 @@ +# UKMARS Gemini Encoder Demo +# Oct 29 2025 +# Prints the left and right motor encoder values + +from machine import Pin +from time import sleep + +# Define pins +# You may need to swap the numbers if one encoder is negative when going forward +left_a = Pin(8, Pin.IN, Pin.PULL_UP) +left_b = Pin(9, Pin.IN, Pin.PULL_UP) + +right_a = Pin(7, Pin.IN, Pin.PULL_UP) +right_b = Pin(6, Pin.IN, Pin.PULL_UP) + + +# Global state +last_left_a = left_a.value() +last_right_a = left_a.value() + +left_counts = 0 +right_counts = 0 + +def left_encoder_callback(pin): + global left_counts, last_left_a + a = left_a.value() + b = left_b.value() + + if a != last_left_a: + # Check direction based on B when A changes + if a == b: + left_counts -= 1 + else: + left_counts += 1 + last_a = a + +def right_encoder_callback(pin): + global right_counts, last_right_a + a = right_a.value() + b = right_b.value() + + if a != last_right_a: + # Check direction based on B when A changes + if a == b: + right_counts -= 1 + else: + right_counts += 1 + last_a = a + + +# Attach interrupts +left_a.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=left_encoder_callback) +right_a.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=right_encoder_callback) + +# Main loop +while True: + print(f"Left: {left_counts} Right: {right_counts}") + sleep(0.1) From a0f3b38daa7ab3eaa61ad9868d8373a860718385 Mon Sep 17 00:00:00 2001 From: Duckida <61168649+duckida@users.noreply.github.com> Date: Thu, 30 Oct 2025 18:13:54 +0000 Subject: [PATCH 2/2] Fix variable name for last encoder value tracking --- sampleCode/encoder_demo.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sampleCode/encoder_demo.py b/sampleCode/encoder_demo.py index 1a8cf9b..3acbcfc 100644 --- a/sampleCode/encoder_demo.py +++ b/sampleCode/encoder_demo.py @@ -32,7 +32,7 @@ def left_encoder_callback(pin): left_counts -= 1 else: left_counts += 1 - last_a = a + last_left_a = a def right_encoder_callback(pin): global right_counts, last_right_a @@ -45,7 +45,7 @@ def right_encoder_callback(pin): right_counts -= 1 else: right_counts += 1 - last_a = a + last_right_a = a # Attach interrupts