Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from machine import Pin, PWM
- from time import sleep
- PWM_MAX_DUTY = 1023
- PWM_MIN_DUTY = 0
- PWM_DUTY_RANGE = PWM_MAX_DUTY - PWM_MIN_DUTY
- def fraction_to_duty(fraction, reverse_polarity):
- duty = int(round(PWM_DUTY_RANGE * fraction)) + PWM_MIN_DUTY
- return PWM_MAX_DUTY - duty if reverse_polarity else duty
- def value_to_duty(value, max_value, reverse_polarity):
- duty = int(round((PWM_DUTY_RANGE * value) / max_value)) + PWM_MIN_DUTY
- return PWM_MAX_DUTY - duty if reverse_polarity else duty
- def unpack_color(color):
- return color & 0xFF0000, color & 0x00FF00, color & 0x0000FF
- class RGBLed:
- class Channel:
- RED = 0
- GREEN = 1
- BLUE = 2
- def __init__(self, r_pin, g_pin, b_pin, inverse_polarity=False):
- self._inverse_polarity = inverse_polarity
- initial_duty = PWM_MAX_DUTY if self._inverse_polarity else 0
- self._r_pwm = PWM(r_pin, freq=500, duty=initial_duty)
- self._g_pwm = PWM(g_pin, freq=500, duty=initial_duty)
- self._b_pwm = PWM(b_pin, freq=500, duty=initial_duty)
- self._pwm_array = [self._r_pwm, self._g_pwm, self._b_pwm]
- def deinit(self):
- [x.deinit() for x in self._pwm_array]
- def __enter__(self):
- return self
- def __exit__(self, exc_type, exc_val, exc_tb):
- self.deinit()
- def set_channel_color(self, value, channel):
- pwm = self._pwm_array[channel]
- pwm.duty(value_to_duty(value, 0xFF, self._inverse_polarity))
- def set_color(self, color):
- channel_values = color if isinstance(color, list) else unpack_color(color)
- for i, pwm in enumerate(self._pwm_array):
- pwm.duty(value_to_duty(channel_values[i], 0xFF, self._inverse_polarity))
- def loop_colors(rgb_led, sleep_time=0.01):
- color = [0xFF, 0, 0]
- for color_dec in range(0, 2):
- color_inc = color_dec + 1 if color_dec < 1 else 0
- for i in range(0, 0xFF):
- color[color_dec] -= 1
- color[color_inc] += 1
- print(color)
- rgb_led.set_color(color)
- sleep(sleep_time)
- def loop_colors_2(rgb_led, sleep_time=0.01):
- max_color = 0xFF
- rgb_led.set_color([0, 0, 0])
- for color_pass in range(0, 2):
- for color in range(0, max_color + 1):
- rgb_led.set_channel_color(color if color_pass == 0 else max_color - color, RGBLed.Channel.RED)
- sleep(sleep_time)
- def main():
- r_pin = Pin(14, Pin.OUT)
- g_pin = Pin(12, Pin.OUT)
- b_pin = Pin(13, Pin.OUT)
- with RGBLed(r_pin, g_pin, b_pin) as rgb_led:
- while True:
- loop_colors(rgb_led)
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement