Created
January 2, 2023 10:45
-
-
Save JiapengLi/74ff6bf47859654e3e0086af75f9100c to your computer and use it in GitHub Desktop.
An example for ESP32-S3 circuitpython board, key control and simple led breathing effect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import time | |
| import board | |
| import neopixel_write | |
| import digitalio | |
| class LED: | |
| def __init__(self, pin): | |
| self.pin = digitalio.DigitalInOut(pin) | |
| self.pin.direction = digitalio.Direction.OUTPUT | |
| self.ts = self.ms | |
| self.cnt = 0 | |
| self.sta = 0 | |
| self.step = 1 | |
| self.max = 16 | |
| @property | |
| def ms(self): | |
| return int(time.monotonic() * 1000) | |
| def off(self): | |
| self.cnt = 0 | |
| self.sta = 0 | |
| self.write(0, 0, 0) | |
| def write(self, R, G, B): | |
| neopixel_write.neopixel_write(self.pin, bytearray([G, R, B])) | |
| # print(f"{R} {G} {B}") | |
| def blink(self): | |
| if self.ms - self.ts < 500: | |
| return | |
| self.ts = self.ms | |
| if self.sta == 0: | |
| self.sta = 1 | |
| self.off() | |
| elif self.sta == 1: | |
| self.sta = 0 | |
| self.write(8, 0, 0) | |
| def breath(self): | |
| if self.cnt == 0: | |
| if self.ms - self.ts < 400: | |
| return | |
| else: | |
| if self.ms - self.ts < 80: | |
| return | |
| self.ts = self.ms | |
| self.cnt += self.step | |
| if self.cnt == 0: | |
| self.step = 1 | |
| elif self.cnt == self.max - 1: | |
| self.step = -1 | |
| R = self.cnt % self.max | |
| G = self.cnt // self.max % self.max | |
| B = self.cnt // self.max // self.max | |
| led.write(R, R, R) | |
| class KEY: | |
| def __init__(self, pin) -> None: | |
| self.pin = digitalio.DigitalInOut(pin) | |
| self.pin.direction = digitalio.Direction.INPUT | |
| self.ts = self.ms | |
| self.sta = 0 | |
| @property | |
| def ms(self): | |
| return int(time.monotonic() * 1000) | |
| def get(self): | |
| if self.ms - self.ts < 10: | |
| return 0 | |
| self.ts = self.ms | |
| if self.sta == 0: | |
| if not self.pin.value: | |
| self.sta = 1 | |
| elif self.sta == 1: | |
| if not self.pin.value: | |
| self.sta = 2 | |
| return 1 | |
| elif self.sta == 2: | |
| if self.pin.value: | |
| self.sta = 0 | |
| return 2 | |
| return 0 | |
| print() | |
| led = LED(board.IO48) | |
| led.off() | |
| key = KEY(board.IO0) | |
| stop = False | |
| while True: | |
| if not stop: | |
| led.breath() | |
| # led.blink() | |
| sw = key.get() | |
| if sw != 0: | |
| print(f"{sw}") | |
| if sw == 1: | |
| stop = not stop | |
| if stop: | |
| led.off() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment