nobcha23の日記

PICマイコンやArduinoを使う電子回路遊びを紹介します

アルディーノでi2cアドレススキャン

さて、ちびでぃーの2にi2cデバイスを繋ぎます。しかし動きません。おかしいな・・・。
こういうときはオシロを出す前にアドレススキャンですね。
ということでお勉強も兼ねて急遽作りました。

ちびでぃーの2フルセット接続のLCDにスキャンして検出したアドレスを表示します。

ストリナのLCDをつないで0x3Eを出すのに苦労しました。

原因はちびでぃーの2基板のアナログ信号ブレイクアウト用コネクタでした。
隣に予備ランドが有り、そこまでコネクタを半田付けしてしまったのです。
1ピン余計だったのに気が付かず、端と次の端子がSCLとSDAと思っていたのが大間違いでした。


次のようなスケッチになりました。呼び込むのはWireLCDライブラリです。

// 
// nobcha's i2c scanning 
// 
// The circuit for chibiduino 2:
//* LCD RS pin to digital pin 5
//* LCD Enable pin to digital pin 6
//* LCD D4 pin to digital pin 9
//* LCD D5 pin to digital pin 10
//* LCD D6 pin to digital pin 11
//* LCD D7 pin to digital pin 12
//* LCD R/W pin to ground
//* 5k-ohm volume
//* ends to +5V and ground
//* wiper to LCD VO pin (pin 3)
//
// 2013.04.25 nobcha
//
//

// include the library codes:
#include <Wire.h>
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(5, 6, 9, 10, 11, 12);

// scanning i2c address
void i2c_scan(byte start_ad, byte end_ad)
{
   char    test_ad;    // Tested i2c address
   byte    dummy;      // Dummy
   byte    detect;     // Detect address
// Open i2c service
   Wire.begin();
// i2c address scan, start_ad to end_ad
   for (test_ad = start_ad; test_ad <= end_ad; test_ad ++)
   {
       Wire.beginTransmission(test_ad);
       Wire.write(&dummy, 0);
       detect = Wire.endTransmission();
// i2c module detected 
       if (detect == 0)
       {
          lcd.setCursor(0, 1);
          lcd.print("i2c ack ad = ");
          lcd.print(test_ad, HEX);
          delay(500); 
       }
    }
}
 
void setup()
{
// set up the LCD's number of columns and rows:
   lcd.begin(20, 2);
// Print a message to the LCD.
   lcd.print("i2c ad scan ");
}
 
void loop()
{
   lcd.setCursor(12, 0); 
   lcd.print("    ");
   digitalWrite(13,HIGH);
   delay(500); 
//  00000xxx & 11111xxx are reserved    
   i2c_scan(8, 0x78);
   lcd.setCursor(12, 0); 
  
   lcd.print(" end");

   digitalWrite(13,LOW);
   delay(1000);
}


WEBでうろうろしていたら、アドレススキャンの結果をUSBポートに出力するスケッチがありました。LCDを繋がなくて良い分取っ付きが良いかと思います。
http://www.gvc-on.net/?page_id=123