用小华半导体HC32L17x_DDL_Rev1.2.0中的i2c_mcu_master_int样例,改写一个SHT30温湿度传感器数据采集的程序
时间: 2023-08-16 14:08:45 浏览: 99
基于STM32的SHT30温湿度采集
好的,下面是一个基于HC32L17x_DDL_Rev1.2.0中的i2c_mcu_master_int样例修改的SHT30温湿度传感器数据采集程序:
```c
#include "hc32l17x.h"
#include "i2c.h"
#define SHT30_ADDR 0x44
static stc_i2c_config_t stcI2cCfg = {
.enFunc = Enable,
.u32Baudrate = 100000,
.enClkDiv = I2cPclkDiv1,
.enI2cMode = I2cMaster,
.enI2cAck = I2cAck,
.u8SlaveAddr = 0,
};
static void SHT30_Init(void)
{
/* I2C GPIO config */
Gpio_SetFunc_I2CSCK3_0(0u);
Gpio_SetFunc_I2CSDA3_0(0u);
/* I2C config */
M4_I2C3_Init(&stcI2cCfg);
}
static uint8_t SHT30_Send_Cmd(uint16_t cmd)
{
uint8_t u8TxData[2] = {0};
uint8_t u8RxData[2] = {0};
u8TxData[0] = (uint8_t)(cmd >> 8);
u8TxData[1] = (uint8_t)cmd;
/* Send command */
if (Ok != M4_I2C3_Transmit(SHT30_ADDR, u8TxData, 2u, I2cFmStart)) {
return Error;
}
/* Delay for measurement */
Ddl_Delay1ms(20u);
/* Receive data */
if (Ok != M4_I2C3_Receive(SHT30_ADDR, u8RxData, 2u, I2cFmStop)) {
return Error;
}
return u8RxData[0];
}
static uint16_t SHT30_Get_Humidity(void)
{
uint16_t u16Humidity = 0;
uint8_t u8Crc = 0;
/* Send measurement command */
if (Ok != SHT30_Send_Cmd(0x2400)) {
return 0;
}
/* Calculate humidity */
u16Humidity = (uint16_t)SHT30_Send_Cmd(0xE000);
/* Calculate CRC */
u8Crc = (uint8_t)(u16Humidity >> 8);
u16Humidity &= 0xFF;
if (u8Crc != (uint8_t)(0xFFu & ((u16Humidity + (u16Humidity >> 8))))) {
return 0;
}
return u16Humidity;
}
static uint16_t SHT30_Get_Temperature(void)
{
uint16_t u16Temperature = 0;
uint8_t u8Crc = 0;
/* Send measurement command */
if (Ok != SHT30_Send_Cmd(0x2400)) {
return 0;
}
/* Calculate temperature */
u16Temperature = (uint16_t)SHT30_Send_Cmd(0xE000);
/* Calculate CRC */
u8Crc = (uint8_t)(u16Temperature >> 8);
u16Temperature &= 0xFF;
if (u8Crc != (uint8_t)(0xFFu & ((u16Temperature + (u16Temperature >> 8))))) {
return 0;
}
return u16Temperature;
}
int main(void)
{
/* Init SHT30 */
SHT30_Init();
while (1) {
/* Get and print temperature and humidity */
uint16_t u16Temperature = SHT30_Get_Temperature();
uint16_t u16Humidity = SHT30_Get_Humidity();
printf("Temperature: %d.%d C, Humidity: %d.%d %%RH\n",
(int)(-45.0 + 175.0 * (float)u16Temperature / 65535.0),
(int)(100.0 * (float)u16Temperature / 65535.0) % 100,
(int)(100.0 * (float)u16Humidity / 65535.0),
(int)(10000.0 * (float)u16Humidity / 65535.0) % 100);
Ddl_Delay1ms(1000u);
}
}
```
这个程序中,我们先调用SHT30_Init()函数初始化I2C外设和GPIO,然后通过SHT30_Send_Cmd()函数向SHT30发送命令并接收采集到的数据。SHT30_Get_Humidity()和SHT30_Get_Temperature()函数分别用于获取湿度和温度数据,并且计算出相应的数值。在主函数中,我们不断循环获取并打印温湿度数据,以便进行实时监测。
阅读全文