基于Linux平台下串口数据接收

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

#includestdio.h#includestdlib.h#includeunistd.h#includesys/types.h#includesys/stat.h#includefcntl.h#includetermios.h#includeerrno.h#includestring.hintUART_Open(intfd,char*port){fd=open(port,O_RDWR|O_NOCTTY|O_NDELAY);if(fd==-1){perror(Can'tOpenSerialPort\n);return-1;}if(fcntl(fd,F_SETFL,0)0){perror(fcntlfailed!\n);return-1;}returnfd;}voidUART_Close(intfd){close(fd);}intUART_Set(intfd,intspeed,intflow_ctrl,intdatabits,intstopbits,charparity){inti;intstatus;intspeed_arr[]={B115200,B19200,B9600,B4800,B2400,B1200,B300};intname_arr[]={115200,19200,9600,4800,2400,1200,300};structtermiosopt;if(tcgetattr(fd,&opt)!=0){perror(GetSerialAttrError!\n);return-1;}for(i=0;isizeof(speed_arr)/sizeof(int);i++){if(speed==name_arr[i]){cfsetispeed(&opt,speed_arr[i]);cfsetospeed(&opt,speed_arr[i]);}}opt.c_iflag&=~(BRKINT|ICRNL|INPCK|ISTRIP|IXON);opt.c_cflag|=CLOCAL|CREAD;switch(flow_ctrl){case0:opt.c_cflag&=~CRTSCTS;break;case1:opt.c_cflag|=CRTSCTS;break;case2:opt.c_cflag|=IXON|IXOFF|IXANY;break;default:return-1;}opt.c_cflag&=~CSIZE;switch(databits){case5:opt.c_cflag|=CS5;break;case6:opt.c_cflag|=CS6;break;case7:opt.c_cflag|=CS7;break;case8:opt.c_cflag|=CS8;break;default:return-1;}switch(parity){case'n':case'N':opt.c_cflag&=~PARENB;opt.c_iflag&=~INPCK;break;case'o':case'O':opt.c_cflag|=(PARODD|PARENB);opt.c_iflag|=INPCK;break;case'e':case'E':opt.c_cflag|=PARENB;opt.c_cflag&=~PARODD;opt.c_iflag|=INPCK;break;case's':case'S':opt.c_cflag&=~PARENB;opt.c_cflag&=~CSTOPB;break;default:return-1;}switch(stopbits){case1:opt.c_cflag&=~CSTOPB;break;case2:opt.c_cflag|=CSTOPB;break;default:return-1;}opt.c_oflag&=~OPOST;opt.c_lflag&=~(ICANON|ECHO|ECHOE|ISIG);opt.c_cc[VTIME]=0;opt.c_cc[VMIN]=0;tcflush(fd,TCIFLUSH);if(tcsetattr(fd,TCSANOW,&opt)!=0){perror(SetSerialError!\n);return-1;}return0;}intUART_Recv(intfd,char*rcv_buf,intdata_len){intlen,fs_sel;fd_setfs_read;FD_ZERO(&fs_read);FD_SET(fd,&fs_read);len=read(fd,rcv_buf,data_len);if(len0){//printf(DataReceived,Length=%d\n,len);returnlen;}else{return0;}}intUART_Send(intfd,char*send_buf,intdata_len){intlen=0;len=write(fd,send_buf,data_len);if(len==data_len){returnlen;}else{tcflush(fd,TCOFLUSH);return-1;}}intmain(intargc,char**argv){intlen;intfd1;intfd2;floatTemp=0.0;floatHumi=0.0;charUart2_buf[50];charUart2_tep[50];charTempString[5]=Test;charHumiString[5]=Test;fd2=UART_Open(fd2,/dev/ttymxc2);UART_Set(fd2,115200,0,8,1,'N');printf(StartProcess...\n);while(1){len=UART_Recv(fd2,Uart2_buf,50);if(len0){Uart2_buf[len]='\0';strcpy(Uart2_tep,Uart2_buf);strncpy(TempString,&Uart2_tep[13],5);strncpy(HumiString,&Uart2_tep[29],5);TempString[4]='\0';HumiString[4]='\0';Temp=atof(TempString);Humi=atof(HumiString);printf(%f%f\n,Temp,Humi);}sleep(1);}UART_Close(fd2);}

1 / 6
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功