120 lines
2.4 KiB
C++
120 lines
2.4 KiB
C++
#include <SoftwareSerial.h>
|
|
#include <Wire.h>
|
|
|
|
#define MRQ_PIN 1
|
|
|
|
SoftwareSerial serial(3,4);
|
|
|
|
enum State { IDLE,
|
|
ACTIVE,
|
|
PAUSE };
|
|
|
|
byte HANDSHAKE[] = { 0x01, 0x00 };
|
|
byte PONG[] = { 0x01, 0x01 };
|
|
byte BUTTON[] = { 0x04, 0x82, 0x91, 0x00, 0x00 };
|
|
|
|
State currentState = IDLE;
|
|
unsigned long lastChange = 0;
|
|
|
|
bool handshakeComplete = false;
|
|
bool processButton = false;
|
|
|
|
byte readBuffer[16];
|
|
bool newBuffer = false;
|
|
|
|
void up() {
|
|
pinMode(MRQ_PIN, INPUT_PULLUP);
|
|
}
|
|
|
|
void down() {
|
|
pinMode(MRQ_PIN, OUTPUT);
|
|
digitalWrite(MRQ_PIN, LOW);
|
|
}
|
|
|
|
void onRequest() {
|
|
while (digitalRead(MRQ_PIN))
|
|
;
|
|
if (!handshakeComplete) {
|
|
Wire.write(HANDSHAKE, sizeof HANDSHAKE);
|
|
} else {
|
|
if (processButton) {
|
|
processButton = false;
|
|
Wire.write(BUTTON, sizeof BUTTON);
|
|
} else {
|
|
Wire.write(PONG, sizeof PONG);
|
|
}
|
|
}
|
|
}
|
|
|
|
void onReceive(int bytes) {
|
|
//Serial.println(bytes);
|
|
byte first_byte = Wire.read();
|
|
byte second_byte = Wire.read();
|
|
if (first_byte == 0x01 && second_byte == 0x11) {
|
|
if (!handshakeComplete) {
|
|
handshakeComplete = true;
|
|
//currentState = PAUSE;
|
|
}
|
|
} else if (first_byte == 0x01 && second_byte == 0x10) {
|
|
handshakeComplete = false;
|
|
//currentState = ACTIVE;
|
|
} else {
|
|
for (int i = 0; i < 16; i++) readBuffer[i] = 0x0;
|
|
readBuffer[0] = first_byte;
|
|
readBuffer[1] = second_byte;
|
|
for (int i = 0; i < bytes - 2; i++) {
|
|
readBuffer[i + 2] = Wire.read();
|
|
}
|
|
newBuffer = true;
|
|
}
|
|
}
|
|
|
|
void setup() {
|
|
serial.begin(9600);
|
|
|
|
Wire.setClock(10000);
|
|
Wire.begin(0x23);
|
|
Wire.onRequest(onRequest);
|
|
Wire.onReceive(onReceive);
|
|
|
|
pinMode(MRQ_PIN, INPUT_PULLUP);
|
|
}
|
|
|
|
void loop() {
|
|
if (serial.available()) {
|
|
BUTTON[3] = serial.read();
|
|
BUTTON[4] = serial.read();
|
|
processButton = true;
|
|
currentState = ACTIVE;
|
|
}
|
|
|
|
if (newBuffer) {
|
|
for (int i = 0; i < 16; i++) {
|
|
serial.write(readBuffer[i]);
|
|
}
|
|
newBuffer = false;
|
|
serial.println();
|
|
}
|
|
|
|
unsigned long now = millis();
|
|
switch (currentState) {
|
|
case PAUSE:
|
|
break;
|
|
case IDLE:
|
|
up();
|
|
if (now - lastChange >= 480) {
|
|
if (digitalRead(MRQ_PIN)) {
|
|
lastChange = now;
|
|
currentState = ACTIVE;
|
|
}
|
|
}
|
|
break;
|
|
case ACTIVE:
|
|
down();
|
|
if (now - lastChange >= 30) {
|
|
lastChange = now;
|
|
currentState = IDLE;
|
|
}
|
|
break;
|
|
}
|
|
} |