#include "main.h"
#include "lcd.h" // Include an LCD library
#include "dht.h" // Include a DHT sensor library
// Define the DHT sensor type (DHT11 or DHT22)
#define DHT_TYPE DHT11
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
int main(void) {
// Initialize the HAL Library
HAL_Init();
// Configure the system clock
SystemClock_Config();
// Initialize GPIO
MX_GPIO_Init();
// Initialize the LCD
LCD_Init();
LCD_Clear();
// Display a welcome message on the LCD
LCD_SetCursor(0, 0);
LCD_Print("Hello, STM32!");
// Initialize the DHT sensor
DHT_Init(GPIOA, GPIO_PIN_6, DHT_TYPE);
// Main loop
while (1) {
float temperature = 0.0, humidity = 0.0;
// Read data from the DHT sensor
if (DHT_Read(&temperature, &humidity) == DHT_OK) {
// Format and display temperature and humidity on the LCD
char buffer[16];
snprintf(buffer, sizeof(buffer), "T: %.1f H: %.1f", temperature, humidity);
LCD_SetCursor(1, 0);
LCD_Print(buffer);
// Control relay based on temperature
if (temperature > 30.0) {
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_7, GPIO_PIN_SET); // Relay ON
} else {
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_7, GPIO_PIN_RESET); // Relay OFF
}
} else {
// Display an error message if the sensor fails
LCD_SetCursor(1, 0);
LCD_Print("DHT Error!");
}
// Wait for 2 seconds
HAL_Delay(2000);
}
}
/* System Clock Configuration */
void SystemClock_Config(void) {
// System clock configuration code generated by STM32CubeMX
}
/* GPIO Initialization Function */
static void MX_GPIO_Init(void) {
GPIO_InitTypeDef GPIO_InitStruct = {0};
// Enable GPIOA clock
__HAL_RCC_GPIOA_CLK_ENABLE();
// Configure GPIO pins for LCD (PA0-PA5)
GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
// Configure GPIO pin for DHT sensor (PA6)
GPIO_InitStruct.Pin = GPIO_PIN_6;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
// Configure GPIO pin for Relay module (PA7)
GPIO_InitStruct.Pin = GPIO_PIN_7;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}