Python Raspberry Pi GPIO output control: control of LED lights

Getting Raspberry Pi GPIO control output from the control LED lights should all start it.

 

Raspberry Pi version: Model 3B +

Raspberry Pi system: Raspbian Stretch with desktop and recommended software, April 2019

Connecting means

Preparing an LED, are two two female Dupont line. FIG raspberry send the connection control and the LED lamp, a requirement is the ground ( the GND negative electrode) connected to a lamp, a  GPIO + BCM ID connect the positive. I chose to pin No. 6 and 12 of the two pins. You can also choose other, remember the code after the BCM will modify the correct number

 

Connected to the power off state. Ligated below, I have positive and negative LED lamp tips pointing red arrow shown in the figure is a positive electrode, a negative electrode blue arrows. If your LED lights is the simplest kind, long pin is positive, negative short.

Raspberry Pi boot.

Installation RPI.GPIO

I installed the Raspberry Pi system has to meet the needs of the environment, no additional download.

You can test whether the module has been open Python3 in the terminal, and then try to import the library:  Import RPi.GPIO AS the GPIO  . If no error occurs, it means already, you can skip the next step.

If an error occurs, execute the following command:

sudo apt-get update
sudo apt-get install python3-rpi.gpio

GPIO Test

Sequentially input command shown below, was observed.

GPIO.setmode() 有两种参数可以选择:可以使用 GPIO.BOARD 选项告诉库根据 GPIO 接口的引脚号引用信号,或者使用 Broadcom 芯片的信号编号( GPIO.setmode(GPIO.BCM) )。

在选择了模式之后,需要确定在程序中使用哪一个 GPIO 信号以及将家门用来作为输入还是输出:GPIO.setup(channel, direction)。我给的例子里是 GPIO.setup(18, GPIO.OUT) 。

后面两个命令控制灯的开关: GPIO.output(18, GPIO.HIGH) 和 GPIO.output(18, GPIO.LOW) 。

 GPIO.cleanup() 用于重置 GPIO 接口,它把所有的 GPIO 引脚设置为低电平状态,所以没有多余的信号出现在界面上。在不使用改函数的情况下,如果试图配置一个已分配信号值的 GPIO 信号引脚,那么 RPi.GPIO 模块会产生一条警告信息。

闪烁 LED

然后我在树莓派上编写了下面这个代码让 LED 灯闪烁五次,保存在 Desktop,命名为 led.py。

#!/usr/bin/python3

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.output(18, GPIO.LOW)
blinks = 0
print('开始闪烁')
while (blinks < 5):
    GPIO.output(18, GPIO.HIGH)
    time.sleep(1.0)
    GPIO.output(18, GPIO.LOW)
    time.sleep(1.0)
    blinks = blinks + 1
GPIO.output(18, GPIO.LOW)
GPIO.cleanup()
print('结束闪烁')

 

演示结果:

 

参考资料

《树莓派Python编程 入门与实战(第2版)》,人民邮电出版社

Guess you like

Origin www.cnblogs.com/zhenqichai/p/raspberry-pi-control-GPIO-with-python.html