STM32F405 standard library SHT20 temperature and humidity sensor

SHT20 is a temperature and humidity sensor, using I2C communication

 The following I2C program needs to be replaced with your own I2C program

SoftReset function: hardware initialization

SET_Resolution function: set the resolution

ReadSht20 function: start measurement

Call like this in the main function of 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

Station B address: https://www.bilibili.com/read/cv8106605

If you encounter any problems, you can ask me my B station https://space.bilibili.com/309103931

Guess you like

Origin blog.csdn.net/qq_33259323/article/details/109304615