对于一个学校项目,我需要制造一辆汽车,该汽车使用RPi.GPIO库通过连接到树莓派零零W上的GPIO的传感器来检查颜色。同时,我想使用gpiozero库使用四个gpio引脚来驾驶汽车。运动的控件通过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()
我让颜色传感器的代码在主线程中运行
我希望一切正常,汽车向前行驶,颜色传感器读取正确的值