资源描述:
《Linux下串口C语言编程》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、串口操作代码#include#include#include#include#include#include#include#include#include#defineBUFFER_SIZE1024#defineHOST_PORT1intset_port(intfd,intbaud_rate,intdata_bits,charparity,
2、intstop_bits){structtermiosnewtio,oldtio;if(tcgetattr(fd,&oldtio)!=0){perror("SetupSerial1");return-1;}bzero(&newtio,sizeof(newtio));newtio.c_cflag
3、=CLOCAL
4、CREAD;newtio.c_cflag&=~CSIZE;/*setbaud_speed*/switch(baud_rate){case2400:cfsetispeed(&newtio,B2400);cfsetospee
5、d(&newtio,B2400);break;case4800:cfsetispeed(&newtio,B4800);cfsetospeed(&newtio,B4800);break;case9600:cfsetispeed(&newtio,B9600);cfsetospeed(&newtio,B9600);break;case19200:cfsetispeed(&newtio,B19200);cfsetospeed(&newtio,B19200);break;case38400:cfsetispeed(&newtio,B38
6、400);cfsetospeed(&newtio,B38400);break;default:case115200:cfsetispeed(&newtio,B115200);cfsetospeed(&newtio,B115200);break;}/*setdata_bitsupon7or8*/switch(data_bits){case7:newtio.c_cflag
7、=CS7;break;default:case8:newtio.c_cflag
8、=CS8;break;}/**/switch(parity){default:c
9、ase'N':case'n':{newtio.c_cflag&=~PARENB;newtio.c_iflag&=~INPCK;}break;case'o':case'O':{newtio.c_cflag
10、=(PARODD
11、PARENB);newtio.c_iflag
12、=INPCK;}break;case'e':case'E':{newtio.c_cflag
13、=PARENB;newtio.c_cflag&=~PARODD;newtio.c_iflag
14、=INPCK;}break;case's':case'S':{newtio.c
15、_cflag&=~PARENB;newtio.c_cflag&=~CSTOPB;}break;}/*setstop_bits1or2*/switch(stop_bits){default:case1:{newtio.c_cflag&=~CSTOPB;}break;case2:{newtio.c_cflag
16、=CSTOPB;}break;}newtio.c_cc[VTIME]=0;newtio.c_cc[VMIN]=1;tcflush(fd,TCIFLUSH);if((tcsetattr(fd,TCSANOW,&newtio))
17、!=0){perror("comseterror");return-1;}printf("setUARTdone!");return0;}intopen_port(intcom_port){intfd=0;char*dev[]={"/dev/ttyS0","/dev/ttyS1","/dev/ttyS2","/dev/ttyS3","/dev/ttyS4","/dev/ttyS5","/dev/ttyS6"};if((com_port<0)
18、
19、(com_port>6)){printf("theportisoutrange"
20、);return-1;}fd=open(dev[com_port],O_RDWR
21、O_NOCTTY
22、O_NDELAY);if(fd<0){perror("openserialport");return-1;}if(fcntl(fd,F_SETFL,0)<0){perror("