Scans for I2C devices and prints out the addresses to serial. Scans once at startup and again whenever it receives a "s" over the serial port. When using putty, turn "Local Echo" and "Local line editing" options to "Force On". Tested on a Nucleo F446RE but should be portable to most boards with minimal editing.
Diff: main.cpp
- Revision:
- 0:300d8042b9fe
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Wed Aug 07 16:20:58 2019 +0000 @@ -0,0 +1,73 @@ +// Basic I2C scanner. Runs at startup and when it receives a "s" character via serial. Prints out the address of any devices found on the bus. + +#include "mbed.h" +#include <string> + +bool i2cScan = true; +bool debugEnabled = true; + +I2C i2c(PB_9, PB_8); // sda, scl +//I2C i2c(D4, D5); // sda, scl +Serial pc(USBTX, USBRX, 115200); // tx, rx, baud + +// Begin serial port functions/variables +Timer serialTimer; + +char cSerialRx; // Raw character from serialRx +string sSerialRx; // Serial received string + +void serialRx_interrupt() +{ + // If time since last character received is too long, reset the received characters string and unlock the i2c bus + if ((uint32_t)serialTimer.read_ms() > 5) { + sSerialRx.clear(); + } + + cSerialRx=pc.getc(); // Get individual characters from serial + sSerialRx+=cSerialRx; // and string them together + + switch (cSerialRx) { + case 's': // Trigger a I2C scan + i2cScan = true; + + sSerialRx.clear(); // clear serial buffer + break; + + + case 'q': + if (debugEnabled) { + pc.printf("Restarting...\n\r"); + } + NVIC_SystemReset(); + + default: + // No action by default; wait for next character + //break; + } + serialTimer.reset(); // Reset timer +} +// End serial port functions/variables + +int main() +{ + int error = 0; + + pc.attach(&serialRx_interrupt, Serial::RxIrq); // Create serial rx interrupt to process incoming commands + serialTimer.start(); // Serial timer to keep track of time between characters + + i2c.frequency(100000); + + while (true) { + if (i2cScan) { + i2cScan = false; + for(int i = 0; i < 128 ; i++) { + i2c.start(); + error = i2c.write(i << 1); + i2c.stop(); + if (error == 1) { + printf("0x%X\r\n", i); //Return 7-bit address + } + } + } + } +} \ No newline at end of file