tunerlistd/arduino/tunerlist_i2c_attiny85/tunerlist_i2c_attiny85.ino

144 lines
2.2 KiB
C++

#include <SoftwareSerial.h>
#include <Wire.h>
#define MRQ_PIN 1
SoftwareSerial serial(3, 4);
enum State
{
IDLE,
ACTIVE
};
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)
{
byte first_byte = Wire.read();
byte second_byte = Wire.read();
if (first_byte == 0x01 && second_byte == 0x11)
{
if (!handshakeComplete)
{
handshakeComplete = true;
}
}
else if (first_byte == 0x01 && second_byte == 0x10)
{
handshakeComplete = false;
}
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(4800);
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 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;
}
}