2016年5月13日 星期五

Arduino - I2C

有在玩控制板的人,應該很常聽到I2C(Inter-Integrated Circuit)這個名詞吧?!

I2C,也有人稱為二線式介面(TWI,Two-Wire Interface),因為它只需要兩根Pin就能和其它支援I2C的元件進行通訊。此兩根Pin(SDA資料線和SCL時脈線)在標準的Arduino和Arduino Mega上,被定義的腳位不同:

  • 標準的Arduino:
    SDA -- Pin A4
    SCL -- Pin A5
  • Arduino Mega:
    SDA -- Pin 20
    SCL -- Pin 21
Arduino要使用I2C進行通訊,通常是透過"Wire"這個Library。在官網上看到一個簡單有趣,而且很實用的範例。使用二塊Arduino互相通訊。

硬體的連線方式可參考官網上的這張圖:

很簡單的連接法,就是SDA接SDA,SCL接SCL,但記得要連接共同的接地。由於這個範例我們需要由電腦顯示接收和傳送的訊息,所以Master Arduino需透過USB與電腦連接。
在供電的部份,由於Master Arduino透過電腦USB提供5V的電來啟動,但Slave Arduino沒有額外5V電源來啟動,所以也需要拉一條5V的電源給Slave Arduino。

程式碼如下:

<< Master Arduino >>

//     =========     //
//     Master Arduino
//     程式碼開始
//     =========     //

#include <Wire.h>

void setup()
{
     Wire.begin(); // join i2c bus (address optional for master)
}

byte x = 0;

void loop()
 {
     Wire.beginTransmission(8); // transmit to device #8
     Wire.write("x is "); // sends five bytes
     Wire.write(x); // sends one byte
     Wire.endTransmission(); // stop transmitting

     x++;
     delay(500);
}

//     =========     //
//     程式碼結尾     //
//     =========     //


<< Slave Arduino >>

//     =========     //
//     Slave Arduino
//     程式碼開始
//     =========     //

#include <Wire.h>

void setup()
{
     Wire.begin(8); // join i2c bus with address #8
     Wire.onReceive(receiveEvent); // register event
     Serial.begin(9600); // start serial for output
}

void loop()
{
     delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
     while (1 < Wire.available())
     { // loop through all but the last
          char c = Wire.read(); // receive byte as a character
          Serial.print(c); // print the character
     }
     int x = Wire.read(); // receive byte as an integer
     Serial.println(x); // print the integer
}

//     =========     //
//     程式碼結尾
//     =========     //



沒有留言:

張貼留言