0

所以基本上我们在一个项目中使用树莓派,其中一部分包括超声波传感器的使用。我们有三个,我们已经能够从所有这些中获取读数(我实际上来自多线程,但决定转向多处理)。这是我的代码:

#Libraries
from multiprocessing import Process, Lock
import RPi.GPIO as GPIO
import time

#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

#set GPIO Pins
GPIO_TRIGGER1 = 23
GPIO_ECHO1 = 24

GPIO_TRIGGER2 = 27
GPIO_ECHO2 = 22

GPIO_TRIGGER3 = 25
GPIO_ECHO3 = 17

#set GPIO direction (IN / OUT)
GPIO.setup(GPIO_TRIGGER1, GPIO.OUT)
GPIO.setup(GPIO_ECHO1, GPIO.IN)

GPIO.setup(GPIO_TRIGGER2, GPIO.OUT)
GPIO.setup(GPIO_ECHO2, GPIO.IN)

GPIO.setup(GPIO_TRIGGER3, GPIO.OUT)
GPIO.setup(GPIO_ECHO3, GPIO.IN)



def sense_distance(lock, processName):
    #lock.acquire()

    gpio_echo_var = ''
    gpio_trigger_var = ''
    if processName == "Sensor-1":
        gpio_echo_var = GPIO_ECHO1
        gpio_trigger_var = GPIO_TRIGGER1
    elif processName == "Sensor-2":
        gpio_echo_var = GPIO_ECHO2
        gpio_trigger_var = GPIO_TRIGGER2
    elif processName == "Sensor-3":
        gpio_echo_var = GPIO_ECHO3
        gpio_trigger_var = GPIO_TRIGGER3

    print "%s process created." % (processName)

    try:
        while True:
            # set Trigger to HIGH
            GPIO.output(gpio_trigger_var, True)
            # set Trigger after 0.01ms to LOW
            time.sleep(0.00001)
            GPIO.output(gpio_trigger_var, False)


            StartTime = time.time()
            StopTime = time.time()

            # save StartTime
            while GPIO.input(gpio_echo_var) == 0:
               StartTime = time.time()

            # save time of arrival
            while GPIO.input(gpio_echo_var) == 1:
               StopTime = time.time()            

            # time difference between start and arrival
            TimeElapsed = StopTime - StartTime
            # multiply with the sonic speed (34300 cm/s)
            # and divide by 2, because there and back
            distance = (TimeElapsed * 34300) / 2

            if distance <= 10:
                print "%s has read less than 10 cm." % (processName)
            else:
                pass

    # Reset by pressing CTRL + C
    except KeyboardInterrupt:
        print("Measurement stopped by User")
        GPIO.cleanup()


    #lock.release()

if __name__ == '__main__':
    lock = Lock()

    Process(target=sense_distance, args=(lock, "Sensor-1")).start()
    Process(target=sense_distance, args=(lock, "Sensor-2")).start()
    Process(target=sense_distance, args=(lock, "Sensor-3")).start()

当输入小于 10 厘米时,它会成功读取输入并打印出文本。然而,过了一段时间,他们停止了。我的想法已经用完了,并且到处搜索,但最终还是失败了。任何形式的帮助将不胜感激。

4

0 回答 0