21,597
社区成员
发帖
与我相关
我的任务
分享
void Uart_Set_Speed(int fd, int speed)
{
int i;
int status;
struct termios Opt;
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("tcsetattr fd1");
return;
}
tcflush(fd,TCIOFLUSH);
}
}
int Uart_Set_Parity(int fd,int databits,int stopbits,char parity)
{
struct termios options;
if ( tcgetattr( fd,&options) != 0)
{
perror("SetupSerial 1");
return(false);
}
options.c_cflag &= ~CSIZE;
switch (databits)
{
case 7:
options.c_cflag |= CS7;
break;
case 8:
options.c_cflag |= CS8;
break;
default:
fprintf(stderr,"Unsupported data size\n");
return (false);
}
switch (parity)
{
/*ÎTD£Ñé*/
case 'n':
case 'N':
options.c_cflag &= ~PARENB; /* Clear parity enable */
options.c_iflag &= ~INPCK; /* Enable parity checking */
break;
/*ÆæD£Ñé*/
case 'o':
case 'O':
options.c_cflag |= (PARODD | PARENB);
options.c_iflag |= INPCK; /* Disable parity checking */
break;
/*żD£Ñé*/
case 'e':
case 'E':
options.c_cflag |= PARENB; /* Enable parity */
options.c_cflag &= ~PARODD;
options.c_iflag |= INPCK; /* Disable parity checking */
break;
case 'S':
case 's': /*as no parity*/
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
break;
default:
fprintf(stderr,"Unsupported parity\n");
return (false);
}
switch (stopbits)
{
case 1:
options.c_cflag &= ~CSTOPB;
break;
case 2:
options.c_cflag |= CSTOPB;
break;
default:
fprintf(stderr,"Unsupported stop bits\n");
return (false);
}
options.c_cflag &= ~CRTSCTS;
options.c_lflag &= ~(ECHO|ICANON|IEXTEN|ISIG);
options.c_iflag &= ~(BRKINT|ICRNL|IXON|ISTRIP);
options.c_oflag &= ~(OPOST);
options.c_cc[VTIME] = 50; // 5 seconds
options.c_cc[VMIN] = FrameLength;
tcflush(fd,TCIOFLUSH);
/* Update the options and do it NOW */
if (tcsetattr(fd,TCSANOW,&options) != 0)
{
perror("SetupSerial 3");
return (false);
}
return (true);
}
int Uart_OpenDev(char *Dev)
{
int fd = open( Dev, O_RDWR | O_NOCTTY ); //| O_NOCTTY | O_NDELAY | O_NONBLOCK
if (-1 == fd)
{
perror("Can't Open Serial Port");
return -1;
}
else
return fd;
}
int Uart_SendFrame(int fd)
{
int i,nwrite;
nwrite = write(fd,Send_Buf,FrameLength);
printf("\nSend %d Bytes\n",nwrite);\
for(i=0;i<FrameLength;i++)
printf("%d ",(u8)Send_Buf[i]);
printf("\n");
return nwrite;
}
int Uart_RecvFrame(int fd)
{
int i,nread;
nread = read(fd,Recv_Buf,FrameLength);
printf("\nReceive %d Bytes\n",nread);
for(i=0;i<FrameLength;i++)
printf("%d ",(u8)Recv_Buf[i]);
printf("\n");
return nread;
}