i'm new raspberry pi, trying send stream of bits sender receiver. bits not received in correct pattern of times, seems shifted little. think i'm unable synchronize them properly. how can sync clocks
python code here
# sender import rpi.gpio gpio import time gpio.setmode(gpio.bcm) gpio.setup(23, gpio.out) while true: gpio.output(23, gpio.high) time.sleep(1) gpio.output(23, gpio.low) time.sleep(1) # .... more bits here
# receiver import rpi.gpio gpio import time gpio.setmode(gpio.bcm) gpio.setup(17, gpio.in) while true: bit = gpio.input(17) print bit time.sleep(1)
you should not try synchronize sender , receiver based on time. should choose frequency of sending on sender side, , let receiver sit there , wait bits come, without sleeping. because sleeping makes miss stuff.
use:
gpio.add_event_detect(17, gpio.both, callback=my_callback)
to listen change on pin, , execute my_callaback
when happens. can choose wait rising edge via gpio.rising
or falling via gpio.falling
.
for example, here start with, not tested or anything:
import rpi.gpio gpio 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) # useful here
this won't enough, since can't detect bits don't change state. tackle this, have quite few options, , mention 2 simple ones:
control signal
you can use pin control signal, , use trigger reads on receiver. way, trigger read on rising edge of control pin, , read value of data pin.
on sender:
def send_bit(pin, bit): gpio.output(24, gpio.high) # first send control bit gpio.output(pin, bit): # data on pin while true: send_bit(23, gpio.high) time.sleep(1) send_bit(23, gpio.low) time.sleep(1)
on receiver:
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)
one wire protocol
another solution, if don't want use 2 wires, create simple protocol. example:
- every transmission consists of 2 bits: 1 , x
- data bit transferred x, whereas first bit 1 , serves trigger receiver
- the x bit guaranteed active 0.1 0.9 seconds after first bit's rising edge.
this might complicated, isn't. need trigger reading on rising edge, , read data somewhere between 0.1 , 0.9 seconds after that. let's make 0.5 seconds, sure in middle of time.
on sender:
def send_bit(pin, bit): gpio.output(pin, gpio.high) # send control bit first, high gpio.output(pin, bit) # send actual data bit while true: send_bit(23, gpio.high) time.sleep(1) send_bit(23, gpio.low) time.sleep(1) # .... more bits here
on receiver:
def readbit(channel): time.sleep(0.5) # waiting in safe time read bit = gpio.input(17) print bit gpio.add_event_detect(17, gpio.rising, callback=readbit)