#include #include #include #include #include #include #include #include #include #define DEV_UART "/dev/tts/0" void initUart(int uart, struct pollfd* pfd, speed_t speed, struct serial_icounter_struct* last_icounter) { struct termios options; tcgetattr( uart, &options ); cfmakeraw( &options ); cfsetispeed( &options, speed ); cfsetospeed( &options, speed ); options.c_cflag &= ~CSIZE; //clear charsize-bits options.c_cflag |= CS8; options.c_iflag &= ~PARENB; options.c_cflag &= ~CSTOPB; options.c_iflag &= ~IGNPAR; // do not ignore framing and parity errors tcsetattr( uart, TCSANOW, &options ); tcflush( uart, TCIOFLUSH ); //read garbage if (poll( pfd, 1, 1000 ) > 0) { usleep( 500 /*ms*/ * 1000 /*us*/ ); unsigned char buffer[16384 + 1]; read( uart, buffer, sizeof( buffer ) ); ioctl( uart, TIOCGICOUNT, last_icounter ); } } void readUart(int uart, struct pollfd* pfd, struct serial_icounter_struct* last_icounter) { int retval = poll( pfd, 1, 1000 ); if ( retval > 0 ) { if ( pfd->revents & POLLIN ) { // etwas warten, damit nicht ständig einzelne Zeichen von der Seriellen geholt werden // TODO: für z.B. A/D-Probe ggf. reduzieren (Template-Argument?) usleep( 2 /*ms*/ * 1000 /*us*/ ); unsigned buffer[16384 + 1]; int countBytes = read( uart, buffer, sizeof( buffer ) ); printf("received something: "); { int i = 0; for (; i < countBytes; ++i) printf("%x ", (unsigned short) buffer[i]); } printf("\n"); struct serial_icounter_struct icounter; ioctl( uart, TIOCGICOUNT, &icounter ); if (icounter.brk != last_icounter->brk ) printf("Break "); if (icounter.frame != last_icounter->frame ) printf("Framing Error "); if (icounter.parity != last_icounter->parity ) printf("Parity Error "); if (icounter.overrun != last_icounter->overrun) printf("Overrun"); printf("\n"); *last_icounter = icounter; } else { printf("received nothing\n"); } } else { int error = errno; printf("error while waiting for data on serial port: %s\n", strerror( error ) ); } } speed_t getNextSpeed(speed_t curSpeed) { switch (curSpeed) { case B4800: return B9600; case B9600: return B19200; case B19200: return B38400; case B38400: return B57600; case B57600: return B115200; case B115200: return B4800; } return B4800; } int main() { struct pollfd pfd; pfd.events = POLLIN; speed_t cur_speed=B4800; struct serial_icounter_struct last_icounter; while(1) { pfd.fd = open( DEV_UART, O_RDWR | O_NONBLOCK ); printf("trying %d\n", cur_speed); initUart(pfd.fd, &pfd, cur_speed, &last_icounter); readUart(pfd.fd, &pfd, &last_icounter ); close( pfd.fd ); cur_speed = getNextSpeed( cur_speed ); } return 0; }