基于stm32写sth11的驱动代码
时间: 2024-03-11 14:50:12 浏览: 49
好的,以下是一个基于STM32的SHT11驱动代码示例,希望对您有所帮助:
```c
#include "stm32f10x.h"
#define SHT11_DATA_OUT() GPIOC->CRH &= 0xFF0FFFFF; GPIOC->CRH |= 0x00300000 //PC13为输出
#define SHT11_DATA_IN() GPIOC->CRH &= 0xFF0FFFFF; GPIOC->CRH |= 0x00800000 //PC13为输入
#define SHT11_SCL_H() GPIOC->BSRR = GPIO_BSRR_BS14 //PC14拉高
#define SHT11_SCL_L() GPIOC->BSRR = GPIO_BSRR_BR14 //PC14拉低
#define SHT11_SDA_H() GPIOC->BSRR = GPIO_BSRR_BS13 //PC13拉高
#define SHT11_SDA_L() GPIOC->BSRR = GPIO_BSRR_BR13 //PC13拉低
#define SHT11_SDA_IN() GPIOC->IDR & GPIO_IDR_IDR13 //读取PC13的输入状态
void Delay_us(uint16_t time_us)
{
uint16_t i;
while(time_us--)
{
i = 10;
while(i--);
}
}
void SHT11_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13 | GPIO_Pin_14;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOC, &GPIO_InitStructure);
SHT11_SDA_H();
SHT11_SCL_H();
}
void SHT11_Reset(void)
{
uint8_t i;
SHT11_DATA_OUT();
SHT11_SDA_H();
SHT11_SCL_L();
Delay_us(2);
SHT11_SCL_H();
Delay_us(1);
SHT11_SDA_L();
Delay_us(2);
SHT11_SCL_L();
Delay_us(10);
SHT11_SCL_H();
Delay_us(1);
SHT11_DATA_IN();
i = 0;
while(SHT11_SDA_IN())
{
i++;
if(i > 200)
{
SHT11_Init();
return;
}
Delay_us(1);
}
SHT11_DATA_OUT();
SHT11_SCL_L();
Delay_us(2);
SHT11_SCL_H();
Delay_us(2);
SHT11_SDA_H();
Delay_us(2);
SHT11_SCL_L();
}
void SHT11_Write_Byte(uint8_t value)
{
uint8_t i;
SHT11_DATA_OUT();
for(i = 0; i < 8; i++)
{
SHT11_SCL_L();
if(value & 0x80)
SHT11_SDA_H();
else
SHT11_SDA_L();
value <<= 1;
Delay_us(2);
SHT11_SCL_H();
Delay_us(2);
}
SHT11_SCL_L();
SHT11_DATA_IN();
Delay_us(2);
SHT11_SCL_H();
Delay_us(2);
SHT11_SCL_L();
}
uint8_t SHT11_Read_Byte(uint8_t ack)
{
uint8_t i, value = 0;
SHT11_DATA_IN();
for(i = 0; i < 8; i++)
{
value <<= 1;
SHT11_SCL_L();
Delay_us(2);
SHT11_SCL_H();
if(SHT11_SDA_IN())
value++;
Delay_us(1);
}
SHT11_DATA_OUT();
if(ack)
{
SHT11_SDA_L();
}
else
{
SHT11_SDA_H();
}
Delay_us(2);
SHT11_SCL_L();
Delay_us(2);
SHT11_SDA_H();
Delay_us(2);
SHT11_SCL_H();
Delay_us(2);
SHT11_SCL_L();
return value;
}
void SHT11_Measure_Temp(void)
{
uint16_t i;
SHT11_Reset();
SHT11_Write_Byte(0x03);
for(i = 0; i < 10000; i++);
SHT11_Read_Byte(1);
SHT11_Read_Byte(0);
}
void SHT11_Measure_Humi(void)
{
uint16_t i;
SHT11_Reset();
SHT11_Write_Byte(0x05);
for(i = 0; i < 10000; i++);
SHT11_Read_Byte(1);
SHT11_Read_Byte(0);
}
float SHT11_Get_Temp(void)
{
uint16_t value;
SHT11_Measure_Temp();
value = SHT11_Read_Byte(1);
value <<= 8;
value |= SHT11_Read_Byte(0);
return (float)value * 0.01 - 40.0;
}
float SHT11_Get_Humi(void)
{
uint16_t value;
SHT11_Measure_Humi();
value = SHT11_Read_Byte(1);
value <<= 8;
value |= SHT11_Read_Byte(0);
return (float)value * 0.04 - 4.0;
}
```
请注意,这只是一个简单的示例代码,需要根据您的具体需求进行修改和调整。同时,应根据您的硬件平台进行相应的引脚配置和时钟设置。
阅读全文