Class implementing a detection mechanism to detect the rotary encoder directions through the i2c multiplexer + interrupt
| 5 | |
| 6 | |
| 7 | class Encoder: |
| 8 | """Class implementing a detection mechanism to detect the rotary encoder directions |
| 9 | through the i2c multiplexer + interrupt""" |
| 10 | |
| 11 | def __init__(self, enc_a: HardwareButton, enc_b: HardwareButton): |
| 12 | self.enc_a = enc_a |
| 13 | self.enc_b = enc_b |
| 14 | self.pos = 0 |
| 15 | self.state = 0b00000000 |
| 16 | self.direction = 0 |
| 17 | |
| 18 | def update(self): |
| 19 | """Updates the internal attributes wrt. to the encoder position and direction.""" |
| 20 | value_enc_a = self.enc_a.state_interrupt |
| 21 | value_enc_b = self.enc_b.state_interrupt |
| 22 | |
| 23 | self.direction = 0 |
| 24 | state = self.state & 0b00111111 |
| 25 | |
| 26 | if value_enc_a: |
| 27 | state |= 0b01000000 |
| 28 | if value_enc_b: |
| 29 | state |= 0b10000000 |
| 30 | |
| 31 | # clockwise pattern detection |
| 32 | if ( |
| 33 | state == 0b11010010 |
| 34 | or state == 0b11001000 |
| 35 | or state == 0b11011000 |
| 36 | or state == 0b11010001 |
| 37 | or state == 0b11011011 |
| 38 | or state == 0b11100000 |
| 39 | or state == 0b11001011 |
| 40 | ): |
| 41 | self.pos += 1 |
| 42 | self.direction = 1 |
| 43 | self.state = 0b00000000 |
| 44 | return |
| 45 | # counter-clockwise pattern detection |
| 46 | elif ( |
| 47 | state == 0b11000100 |
| 48 | or state == 0b11100100 |
| 49 | or state == 0b11100001 |
| 50 | or state == 0b11000111 |
| 51 | or state == 0b11100111 |
| 52 | ): |
| 53 | self.pos -= 1 |
| 54 | self.direction = -1 |
| 55 | self.state = 0b00000000 |
| 56 | return |
| 57 | |
| 58 | self.state = state >> 2 |