- 2
- 0
- 约4.53千字
- 约 8页
- 2023-04-26 发布于上海
- 举报
PAGE
PAGE 1
Linux 下的串口编程
一:串口发送端程序
/***********************************************************************
****************************
**文件:w_uart.c
**编写者:huangminqiang
**编写日期:2012 年 10 月 15 号
**简要描述:串口发送程序,在 PC 机上发送。
**修改者:
**修改日期:2012 年 11 月 12 号
**注:
************************************************************************
****************************/ #include stdio.h
#include string.h #include termios.h #include fcntl.h #include sys/stat.h #include sys/types.h
#define COM /dev/ttyS0
typedef enum
{
NON, //无校验ODD, //偶校验EVEN,//奇校验
}cal_t;
/****** 设置串口
************************************************************************
***************/
static int set_com(int fd, int speed, int bits, cal_t cal, int stop )
{
struct termios curtio;
memset(curtio, 0, sizeof(curtio));
//取得串口已有的属性
if (0 != tcgetattr(fd, curtio))
{
perror(Failed to tcgetattr); return -1;
}
//设置输入输出波特率cfsetispeed(curtio, speed); cfsetospeed(curtio, speed);
//设置为原始模式
curtio.c_lflag = ~(ECHO | ICANON | IEXTEN | ISIG | ECHOE | ECHOK | ECHONL); curtio.c_iflag = ~(BRKINT | IUCLC | ICRNL | INLCR | IGNCR);
//激活相应选项
curtio.c_cflag |= CLOCAL | CREAD;
// 设 置 数 据 位 curtio.c_cflag = ~CSIZE; curtio.c_cflag |= bits;
//设置校验位
if (ODD == cal)
{
curtio.c_iflag |= (INPCK | ISTRIP); curtio.c_cflag |= PARENB; curtio.c_cflag |= PARODD;
}
else if(EVEN == cal)
{
curtio.c_iflag |= (INPCK | ISTRIP); curtio.c_cflag |= PARENB; curtio.c_cflag = ~PARODD;
}
else
{
curtio.c_cflag = ~PARENB;
}
//设置停止位if (2 == stop)
{
curtio.c_cflag |= CSTOPB;
}
else
{
curtio.c_cflag = ~CSTOPB;
}
//设置最少字符等待时间curtio.c_cc[VTIME] = 0;
curtio.c_cc[VMIN] = 0;
//清空缓冲
tcflush(fd, TCIOFLUSH);
//设置新串口属性
if (0 != tcsetattr(fd, TCSANOW, curtio))
{
perror(Failed to tcgetattr); return -1;
}
printf(set done!\n); return 0;
}
/****** 写入串口信
息 **********************************************************************
************/
int WriteUartInfo(void)
{
int fd;
int cnt = 0; int w_cnt = 0;
unsigned char w_buf[128];
//打开串口
fd = open(COM, O_RDWR); if(0 fd)
{
perror(ua
原创力文档

文档评论(0)