## 交通灯 ![](https://img.kancloud.cn/dd/25/dd250dbe045a360551c15d36e9656df5_491x388.png) 全彩交通灯系统。 像使用Pi-Stop一样使用`TrafficLights`套件。 >译注:Pi-Stop是下面这个硬件: ![](https://img.kancloud.cn/e4/94/e494d77d4b8466d05fe3d5d994629f4e_587x275.png) ![](https://img.kancloud.cn/5d/9d/5d9dd3742ab54a478c9ce97fc4a3ba02_494x438.png) ~~~ from gpiozero import TrafficLights from time import sleep lights = TrafficLights(2, 3, 4) lights.green.on() while True: sleep(10) lights.green.off() lights.amber.on() sleep(1) lights.amber.off() lights.red.on() sleep(10) lights.amber.on() sleep(1) lights.green.on() lights.amber.off() lights.red.off() ~~~ 等效写法: ~~~ from gpiozero import TrafficLights from time import sleep from signal import pause lights = TrafficLights(2, 3, 4) def traffic_light_sequence(): while True: yield (0, 0, 1) # green sleep(10) yield (0, 1, 0) # amber sleep(1) yield (1, 0, 0) # red sleep(10) yield (1, 1, 0) # red+amber sleep(1) lights.source = traffic_light_sequence() pause() ~~~ >译注:等效写法使用了`yield`生成器功能,可以忽略,这个功能比较抽象,有点难以理解。 如果不用`TrafficLights`套件,而是用`LED`类,代码如下: ~~~ from gpiozero import LED from time import sleep red = LED(2) amber = LED(3) green = LED(4) green.on() amber.off() red.off() while True: sleep(10) green.off() amber.on() sleep(1) amber.off() red.on() sleep(10) amber.on() sleep(1) green.on() amber.off() red.off() ~~~