Arduino开发实例-两个Arduino之间I2C通信
两个Arduino之间I2C通信
有时,需要多个Arduino开发板协调工作,扩展I/O,因此多个开发板之间就需要相互通信。 Inter-Integrated Circuit简称I2C是其中一种解决方案。
I2C协议通常用于在相机和任何嵌入式电子系统中的主板上的组件之间进行通信。
在这里,我们将使用两个Arduino制作I2C总线。 我们将对一个主Arduino进行编程,以命令另一个从Arduino使其内置的LED闪烁一次或两次,具体取决于接收的值。

1、硬件准备
- Arduino UNO R3开发板两个及两根数据线
- 杜绑若干
- 笔记本电脑一台
2、硬件连接
- Arudino 连接电脑
- 两个Arduino的I2C连接如下:



2、软件准备
3、代码实现
I2C主机代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| #include <Wire.h> #define CMD_LED_ON 1 #define CMD_LED_OFF 0 void setup() { // 启动I2C总线总机模式 Wire.begin(); Serial.begin(115200); } void loop() { // 向设备地址为9的设备发送数据 Wire.beginTransmission(9); Wire.write(CMD_LED_ON); // 结束发送 Wire.endTransmission(); delay(1000); Wire.beginTransmission(9); Wire.write(CMD_LED_ON); Wire.endTransmission(); delay(1000); }
|
I2C从机代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| #include <Wire.h> int x = 0; #define CMD_LED_ON 1 #define CMD_LED_OFF 0 void setup() { // 定义LED pinMode (LED_BUILTIN , OUTPUT); // 启动I2C总线从模式,地址为9 Wire.begin(9); // 接到数据的回调函数 Wire.onReceive(receiveEvent); Serial.begin(115200); } // 数据接收回调函数 void receiveEvent(int bytes) { x = Wire.read(); // read one character from the I2C } void loop() { if (x == CMD_LED_OFF) { Serial.println("led off"); digitalWrite(LED_BUILTIN,LOW); } if (x == CMD_LED_ON) { Serial.println("led on"); digitalWrite(LED_BUILTIN,HIGH); } }
|
I2C的主机模式和从机模式的代码主要使用了Wire库。
当主机需要向从机请求数据里,可以添加如下代码:
I2C主机代码:
1 2 3 4 5 6 7 8 9 10
| // 向从机请求数据 Wire.beginTransmission(SLAVE_ADDRESS); Wire.requestFrom(SLAVE_ADDRESS, DATA_SIZE); if (Wire.available()) { Serial.print("Data returned: "); while (Wire.available()) Serial.print((char) Wire.read()); Serial.println(); } Wire.endTransmission();
|
I2C从机代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #define SLAVE_ADDRESS 0x12 void requestEvent() { switch (x) { case CMD_LED_OFF: Wire.write("led off",SLAVE_ADDRESS); break; case CMD_LED_ON: Wire.write("led on",SLAVE_ADDRESS); break; default: Wire.write("nothing",SLAVE_ADDRESS); } }
|
同时在从机的setup函数中添加如下代码:
1 2
| Wire.onRequest(requestEvent);
|
关于I2C的通信原理,在这里就不做详细描述了。
文章来源: https://iotsmart.blog.csdn.net/article/details/114486466
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!