Hi -
I’m trying to send data bytes from a GPIO pin at a rate of 10 k bits/sec. I’ve tried writing code in Python and in C. After I set or clear the pin, I call a sleep
function to adjust the length of the bit to be 100 uS. Although any call to the usleep
function produces a delay of more than 100 uS, even using usleep(1)
to usleep(50)
.
Is there a way to get the code to execute faster or is it the nature of what’s running in the background like the GUI etc taking up processing power?? Or is there a better way of timing the delay precisely?
Here are the loop tests I created.
Python:
import time
import sys
receive_pin = 18 # BCM pin number. physical pin 12
transmit_pin = 4 # BCM pin number. physical pin 7
def __init__(self,receive_pin, transmit_pin):
self.rx_pin = receive_pin
self.tx_pin = transmit_pin
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.tx_pin, GPIO.OUT)
while True:
GPIO.output(self.tx_pin,0)
time.sleep(1/100000)
GPIO.output(self.tx_pin,1)
time.sleep(1/100000)
C example:
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int fd = open("/sys/class/gpio/gpio79/direction", O_WRONLY);
if (fd == -1) {
perror("Unable to open /sys/class/gpio/gpio79/direction");
exit(1);
}
if (write(fd, "out", 3) != 3) {
perror("Error writing to /sys/class/gpio/gpio79/direction");
exit(1);
}
close(fd);
fd = open("/sys/class/gpio/gpio79/value", O_WRONLY);
if (fd == -1) {
perror("Unable to open /sys/class/gpio/gpio79/value");
exit(1);
}
// Endless loop to test write speed
for (;;) {
write(fd, "1", 1);
usleep(1); // Delay for 1 u Sec
write(fd, "0", 1);
usleep(1); // Delay for 1 u Sec
}
close(fd);
return 0;
}
In both of these examples when the sleep function is called, the delay is too long.
Any help will be very appreciated!
Thanks
Jamie