串口通信
最近做了串口传送数据的实验,主要是设置设置串口传输速度,串口属性参数,对其初始化后,便可以用相应的文件描述符来读取与发送数据。具体代码如下:
/***********************************************
*Function: set_speed
*Description: 设置串口传输速度
*Input: fd 串口的句柄
*speed 串口传输速度
***********************************************/
int set_speed(int fd, int speed)
{
struct termios opt;
if (tcgetattr(fd, &opt) != 0) {
printf("tcgetattr %s/n", strerror(errno));
return -10;
}
tcflush(fd, TCIOFLUSH);
cfsetispeed(&opt, speed);
cfsetospeed(&opt, speed);
tcsetattr(fd, TCSANOW, &opt);
tcflush(fd, TCIOFLUSH);
return 0;
}
/***********************************************
*Function: set_parity
*Description: 设置串口参数
*Input: fd 串口的句柄
*databits 数据位
*stopbits 停止位
*parity 奇偶校验
***********************************************/
int set_parity(int fd, int databits, int stopbits, int parity)
{
struct termios opt;
if (tcgetattr(fd, &opt) != 0) {
printf("tcgetattr %s/n", strerror(errno));
return -10;
}
opt.c_cflag &= ~CSIZE; /* 不按位数据位掩码 */
opt.c_cflag |= CS8;
opt.c_cflag &= ~PARENB; /* Clear parity enable */
opt.c_iflag &= ~INPCK; /* disable parity checking */
opt.c_cflag &= ~CSTOPB;/* one stopbit */
opt.c_cc[VTIME] = 50; /* 5 seconds */
opt.c_cc[VMIN] = 0;
opt.c_lflag &= ~(ECHO|ECHOE|ISIG|ICANON);
opt.c_oflag &= ~OPOST;
opt.c_iflag &= ~(IXON|IXOFF|INLCR|IGNCR|ICRNL);
tcflush(fd,TCIFLUSH); /* Update options NOW */
tcsetattr(fd,TCSANOW,&opt);
return 0;
}
int init_uart(int number)
{
int fd;
char name[16] = { 0, };
sprintf(name, "/dev/ttyS%d", number);
fd = open(name, O_RDWR);
if (fd == -1) {
UARTERR("Device %s not found/n", name);
return -1;
} else {
UARTINFO("Open device %s/n", name);
}
set_speed(fd, B115200);
set_parity(fd, 8, 1, 'n');
return fd;
}
初始化完成后,便可以通过read(uartfd, &buff, length),write(uartfd, buf, length);进行串口通信,接收与传送数据。