树莓派Python循环停止

2024-04-18 09:16:55 发布

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

我操纵一个传感器:hcsr04来捕捉距离。 我是Python和RPI的新手。我的代码工作,我捕捉的距离在一段时间内,但有一刻脚本停止。。。在

我的代码:

GPIO.setmode(GPIO.BCM)

GPIO_TRIGGER = 23
GPIO_ECHO = 24

GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)

def main():
    global state
    print("ultrasonic")
    while True:
        print "1s second refresh.."
        time.sleep(1)

        i = 0
        datas = []
        average = 0

        while i< 1:
            GPIO.output(GPIO_TRIGGER, False)

            time.sleep(C.time['count'])
            GPIO.output(GPIO_TRIGGER, True)
            time.sleep(0.00001)
            GPIO.output(GPIO_TRIGGER, False)

            while GPIO.input(GPIO_ECHO) == 0:
                start = time.time()

            while GPIO.input(GPIO_ECHO) == 1:
                stop = time.time()

            distance = (stop-start) * 17000

            print "Distance : %.1f" % distance

        average = F.getAverage(datas)
        print "Average: %.1f" % average

    GPIO.cleanup()

代码到此为止

^{pr2}$

解决方案:有一个示例超时:

now = time()

while GPIO.input(self.gpio_echo) == 0 and time()-now<waitTime:
    pass

Tags: 代码echotrue距离inputoutputgpiotime
3条回答

不是真的,我想我失去信号了,我试着暂停一下

while GPIO.input(GPIO_ECHO)==GPIO.LOW:
    start = time.time()

我认为我的程序无限期地等待一个信号,但他保持在0

我很确定你想要

while GPIO.input(GPIO_ECHO)==GPIO.LOW:
    start = time.time()

while GPIO.input(GPIO_ECHO) == GPIO.HIGH:
    stop = time.time()

我不认为GPIO.input.输入很自然地返回0或1,但您可以对此进行测试。在

我也在摆弄这个传感器。我的代码执行与你的代码相似,我不需要超时就可以工作。 唯一不同的是:

while i< 1:
        GPIO.output(GPIO_TRIGGER, False)

        time.sleep(C.time['count'])

我不知道这里的睡眠时间有多长,但这可能是造成问题的原因。如果它将类似于我的设置,触发器设置为假将直接在设置输入/输出引脚,然后有两秒钟的等待,以消除噪音。你的等待时间可能会短些,我不知道。在你发送脉冲之前,不需要再把触发器设为false,我不知道,但这可能会导致错误的启动。我会将其更改为与我的类似,然后在while循环中将设置删除为false。在

^{pr2}$

我不确定这是否能在不需要暂停的情况下解决问题,但我似乎不需要暂停。在


我已经写了一个模块来制作传感器的对象,然后允许一些更可读的脚本。我对python也很陌生,根本不是一个有经验的程序员,所以可能会有一些有趣的错误,但如果您想使用它或只是比较代码,请看下面的内容:

#! /usr/bin/python3

# dist.py this is a module for objectifying an ultrasonic distance sensor.

import RPi.GPIO as GPIO
import time


class Distancer(object):
    #init takes an input of one GPIO for trigger and one for echo and creates the object,
    #it searches for a calibration file in the working directory (name)Const.txt, if none
    #is found it will initiate a calibration
    def __init__(self, trig, cho, name):
        self.trigger = trig
        self.echo = cho
        self.name = name
        self.filename = self.name + 'Const.txt'
        GPIO.setup(self.trigger, GPIO.OUT)
        GPIO.setup(self.echo, GPIO.IN)
        GPIO.output(self.trigger, False)
        print("Waiting for sensor to calm down")
        time.sleep(2)

        try:
            with open(self.filename, "r") as inConst:
                self.theConst = int(inConst.read())
        except (OSError, IOError) as e:
            print("Not calibrated, initializing calibration")
            self.calibrate()
            with open(self.filename, "r") as inConst:
                self.theConst = int(inConst.read())


    #Returns the echo time
    def measureTime(self):
        GPIO.output(self.trigger, True)
        time.sleep(0.00001)
        GPIO.output(self.trigger, False)

        while GPIO.input(self.echo) == 0:
            pulse_start = time.time()
        while GPIO.input(self.echo) == 1:
            pulse_end = time.time()

        pulse_duration = pulse_end - pulse_start
        return pulse_duration


    #Returns a distance in cm        
    def measure(self):  
        return self.measureTime() * self.theConst


    #Makes you set up the sensor at 3 different distances in order to find the
    #relation between pulse time and distance, it creates the file (name)Const.txt
    #in the working directory and stores the constant there.
    def calibrate(self):

        ten = []
        thirty = []
        seventy = []

        print("Make distance 10 cm, enter when ready")
        input()
        for i in range(30):
            ten.append(10/self.measureTime())
            time.sleep(0.2)

        print("Make distance 30 cm, enter when ready")
        input()
        for i in range(30):
            thirty.append(30/self.measureTime())
            time.sleep(0.2)

        print("Make distance 70 cm, enter when ready")
        input()
        for i in range(30):
            seventy.append(70/self.measureTime())
            time.sleep(0.2)

        allTime = ten + thirty + seventy
        theOne = 0.0
        for i in range(90):
            theOne = theOne + allTime[i]
        theOne = theOne / 90

        with open(self.filename, "w") as inConst:
                inConst.write(str(round(theOne)))


    #Will continually check distance with a given interval until something reaches the
    #treshold (cm), takes an argument to set wether it should check for something being
    #nearer(near) or farther(far) than the treashold. Returns True when treshold is reached. 
    def distWarn(self, nearfar, treashold):
        if nearfar.lower() == "near":
            while True:
                if self.measure() < treashold:
                    return True
                    break
                time.sleep(0.2)

        if nearfar.lower() == "far":
            while True:
                if self.measure() > treashold:
                    return True
                    break
                time.sleep(0.2)             


    #Will measure with a second interval and print the distance
    def keepGoing(self):
        while True:
            try:
                print(str(round(self.measure())) + ' cm')
                time.sleep(1)
            except KeyboardInterrupt:
                print("Won't keep going")
                break

我用下面的代码运行它来测试它,一切似乎都正常。第一次运行时,它会提示你校准传感器,把它放在不同的距离。在

#! /usr/bin/python3

import RPi.GPIO as GPIO
import time
import dist as distancer

GPIO.setmode(GPIO.BOARD)
TRIG = 16
ECHO = 18

dist = distancer.Distancer(TRIG, ECHO, 'dist')

def main():
    global dist
    print(str(round(dist.measureTime(),5)) + ' s')  
    print(str(round(dist.measure())) + ' cm')

    dist.distWarn('near', 10)
    print('Warning, something nearer than 10 cm at ' + time.asctime( time.localtime(time.time()) ))

    dist.distWarn('far', 10)
    print('Warning, something further than 10 cm at ' + time.asctime( time.localtime(time.time()) ))


    dist.keepGoing()
    GPIO.cleanup()
    print('Fin')


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        GPIO.cleanup()
        print("Exiting")
        time.sleep(1)

相关问题 更多 >