压力传感器XGZP6857D驱动

#include <math.h>

#include <stdio.h>

#include "main.h"

#include "i2c.h"

#define DELAY_TIME 600

#define TRUE 1

#define FALSE 0

#define uchar unsigned char

#define uint unsigned int

#define XGZPxx_ADDR 0x6D

#define XGZPxx_ADDR_WRITE XGZPxx_ADDR << 1

#define XGZPxx_ADDR_READ ((XGZPxx_ADDR << 1) | 1)

typedef enum

{

DATA_MSB_CMD = 0x06,

DATA_CSB_CMD = 0x07,

DATA_LSB_CMD = 0x08,

TEMP_MSB_CMD = 0x09,

TEMP_LSB_CMD = 0x0A,

CMD = 0x30,

SYS_CONFIG_CMD = 0xA5,

P_CONFIG_CMD = 0xA6,

} XGZPxx_CMD;

static void XGZPxx_Write(uint8_t regadr, uint8_t data);

static uint8_t XGZPxx_Read(uint8_t regadr);

uint8_t pressure_H, pressure_M, pressure_L, temperature_H, temperature_L;

int32_t pressure_adc; // 24位有符号ADC值

int16_t temperature_adc; // 16位有符号ADC值

const float K = 16.0f; // 根据传感器规格调整的比例因子

uint8_t XGZPxx_ReadData(float* temp, float* pressure)

{

// 启动组合转换(温度+压力)

XGZPxx_Write(0x30, 0x0A);

// 等待转换完成(带超时机制)

uint32_t timeout = HAL_GetTick();

while((XGZPxx_Read(0x30) & 0x08))

{

//20ms超时

if(HAL_GetTick() - timeout > 20)

break;

}

// 读取压力ADC值(24位)

pressure_H = XGZPxx_Read(0x06);

pressure_M = XGZPxx_Read(0x07);

pressure_L = XGZPxx_Read(0x08);

// 组合24位有符号整数(使用符号扩展)

pressure_adc = (int32_t)((pressure_H << 16) | (pressure_M << 8) | pressure_L);

// 检查符号位

if(pressure_adc & 0x800000)

{

// pressure_adc |= 0xFF000000; // 负值符号扩展

pressure_adc = pressure_adc - 16777216;

}

// 计算实际压力值(单位Pa)

*pressure = (float)pressure_adc / K;

// Convert pressure to kPa (Pa to kPa)

*pressure /= 1000;

// 读取温度ADC值(16位)

temperature_H = XGZPxx_Read(0x09);

temperature_L = XGZPxx_Read(0x0A);

temperature_adc = (int16_t)((temperature_H << 8) | temperature_L);

// 计算实际温度值(单位℃)

if(temperature_adc > 65536)

{

*temp = (float)(temperature_adc - 65536) / 256.0f;

}

else

{

*temp = (float)(temperature_adc / 256.0f);

}

return SUCCESS;

}

static void XGZPxx_Write(uint8_t regadr, uint8_t data)

{

if(HAL_I2C_Mem_Write(&hi2c1, XGZPxx_ADDR_WRITE, regadr, I2C_MEMADD_SIZE_8BIT, &data, 1, HAL_MAX_DELAY) != HAL_OK)

{

printf("HAL_I2C_Mem_Write, error.\n");

}

}

static uint8_t XGZPxx_Read(uint8_t regadr)

{

static uint8_t val = 0;

if(HAL_I2C_Mem_Read(&hi2c1, XGZPxx_ADDR_READ, regadr, I2C_MEMADD_SIZE_8BIT, &val, 1, HAL_MAX_DELAY) != HAL_OK)

{

printf("HAL_I2C_Mem_Read, error.\n");

}

return val;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiaomin2017

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值