/**
 ******************************************************************************
 * @file           : main.c
 * @author         : Auto-generated by STM32CubeIDE
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * <h2><center>&copy; Copyright (c) 2020 STMicroelectronics.
 * All rights reserved.</center></h2>
 *
 * This software component is licensed by ST under BSD 3-Clause license,
 * the "License"; You may not use this file except in compliance with the
 * License. You may obtain a copy of the License at:
 *                        opensource.org/licenses/BSD-3-Clause
 *
 ******************************************************************************
 */

#if !defined(__SOFT_FP__) && defined(__ARM_FP)
  #warning "FPU is not initialized, but the project is compiling for an FPU. Please initialize the FPU before use."
#endif

#include <stm32f4xx.h>
#include <stdint.h>
#include <stdbool.h>

#include <mcalGPIO.h>

int main(void)
{
    uint16_t result = 0;

    // GPIOA: Initialisierung
    gpioInitPort(GPIOA);
    gpioSelectPinMode(GPIOA, PIN5, OUTPUT);

    // ADC1: Initialisierung
    RCC->APB2ENR |= RCC_APB2ENR_ADC1EN;
    gpioSelectPinMode(GPIOA, PIN1, ANALOG); // PA1: Analog Input

    ADC1->CR2   = 0;
    ADC1->SQR3  = ADC_SQR3_SQ1_0;           // Wir beginnen mit Kanal 1...
    ADC1->SQR1  = ADC_SQR1_L_0;             // ... und setzen die Laenge auf 1
    ADC1->CR2  |= ADC_CR2_ADON;             // ADC aktivieren

    while (1)
    {
        ADC1->CR2 |= ADC_CR2_SWSTART;       // A/D-Wandlung wird gestartet
        while (!(ADC1->SR & ADC_SR_EOC))    // Warten, bis Konvertierung beendet
        {
            ;
        }
        result = ADC1->DR;                  // Konvertierte Daten abholen
        if (result & 0x100)                 // LED in Abhaengigkeit vom Resultat
        {
            gpioSetPin(GPIOA, PIN5);        // einschalten oder
        }
        else
        {
            gpioResetPin(GPIOA, PIN5);      // ausschalten
        }
    }

    return 0;
}
