资源描述:
《LINUX环境,串口通讯案例源代码参考.doc》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、.LINUX环境,串口通讯案例源代码参考#include#include#include#include#include#include#include#include#include#include#include#include#include#d
2、efineFALSE-1#defineTRUE1intmy_write(intfd,void*buffer,intlength){intbytes_left;intwritten_bytes;..char*ptr;ptr=buffer;bytes_left=length;while(bytes_left>0){written_bytes=write(fd,ptr,bytes_left);if(written_bytes<0){if(errno==EINTR)written_bytes=0;elsereturn(-1);}b
3、ytes_left-=written_bytes;ptr+=written_bytes;}return(0);}//16位crc校验voidchecksum(unsignedchar*data,unsignedchar*check,intn){..longtemp=0;inti;for(i=0;i>8)&0xff);check[1]=(temp&0xff);}voidlchecksum(unsigned
4、charlenid,char*lenth){//16位crc校验*(lenth+3)=lenid&0x0f;*(lenth+2)=(lenid>>4)&0x0f;*(lenth+1)=(lenid>>8)&0x0f;*lenth=(~(((*(lenth+3))+(*(lenth+2))+(*(lenth+1)))%16)+1)&0x0f;}//定义内核bott常量对照表..intspeed_arr[]={B38400,B19200,B9600,B4800,B2400,B1200,B300,B38400,B19200,B9
5、600,B4800,B2400,B1200,B300,};intname_arr[]={38400,19200,9600,4800,2400,1200,300,38400,19200,9600,4800,2400,1200,300,};//定义bott率voidset_speed(intfd,intspeed){inti,status;structtermiosOpt;tcgetattr(fd,&Opt);for(i=0;i6、_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);}}//定义其他串口参数intset_Parity(intfd,intdatabits,intstopbits,intparity){st
7、ructtermiosoptions;if(tcgetattr(fd,&options)!=0){perror("SetupSerial1");return(FALSE);}options.c_cflag&=~CSIZE;switch(databits){case7:options.c_cflag
8、=CS7;break;..case8:options.c_cflag
9、=CS8;break;default:fprintf(stderr,"Unsupporteddatasize");return(FALSE);}switc
10、h(parity){case'n':case'N':options.c_cflag&=~PARENB;options.c_iflag&=~INPCK;break;case'o':case'O':options.c_cflag
11、=(PARODD
12、PARENB);options.c_iflag
13、=INPCK