Skip to content

Instantly share code, notes, and snippets.

@deltaphi
Created May 23, 2020 07:48
Show Gist options
  • Save deltaphi/72f9a7bcf23710ae070364f882ee6688 to your computer and use it in GitHub Desktop.
Save deltaphi/72f9a7bcf23710ae070364f882ee6688 to your computer and use it in GitHub Desktop.
Stand-Alone Responder to a Marklin Keyboard i2c bus message.
// Wire Slave Receiver
// by Nicholas Zambetti <http://www.zambetti.com>
// Demonstrates use of the Wire library
// Receives data as an I2C/TWI slave device
// Refer to the "Wire Master Writer" example for use with this
// Created 29 March 2006
// This example code is in the public domain.
#include <Wire.h>
constexpr const uint8_t kCentralAddr = 0x7F;
constexpr const uint8_t myAddr = kCentralAddr;
typedef struct DataMessage {
uint8_t destination = myAddr;
uint8_t source = 0;
uint8_t data = 0;
} DataMessage;
DataMessage lastMsg;
bool messageReceived;
void setup() {
messageReceived = false;
Wire.begin(myAddr); // join i2c bus with address #8
Wire.onReceive(receiveEvent); // register event
Serial.begin(115200); // start serial for output
Serial.println(F("slave_receiver ready."));
}
void loop() {
// delay(100);
if (messageReceived) {
// Craft a response
DataMessage response;
response.destination = lastMsg.source >> 1; // guesswork: shift by 1. Observation: Keyboard that sent with 20 gets its response on 10.
response.source = lastMsg.destination << 1; // guesswork: shift by 1. Observation: Central that received on 0x7F sends from 0xFE
response.data = lastMsg.data;
SendMessage(response);
messageReceived = false;
}
}
void SendMessage(DataMessage& msg) {
Wire.beginTransmission(msg.destination);
Wire.write(msg.source);
Wire.write(msg.data);
Wire.endTransmission();
Serial.println(F("Response sent."));
}
// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
if (!messageReceived) {
lastMsg.destination = myAddr;
lastMsg.source = Wire.read();
lastMsg.data = Wire.read();
Serial.println(F("Message received."));
messageReceived = true;
} else {
Serial.println(F("Buffer full, lost message."));
}
/*
while (1 < Wire.available()) { // loop through all but the last
uint8_t c = Wire.read(); // receive byte as a character
Serial.print(c, HEX); // print the character
Serial.print(' ');
}
int x = Wire.read(); // receive byte as an integer
Serial.println(x, HEX); // print the integer
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment