73 lines
1.0 KiB
C++
73 lines
1.0 KiB
C++
|
|
||
|
#include <Arduino.h>
|
||
|
#include <SoftwareSerial.h>
|
||
|
#include "serial.hpp"
|
||
|
|
||
|
constexpr int DTR = A0;
|
||
|
constexpr int CTS = A3;
|
||
|
|
||
|
struct CTSGuard {
|
||
|
CTSGuard() {
|
||
|
digitalWrite(CTS, 0);
|
||
|
}
|
||
|
~CTSGuard() {
|
||
|
digitalWrite(CTS, 1);
|
||
|
}
|
||
|
};
|
||
|
|
||
|
void serial::init() {
|
||
|
pinMode(DTR, INPUT_PULLUP);
|
||
|
pinMode(CTS, OUTPUT);
|
||
|
pinMode(RXD, INPUT_PULLUP);
|
||
|
pinMode(TXD, OUTPUT);
|
||
|
digitalWrite(CTS, 1);
|
||
|
dev.begin(57600);
|
||
|
dev.listen();
|
||
|
}
|
||
|
|
||
|
bool serial::is_connected() {
|
||
|
return digitalRead(DTR) == 0;
|
||
|
}
|
||
|
|
||
|
static bool wait_until() {
|
||
|
while(!serial::dev.available()) {
|
||
|
if(!serial::is_connected()) {
|
||
|
return false;
|
||
|
}
|
||
|
}
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
unsigned serial::read(char* data, unsigned len) {
|
||
|
CTSGuard guard;
|
||
|
|
||
|
for(unsigned i = 0; i < len; i++) {
|
||
|
if(!wait_until()) {
|
||
|
return i;
|
||
|
}
|
||
|
data[i] = dev.read();
|
||
|
}
|
||
|
|
||
|
return len;
|
||
|
}
|
||
|
|
||
|
void serial::write(const char* data, unsigned len) {
|
||
|
for(unsigned i = 0; i < len; i++) {
|
||
|
dev.write(data[i]);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
void serial::put(char ch) {
|
||
|
dev.write(ch);
|
||
|
}
|
||
|
|
||
|
int serial::get() {
|
||
|
unsigned char ch;
|
||
|
if(read(&ch, 1)) {
|
||
|
return ch;
|
||
|
} else {
|
||
|
return -1;
|
||
|
}
|
||
|
}
|
||
|
|