# 作者:林宜駿 (Eric Lin)
# 主題:變數與迴圈
# 最後更新:2022-10-16
# ※※※ RGB LED 燈預設 COM 腳是陽極,要到 diagram.json 把 COM 改為陰極 (cathode)
# ===== 6~26 的程式碼在設定 MCU 的腳位,可以略過 =====
from machine import Pin, PWM
import time
# 建立接腳資訊的變數
p18 = Pin(18, mode=Pin.OUT)
p19 = Pin(19, mode=Pin.OUT)
p21 = Pin(21, mode=Pin.OUT)
# 把數位訊號接腳包裝成「可模擬類比訊號」的 PWM 接腳
red_led = PWM(p18)
green_led = PWM(p19)
blue_led = PWM(p21)
# 設定模擬類比訊號的頻率範圍
red_led.freq(1000)
green_led.freq(1000)
blue_led.freq(1000)
# ===== 6~26 的程式碼在設定 MCU 的腳位,可以略過 =====
# 筆記 (1) 變數的使用 (可在 Google 搜尋 color picker 查色碼):
scale = 1000 / 255
r = int(0 * scale)
g = int(255 * scale)
b = int(255 * scale)
# 筆記 (2) 函式的使用
# red_led.duty(r)
# green_led.duty(g)
# blue_led.duty(b)
# 筆記 (3) while 迴圈
# count = 0
# while count < 5:
# red_led.duty(r)
# green_led.duty(g)
# blue_led.duty(b)
# time.sleep(1) # time.sleep(x) 函式的作用是讓電腦休眠不做事 x 秒
# red_led.duty(0)
# green_led.duty(0)
# blue_led.duty(0)
# time.sleep(1)
# count = count + 1
# 筆記 (4) for 迴圈
scale = 1000 / 255
color_dictionary = {
'紅': (255, 0, 0),
'橙': (255, 125, 0),
'黃': (255, 255, 0),
'綠': (0, 255, 0),
'藍': (0, 0, 255),
'靛': (0, 255, 255),
'紫': (255, 0, 255),
}
def show_color(color_text):
color = color_dictionary.get(color_text, (255, 255, 255))
r = int(color[0] * scale)
g = int(color[1] * scale)
b = int(color[2] * scale)
red_led.duty(r)
green_led.duty(g)
blue_led.duty(b)
time.sleep(0.5)
red_led.duty(0)
green_led.duty(0)
blue_led.duty(0)
time.sleep(0.5)
for c in ['紅', '橙', '黃', '綠', '藍', '靛', '紫']:
show_color(c)