linux - C program setting port parameters before opening port fails -



linux - C program setting port parameters before opening port fails -

i trying write c code on linux system, set serial port parameters open serial port, have found out though code compiles , runs, cannot read , write serial port (so serial port not opened successfully)!

code works (not needed):

int fd; char *portname; portname = "/dev/ttyusb0"; struct termios tty; fd = open(portname, o_rdwr | o_noctyy | o_sync ); memset(&tty,0,sizeof tty); tty.c_cflag &= ~parenb; tty.c_cflag &= ~cstop; tty.c_cflag &= ~csize; tty.c_cflag |= cs8; tty.c_cflag &= ~crtscts; tcsetattr(fd,tcsanow,&tty);

code doesn't work (needed)

int fd; char *portname; portname = "/dev/ttyusb0"; struct termios tty; memset(&tty,0,sizeof tty); tty.c_cflag &= ~parenb; tty.c_cflag &= ~cstop; tty.c_cflag &= ~csize; tty.c_cflag |= cs8; tty.c_cflag &= ~crtscts; tcsetattr(fd,tcsanow,&tty); fd = open(portname, o_rdwr | o_noctyy | o_sync );

solid question: application sequence requires me set serial port parameters open serial port. there way this? if yes, how?

i appreciate help.

update: removed c++ code noticed @alter mann. update: removed zeroing-out termios construction noticed @sawdust.

in first case actual file descriptor fd , after utilize it. in sec case seek setting uninitialized file descriptor fd (probably 0 if it's declared in global scope) , after actual value of it.

below workaround works me:

#include <fcntl.h> #include <termios.h> #include <strings.h> #include <stdlib.h> int main (int argc, char * argv []) { struct termios tty; const char * portname = "/dev/ttyusb0"; const int fd = open (portname, o_rdonly); if (-1 == fd) { // problem... homecoming exit_failure; } if (tcgetattr (fd, &tty) < 0) { // problem... homecoming exit_failure; } cfsetospeed (&tty, (speed_t) b9600); cfsetispeed (&tty, (speed_t) b9600); tty.c_cflag |= b9600; tty.c_cflag |= (tty.c_cflag & ~csize) | cs8; tty.c_cflag |= (clocal | cread); tty.c_cflag &= ~(parenb | parodd); tty.c_cflag |= ignpar; tty.c_cflag &= ~(crtscts); tty.c_cflag &= ~(cstopb); tty.c_iflag |= ignbrk; tty.c_iflag &= ~(ixon | ixoff | ixany); tty.c_lflag = 0; tty.c_oflag = 0; tcflush (fd, tciflush); if (tcsetattr (fd, tcsanow, &tty) ) { // problem... homecoming exit_failure; } homecoming exit_success; }

c linux serial-port

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -