树莓派GPIO的使用与Arduino的引入
1. Pulse Width Modulation (PWM)
树莓派的GPIO接口上只有两个PWM引脚(引脚18和19),了解如何正确控制它们是很有用的。下面以引脚18控制LED闪烁为例进行说明。
1.1 连接电路
使用之前为LED练习搭建的电路,将跳线从引脚16移到引脚18。
1.2 编写代码
- 打开Thonny。
- 点击“New”。
- 将文件保存为
gpio_pwm_led.py
到项目文件夹。 - 输入以下代码:
# GPIO example blinking LED
# Import the GPIO and time libraries
import RPi.GPIO as GPIO
import time
# Set the GPIO mode to BCM and disable warnings
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# Define pins
pwmPin = 18
GPIO.setup(pwmPin,GPIO.OUT)
pwm = GPIO.PWM(pwmPin,100)
# Make sure LED is off
pwm.start(0)
# Begin Loop
while True:
count = 1
# begin while loop to brighten LED