您不应该尝试根据时间同步发送方和接收方。您应该在发送方选择发送频率,让接收方坐在那里等待比特的到来,而不是休眠。因为睡觉会让你想念东西。
采用:
GPIO.add_event_detect(17, GPIO.BOTH, callback=my_callback)
监听 PIN 的变化,并my_callaback
在发生变化时执行。您也可以选择等待上升沿 viaGPIO.RISING
或下降 via GPIO.FALLING
。
对于您的示例,这是开始的,未经测试的东西或任何东西:
import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN)
def readbit(channel):
bit = GPIO.input(17)
print bit
GPIO.add_event_detect(17, GPIO.BOTH, callback=readbit)
while True:
sleep(1) # do something useful here
这可能还不够,因为您无法检测到不改变状态的位。要解决这个问题,您有很多选择,我只会提到两个最简单的选择:
控制信号
您可以使用另一个 PIN 作为控制信号,并使用它来触发接收器上的读取。这样,您在控制引脚的上升沿触发读取,并读取数据引脚的值。
在发件人上:
def send_bit(pin, bit):
GPIO.output(24, GPIO.HIGH) # first send the control bit
GPIO.output(pin, bit): # then the data on another pin
while True:
send_bit(23, GPIO.HIGH)
time.sleep(1)
send_bit(23, GPIO.LOW)
time.sleep(1)
在接收器上:
DATA_PIN = 17
CONTROL_PIN = 18 # or whatever
def readbit(channel):
bit = GPIO.input(DATA_PIN)
print bit
GPIO.add_event_detect(CONTROL_PIN, GPIO.RISING, callback=readbit)
单线协议
如果您不想使用两条线,另一种解决方案是创建一个简单的协议。例如:
- 每个传输都包含两个位:1 和 X
- 要传输的数据位是 X,而第一位始终为 1,并用作接收器的触发器
- X 位保证在第一位上升沿后的 0.1 到 0.9 秒内有效。
This might be complicated, but it actually isn't. All you need to do now is to trigger the reading on the rising edge, and read the data somewhere between 0.1 and 0.9 seconds after that. Let's make it 0.5 seconds, to be sure we are in the middle of this time.
On the sender:
def send_bit(pin, bit):
GPIO.output(pin, GPIO.HIGH) # send the control bit first, always HIGH
GPIO.output(pin, bit) # send the actual data bit
while True:
send_bit(23, GPIO.HIGH)
time.sleep(1)
send_bit(23, GPIO.LOW)
time.sleep(1)
# .... some more bits here
On the receiver:
def readbit(channel):
time.sleep(0.5) # waiting to be in the safe time for read
bit = GPIO.input(17)
print bit
GPIO.add_event_detect(17, GPIO.RISING, callback=readbit)