1335浏览
查看: 1335|回复: 0

[ESP8266/ESP32] ESP32 Arduino I2C Slave 的例子

[复制链接]
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


您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

为本项目制作心愿单
购买心愿单
心愿单 编辑
[[wsData.name]]

硬件清单

  • [[d.name]]
btnicon
我也要做!
点击进入购买页面
上海智位机器人股份有限公司 沪ICP备09038501号-4

© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed

mail