简介
基于 BearPi Std 板从入门到放弃 - 引气入体篇(5)(printf打印到串口), 通过I2C接口,读取光照强度并打印到串口;
开发板 : Bearpi Std(小熊派标准板)
主芯片: STM32L431RCT6
LED : PC13 \ 推挽输出即可 \ 高电平点亮
串口: Usart1
I2C : I2C1
光照强度传感器:BH1750
步骤
- 基于上一篇BearPi Std 板从入门到放弃 - 引气入体篇(5)(printf打印到串口) 所讲工程新增I2C1配置
- I2C1配置
保持默认设置即可 - 生成项目工程 BearPi_I2C1
- Keil打开项目, 加入用户代码
float ReadBH1750(void);int main(void)
{float lux = 0.0;...while (1){HAL_Delay(1000);lux = ReadBH1750();printf("current lux : %0.3f\r\n", lux);}
}/* USER CODE BEGIN 4 */
float ReadBH1750(void)
{uint8_t temp[1]={0x11};float lux=0;uint8_t ReadData[2]={0};HAL_I2C_Master_Transmit(&hi2c1, 0x46, temp, 1, 0xff);HAL_Delay(180);HAL_I2C_Master_Receive(&hi2c1, 0x47,ReadData, 2, 0xff);lux = (float)((ReadData[0]<<8)|ReadData[1]);lux /= 1.2;return lux;
}
/* USER CODE END 4 */
小扩展
简单加上一个范围判定, 大于此范围则LED自动亮起, 否则LED熄灭
/*** @brief The application entry point.* @retval int*/
int main(void)
{/* USER CODE BEGIN 1 */float lux = 0.0;uint32_t threshold = 3500;uint32_t luxTemp = 0;/* USER CODE END 1 */.../* Infinite loop *//* USER CODE BEGIN WHILE */while (1){/* USER CODE END WHILE *//* USER CODE BEGIN 3 */HAL_Delay(1000);lux = ReadBH1750();luxTemp = (uint32_t)(lux * 100);printf ("current lux : %0.3f\r\n", lux);if (luxTemp <= threshold){if (HAL_GPIO_ReadPin(USER_LED_GPIO_Port, USER_LED_Pin) == GPIO_PIN_RESET){printf ("led's on!\r\n");HAL_GPIO_WritePin(USER_LED_GPIO_Port, USER_LED_Pin, GPIO_PIN_SET);}}else{if (HAL_GPIO_ReadPin(USER_LED_GPIO_Port, USER_LED_Pin) == GPIO_PIN_SET){printf ("led's off!\r\n");HAL_GPIO_WritePin(USER_LED_GPIO_Port, USER_LED_Pin, GPIO_PIN_RESET);}}}/* USER CODE END 3 */
}
前言后说
-
I2C发送接收函数
HAL_I2C_Master_Transmit(I2C_HandleTypeDef hi2c, uint16_t DevAddress, uint8_tpData,uint16_t Size, uint32_t Timeout);
HAL_I2C_Master_Receive(I2C_HandleTypeDef hi2c, uint16_t DevAddress, uint8_tpData,uint16_t Size, uint32_t Timeout); -
光照传感器说明
a. 读地址为0X47,写地址为0X46;
b. 连续高分辨率模式 : 精度1lux/指令 0x10 / 测量时间 120ms ~ 180ms
连续高分辨率模式2 : 精度 0.5lux /指令 0x11 / 测量时间120ms ~ 180ms
低分辨率模式 : 精度4lux / 指令 0x13/ 测量时间 16ms ~ 24ms
c. 数据手册记录光照强度计算公式 = (Vhi << 8 | Vlo)/1.2
d. 本次采用 连续高分辨率模式2
BearPi_I2C1 完整项目