Skip to content

Instantly share code, notes, and snippets.

@AJMartel
Forked from maly/i2cbridge.ino
Created June 25, 2019 16:52
Show Gist options
  • Save AJMartel/835f2e10ad09493ddf0356414912b3d1 to your computer and use it in GitHub Desktop.
Save AJMartel/835f2e10ad09493ddf0356414912b3d1 to your computer and use it in GitHub Desktop.
Serial to I2C bridge for Arduino Uno
#include <Wire.h>
char inputString[200];
uint8_t ipos = 0;
boolean stringComplete = false;
void setup() {
Serial.begin(9600);
Wire.begin();
ipos = 0;
}
int parseHex(char *g){
uint8_t a,b;
a = g[0];
b = g[1];
if (a>'f') return -1;
if (a<'0') return -1;
if (a>'9' && a<'A') return -1;
if (a>'F') a-=32; //abcdef -> ABCDEF
a = a-'0';
if (a>9) a-=7;
if (a>15) return -1;
if (a<0 || a>15) return -1;
if (b>'f') return -1;
if (b<'0') return -1;
if (b>'9' && b<'A') return -1;
if (b>'F') b-=32; //abcdef -> ABCDEF
b = b-'0';
if (b>9) b-=7;
if (b>15) return -1;
if (b<0 || b>15) return -1;
return a*16+b;
}
char output[3];
char *toHex(int i){
output[0] = i/16;
output[1] = i%16;
output[0] += '0';
output[1] += '0';
if (output[0]>'9') output[0] += 7;
if (output[1]>'9') output[1] += 7;
output[2] = 0;
return output;
}
int defaddr = 0;
void loop() {
int addr;
int val;
int xpos;
int len;
if (stringComplete) {
//Serial.print("Go: ");
xpos = 2;
addr = parseHex(inputString);
//Serial.println(toHex(addr));
if (addr == -1) {
xpos = 0;
addr = defaddr;
}
switch (inputString[xpos++]){
//commands
case '!':
//set addr
defaddr = addr;
Serial.print("Default address set to ");
Serial.println(toHex(addr));
break;
case '.':
Serial.print("Write to ");
Serial.print(toHex(addr));
Serial.print(":");
Wire.beginTransmission(addr);
while(1) {
val = parseHex(inputString + xpos);
xpos += 2;
if (val==-1) {
if (inputString[xpos-2]=='?') {
Serial.print(" ? ");
xpos--;
len = parseHex(inputString + xpos);
if (len==-1) {
Wire.endTransmission();
newString();return;
}
Wire.requestFrom(addr,len);
while(len--) {
val = Wire.read();
Serial.print(toHex(val));
Serial.print(" ");
}
}
Serial.println("*");
Wire.endTransmission();
newString();return;
}
Wire.write(val);
Serial.print(toHex(val));
}
break;
case '?':
len = parseHex(inputString + xpos);
if (len==-1) {
newString();return;
}
Serial.print("Read ");
Serial.print(len);
Serial.print(" bytes from ");
Serial.print(toHex(addr));
Serial.print(": ");
Wire.requestFrom(addr,len);
while(Wire.available()) {
val = Wire.read();
Serial.print(toHex(val));
Serial.print(" ");
}
newString();return;
}
// clear the string:
newString();
}
}
void newString(void) {
stringComplete = false;
ipos = 0;
}
//---------------
void serialEvent() {
while (Serial.available()) {
char inChar = (char)Serial.read();
if (ipos==199) return;
inputString[ipos++] = inChar;
inputString[ipos] = 0;
if (inChar == '\n') {
stringComplete = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment