#include <stdio.h> /*标准输入输出定义*/
#include <stdlib.h> /*标准函数库定义*/
#include <unistd.h> /*Unix 标准函数定义*/
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> /*文件控制定义*/
#include <termios.h> /*POSIX 终端控制定义*/
#include <errno.h> /*错误号定义*/
#include <string.h> /*字符串功能函数*/
#include <sys/time.h>
#include <sys/types.h>
int tty_fd = -1;
char r_buf[128];
struct termios options;
fd_set rset;
_Bool isOpne = 0;void close_serial() {printf("close_seria ===============\n\n");isOpne = 1;close(tty_fd);
}void open_serial_init() {int rv = -1;tty_fd = open("/dev/ttyS7", O_RDWR | O_NOCTTY); //打开串口设备if (tty_fd < 0){printf("open tty failed:%s\n", strerror(errno));close_serial();return;}printf("open devices sucessful!\n");memset(&options, 0, sizeof(options));rv = tcgetattr(tty_fd, &options); //获取原有的串口属性的配置if (rv != 0){printf("tcgetattr() failed:%s\n", strerror(errno));close_serial();return;}options.c_cflag |= (CLOCAL | CREAD); // CREAD 开启串行数据接收,CLOCAL并打开本地连接模式options.c_cflag &= ~CSIZE;// 先使用CSIZE做位屏蔽 options.c_cflag |= CS8; //设置8位数据位options.c_cflag &= ~PARENB; //无校验位/* 设置波特率 */cfsetispeed(&options, B115200);cfsetospeed(&options, B115200);options.c_cflag &= ~CSTOPB;/* 设置一位停止位; */options.c_cc[VTIME] = 10;/* 非规范模式读取时的超时时间;*/options.c_cc[VMIN] = 0; /* 非规范模式读取时的最小字符数*/tcflush(tty_fd, TCIFLUSH);/* tcflush清空终端未完成的输入/输出请求及数据;TCIFLUSH表示清空正收到的数据,且不读取出来 */if ((tcsetattr(tty_fd, TCSANOW, &options)) != 0){printf("tcsetattr failed:%s\n", strerror(errno));close_serial();return;}
}
void write_serial(char* buff, int size) {int rv = -1;rv = write(tty_fd, buff, size);printf("write_serial rv=============== size=%d\n", rv);if (rv < 0){printf("Write() error:%s\n", strerror(errno));close_serial();return;}}
void read_serial() {int rv = -1;while (1) {if (isOpne == 0) {memset(r_buf, 0, sizeof(r_buf));rv = read(tty_fd, r_buf, sizeof(r_buf));if (rv < 0){printf("Read() error:%s\n", strerror(errno));close_serial();return;}else {//打印数据int i = 0;while (i < rv) {printf("tty=: %x\n", r_buf[i]);i++;}if (0x15 == r_buf[0]) {printf("ttyS7 is live!\n");break;}}usleep(5000);}else {printf("Read tty null=: %s\n", r_buf);}}
}//往串口发数据(byte)的例子
void test() {int num = 0;char buff[3];buff[num++] = 0x02;buff[num++] = 0x41;buff[num++] = 0x03;write_serial(buff, num);
}
int main(int argc, char* argv[])
{printf("hello world, Harmony is coming!\n");open_serial_init();test();read_serial();close_serial();return 0;
}
注意串口初始化里串口名字,这里是 /dev/ttyS7,实际调试可能是/dev/ttyUSB0 或 其他什么,注意修改
linux下查看启用串口的命令
dmesg | grep tty
如果是windows下则是 com1 com2这样