mikenycz
mikenycz

Reputation: 81

Linux termios parameter interpretation

I have been trying to set up a serial port on an Olimex A13 machine with the Linux (Debian Wheezy) operating system. To set up the parameters to set up the UART I am using the termios structure. In my case I am simply setting a parameter = value like below...

options.c_cflag = (CLOCAL | CREAD);

I have also seen example code on the internet that looks like the following...

tcgetattr(fd, &options);

cfsetispeed(&options, B115200);
cfsetospeed(&options, B115200);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~( ICANON | ECHO | ECHOE |ISIG );
options.c_iflag &= ~(IXON | IXOFF | IXANY );
options.c_oflag &= ~OPOST;

tcsetattr(fd, TCSANOW, &options);

In the above case it looks like the parameter assignments are using bit-wise operators to set the parameters.
My question is, how are the above assignments interpreted?

For example: How is...

options.c_cflag |= (CLOCAL | CREAD);

interpreted compared to...

options.c_cflag = (CLOCAL | CREAD);   

???

And the same for: How is...

options.c_cflag &= ~PARENB;  

interpreted Compared to...

options.c_cflag = ~PARENB;   

???

Are the termios flags really a set of bits where the parameters correspond to a particular bit location in the flag?
Since these values are being set by parameters (i.e. CLOCAL, CREAD) are the bit wise operators redundant when setting the flag = to the parameters?
If someone can clarify this I would greatly appreciate it.

Upvotes: 1

Views: 1423

Answers (2)

Alex
Alex

Reputation: 1

options.c_cflag = ~PARENB;

options.c_cflag |= ~PARENB; // So it will be the only true

Upvotes: 0

mfro
mfro

Reputation: 3335

The termios bits are indeed bits set on an unsigned int wiithin a struct termios (at least on Linux). They are defined in /usr/include/<platform>/bits/termios.h.

How is... options.c_cflag |= (CLOCAL | CREAD); ...interpreted compared to... options.c_cflag = (CLOCAL | CREAD);

|= (CLOCAL | CREAD) will set the requested termios bits additionally to what's already there, while = (CLOCAL | CREAD) will set only the bits you requested resetting everything else to zero (which is plain wrong most likely since it will set e.g. the character size to 5 bits (CS5).

The same with c_cflag &= ~PARENB; against options.c_cflag = ~PARENB. While the former will set only the PARENB flag to zero, the latter will set all bits to 1 except the PARENB flag which will be set to zero - I don't think that's the desired result.

Upvotes: 3

Related Questions