如何在Raspberry Pi 3 B中使用感應式接近傳感器「Python」

如何在Raspberry Pi 3 B中使用感应式接近传感器[Python]

如何在Raspberry Pi 3  B中使用感应式接近传感器「Python」

  1. 硬件准备:
  2. Raspberry Pi 3 B与Raspbian
  3. 电感式接近传感器

如何设置Raspberry Pi

如何在Raspberry Pi 3  B中使用感应式接近传感器「Python」

Raspberry pi 3 B的引脚定义

需要了解的第一件事是Raspberry pi 3 B的引脚名称。使用GPIO(通用输入/输出)引脚,并且引脚的数也会在代码中使用。

如何在Raspberry Pi 3  B中使用感应式接近传感器「Python」

Raspberry Pi的电路和传感器接线

将橙色线与第4针(5V电源)相连,将黑色线与第6针(接地)相连,将蓝色线与第11针(GPIO 17)相连。

如何设置python代码

1、安装相关库RPi.GPIO

sudo apt-get更新
sudo apt-get install rpi.gpio

2、创建一个名为test.py的python文件

nano test.py

3. 以下是需要输入的代码

import time
import RPi.GPIO as GPIO
# Pin of Input
GPIOpin = -1

导入时间库以延迟打印输出值和RPI.GPIO用于获取输入值的时间。

# Initial the input pin
def initialInductive(pin):
global GPIOpin
GPIOpin = pin
GPIO.setmode(GPIO.BCM)
GPIO.setup(GPIOpin,GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
print("Finished Initiation")
print(GPIOpin)

创建“ initialInductive”函数来更轻松地初始化树莓派的引脚。

# 金属检测功能
def detectMetal():
if(GPIOpin != -1):
state = GPIO.input(GPIOpin)
if state:
print("Metal Detected")
else :
print("Metal Not Detected")
else:
print("Please Initial Input Pin")

编写“检测到金属”功能,该功能从输入引脚读取数字值,然后将其打印出来。状态变量将有2个值为1或true的值,因此如果为true,将打印“ 检测到金属”。否则,我将打印“未检测到金属”

# test module
if __name__ == '__main__':
pin = 17
initialInductive(pin)
while True:
detectMetal()
time.sleep(0.2)

这是用来检查所有函数的代码。用GPIO引脚17来测试。


分享到:


相關文章: