#include "stm32f4xx_hal.h" // Change to your STM32 series
#include "dht22.h" // Include the DHT22 library header
// Define the pin connected to the DHT22 sensor
#define DHT22_PIN GPIO_PIN_1 // Change to your pin
#define DHT22_PORT GPIOB // Change to your GPIO port
// Function prototypes
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
// Initialize DHT22
DHT22 dht22;
int main(void)
{
// Initialize the HAL Library
HAL_Init();
// Configure the system clock
SystemClock_Config();
// Initialize all configured peripherals
MX_GPIO_Init();
MX_DMA_Init();
// Initialize DHT22 sensor
dht22_init(&dht22, DHT22_PORT, DHT22_PIN);
// Main loop
while (1)
{
// Read temperature and humidity
float temperature, humidity;
if (dht22_read(&dht22, &temperature, &humidity))
{
// Success: process the data
// Example: Toggle an LED based on the temperature
if (temperature > 25.0)
{
HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5); // Toggle LED on GPIOA pin 5
}
}
else
{
// Error: Handle the error (e.g., blink LED, print error message, etc.)
}
// Delay before next read
HAL_Delay(2000);
}
}
// Initialize all configured peripherals
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
// Configure LED pin as output
GPIO_InitStruct.Pin = GPIO_PIN_5; // Change to your LED pin
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 DHT22 data pin as input
GPIO_InitStruct.Pin = DHT22_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP; // or GPIO_PULLDOWN based on your circuit
HAL_GPIO_Init(DHT22_PORT, &GPIO_InitStruct);
}
// DMA initialization function (if needed)
static void MX_DMA_Init(void)
{
// Configure DMA settings if needed
}
// System Clock Configuration
void SystemClock_Config(void)
{
// Configure the system clock
}