Serial programming under Linux

Source: Internet
Author: User

Open the serial port

In a Linux system, opening the serial port is done by using the standard file Open function.

#include <fcntl.h>

/* Open in Read/write mode */

int fd = open ("/dev/ttyusb0", O_RDWR);

Set up the serial port

All operations on the serial port are implemented by struct Termios and several functions.

Tcgetattr//Get PropertiesTcsetattr//Setting PropertiesCfgetispeed//Get input SpeedCfsetispeed//set the input speedCfgetospeed//get the output speedCfsetospedd//setting the output speedTcdrain//wait for all outputs to be transmittedTcflow//suspend transmit or receiveTcflush//brushed pending inputs and outputsTcsendbreak//Send break characterTcgetpgrp//get foreground process group IDTcsetpgrp//set the foreground process group ID
Tcgetattr (0,&oldstdio); //Get default configuration options stored in the Oldstdio structure
Tcgetattr (Fd,&oldstdio); //Get current configuration options stored in the Oldstdio structure
Tcsetattr (Fd,tcsanow,&oldstdio); //tcsanow changes take effect immediately
Cfgetispeed (&oldstdio); //Get baud rate
Cfsetispeed (&oldstdio, B115200) //Set baud rate to 115200
You can use read or open to operate the serial port to send and receive.

Test code:
#include <stdio.h>#include<fcntl.h>#include<termios.h>#include<unistd.h>#include<string.h>intSerial_send (intFdChar*Data);intMain () {intFD; intnum; structTermios Oldstdio; FD= Open ("/dev/ttyusb0", O_RDWR); if( -1==FD) {printf ("cannot open/dev/ttyusb0\r\n"); return-1; } tcgetattr (FD,&Oldstdio); Cfsetispeed (&Oldstdio, B115200); Tcsetattr (FD, Tcsanow,&Oldstdio);    Tcflush (FD, Tciflush); Num= Serial_send (FD,"Serial baund is default \ r \ n" );    Close (FD); return 0;}intSerial_send (intFdChar*Data) {    intString_num; String_num=strlen (Data); returnWrite (Fd,data, string_num);}

Serial 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.