Last active
May 29, 2023 13:48
-
-
Save dragoncoder047/e418736f62aefd963bdd56f2017431ae to your computer and use it in GitHub Desktop.
Quick I2C REPL for Arduinos.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <Wire.h> | |
| #include <string.h> | |
| void setup() { | |
| Wire.begin(); | |
| Wire.setClock(1000); | |
| Serial.begin(115200); | |
| Serial.println("i2c REPL"); | |
| } | |
| unsigned int tgt_addr = 0x05; | |
| void loop() { | |
| if (Serial.available()) { | |
| char c = tolower(Serial.read()); | |
| int read, write; | |
| bool nack; | |
| switch (c) { | |
| case 'a': | |
| tgt_addr = Serial.parseInt() & 127; | |
| Serial.printf("Target address %#x\n", tgt_addr); | |
| break; | |
| case '[': | |
| Serial.printf("Begin transmission at target address %#x\n", tgt_addr); | |
| Wire.beginTransmission((uint8_t)tgt_addr); | |
| break; | |
| case ']': | |
| Serial.print("End transmission "); | |
| nack = Wire.endTransmission(); | |
| if (nack) Serial.write('N'); | |
| Serial.println("ACK"); | |
| break; | |
| case '@': | |
| Serial.print("Restart transmission "); | |
| nack = Wire.endTransmission(false); | |
| if (nack) Serial.write('N'); | |
| Serial.println("ACK"); | |
| break; | |
| case 'w': | |
| write = Serial.parseInt() & 255; | |
| Serial.printf("Writing byte %#x\n", write); | |
| Wire.write((uint8_t)write); | |
| break; | |
| case 'r': | |
| read = Serial.parseInt(); | |
| Serial.printf("Requesting %i bytes from address %#x:\n", read, tgt_addr); | |
| Wire.requestFrom(tgt_addr, read); | |
| for (int i = 0; i < read; i++) { | |
| Serial.print(Wire.read() & 255); | |
| Serial.write(' '); | |
| } | |
| Serial.write('\n'); | |
| break; | |
| case '\n': | |
| case '\r': | |
| case ' ': | |
| case '\t': | |
| // whitespace ignored | |
| break; | |
| default: | |
| Serial.printf("Unknown command '%c'!\n", c); | |
| Serial.flush(); | |
| break; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment