STM32F405 标准库 SHT20温湿度传感器

SHT20是个温湿度传感器,使用I2C通信

 下面的I2C程序需要换成你们自己的I2C程序

SoftReset函数:硬件初始化

SET_Resolution函数:设置分辨率

ReadSht20函数:开始测量

在main.c主函数里面这样调用

    if(SoftReset() == 0){
		printf("初始化成功\r\n");
	}
	
	while(1){
		printf("Humidity %f \r\n",ReadSht20((char)0xF5));
		printf("Temperature %f \r\n",ReadSht20((char)0xF3));
		delay_ms(1000);
	}

sht20.c

#include "sht20.h"
#include "hardiic.h"
#include "delay.h"
#include "usart.h"
#define SHT20ADDR 0x80

char SoftReset(void) {
	IIC_Start(); 
	IIC_Send_Byte(SHT20ADDR&0xfe); //I2C address + write
    if(IIC_Wait_Ack() == 1)return 1;
	IIC_Send_Byte(0xfe); //soft reset
    if(IIC_Wait_Ack() == 1)return 1;
	IIC_Stop(); //stop I2C

	return 0;
}

char SET_Resolution(void){
    IIC_Start(); 
    IIC_Send_Byte(SHT20ADDR&0xfe);
    if(IIC_Wait_Ack() == 1)return 1;
    IIC_Send_Byte(0xe6);
    if(IIC_Wait_Ack() == 1)return 1;
    IIC_Send_Byte(0x83);
    if(IIC_Wait_Ack() == 1)return 1;
    IIC_Stop();

	return 0;
}

float ReadSht20(char whatdo){
    float temp = 0.0f;
	unsigned char MSB,LSB;
	float Humidity = 0.0f;
	float Temperature = 0.0f;

	if(SET_Resolution() == 0){
		//printf("set ok \r\n");
	}

	delay_ms(20);

    IIC_Start();
    IIC_Send_Byte(SHT20ADDR&0xfe);
    if(IIC_Wait_Ack() == 1)return 0;
    IIC_Send_Byte(whatdo);
    if(IIC_Wait_Ack() == 1)return 0;

    do{
		delay_ms(6);
		IIC_Start(); 
        IIC_Send_Byte(SHT20ADDR|0x01);
	}while(IIC_Wait_Ack() != 0); 

    MSB = IIC_Read_Byte(1);
	LSB = IIC_Read_Byte(1);
	IIC_Read_Byte(0);
	IIC_Stop();

    LSB &= 0xfc;
	temp = MSB*256 + LSB; 

	delay_ms(20);

	if (whatdo==((char)0xF5)){
	 	Humidity = (temp*125)/65536-6; 
		return Humidity;
	}else{ 
		Temperature = (temp*175.72)/65536-46.85; 
		return Temperature; 
	}
}

sht20.h 

#ifndef __SHT20_H
#define __SHT20_H
#include "sys.h" 
   	   		   
char SoftReset(void);
char SET_Resolution(void);
float ReadSht20(char whatdo);
#endif

B站地址:https://www.bilibili.com/read/cv8106605

如果遇到什么问题可以来问我我的B站https://space.bilibili.com/309103931

猜你喜欢

转载自blog.csdn.net/qq_33259323/article/details/109304615