以I2C为接口的设备很多,比如温湿度传感器中有很多器件就是使用I2C接口的,又如I2C接口的OLED。本次实验,编程使用树莓派Pico开发板,检测连接的I2C设备的访问地址。
树莓派Pico开发板本身提供了两组I2C外设,可以映射到一下的引脚组合中,

本次实验使用GPIO0、GPIO1来测试。测试对象为I2C接口的OLED,已知该OLED的I2C地址为0x3C。连接如下:

代码如下
#include <Wire.h> // 包含I2C库
/**
使用说明
将上述代码上传到Pico开发板
打开串口监视器,波特率设置为115200
程序会每5秒扫描一次I2C总线并显示发现的设备地址
Pico的I2C引脚:默认引脚:SDA = GPIO0, SCL = GPIO1,或者SDA = GPIO2, SCL = GPIO3
*/
#define LCD_RESET 4
#define LCD_SCL 1
#define LCD_SDA 0
void setup() {
Serial.begin(115200); // 初始化串口通信
while (!Serial); // 等待串口连接(仅对某些开发板需要)
Serial.println("\nI2C Scanner");
delay(5000);
pinMode(LCD_RESET, OUTPUT);
digitalWrite(LCD_RESET, LOW);
delay(100);
digitalWrite(LCD_RESET, LOW);
delay(100);
Wire.setSDA(LCD_SDA);
Wire.setSCL(LCD_SCL);
Wire.begin();
//Wire1.setSDA(2);
//Wire1.setSCL(3);
//Wire1.begin(0x30);
//Wire1.onReceive(recv);
//Wire1.onRequest(req);
}
void loop() {
byte error, address;
int nDevices = 0;
Serial.println("Scanning I2C bus...");
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.print(address, HEX);
Serial.println();
nDevices++;
} else if (error == 4) {
Serial.print("Unknown 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("Scan completed\n");
}
delay(5000); // 每5秒扫描一次
}
测试结果:

与预想的一致。
我要赚赏金
