2 I2C scanner examples for the micro:bit
The micro:bit has 2 I2C devices the accelerometer and magnetometer. the address of the devices are as follows
Device | I2C Address |
---|---|
Accelerometer | 0x1D |
Magnetometer (compass) | 0x0E |
Now you can also connect I2C devices to your micro:bit and sometimes you need to check the address of the device or this can also be used as a useful debug tool to make sure your device is detected.
There are 2 ways of doing this here, the first is in python using the mu editor and the next one is using an Arduino
Code
[codesyntax lang=”python”]
from microbit import * start = 0x07 end = 0x70 while True: display.show(Image.ARROW_W) if button_a.was_pressed(): display.show(Image.SMILE) print("Scanning I2C bus...") for i in range(start, end + 1): try: i2c.read(i, 1) except OSError: pass else: print("Found: [%s]" % hex(i)) print("Scanning complete") sleep(10)
[/codesyntax]
Now look at the REPL
>>> Scanning I2C bus…
Found: [0xe]
Found: [0x1d]
Scanning complete
Magnetometer [0x0e] Accelerometer [0x1d]
Now for the Arduino version
[codesyntax lang=”cpp”]
#include <Wire.h> void setup() { Wire.begin(); Serial.begin(9600); Serial.println("\nI2C Scanner"); } void loop() { byte error, address; int nDevices; Serial.println("Scanning..."); nDevices = 0; for(address = 1; address < 127; address++ ) { Wire.beginTransmission(address); error = Wire.endTransmission(); if (error == 0) { Serial.print("I2C device found at address 0x"); if (address<16) Serial.print("0"); Serial.print(address,HEX); Serial.println(" !"); nDevices++; } else if (error==4) { Serial.print("Unknown error at address 0x"); if (address<16) Serial.print("0"); Serial.println(address,HEX); } } if (nDevices == 0) Serial.println("No I2C devices found\n"); else Serial.println("done\n"); delay(5000); // wait 5 seconds for next scan }
[/codesyntax]
Open the serial monitor and you should see something like this
Scanning…
I2C device found at address 0x0E !
I2C device foun!
I2C device found at address 0x1D !
done