ESP32 Arduino I2C Slave 的例子

2023-04-095959
AI 快速预览详细 收起
本文介绍了如何使用ESP32作为I2C从设备的示例代码。通过Wire库,ESP32可以加入I2C总线并处理来自主设备的数据接收和请求。示例代码中注册了数据接收和请求的事件处理器,确保数据正确传输。通过该代码,您可以轻松实现ESP32与主设备之间的数据传输,解决I2C通信中的问题,节省调试时间。
Arduino 作为 I2C Slave 算是比较冷门的使用方式,下面是一个经过测试能够在 ESP32 下使用的例子:
  1. #include <Wire.h>
  2. byte i2c_rcv=0;               // data received from I2C bus
  3. void setup() {
  4.   Wire.begin(0x08);           // join I2C bus as Slave with address 0x08
  5.   // event handler initializations
  6.   Wire.onReceive(dataRcv);    // register an event handler for received data
  7.   Wire.onRequest(dataRqst);   // register an event handler for data request
  8.   Serial.begin(115200);
  9. }
  10. void loop() {
  11. }
  12. //received data handler function
  13. void dataRcv(int numBytes) {
  14.   Serial.print("Slave Received ");
  15.   Serial.print(numBytes);
  16.   Serial.println("Bytes");
  17.   while (Wire.available()) { // read all bytes received
  18.     i2c_rcv = Wire.read();
  19.     Serial.print("[");
  20.     Serial.print(i2c_rcv);
  21.     Serial.print("]");
  22.   }
  23.   Serial.println("");
  24. }
  25. // requests data handler function
  26. void dataRqst() {
  27.     Wire.write(i2c_rcv); // send potentiometer position
  28.     Serial.print("Slave send ");
  29.     Serial.print(i2c_rcv,HEX);
  30. }
复制代码

运行之后,Arduino作为一个地址为 0x08 I2C设备。当它收到 Master 发送过来的数据,会进入 void dataRcv(int numBytes)  函数,然后将收到的数据输出到串口上;当它收到 Master 发送的读请求,会进入voiddataRqst() 函数,将之前收到的数据返回给 Master
试验使用 Leonardo 板子,使用调试器发送 10 17 表示对 0x08 地址的设备发送 0x17,之后调试器发送 11 01 表示从 0x08 设备读取一字节数据:

ESP32 Arduino I2C Slave 的例子图1

ESP32 Arduino I2C Slave 的例子图2


创作许可协议

本项目采用 None(不开放任何权利,保留所有权利) 进行许可。

评论(0)
- 没有更多了 -