stm32-dht22-Main

by Marwen Maghrebi
int main(void) {
    /* USER CODE BEGIN 1 */
    float Voltage_mV = 0;
    float Temperature_C = 0;
    float Temperature_F = 0;
    char msg[50];
    /* USER CODE END 1 */
    
    HAL_Init();
    SystemClock_Config();
    MX_GPIO_Init();
    MX_USART1_UART_Init();
    MX_TIM1_Init();
    
    /* USER CODE BEGIN 2 */
    HAL_TIM_Base_Start(&htim1);
    send_uart("Initialization complete\n\r");
    /* USER CODE END 2 */

    /* USER CODE BEGIN WHILE */
    while (1) {
        HAL_Delay(1000); // Delay for 1 second
        start_signal(); // Send start signal to DHT22
        
        uint8_t check = check_response();
        if (!check) {
            send_uart("No response from the sensor\r\n");
        } else {
            // Read bytes from DHT22
            RH_Byte1 = read_byte();
            RH_Byte2 = read_byte();
            T_Byte1 = read_byte();
            T_Byte2 = read_byte();
            CheckSum = read_byte();

            // Combine humidity and temperature bytes
            uint16_t rh = (RH_Byte1 << 8) | RH_Byte2;
            uint16_t temp = (T_Byte1 << 8) | T_Byte2;
            uint8_t sign = 0;

            // Check if temperature is negative
            if (temp > 0x8000) {
                temp &= 0x7FFF; // Clear the sign bit
                sign = 1; // Indicate negative temperature
            }

            char rh_buf[5], temp_buf[5];
            sprintf(rh_buf, "%03u", rh);
            sprintf(temp_buf, "%03u", temp);

            // Check checksum
            if (CheckSum == ((RH_Byte1 + RH_Byte2 + T_Byte1 + T_Byte2) & 0xFF)) {
                sprintf(msg, "RH = %03u.%1u %% ", rh / 10, rh % 10);
                send_uart(msg);
                sprintf(msg, "Temp = %c%03u.%1u C \r\n", sign ? '-' : ' ', temp / 10, temp % 10);
                send_uart(msg);
            } else {
                send_uart("Checksum Error! Trying Again ...\r\n");
            }
        }
    }
}
Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?
-
00:00
00:00
Update Required Flash plugin
-
00:00
00:00