串口通信实现
前段时间编写了串口通信的代码用的是RS-232数据线,但是不知道为什么读取不到从口传来的GPS数据,是在Ubuntu下面编译的,大家看看!
#include <stdio.h> /*标准输入输出定义*/#include <stdlib.h> /*标准函数库定义*/#include <unistd.h> /*Unix 标准函数定义*/#include <sys/types.h>#include <sys/stat.h>#include <errno.h>#include <string.h>#include <fcntl.h>#include <termios.h>#define dev "/dev/ttyS1"#define MAX_SIZE 2048int set_com_config(int fd,int baud_rate,int data_bits,char parity,int stop_bits){struct termios new_cfg,old_cfg;int speed;//保存并测试现有串口参数设置,在这里如果串口号出错,会有相关的出错信息if(tcgetattr(fd,&old_cfg)!=0){perror("tcgetattr");return -1;}//设置字符大小new_cfg = old_cfg;cfmakeraw(&new_cfg);//配置为原始模式new_cfg.c_cflag&=~CSIZE;//设置波特率switch(baud_rate){case 2400:{speed = B2400;break;}case 4800:{speed = B4800;break;}case 9600:{speed = B9600;break;}case 19200:{speed = B19200;break;}case 38400:{speed = B38400;break;}case 115200:{speed = B115200;break; }default: break;}cfsetispeed(&new_cfg,speed);cfsetospeed(&new_cfg,speed);//设置停止位switch(data_bits){case 7:{new_cfg.c_cflag|=CS7;break;}default:case 8:{new_cfg.c_cflag|=CS8;break;}}//设置奇偶校验位switch(parity){case 'o':case 'O':{new_cfg.c_cflag|=(PARODD|PARENB);new_cfg.c_iflag|=(INPCK);break;}case 'e':case 'E':{new_cfg.c_cflag |=PARENB;new_cfg.c_cflag &=~PARODD;new_cfg.c_iflag |=INPCK;break;}case 's':case 'S':{new_cfg.c_cflag &=~PARENB;new_cfg.c_cflag &=~CSTOPB;break;}default:case 'n':case 'N':{new_cfg.c_cflag &=~PARENB;new_cfg.c_iflag &=~INPCK;break;}}//设置停止位switch(stop_bits){case 2:{new_cfg.c_cflag |=CSTOPB;break;}default:case 1:{new_cfg.c_cflag &=~CSTOPB;break;}}//设置等待时间和最小接收字符new_cfg.c_cc[VTIME] =0;new_cfg.c_cc[VMIN] =1;//处理未接收字符tcflush(fd,TCIFLUSH);//激活新配置if((tcsetattr(fd,TCSANOW,&new_cfg))!=0){perror("tcsetattr");return -1;}return 0;}//打开串口函数int open_port(int com_port){int fd;#if (COM_TYPE == GNR_COM)//使用普通串口 char*dev[] = {"/dev/ttyS0","/dev/ttyS1","/dev/ttyS2"};#else//使用USB转串口 char*dev[] = {"/dev/ttyUSB0","/dev/ttyUSB1","/dev/ttyUSB2"};#endifif((com_port<0)||(com_port > MAX_COM_NUM)){return -1;}//打开串口if((fd=open(dev[com_port-1],O_RDWR|O_NOCTTY|O_NDELAY))<0){perror("open serial port");return -1;}//恢复串口为堵塞状态if(fcntl(fd,F_SETFL,0) <0 ){perror("fcntl F_SETFL\n");return -1;}//测试是否为终端设备if(isatty(STDIN_FILENO)==0){perror("standard input is not a terminal device");}return fd;}int main(int argc,char*argv[]){ int fd=0; int real_read=0; char buffer[MAX_SIZE]; memset(buffer,0,sizeof(buffer)); int HOST_COM_PORT=2; if((fd=open_port(HOST_COM_PORT))<0) { perror("open fail!"); exit(1); } printf("open sucess!\n"); if((set_com_config(fd,9600,8,'N',1))<0) {perror("set_com_config fail!\n");exit(1); } printf("set sucess!\n"); real_read=read(fd,buffer,sizeof(buffer)); if(real_read<0) { perror("read fail!\n"); exit(1); } printf("start read...\n"); printf("....%s..\n",buffer); close(fd); return 0;}