python和Rasldr结合使用两个伺服代码

2024-04-26 21:53:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我在我的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_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,一个MG90,我也连接到pi和4AA电池组,移动大约90度。 我试图整合代码来移动伺服:

^{pr2}$

我想合并这两个Python代码。我试过一段时间,但我几乎没有Python的经验。在


Tags: theto代码importinputgpiotimecount
3条回答

代码现在是:

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

阻止到:

^{pr2}$

否则,代码将在执行函数调用之前返回。现在有效吗?在

您可以将用于移动MG90的代码块集成到一个函数中,将其插入到def rc_time (pin_to_circuit):之前或之下(但是首先必须在内部定义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()

定义此函数后,在第一个块中调用它,如下所示:

^{pr2}$

那应该行得通。在

相关问题 更多 >