概要
基于STM32F1读取MPL3115大气压
整体架构流程
数据手册中对0x26地址发送0xB9(10111001),即高度计模式,最短采样间隔512ms。若要读取气压值,修改发送数据为0x39(00111001)。
驱动代码
使用串口模拟IIC
/**
* @brief 写MPL3115
* @param [in] slaveAddr 从机地址
regAddr 寄存器地址
nBytes 读取数据数
[out] pData 读取数据
* @return void;
**/
static int WriteI2cMPL3115(uint8_t slaveAddr, uint8_t regAddr, uint32_t nBytes, uint8_t *pData, u8 channel)
{
u8 i = 0;
u8 ack = 0;
/* IIC开始 */
Start_IIC(channel);
/* 发送从地址 */
IIC_Send_Byte((slaveAddr << 1) | IIC_WR, channel);
ack = IIC_Wait_Ack(channel);
if (ack != ACK)
{
Stop_IIC(channel);
return IIC_ERR;
}
/* 发送寄存器地址 */
IIC_Send_Byte(regAddr, channel);
ack = IIC_Wait_Ack(channel);
if (ack != ACK)
{
Stop_IIC(channel);
return IIC_ERR;
}
/* 发送寄存器数据地址 */
for (i = 0; i < nBytes; i++)
{
IIC_Send_Byte(pData[i], channel);
ack = IIC_Wait_Ack(channel);
if (ack != ACK)
{
Stop_IIC(channel);
return IIC_ERR;
}
}
Stop_IIC(channel);
return IIC_OK;
}
/**
* @brief 读SPL06
* @param [in] slaveAddr 从机地址
regAddr 寄存器地址
nBytes 读取数据数
[out] pData 读取数据
* @return void;
**/
static int ReadI2cMPL3115(uint8_t slaveAddr, uint8_t regAddr, uint32_t nBytes, uint8_t *pData, u8 channel)
{
u16 i = 0;
u8 ack = 0;
/* IIC开始 */
Start_IIC(channel);
/* 发送从地址 */
IIC_Send_Byte((slaveAddr << 1) | IIC_WR, channel);
ack = IIC_Wait_Ack(channel);
if (ack != ACK)
{
Stop_IIC(channel);
return IIC_ERR;
}
/* 发送寄存器地址 */
IIC_Send_Byte(regAddr, channel);
ack = IIC_Wait_Ack(channel);
if (ack != ACK)
{
Stop_IIC(channel);
return IIC_ERR;
}
/******************************************/
/* IIC开始 */
Start_IIC(channel);
/* 发送从地址 */
IIC_Send_Byte((slaveAddr << 1) | IIC_RD, channel);
ack = IIC_Wait_Ack(channel);
if (ack != ACK)
{
Stop_IIC(channel);
return IIC_ERR;
}
for (i = 0; i < nBytes; i++)
{
if (i != nBytes - 1)
{
pData[i] = IIC_Read_Byte(ACK, channel);
}
else
{
pData[i] = IIC_Read_Byte(NACK, channel);
}
}
Stop_IIC(channel);
return IIC_OK;
}
/**
* @brief 读取MPL3115气压
* @param *pressure 气压
* @return state;
**/
static u8 ReadMPL3115Press(float *pressure, u8 channel)
{
u8 regval = 0;
u8 msb = 0;
u8 csb = 0;
u8 lsb = 0;
int data = 0;
ReadI2cMPL3115(MPL3115_ADDR, STATUS, 1, ®val, channel);
if (regval & 0x08) {
ReadI2cMPL3115(MPL3115_ADDR, OUT_P_MSB, 1, &msb, channel);
ReadI2cMPL3115(MPL3115_ADDR, OUT_P_CSB, 1, &csb, channel);
ReadI2cMPL3115(MPL3115_ADDR, OUT_P_LSB, 1, &lsb, channel);
data = (int)msb << 16 | (int)csb << 8 | lsb;
*pressure = (float)data / 64;
return IIC_OK;
}
else {
return IIC_ERR;
}
}
/**
* @brief MPL3115初始化
* @param none
* @return state;
**/
u8 MPL3115DeviceInit(u8 channel)
{
u8 state = IIC_ERR;
u8 regval = 0;
regval = 0x38;
state = WriteI2cMPL3115(MPL3115_ADDR, CTRL_REG1, 1, ®val, channel);
regval = 0x07;
state = WriteI2cMPL3115(MPL3115_ADDR, PT_DATA_CFG, 1, ®val, channel);
regval = 0x39;
state = WriteI2cMPL3115(MPL3115_ADDR, CTRL_REG1, 1, ®val, channel);
return state;
}