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

2 years ago
  1. #include "uart.hpp"
  2. #include <fcntl.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <iostream>
  7. using namespace iflytop;
  8. using namespace std;
  9. Uart::Uart() {}
  10. Uart::~Uart() {}
  11. int Uart::open(string path) {
  12. int rc;
  13. m_name = path;
  14. m_fd = ::open(path.c_str(), O_RDWR | O_NOCTTY);
  15. if (m_fd < 0) {
  16. cout << "open " << path << " failed" << endl;
  17. return -1;
  18. }
  19. memset(&m_tty, 0, sizeof(m_tty));
  20. m_tty.c_cflag |= CLOCAL | CREAD; // 激活本地连接与接受使能
  21. m_tty.c_cflag &= ~CSIZE; // 失能数据位屏蔽
  22. m_tty.c_cflag |= CS8; // 8位数据位
  23. m_tty.c_cflag &= ~CSTOPB; // 1位停止位
  24. m_tty.c_cflag &= ~PARENB; // 无校验位
  25. m_tty.c_cc[VTIME] = 0;
  26. m_tty.c_cc[VMIN] = 0;
  27. cfsetispeed(&m_tty, B115200); // 设置输入波特率
  28. cfsetospeed(&m_tty, B115200); // 设置输出波特率
  29. tcflush(m_fd, TCIFLUSH); // 刷清未处理的输入和/或输出
  30. /* Apply attributes */
  31. rc = tcsetattr(m_fd, TCSANOW, &m_tty);
  32. if (rc) {
  33. cout << "tcsetattr failed" << endl;
  34. return -3;
  35. }
  36. return 0;
  37. }
  38. int Uart::send(char *data, int size) {
  39. int sent = 0;
  40. sent = write(m_fd, data, size);
  41. if (sent > 0) {
  42. printf("send success, data is %s\r\n", data);
  43. }
  44. return sent;
  45. }
  46. int Uart::receive(char *data, int size_max) {
  47. int received = 0;
  48. received = read(m_fd, data, size_max);
  49. if (received > 0) {
  50. printf("recv success,recv size is %d,data is %s\r\n", received, data);
  51. }
  52. return received;
  53. }
  54. int Uart::close() {
  55. ::close(m_fd);
  56. m_fd = -1;
  57. return 0;
  58. }
  59. bool Uart::flush_rx() {
  60. if (m_fd < 0) return false;
  61. int rc = tcflush(m_fd, TCIFLUSH);
  62. return rc == 0;
  63. }
  64. bool Uart::flush_tx() {
  65. if (m_fd < 0) return false;
  66. int rc = tcflush(m_fd, TCOFLUSH);
  67. return rc == 0;
  68. }