设置I2C通信

如何解决设置I2C通信

我试图在STM32F466RE板上的两个Adafruit TOF传感器VL6180X之间建立I²C通信。我正在使用cubeMX和VS代码,并且还可以使用ST website的x-nucleo-6180xa1上的VL6180X API进行帮助,因此我想对其进行设置,以便可以分别测试两个传感器。到目前为止,我仅成功测量了一个传感器,但是当我尝试将两个传感器都连接到SHDN到STM32F466RE核上的GPIO时,却遇到了问题。我正在尝试管理一些主从操作,但是我是新手,没人知道怎么做吗?

我正在寻找的是示例代码,因此我可以看到它是如何实现的。这不是生产运行,而是供家庭使用。要在这两个TOF传感器上进行管理,我一直找不到要研究的代码。

那是我的主要代码:

/* Private variables ---------------------------------------------------------*/
I2C_HandleTypeDef hi2c1;

UART_HandleTypeDef huart2;

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_I2C1_Init(void);
static void MX_USART2_UART_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

void WaitMilliSec(int ms);

VL6180xDev_t theVL6180xDev;
struct MyVL6180Dev_t BoardDevs[2] = { 
                                        [0]= { .DevID = 0 },[1]= { .DevID = 1 } 
                                    };

VL6180xDev_t theVL6180xDev = &BoardDevs[0];

/**
 * VL6180x CubeMX F401 multiple device i2c implementation
 */

#define i2c_bus      (&hi2c1)
#define def_i2c_time_out 100

int VL6180x_I2CWrite(VL6180xDev_t dev,uint8_t *buff,uint8_t len) {
    int status;
    status = HAL_I2C_Master_Transmit(i2c_bus,dev->I2cAddr,buff,len,def_i2c_time_out);
    if (status) {
        HAL_I2C_MspInit(&hi2c1);
    }
    return status? -1 : 0;
}

int VL6180x_I2CRead(VL6180xDev_t dev,uint8_t len) {
    int status;
    status = HAL_I2C_Master_Receive(i2c_bus,def_i2c_time_out);
    if (status) {
        HAL_I2C_MspInit(&hi2c1);
    }

    return status? -1 : 0;
}

void WaitMilliSec(int ms) {
    HAL_Delay(ms); /* it's milli sec  cos we do set systick to 1KHz */
}

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */
  #define MAX_DEV 1
  VL6180x_RangeData_t Range[MAX_DEV];

  int status;
  int i;
  int n_dev=1;
  int PresentDevMask;
  int nPresentDevs;
  int PresentDevIds[MAX_DEV];
  int nReady;
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals,Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_I2C1_Init();
  MX_USART2_UART_Init();
  /* USER CODE BEGIN 2 */
  
  /* detect presence and initialize devices i2c address  */
    /*set device i2c address for dev[i] = 0x52+(i+1)*2 */
    PresentDevMask = 0;
    nPresentDevs = 0;
    //strcpy(DisplayStr,"TLBR");
    for (i = 0; i <= n_dev; i++){
        int FinalI2cAddr;
        uint8_t id;
        /* unreset device that wake up at default i2c addres 0x52 */
        WaitMilliSec(2);    /* at least 400usec before to acces device */
        BoardDevs[i].I2cAddr = 0x52;
        /* to detect device presence try to read it's dev id */
        status = VL6180x_RdByte(&BoardDevs[i],IDENTIFICATION_MODEL_ID,&id);
        if (status) {
            /* these device is not present skip init and clear it's letter on string */
            BoardDevs[i].Present = 0;
            //DisplayStr[i]=' ';
            continue;
        }

        /* device present only */
        BoardDevs[i].Present = 1;
        PresentDevMask |= 1 << i;
        PresentDevIds[nPresentDevs]=i;
        nPresentDevs++;
        status = VL6180x_InitData(&BoardDevs[i]);

        FinalI2cAddr = 0x52 + ((i+1) * 2);
        if (FinalI2cAddr != 0x52) {
            status = VL6180x_SetI2CAddress(&BoardDevs[i],FinalI2cAddr);
            if( status ){
                //HandleError("VL6180x_SetI2CAddress fail");
            }
            BoardDevs[i].I2cAddr = FinalI2cAddr;
        }

        WaitMilliSec(1);
        status = VL6180x_RdByte(&BoardDevs[i],&id);
        WaitMilliSec(1);
        status= VL6180x_Prepare(&BoardDevs[i]);
        if( status<0 ){
            //HandleError("VL6180x_Prepare fail");
        }
        /* Disable Dmax computation */
        VL6180x_DMaxSetState(&BoardDevs[i],0);
    }
    
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    
    
    VL6180xDev_t dev;
    /*
    VL6180x_RangePollMeasurement(dev,&Range[0]);
    HAL_Delay(20);
    */
        // kick off measure on all device 
        for( i=0; i<nPresentDevs; i++){

            dev =  BoardDevs + PresentDevIds[i];
            //TODO: GPIO enamble of pa11
            status = VL6180x_RangeStartSingleShot(dev);
            if( status<0 ){
                //HandleError("VL6180x_RangeStartSingleShot fail");
            }
            dev->Ready=0;
        }
        // wait for all present device to have a measure  
        nReady=0;
        do{
            //DISP_ExecLoopBody();
            for( i=0; i<nPresentDevs; i++){
                dev =  BoardDevs + PresentDevIds[i];
                if( !dev->Ready ){
                    status = VL6180x_RangeGetMeasurementIfReady(dev,&Range[i]);
                    if( status == 0 ){
                        if(Range[i].errorStatus == DataNotReady)
                            continue;
                        // New measurement ready 
                        dev->Ready=1;
                        nReady++;
                    } else {
                        //HandleError("VL6180x_RangeStartSingleShot fail");
                    }
                }
            }
        }
        while( nReady<nPresentDevs);
        
      

    /* USER CODE END WHILE */
   
    
    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

...

解决方法

我进入这类问题的方式如下。

  • 从任何来源下载该传感器的Arduino库。 here
  • 仔细阅读源文件,找出在哪里可以使用i2c通信的核心功能。
  • 修改该核心功能以适合您的任务。(执行适当的i2c调用)
  • 将修改后的头文件和源文件包含到您的项目中并使用它们。
,

我解决了我的问题。如您所知,要使一些Adafruit TOF VL6180X传感器协同工作,必须将它们的SHDN连接到板上的GPIO。实际上缺少的是所有传感器的RESET和这些传感器的SET及其地址。寻找解决方案时遇到的问题之一是命令的顺序。重要的是要注意,我们首先将所有传感器复位,然后在分配它们的地址后复位。如果您也有兴趣,可以附加对代码的更正。您可以在依赖于循环中变量i的代码中看到if查询,以便将两个传感器分开。我这样做是为了找到特定的组件。有一种更聪明的方法,只是为了了解命令的顺序。

在评论中查看我的解决方案:

<<<<-------------------------RESET-----

<<<<-------------------------SET-----

/* USER CODE BEGIN PV */
// global vars only for debugging with STMStudio
VL6180x_RangeData_t Range[MAX_DEV];
VL6180x_RangeData_t RangeDB1;
VL6180x_RangeData_t RangeDB2;

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_I2C1_Init(void);
static void MX_USART2_UART_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

void WaitMilliSec(int ms);

VL6180xDev_t theVL6180xDev;
struct MyVL6180Dev_t BoardDevs[MAX_DEV] = { 
                                        [0]= { .DevID = 0 },[1]= { .DevID = 1 },};

VL6180xDev_t theVL6180xDev = &BoardDevs[0];


/**
 * VL6180x CubeMX F401 multiple device i2c implementation
 */

#define i2c_bus      (&hi2c1)
#define def_i2c_time_out 100


int VL6180x_I2CWrite(VL6180xDev_t dev,uint8_t *buff,uint8_t len) {
    int status;
    status = HAL_I2C_Master_Transmit(i2c_bus,dev->I2cAddr,buff,len,def_i2c_time_out);
    if (status) {
        HAL_I2C_MspInit(&hi2c1);
    }
    return status? -1 : 0;
}

int VL6180x_I2CRead(VL6180xDev_t dev,uint8_t len) {
    int status;
    status = HAL_I2C_Master_Receive(i2c_bus,def_i2c_time_out);
    if (status) {
        HAL_I2C_MspInit(&hi2c1);
    }

    return status? -1 : 0;
}

void WaitMilliSec(int ms) {
    HAL_Delay(ms); /* it's milli sec  cos we do set systick to 1KHz */
}



/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */
  

  int status;
  int i;
  int n_dev=2;
  int PresentDevMask;
  int nPresentDevs;
  int PresentDevIds[MAX_DEV];
  int nReady;
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals,Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  // here I put all my devices under reset <<<<-------------------------RESET----- 
  HAL_GPIO_WritePin(GPIOA,GPIO_PIN_11,GPIO_PIN_RESET);
  HAL_GPIO_WritePin(GPIOA,GPIO_PIN_12,GPIO_PIN_RESET);


  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_I2C1_Init();
  MX_USART2_UART_Init();
  /* USER CODE BEGIN 2 */


  /* detect presence and initialize devices i2c address  */
  /*set device i2c address for dev[i] = 0x52+(i+1)*2 */
  PresentDevMask = 0;
  nPresentDevs = 0;
  //strcpy(DisplayStr,"TLBR");
  for (i = 0; i <= n_dev - 1; i++) {
      int FinalI2cAddr;
      uint8_t id;
      // here I put all my devices under set <<<<-------------------------SET-----
      if (i==0){
        HAL_GPIO_WritePin(GPIOA,GPIO_PIN_SET);
      }
      if (i==1){
        HAL_GPIO_WritePin(GPIOA,GPIO_PIN_SET);
      }
      /* unreset device that wake up at default i2c addres 0x52 */
      WaitMilliSec(2);    /* at least 400usec before to acces device */
      BoardDevs[i].I2cAddr = 0x52;
      /* to detect device presence try to read it's dev id */
      status = VL6180x_RdByte(&BoardDevs[i],IDENTIFICATION_MODEL_ID,&id);
      if (status) {
          /* these device is not present skip init and clear it's letter on string */
          /*we can add here some debug prints*/
          //BoardDevs[i].Present = 0;
          //DisplayStr[i]=' ';
          continue;
      }
      /* device present only */
      BoardDevs[i].Present = 1;
      PresentDevMask |= 1 << i;
      PresentDevIds[nPresentDevs]=i;
      nPresentDevs++;
      status = VL6180x_InitData(&BoardDevs[i]);

      FinalI2cAddr = 0x52 + ((i+1) * 2);
      if (FinalI2cAddr != 0x52) {
          status = VL6180x_SetI2CAddress(&BoardDevs[i],FinalI2cAddr);
          if( status ){
              //HandleError("VL6180x_SetI2CAddress fail");
          }
          BoardDevs[i].I2cAddr = FinalI2cAddr;
      }

      WaitMilliSec(1);
      status = VL6180x_RdByte(&BoardDevs[i],&id);
      WaitMilliSec(1);
      status= VL6180x_Prepare(&BoardDevs[i]);
      if( status<0 ){
          //HandleError("VL6180x_Prepare fail");
      }
      /* Disable Dmax computation */
      VL6180x_DMaxSetState(&BoardDevs[i],0);

    }
    
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    VL6180xDev_t dev;
    
    // kick off measure on all device 
    for( i=0; i<nPresentDevs; i++){
        dev =  BoardDevs + PresentDevIds[i];
        status = VL6180x_RangeStartSingleShot(dev);
        if( status<0 ){
            //TODO: print error : debug
        }
        dev->Ready=0;
    }

    // wait for all present device to have a measure  
    nReady=0;
    
    do{
        //DISP_ExecLoopBody();
        for( i=0; i<nPresentDevs; i++){
            dev =  BoardDevs + PresentDevIds[i];
            if( !dev->Ready ){
                status = VL6180x_RangeGetMeasurementIfReady(dev,&Range[i]);
                if (i==0)
                  RangeDB1 = Range[i];
                if (i==1)
                  RangeDB2 = Range[i];
                if( status == 0 ){
                    if(Range[i].errorStatus == DataNotReady)
                        continue;
                    // New measurement ready 
                    dev->Ready=1;
                    nReady++;
                } else {
                    //HandleError("VL6180x_RangeStartSingleShot fail");
                }
            }
        }
    }
    while( nReady<nPresentDevs);
    
    HAL_Delay(10);
      
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}


版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-