---
# System prepended metadata

title: 紅綠燈作業

---

# 紅綠燈作業
## code
```python=
from machine import Pin,Timer
import time

_pins = [13,12,16] #腳位[綠,黃,紅]
led_num = 0 #腳位紀錄
led_time=[700,300,1200] #自動時間
mode = False #True->自動 False->手動
timer = Timer(0)

def init_led():#初始化led
    for i in range(3):
        Pin(_pins[i], Pin.OUT).value(0)

def auto_mode(t):#自動模式
    global led_num
    Pin(_pins[led_num], Pin.OUT).value(0)
    led_num = (led_num+1)%3
    Pin(_pins[led_num], Pin.OUT).value(1)
    timer.init(period=led_time[led_num], mode=Timer.ONE_SHOT, callback=auto_mode)

def manual_mode(x):#手動模式
    global led_num
    if(Pin(36,Pin.IN,Pin.PULL_UP).value()==0):
        Pin(_pins[led_num], Pin.OUT).value(0)
        led_num = (led_num+1)%3
        Pin(_pins[led_num], Pin.OUT).value(1)
        while(Pin(36,Pin.IN,Pin.PULL_UP).value()==0):
            pass

def mode_switch(pin):
    init_led()
    global mode,led_num
    Pin(_pins[led_num], Pin.OUT).value(1)
    if mode == True:  #自動->手動
        timer.init(period =100 ,mode = Timer.PERIODIC,callback = manual_mode)
    else:             #手動->自動
        timer.init(period=led_time[led_num], mode=Timer.ONE_SHOT, callback=auto_mode)
    mode = not mode
    time.sleep(0.3)

Pin(5,Pin.IN,Pin.PULL_UP).irq(handler = mode_switch, trigger = Pin.IRQ_FALLING)
```


