You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

89 lines
1.8 KiB

#include "uart.hpp"
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace iflytop;
using namespace std;
Uart::Uart() {}
Uart::~Uart() {}
int Uart::open(string path) {
int rc;
m_name = path;
m_fd = ::open(path.c_str(), O_RDWR | O_NOCTTY);
if (m_fd < 0) {
cout << "open " << path << " failed" << endl;
return -1;
}
memset(&m_tty, 0, sizeof(m_tty));
m_tty.c_cflag |= CLOCAL | CREAD; // 激活本地连接与接受使能
m_tty.c_cflag &= ~CSIZE; // 失能数据位屏蔽
m_tty.c_cflag |= CS8; // 8位数据位
m_tty.c_cflag &= ~CSTOPB; // 1位停止位
m_tty.c_cflag &= ~PARENB; // 无校验位
m_tty.c_cc[VTIME] = 0;
m_tty.c_cc[VMIN] = 0;
cfsetispeed(&m_tty, B115200); // 设置输入波特率
cfsetospeed(&m_tty, B115200); // 设置输出波特率
tcflush(m_fd, TCIFLUSH); // 刷清未处理的输入和/或输出
/* Apply attributes */
rc = tcsetattr(m_fd, TCSANOW, &m_tty);
if (rc) {
cout << "tcsetattr failed" << endl;
return -3;
}
return 0;
}
int Uart::send(char *data, int size) {
int sent = 0;
sent = write(m_fd, data, size);
if (sent > 0) {
printf("send success, data is %s\r\n", data);
}
return sent;
}
int Uart::receive(char *data, int size_max) {
int received = 0;
received = read(m_fd, data, size_max);
if (received > 0) {
printf("recv success,recv size is %d,data is %s\r\n", received, data);
}
return received;
}
int Uart::close() {
::close(m_fd);
m_fd = -1;
return 0;
}
bool Uart::flush_rx() {
if (m_fd < 0) return false;
int rc = tcflush(m_fd, TCIFLUSH);
return rc == 0;
}
bool Uart::flush_tx() {
if (m_fd < 0) return false;
int rc = tcflush(m_fd, TCOFLUSH);
return rc == 0;
}