/**
 ******************************************************************************
 * @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>

#define DAC_MAX_VAL_12_BIT      (4095)

#include <mcalGPIO.h>

int main(void)
{
    uint16_t dac1Data     = 0;
    uint16_t dac2Data     = DAC_MAX_VAL_12_BIT;
    bool     dac1RampUp   = true;
    bool     dac2RampDown = false;

    gpioInitPort(GPIOA);                        // GPIOA : Bustakt aktivieren
    gpioSelectPinMode(GPIOA, PIN4, ANALOG);     // PA4   : Analog
    gpioSelectPinMode(GPIOA, PIN5, ANALOG);     // PA5   : Analog

    RCC->APB1ENR |= RCC_APB1ENR_DACEN;          // DAC   : Bustakt aktivieren
    DAC->CR      |= DAC_CR_EN1;                 // DAC   : Kanal 1 aktivieren
    DAC->CR      |= DAC_CR_EN2;                 // DAC   : Kanal 2 aktivieren

    while (1)
    {
        /**
         * Dreiecksignale an Ausgang 1 generieren
         */
        if (dac1RampUp == true)
        {
            DAC->DHR12R1 = dac1Data++ & 0x0FFF;

            if (dac1Data > DAC_MAX_VAL_12_BIT)
            {
                dac1RampUp = false;
            }
        }
        else
        {
            DAC->DHR12R1 = dac1Data-- & 0x0FFF;
            if (dac1Data <= 0)
            {
                dac1RampUp = true;
            }
        }

        /**
         * Dreiecksignale an Ausgang 2 generieren. Das Ausgangssignal
         * ist hier um 90° verschoben.
         */
        if (dac2RampDown == true)
        {
            DAC->DHR12R2 = dac2Data-- & 0x0FFF;
            if (dac2Data <= 0)
            {
                dac2RampDown = false;
            }
        }
        else
        {
            DAC->DHR12R2 = dac2Data++ & 0x0FFF;
            if (dac2Data >= DAC_MAX_VAL_12_BIT)
            {
                dac2RampDown = true;
            }
        }
    }

    return 0;
}
