Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IOT-123/75472f61da8fa86a0a1aedc4aa397451 to your computer and use it in GitHub Desktop.
Save IOT-123/75472f61da8fa86a0a1aedc4aa397451 to your computer and use it in GitHub Desktop.
Captures serial input (keyboard input in the console window) and forwards it to an I2C slave in the format char, byte, byte.
#include <Wire.h>
#define I2C_MSG_IN_SIZE 2
#define I2C_MSG_OUT_SIZE 3
#define I2C_SLAVE_ADDRESS 10
boolean _newData = false;
const byte _numChars = 32;
char _receivedChars[_numChars]; // an array to store the received data
void setup() {
Serial.begin(9600);
Wire.begin(D2, D1);
delay(5000);
}
void loop() {
recvWithEndMarker();
parseSendCommands();
}
void recvWithEndMarker() {
static byte ndx = 0;
char endMarker = '\n';
char rc;
while (Serial.available() > 0 && _newData == false) {
rc = Serial.read();
if (rc != endMarker) {
_receivedChars[ndx] = rc;
ndx++;
if (ndx >= _numChars) {
ndx = _numChars - 1;
}
} else {
_receivedChars[ndx] = '\0'; // terminate the string
ndx = 0;
_newData = true;
}
}
}
void parseSendCommands() {
if (_newData == true) {
const char delim[2] = " ";
char *token;
token = strtok(_receivedChars, delim);
char cmd = _receivedChars[0];
byte index = 0;
byte value = 0;
int i = 0;
while( token != NULL ) {
//Serial.println(token);
i++;
switch (i){
case 1:
token = strtok(NULL, delim);
index = atoi(token);
break;
case 2:
token = strtok(NULL, delim);
if (token != NULL){
value = atoi(token);
}
break;
default:
token = NULL;
}
}
sendCmd(cmd, index, value);
_newData = false;
}
}
void sendCmd(char cmd, byte index, byte value) {
Serial.println("-----");
Serial.println("Sending command:");
Serial.println("\t" + String(cmd) + " " + String(index) + " " + String(value) );
Serial.println("-----");
Wire.beginTransmission(I2C_SLAVE_ADDRESS); // transmit to device
Wire.write(cmd); // sends a char
Wire.write(index); // sends one byte
Wire.write(value); // sends one byte
Wire.endTransmission();
byte response = 0;
bool hadResponse = false;
if (cmd == 'G'){
Wire.requestFrom(I2C_SLAVE_ADDRESS,1);
while(Wire.available()) // slave may send less than requested
{
hadResponse = true;
response = Wire.read();
}
if (hadResponse == true){
Serial.println("Getting response:");
Serial.println(response);
}else{
Serial.println("No response, check the address/connection");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment