linux串口讀寫
發布時間: 2022-06-16 18:37:09
① linux怎麼讀取串口數據
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<termios.h>
#include<errno.h>
#defineFALSE-1
#defineTRUE0
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;i<sizeof(speed_arr)/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);
}
}
}
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|=CS7;
break;
case8:
options.c_cflag|=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|=(PARODD|PARENB);
options.c_iflag|=INPCK;/*Disnableparitychecking*/
break;
case'e':
case'E':
options.c_cflag|=PARENB;/*Enableparity*/
options.c_cflag&=~PARODD;
options.c_iflag|=INPCK;/*Disnableparitychecking*/
break;
case'S':
case's':/*asnoparity*/
options.c_cflag&=~PARENB;
options.c_cflag&=~CSTOPB;break;
default:
fprintf(stderr,"Unsupportedparity ");
return(FALSE);
}
switch(stopbits)
{
case1:
options.c_cflag&=~CSTOPB;
break;
case2:
options.c_cflag|=CSTOPB;
break;
default:
fprintf(stderr,"Unsupportedstopbits ");
return(FALSE);
}
/*Setinputparityoption*/
if(parity!='n')
options.c_iflag|=INPCK;
tcflush(fd,TCIFLUSH);
options.c_cc[VTIME]=150;
options.c_cc[VMIN]=0;/*UpdatetheoptionsanddoitNOW*/
if(tcsetattr(fd,TCSANOW,&options)!=0)
{
perror("SetupSerial3");
return(FALSE);
}
return(TRUE);
}
intmain()
{
printf("Thisprogramupdateslasttimeat%s%s ",__TIME__,__DATE__);
printf("STDIOCOM1 ");
intfd;
fd=open("/dev/ttyS0",O_RDWR);
if(fd==-1)
{
perror("serialporterror ");
}
else
{
printf("open");
printf("%s",ttyname(fd));
printf("succesfully ");
}
set_speed(fd,115200);
if(set_Parity(fd,8,1,'N')==FALSE){
printf("SetParityError ");
exit(0);
}
charbuf[]="fe55aa07bc010203040506073d";
write(fd,&buf,26);
charbuff[512];
intnread;
while(1)
{
if((nread=read(fd,buff,512))>0)
{
printf(" Len:%d ",nread);
buff[nread+1]='