/* Includes ------------------------------------------------------------------*/
#include "stm8l15x.h"
#include "stm8l15x_conf.h"
#include "stm8l15x_it.h" /* SDCC patch: required by SDCC for interrupts */

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/

// #define Led1_Init GPIO_Init(GPIOC, GPIO_Pin_4, GPIO_Mode_Out_PP_Low_Fast)
// #define Led1_ON GPIO_SetBits(GPIOC, GPIO_Pin_4)
// #define Led1_OFF GPIO_ResetBits(GPIOC, GPIO_Pin_4)

#define Led2_Init GPIO_Init(GPIOB, GPIO_Pin_2, GPIO_Mode_Out_PP_Low_Fast)
#define Led2_ON GPIO_SetBits(GPIOB, GPIO_Pin_2)
#define Led2_OFF GPIO_ResetBits(GPIOB, GPIO_Pin_2)

#define Mono_Init GPIO_Init(GPIOB, GPIO_Pin_0, GPIO_Mode_Out_PP_High_Slow)
#define Mono_OFF GPIO_SetBits(GPIOB, GPIO_Pin_0)
#define Mono_ON GPIO_ResetBits(GPIOB, GPIO_Pin_0)

/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static void CLK_Config(void);
static void PWR_Config(void);
static void blink2();
/* Private functions ---------------------------------------------------------*/
void main(void)
{
  GPIO_Init(GPIOC, GPIO_Pin_0, GPIO_Mode_Out_PP_Low_Fast);
  
  // Led1_Init;
  // Led1_ON;
  CLK_Config();
  PWR_Config();
  Led2_Init;
  Mono_Init;
  blink2();
  // Led1_OFF;


  CLK_RTCClockConfig(CLK_RTCCLKSource_LSE, CLK_RTCCLKDiv_1);
  CLK_PeripheralClockConfig(CLK_Peripheral_RTC, ENABLE);
  // RTC_RatioCmd(ENABLE);

  RTC_WakeUpCmd(DISABLE);
  RTC_WakeUpClockConfig(RTC_WakeUpClock_RTCCLK_Div2);
  RTC_SetWakeUpCounter(250);
  RTC_WakeUpCmd(ENABLE);

  RTC_ITConfig(RTC_IT_WUT, ENABLE);

  enableInterrupts();
  while (1){
    blink2();
    halt();
  }
}

static void PWR_Config(void){
  PWR->CSR1 = PWR_CSR1_PVDIF;
  PWR->CSR2 = PWR_CSR2_RESET_VALUE;
  PWR->CSR2 |= PWR_CSR2_ULP;
  PWR->CSR2 |= PWR_CSR2_FWU;
}

static void CLK_Config(void)
{
  CLK_SYSCLKSourceSwitchCmd(ENABLE);
  CLK_SYSCLKSourceConfig(CLK_SYSCLKSource_LSI);
  CLK_SYSCLKDivConfig(CLK_SYSCLKDiv_1);
  while (CLK_GetSYSCLKSource() != CLK_SYSCLKSource_LSI);
}

// static void blink1(uint32_t time) {
//   Led1_ON;
//   for (uint16_t j = 0; j <= time; j++) {nop();}
//   Led1_OFF;
// }

// static void blink1_alt() {
//   Led1_ON;
//   Led1_OFF;
// }

static void blink2() {
  Mono_ON;
  Led2_ON;
  Led2_OFF;
  Mono_OFF;
}

/************************ (C) suuppl *****END OF FILE****/
