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