这些小活动你都参加了吗?快来围观一下吧!>>
电子产品世界 » 论坛首页 » 综合技术 » 基础知识 » 树莓派PICO在Arduino下的开发-----扫描I2C设备

共2条 1/1 1 跳转至

树莓派PICO在Arduino下的开发-----扫描I2C设备

专家
2026-04-24 22:42:00     打赏

以I2C为接口的设备很多,比如温湿度传感器中有很多器件就是使用I2C接口的,又如I2C接口的OLED。本次实验,编程使用树莓派Pico开发板,检测连接的I2C设备的访问地址。

树莓派Pico开发板本身提供了两组I2C外设,可以映射到一下的引脚组合中,

图片1.png

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

图片2.png

代码如下

#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秒扫描一次

}

测试结果:

图片3.png

与预想的一致。




关键词: 菜鸟学单片机     Pico     I2C    

院士
2026-04-26 14:49:56     打赏
2楼

谢谢分享,学习了。


共2条 1/1 1 跳转至

回复

匿名不能发帖!请先 [ 登陆 注册 ]