簡單的 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
沒有留言:
張貼留言