stm32103c8与lcd1602做成温度采集的库函数与程序
时间: 2023-10-09 19:15:02 浏览: 31
以下是基于STM32CubeIDE和HAL库编写的温度采集程序,使用的传感器为DS18B20,LCD显示模块为HD44780兼容的1602液晶显示屏。请注意,这只是一个简单的示例程序,您需要根据您的具体硬件配置和需求进行适当的修改。
首先需要在STM32CubeIDE中配置GPIO和OneWire总线的初始化函数。以下是基于STM32CubeMX生成的代码示例:
```c
/* Configure GPIO pins */
GPIO_InitTypeDef GPIO_InitStruct = {0};
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOB, LCD_RS_Pin|LCD_RW_Pin|LCD_E_Pin|DS18B20_Pin, GPIO_PIN_RESET);
/*Configure GPIO pins : LCD_RS_Pin LCD_RW_Pin LCD_E_Pin */
GPIO_InitStruct.Pin = LCD_RS_Pin|LCD_RW_Pin|LCD_E_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pin : DS18B20_Pin */
GPIO_InitStruct.Pin = DS18B20_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(DS18B20_GPIO_Port, &GPIO_InitStruct);
/* Configure OneWire bus */
OneWire_Init(&hds18b20, DS18B20_GPIO_Port, DS18B20_Pin);
```
接下来是主函数中的代码,其中包括了LCD显示和DS18B20温度采集的部分:
```c
/* Initialize LCD */
LCD_Init();
/* Display welcome message */
LCD_GotoXY(0,0);
LCD_WriteString("Hello World!");
LCD_GotoXY(0,1);
LCD_WriteString("Temp: --.- C");
/* Initialize OneWire bus */
OneWire_Init(&hds18b20, DS18B20_GPIO_Port, DS18B20_Pin);
/* Main loop */
while (1)
{
/* Start temperature conversion */
OneWire_Reset(&hds18b20);
OneWire_WriteByte(&hds18b20, 0xCC);
OneWire_WriteByte(&hds18b20, 0x44);
/* Wait for conversion to complete */
HAL_Delay(800);
/* Read temperature from DS18B20 */
OneWire_Reset(&hds18b20);
OneWire_WriteByte(&hds18b20, 0xCC);
OneWire_WriteByte(&hds18b20, 0xBE);
uint16_t temperature = OneWire_ReadByte(&hds18b20);
temperature |= OneWire_ReadByte(&hds18b20) << 8;
/* Convert temperature to Celsius */
float celsius = (float)temperature * 0.0625;
/* Display temperature on LCD */
char buffer[16];
sprintf(buffer, "Temp: %.1f C", celsius);
LCD_GotoXY(0,1);
LCD_WriteString(buffer);
/* Wait for a while */
HAL_Delay(1000);
}
```
其中,LCD_Init()、LCD_GotoXY()、LCD_WriteString()等函数是用于控制LCD显示模块的函数,您需要根据您的具体硬件配置和LCD显示模块的型号进行适当的修改。DS18B20的温度转换时间为750ms,我们这里设置为800ms。在读取温度值时,需要注意高位在前低位在后。最后使用sprintf函数将温度值格式化成字符串并显示在LCD上。