![](/media/cache/profiles/45364131_10156363599144681_3034524867140517888_n.jpg.50x50_q85.jpg)
finds I2C slaves on BUS
main.cpp@0:4241a76032ad, 2017-10-09 (annotated)
- Committer:
- andcor02
- Date:
- Mon Oct 09 09:50:19 2017 +0000
- Revision:
- 0:4241a76032ad
test and find I2C slaves on BUS
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
andcor02 | 0:4241a76032ad | 1 | //Credit to Paul Staron. https://os.mbed.com/questions/6129/I2C-Not-Working/ |
andcor02 | 0:4241a76032ad | 2 | |
andcor02 | 0:4241a76032ad | 3 | #include "mbed.h" |
andcor02 | 0:4241a76032ad | 4 | |
andcor02 | 0:4241a76032ad | 5 | #define I2C_SDA PF_0 |
andcor02 | 0:4241a76032ad | 6 | #define I2C_SCL PF_1 |
andcor02 | 0:4241a76032ad | 7 | |
andcor02 | 0:4241a76032ad | 8 | Serial pc(USBTX, USBRX); |
andcor02 | 0:4241a76032ad | 9 | |
andcor02 | 0:4241a76032ad | 10 | I2C i2c(I2C_SDA, I2C_SCL); // I2C device sda, scl |
andcor02 | 0:4241a76032ad | 11 | |
andcor02 | 0:4241a76032ad | 12 | |
andcor02 | 0:4241a76032ad | 13 | int main() { |
andcor02 | 0:4241a76032ad | 14 | i2c.frequency(10000); // set required i2c frequency |
andcor02 | 0:4241a76032ad | 15 | |
andcor02 | 0:4241a76032ad | 16 | pc.printf("I2C Searching!\n\n"); |
andcor02 | 0:4241a76032ad | 17 | pc.printf("Starting....\n\n"); |
andcor02 | 0:4241a76032ad | 18 | |
andcor02 | 0:4241a76032ad | 19 | while (1) { |
andcor02 | 0:4241a76032ad | 20 | int count = 0; |
andcor02 | 0:4241a76032ad | 21 | for (int address=0; address<256; address+=2) { |
andcor02 | 0:4241a76032ad | 22 | if (!i2c.write(address, NULL, 0)) { // 0 returned is ok |
andcor02 | 0:4241a76032ad | 23 | pc.printf("I2C address 0x%02X\n", address); |
andcor02 | 0:4241a76032ad | 24 | count++; |
andcor02 | 0:4241a76032ad | 25 | } |
andcor02 | 0:4241a76032ad | 26 | } |
andcor02 | 0:4241a76032ad | 27 | pc.printf("%d devices found\n\n\n", count); |
andcor02 | 0:4241a76032ad | 28 | wait(2); |
andcor02 | 0:4241a76032ad | 29 | } |
andcor02 | 0:4241a76032ad | 30 | } |