【STM32C031试用】OLED+helloworld (stmicroelectronics.cn)
在这篇文章的基础上增加sht20的温度传感器采集程序。
1、在Src目录下新增sht20.c以及sht20.h:
2、sht20.c代码如下:
#include "sht20.h"
#include "main.h"
#include <stdio.h>
unsigned char SHT20_SoftReset(void)
{
uint8_t buffer =SHT20_SOFT_RESET;
if(HAL_OK==HAL_I2C_Master_Transmit(&hi2c1, SHT20_Write_Add, &buffer, 1, 1000))
{
printf("成功\r\n");
return 0;
}
else
{
printf("失败\r\n");
return 1;
}
}
unsigned char SHT20_Read_Reg(void)
{
uint8_t buffer =SHT20_READ_REG;
if(HAL_OK==HAL_I2C_Master_Transmit(&hi2c1, SHT20_Write_Add, &buffer, 1, 1000))
{
if(HAL_OK==HAL_I2C_Master_Receive(&hi2c1, SHT20_Write_Add, &buffer, 1, 1000))
{
return buffer;
}
else
{
return 1;
}
}
else
{
return 1;
}
}
unsigned char SHT20_Config(void)//采集温度为14位,采集湿度为12位
{
uint8_t val;
val = (SHT20_Read_Reg()&0x7E)|0x00;
if(HAL_OK==HAL_I2C_Mem_Write(&hi2c1, (uint16_t)SHT20_Write_Add, (uint16_t)SHT20_WRITE_REG, (uint16_t)I2C_MEMADD_SIZE_8BIT, &val, 1, 1000))
{
return 0;
}
else
{
return 1;
}
}
void SHT20_Init()
{
if(SHT20_SoftReset())
{
printf("SHT20 复位失败\r\n");
}
else
{
printf("SHT20 复位成功\r\n");
}
HAL_Delay(100);
if(SHT20_Config())
{
printf("初始化失败\r\n");
}
else
{
printf("初始化成功\r\n");
}
}
float SHT20_GetTemperature(void)
{
uint8_t val[3];
if(HAL_OK==HAL_I2C_Mem_Read(&hi2c1, (uint16_t)SHT20_Write_Add, (uint16_t)SHT20_Measurement_T_HM, (uint16_t)I2C_MEMADD_SIZE_8BIT, val, 3, 1000))
{
return (-46.85 + (175.72 * (((val[0]<<8)|(val[1]&0xFC))) / 65536.0));
}
else
{
printf("error\r\n");
}
}
float SHT20_GetHumidity(void)
{
uint8_t val[3];
if(HAL_OK==HAL_I2C_Mem_Read(&hi2c1, (uint16_t)SHT20_Write_Add, (uint16_t)SHT20_Measurement_RH_HM, (uint16_t)I2C_MEMADD_SIZE_8BIT, val, 3, 1000))
{
return -6+125*(((val[0]<<8)|(val[1]&0xF0))/65536.0);
}
else
{
printf("error\r\n");
}
}
sht20.h代码如下:
#ifndef __SHT20_H
#define __SHT20_H
#include "main.h"
/*SHT20 设备操作相关宏定义,详见手册*/
#define SHT20_ADDRESS 0X40
#define SHT20_Write_Add 0x80 //STM32 hal库 slave地址为读地址
#define SHT20_Read_Add 0x81
#define SHT20_Measurement_RH_HM 0XE5
#define SHT20_Measurement_T_HM 0XE3
#define SHT20_Measurement_RH_NHM 0XF5 //非主机模式地址
#define SHT20_Measurement_T_NHM 0XF3 //非主机模式地址
#define SHT20_READ_REG 0XE7
#define SHT20_WRITE_REG 0XE6
#define SHT20_SOFT_RESET 0XFE
extern I2C_HandleTypeDef hi2c1;
void SHT20_Init(void);
unsigned char SHT20_SoftReset(void);
unsigned char SHT20_Read_Reg(void);
float SHT20_GetTemperature(void);
float SHT20_GetHumidity(void);
#endif
3、sht20接线,sht20也是i2c接口,sda接到D15,scl接到D14。
4、实现效果如图:
【小结】这次把sht20的代码移植过来后,内存不够用了,后面减少了字库,取消掉了printf打印float才编译过。在以后的使用中要节约内存了。