stm32标准库读取ds18b20的温度
时间: 2023-09-11 20:11:55 浏览: 81
好的,下面是基于STM32标准库的读取DS18B20温度的代码:
首先,需要开启相关外设时钟,设置引脚为推挽输出模式,并将引脚输出高电平。
```
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); // 使能GPIOA时钟
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_SetBits(GPIOA, GPIO_Pin_2);
```
然后,发送读取温度命令,等待一段时间后读取DS18B20返回的温度值。
```
void DS18B20_ReadTemp(void)
{
GPIO_ResetBits(GPIOA, GPIO_Pin_2); //拉低总线
Delay_us(500); //延时500us
GPIO_SetBits(GPIOA, GPIO_Pin_2); //拉高总线
Delay_us(80); //延时80us
GPIO_ResetBits(GPIOA, GPIO_Pin_2); //拉低总线
Delay_us(10); //延时10us
GPIO_SetBits(GPIOA, GPIO_Pin_2); //拉高总线
Delay_us(15); //延时15us
uint8_t presence = GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_2); //读取DS18B20的握手信号
if (presence == RESET)
{
DS18B20_WriteByte(0xCC); //跳过ROM操作,直接发送读取温度命令
DS18B20_WriteByte(0x44);
Delay_us(800); //等待转换完成
DS18B20_WriteByte(0xCC); //跳过ROM操作,直接发送读取温度命令
DS18B20_WriteByte(0xBE);
uint8_t LSB = DS18B20_ReadByte(); //读取温度值的低8位
uint8_t MSB = DS18B20_ReadByte(); //读取温度值的高8位
int16_t temp = (MSB << 8) | LSB; //将两个字节组成温度值
temp = temp * 0.0625; //计算实际温度值
}
}
```
其中,DS18B20_WriteByte和DS18B20_ReadByte分别用于向DS18B20写入字节和从DS18B20读取字节。这两个函数需要自行实现。
注意:以上代码仅供参考,具体实现需要根据具体硬件环境和需求进行调整。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)