Reputation: 133
I got a character device for some gpio on an industrial PC running under Debian.
Reading in C works pretty fine
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main (int argc, char **argv) {
int fd;
fd = open("/dev/bsw_gpio", O_RDWR);
if (fd == -1) {
printf("could not open device");
return 1;
}
unsigned char val;
int ret;
ret = read(fd, &val, sizeof(val));
if (ret == 0)
printf("Value : %d\n", val);
else
printf("No val read\n");
if(close(fd) != 0) {
printf("Could not close file");
}
return 0;
}
I forgot; this gets me the status of the two io pins as value between 0 and 3 and works well.. But I need to do this in Python.
Whereas Python reacts this way
>>> import os
>>> fp = os.open("/dev/bsw_gpio", os.O_RDWR)
>>> os.read(fp, 1)
b''
or, using normal open:
>>> with open('/dev/bsw_gpio', 'r+b', buffering=0) as fp:
... fp.read()
...
b''
How can I fix this?
Upvotes: -1
Views: 49
Reputation: 133
i found out that I need to read into a fixed size bytearray. Since I needed to convert to int after, I just used an array of 2 bytes, reversed it and have the correct value now.
class DigitalIO():
def __init__(self):
'''
öffne die Datei
'''
self.file = open(DigitalIO.FILENAME, 'r+b', 0)
def read_value(self):
'''
lies einen Wert
'''
val = bytearray(2)
self.file.readinto(val)
val.reverse()
return int(val.hex(), 16)
def write_value(self, value):
'''
schreibe einen Wert
'''
self.file.write(value.to_bytes(1, 'little'))
Upvotes: 0