1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <unistd.h> 4 #include <sys/types.h> 5 #include <sys/stat.h> 6 #include <fcntl.h> //文件控制定义 7 #include <termios.h>//终端控制定义 8 #include <errno.h> 9 10 char *comport; 11 int bRate = 0; 12 13 int serial_fd = 0; 14 15 //打开串口并初始化设置 16 int init_serial(void) 17 { 18 serial_fd = open(comport, O_RDWR | O_NOCTTY | O_NDELAY); 19 if (serial_fd < 0) { 20 perror("open"); 21 return -1; 22 } 23 else 24 printf("open %s success! ", comport); 25 26 //串口主要设置结构体termios <termios.h> 27 struct termios options; 28 29 /**1. tcgetattr函数用于获取与终端相关的参数。 30 *参数fd为终端的文件描述符,返回的结果保存在termios结构体中 31 */ 32 tcgetattr(serial_fd, &options); 33 /**2. 修改所获得的参数*/ 34 options.c_cflag |= (CLOCAL | CREAD);//设置控制模式状态,本地连接,接收使能 35 options.c_cflag &= ~CSIZE;//字符长度,设置数据位之前一定要屏掉这个位 36 options.c_cflag &= ~CRTSCTS;//无硬件流控 37 options.c_cflag |= CS8;//8位数据长度 38 options.c_cflag &= ~CSTOPB;//1位停止位 39 options.c_iflag |= IGNPAR;//无奇偶检验位 40 options.c_oflag = 0; //输出模式 41 options.c_lflag = 0; //不激活终端模式 42 43 switch(bRate) 44 { 45 case 9600:cfsetospeed(&options, B9600);break;//设置波特率 46 case 115200:cfsetospeed(&options, B115200);break;//设置波特率 47 } 48 49 /**3. 设置新属性,TCSANOW:所有改变立即生效*/ 50 tcflush(serial_fd, TCIFLUSH);//溢出数据可以接收,但不读 51 tcsetattr(serial_fd, TCSANOW, &options); 52 53 return 0; 54 } 55 56 void uart_recv(int fd) 57 { 58 char data[1024]; 59 int len=0, ret = 0; 60 fd_set fs_read; 61 struct timeval tv_timeout; 62 63 FD_ZERO(&fs_read); 64 FD_SET(fd, &fs_read); 65 tv_timeout.tv_sec = 6000;//(10*20/115200+2); 66 tv_timeout.tv_usec = 0; 67 68 while (1) 69 { 70 ret = select(fd+1, &fs_read, NULL, NULL, &tv_timeout); 71 //printf("ret = %d ", ret); 72 if (FD_ISSET(fd, &fs_read)) { 73 len = read(fd, data, sizeof(data)); 74 printf("len: %d(bytes) recv: %s ", len, data); 75 } else { 76 perror("select"); 77 } 78 } 79 } 80 81 int main(int argc, char **argv) 82 { 83 comport = (char *)malloc(1024); 84 memset(comport, '