#include <stdlib.h> /*标准函数库定义*/
#include <unistd.h> /*Unix 标准函数定义*/
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h> /*文件控制定义*/
#include <termios.h> /*PPSIX 终端控制定义*/
#include <errno.h> /*错误号定义*/
#define FALSE -1
#define TRUE 0
int OpenDev(char *Dev)
{
int fd = open( Dev, O_RDWR ); //| O_NOCTTY | O_NDELAY
if (-1 == fd) /*判断串口是否打开成功*/
{
perror("Can't Open Serial Port\n");
return -1;
}
else
{
printf("open successful");
}
return fd;}
int set_opt(int fd,int nSpeed, int nBits, char nEvent, int nStop) /*设置串口参数 波特率 数据位 奇偶校验位 停止位*/
{
struct termios newtio,oldtio;
if ( tcgetattr( fd,&oldtio) != 0)
{
perror("SetupSerial 1");
return -1;
}
bzero( &newtio, sizeof( newtio ) );
newtio.c_cflag |= CLOCAL | CREAD;
newtio.c_cflag &= ~CSIZE;
switch( nBits )
{
case 7:
newtio.c_cflag |= CS7;
break;
case 8:
newtio.c_cflag |= CS8;
break;
}
switch( nEvent )
{
case 'O':
newtio.c_cflag |= PARENB;
newtio.c_cflag |= PARODD;
newtio.c_iflag |= (INPCK | ISTRIP);
break;
case 'E':
newtio.c_iflag |= (INPCK | ISTRIP);
newtio.c_cflag |= PARENB;
newtio.c_cflag &= ~PARODD;
break;
case 'N':
newtio.c_cflag &= ~PARENB;
break;
}
switch( nSpeed )
{
case 2400:
cfsetispeed(&newtio, B2400);
cfsetospeed(&newtio, B2400);
break;
case 4800:
cfsetispeed(&newtio, B4800);
cfsetospeed(&newtio, B4800);
break;
case 9600:
cfsetispeed(&newtio, B9600);
cfsetospeed(&newtio, B9600);
break;
case 115200:
cfsetispeed(&newtio, B115200);
cfsetospeed(&newtio, B115200);
break;
default:
cfsetispeed(&newtio, B9600);
cfsetospeed(&newtio, B9600);
break;
}
if( nStop == 1 )
newtio.c_cflag &= ~CSTOPB;
else if ( nStop == 2 )
newtio.c_cflag |= CSTOPB;
newtio.c_cc[VTIME] = 0;
newtio.c_cc[VMIN] = 0;
tcflush(fd,TCIFLUSH);
if((tcsetattr(fd,TCSANOW,&newtio))!=0)
{
perror("com set error");
return -1;
}
printf("set done!\n");
return 0;
}
int main(void)
{
int fd;
int nread;
char write_buff[512];
char read_buff[512];
char *dev = "/dev/ttyS1"; //串口二
fd = OpenDev(dev);
if(fd>0)
{
printf("open successful\n");
printf("fd=%d\n",fd);
}
else
{
printf("open fail!\n");
printf("fd=%d\n",fd);
}
if (set_opt(fd,19200,8,1,'N') == FALSE)
{
printf("Set Parity Error\n");
exit (0);
}
else
printf("set Parity successful\n");
while(1)
{
strcpy(write_buff, "ping");
if( write(fd, write_buff, 5 ) > 0)
{
printf("write ok\n");
printf("write data:%s\n",write_buff);
}
else
{
printf("write fail!\n");
}
if(read(fd, write_buff, 5) >0)
{
printf("read data:%s\n",write_buff);
}
strcpy(read_buff, "pang");
// printf("write buff:%s\n",write_buff);
if(write(fd, read_buff, 5) >0)
{
printf("write data: %s\n",read_buff);
}
if((nread=read(fd, read_buff, 5)) > 0 )
{
printf("read ok\n");
printf("read Byte:%d\n",nread);
printf("read data:%s\n",read_buff);
}
else
{
printf("read fail\n");
printf("nread=%d\n",nread);
}
sleep(2);
}
close(fd);
return -1;
}
此程序是为了用于自发自收的,需要短接2,3引脚。
运行结果如下:
~ >: ./serial
open successful
fd=3
set done!
set Parity successful
write ok
write data:ping
write data: pang
read ok
read Byte:5
read data:pang