将raspberry pi的两个python代码与伺服和ldr传感器相结合
我在我的raspberry pi 2b和一个光传感器上运行Python代码,它测量光传感器电容器充电和将引脚发送到高位所需的时间:将raspberry pi的两个python代码与伺服和ldr传感器相结合,python,raspberry-pi2,Python,Raspberry Pi2,我在我的raspberry pi 2b和一个光传感器上运行Python代码,它测量光传感器电容器充电和将引脚发送到高位所需的时间: import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) pin_to_circuit = 7 def rc_time (pin_to_circuit): count = 0 #Output on the pin for GPIO.setup(pin_to_circui
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
pin_to_circuit = 7
def rc_time (pin_to_circuit):
count = 0
#Output on the pin for
GPIO.setup(pin_to_circuit, GPIO.OUT)
GPIO.output(pin_to_circuit, GPIO.LOW)
time.sleep(0.1)
#Change the pin back to input
GPIO.setup(pin_to_circuit, GPIO.IN)
#Count until the pin goes high
while (GPIO.input(pin_to_circuit) == GPIO.LOW):
count += 1
if count > 1000000:
return True
else:
return count
#Catch when script is interrupted, cleanup correctly
try:
# Main loop
while True:
print rc_time(pin_to_circuit)
except KeyboardInterrupt:
pass
finally:
GPIO.cleanup()
我希望当计数超过1000000时,MG90S,我也连接到pi和4AA电池组,移动大约90度。
我尝试集成的代码用于移动伺服:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)
p.ChangeDutyCycle(7.5) # turn towards 90 degree
time.sleep(1) # sleep 1 second
p.stop()
GPIO.cleanup()
我想结合这两个Python代码。我尝试了一点,但我几乎没有Python经验。您可以将用于移动MG90的代码块集成到一个函数中,在
def rc\u时间(pin\u-to\u电路)之前或之下插入它:
(但首先您必须在内部定义p
,这并不清楚p
指的是什么):
来自第二个代码块的新函数:
def move_90_degrees():
p = '???'
GPIO.setup(12, GPIO.OUT)
p.ChangeDutyCycle(7.5) # turn towards 90 degree
time.sleep(1) # sleep 1 second
p.stop()
定义此函数后,在第一个块内调用它,如:
if count > 1000000:
move_90_degrees()
return True
else:
return count
这应该行得通。代码现在是:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
pin_to_circuit = 7
def move_90_degrees():
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)
p = GPIO.PWM(12, 50)
p.start(7.5)
p.ChangeDutyCycle(7.5) # turn towards 90 degree
time.sleep(1) # sleep 1 second
p.stop()
def rc_time (pin_to_circuit):
count = 0
#Output on the pin for
GPIO.setup(pin_to_circuit, GPIO.OUT)
GPIO.output(pin_to_circuit, GPIO.LOW)
time.sleep(0.1)
#Change the pin back to input
GPIO.setup(pin_to_circuit, GPIO.IN)
#Count until the pin goes high
while (GPIO.input(pin_to_circuit) == GPIO.LOW):
count += 1
if count > 1000000:
return True
move_90_degrees()
else:
return count
#Catch when script is interrupted, cleanup correctly
try:
# Main loop
while True:
print rc_time(pin_to_circuit)
except KeyboardInterrupt:
pass
finally:
GPIO.cleanup()
当计数超过1000000时,代码打印为真,但伺服仍不移动。然而,伺服代码本身不能正常工作。(我忘记了一点伺服代码,这就是为什么p没有定义,对不起。)我在代码中犯了一个错误。我在
if count > 1000000:
return True
move_90_degrees()
else:
return count
阻止到:
if count > 1000000:
move_90_degrees()
return True
else:
return count
否则,代码将在执行函数调用之前返回。现在可以用了吗