I2C - 向Arduino UNO 发送资料

Introduction of I2C

I2C里有两个角色,一个是Master,另一个是Slave。 Master的角色只能有一个,而Slave可以有很多个。每个Slave都有自己的位址(address)编号,所以当Master要与特定的Slave沟通时,就会使用这个位址。I2C使用了两根接脚,一根是资料线 (SDA),另一根是时脉线 (SCL)。 Master藉由控制SCL让Slave知道有东西要传,而资料就可以在SDA上面传送。I2C在当初Arduino的范例里,为了亲易近人而称呼I2C为Wire。

材料准备

  • AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1

  • Arduino UNO x 1

范例说明

In this example, we use Ameba as the I2C master writer, and use Arduino as the I2C slave receiver. When the I2C slave receives string sent from I2C master, it prints the received string.

Setting up Arduino Uno to be I2C Slave

First, select Arduino in the Arduino IDE in “Tools” “Board” “Arduino Uno” Open the “Slave Receiver” example in “Examples” “Wire” “slave_receiver”:

../../../../_images/image156.png

Then click “Sketch” “Upload” to compile and upload the example to Arduino Uno.

Setting up Ameba to be I2C Master

Next, open another window of Arduino IDE, make sure to choose your Ameba development board in the IDE: “Tools” “Board” Then open the “Master Writer” example in “File” “Examples” “AmebaWire” “MasterWriter”

../../../../_images/image252.png

接线

The Arduino example uses A4 as the I2C SDA and A5 as the I2C SCL. Another important thing is that the GND pins of Arduino and Ameba should be connected to each other.

AMB21 / AMB22 的接线图如下:

../../../../_images/image334.png

AMB23 的接线图如下:

../../../../_images/image3-15.png

BW16 的接线图如下:

../../../../_images/image3-35.png

BW16-TypeC Wiring Diagram:

../../../../_images/image3-42.png

Open the Arduino IDE of the Arduino Uno and open the serial monitor (“Tools” → “Serial Monitor”). In the Serial Monitor, you can see the messages printed from Arduino Uno. Next, press the reset button on Arduino Uno. Now the Arduino Uno is waiting for the connection from I2C Master. We press the reset button on Ameba to start to send messages. Then observe the serial monitor, you can see the messages show up every half second.

../../../../_images/image426.png

程式码说明

You can find detailed information of this example in the documentation of Arduino: https://www.arduino.cc/en/Tutorial/MasterWriter

First use Wire.begin()/Wire.begin(address) to join the I2C bus as a master or slave, in the Master case the address is not required. https://www.arduino.cc/en/Reference/WireBegin

Next, the Master uses Wire.beginTransmission(address) to begin a transmission to the I2C slave with the given address: https://www.arduino.cc/en/Reference/WireBeginTransmission

Uses Wire.write() to send data, and finally use Wire.endTransmission() to end a transmission to a Slave and transmits the bytes that were queued: https://www.arduino.cc/en/Reference/WireEndTransmission