UART application programming under Linux

Source: Internet
Author: User
Tags lowercase sigint signal

Objective: to control UART serial port transmitting and receiving data in user space by reading and writing UART device files.

Setting the UART baud rate, parity enable, and so on in user space is done through the Termios structure and the Termios library function , which requires the termios.h header file to be included in the application.

I. Definition of Termios structural body

#define NCCS   //control the length of the character array. struct termios{unsigned long c_iflag;  Input mode flag unsigned long c_oflag;  Output mode flag unsigned long c_cflag;  Control mode flag unsigned long c_lflag;  Local mode flag unsigned char c_line;   Line procedure (rate) unsigned char C_cc[nccs];  control character Array};


The c_iflag tag parameters are:

#define IGNBRK 0000001  //input ignores break condition # define Brkint 0000002  //If no ignbrk is set, the SIGINT signal # define is generated when break Ignpar 0000004  //Ignore parity and Frame error # define PARMRK 0000010//  mark parity error when INPCK is set and Ignpar is not set with # define INPCK 0000020   // Enable frame and parity Error check # define Istrip 0000040  //Masked characters 8th bit # define INLCR 0000100   //input line break NL mapped to carriage return cr#define igncr 0000200   //Ignore carriage return cr#define icrnl 0000400   //The carriage return CR is mapped to a newline character at input nl#define IUCLC 0001000   //Convert uppercase characters to lowercase characters at input # define Ixon 0002000    //Allow Start/stop (Xon/xoff) Output control # define Ixany   0004000//allow any character restart output # define Ixoff 0010000   //Allow Start/ Stop (Xon/xoff) input control # define Imaxbel 0020000  //input Queue full-time ringing

The c_oflag tag parameters are:

#define OPOST 0000001//Enable output processing. Only this tag is set, C_oflag other settings will be valid # OLCUC 0000002//lowercase characters are converted to uppercase in the output # define ONLCR 0000004//When output, the newline character NL is mapped to carriage return-line feed cr-nl# Define OCRNL 0000010//The carriage return CR is mapped to a newline character at output nl#define ONOCR 0000020//In 0 column does not output carriage return cr#define onlret 0000040//newline character NL execution return function Can # define Ofill 0000100//delay using the fill character instead of the time delay # define Ofdel 0000200//Fill character is the ASCII code DEL. If not set, use ASCII null#define nldly 0000400//Select newline Delay # define NL0 0000000//Line break delay type 0#define NL1 0000400//Line break delay type 1#d Efine crdly 0003000//Select Enter Delay # define CR0 0000000//Enter delay type 0#define CR1 0001000//Enter delay type 1#define CR2 0002000//Enter Delay type 2#define CR3 0003000//Enter delay type 3#define tabdly 0014000//Select horizontal tab Delay # define TAB0 0000000//Horizontal tab delay type 0#define TAB1 0 004000//Horizontal tab delay type 1#define TAB2 0010000//Horizontal tab delay type 2#define TAB3 0014000//Horizontal tab delay type 3#define xtabs 0014000//Will tab tab to spaces, which represents the number of spaces # bsdly 0020000//Select BACKSPACE delay # define BS0 0000000//BACKSPACE delay type 0#define BS1 0020000//BACKSPACE delay type 1#d Efine vtdly 0040000//Vertical tab Delay # define VT0 0000000//Longitudinal tab delay type 0#define VT1 0040000//Vertical tab delay type 1#define ffdly 0040000//select Page Break # # # FF0 00 00000//page change delay type 0#define FF1 0040000//page break delay Type 1

The c_cflag tag parameters are:

#define CBAUD 0000017//Transmit rate bit mask # B0 0000000//Hang up line #define B50 0000001//baud rate 50#define B75 0000002 Baud rate 75#define B110 0000003//baud rate 110#define B134 0000004//baud rate 134#define B150 0000005//baud rate 150#define B 200 0000006//baud rate 200#define B300 0000007//baud rate 300#define B600 0000010//baud rate 600#define B1200 0000011//Baud Rate 1200#define B1800 0000012//baud rate 1800#define B2400 0000013/baud rate 2400#define B4800 0000014//baud rate 4800#define B96  00 0000015//Baud rate 9600#define B19200 0000016//baud rate 19200#define B38400 0000017//baud rate 38400#define exta B19200// Extended baud rate A#define EXTB B38400//Extended baud rate b#define CSIZE 0000060//character bit width Shield code # define CS5 0000000//5 bit per character # define CS6 0000 020//character 6 bit # # CS7 0000040/per character 7 bit # # CS8 0000060//character 8 bit # # CSTOPB 0000100//Set two stop bit #def INE Cread 0000200//character receive enable. If there is no setting, the characters are still received from the port, but these characters are discarded # # # Cparenb 0000400//Turn on output when parity bit is generated, parity # cparodd 0001000//input/input check is odd check#define HUPCL 0002000//Last process off after hanging up # clocal 0004000//Ignore modem control line # define Cibaud 03600000/input baud rate (not used) # Define crtscts 020000000000//Flow control # define PARENB CPARENB//Turn on output to generate parity bit, parity on input # define parodd cparodd//input/input check is odd check

The c_lflag tag parameters are:

#define ISIG 0000001    //When a character intr, QUIT, SUSP, or Dsusp are received, generate the corresponding signal # define Icanon 0000002  //Open spec mode (cooked mode) #define Xcase 0000004   //If Icanon is set, the terminal is a # define ECHO 0000010    //Echo input character for uppercase characters # # Echoe 0000020   //If Icanon is set, then erase/ Werase will erase the previous character/Word # define Echok 0000040   //If Icanon is set, the kill character will erase the current line # define ECHONL 0000100  //If Icanon is set, If ECHO is not turned on also echoes the NL character # # Noflsh 0000200  //When generating SIGINT and sigquit signals without flushing the input output queue, refresh the input queue # define SIGSUSP when generating the tostop signal 0000400  //Send Sigttou signal to the process group of the background process, the background process tries to write its own control terminal # define ECHOCTL 0001000  //If Echo is set, the tab, NL, START, and stop Other than the ASCII control signal will be echoed into the ^x style, the X value is the control +0x40#define echoprt 0002000  //If Icanon and Iecho are set, then the character will display a # define Echoke 0004000 when erased   //If Icanon is set, kill all characters on the erase line are echoed by the # define Flusho 0010000   //output is refreshed. By typing the discard character, the flag is flipped # # Pendin 0040000   //The next character is read, all characters in the input queue will be re-marked # Iexten 0100000   // Turn on input processing defined when implementing

The c_line parameters are:
#define TIOCM_LE 0x001//   lines allow (line enable) #define TIOCM_DTR 0x002  //terminal Ready (Data Terminal readiness) #define TIOCM_ RTS 0x004  //Request send (requests to send) #define TIOCM_ST 0x008   //serial data Send (Serial Transfer) #define TIOCM_SR 0x010   // Serial Data Reception (Serial receive) #define TIOCM_CTS 0x020  //Clear Send (clear to send) #define TIOCM_CAR 0x040  //Carrier monitoring (Carrier Detect) #define TIOCM_RNG 0x080  //Ring indicator (ring indicate) #define TIOCM_DSR 0x100  //Data Set ready #define TIOCM_CD Tiocm_car#define Tiocm_ri tiocm_rng

C_cc[nccs] Array:

To-do

Second, Termios library function

1, get the current operation mode parameters

int tcgetattr (int fd, struct Termios *termios_p)

2 . Use *termios_p to set operating mode parameters

int tcsetattr (int fd, int optional_actions, struct Termios *termios_p)

Parameters of the Optional_actions:

#define TCSANOW 0    //change immediate occurrence # define Tcsadrain 1  //change occurs after all written output is transmitted # define Tcsaflush 2  // Changes occur after all the written output is transmitted and after all data that has been received but not read is discarded

3 . Get the sending baud rate in *termios_p

speed_t cfgetospeed (struct Termios *termios_p)

4 . Receive baud rate in *termios_p

speed_t cfgetispeed (struct Termios *termios_p)

5 . Set the transmit baud rate in *termios_p

int cfsetospeed (struct Termios *termios_p, speed_t speed)

6 . Set the receive baud rate in *termios_p

int cfsetispeed (struct Termios *termios_p, speed_t speed)

7. wait for all output data to be sent

int tcdrain (int fd)

8. empty input/output buffers

int Tcflush (int fd, int queue_selector)

Parameters of the Queue_selector:

#define TCIFLUSH 0  //empties the input buffer (the driver has been received but the user program has not yet been read) #define TCOFLUSH 1  //empties the output buffer (the user program has been written but the driver has not yet been sent) #define Tcioflush 2  //emptying input and output buffers

9, control the input and output stream

int tcflow (int fd, int action)

Parameters for action:

#define TCOOFF 0  //suspend output. #define Tcoon 1   //Restart the output that was suspended. #define TCIOFF 2  //system transmits a stop character, which causes the device to stop transmitting data to the system. #define TCION 3   //system transmits a start character that enables the device to begin transmitting data to the system.

10. Send Break

int tcsendbreak (int fd, int duration)
Sends a continuous binary number 0 within a specified time interval. If the duration parameter is 0, this type of send lasts 0,25~0.5 seconds. Posix.1 description If duration is not 0, then the send time depends on the implementation.

Iii. Examples of programming

#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <termios.h> #include    <stdio.h> #define Uart_device "/DEV/TTYPS0"//uart device file name int main (int argc, char *argv[]) {int FD, res;    struct Termios oldtio, newtio;    Char ch; Char buf[256] = {0};//-----------Open the UART device file------------------fd = open (Uart_device, o_rdwr|        O_noctty)///Not set O_nonblock, so here read and write are blocking operations if (FD < 0) {perror (uart_device);    Exit (1);    } else printf ("Open%s successfully\n", Uart_device); -----------Set operation parameters-----------------------Tcgetattr (fd, &oldtio);//get current operating mode parameter memset (&newtio, 0, sizeof (NE Wtio));//Baud rate = 115200 data bit =8 enable data receive Newtio.c_cflag = b115200| cs8| clocal|    Cread;     Newtio.c_iflag = Ignpar; Newtio.c_oflag = Opost | OLCUC;    /* Set to Normal mode *///newtio.c_lflag = Icanon; Tcflush (FD, Tciflush);//empties the input buffer and output buffer tcsetattr (FD, Tcsanow, &newtio);//Set new operation parameters//------------ Send data to Urat-------------------res=write (fd, "\r\nbegin Uart tx", 16); while (1) {//Get the data from the console terminal and send it through the UART until it is received! Character while ((Ch=getchar ())! = '!            ') {buf[0]=ch;        Res=write (FD, buf, 1);        } buf[0]=ch;        Buf[1]= ' \ n ';        res = write (FD, buf, 2);    Break  }//-------------receive data from the UART-------------------while (1) {res = read (FD, buf, 255);//The program will hang here until the data is received from the UART (blocking operation) if    (res = = 0) continue;  Buf[res] = ' + '; printf ("res =%d, buf =%s\n", res, BUF);//Print out the UART received characters if (buf[0] = = '! ') UART received!  Character and then exit while break;    }//------------Close the UART device file and restore the original parameter--------close (FD);    printf ("Close%s\n", uart_device); Tcsetattr (FD, Tcsanow, &oldtio); Restore the original settings return 0;}






Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

UART application programming under Linux

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.