diff --git a/adafruit_seesaw/seesaw.py b/adafruit_seesaw/seesaw.py index 0e5d022..c4e0caf 100644 --- a/adafruit_seesaw/seesaw.py +++ b/adafruit_seesaw/seesaw.py @@ -61,6 +61,7 @@ def const(x): _EEPROM_BASE = const(0x0D) _NEOPIXEL_BASE = const(0x0E) _TOUCH_BASE = const(0x0F) +_ENCODER_BASE = const(0x11) _GPIO_DIRSET_BULK = const(0x02) _GPIO_DIRCLR_BULK = const(0x03) @@ -109,6 +110,12 @@ def const(x): _HW_ID_CODE = const(0x55) _EEPROM_I2C_ADDR = const(0x3F) +_ENCODER_STATUS = const(0x00) +_ENCODER_INTENSET = const(0x10) +_ENCODER_INTENCLR = const(0x20) +_ENCODER_POSITION = const(0x30) +_ENCODER_DELTA = const(0x40) + # TODO: update when we get real PID _CRICKIT_PID = const(9999) _ROBOHATMM1_PID = const(9998) @@ -362,6 +369,31 @@ def set_pwm_freq(self, pin, freq): else: raise ValueError("Invalid PWM pin") + def get_encoder_pos(self, encoder=0): + """Read the current position of the encoder""" + buf = bytearray(4) + self.read(_ENCODER_BASE, _ENCODER_POSITION + encoder, buf) + return struct.unpack(">i", buf)[0] + + def set_encoder_pos(self, pos, encoder=0): + """Set the current position of the encoder""" + cmd = struct.pack(">i", pos) + self.write(_ENCODER_BASE, _ENCODER_POSITION + encoder, cmd) + + def get_encoder_delta(self, encoder=0): + """Read the change in encoder position since it was last read""" + buf = bytearray(4) + self.read(_ENCODER_BASE, _ENCODER_DELTA + encoder, buf) + return struct.unpack(">i", buf)[0] + + def enable_encoder_interrupt(self, encoder=0): + """Enable the interrupt to fire when the encoder changes position""" + self.write8(_ENCODER_BASE, _ENCODER_INTENSET + encoder, 0x01) + + def disable_encoder_interrupt(self, encoder=0): + """Disable the interrupt from firing when the encoder changes""" + self.write8(_ENCODER_BASE, _ENCODER_INTENCLR + encoder, 0x01) + # def enable_sercom_data_rdy_interrupt(self, sercom): # # _sercom_inten.DATA_RDY = 1 diff --git a/examples/seesaw_rotary_simpletest.py b/examples/seesaw_rotary_simpletest.py new file mode 100644 index 0000000..5eaac54 --- /dev/null +++ b/examples/seesaw_rotary_simpletest.py @@ -0,0 +1,32 @@ +# SPDX-FileCopyrightText: 2021 John Furcean +# SPDX-License-Identifier: MIT + +import board +import busio +from adafruit_seesaw.seesaw import Seesaw +from adafruit_seesaw.digitalio import DigitalIO + +i2c_bus = busio.I2C(board.SCL, board.SDA) + +seesaw = Seesaw(i2c_bus, addr=0x36) + +button = DigitalIO(seesaw, 24) +button_held = False + +last_pos = seesaw.get_encoder_pos() + +while True: + + # read position of the rotary encoder + pos = seesaw.get_encoder_pos() + if pos != last_pos: + last_pos = pos + print(f"Position: {pos}") + + if not button.value and not button_held: + button_held = True + print("Button pressed") + + if button.value and button_held: + button_held = False + print("Button released")