python - 多线程python中的gpio阻塞
问题描述
对于一个学校项目,我需要使用 RPi.GPIO 库制作一辆汽车,该汽车使用连接到树莓派零 W 上的 GPIO 的传感器检查颜色。同时,我还想用四个 gpio 引脚使用 gpiozero 库来驾驶汽车。用于移动的控制器通过 python 套接字服务器发送到 pi 零。我已将所有这些进程放在不同的线程中,但现在我似乎无法驾驶汽车。似乎 Gpiozero 被禁用并且 Rpi.Gpio 只能工作。
颜色传感器代码
import RPi.GPIO as GPIO
import time
S2 = 26 #select color / S2
S3 = 21 #select color / S3
wave = 20 #sine wave proportional to light frequency / OUT
pulses = 1000 #pulses to check, more pulses increase accuracy but decreases speed
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setup(wave, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(S2, GPIO.OUT)
GPIO.setup(S3, GPIO.OUT)
def getFrequency(color):
if (color == 'red'):
GPIO.output(S2, GPIO.LOW)
GPIO.output(S3, GPIO.LOW)
if (color == 'green'):
GPIO.output(S2, GPIO.HIGH)
GPIO.output(S3, GPIO.HIGH)
if (color == 'blue'):
GPIO.output(S2, GPIO.LOW)
GPIO.output(S3, GPIO.HIGH)
if (color == 'clear'):
GPIO.output(S2, GPIO.HIGH)
GPIO.output(S3, GPIO.LOW)
startTime = time.time()
for pulseCount in range(pulses):
GPIO.wait_for_edge(wave, GPIO.FALLING)
duration = time.time() - startTime
frequency = wave / duration
return frequency
def endProgram():
GPIO.cleanup()
setup()
运动代码
from gpiozero import Motor
class Movement:
#define pi zero pin numbers and pwm speed
pin1 = 17 #forward
pin2 = 18 #backward
pin3 = 22 #left
pin4 = 23 #right
pwm = 1.0 #0.0 to 1.0
motor = Motor(pin1, pin2, True)
steer = Motor(pin3, pin4)
# Set the pwm of the car
def setPWM(self, pwm):
self.pwm = pwm
def forward(self):
self.motor.forward(self.pwm)
def backward(self):
self.motor.backward(self.pwm)
def halt(self):
self.motor.stop()
def right(self):
self.steer.forward()
def left(self):
self.steer.backward()
def straight(self):
self.steer.stop()
在另一个文件中,我有这些功能
def listen():
print("Listening to commands")
while True:
msg = socket.receive()
print("received: " + msg)
try:
if(msg == something):
movement.forward() #ect
except:
print(msg)
listening = Thread(target=listen)
listening.start()
我让颜色传感器的代码在主线程中运行
我希望一切正常,汽车向前行驶,颜色传感器读取正确的值
解决方案
推荐阅读
- c# - 无法使用 c# 以编程方式访问 iis 远程服务器
- elasticsearch - Elasticsearch 匹配数组使用
- powershell - 找不到 SqlServerIntegrationService 的路径,但确实存在
- sql - Use for loop in Oracle SQL developer
- php - 删除功能无法在php ajax中删除表中的一行
- pyspark - get date Intervals in pyspark
- javascript - How to append to Map JavaScript?
- json - Use jq to filter json with regex, and the rest objects split into two separate chunks, containing half of the remaining objects each
- android - apk 符号-> 错误:com.android.build.gradle.internal.transforms.ProGuardTransform.transform
- sql - How to find if records match or not