2015-04-16 76 views
3

我將我的樹莓派連接到2.4ghz rc接收器,並且我試圖使用python來解釋脈衝寬度信號。我使用一個輸入引腳來讀取沒有輸入的時間,然後是有輸入的時間,然後減去兩個。脈衝寬度閱讀器每次打印相同的值

import RPi.GPIO as GPIO 
import time 

GPIO.setmode(GPIO.BOARD) 

GPIO.setup(13,GPIO.IN) 
GPIO.setup(15,GPIO.OUT) 
GPIO.output(15,GPIO.HIGH) 

start = time.time() 
stop = time.time() 

x = 0 
y = 0 

while(x == 0): 
    if(GPIO.input(13) == 0): 
     start = time.time() 
     x = 1 

while(y == 0): 
    if(GPIO.input(13) == 1): 
     stop = time.time() 
     y = 1 

Width = stop-start 

print(Width) 

GPIO.cleanup() 

我遇到的問題是,不管多久,我讓脈衝寬度(通過手動連接和斷開銷13和15),它打印〜0.006。它也將不會打印,直到我斷開對方的針腳,雖然我一直無法弄清楚爲什麼。

+0

看不出爲什麼這樣做不起作用,但是你可以用中斷來代替:https://www.raspberrypi.org/forums/viewtopic.php?f=32&t=43069 – 101

回答

0

針13可能是浮動的。我建議你更換...

GPIO.setup(13,GPIO.IN) 

...與...

GPIO.setup(13,GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 

這裏有一個如何使用中斷做到這一點的例子:

#!/usr/bin/env python3 
# example of reading PWM with GPIO interrupts 
# Warning: Linux isn't built for real-time applications. 
# A Raspberry Pi with Jessie will not produce reliable results 
# That said... 

import RPi.GPIO as GPIO 
import time 

GPIOpin_IN = 13 
GPIOpin3v3 = 1 # fixed at 3v3 volts 
myStart = None 
myStop = None 

GPIO.setmode(GPIO.BOARD) 
GPIO.setup(GPIOpin_IN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 

def pinGoesUp(gpioIdentity): 
    myStart = time.time() 

def pinGoesDown(gpioIdentity): 
    myStop = time.time() 

GPIO.add_event_detect(GPIOpin_IN, GPIO.RISING, callback=pinGoesUp) 
GPIO.add_event_detect(GPIOpin_IN, GPIO.FALLING, callback=pinGoesDown) 

while True: 
    if myStop < myStart: 
     Width = stop-start 
     print(Width)` 

documentation on gpio input

在附註中,您將難以獲得可靠的讀數。 Jessie並不打算提供實時交互,並且經常需要很小的休假來完成其他任務。