Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help a noob
#1
Hello

Got me a Trinket M0 with CircuitPython

Successfully loaded and ran Trinket M0 Media Dial code and functionality with rotary encoder (arrow up-arrow down)

Actually, I want to change windows function from arrow up-down to volume increment-decrement

added the import for the correct library as shown in:

https://circuitpython.readthedocs.io/pro...mercontrol
import time
from digitalio import *
from board import *
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keycode import Keycode
from adafruit_hid.consumer_control_code import ConsumerControlCode
import neopixel

Modified original code:
    
# Check if rotary encoder went up
    if encoder_direction == 1:
        kbd.press(Keycode.CONTROL, Keycode.UP_ARROW)
        kbd.release_all() 

    # Check if rotary encoder went down
    if encoder_direction == -1:
        kbd.press(Keycode.CONTROL, Keycode.DOWN_ARROW)
        kbd.release_all()
to
    # Check if rotary encoder went up
    if encoder_direction == 1:
        consumer_control.send(ConsumerControlCode.VOLUME_INCREMENT) 

    # Check if rotary encoder went down
    if encoder_direction == -1:
        consumer_control.send(ConsumerControlCode.VOLUME_DECREMENT)
Does not work, Trinket shows its a NameError (it has an RGB status LED on the board)

More than likely, I will never touch Python or related stuff. Looks like a simple thing to fix, any help would be awesome
Reply
#2
Is there more specific information about error? In case of NameError Python usually reports what name is not defined.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
Trinket has RGB LED, that flashes the information. Im using Mu editor, not sure at this point if it has a debug built in.

But it flashes location information too fast to count. Flashes white for NameError and then fast series specifing the location of error.
It flashes NameError on the import section and encoder signal section. (alternating between 10's (blue) line where the import is declared and 100's (yellow) line where the encoder signal is defined). So I think there is a mismatch in both cases...somehow.

I will copy the entire Media dial code:

    """
A CircuitPython 'multimedia' dial demo
Uses a Trinket M0 + Rotary Encoder -> HID keyboard out with neopixel ring
"""
 
import time
from digitalio import *
from board import *
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keycode import Keycode
import neopixel
 
DOT_COLOR = 0xFF0000              # set to your favorite webhex color
PRESSED_DOT_COLOR = 0x008080      # set to your second-favorite color
LIT_TIMEOUT = 15                  # after n seconds, turn off ring

# NeoPixel LED ring on pin D1
# Ring code will auto-adjust if not 16 so change to any value!
ring = neopixel.NeoPixel(D1, 16, brightness=0.2)
dot_location = 0  # what dot is currently lit

# Encoder button is a digital input with pullup on D2
button = DigitalInOut(D2)
button.direction = Direction.INPUT
button.pull = Pull.UP

# Rotary encoder inputs with pullup on D3 & D4
rot_a = DigitalInOut(D3)
rot_a.direction = Direction.INPUT
rot_a.pull = Pull.UP
rot_b = DigitalInOut(D4)
rot_b.direction = Direction.INPUT
rot_b.pull = Pull.UP

# Used to do HID output, see below
kbd = Keyboard()

# time keeper, so we know when to turn off the LED
timestamp = time.monotonic()

######################### MAIN LOOP ##############################

# the counter counts up and down, it can roll over! 16-bit value
encoder_counter = 0
# direction tells you the last tick which way it went
encoder_direction = 0

# constants to help us track what edge is what
A_POSITION = 0
B_POSITION = 1
UNKNOWN_POSITION = -1  # initial state so we know if something went wrong

rising_edge = falling_edge = UNKNOWN_POSITION

# get initial/prev state and store at beginning
last_button = button.value
rotary_prev_state = [rot_a.value, rot_b.value]

while True:
    # reset encoder and wait for the next turn
    encoder_direction = 0

    # take a 'snapshot' of the rotary encoder state at this time
    rotary_curr_state = [rot_a.value, rot_b.value]

    if rotary_curr_state != rotary_prev_state:
        #print("Changed")
        if rotary_prev_state == [True, True]:
            # we caught the first falling edge!
            if not rotary_curr_state[A_POSITION]:
                #print("Falling A")
                falling_edge = A_POSITION
            elif not rotary_curr_state[B_POSITION]:
                #print("Falling B")
                falling_edge = B_POSITION
            else:
                # uhh something went deeply wrong, lets start over
                continue

        if rotary_curr_state == [True, True]:
            # Ok we hit the final rising edge
            if not rotary_prev_state[B_POSITION]:
                rising_edge = B_POSITION
                # print("Rising B")
            elif not rotary_prev_state[A_POSITION]:
                rising_edge = A_POSITION
                # print("Rising A")
            else:
                # uhh something went deeply wrong, lets start over
                continue

            # check first and last edge
            if (rising_edge == A_POSITION) and (falling_edge == B_POSITION):
                encoder_counter -= 1
                encoder_direction = -1
                print("%d dec" % encoder_counter)
            elif (rising_edge == B_POSITION) and (falling_edge == A_POSITION):
                encoder_counter += 1
                encoder_direction = 1
                print("%d inc" % encoder_counter)
            else:
                # (shrug) something didn't work out, oh well!
                encoder_direction = 0

            # reset our edge tracking
            rising_edge = falling_edge = UNKNOWN_POSITION

    rotary_prev_state = rotary_curr_state

    # Check if rotary encoder went up
    if encoder_direction == 1:
        kbd.press(Keycode.CONTROL, Keycode.UP_ARROW)
        kbd.release_all()

    # Check if rotary encoder went down
    if encoder_direction == -1:
        kbd.press(Keycode.CONTROL, Keycode.DOWN_ARROW)
        kbd.release_all()

    # Button was 'just pressed'
    if (not button.value) and last_button:
        print("Button pressed!")
        kbd.press(44) #Keycode.SPACE
        kbd.release_all()
        ring[dot_location] = PRESSED_DOT_COLOR # show it was pressed on ring
        timestamp = time.monotonic()        # something happened!
    elif button.value and (not last_button):
        print("Button Released!")
        # kbd.press(Keycode.SHIFT, Keycode.SIX)
        # kbd.release_all()
        ring[dot_location] = DOT_COLOR      # show it was released on ring
        timestamp = time.monotonic()        # something happened!
    last_button = button.value

    if encoder_direction != 0:
        timestamp = time.monotonic()        # something happened!
        # spin neopixel LED around!
        previous_location = dot_location
        dot_location += encoder_direction   # move dot in the direction
        dot_location += len(ring)           # in case we moved negative, wrap around
        dot_location %= len(ring)
        if button.value:
            ring[dot_location] = DOT_COLOR  # turn on new dot
        else:
            ring[dot_location] = PRESSED_DOT_COLOR # turn on new dot
        ring[previous_location] = 0         # turn off previous dot

    if time.monotonic() > timestamp + LIT_TIMEOUT:
        ring[dot_location] = 0   # turn off ring light temporarily
Reply
#4
Hello

Got me thinking: best to get a proper editor with debugger.
Reply
#5
(May-28-2019, 11:59 AM)Tartupets Wrote: Got me thinking: best to get a proper editor with debugger.


look at VSCode
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
(May-28-2019, 12:48 PM)buran Wrote: look at VSCode

Got VSCode and got Python environment installed. Code loaded

Cant get debugger to work, asks to open a folder.

Mu Editor has a rudimentary debugger:

added import commands on both ConsumerControl and ConsumerControlCode libraries. Mu editor said: Import successful, but unused

Modified the rotary encoder command and mu editor said: consumer_control.send may be undefined or defined from star imports: board digitalio

Then I rotated the encoder to check if it works and then Trinket starts showing NameError (white light) and ValueError (Purple). Managed to read a little bit of the position counter and all faults point to consumer_control.send (placement showed on line 100+)
Reply
#7
Hello

The solution manifested itself: had to restart the PC. Work flawlessly as an external volume control...
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020