串口初始化

来源:互联网 发布:帝国cms电影源码 编辑:程序博客网 时间:2024/05/22 02:24

在开发过程中常用的串口,初始化程序,以及封装的字符串发送函数

#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);//波特率为115200cfsetospeed(&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!");}}


1 0
原创粉丝点击