资源描述:
《Linux下串口程序实例.pdf》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、#include/*标准输入输出定义*/#include/*标准函数库定义*/#include/*Unix标准函数定义*/#include/**/#include/**/#include/*文件控制定义*/#include/*PPSIX终端控制定义*/#include/*错误号定义*//***@brief设置串口通信速率*@paramfd类型int打开串口的文件句柄*@paramspeed类型int串口速度*@returnvoid
2、*/intspeed_arr[]={B38400,B19200,B9600,B4800,B2400,B1200,B300,B38400,B19200,B9600,B4800,B2400,B1200,B300,};intname_arr[]={38400,19200,9600,4800,2400,1200,300,38400,19200,9600,4800,2400,1200,300,};voidset_speed(intfd,intspeed){inti;intstatus;structtermiosOpt;tcgetattr(fd,&Opt);for(i=0;i3、rr)/sizeof(int);i++){if(speed==name_arr[i]){tcflush(fd,TCIOFLUSH);cfsetispeed(&Opt,speed_arr[i]);cfsetospeed(&Opt,speed_arr[i]);status=tcsetattr(fd,TCSANOW,&Opt);if(status!=0)perror("tcsetattrfd1");return;}tcflush(fd,TCIOFLUSH);}}/***@brief设置串口数据位,停止位和效验位*@paramfd类型int打开的串口文件句柄**@paramdatabits类型int数
4、据位取值为7或者8**@paramstopbits类型int停止位取值为1或者2**@paramparity类型int效验类型取值为N,E,O,,S*/intset_Parity(intfd,intdatabits,intstopbits,intparity){structtermiosoptions;if(tcgetattr(fd,&options)!=0){perror("SetupSerial1");return(FALSE);}options.c_cflag&=~CSIZE;switch(databits)/*设置数据位数*/{case7:options.c_cflag
5、=CS7;br
6、eak;case8:options.c_cflag
7、=CS8;break;default:fprintf(stderr,"Unsupporteddatasize");return(FALSE);}switch(parity){case'n':case'N':options.c_cflag&=~PARENB;/*Clearparityenable*/options.c_iflag&=~INPCK;/*Enableparitychecking*/break;case'o':case'O':options.c_cflag
8、=(PARODD
9、PARENB);/*设置为奇效验*/options.c_
10、iflag
11、=INPCK;/*Disnableparitychecking*/break;case'e':case'E':options.c_cflag
12、=PARENB;/*Enableparity*/options.c_cflag&=~PARODD;/*转换为偶效验*/options.c_iflag
13、=INPCK;/*Disnableparitychecking*/break;case'S':case's':/*asnoparity*/options.c_cflag&=~PARENB;options.c_cflag&=~CSTOPB;break;default:fprintf(stderr,
14、"Unsupportedparity");return(FALSE);}/*设置停止位*/switch(stopbits){case1:options.c_cflag&=~CSTOPB;break;case2:options.c_cflag
15、=CSTOPB;break;default:fprintf(stderr,"Unsupportedstopbits");return(FALSE);}