Witam!
Muszę zrobić komunikację po rs232.
Problem polega na tym, że program musi być responsywny cały czas i nie może męczyć procesora. Trochę poczytałem i wymyśliłem sobie, że będzie to działało następująco:
otworzę port, utworzę nowy wątek (pthread), w którym użyję funkcji poll, która czeka na otrzymanie danych.
Niestety użycie funkcji poll blokuje wykonanie całości kodu (program nie wykonuje nawet jedniej instrukcji (pierwszej w mainie)).
Docelowo wątek odbierania ma być uśpiony do czasu odebrania danych bądź do zakończenia programu.
Program będzie uruchamiany na Raspberry PI
#define SERIAL_DEVICE "/dev/ttyUSB0"
#define SERIAL_BAUD 2400
#include <wiringSerial.h>
#include <stdio.h>
#include <pthread.h>
#include <poll.h>
void *receiving( void *ptr )
{
printf("Jestem w nowym watku");
int fd= (int)ptr;
struct pollfd fds[1];
fds[0].fd = fd;
fds[0].events = POLLIN ;
int pollrc=-1;
while(1)
{
pollrc = poll( fds, 1, -1);
if (pollrc < 0)
{
perror("poll");
}
else if( pollrc > 0)
{
if( fds[0].revents & POLLIN )
{
unsigned char buff[1024];
ssize_t rc = read(fd, buff, sizeof(buff) );
if (rc > 0)
{
printf("Przeczytalem: %s",buff);
}
}
}
}
}
int main(int argc, char *argv[])
{
int fd = serialOpen(SERIAL_DEVICE, SERIAL_BAUD);
if (fd<0)
{
printf("Serial opening error");
return 1;
}
pthread_t serialReceiver;
printf("-----");
int thr=pthread_create(&serialReceiver,NULL,receiving,fd);
printf("%i",thr);
if(thr!=0)
{
printf("Error during creating serialReceiver thread.");
return 1;
}
int status;
pthread_join(serialReceiver,(void **)&status);
printf("%i",status);
return 0;
}