Linux serial port setup and programming

Source: Internet
Author: User
Tags bitmask control characters flushes function prototype vmin

The basic way of the user's common data communication can be divided into parallel communication and serial communication.

Parallel communication refers to the use of multiple data transmission lines to transmit a single data. Characterized by fast transmission speed, suitable for short-distance communication, but requires high transmission speed of applications.

Serial communication refers to the sequential transmission of a single bit of data using a transmission line. The characteristic is the simple communication line, can realize the communication through the simple cable, reduces the cost, is suitable for the long-distance communication, but the transmission speed is slow application occasions. The common serial port has the Rs-232-c interface (the full name is "The Data Terminal equipment (DTE) and the Data Communication device (DCE) between the serial Binary Data Interchange Interface Technical standard").

UART Controller: Can operate in interrupt (interrupt) mode or DMA (direct memory access) mode. With a 16-byte FIFO (first-in, first-out register), the maximum baud rate can be up to 230.4Kbps.

UART Operation: Data transmission, data reception, interrupt generation, baud rate, loopback mode, IR mode and automatic flow control mode.

The serial port settings include: Baud rate, number of start bits, number of data bits, number of stop bits, and flow control protocol. Here you can configure a baud rate of 115200, a starting bit of 1b, data bit 8b, stop bit 1b, and no flow control protocol.

Serial port One, serial port two corresponding device name is "/dev/ttys0", "/dev/ttys1" in turn.

In Linux to read and write the serial port can use a simple "read", "write" function to complete, the difference is that the other parameters of the serial port should be set up separately.

6.4.2 Serial port Settings details

The main port setting is to set the struct Termios struct member value:

#include <termios.h>

Struct Termio

{

unsigned short c_iflag; /* Input Mode flag */

unsigned short c_oflag; /* Output Mode flag */

unsigned short c_cflag; /* Control Mode flag */

unsigned short c_lfag; /* Local mode flag */

unsigned short c_line; /*line discipline*/

unsigned short C_CC[NCC]; /*control characters*/

};

By assigning values to the C_cflag, you can set the baud rate, character size, data bits, stop bit, parity bit, and hardware flow control.

Set serial port Properties Basic flow:

1. Save the original serial port configuration

For the sake of safety and later debugging program convenient, can first save the original serial port configuration, using function Tcgetattr (fd,&oldtio). This function gets the parameters associated with the object that the FD points to, and saves them in the TERMIOS structure referenced by the lodtio. This function can test whether the configuration is correct, whether the serial port is available, and so on. The debug succeeds, the function returns 0, fails, and the function returns-1.

if (tcgetattr (fd,&oldtio)!=0)

{

Perror ("Setupserial 1");

return-1;

}

2. Activation options are clocal and Cread

The clocal and Cread are used for local connection and accept enable respectively, and are activated by a bitmask of these two options.

Newtio.c_cflag |= clocal | Cread;

3. Setting the baud rate

The functions for setting the baud rate are mainly cfsetispeed and cfsetospeed.

Cfsetispeed (&newtio,b115200);

Cfsetospeed (&newtio,b115200);

In general, the user needs to set the baud rate of the input and output functions to be the same. These functions return 0 on success and fail-1.

4. Set the character size

There are no ready-made functions, and a bitmask is required. The bit masks in the data bits are generally removed and then set again as required.

Options.c_cflag &= ~csize; /*mask the character size bits*/

Options.c_cflag |= CS8;

5. Set parity bit

Activates the check bit in the C_cflag to enable the flag Parenb and whether to make even parity, and also activates the parity enable in C_iflag. If the Enable parity check, the code is as follows:

Newtio.c_cflag |= Parenb;

Newtio.c_cflag |=parodd;

Newtio.c_iflag |= (INPCK | Istrip);

The Enable-parity code is:

Newtio.c_iflag |= (INPCK | Istrip);

Newtio.c_cflag |= Parenb;

Newtio.c_cflag &= ~parood;

6. Setting the STOP bit

Implemented by activating the CSTOPB in C_cflag. If the stop bit is 1, the CSTOPB is cleared, and if the stop bit is 0, the CSTOPB is activated. Here is the code that stops bit 1 o'clock:

Newtio.c_cflag &= ~CSTOPB;

7. Set minimum characters and wait time

You can set it to 0 if there is no special requirement for the receive character and wait time:

Newtio.c_cc[vtime] = 0;

newtio.c_cc[vmin]=0;

8. Processing the Reference object to be written

After the serial port is reset, the reference object to be written before is re-processed, calling function Tcflush (fd,queue_selector) to process the object to which the reference is to be written. For data that is transferred, or received but not read, the processing method depends on the value of Queue_selector.

Queue_selector Possible values:

Tciflush: Refreshes the received data but does not read

Tcoflush: Flushes the written data but does not transmit

Tciolflush: Flushes the received data at the same time but does not read, and flushes the written data but does not transmit

This example takes one:

Tcflush (FD, Tciflush)

9. Activating the configuration

Use the function tcsetattr:

Function prototype: tcsetattr (Fd,option,&newtio);

The newtio here is a variable of type Termios, and the option may be as follows:

Tcsanow: Changed configuration takes effect immediately

Tcsadrain: Changed configuration takes effect after all outputs written to FD are ended

Tcsaflush: Changed configuration self-love all output that is written to the FD reference object takes effect after it is ended, and all inputs that have been accepted but read are discarded before the change occurs.

The function call successfully returned 0, failed-1.

if ((Tcsetattr (fd,tcsanow,&newtio))!=0)

{

Perror ("com set error");

return-1;

}

/* The full function of the serial port configuration, for the versatility of the function, usually the commonly used options are listed in the function, can be greatly convenient for later user debugging use */int set_opt (int fd,int nspeed,int Nbits,char nevent,int nstop) { struct Termios newtio,oldtio;         /* Save test existing serial port parameter settings, where there is error message if string number, etc. */if (tcgetattr (fd,&oldtio)!=0) {perror ("Setupserial 1"); return-1; } bzero (&newtio,sizeof (newtio)); /* Step one, set the character size */Newtio.c_cflag |= clocal | Cread; Newtio.c_cflag &= ~csize; /* Set stop bit */switch (nBits) {case 7:     newtio.c_cflag |=cs7;     break; case 8:      Newtio.c_cflag |=cs8;     break; }/* Set parity bit */switch (nevent) {case ' O '://Odd    newtio.c_cflag |= parenb;    Newtio.c_cflag |=parodd;    newtio.c_iflag |= (INPCK | Istrip);    break, Case ' E ':/Even    newtio.c_iflag |= (INPCK | Istrip);    Newtio.c_cflag |= Parenb;    Newtio.c_cflag &= ~parodd; Case ' N '://No parity bit    newtio.c_cflag &= ~parenb;    break; }/* Set baud rate */switch (nspeed) {case 2400:    cfsetispeed (&newtio,b2400);    cfsetospeed (& NEWTIO,B2400);    break; Case 4800:    cfsetispeed (&newtio,b4800);    cfsetospeed (&newtio,b4800);    break; Case 9600:    cfsetispeed (&newtio,b9600);    cfsetospeed (&newtio,b9600);    break; Case 115200:    cfsetispeed (&newtio,b115200);    cfsetospeed (&newtio,b115200);    break; Case 460800:    cfsetispeed (&newtio,b460800);    cfsetospeed (&newtio,b460800);    break; Default:    cfsetispeed (&newtio,b9600);    cfsetospeed (&newtio,b9600);    break; }/* Set stop bit */if (nstop==1)    newtio.c_cflag &= ~CSTOPB; else if (nstop==2)    newtio.c_cflag |= CSTOPB; /* Set wait time and minimum receive character */newtio.c_cc[vtime] = 0; newtio.c_cc[vmin]=0; /* Handle the unacceptable character */Tcflush (FD, Tciflush);/* Activate new configuration */if ((Tcsetattr (fd,tcsanow,&newtio))!=0)

{perror ("com set error"); return-1; } printf ("Set done!\n"); return 0; }

Reprinted from: http://www.linuxidc.com/Linux/2011-02/32253.htm

Linux serial Port Setup and programming (RPM)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.