2022年7月17日 星期日

Linux 系統使用 termios2 客製化 baud rate

簡單的 class,用來與 uBit V1.5 的 Serial port (/dev/ttyACM0)做溝通, 原始程式碼:

 #ifndef MySerial_H
#define MySerial_H
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <asm/termbits.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#define defaultBaudrate 115200

class MySerial {
  private:
    int fd = 0;
  public:
    ~MySerial() { if (fd) close(fd);  }
    MySerial(const char *dev = "/dev/ttyACM0", int baud = defaultBaudrate) {
      int ttyFD = open(dev, O_RDWR | O_NONBLOCK);
      if (ttyFD > 0) {
        fd = ttyFD;
        struct termios2 uart2;
        uart2.c_iflag     = 0;
        uart2.c_oflag     = 0;
        uart2.c_lflag     = 0;
        uart2.c_cc[VMIN]  = 1;
        uart2.c_cc[VTIME] = 0;
        uart2.c_cflag     = CS8 | CREAD | CLOCAL;
        uart2.c_cflag    &= ~CBAUD;
        uart2.c_cflag    |= CBAUDEX;
        uart2.c_ispeed = baud;
        uart2.c_ospeed = baud;
        ioctl(fd, TCSETS2, &uart2);       
      }
    }
    bool ready() { return fd > 0;  }

    int available() {
      if (fd > 0) {
          int bytes;
          ioctl(fd, FIONREAD, &bytes);
          return bytes;
      }
      return 0;
    }

    ssize_t write(char *buffer) {
      if (fd && buffer) return ::write(fd, buffer, strlen(buffer));// use global write      
      return 0;
    }

    ssize_t read(char *buffer, int n) {
      if (fd && buffer && n) return ::read(fd, buffer, n); // use global read
      return 0;
    }

    int printf(const char *fmt, ...) {
      static char strBuffer[1024];// Note: upto 1024 characters
      va_list parameters;
      va_start(parameters, fmt);
      vsprintf(strBuffer, fmt, parameters);
      va_end(parameters);
      return write(strBuffer);// this->write
    }
};
#endif

沒有留言:

張貼留言

使用 pcie 轉接器連接 nvme SSD

之前 AM4 主機板使用 pcie ssd, 但主機板故障了沒辦法上網, 只好翻出以前買的 FM2 舊主機板, 想辦法讓老主機復活, 但舊主機板沒有 nvme 的界面, 因此上網買了 pcie 轉接器用來連接 nvme ssd, 遺憾的是 grub2 bootloader 無法識...