Skip to content

Instantly share code, notes, and snippets.

@luigidifraia
Last active July 8, 2019 10:30
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 luigidifraia/ebedd12485523197385a2e76b6b5deb3 to your computer and use it in GitHub Desktop.
Save luigidifraia/ebedd12485523197385a2e76b6b5deb3 to your computer and use it in GitHub Desktop.
Arduino sketch for bridging the I2C and USB serial interfaces
/*
* Title: I2C <-> USB serial bridge
* Board: Arduino Pro-Micro (ATMega32U4)
* Author: Luigi Di Fraia
*
* Note: This example is provided as a guideline only, without any warranty!
*/
#include <Wire.h>
const byte addressSlave = 8; // slave's address
void setup() {
Wire.begin(addressSlave); // join i2c bus as slave with chosen address
Wire.onReceive(receiveEvent); // register receive event
Wire.onRequest(requestEvent); // register request event
Serial.begin(9600); // configure USB serial (always 12 Mbit/sec)
}
void loop() {
delay(100);
}
void receiveEvent (int numBytes)
{
while (numBytes--) { // loop through all bytes
byte c = Wire.read(); // receive byte on i2c bus
Serial.write(c); // output byte to USB serial
}
}
void requestEvent (void)
{
while (Serial.available()) { // loop through all bytes
byte c = Serial.read(); // receive byte on USB serial
Wire.write(c); // output byte to i2c bus
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment