Click to See Complete Forum and Search --> : Wierd C code???????


greadey
04-30-2001, 04:34 PM
Hi peeps, I am trying (must be a masochist) to write my own C-code to read and write to a serial port. One of my biggest problems is I have to understand why I'm doing something. So here we go;

the serial port is programmed with the use of the termios.h header which allows a struct of type termios to be defined. This struct contains the various flags to set serial port parameters. This much I have no problem with, what is bugging me is the way that the following is written;

newtio.c_cflag = BAUDRATE | CRTCTS | CS8 | CLOCAL | CREAD;

where newtio is predeclared as:-

struct termios newtio;

and BAUDRATE is #defined as "B9600".

c_cflag is obviously an array variable in newtio, what I don't understand is the apparently strange way of filling it. The code suggests to me that newtio.c_cflag can take any of the values assigned to it, and that termios.h knows which one it needs and where. Am I correct or way of base? If someone can help, this naive newbie would be very grateful.

greadey :confused:

Strike
04-30-2001, 04:49 PM
No, notice those are single "pipes", meaning bitwise OR, not logical OR. So, those are all OR'ed together.

Stuka
04-30-2001, 06:42 PM
What Strike said!

Actually, what's happening is that those values are set up as independent flag bits in a larger variable. Using the bitwise or creates a single value with the appropriate bits set. For example, suppose I was using a single byte - 00000000 would indicate all flags off. Suppose I #define FOOFLAG 32. Now, if FOOFLAG is on, I'll have 00100000. And if I want to turn on BARFLAG (#define BARFLAG 8) I need to do FOOFLAG | BARFLAG, which gives me 00101000 - both flags are on. So that's what's really goin' on in that assignment code. Hope this makes sense.

Strike
04-30-2001, 07:04 PM
Thanks Stuka, I didn't want to give a long description (I'm just lazy), but yours did a good job.

greadey
05-01-2001, 02:38 PM
Well what can I say Stuka, it all falls into place as the penny drops.

Many thanks for your time and help.

greadey :) :)

Stuka
05-01-2001, 04:16 PM
Glad to help...not often I do that much good! :)