3624| 1
|
[教程] zero玩树莓派2 有趣的blink和pwm |
一、教学目标 1.了解blink方法和PWMLED类 2.编程实现LED呼吸灯 二、实验设备 1.树莓派 *1https://www.dfrobot.com.cn/goods-1976.html 2.树莓派扩展板*1 https://www.dfrobot.com.cn/goods-2041.html 3.LED模块*1https://www.dfrobot.com.cn/goods-72.html (2-3两个设备取代面包板,LED, 杜邦线 , 电阻,完美解决接线的烦恼) 知识回顾 LED模块点亮程序1,通过LED的 on 和off 方法来控制led灯的亮灭 程序实操: 新知识,有趣的ZERO库中也可以用blink方法来实现,而且代码少: blink(on_time=1, off_time=1, fade_in_time=0, fade_out_time=0, n=None, background=True) Make the device turn on and off repeatedly.
示例代码: from gpiozero import LED from signal import pause led =LED(17) led.blink() pause() #注意pause函数 不能去掉,否则程序执行一遍就停止了。 新知识:PWMLED实现呼吸灯的效果 PWM信号调节LED亮度,是学习LED时的入门课程。 PWM是脉冲宽度调制信号,即脉冲的高电平的时间。调用PWMLED的类, 配合pulse命令发射信号指令,控制LED呼吸灯效果。 classgpiozero.PWMLED(pin, *, active_high=True, initial_value=0, frequency=100, pin_factory=None) Extends PWMOutputDevice and represents a light emitting diode (LED) with variable brightness. A typical configuration of such a device is to connect a GPIO pin to the anode (long leg) of the LED, and the cathode (short leg) to ground, with an optional resistor to prevent the LED from burning out.
具体代码一from gpiozero import PWMLED #导入 PWMLED类 from signal import pause led =PWMLED(17) #设置GPIO17端口 led.pulse() #发送脉冲 pause() 具体代码二 你也可以用下面的代码来写同样的程序,其中,value值为0-1之间 from gpiozero import PWMLED from time import sleep led =PWMLED(17) while True: led.value =0 sleep(1) led.value =0.5 sleep(1) led.value =1 sleep(1) 具体代码三 同样可以用for 循环实现 from gpiozero import PWMLED from time import sleep led =PWMLED(17) num =0 while True: for i in range(0,11): num=i*0.1 led.value =num sleep(1) #此处一秒时间较长,后续调整成了0.1秒效果更好 具体代码四 from gpiozero import PWMLED from time import sleep led =PWMLED(17) num =0 while True: for i in range(0,11): num=i*0.1 led.value =num sleep(0.1) |
© 2013-2025 Comsenz Inc. Powered by Discuz! X3.4 Licensed