Find the answer to your Linux question:
Results 1 to 2 of 2
Hello again! I'm using the serial port of a device to communicate with a hardware. (that can assume some different configurations of baud rate, data bits, etc.) Well, I can ...
  1. #1
    Just Joined! striker07's Avatar
    Join Date
    Jul 2010
    Location
    Santa Rita do Sapucaí, Brazil
    Posts
    47

    Applying configuration to serial port - struct termios

    Hello again!

    I'm using the serial port of a device to communicate with a hardware. (that can assume some different configurations of baud rate, data bits, etc.) Well, I can obtain that configuration, but I'm not certain in how to apply them to the serial. I'm using the struct termios to do that. I did some search, and found how to configure the baud rate and data bits. I'm doing this:

    Code:
    struct termios config;
    int fd;
    
    id = open(port, O_RDWR | O_NOCTTY | O_NDELAY);
    
    // After open the fd, I take the actual config (using ioctl()). Then, I set the new config
    
    config.c_oflag = 0;
    config.c_iflag = 0;
    config.c_lflag = 0;
    
    // If baud rate is 9600bps
    config.c_cflag = B9600;
    
    // And 6 data bits
    config.c_cflag |= CS6;
    
    ...
    Is the code right? And how I set the stop bits (1, 1.5 or 2 bits), the parity (even, odd, none, mark or space) and the flow control (hardware, software, none or xon/xoff)?

  2. #2
    Linux Guru Rubberman's Avatar
    Join Date
    Apr 2009
    Location
    I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
    Posts
    8,974
    Usually what one does is use the tcgetattr() function to fill in the termios structure with the device's current settings, then you set the members of the structure to the new settings you want (like a different baud rate, stop bits, etc) and call tcsetattr() with the modified termios structure. Read the termios manpage for more information about all of this: man termios

    Take special note of this paragraph regarding getting/setting baud rates - caveat programmer!
    Code:
                  (POSIX says that the baud speed is stored in the termios structure without  specify-
                  ing where precisely, and provides cfgetispeed() and cfsetispeed() for getting at it.
                  Some systems use bits selected by CBAUD  in  c_cflag,  other  systems  use  separate
                  fields, e.g.  sg_ispeed and sg_ospeed.)
    Sometimes, real fast is almost as good as real time.
    Just remember, Semper Gumbi - always be flexible!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...