### lab5-1 ### from machine import Pin import utime, urandom r = Pin(14, Pin.OUT) g = Pin(12, Pin.OUT) b = Pin(13, Pin.OUT) while True: r.value(urandom.getrandbits(1)) g.value(urandom.getrandbits(1)) b.value(1 if r.value() == 0 and g.value() == 0 else urandom.getrandbits(1)) utime.sleep_ms(500) ### lab5-2 ### from machine import Pin, PWM import utime, urandom while True: #隨機指定每個燈號是否要亮起 r_switch = urandom.getrandbits(1) g_switch = urandom.getrandbits(1) b_switch = 1 if r_switch == 0 and g_switch == 0 else urandom.getrandbits(1) #指定的燈號要亮起時再建立該 PWM 物件 if r_switch == 1: r = PWM(Pin(14, Pin.OUT), freq=1000, duty=0) if g_switch == 1: g = PWM(Pin(12, Pin.OUT), freq=1000, duty=0) if b_switch == 1: b = PWM(Pin(13, Pin.OUT), freq=1000, duty=0) for i in range(1024): if r_switch == 1: r.duty(i) if g_switch == 1: g.duty(i) if b_switch == 1: b.duty(i) utime.sleep_ms(1) for i in reversed(range(1024)): if r_switch == 1: r.duty(i) if g_switch == 1: g.duty(i) if b_switch == 1: b.duty(i) utime.sleep_ms(1) #每次燈滅掉後都關閉所有的 PWM 物件 if r_switch == 1: r.deinit() if g_switch == 1: g.deinit() if b_switch == 1: b.deinit() ### lab5-3 ### from machine import Pin, I2C, PWM from hcsr04 import HCSR04 import bh1750fvi, utime sonar = HCSR04(trigger_pin=0, echo_pin=16) r = PWM(Pin(14, Pin.OUT), freq=1000, duty=0) g = PWM(Pin(12, Pin.OUT), freq=1000, duty=0) b = PWM(Pin(13, Pin.OUT), freq=1000, duty=0) while True: distance = sonar.distance_cm() light_level = bh1750fvi.sample(I2C(scl=Pin(5), sda=Pin(4)), mode=0x23) if 2 <= distance <= 30: led_light_value = 1023 else: if light_level > 256: light_level = 256 led_light_value = (256 - light_level) * 4 - 1 r.duty(led_light_value) g.duty(led_light_value) b.duty(led_light_value) utime.sleep_ms(50)