连接测试
ESP32 默认I2C引脚是21(SDA),22(SCL)
完成连接后可以先运行I2C扫描程序,查看是否连接与I2C地址
#include <Arduino.h>
#include <Wire.h>
void i2cScan(void) {
// Wire.setPins(23, 18); // 此处可以改为自定义SDA和SCL
Wire.begin();
Serial.println("\nI2C Scanner");
for (;;) {
byte error, address;
int nDevices;
Serial.println("Scanning...");
nDevices = 0;
for (address = 1; address < 127; address++) {
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0) {
Serial.print("I2C device found at address 0x");
if (address < 16) {
Serial.print("0");
}
Serial.println(address, HEX);
nDevices++;
} else if (error == 4) {
Serial.print("Unknow error at address 0x");
if (address < 16) {
Serial.print("0");
}
Serial.println(address, HEX);
}
}
if (nDevices == 0) {
Serial.println("No I2C devices found\n");
} else {
Serial.println("done\n");
}
delay(5000);
}
}
void setup() {
Serial.begin(115200);
i2cScan();
}
void loop() { delay(1000); }
基础使用
- 引用 Wire 库
- 直接使用创建好的 Wire/Wire1 对象
- Wire初始化
- 开始传输
- 写入传输内容
- 结束传输
#include <Arduino.h>
#include <Wire.h>
static constexpr uint8_t I2C_ADDRESS = 0x68;
void setup() {
Serial.begin(115200);
Wire.begin();
Wire.beginTransmission(I2C_ADDRESS);
Wire.write(0x00); // 写入需要的值
auto ret = Wire.endTransmission();
Serial.println(ret);
/**
* 0: 成功
* 1: 数据过长,超出发送缓存
* 2: 在地址发送时接收到NACK
* 3: 在数据发送时接收到NACK
* 4: 其他错误
* 5: 发送超时
*/
}
void loop() { delay(1000); }
器件通信测试
先使用上方的扫描程序直接扫出地址,或是阅读数据手册来获取7位的I2C从机地址。
注:ESP32的I2C使用通信地址是直接填入7位的地址,例如

Comments NOTHING