Serial Port Programming Part 1 - Setting Baud Rate

What is Baud Rate?

Baud rate is the number of signal units transmitted per unit time, this is different from Bit rate, which is the number of bits transmitted per unit time.

Difference between bit rate and baud rate is that one signal unit can carry one or more than one bit of information.

Bit rate = Baud rate * number of bits per baud.

Baud rate can be any value, but the only requirement is both the devices should be configured with the same baud rate for communication to happen. Common baud rates are 1200, 2400, 4800, 9600, 19200, 38400, 57600 and 115200

We will be using PL2303 (USB to Serial Converter) for this Serial Port Series.
When you connect PL2303 on Linux OS, ttyUSB* device will be created. In our case, /dev/ttyUSB0 is created




struct termios structure declared in <termios.h> holds all the settings for a specific port on the tty device. The input and output baud rates are stored in the termios structure.


  • input flags control the input of characters by the terminal device(eg. strip eight bit on input, enable input parity checking)
  • output flags control the driver output (eg. perform output processing, map newline to CR/LF)
  • control flags affect RS-232 serial lines (eg. ignore modem status lines, one or two stop bits per character)
  • local flags affect the interface between the driver and the user (eg. echo on or off, visually erase characters)
  • c_cc array contains all the special characters that we can change.
tcgetattr and tcsetattr functions of the C Library will get/set the struct termios of a particular port.
int tcgetattr(int fd, struct termios *termptr);
int tcsetattr(int fd, int opt, const struct termios *termptr);
The opt argument of tcsetattr let us specifies when the new terminal attributes takes effect. The opt can be any of the  below three values:
  • TCSANOW: Change occurs immediately
  • TCSADRAIN: Change occurs after all output has been transmitted. This option should be used if we are changing the output parameters.
  • TCSAFLUSH: Change occurs after all output has been transmitted. When the change takes place, all input data that has not been read is discarded (flushed)

cfgetospeed/cfgetispeed functions returns the input and output baud rate stored in the termios structure

cfsetospeed/cfsetispeed functions sets the input and output baud rate stored in the termios structure

The values passed to this functions are constant present in termios.h




Code:




Output:





Comments

  1. Nice blog! If you want to connect a serial device to your PC but it doesn’t have a serial port then all you need is a USB to Serial adapter.

    ReplyDelete

Post a Comment

Popular posts from this blog

bb.utils.contains yocto

Difference between RDEPENDS and DEPENDS in Yocto

PR, PN and PV Variable in Yocto