I2Cスキャナーを作ってみよう
I2Cには各デバイスにアドレスがあることを知っていますか?
アドレスというのはそのデバイスの住所です。
ライブラリを使っているとアドレスがあるということすら忘れますが、実はすごく大切です。
I2Cデバイスがつながらないな。おかしいなという時のために、I2Cのスキャナを作っていきましょう。
用途
I2Cのデバイスの配線をつないでうまく動かないとき。なにかデータがおかしいとき。
I2Cのアドレスを0からFFまでスキャンすればいいだけです。
#include <Wire.h>
int nDevices = 0;
void setup()
{
Wire.begin();
Serial.begin(115200);
while (!Serial); // Leonardo: wait for serial monitor
Serial.println("\nI2C Scanner");
}
void loop()
{
byte error, address;
if(nDevices != 0)
return;
Serial.println("I2C device Scanning...");
for(address = 1; address < 0xff; address++ )
{
// The i2c_scanner uses the return value of
// the Write.endTransmisstion to see if
// a device did acknowledge to the address.
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0)
{
Serial.print("Found at 0x");
if (address<16)
Serial.print("0");
Serial.println(address,HEX);
nDevices++;
}
else if (error == 2)
{
//2は最初のほうでエラーで返ってきます
}
else if (error == 4)
{
//ないものを表示したくない場合はここらへんをコメントアウト
Serial.print("Unknown error at address 0x");
if (address < 0xf)
Serial.print("0");
Serial.println(address,HEX);
}
}
if (nDevices == 0)
{
nDevices = -1;
Serial.println("No I2C devices found\n");
}
else
{
Serial.print(nDevices);
Serial.println(" found. done\n");
}
}



