Skip to content

Instantly share code, notes, and snippets.

@IOT-123
Created December 30, 2017 09:44
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/7f3b32ae91fbabea418df090de874dee to your computer and use it in GitHub Desktop.
Save IOT-123/7f3b32ae91fbabea418df090de874dee to your computer and use it in GitHub Desktop.
Use serial input (console) to send I2C commands to an I2C slave. Must accept the format <char><byte> (2 bytes of data).
#include <Wire.h>
const byte _numChars = 32;
char _receivedChars[_numChars]; // an array to store the received data
boolean _newData = false;
void setup() {
Serial.begin(9600);
Wire.begin(); // join i2c bus (address optional for master)
delay(2000);
Serial.println("D1M WIFI BLOCK is ready - you can cofigure you I2C D1M Shield from here!");
Serial.println("");
Serial.println("Set line ending to newline (lower RHS combo box)");
Serial.println("");
Serial.println("The format of commands are:");
Serial.println("\t<character><byte> <enter>");
Serial.println("\tEverything after the first character will attempt to convert to a byte value");
Serial.println("\tIf only one character is entered or the characters cannot be coerced to a byte, 0 will be sent as the byte param");
Serial.println("");
sendCmd('D', 0); // disable watchdog so it does not reset - the user can input E (to re-enable)
}
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) {
char c = _receivedChars[0];
byte b = 0;
if (strlen (_receivedChars) > 1){
char* numberPart = _receivedChars + 1;
b = atoi(numberPart);
}
sendCmd(c, b);
_newData = false;
}
}
void sendCmd(char cmd, byte par) {
Wire.beginTransmission(8); // transmit to device #8
Wire.write(cmd); // sends a char
Wire.write(par); // sends one byte
Wire.endTransmission();
byte response = 0;
bool hadResponse = false;
if (cmd == 'G'){
Wire.requestFrom(8,1); // request a single byte from slave device #25
while(Wire.available()) // slave may send less than requested
{
hadResponse = true;
response = Wire.read(); // receive a byte as character
}
}
Serial.println("Sending command:");
Serial.println("\t" + String(cmd) + " : " + String(par));
if (cmd == 'G'){
if (hadResponse){
Serial.println("Getting response:");
Serial.println("\t" + String(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