

Create an object, “led” which is used to create a link between the physical GPIO pin and our code. The first is the Pin class from the Machine library, the second is utime, used to control the pace of our code. Our code is written in the large blank space above the REPL and we start by importing two MicroPython libraries. Interrupt Requests are also useful for time critical changes you want to detect.4. It also makes your main project code easier to follow. You can seperate out all the code and logic into a really useful class.

handlers: handler( type ) Links To Download Code #Ĭlasses are very useful if you find yourself using the same code in multiple projects. handlers.append(handler) def call_handlers (self, type): for handler in self. SW_PRESS ) def add_handler (self, handler): self. SW_RELEASE ) else : micropython.schedule( self. sw_pin.value(): micropython.schedule( self. last_status = new_status def switch_detect (self,pin): if self. ROT_CW ) elif transition = 0b 1101 : micropython.schedule( self.

last_status << 2 ) | new_status if transition = 0b 1110 : micropython.schedule( self. sw_pin.value() def rotary_change (self, pin): new_status = ( self. Here is the code for the class rotary.py import machine import utime as time from machine import Pin import micropython class Rotary : ROT_CW = 1 ROT_CCW = 2 SW_PRESS = 4 SW_RELEASE = 8 def _init_ (self,dt,clk,sw): self. SW_RELEASE : print ( 'RELEASE' ) rotary.add_handler(rotary_changed) while True : time.sleep( 0.1 ) SW_PRESS : print ( 'PRESS' ) elif change = Rotary. ROT_CCW : val = val - 1 print (val) elif change = Rotary. ROT_CW : val = val + 1 print (val) elif change = Rotary. from rotary import Rotary import utime as time rotary = Rotary( 0, 1, 2 ) val = 0 def rotary_changed (change): global val if change = Rotary. MicroPython Code #īelow is a simple example of how to use the rotary class. Thanks to everyone who took the time to point that out to us. Ours had pull down resistors on the component, but it seems not all components listed as KY-040 have those but you can do that with code. You should be able to apply what you have learned here to other rotary encoders.
