/**
  * @brief  This function configures the system to enter Stop mode for
  *         current consumption measurement purpose.
  *         STOP Mode
  *         =========
  *           - Regulator in LP mode
  *           - LSI, HSI and HSE OFF
  *           - No IWDG
  *           - Current Consumption ~0.5uA
  *           - Wakeup using EXTI Line (Key Button PA.00)  
  * @param  None
  * @retval None
  */
void StopMode_Measure(void)
{
  /* Configure all GPIO as analog to reduce current consumption on non used IOs */
  /* Enable GPIOs clock */
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA | RCC_AHBPeriph_GPIOB | RCC_AHBPeriph_GPIOC |
                        RCC_AHBPeriph_GPIOD | RCC_AHBPeriph_GPIOE | RCC_AHBPeriph_GPIOH |
                        RCC_AHBPeriph_GPIOF | RCC_AHBPeriph_GPIOG, ENABLE);

  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_40MHz;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_All;
  GPIO_Init(GPIOC, &GPIO_InitStructure);
  GPIO_Init(GPIOD, &GPIO_InitStructure);
  GPIO_Init(GPIOE, &GPIO_InitStructure);
  GPIO_Init(GPIOH, &GPIO_InitStructure);
  GPIO_Init(GPIOF, &GPIO_InitStructure);
  GPIO_Init(GPIOG, &GPIO_InitStructure);  
  GPIO_Init(GPIOA, &GPIO_InitStructure); 
  GPIO_Init(GPIOB, &GPIO_InitStructure);   

  /* Disable GPIOs clock */
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA | RCC_AHBPeriph_GPIOB | RCC_AHBPeriph_GPIOC |
                        RCC_AHBPeriph_GPIOD | RCC_AHBPeriph_GPIOE | RCC_AHBPeriph_GPIOH |
                        RCC_AHBPeriph_GPIOF | RCC_AHBPeriph_GPIOG, DISABLE);
  
  /*  Configure Key Button*/
  STM_EVAL_PBInit(BUTTON_KEY, BUTTON_MODE_GPIO);

  /* Wait Until Key button pressed */
  while(STM_EVAL_PBGetState(BUTTON_KEY) == RESET)
  {
  }
  /* Wait Until Key button pressed */
  while(STM_EVAL_PBGetState(BUTTON_KEY) != RESET)
  {
  }

  /*  Configure Key Button*/
  STM_EVAL_PBInit(BUTTON_KEY, BUTTON_MODE_EXTI);
    
  /* Enable Ultra low power mode */
  PWR_UltraLowPowerCmd(ENABLE);

  /* Enter Stop Mode */
  PWR_EnterSTOPMode(PWR_Regulator_LowPower, PWR_STOPEntry_WFI);

  /* Initialize LED1 on STM32L152-EVAL board */
  STM_EVAL_LEDInit(LED1);

  /* Infinite loop */
  while (1)
  {
    /* Toggle The LED1 */
    STM_EVAL_LEDToggle(LED1);

    /* Inserted Delay */
    for(index = 0; index < 0x5FF; index++);
  }
}
Example #2
0
void LowPower_Init(void)
{
  LowPower_CLK_Config();
  CLK_HaltConfig(CLK_Halt_FastWakeup,ENABLE);//快速唤醒
  LowPower_GPIO_Config(); 
  PWR_UltraLowPowerCmd(ENABLE);   
}
/**
  * @brief  This function configures the system to enter Standby mode for
  *         current consumption measurement purpose.
  *         STANDBY Mode
  *         ============
  *           - IWDG and LSI OFF
  *           - Current Consumption ~0.3uA
  *           - Wakeup using WakeUp Pin 1 (PA.00)    
  * @param  None
  * @retval None
  */
void StandbyMode_Measure(void)
{
  /*  Configure Key Button*/
  STM_EVAL_PBInit(BUTTON_KEY,BUTTON_MODE_GPIO);

  /* Wait Until Key button pressed */
  while(STM_EVAL_PBGetState(BUTTON_KEY) == RESET)
  {
  }
  /* Wait Until Key button pressed */
  while(STM_EVAL_PBGetState(BUTTON_KEY) != RESET)
  {
  }

  /* Enable Ultra low power mode */
  PWR_UltraLowPowerCmd(ENABLE);

  /* Clear PWR WakeUp flag */
  PWR_ClearFlag(PWR_FLAG_WU);

  /* Enable WKUP pin 1 */
  PWR_WakeUpPinCmd(PWR_WakeUpPin_1, ENABLE);

  /* Request to enter STANDBY mode */
  PWR_EnterSTANDBYMode();
  
  /* Infinite loop */
  while (1)
  {
  }
}
Example #4
0
static void Goto_HALT()
{
  // Prepare for HALT mode
  LED_OFF;
  RFM_OFF;
  btn_pressed = 0;
  CLK->PCKENR1 = 0x00; //Stop all peripheral clocks
  CLK->PCKENR2 = 0x00;
  CLK->PCKENR3 = 0x00;
  PWR_FastWakeUpCmd(ENABLE);     //Enables or disables the Fast WakeUp from Ultra Low Power mode, system does not wait for VrefINT to stabilize (around 3ms)
  PWR_UltraLowPowerCmd(ENABLE);  //Enables or disables the Ultra Low Power mode, disable VrefINT during Halt or Active-Halt modes
  CLK_HaltConfig(CLK_Halt_FastWakeup, ENABLE);  //Configures clock during halt and active halt modes
                                                  //Fast wakeup from Halt/Active-halt modes enabled: HSI/8 used as system clock source after wakeup from Halt/Active-halt
  CLK_HaltConfig(CLK_Halt_SlowWakeup, ENABLE);  //When it is set, the main voltage regulator is powered off as soon as the MCU enters Active-halt mode, so the wakeup time is longer
                                                  //1: MVR regulator OFF in Active-halt mode
  halt(); /* go to HALT mode */
}
Example #5
0
/***********************************************************************
  * @brief  IdleTask
  * @param  None
  * @retval None
************************************************************************/
void IdleTask(void)
{	
	#ifdef DEBUG
		printf("IdleTask ...\r\n");
		AppTrace_DeInit();
	#endif

	PWR_UltraLowPowerCmd(ENABLE);
	CLK_HaltConfig(CLK_Halt_FastWakeup, ENABLE);
	PWR_FastWakeUpCmd(ENABLE);
    halt();

	#ifdef DEBUG
		AppTrace_Init();
		printf("Wakeup ...\r\n");
	#endif
}
Example #6
0
void sleep_mode(FunctionalState sleep)
{ 
  if(Settings.Sleep_time>0 && !Power.USB_active)
  {
		Power.Pump_deny=ENABLE;
		if(Power.Pump_active)Pump_now(DISABLE);
		
		set_msi();
    if(sleep)
    {
			RTC_ITConfig(RTC_IT_WUT, DISABLE);

			Power.led_sleep_time=0;
			GPIO_SetBits(GPIOC,GPIO_Pin_13);// Выключаем подсветку  				

      display_off(); // выключить дисплей
 			GPIO_ResetBits(GPIOA,GPIO_Pin_7);// Фиксируем режим 1.8 вольта, с низким потреблением ножки

			delay_ms(1000); // подождать установки напряжения
			DataUpdate.Need_batt_voltage_update=ENABLE; // разрешить работу АЦП
			adc_check_event(); // запустить преобразование
			delay_ms(100); // подождать установки напряжения

			PWR_FastWakeUpCmd(DISABLE);
			PWR_UltraLowPowerCmd(ENABLE); 
			PWR_PVDCmd(DISABLE);
			RTC_ITConfig(RTC_IT_WUT, ENABLE);
    }
    else
    {
			RTC_ITConfig(RTC_IT_WUT, DISABLE);
			GPIO_SetBits(GPIOA,GPIO_Pin_7);// Переключаем в режим 3 вольта
			delay_ms(400); // подождать установки напряжения
      display_on(); // включить дисплей
			DataUpdate.Need_batt_voltage_update=ENABLE; // разрешить работу АЦП
			DataUpdate.Need_display_update=ENABLE;
			adc_check_event(); // запустить преобразование
			RTC_ITConfig(RTC_IT_WUT, ENABLE);
			sound_deactivate();
    }
		Power.Pump_deny=DISABLE;
  } 
}
Example #7
0
void RtcRecoverMcuStatus( void )
{
    if( TimerGetLowPowerEnable( ) == true )
    {
        if( ( LowPowerDisableDuringTask == false ) && ( RtcTimerEventAllowsLowPower == true ) )
        {
            // Disable IRQ while the MCU is not running on HSI
            __disable_irq( );

            /* After wake-up from STOP reconfigure the system clock */
            /* Enable HSI */
            RCC_HSICmd( ENABLE );

            /* Wait till HSI is ready */
            while( RCC_GetFlagStatus( RCC_FLAG_HSIRDY ) == RESET )
            {}

            /* Enable PLL */
            RCC_PLLCmd( ENABLE );

            /* Wait till PLL is ready */
            while( RCC_GetFlagStatus( RCC_FLAG_PLLRDY ) == RESET )
            {}

            /* Select PLL as system clock source */
            RCC_SYSCLKConfig( RCC_SYSCLKSource_PLLCLK );

            /* Wait till PLL is used as system clock source */
            while( RCC_GetSYSCLKSource( ) != 0x0C )
            {}

            /* Set MCU in ULP (Ultra Low Power) */
            PWR_UltraLowPowerCmd( DISABLE ); // add up to 3ms wakeup time

            /* Enable the Power Voltage Detector */
            PWR_PVDCmd( ENABLE );

            BoardInitMcu( );

            __enable_irq( );
        }
    }
}
Example #8
0
void RtcEnterLowPowerStopMode( void )
{
    if( ( LowPowerDisableDuringTask == false ) && ( RtcTimerEventAllowsLowPower == true ) )
    {
        // Disable IRQ while the MCU is being deinitialized to prevent race issues
        __disable_irq( );

        BoardDeInitMcu( );

        __enable_irq( );

        /* Disable the Power Voltage Detector */
        PWR_PVDCmd( DISABLE );

        /* Set MCU in ULP (Ultra Low Power) */
        PWR_UltraLowPowerCmd( ENABLE );

        /*Disable fast wakeUp*/
        PWR_FastWakeUpCmd( DISABLE );

        /* Enter Stop Mode */
        PWR_EnterSTOPMode( PWR_Regulator_LowPower, PWR_STOPEntry_WFI );
    }
}
Example #9
0
File: main.c Project: tymbys/Watch
int main(void)
{


	RCC_APB1PeriphClockCmd( RCC_APB1Periph_PWR, ENABLE);//!!!!

	// тактирование ядра низкоскоростным внутренним генератором 4мгц
	RCC->ICSCR &= ~RCC_ICSCR_MSIRANGE;//!!!!
	RCC->ICSCR |= RCC_ICSCR_MSIRANGE_6;//!!!!
	//RTC_Initilithahion();//!!!!
	////////////////////////////////////////////////////////////////////

	delay_ms(1000);//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!



	curent_cmd = 0;
	PCount_Start = 0;
	/////////////////// настройка пробуждения
		RCC_HSICmd(DISABLE);
		PWR_PVDCmd(DISABLE);
		PWR_UltraLowPowerCmd(ENABLE);
		PWR_WakeUpPinCmd(PWR_WakeUpPin_1,ENABLE);
		PWR_UltraLowPowerCmd(ENABLE);

	////////////// настройка прирывания для будильника в неспящем режиме
		EXTI_InitTypeDef exti;
		NVIC_InitTypeDef NVIC_InitStructure;

		EXTI_ClearITPendingBit(EXTI_Line17);
		exti.EXTI_Line = EXTI_Line17;
		exti.EXTI_Mode = EXTI_Mode_Interrupt;
		exti.EXTI_Trigger = EXTI_Trigger_Rising;
		exti.EXTI_LineCmd = ENABLE;
		EXTI_Init(&exti);

		NVIC_InitStructure.NVIC_IRQChannel = RTC_Alarm_IRQn;
		NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
		NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
		NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
		NVIC_Init(&NVIC_InitStructure);

		//////////////////




	if(PWR_GetFlagStatus(PWR_FLAG_SB)!=RESET)//Если МК вышел из режима standby
	{
		WkupFlag=1;
		curent_cmd = 1;


		if(RTC_GetFlagStatus(RTC_FLAG_ALRAF)!=RESET)//Если МК вышел из режима ALARM
		{
							//RTC_Initilithahion();//!!!!
						//PWR_RTCAccessCmd(ENABLE);
						//RTC_ClearFlag(RTC_FLAG_ALRAF);
						//PWR_RTCAccessCmd(DISABLE);
							//f_WakeupToAlarm=1;
						curent_cmd = 5;
		}




		//RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR,ENABLE);
		PWR_ClearFlag(PWR_FLAG_SB); //Сброс флага, который указывает на то, что МК вышел из режима standby


		PWR_RTCAccessCmd(ENABLE); // Доступ в RTC
		//RTC_ClearITPendingBit(RTC_IT_WUT);
		//RTC_ClearFlag(RTC_FLAG_WUTF);
		RTC_ClearFlag(RTC_FLAG_ALRAF);
		PWR_RTCAccessCmd(DISABLE);





	}
	else
	{


		WkupFlag=0;

		RTC_TimeTypeDef alarmTime;
		alarmTime.RTC_H12 = RTC_H12_PM;//!!!!;
		alarmTime.RTC_Hours = 20;
		alarmTime.RTC_Minutes = 0;
		alarmTime.RTC_Seconds = 20;


		RTC_Initilithahion();//!!!!
		//RTC_Set_Alarm(alarmTime);/// Магическая последовательность, 1. RTC_Set_Alarm, 2. RTC_Set_Time иначе не работает будильник


		RTC_TimeTypeDef RTC_Time;
		RTC_DateTypeDef RTC_Date;

		RTC_Time.RTC_H12 = RTC_H12_PM;//!!!!;
		RTC_Time.RTC_Hours = 20;
		RTC_Time.RTC_Minutes = 00;
		RTC_Time.RTC_Seconds = 00;


		RTC_Date.RTC_WeekDay = RTC_Weekday_Sunday;

		RTC_Date.RTC_Year = 14;
		RTC_Date.RTC_Month = 8;
		RTC_Date.RTC_Date = 17;

		RTC_Set_TimeDate(RTC_Time, RTC_Date);///


	}





	//else curent_cmd = 0;//f_WakeupToAlarm=0;











	//RTC_Initilithahion();//!!!!
	//RTC_Set_Time();






OLED_Init();
OLED_Clear();
char i,j;






/*
RCC_GetClocksFreq(&Frequency);
f=Frequency.SYSCLK_Frequency/1000;
IntToStr(a,f);
OLED_DrawString_fast(30,30,a,10);
*/


OLED_LcdCache_Clear();



//if(0==WkupFlag) //Если МК до этого не находился в режиме STANDBY!!!!!!!!!!!!!!!!!
//PWR_EnterSTANDBYMode(); //Перейди в режим STANDBY!!!!!!!!!!!!!!!!!!!


//OLED_DrawBitmap_fast(3,12,menu1_sprait,123,40);
//delay_ms(10000);


WaitToSleep = 0;



TACT_Config();

BackTimeAndData.hour=0;
BackTimeAndData.minute=0;
BackTimeAndData.second=0;

globa_menu = 1;
f_aktive_menu = 0;
//curent_cmd = 0;

PWatch_Setup_Step = 0;

key_up = 0;
key_down = 0;
key_ok = 0;

PCount_Start = 0;

while(1)
{

	key = 0;

	key_ok = GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0);
	key_down = GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_2);
	key_up = GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_12);


/*
	OLED_DrawString_fast(0,0,"            ",10);

	IntToStr(bbb,key_ok);
	OLED_DrawString_fast(0,0,bbb,10);

	IntToStr(bbb,key_down);
	OLED_DrawString_fast(30,0,bbb,10);

	IntToStr(bbb,key_up);
	OLED_DrawString_fast(60,0,bbb,10);
*/

	if (key_ok!=0)
	{
		key_ok = 0;
		key = 1;



		//OLED_DrawString_fast(0,0,"000000000",10);
		//f_aktive_menu = 1;


		/*
		if (f_aktive_menu == 1)
		{
			//f_work_comand = 1;
			f_aktive_menu = 0;
			f_clearScrin = 1;
			curent_cmd = menu_cmd[globa_menu-1];

		}
		else curent_cmd = 255 ;
		*/
	}


	if (key_down==0)
	{
		key_down = 0;
		key = 2;

		/*
		if ((globa_menu>1)&&(f_work_comand == 0)) globa_menu--;
		else globa_menu = 1;

		//IntToStr(bbb,globa_menu);
		//OLED_DrawString_fast(0,0,bbb,10);

		 */

	}


	if (key_up==0)
	{

		key_up = 0;
		key = 12;

		/*
		if ((globa_menu<4)&&(f_work_comand == 0)) globa_menu++;
		else globa_menu = 4;

		//IntToStr(bbb,globa_menu);
		//OLED_DrawString_fast(0,0,bbb,10);

		 */

	}


	if (key!=0)
		{
			GPIO_SetBits(GPIOA, GPIO_Pin_1);
			delay_ms(30);
			GPIO_ResetBits(GPIOA, GPIO_Pin_1);
		}



/*
	if (f_clearScrin==1)
	{
		OLED_Clear();
		f_clearScrin=0;
	}
*/


	//if (f_aktive_menu==0)
	//{

	switch(curent_cmd)
	{
		case 0:			//нет команды

				PWatch_Menu();

				break;
		case 1:			//Программа показа часов (главная страница)

				//OLED_Clear();
				//f_work_comand = 1;
				PWatch_Anim();
				break;
		case 2:			//Программа настройки даты/времени и др.

				//OLED_Clear();
				OLED_DrawString_fast(0,0,"Календарь",10);
				curent_cmd = 0;
				break;

		case 3:

				//OLED_Clear();
				PWatch_Set_Alarm();
				break;

		case 4:

				//OLED_Clear();
				//OLED_DrawString_fast(0,0,"Настройки",10);

				//f_work_comand = 1;
				PWatch_Setup();

				break;

		case 5:

				PWatch_Vibration();

				break;


		case 254:

				OLED_Clear();

				break;

		/*case 255:

				OLED_Clear();
				OLED_DrawBitmap_fast(3,12,menu1_sprait,123,40);
				f_aktive_menu = 1;
				//f_work_comand = 0;
				//key=0;
				break;
		*/
		default: 		//выполнить, если ни один вариант не подошел

				break;
	}
	//}
	//else
	//{
		//PWatch_Menu();
	//}

/*
				if(WainToAlarm == 1)
				{
					OLED_DrawString_fast(0,0,"alarm1",10);
					WainToAlarm =0;
				}
*/


				//if(WaitToSleep>=5)
				//{
					//WaitToSleep=0;


					//PWR_ClearFlag(PWR_FLAG_SB); //Сброс флага, который указывает на то, что МК вышел из режима standby


/*
					for (i=255; i>0; i--)
					{
						OLED_SetContrast(i);
						IntToStr(a,i);
						OLED_DrawString_fast(0,0,a,10);
						//delay_ms(500);
					}*/




					//OLED_DrawBitmap_fast(32,10,Fallout_Bitmaps,58,60);
					//delay_ms(1000);

					//OLED_Display_Off();!!!!!!!!!!!!!!!!!!!!!!!!1

					//RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, DISABLE);
					//походу стабилитрон кушает 0.1 мА, общее потребление 0.15мА


					//PWR_EnterSTANDBYMode();!!!!!!!!!!!!!!!!!!!!!



				//}


				//WaitToSleep++;

/*
				RCC_GetClocksFreq(&Frequency);
				f=Frequency.SYSCLK_Frequency/1000;
				IntToStr(a,f);
				OLED_DrawString_fast(0,0,a,10);
*/






	delay_ms(250);



}

}
Example #10
0
/**
  * @brief Current measurement in different MCU modes:
  * RUN/SLEEP/LowPower/STANDBY with/without RTC
  * @caller main and ADC_Icc_Test
  * @param MCU state
  * @retval ADC value.
  */
uint16_t ADC_Icc_Test(uint8_t Mcu_State)
{
  GPIO_InitTypeDef GPIO_InitStructure;
  uint16_t adc_measure;
  uint32_t i;
  RCC_TypeDef SavRCC;
  /* Reset UserButton State */
  UserButton = FALSE;
  /* Start counter */
  GPIO_HIGH(CTN_GPIO_PORT,CTN_CNTEN_GPIO_PIN);
  /* Disable the RTC Wakeup Interrupt */
  RTC_ITConfig(RTC_IT_WUT, DISABLE);
  /* Disable LCD */
  LCD_Cmd(DISABLE);
  /* wait until LCD disable */
  while (LCD_GetFlagStatus(LCD_FLAG_ENS) == SET);
  /*Reset Idd-WakeUP flag*/
  Idd_WakeUP = FALSE;
  /* Set IO in lowpower configuration*/
  GPIO_LowPower_Config(); 
  /*Disable fast wakeUp*/
  PWR_FastWakeUpCmd(DISABLE);
  
/* Test MCU state for configuration */
  switch (Mcu_State)
  {
    /* Run mode : Measurement Measurement performed with MSI 4 MHz without RTC*/	
    case MCU_RUN:
        /* switch on MSI clock */
        SetHSICLKToMSI(RCC_MSIRange_6,NoDIV2,NoRTC) ;   
        /* shitch on MSI clock */
        Config_RCC(&SavRCC);    
        SysTick->CTRL = 0;     
        RCC->APB1ENR = 0;

        /* To run nops during measurement:
        it's the best case for low current */     

        for (i=0;i<0xffff;i++) {
          __NOP();  __NOP();    __NOP();  __NOP();
          __NOP();  __NOP();    __NOP();  __NOP();
          __NOP();  __NOP();    __NOP();  __NOP();
          __NOP();  __NOP();    __NOP();  __NOP();
          __NOP();  __NOP();    __NOP();  __NOP();
          __NOP();  __NOP();    __NOP();  __NOP();
          __NOP();  __NOP();    __NOP();  __NOP();
          __NOP();  __NOP();    __NOP();  __NOP();
          __NOP();  __NOP();    __NOP();  __NOP();
          __NOP();  __NOP();    __NOP();  __NOP();
          __NOP();  __NOP();    __NOP();  __NOP();
        }
        
    break;

    /* SLEEP mode : Measurement performed with MSI 4 MHz without RTC in WFI mode*/
    case MCU_SLEEP:
         
        SetHSICLKToMSI(RCC_MSIRange_6,NoDIV2,NoRTC) ;   
        Config_RCC(&SavRCC);  
        Config_Systick_50ms();
        Delay(1);

       /* Request Wait For Interrupt */
        PWR_EnterSleepMode(PWR_Regulator_ON,PWR_SLEEPEntry_WFI);   
           
        break;    

   /* RUN LOW POWER mode :   Measurement performed with MSI 32 Khz without RTC */
    case MCU_LP_RUN:
      
        /* Disable PVD */
        PWR_PVDCmd(DISABLE);

        /* Enable The ultra Low Power Mode */
        PWR_UltraLowPowerCmd(ENABLE);         

        /* Save the RCC configuration registers */
        Config_RCC(&SavRCC);      
        
        /* Stop the sys tick in order to avoid IT */
        SysTick->CTRL = 0; 
        
#ifdef TESTINRAM        
        SetHSICLKToMSI(RCC_MSIRange_0,DIV2,NoRTC) ; 
        
        PWR_EnterLowPowerRunMode(ENABLE);
        while(PWR_GetFlagStatus(PWR_FLAG_REGLP) == RESET) ;  

        DisableInterrupts();
        EnterLPRUNModeRAM();
        EnableInterrupts();        
#else         
        /* Swith in MSI 32KHz */
        SetHSICLKToMSI(RCC_MSIRange_64KHz,DIV2,NoRTC) ;    
                
        PWR_EnterLowPowerRunMode(ENABLE);
        while(PWR_GetFlagStatus(PWR_FLAG_REGLP) == RESET) ;              
        
        /* Launch the counter */
        GPIO_LOW(CTN_GPIO_PORT,CTN_CNTEN_GPIO_PIN);           
           
        /* To run the nop during measurement:
        it's the best case for low current
        until counter reach detected by IT --> Idd_WakeUP */
        do{
          __NOP();  __NOP();    __NOP();  __NOP();
          __NOP();  __NOP();    __NOP();  __NOP(); 
          __NOP();  __NOP();    __NOP();  __NOP();
          __NOP();  __NOP();    __NOP();  __NOP();  
          __NOP();  __NOP();    __NOP();  __NOP();
          __NOP();  __NOP();    __NOP();  __NOP(); 
          __NOP();  __NOP();    __NOP();  __NOP();
          __NOP();  __NOP();    __NOP();  __NOP();            
        }  while (Idd_WakeUP == FALSE );       
#endif        
        
        PWR_EnterLowPowerRunMode(DISABLE);
        while(PWR_GetFlagStatus(PWR_FLAG_REGLP) != RESET) ;  
    
        break; 
      
      /* SLEEP LOW POWER mode
         Measurement done to MSI 32 Khz without RTC
      */	
      case MCU_LP_SLEEP:
        
        /* Disable PVD */
        PWR_PVDCmd(DISABLE);   
        
        /* Enable Ultra low power mode */
        PWR_UltraLowPowerCmd(ENABLE);

                
        /* To save the RCC configuration registers */
        Config_RCC(&SavRCC);     
        
        /* To stop the sys tick for avoid IT */
        SysTick->CTRL = 0; 
        
        /* Swith in MSI 32KHz */
        SetHSICLKToMSI(RCC_MSIRange_0,DIV2,NoRTC) ;

#ifdef TESTINRAM
        DisableInterrupts();
        EnterLPSLEEPModeRAM();
        EnableInterrupts();
#else        
        /* Falling edge for start counter */		
        GPIO_LOW(CTN_GPIO_PORT,CTN_CNTEN_GPIO_PIN);

        /* Request Wait For Interrupt */    
        PWR_EnterSleepMode(PWR_Regulator_LowPower,PWR_SLEEPEntry_WFI);
#endif              
        break;   
        
      /* STOP modes
       Measurement done to MSI 32 Khz without or with RTC
       */		
      case MCU_STOP_NoRTC:
      case MCU_STOP_RTC:

        /* Disable PVD */
        PWR_PVDCmd(DISABLE);
          
        /* Enable Ultra low power mode */
        PWR_UltraLowPowerCmd(ENABLE);           
        
        /* To save the RCC configuration registers */
        Config_RCC(&SavRCC);  

        /* To stop the sys tick for avoid IT */
        SysTick->CTRL = 0; 
               
       /* Swith in MSI 32KHz */
        if( Mcu_State == MCU_STOP_NoRTC )
          SetHSICLKToMSI(RCC_MSIRange_0,DIV2,NoRTC) ;
        else
         SetHSICLKToMSI(RCC_MSIRange_0,DIV2,WITHRTC) ;          

        /* Falling edge for start counter */		
        GPIO_LOW(CTN_GPIO_PORT,CTN_CNTEN_GPIO_PIN);
        
        /* Request Wait For Interrupt */    
        PWR_EnterSTOPMode(PWR_Regulator_LowPower,PWR_STOPEntry_WFI);              

        break;        
          
        /* Standby mode without RTC
          Measurement done to MSI 32 Khz without RTC
        */
        case MCU_STBY:
          
          /* Disable PVD */
          PWR_PVDCmd(DISABLE);
          
          /* Enable Ultra low power mode */
          PWR_UltraLowPowerCmd(ENABLE);
          
          RTC_OutputTypeConfig(RTC_OutputType_PushPull);
          RTC_OutputConfig(RTC_Output_WakeUp,RTC_OutputPolarity_High);        
          
          /* To configure PC13 WakeUP output */
         GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13  ;
          //GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0  ;
          GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
          GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
          GPIO_InitStructure.GPIO_Speed = GPIO_Speed_400KHz;  
          GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
          GPIO_Init( GPIOC, &GPIO_InitStructure); 
         // GPIO_Init( GPIOA, &GPIO_InitStructure);
          
         GPIO_PinAFConfig(GPIOC, GPIO_PinSource13,GPIO_AF_RTC_AF1) ;
          //GPIO_PinAFConfig(GPIOA, GPIO_PinSource0,GPIO_AF_RTC_AF1) ;
          Config_RCC(&SavRCC);  
          
          SysTick->CTRL = 0; 
                  
          /* Swith in MSI 32KHz */
          SetHSICLKToMSI(RCC_MSIRange_0,DIV2,NoRTC) ;     
          
          PWR_WakeUpPinCmd(PWR_WakeUpPin_1,ENABLE);
          
          PWR_UltraLowPowerCmd(ENABLE); 
          
           PWR_EnterSTANDBYMode();
          /* Stop here WakeUp EXIT on RESET */
        
        break;
      }
  
  SetHSICLK();  

  Config_Systick(); 
  RCC->AHBENR = SavRCC.AHBENR;	
         
  PWR_VoltageScalingConfig(PWR_VoltageScaling_Range1);
  /* Wait Until the Voltage Regulator is ready */
  while (PWR_GetFlagStatus(PWR_FLAG_VOS) != RESET) ;

   /* Read ADC for current measurmeent */
   adc_measure = Current_Measurement();
    
  /* ICC_CNT_EN Hi */
  GPIO_HIGH(CTN_GPIO_PORT,CTN_CNTEN_GPIO_PIN);
  UserButton = TRUE;

  /* To restore RCC registers */
  RCC->APB1ENR = SavRCC.APB1ENR;
  RCC->APB2ENR = SavRCC.APB2ENR; 
  RCC->AHBLPENR = SavRCC.AHBLPENR;	
  RCC->APB1LPENR = SavRCC.APB1LPENR;
  RCC->APB2LPENR = SavRCC.APB2LPENR;
  
  /* Need to reinit RCC for LCD*/
  RCC_Configuration();

  PWR_EnterLowPowerRunMode(DISABLE);
  
  /* Disable Ultra low power mode */
  PWR_UltraLowPowerCmd(DISABLE);
  
  /* Disable FLASH during SLeep LP */
  FLASH_SLEEPPowerDownCmd(DISABLE);
  
  Restore_GPIO_Config();  
 
  /* Clear Wake Up flag */
  PWR_ClearFlag(PWR_FLAG_WU);
  
  /* Enable PVD */
  PWR_PVDCmd(ENABLE);

  LCD_GLASS_Init();
   
  return (adc_measure);
}
/**
  * @brief  This function configures the system to enter Standby mode with RTC 
  *         clocked by LSI for current consumption measurement purpose.
  *         STANDBY Mode with RTC clocked by LSI
  *         ====================================   
  *           - RTC Clocked by LSI
  *           - IWDG OFF
  *           - Current Consumption ~1.1uA
  *           - Automatic Wakeup using RTC clocked by LSI (after ~4s)    
  * @param  None
  * @retval None
  */
void StandbyRTCLSIMode_Measure(void)
{
  /*  Configure Key Button*/
  STM_EVAL_PBInit(BUTTON_KEY,BUTTON_MODE_GPIO);

  /* Wait Until Key button pressed */
  while(STM_EVAL_PBGetState(BUTTON_KEY) == RESET)
  {
  }
  /* Wait Until Key button pressed */
  while(STM_EVAL_PBGetState(BUTTON_KEY) != RESET)
  {
  }
    
  /* Allow access to RTC */
  PWR_RTCAccessCmd(ENABLE);

  /*!< LSI Enable */
  RCC_LSICmd(ENABLE);

  /*!< Wait till LSI is ready */
  while (RCC_GetFlagStatus(RCC_FLAG_LSIRDY) == RESET)
  {}

  /*!< RTC Clock Source Selection */
  RCC_RTCCLKConfig(RCC_RTCCLKSource_LSI);

  /* Enable the RTC Clock */
  RCC_RTCCLKCmd(ENABLE);

  /* Wait for RTC APB registers synchronisation */
  RTC_WaitForSynchro();  

  /* Enable Ultra low power mode */
  PWR_UltraLowPowerCmd(ENABLE);

  /* RTC Wakeup Interrupt Generation: Clock Source: RTCCLK_Div16, Wakeup Time Base: ~4s 
     RTC Clock Source LSI ~37KHz  
  */
  RTC_WakeUpClockConfig(RTC_WakeUpClock_RTCCLK_Div16);
  RTC_SetWakeUpCounter(0x2421);

  /* Clear PWR WakeUp flag */
  PWR_ClearFlag(PWR_FLAG_WU);
  
  /* Clear RTC WakeUp (WUTF) flag */
  RTC_ClearFlag(RTC_FLAG_WUTF);

  /* Enable the Wakeup Interrupt */
  RTC_ITConfig(RTC_IT_WUT, ENABLE);

  /* Enable Wakeup Counter */
  RTC_WakeUpCmd(ENABLE); 

  /* Request to enter STANDBY mode */
  PWR_EnterSTANDBYMode();
  
  /* Infinite loop */
  while (1)
  {
  }
}
/**
  * @brief  This function configures the system to enter Stop mode with RTC 
  *         clocked by LSI for current consumption measurement purpose.
  *         STOP Mode with RTC clocked by LSI
  *         =================================   
  *           - RTC Clocked by LSI
  *           - Regulator in LP mode
  *           - HSI and HSE OFF
  *           - No IWDG
  *           - Current Consumption ~1.3uA
  *           - Automatic Wakeup using RTC clocked by LSI (after ~4s)  
  * @param  None
  * @retval None
  */
void StopRTCLSIMode_Measure(void)
{
  NVIC_InitTypeDef  NVIC_InitStructure;
  EXTI_InitTypeDef  EXTI_InitStructure;
  
  /* Allow access to RTC */
  PWR_RTCAccessCmd(ENABLE);

  /*!< LSI Enable */
  RCC_LSICmd(ENABLE);

  /*!< Wait till LSI is ready */
  while (RCC_GetFlagStatus(RCC_FLAG_LSIRDY) == RESET)
  {}

  /*!< RTC Clock Source Selection */
  RCC_RTCCLKConfig(RCC_RTCCLKSource_LSI);

  /* Enable the RTC Clock */
  RCC_RTCCLKCmd(ENABLE);

  /* Wait for RTC APB registers synchronisation */
  RTC_WaitForSynchro();

  /* Configure all GPIO as analog to reduce current consumption on non used IOs */
  /* Enable GPIOs clock */
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA | RCC_AHBPeriph_GPIOB | RCC_AHBPeriph_GPIOC |
                        RCC_AHBPeriph_GPIOD | RCC_AHBPeriph_GPIOE | RCC_AHBPeriph_GPIOH |
                        RCC_AHBPeriph_GPIOF | RCC_AHBPeriph_GPIOG, ENABLE);

  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_40MHz;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_All;
  GPIO_Init(GPIOC, &GPIO_InitStructure);
  GPIO_Init(GPIOD, &GPIO_InitStructure);
  GPIO_Init(GPIOE, &GPIO_InitStructure);
  GPIO_Init(GPIOH, &GPIO_InitStructure);
  GPIO_Init(GPIOG, &GPIO_InitStructure); 
  GPIO_Init(GPIOF, &GPIO_InitStructure);  
  GPIO_Init(GPIOA, &GPIO_InitStructure); 
  GPIO_Init(GPIOB, &GPIO_InitStructure);

  /* Disable GPIOs clock */
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA | RCC_AHBPeriph_GPIOB | RCC_AHBPeriph_GPIOC |
                        RCC_AHBPeriph_GPIOD | RCC_AHBPeriph_GPIOE | RCC_AHBPeriph_GPIOH |
                        RCC_AHBPeriph_GPIOF | RCC_AHBPeriph_GPIOG, DISABLE);

  /*  Configure Key Button*/
  STM_EVAL_PBInit(BUTTON_KEY,BUTTON_MODE_GPIO);

  /* Wait Until Key button pressed */
  while(STM_EVAL_PBGetState(BUTTON_KEY) == RESET)
  {
  }
  /* Wait Until Key button pressed */
  while(STM_EVAL_PBGetState(BUTTON_KEY) != RESET)
  {
  }
    
  /* EXTI configuration *******************************************************/
  EXTI_ClearITPendingBit(EXTI_Line20);
  EXTI_InitStructure.EXTI_Line = EXTI_Line20;
  EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
  EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
  EXTI_InitStructure.EXTI_LineCmd = ENABLE;
  EXTI_Init(&EXTI_InitStructure);
  
  /* Enable the RTC Wakeup Interrupt */
  NVIC_InitStructure.NVIC_IRQChannel = RTC_WKUP_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);
  
  /* RTC Wakeup Interrupt Generation: Clock Source: RTCCLK_Div16, Wakeup Time Base: ~4s 
     RTC Clock Source LSI ~37KHz  
  */
  RTC_WakeUpClockConfig(RTC_WakeUpClock_RTCCLK_Div16);
  RTC_SetWakeUpCounter(0x2421);

  /* Enable the Wakeup Interrupt */
  RTC_ITConfig(RTC_IT_WUT, ENABLE);
      
  /* Enable Ultra low power mode */
  PWR_UltraLowPowerCmd(ENABLE);

  /* Enable Wakeup Counter */
  RTC_WakeUpCmd(ENABLE);
    
  /* Enter Stop Mode */
  PWR_EnterSTOPMode(PWR_Regulator_LowPower, PWR_STOPEntry_WFI);

  /* Infinite loop */
  while (1)
  {
    /* Toggle The LED1 */
    STM_EVAL_LEDToggle(LED1);

    /* Inserted Delay */
    for(index = 0; index < 0x5FF; index++);
  }
}
/**
  * @brief  This function configures the system to enter Low Power Sleep mode for
  *         current consumption measurement purpose.
  *         The maximum clock when the system is in Low Power Run mode is ~128KHz.
  *         This mode can only be entered when Voltage Range 2 is selected. 
  *         Low Power Sleep Mode
  *         ====================   
  *           - System Running at MSI (~32KHz)
  *           - Flash 0 wait state  
  *           - Voltage Range 2
  *           - Code running from Internal FLASH
  *           - All peripherals OFF
  *           - VDD from 1.65V to 3.6V
  *           - Current Consumption ~4.07uA
  *           - Wakeup using EXTI Line (Key Button PA.00)      
  * @param  None
  * @retval None
  */
void LowPowerSleepMode_Measure(void)
{
  /* Configure the System Clock to MSI Range 0 (65KHz). ----------------------*/

  /* RCC system reset */
  RCC_DeInit();
  
  /* Flash 0 wait state */
  FLASH_SetLatency(FLASH_Latency_0);
    
  /* Disable Prefetch Buffer */
  FLASH_PrefetchBufferCmd(DISABLE);    

  /* Disable 64-bit access */
  FLASH_ReadAccess64Cmd(DISABLE);

  /* Enable the PWR APB1 Clock */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);
  
  /* Select the Voltage Range 2 (1.5V) */
  PWR_VoltageScalingConfig(PWR_VoltageScaling_Range2);
  
  /* Wait Until the Voltage Regulator is ready */
  while(PWR_GetFlagStatus(PWR_FLAG_VOS) != RESET)
  {
  }
        
  /* HCLK = SYSCLK/2 = ~32KHz */
  RCC_HCLKConfig(RCC_SYSCLK_Div2);

  /* PCLK2 = HCLK */
  RCC_PCLK2Config(RCC_HCLK_Div1);

  /* PCLK1 = HCLK */
  RCC_PCLK1Config(RCC_HCLK_Div1);

  /* Set MSI clock range to 65.536KHz */
  RCC_MSIRangeConfig(RCC_MSIRange_0);
  
  /* Select MSI as system clock source */
  RCC_SYSCLKConfig(RCC_SYSCLKSource_MSI);

  /* Wait till PLL is used as system clock source */
  while (RCC_GetSYSCLKSource() != 0x00)
  {} 
  
  /* Configure all GPIO as analog to reduce current consumption on non used IOs */  
  /* Enable GPIOs clock */
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA | RCC_AHBPeriph_GPIOB | RCC_AHBPeriph_GPIOC |
                        RCC_AHBPeriph_GPIOD | RCC_AHBPeriph_GPIOE | RCC_AHBPeriph_GPIOH |
                        RCC_AHBPeriph_GPIOF | RCC_AHBPeriph_GPIOG, ENABLE);

  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_40MHz;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_All;
  GPIO_Init(GPIOC, &GPIO_InitStructure);
  GPIO_Init(GPIOD, &GPIO_InitStructure);
  GPIO_Init(GPIOE, &GPIO_InitStructure);
  GPIO_Init(GPIOH, &GPIO_InitStructure);
  GPIO_Init(GPIOF, &GPIO_InitStructure);
  GPIO_Init(GPIOG, &GPIO_InitStructure);  
  GPIO_Init(GPIOA, &GPIO_InitStructure); 
  GPIO_Init(GPIOB, &GPIO_InitStructure);

  /* Disable GPIOs clock */
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA | RCC_AHBPeriph_GPIOB | RCC_AHBPeriph_GPIOC |
                        RCC_AHBPeriph_GPIOD | RCC_AHBPeriph_GPIOE | RCC_AHBPeriph_GPIOH |
                        RCC_AHBPeriph_GPIOF | RCC_AHBPeriph_GPIOG, DISABLE);

  /*  Configure Key Button*/
  STM_EVAL_PBInit(BUTTON_KEY,BUTTON_MODE_GPIO);

  /* Wait Until Key button pressed */
  while(STM_EVAL_PBGetState(BUTTON_KEY) == RESET)
  {
  }
  /* Wait Until Key button pressed */
  while(STM_EVAL_PBGetState(BUTTON_KEY) != RESET)
  {
  }

  /*  Configure Key Button*/
  STM_EVAL_PBInit(BUTTON_KEY,BUTTON_MODE_EXTI);
  
  /* Enable The ultra Low Power Mode */
  PWR_UltraLowPowerCmd(ENABLE);
  
  /* Enable the power down mode during Sleep mode */
  FLASH_SLEEPPowerDownCmd(ENABLE);
  
  /* Request to enter SLEEP mode with regulator in low power mode */
  PWR_EnterSleepMode(PWR_Regulator_LowPower, PWR_SLEEPEntry_WFI);

  /* Initialize LED1 on STM32L152-EVAL board */
  STM_EVAL_LEDInit(LED1);
  

  /* Infinite loop */
  while (1)
  {
    /* Toggle The LED1 */
    STM_EVAL_LEDToggle(LED1);

    /* Inserted Delay */
    for(index = 0; index < 0x5FF; index++);
  }
}
Example #14
0
/**
  * @brief  Enter the MCU selected low power modes.
  * @param  lpmode: selected MCU low power modes. This parameter can be one of the
  *         following values:
  *              @arg STM32L_RUN: Run mode at 32MHz.
  *              @arg STM32L_RUN_1M: Run mode at 1MHz.
  *              @arg STM32L_RUN_LP: Low power Run mode at 32KHz.  
  *              @arg STM32L_SLEEP: Sleep mode at 16MHz.
  *              @arg STM32L_SLEEP_LP: Low power Sleep mode at 32KHz.
  *              @arg STM32L_STOP: Stop mode with or without RTC.
  *              @arg STM32L_STANDBY: Standby mode with or without RTC.
  * @param  RTCState: RTC peripheral state during low power modes. This parameter
  *         is valid only for STM32L_RUN_LP, STM32L_SLEEP_LP, STM32L_STOP and
  *         STM32L_STANDBY. This parameter can be one of the following values:
  *              @arg RTC_STATE_ON: RTC peripheral is ON during low power modes.
  *              @arg RTC_STATE_OFF: RTC peripheral is OFF during low power modes.
  * @param  CalibrationState: Bias Calibration mode selection state during low 
  *         power modes. 
  *         This parameter can be one of the following values:
  *              @arg BIAS_CALIB_OFF: Bias Calibration mode is selected during 
  *                   low power modes.
  *              @arg BIAS_CALIB_ON: Bias Calibration mode isn't selected during 
  *                   low power modes.
  * @retval None
*/
void IDD_Measurement(uint32_t lpmode, uint8_t RTCState, uint8_t CalibrationState)
{
  GPIO_InitTypeDef GPIO_InitStructure;
  uint16_t mode = STM32L_MODE_LP, adcdata, i;

  /* Disable the Wakeup Interrupt */
  RTC_ITConfig(RTC_IT_WUT, DISABLE);

  /* Disable the JoyStick interrupts */
  Demo_IntExtOnOffConfig(DISABLE);

  /* Disable Leds toggling */
  Demo_LedShow(DISABLE);

  /* Save the RCC configuration */
  RCC_AHBENR   = RCC->AHBENR;
  RCC_APB2ENR  = RCC->APB2ENR;
  RCC_APB1ENR  = RCC->APB1ENR;

  /* Disable PVD */
  PWR_PVDCmd(DISABLE);

  /* Wait until JoyStick is pressed */
  while (Menu_ReadKey() != NOKEY)
  {}

  /* Save the GPIO pins current configuration then put all GPIO pins in Analog
     Input mode ...*/
  IDD_Measurement_SaveContext();

  /* Clear Wake Up flag */
  PWR_ClearFlag(PWR_FLAG_WU);

  RCC->AHBENR = 0x05;
  RCC->APB2ENR = 0x00;
  RCC->APB1ENR = 0x10000000;  /* PWR APB1 Clock enable */
  
  switch(lpmode)
  {
    /*=========================================================================*
     *                        RUN MODE 32MHz (HSE + PLL)                       *
     *========================================================================*/
    case STM32L_RUN:
    {  
      mode = STM32L_MODE_RUN;
      /* Needed delay to have a correct value on capacitor C25.
        Running NOP during waiting loop will decrease the current consumption. */
      for (i = 0;i < 0xFFFF; i++) 
      {
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
      }
    }
    break;

    /*=========================================================================*
     *                        RUN MODE MSI 1MHz                                *
     *========================================================================*/
    case STM32L_RUN_1M:
    {      
      mode = STM32L_MODE_RUN;
      
      /* Reconfigure the System Clock at MSI 1 MHz */
      SetHCLKToMSI_1MHz();
        
      /* Needed delay to have a correct value on capacitor C25.
        Running NOP during waiting loop will decrease the current consumption. */
      for (i = 0;i < 0x3FFF; i++) 
      {
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
      }
    }
    break;

    /*=========================================================================*
     *                        RUN LOW POWER MODE MSI 32KHz                     *
     *========================================================================*/    
    case STM32L_RUN_LP:
    {                
      if(!RTCState)
      {  
        RCC_LSEConfig(RCC_LSE_OFF);
      }
      else
      {
        if (RTC_GetFlagStatus(RTC_FLAG_INITS) == RESET)
        {
          /* RTC Configuration ************************************************/
          /* Reset RTC Domain */
          RCC_RTCResetCmd(ENABLE);
          RCC_RTCResetCmd(DISABLE);
          
          /* Enable the LSE OSC */
          RCC_LSEConfig(RCC_LSE_ON);
          
          /* Wait till LSE is ready */
          while (RCC_GetFlagStatus(RCC_FLAG_LSERDY) == RESET)
          {}
          
          /* Select the RTC Clock Source */
          RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);
          
          /* Enable the RTC Clock */
          RCC_RTCCLKCmd(ENABLE);
          
          /* Wait for RTC APB registers synchronisation */
          RTC_WaitForSynchro();
        }        
      }
      /* Configure the System Clock at MSI 32 KHz */
      SetHCLKToMSI_64KHz(); 
      RCC_HCLKConfig(RCC_SYSCLK_Div2); 
      
      /* Clear IDD_CNT_EN pin */
      GPIO_ResetBits(IDD_CNT_EN_GPIO_PORT, IDD_CNT_EN_PIN);
      
      /* Enter low power run mode */
      PWR_EnterLowPowerRunMode(ENABLE);
      
      /* Waiting wake-up interrupt */
      /* Needed delay to have a correct value on capacitor C25.
        Running NOP during waiting loop will decrease the current consumption. */
      do 
      {
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
        __NOP();  __NOP();    __NOP();  __NOP();
      }while(LowPowerStatus == 0x00);

      /* Exit low power run mode before setting the clock to 32MHz */
      PWR_EnterLowPowerRunMode(DISABLE);
      while(PWR_GetFlagStatus(PWR_FLAG_REGLP) != RESET)
      {
      }  
    }       
    break;

    /*=========================================================================*
     *                        SLEEP MODE HSI 16MHz                             * 
     *========================================================================*/        
    case STM32L_SLEEP:
    {            
      mode = STM32L_MODE_RUN;      
      /* Enable Ultra low power mode */
      PWR_UltraLowPowerCmd(ENABLE);
      
      /* Diable FLASH during SLeep LP */
      FLASH_SLEEPPowerDownCmd(ENABLE);
            
      RCC_APB2PeriphClockLPModeCmd(RCC_APB2Periph_CLOCK, ENABLE);
      RCC_APB1PeriphClockLPModeCmd(RCC_APB1Periph_CLOCK, ENABLE);
      RCC_AHBPeriphClockLPModeCmd(RCC_AHBPeriph_CLOCK, ENABLE);
      
      /* Configure the System Clock to 16MHz */
      SetHCLKToHSI();
      
      Demo_SysTickConfig();
      Demo_Delay(5);
      
      /* Request to enter SLEEP mode with regulator on */
      PWR_EnterSleepMode(PWR_Regulator_ON, PWR_STOPEntry_WFI); 
    }   
    break;

    /*=========================================================================*
     *                      SLEEP LOW POWER MODE MSI 32KHz                     *
     *========================================================================*/     
    case STM32L_SLEEP_LP:
    {            
      if(!RTCState)
      {  
        RCC_LSEConfig(RCC_LSE_OFF);
      }
      else
      {
        if (RTC_GetFlagStatus(RTC_FLAG_INITS) == RESET)
        {
          /* RTC Configuration ************************************************/
          /* Reset RTC Domain */
          RCC_RTCResetCmd(ENABLE);
          RCC_RTCResetCmd(DISABLE);
          
          /* Enable the LSE OSC */
          RCC_LSEConfig(RCC_LSE_ON);
          
          /* Wait till LSE is ready */
          while (RCC_GetFlagStatus(RCC_FLAG_LSERDY) == RESET)
          {}
          
          /* Select the RTC Clock Source */
          RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);
          
          /* Enable the RTC Clock */
          RCC_RTCCLKCmd(ENABLE);
          
          /* Wait for RTC APB registers synchronisation */
          RTC_WaitForSynchro();
        }        
      }
      
      /* Enable Ultra low power mode */
      PWR_UltraLowPowerCmd(ENABLE);
      
      /* Diable FLASH during SLeep LP */
      FLASH_SLEEPPowerDownCmd(ENABLE);
      
      /* Disable HSI clock before entering Sleep LP mode */ 
      RCC_HSICmd(DISABLE);
      /* Disable HSE clock */
      RCC_HSEConfig(RCC_HSE_OFF);
      /* Disable LSI clock */
      RCC_LSICmd(DISABLE);
      
      RCC_APB2PeriphClockLPModeCmd(RCC_APB2Periph_CLOCK, ENABLE);
      RCC_APB1PeriphClockLPModeCmd(RCC_APB1Periph_CLOCK, ENABLE);
      RCC_AHBPeriphClockLPModeCmd(RCC_AHBPeriph_CLOCK, ENABLE);
      
      /* Clear IDD_CNT_EN pin */
      GPIO_ResetBits(IDD_CNT_EN_GPIO_PORT, IDD_CNT_EN_PIN);
      
      /* Reconfigure the System Clock at MSI 64 KHz */
      SetHCLKToMSI_64KHz();
      RCC_HCLKConfig(RCC_SYSCLK_Div2); 
      
      /* Request to enter SLEEP mode with regulator low power */
      PWR_EnterSleepMode(PWR_Regulator_LowPower, PWR_STOPEntry_WFI);        
    }
    break;
    
    /*=========================================================================*
     *                          STOP LOW POWER MODE                            *
     *========================================================================*/    
    case STM32L_STOP:
    {                 
      /* Enable Ultra low power mode */
      PWR_UltraLowPowerCmd(ENABLE);

      if(!RTCState)
      {  
        RCC_LSEConfig(RCC_LSE_OFF);
      }
      else
      {
        if (RTC_GetFlagStatus(RTC_FLAG_INITS) == RESET)
        {
          /* RTC Configuration ************************************************/
          /* Reset RTC Domain */
          RCC_RTCResetCmd(ENABLE);
          RCC_RTCResetCmd(DISABLE);
          
          /* Enable the LSE OSC */
          RCC_LSEConfig(RCC_LSE_ON);
          
          /* Wait till LSE is ready */
          while (RCC_GetFlagStatus(RCC_FLAG_LSERDY) == RESET)
          {}
          
          /* Select the RTC Clock Source */
          RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);
          
          /* Enable the RTC Clock */
          RCC_RTCCLKCmd(ENABLE);
          
          /* Wait for RTC APB registers synchronisation */
          RTC_WaitForSynchro();
        }        
      }
      
      /* Clear IDD_CNT_EN pin */
      GPIO_ResetBits(IDD_CNT_EN_GPIO_PORT, IDD_CNT_EN_PIN);
      
      /* Request to enter STOP mode with regulator in low power */
      PWR_EnterSTOPMode(PWR_Regulator_LowPower, PWR_STOPEntry_WFI);
      
      /* Reset the counter by programming IDD_CNT_EN High in less than 70ms after
      the wakeup to avoid 1Kohm to be connected later on VDD_MCU */
      GPIO_SetBits(IDD_CNT_EN_GPIO_PORT, IDD_CNT_EN_PIN);
      
      /* Configures system clock after wake-up from STOP: enable HSE, PLL and select PLL
         as system clock source (HSE and PLL are disabled in STOP mode) */
      IDD_Measurement_SYSCLKConfig_STOP();      
    }
    break;

    /*=========================================================================*
     *                          STANDBY LOW POWER MODE                         *
     *========================================================================*/        
    case STM32L_STANDBY:
    {      
      if (RTC_GetFlagStatus(RTC_FLAG_INITS) == RESET)
      {
        /* RTC Configuration **************************************************/
        /* Reset RTC Domain */
        RCC_RTCResetCmd(ENABLE);
        RCC_RTCResetCmd(DISABLE);
        
        /* Enable the LSE OSC */
        RCC_LSEConfig(RCC_LSE_ON);
        
        /* Wait till LSE is ready */
        while (RCC_GetFlagStatus(RCC_FLAG_LSERDY) == RESET)
        {}
        
        /* Select the RTC Clock Source */
        RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);
        
        /* Enable the RTC Clock */
        RCC_RTCCLKCmd(ENABLE);
        
        /* Wait for RTC APB registers synchronisation */
        RTC_WaitForSynchro();
      } 
      
      RTC_OutputTypeConfig(RTC_OutputType_PushPull);
      RTC_OutputConfig(RTC_Output_WakeUp, RTC_OutputPolarity_High);  
      
      /* To configure PC13 WakeUP output */
      GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
      GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
      GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
      GPIO_InitStructure.GPIO_Speed = GPIO_Speed_400KHz;  
      GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
      GPIO_Init(GPIOC, &GPIO_InitStructure); 
      GPIO_PinAFConfig(GPIOC, GPIO_PinSource13, GPIO_AF_RTC_AF1);
      
      PWR_WakeUpPinCmd(PWR_WakeUpPin_1, ENABLE);
      
      PWR_UltraLowPowerCmd(ENABLE); 
      
      RTC_ClearFlag(RTC_FLAG_WUTF | RTC_FLAG_ALRBF | RTC_FLAG_ALRAF | RTC_FLAG_TAMP1F | RTC_FLAG_TSF); 
      RTC_ITConfig(RTC_IT_WUT, DISABLE);

      if(!RTCState)
      {  
        RCC_LSEConfig(RCC_LSE_OFF);
      }
      
      /* Clear Wake Up flag */
      PWR_ClearFlag(PWR_FLAG_WU);  
      
      /* Request to enter STANDBY mode (Wake Up flag is cleared in PWR_EnterSTANDBYMode function) */
      PWR_EnterSTANDBYMode();
    }     
    break; 
  }

  /* Configure the System Clock to 32MHz */
  SetHCLKTo32();
      
  /* Reset lowpower status variable*/  
  LowPowerStatus = 0x00;
      
  RCC->AHBENR = RCC_AHBENR;
  RCC->APB2ENR = RCC_APB2ENR;
  RCC->APB1ENR = RCC_APB1ENR;
      
  /* Reset the counter by programming IDD_CNT_EN High in less than 70ms after
     the wakeup to avoid 1Kohm to be connected later on VDD_MCU */
  GPIO_SetBits(IDD_CNT_EN_GPIO_PORT, IDD_CNT_EN_PIN);
  
  /* Measure the Voltage using the ADC */    
  adcdata = IDD_Measurement_ADC_ReadValue();
  
  /* Write the ADC converted value in the DATA EEPROM memory for Bias Measurement */
  if(CalibrationState == BIAS_CALIB_ON)
  {
    /* Unlock EEPROM write access*/
    DATA_EEPROM_Unlock();
  
    /* Store the value in EEPROM for application needs */
    DATA_EEPROM_ProgramHalfWord(DATA_EEPROM_BIAS_ADDR, adcdata);
  
    /* Lock back EEPROM write access */
    DATA_EEPROM_Lock(); 
  }

  IDD_Measurement_ADC_DisplayValue(adcdata, mode);
    
  /* Clear Wake Up flag */
  PWR_ClearFlag(PWR_FLAG_WU);
      
  /* Enable PVD */
  PWR_PVDCmd(ENABLE);
      
  /* Restore Demonstration Context. */
  IDD_Measurement_RestoreContext();
  
  LCD_SetBackColor(LCD_COLOR_GREEN);  
  LCD_DisplayStringLine(LCD_LINE_6, "STM32L LowPower Mode");          
  LCD_DisplayStringLine(LCD_LINE_7, Str);

  LCD_DisplayStringLine(LCD_LINE_8, "Press JoyStick to   ");
  LCD_DisplayStringLine(LCD_LINE_9, "continue.           ");  

  /* Wait until Joystick pressed. */
  while (Menu_ReadKey() == NOKEY)
  {} 
  
  /* Disable ADC1 */
  ADC_Cmd(ADC1, DISABLE);

  LCD_Clear(LCD_COLOR_WHITE);
  
  LCD_GLASS_DisplayString(" STM32L ");

  /* Enable the Wakeup Interrupt */
  RTC_ITConfig(RTC_IT_WUT, ENABLE);

  /* Enable the JoyStick interrupts */
  Demo_IntExtOnOffConfig(ENABLE);
  
  /* Display the previous menu */
  Menu_DisplayMenu(); 
}
int main(void)
{
    //int ret;
    
    NVIC_SetVectorTable(NVIC_VectTab_FLASH,VECTOR_TABLE_BASE_ADDRESS);
    
    /* Identify the BlueNRG platform */
    SdkEvalIdentification();

    RCC_Configuration();
    /* Basic button init function for handling application jumping */
    Configure_Button();
 
#if 0 /* TBR */
    PWR_PVDCmd(DISABLE);
    
    /* Disable FLASH during Sleep  */
    FLASH_SLEEPPowerDownCmd(ENABLE);
    
    /* Enable Ultra low power mode */
    PWR_UltraLowPowerCmd(ENABLE);
    
    PWR_FastWakeUpCmd(DISABLE);
#endif 
    
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
    
    Clock_Init();
    
    HCI_Init();
 
    /* Init SPI interface */
    SdkEvalSpiInit(SPI_MODE_EXTI);
    /* Reset BlueNRG SPI interface */
    BlueNRG_RST();
    
    /* Init leds */
    SdkEvalLedInit(LED1);
    SdkEvalLedInit(LED2);

    {
        tHalUint8 bdaddr[] = {0x12, 0x34, 0x00, 0xE1, 0x80, 0x02};

        aci_hal_write_config_data(CONFIG_DATA_PUBADDR_OFFSET, CONFIG_DATA_PUBADDR_LEN,
                                        bdaddr);
    }
    
    aci_gatt_init();    
    
    {
        uint16_t service_handle, dev_name_char_handle, appearance_char_handle;
        aci_gap_init(1, &service_handle, &dev_name_char_handle, &appearance_char_handle);        
    }
    
#if 0/* TBR */
    aci_gap_set_auth_requirement(MITM_PROTECTION_REQUIRED,
                                       OOB_AUTH_DATA_ABSENT,
                                       NULL,
                                       7,
                                       16,
                                       USE_FIXED_PIN_FOR_PAIRING,
                                       123456,
                                       BONDING);
#endif 
    
    //PRINTF("BLE Stack Initialized.\n");
    
#ifdef ST_OTA_BTL
    /* Add OTA bootloader service */
    Add_Btl_Service();
#endif
    
    /* -2 dBm output power */
    aci_hal_set_tx_power_level(1,4);
    
    while(1)
    {
#ifdef ST_OTA_BTL
      static tClockTime startTime = 0;

      if (Clock_Time() - startTime >led_blinking_rate)
      {    
        /* LED D1 is toggling on OTA_Service Manager */
        SdkEvalLedToggle(LED1);     
        startTime = Clock_Time();
      }
#endif /* end ST_OTA_BTL */

        HCI_Process();
        
        if(set_connectable){
            setConnectable();
            set_connectable = 0;
        }
        
      /* Use button to switch to the basic Reset Manager */
      if (GPIO_ReadInputDataBit(ButtonPort,ButtonPin) == RESET)
      {
        /* Add delay to avoid conlict with DFU activation */
        Clock_Wait(2000);
        
        /* Check if an application has been loaded previously through OTA service
           manager */
        if (*((uint32_t*) NEW_APP_MEM_INFO)!= 0) 
          /* Service Manager will jump to the Application previously loaded at
           address  APPLICATION_JUMP_ADDRESS */
          Switch_To_OTA_Service_Manager_Application(APPLICATION_JUMP_ADDRESS);
      }
    }
}