开发环境
单片机:STM32F103C8T6
光照度传感器:BH1750
IDE:KEIL+STM32CUBEMX
单片机配置
1、STM32CUBEMX
BH1750代码
1、头文件
/*
*************************************************
BH1750
光照数据计算(LUX)
LUX = 读取数据/1.2
例如:
读取值为0x56,0x78
LUX = 0X5678 / 1.2 = 22136/1.2 = 18447
*************************************************
*/
#ifndef __BH1750_H
#define __BH1750_H
#include "main.h"
#define BH1750_PORT hi2c2 /*使用端口*/
#define BH1750_ADDRESS 0x46 /*ADDRESS引脚接地时地址为0x46,接电源时地址为0xB8*/
#define BH1750_POW_OFF 0X00
#define BH1750_POW_ON 0X01
#define BH1750_POW_RST 0X07
#define BH1750_CONT_HI_RSLT_1 0X10 /*连续测量,1lx精度开始测量,周期120ms*/
#define BH1750_CONT_HI_RSLT_2 0X11 /*连续测量,0.5lx精度开始测量,周期120ms*/
#define BH1750_CONT_LOW_RSLT 0X13 /*连续测量,4lx精度开始测量,周期16ms*/
#define BH1750_ONE_HI_RSLT_1 0X20 /*一次测量,1lx精度开始测量,周期120ms,测量完后自动进入POWER DOWN*/
#define BH1750_ONE_HI_RSLT_2 0X21 /*一次测量,0.5lx精度开始测量,周期120ms,测量完后自动进入POWER DOWN*/
#define BH1750_ONE_LOW_RSLT 0X23 /*一次测量,4lx精度开始测量,周期16ms,测量完后自动进入POWER DOWN*/
HAL_StatusTypeDef BH1750_Init(void);
HAL_StatusTypeDef BH1750_WriteOpecode(uint8_t* pData, uint16_t size);
HAL_StatusTypeDef BH1750_ReadData(uint8_t* pData, uint16_t size);
#endif
2、C文件
#include "bh1750.h"
#include "i2c.h"
HAL_StatusTypeDef BH1750_Init(void)
{
uint8_t opecode = 0x01;
return (BH1750_WriteOpecode(&opecode, 1));
}
/*
*************************************************
功能:写BH1750操作码到芯片,控制模式
*************************************************
*/
HAL_StatusTypeDef BH1750_WriteOpecode(uint8_t* pData, uint16_t size)
{
HAL_StatusTypeDef status = HAL_OK;
status = HAL_I2C_Master_Transmit(&BH1750_PORT, BH1750_ADDRESS,pData, size, 1);
return status;
}
/*
*************************************************
功能:读取BH1750的数据,存放到pData中
*************************************************
*/
HAL_StatusTypeDef BH1750_ReadData(uint8_t* pData, uint16_t size)
{
HAL_StatusTypeDef status = HAL_OK;
status = HAL_I2C_Master_Receive(&BH1750_PORT, BH1750_ADDRESS+1,pData, size, 1);
return status;
}
3、主函数操作BH1750
/* USER CODE BEGIN 2 */
BH1750_Init(); /*初始化BH1750,上电*/
opeCode= BH1750_CONT_HI_RSLT_1; /*配置工作模式为连续高分辨率转换,1lx精度,120ms转换周期*/
BH1750_WriteOpecode(&opeCode,1);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
HAL_Delay(200);
BH1750_ReadData(g_ucaDataBuff,2);/*获取照度数据*/
ftmp = (g_ucaDataBuff[0]<<8 | g_ucaDataBuff[1]) / 1.2f + 0.5f;/*转换照度数据*/
g_usLux = (uint16_t)ftmp;
HAL_Delay(500);
}
/* USER CODE END 3 */