Axel Utech
/
Nucleo_i2c_devicelist
Prints all availabe devices on the i2c bus
main.cpp
- Committer:
- aAXEe
- Date:
- 2014-11-05
- Revision:
- 0:2ccb0f491eab
File content as of revision 0:2ccb0f491eab:
#include "mbed.h" I2C i2c(I2C_SDA, I2C_SCL); Serial pc(SERIAL_TX, SERIAL_RX); #define CHAR_BIT 8 #define FMT_BUF_SIZE (CHAR_BIT*sizeof(uintmax_t)+1) char *binary_fmt(uintmax_t x, char* buf) { char *s = buf + FMT_BUF_SIZE; *--s = 0; if (!x) *--s = '0'; for(; x; x/=2) *--s = '0' + x%2; return s; } char binary_buffer[FMT_BUF_SIZE]; char text_buffer[100]; char* getDeviceName(int addr){ int devType = (addr & 0xf0) >> 4; int count = 0; switch(devType){ case 0: count += sprintf(text_buffer + count, "General call"); break; case 0x9: count += sprintf(text_buffer + count, "TMP10X"); break; case 0xD: count += sprintf(text_buffer + count, "ADC MCP3428"); break; case 0xC: count += sprintf(text_buffer + count, "DAC MCP4728"); break; case 0x4: count += sprintf(text_buffer + count, "IO Expander PCF8574"); break; case 0xA: count += sprintf(text_buffer + count, "FRAM FM24CL16B"); break; default: count += sprintf(text_buffer + count, "unknown"); } int addrPins = (addr & 0xf) >> 1; int rw = (addr & 1); count += sprintf(text_buffer + count, " addr: %s %s", binary_fmt(addrPins, binary_buffer), rw ? "read" : "write"); return text_buffer; } void findDevices(void) { pc.printf("Scanning for devices ..\n"); for(int i=0; i<256; i++) { if(i2c.write(i, NULL, 0, 0) == 0){ printf("Device %s is present: %s\n", binary_fmt(i, binary_buffer), getDeviceName(i)); //printf("Device %i present\n", i); } // else // printf("Device %i not present\n", i); } } int main() { while (1) { findDevices(); wait(1.0); } }