/ Rotary_Trinkey_Brightness_Crank / code.py
code.py
1 # SPDX-FileCopyrightText: 2021 foamyguy for Adafruit Industries 2 # 3 # SPDX-License-Identifier: MIT 4 5 """ 6 Rotary Trinkey gadget that forces you to crank the handle in order 7 to keep the brightness up on your phone or tablet. 8 """ 9 10 import time 11 import math 12 import board 13 import digitalio 14 import rotaryio 15 import usb_hid 16 from adafruit_hid.consumer_control import ConsumerControl 17 from adafruit_hid.consumer_control_code import ConsumerControlCode 18 19 # how frequently we check the encoder value and apply brightness changes 20 ACTION_INTERVAL = 3 # seconds 21 22 # if encoder value increases at least this much 23 # then brightness stays the same 24 # if encoder value increases less than this 25 # then brightness goes down 26 STAY_EVEN_CHANGE_THRESHOLD = 60 27 28 # if encoder value increases at least this much 29 # then brightness goes up 30 INCREASE_CHANGE_THRESHOLD = 95 31 32 # timestamp of last time an action occurred 33 LAST_ACTION_TIME = 0 34 35 # encoder value variable 36 CUR_VALUE = 0 37 38 # pause state 39 PAUSED = False 40 41 cc = ConsumerControl(usb_hid.devices) 42 43 encoder = rotaryio.IncrementalEncoder(board.ROTA, board.ROTB) 44 switch = digitalio.DigitalInOut(board.SWITCH) 45 switch.switch_to_input(pull=digitalio.Pull.DOWN) 46 47 switch_state = None 48 49 # previous encoder position variable 50 last_position = encoder.position 51 52 # previous switch variable 53 prev_switch_value = False 54 55 while True: 56 now = time.monotonic() 57 58 if switch.value and not prev_switch_value: 59 print("toggling pause") 60 PAUSED = not PAUSED 61 62 if not PAUSED: 63 LAST_ACTION_TIME = now 64 65 prev_switch_value = switch.value 66 67 # read current encoder value 68 current_position = encoder.position 69 position_change = int(current_position - last_position) 70 71 # positive change 72 if position_change > 0: 73 for _ in range(position_change): 74 CUR_VALUE += position_change 75 76 # negative change 77 elif position_change < 0: 78 for _ in range(-position_change): 79 # use absolute value to convert to positive 80 CUR_VALUE += int(math.fabs(position_change)) 81 82 last_position = current_position 83 84 if not PAUSED: 85 # is it time for an action? 86 if now > LAST_ACTION_TIME + ACTION_INTERVAL: 87 print(CUR_VALUE) 88 89 # update previous time variable 90 LAST_ACTION_TIME = now 91 92 # less than stay even threshold 93 if CUR_VALUE < STAY_EVEN_CHANGE_THRESHOLD: 94 cc.send(ConsumerControlCode.BRIGHTNESS_DECREMENT) 95 print("brightness down") 96 97 # more than stay even threshold 98 elif CUR_VALUE < INCREASE_CHANGE_THRESHOLD: 99 print("stay even") 100 101 # more than increase threshold 102 else: 103 cc.send(ConsumerControlCode.BRIGHTNESS_INCREMENT) 104 print("brightness up") 105 106 # reset encoder value 107 CUR_VALUE = 0 108 109