您的位置:首页 > 其它

串口初始化

2016-04-06 18:07 351 查看
在开发过程中常用的串口,初始化程序,以及封装的字符串发送函数

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <string.h>

static struct termios option_old;

/************************************************************
*函数名称: int uart_init(char *devname)
*函数功能: 串口初始化程序
*函数参数: devname 串口设备文件序号
*函数返回: 串口设备文件描述符
***********************************************************/
int uart_init(char *devname)
{
int uart_fd;
struct termios option_new;

uart_fd = open(devname, O_RDWR|O_NDELAY); //O_NDELAY 不阻塞
if(uart_fd < 0)
{
DebugL("open_dev error!");
_exit(-1);
}
tcgetattr(uart_fd, &option_old); //保存串口属性
tcgetattr(uart_fd, &option_new);

cfsetispeed(&option_new, B115200); //波特率为115200
cfsetospeed(&option_new, B115200); //波特率为115200
/*option_new.c_cflag &= ~CSIZE; //设置数据位时先关闭历史设置
option_new.c_cflag |= CS8; //数据位为8位
option_new.c_cflag &= ~CSTOPB; //1位停止位
option_new.c_cflag &= ~PARENB; //无奇偶校验位
option_new.c_lflag &= ~(ICANON); //非标准模式
// option_new.c_lflag &= ~ECHO; //关回显,在使用GPRS模组时需关回显
option_new.c_lflag |= ECHO; */ //开回显

/***********能接收0x03的配置***************/
option_new.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
option_new.c_oflag &= ~OPOST;
option_new.c_cflag |= CLOCAL | CREAD;
option_new.c_lflag &= ~(ICANON | ECHOE | ISIG);

tcsetattr(uart_fd, TCSANOW, &option_new);
return uart_fd;
}

/************************************************************
*函数名称: void uart_uninit(int uart_fd)
*函数功能: 串口反初始化程序
*函数参数: uart_fd 串口设备文件描述符
*函数返回: 无
***********************************************************/
void uart_uninit(int uart_fd)
{
/*还原串口属性*/
tcsetattr(uart_fd, TCSANOW, &option_old);

/*关闭串口*/
close(uart_fd);
}

/************************************************************
*函数名称: void uart_send_str(int uart_fd, char *str)
*函数功能: 串口发送字符串
*函数参数: uart_fd 串口设备文件描述符
* str:待发送的字符
*函数返回: 无
***********************************************************/
void uart_send_str(int uart_fd, char *str)
{
int ret;

ret = write(uart_fd, str, strlen(str));
if(ret < 0)
{
DebugL("write error!");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: