Exemplo n.º 1
0
/**
  * @brief  Calibration of External crystal oscillator manually
  * @param  None
  * @retval : None
  */
void ManualClockCalibration(void)
{
  UpDownIntOnOffConfig(ENABLE);
  RightLeftIntExtOnOffConfig(ENABLE);
  SelIntExtOnOffConfig(DISABLE);
  LCD_Clear(Blue2);
  BKP_TamperPinCmd(DISABLE);
  BKP_RTCOutputConfig(BKP_RTCOutputSource_CalibClock);
  LCD_DisplayString(Line1,Column5,"Calibration");
  LCD_DisplayString(Line3,Column0,"LSE/64 is available");
  LCD_DisplayString(Line4,Column0,"on PC13.Measure the");
  LCD_DisplayString(Line5,Column0,"the frequency and");
  LCD_DisplayString(Line6,Column0,"press Sel to proceed");
  
  while(ReadKey()!=SEL)
  {
  }
  
  LCD_Clear(Blue2);
  BKP_RTCOutputConfig(BKP_RTCOutputSource_None);
  LCD_DisplayString(Line1,Column4,"Please enter");
  LCD_DisplayString(Line2,Column2,"Calibration Value");
  LCD_DisplayCount(Line4,Column6,1,ArrayTime[0]+0x30);
  LCD_DisplayCount(Line4,Column7,0,ArrayTime[1]+0x30);
  LCD_DisplayCount(Line4,Column8,0,ArrayTime[2]+0x30);
  LCD_DisplayString(Line6,Column6,"(0-121)");
  LCD_SetBackColor(Green);
  SelIntExtOnOffConfig(ENABLE);
}
Exemplo n.º 2
0
/* 配置是否使能64分频引脚 */
void cfg_rtc_pin(int enable)
{
	if (1 == enable) {
		BKP_TamperPinCmd(ENABLE);
		BKP_RTCOutputConfig(BKP_RTCOutputSource_CalibClock);
	} else {
		BKP_TamperPinCmd(DISABLE);
		BKP_RTCOutputConfig(BKP_RTCOutputSource_None);
	}

}
Exemplo n.º 3
0
/**
  * @brief  Apllication Initialisation Routine
  * @param  None
  * @retval : None
  */
void ApplicationInit(void)
{
  /* System Clocks Configuration */
  RCC_Configuration();
  /*Enables the clock to Backup and power interface peripherals    */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_BKP | RCC_APB1Periph_PWR,ENABLE);
  
  /* SysTick Configuration*/
  SysTickConfig();
  
  /*Initialisation of TFT LCD */
  STM3210B_LCD_Init();
  
  /* Unlock the Flash Program Erase controller */
  FLASH_Unlock();
  /*RTC_NVIC Configuration */
  RTC_NVIC_Configuration();
  
  /* RTC Configuration*/
  RTC_Configuration();
  BKP_RTCOutputConfig(BKP_RTCOutputSource_None);
  
  /* General Purpose I/O Configuration */
  GPIO_Configuration();
  
  /* Battery Removal Emulation   */
  GPIO_SetBits(GPIOC, GPIO_Pin_8);
  
  while(!(GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_13)))
  {
    TamperEvent = 1;
  }
  
  /* Joystick NVIC Configuration  */
  NVIC_JoyStickConfig();

  /* Tamper pin NVIC Configuration  */
  Tamper_NVIC_Configuration();

  /* Configure PVD Supervisor to disable the Tamper Interrupt when voltage drops 
  below 2.5 volts*/
  PWR_PVDCmd(ENABLE);
  PWR_PVDLevelConfig(PWR_PVDLevel_2V5);
  PWR_BackupAccessCmd(ENABLE);

  /* Only JoyStick Sel Interrupt is enabled on startup */
  SelIntExtOnOffConfig(ENABLE);

  /* Tamper FeatureRTC  -   Enable Tamper Interrupt and configure for Low level */
  BKP_ITConfig(ENABLE);

  /* Enable Tamper Pin for Active low level: Tamper level detected for low level*/
  BKP_TamperPinLevelConfig(BKP_TamperPinLevel_Low);

  /* Enable tamper Pin Interrupt */
  BKP_TamperPinCmd(ENABLE);

  /*  Menu Initialisation  */
  MenuInit();
}
Exemplo n.º 4
0
 /**
  * @file   RTC_Init
  * @brief  RTC Initialization
  * @param  无
  * @retval 无
  */
void RTC_Init(void)
{
  if (BKP_ReadBackupRegister(BKP_DR1)!= 0xA5A5)
  {
    /* Backup data register value is not correct or not yet programmed (when
    the first time the program is executed) */
    printf("RTC not yet configured....\r\n");
    /* RTC Configuration */
     RTC_Configuration();
	   Time_Regulate();
	/* Adjust time by values entred by the user on the hyperterminal */
    printf("RTC configured....\r\n");
    BKP_WriteBackupRegister(BKP_DR1, 0xA5A5);
  }
  else
  {
    /* Check if the Power On Reset flag is set */
    if (RCC_GetFlagStatus(RCC_FLAG_PORRST) != RESET)
    {
      printf("Power On Reset occurred....\r\n");
    }
    /* Check if the Pin Reset flag is set */
    else if (RCC_GetFlagStatus(RCC_FLAG_PINRST) != RESET)
    {
      printf("External Reset occurred....\r\n");
    }

    printf("No need to configure RTC....\r\n");
    /* Wait for RTC registers synchronization */
    RTC_WaitForSynchro();

    /* Enable the RTC Second */
    RTC_ITConfig(RTC_IT_SEC, ENABLE);
    /* Wait until last write operation on RTC registers has finished */
    RTC_WaitForLastTask();
  }

   /* NVIC configuration */
   NVIC_Configuration();

#ifdef RTCClockOutput_Enable
  /* Enable PWR and BKP clocks */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);

  /* Allow access to BKP Domain */
  PWR_BackupAccessCmd(ENABLE);

  /* Disable the Tamper Pin */
  BKP_TamperPinCmd(DISABLE); /* To output RTCCLK/64 on Tamper pin, the tamper
                                 functionality must be disabled */

  /* Enable RTC Clock Output on Tamper Pin */
  BKP_RTCOutputConfig(BKP_RTCOutputSource_CalibClock);
#endif

   /* Clear reset flags */
  RCC_ClearFlag();
  return;
}
Exemplo n.º 5
0
/**
  * @brief  Configures the RTC.
  * @param  None
  * @retval : None
  */
void RTC_Configuration(void)
{
  /* Enable PWR and BKP clocks */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);

  /* Allow access to BKP Domain */
  PWR_BackupAccessCmd(ENABLE);

  /* Reset Backup Domain */
  BKP_DeInit();

  /* Enable the LSI OSC */
  RCC_LSICmd(ENABLE);
  /* Wait till LSI is ready */
  while (RCC_GetFlagStatus(RCC_FLAG_LSIRDY) == RESET)
  {}
  /* Select the RTC Clock Source */
  RCC_RTCCLKConfig(RCC_RTCCLKSource_LSI);

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

  /* Wait for RTC registers synchronization */
  RTC_WaitForSynchro();

  /* Wait until last write operation on RTC registers has finished */
  RTC_WaitForLastTask();

  /* Enable the RTC Second */
  RTC_ITConfig(RTC_IT_SEC, ENABLE);

  /* Wait until last write operation on RTC registers has finished */
  RTC_WaitForLastTask();

  /* Set RTC prescaler: set RTC period to 1sec */
  RTC_SetPrescaler(40000);

  /* Wait until last write operation on RTC registers has finished */
  RTC_WaitForLastTask();

  /* To output second signal on Tamper pin, the tamper functionality
       must be disabled (by default this functionality is disabled) */
  BKP_TamperPinCmd(DISABLE);

  /* Enable the RTC Second Output on Tamper Pin */
  BKP_RTCOutputConfig(BKP_RTCOutputSource_Second);
}
Exemplo n.º 6
0
int main(void)
{
	uint8_t system_state=0, i2c_resets=0, si446x_resets=0;//used to track button press functionality and any errors
	uint8_t sensors=0;
	uint32_t repetition_counter=0;			//Used to detect any I2C lockup
	uint8_t L3GD20_Data_Buffer_old[8];		//Used to test for noise in the gyro data (indicating that it is working)
	uint8_t UplinkFlags=0,CutFlags=0;
	uint16_t UplinkBytes=0;				//Counters and flags for telemetry
	uint32_t last_telemetry=0,cutofftime=0,indtest=0,badgyro=0,permission_time=0,countdown_time=0,last_cuttest=0;
	uint16_t sentence_counter=0;
	uint8_t silab;
	//Cutdown config stuff here, atm uses hardcoded polygon defined in polygon.h
	static const int32_t Geofence[UK_GEOFENCE_POINTS*2]=UK_GEOFENCE;
	RTC_t RTC_time;
        _REENT_INIT_PTR(&my_reent);
        _impure_ptr = &my_reent;
	SystemInit();					//Sets up the clk
	setup_gpio();					//Initialised pins, and detects boot source
	DBGMCU_Config(DBGMCU_IWDG_STOP, ENABLE);	//Watchdog stopped during JTAG halt
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);/* Enable PWR and BKP clocks */
	PWR_BackupAccessCmd(ENABLE);/* Allow access to BKP Domain */
	uint16_t shutdown_lock=BKP_ReadBackupRegister(BKP_DR3);	//Holds the shutdown lock setting
	uint16_t reset_counter=BKP_ReadBackupRegister(BKP_DR2); //The number of consecutive failed reboot cycles
	PWR_BackupAccessCmd(DISABLE);
	if(RCC->CSR&RCC_CSR_IWDGRSTF && shutdown_lock!=SHUTDOWNLOCK_MAGIC) {//Watchdog reset, turn off
		RCC->CSR|=RCC_CSR_RMVF;			//Reset the reset flags
		shutdown();
	}
	if(USB_SOURCE==bootsource) {
		RCC->CFGR &= ~(uint32_t)RCC_CFGR_PPRE1_DIV16;
		RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV4;//Swap the ABP1 bus to run at 12mhz rather than 4 if we booted from USB, makes USB fast enough
	}
	SysTick_Configuration();			//Start up system timer at 100Hz for uSD card functionality
	Watchdog_Config(WATCHDOG_TIMEOUT);		//Set the watchdog
	Watchdog_Reset();				//Reset watchdog as soon as possible incase it is still running at power on
	rtc_init();					//Real time clock initialise - (keeps time unchanged if set)
	Usarts_Init();
	ISR_Config();
	rprintfInit(__usart_send_char);			//Printf over the bluetooth
	if(USB_SOURCE==bootsource) {
		Set_System();				//This actually just inits the storage layer
		Set_USBClock();
		USB_Interrupts_Config();
		USB_Init();
		uint32_t nojack=0x000FFFFF;		//Countdown timer - a few hundered ms of 0v on jack detect forces a shutdown
		while (bDeviceState != CONFIGURED) {	//Wait for USB config - timeout causes shutdown
			if((Millis>10000 && bDeviceState == UNCONNECTED)|| !nojack)	//No USB cable - shutdown (Charger pin will be set to open drain, cant be disabled without usb)
				shutdown();
			if(GET_VBUS_STATE)		//Jack detect resets the countdown
				nojack=0x0FFFFF;
			nojack--;
			Watchdog_Reset();		//Reset watchdog here, if we are stalled here the Millis timeout should catch us
		}
		PWR_BackupAccessCmd(ENABLE);		/* Allow access to BKP Domain */
		BKP_WriteBackupRegister(BKP_DR3,0x0000);//Wipe the shutdown lock setting
		PWR_BackupAccessCmd(DISABLE);
		while(1) {
			if(!(Millis%1000) && bDeviceState == SUSPENDED) {
				Delay(100);
				if(!GET_VBUS_STATE)
					shutdown();
			}
			Watchdog_Reset();
			__WFI();			//Sleep mode
		}
	}
        if(!GET_PWR_STATE && !(CoreDebug->DHCSR&0x00000001) && shutdown_lock!=SHUTDOWNLOCK_MAGIC) {//Check here to make sure the power button is still pressed, if not, sleep if no debug and not in always on flight mode
                shutdown();                             //This means a glitch on the supply line, or a power glitch results in sleep
        }
	// check to see if battery has enough charge to start
	ADC_Configuration();				//We leave this a bit later to allow stabilisation
	{
	uint32_t t=Millis;
	while(Millis<(t+100)){__WFI();}			//Sensor+inst amplifier takes about 100ms to stabilise after power on
	}
	if(Battery_Voltage<BATTERY_STARTUP_LIMIT) {	//We will have to turn off
		if(reset_counter<10)
			shutdown();
	}
	Watchdog_Reset();				//Card Init can take a second or two
	// system has passed battery level check and so file can be opened
	{//Context
	uint8_t silabs_header[5]={};
	uint8_t* silabs_header_=NULL;			//Pointer to the array (if all goes ok)
	if((f_err_code = f_mount(0, &FATFS_Obj)))Usart_Send_Str((char*)"FatFs mount error\r\n");//This should only error if internal error
	else {						//FATFS initialised ok, try init the card, this also sets up the SPI1
		if(!(f_err_code=f_open(&FATFS_logfile,(const TCHAR*)"time.txt",FA_OPEN_EXISTING|FA_READ|FA_WRITE))){//Try to open time file get system time
			if(!f_stat((const TCHAR *)"time.txt",&FATFS_info)) {//Get file info
				if(FATFS_info.fsize<5) {	//Empty file
					RTC_time.year=(FATFS_info.fdate>>9)+1980;//populate the time struct (FAT start==1980, RTC.year==0)
					RTC_time.month=(FATFS_info.fdate>>5)&0x000F;
					RTC_time.mday=FATFS_info.fdate&0x001F;
					RTC_time.hour=(FATFS_info.ftime>>11)&0x001F;
					RTC_time.min=(FATFS_info.ftime>>5)&0x003F;
					RTC_time.sec=(FATFS_info.ftime<<1)&0x003E;
					rtc_settime(&RTC_time);
					rprintfInit(__fat_print_char);//printf to the open file
					printf("RTC set to %d/%d/%d %d:%d:%d\n",RTC_time.mday,RTC_time.month,RTC_time.year,\
					RTC_time.hour,RTC_time.min,RTC_time.sec);
				}				
			}
			f_close(&FATFS_logfile);	//Close the time.txt file
		}
		// load settings if file exists
		Watchdog_Reset();			//Card Init can take a second or two
		if(!f_open(&FATFS_logfile,(const TCHAR *)"settings.dat",FA_OPEN_EXISTING | FA_READ)) {
			UINT br;
			int8_t rtc_correction;
			f_read(&FATFS_logfile, (void*)(&rtc_correction),sizeof(rtc_correction),&br);
			//Use the setting to apply correction to the RTC
                        if(br && (rtc_correction<30) && (rtc_correction>-92) && rtc_correction ) {
                                PWR_BackupAccessCmd(ENABLE);/* Allow access to BKP Domain */
                                uint16_t tweaked_prescale = (0x0001<<15)-2;/* Try to run the RTC slightly too fast so it can be corrected either way */
                                RTC_WaitForSynchro();   /* Wait for RTC registers synchronization */
                                if( RTC->PRLL != tweaked_prescale ) {/*Note that there is a 0.5ppm offset here (correction 0==0.5ppm slow)*/
                                        RTC_SetPrescaler(tweaked_prescale); /* RTC period = RTCCLK/RTC_PR = (32.768 KHz)/(32767-2+1) */
                                        RTC_WaitForLastTask();
                                }
                                BKP_SetRTCCalibrationValue((uint8_t) ((int16_t)31-(21*(int16_t)rtc_correction)/(int16_t)20) );
                                BKP_RTCOutputConfig(BKP_RTCOutputSource_None);/* Ensure any output is disabled here */
                                /* Lock access to BKP Domain */
                                PWR_BackupAccessCmd(DISABLE);
                        }
                        else if(br && ((uint8_t)rtc_correction==0x91) ) {/* 0x91 magic flag sets the RTC clock output on */
                                PWR_BackupAccessCmd(ENABLE);/* Allow access to BKP Domain */
                                BKP_RTCOutputConfig(BKP_RTCOutputSource_CalibClock);/* Output a 512Hz reference clock on the TAMPER pin*/
                                PWR_BackupAccessCmd(DISABLE);
                        }
			if(br) {
				f_read(&FATFS_logfile, (void*)(&shutdown_lock),sizeof(shutdown_lock),&br);/*This needs to be set with the same magic flag value*/
				if(br==2) {
                                	PWR_BackupAccessCmd(ENABLE);/* Allow access to BKP Domain */
					BKP_WriteBackupRegister(BKP_DR3,shutdown_lock);//Wipe the shutdown lock setting
                               		PWR_BackupAccessCmd(DISABLE);
				}
			}
			if(br==2) {			//Read was successful, next try to read 5 bytes of packet header
				f_read(&FATFS_logfile, (void*)(silabs_header),5,&br);
				if(br!=5)
					silabs_header_=silabs_header;
			}
			f_close(&FATFS_logfile);	//Close the settings.dat file
		}
#ifndef SINGLE_LOGFILE
		rtc_gettime(&RTC_time);			//Get the RTC time and put a timestamp on the start of the file
		rprintfInit(__str_print_char);		//Print to the string
		printf("%02d-%02d-%02dT%02d-%02d-%02d-%s.csv",RTC_time.year,RTC_time.month,RTC_time.mday,RTC_time.hour,RTC_time.min,RTC_time.sec,"Log");//Timestamp name
		rprintfInit(__usart_send_char);		//Printf over the bluetooth
#endif
		Watchdog_Reset();			//Card Init can take a second or two
		if((f_err_code=f_open(&FATFS_logfile,(TCHAR*)LOGFILE_NAME,FA_CREATE_ALWAYS | FA_WRITE))) {//Present
			Delay(10000);
			if((f_err_code=f_open(&FATFS_logfile,(TCHAR*)LOGFILE_NAME,FA_CREATE_ALWAYS | FA_WRITE))) {//Try again
				printf("FatFs drive error %d\r\n",f_err_code);
				if(f_err_code==FR_DISK_ERR || f_err_code==FR_NOT_READY)
					Usart_Send_Str((char*)"No uSD card inserted?\r\n");
			}
		}
		else {
			Watchdog_Reset();		//Card Init can take a second or two
			print_string[strlen(print_string)-4]=0x00;//Wipe the .csv off the string
			strcat(print_string,"_gyro.wav");
			if((f_err_code=f_open(&FATFS_wavfile_gyro,(TCHAR*)LOGFILE_NAME,FA_CREATE_ALWAYS | FA_WRITE))) {//Present
				printf("FatFs drive error %d\r\n",f_err_code);
				if(f_err_code==FR_DISK_ERR || f_err_code==FR_NOT_READY)
					Usart_Send_Str((char*)"No uSD card inserted?\r\n");
			}
			else {					//We have a mounted card
				f_err_code=f_lseek(&FATFS_logfile, PRE_SIZE);// Pre-allocate clusters
				if (f_err_code || f_tell(&FATFS_logfile) != PRE_SIZE)// Check if the file size has been increased correctly
					Usart_Send_Str((char*)"Pre-Allocation error\r\n");
				else {
					if((f_err_code=f_lseek(&FATFS_logfile, 0)))//Seek back to start of file to start writing
						Usart_Send_Str((char*)"Seek error\r\n");
					else
						rprintfInit(__str_print_char);//Printf to the logfile
				}
				if(f_err_code)
					f_close(&FATFS_logfile);//Close the already opened file on error
				else
					file_opened=1;		//So we know to close the file properly on shutdown
				if(file_opened==1) {
					Watchdog_Reset();	//Card Init can take a second or two
					if (f_err_code || f_tell(&FATFS_wavfile_gyro) != PRE_SIZE)// Check if the file size has been increased correctly
						Usart_Send_Str((char*)"Pre-Allocation error\r\n");
					else {
						if((f_err_code=f_lseek(&FATFS_logfile, 0)))//Seek back to start of file to start writing
							Usart_Send_Str((char*)"Seek error\r\n");
						else
							rprintfInit(__str_print_char);//Printf to the logfile
					}
					if(f_err_code)
						f_close(&FATFS_wavfile_gyro);//Close the already opened file on error
					else
						file_opened|=2;	//So we know to close the file properly on shutdown
				}
			}
		}
	}
	f_err_code|=write_wave_header(&FATFS_wavfile_gyro, 4, 100, 16);//4 channels, last channel is for the current rpm
	Watchdog_Reset();				//Card Init can take a second or two
	//Setup and test the silabs radio
	silab=si446x_setup(silabs_header_);
	if(silab!=0x44) {				//Should return the device code
		print_string[0]=0x00;
		printf("Silabs: %02x\n",silab);
		f_puts("Silabs detect error, got:",&FATFS_logfile);
		f_puts(print_string,&FATFS_logfile);
		shutdown_filesystem(ERR, file_opened);//So we log that something went wrong in the logfile
		shutdown();
	}
	}//Context
Exemplo n.º 7
0
/**
  * @brief  Setting up the time by Serial USART1.
  * @param  None
  * @retval None
  */
void RTC_SetTimeBySerial(void) {
  if (BKP_ReadBackupRegister(BKP_DR1) != 0xA5A5) {
    /* Backup data register value is not correct or not yet programmed (when
       the first time the program is executed) */

    printf("\r\n * Begin RTC initialization");
    
    /* RTC Configuration */
    RTC_Configuration();
    
    printf("\r\n * Please set calendar");
    
    /* setup year, month, date in 4, 2, 2 digits each */
    Date_Regulate();
    
    printf("\r\n * Please set time");

    /* Adjust time by values entered by the user on the hyperterminal */
    Time_Adjust();
    
    BKP_WriteBackupRegister(BKP_DR1, 0xA5A5);
  } else {
    /* Check if the Power On Reset flag is set */
    if (RCC_GetFlagStatus(RCC_FLAG_PORRST) != RESET) {
      printf("\r\n * Power On Reset occurred....");
    }
    /* Check if the Pin Reset flag is set */  
    else if (RCC_GetFlagStatus(RCC_FLAG_PINRST) != RESET) {
      printf("\r\n\n * External Reset occurred....");
    }

    printf("\r\n * No need to configure RTC....");
    
    /* Check whether we've written year or month or day value before */
    if(BKP_ReadBackupRegister(BKP_DR2) == 0x0000 || BKP_ReadBackupRegister(BKP_DR3) == 0x0000) {
      /* setup year, month, date in 4, 2, 2 digits each */
      Date_Regulate();
    } else {
      
      uint16_t YY, MD;
      YY = BKP_ReadBackupRegister(BKP_DR2);
      MD = BKP_ReadBackupRegister(BKP_DR3);
      
      int month, day;
      if( (MD / 1000) % 10 == 0) {
        month = (MD / 100) % 10;
      } else {
        month = (MD / 1000) % 10 + (MD / 100) % 10 ;
      }
      
      if( (MD / 10) % 10 == 0 ) {
        day = MD % 10;
      } else {
        day = MD - (MD / 100) * 100;
      }
      
      printf("\r\n\n Previous written calendar data found !");
      printf("\r\n Written values are as follows :");
      printf("\r\n Year : %d, Month : %d, Day : %d", YY, month, day);
      printf("\r\n Above calendar datas will be used to set current calendar automatically\r\n");
      
      TranslateIntoYear(YY);
      TranslateIntoMonth(month);
      TranslateIntoDay(day);
    }
        
    /* NVIC MUST BE CONFIGURED before branch into power on reset */
    NVIC_InitTypeDef NVIC_InitStructure;
    EXTI_InitTypeDef EXTI_InitStructure;
  
    /* Configure one bit for preemption priority */
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
  
    /* Enable the RTC Interrupt */
    NVIC_InitStructure.NVIC_IRQChannel = RTC_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
    
    NVIC_InitStructure.NVIC_IRQChannel = RTCAlarm_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0xFF;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
    
    /* Configure EXTI Line17 (RTC Alarm)to generate an interrupt on rising edge */
    EXTI_ClearITPendingBit(EXTI_Line17);
    EXTI_InitStructure.EXTI_Line = EXTI_Line17;
    EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
    EXTI_Init(&EXTI_InitStructure);
  
    /* Wait for RTC registers synchronization */
    RTC_WaitForSynchro();
    
    /* Wait until last write operation on RTC registers has finished */
    RTC_WaitForLastTask();
    
    /* Alarm in 3 second */
    //RTC_SetAlarm(3);
    
    /* Wait until last write operation on RTC registers has finished */
    RTC_WaitForLastTask();
    
    /* Enable the RTC Second, RTC Alarm interrupt */
    RTC_ITConfig(RTC_IT_SEC || RTC_IT_ALR, ENABLE);
    
    /* Wait until last write operation on RTC registers has finished */
    RTC_WaitForLastTask();
  }

#ifdef RTCClockOutput_Enable
  /* Enable PWR and BKP clocks */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);

  /* Allow access to BKP Domain */
  PWR_BackupAccessCmd(ENABLE);

  /* Disable the Tamper Pin */
  BKP_TamperPinCmd(DISABLE); /* To output RTCCLK/64 on Tamper pin, the tamper
                                 functionality must be disabled */

  /* Enable RTC Clock Output on Tamper Pin */
  BKP_RTCOutputConfig(BKP_RTCOutputSource_Second);
#endif
  
  /* Clear reset flags */
  RCC_ClearFlag();
}
Exemplo n.º 8
0
/**
 * @brief  COnfiguration of RTC Registers, Selection and Enabling of 
 *   RTC clock
 * @param  None
 * @retval : None
 */
void RTC_Configuration()
{
	uint16_t WaitForOscSource;

	/*Allow access to Backup Registers*/
	PWR_BackupAccessCmd(ENABLE);

	BKP_RTCOutputConfig(BKP_RTCOutputSource_None);

	if(READ_BKP_CONFIGURATION() != CONFIGURATION_DONE)
	{
		/*Enables the clock to Backup and power interface peripherals    */
		RCC_APB1PeriphClockCmd(RCC_APB1Periph_BKP | RCC_APB1Periph_PWR, ENABLE);

		/* Backup Domain Reset */
		BKP_DeInit();

		set_time(&s_DateStructVar);	 
		set_alarm(&s_AlarmDateStructVar);

		//EE_Format();

		/*Enable 32.768 kHz external oscillator */
		RCC_LSEConfig(RCC_LSE_ON);
		for(WaitForOscSource = 0; WaitForOscSource < 5000; WaitForOscSource++);   

		RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);

		/* RTC Enabled */
		RCC_RTCCLKCmd(ENABLE);
		RTC_WaitForLastTask();

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

		/* Setting RTC Interrupts-Seconds interrupt enabled */
		/* Enable the RTC Second */
		RTC_ITConfig(RTC_IT_SEC , ENABLE);
		RTC_WaitForLastTask();

		/* Set RTC prescaler: set RTC period to 1 sec */
		RTC_SetPrescaler(32765); /* RTC period = RTCCLK/RTC_PR = (32.768 KHz)/(32767+1) */
		/* Prescaler is set to 32766 instead of 32768 to compensate for
			lower as well as higher frequencies*/
		RTC_WaitForLastTask();

		WRITE_BKP_CONFIGURATION(CONFIGURATION_DONE);
	}
	else
	{
		/* PWR and BKP clocks selection */
		RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);
		for(WaitForOscSource = 0; WaitForOscSource < 5000; WaitForOscSource++);
		RTC_WaitForLastTask();

		/* Enable the RTC Alarm */
		RTC_ITConfig(RTC_IT_SEC, ENABLE);
		RTC_WaitForLastTask();
	}

	/* Check if how many days are elapsed in power down/Low Power Mode-
		Updates Date that many Times*/
	CheckForDaysElapsed();
}
Exemplo n.º 9
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       file (startup_stm32f10x_xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f10x.c file
     */     

  /* Initialize LED1 mounted on STM3210X-EVAL board */       
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA , ENABLE);
	
	 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 ; // USART 2
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIOA, &GPIO_InitStructure);
	
		 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 ; // USART 2
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	
  /* USARTx configured as follow:
        - BaudRate = 115200 baud  
        - Word Length = 8 Bits
        - One Stop Bit
        - No parity
        - Hardware flow control disabled (RTS and CTS signals)
        - Receive and transmit enabled
  */
	
	
	
	
	
	
  USART_InitStructure.USART_BaudRate = 115200;
  USART_InitStructure.USART_WordLength = USART_WordLength_8b;
  USART_InitStructure.USART_StopBits = USART_StopBits_1;
  USART_InitStructure.USART_Parity = USART_Parity_No;
  USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;

	
	USART_Init(USART1,&USART_InitStructure);
	USART_Cmd(USART1,  ENABLE);




  /* NVIC configuration */
  NVIC_Configuration();

  if (BKP_ReadBackupRegister(BKP_DR1) != 0xA5A5)
  {
    /* Backup data register value is not correct or not yet programmed (when
       the first time the program is executed) */

    printf("\r\n\n RTC not yet configured....");

    /* RTC Configuration */
    RTC_Configuration();

    printf("\r\n RTC configured....");

    /* Adjust time by values entered by the user on the hyperterminal */
    Time_Adjust();

    BKP_WriteBackupRegister(BKP_DR1, 0xA5A5);
  }
  else
  {
    /* Check if the Power On Reset flag is set */
    if (RCC_GetFlagStatus(RCC_FLAG_PORRST) != RESET)
    {
      printf("\r\n\n Power On Reset occurred....");
    }
    /* Check if the Pin Reset flag is set */
    else if (RCC_GetFlagStatus(RCC_FLAG_PINRST) != RESET)
    {
      printf("\r\n\n External Reset occurred....");
    }

    printf("\r\n No need to configure RTC....");
    /* Wait for RTC registers synchronization */
    RTC_WaitForSynchro();

    /* Enable the RTC Second */
    RTC_ITConfig(RTC_IT_SEC, ENABLE);
    /* Wait until last write operation on RTC registers has finished */
    RTC_WaitForLastTask();
  }

#ifdef RTCClockOutput_Enable
  /* Enable PWR and BKP clocks */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);

  /* Allow access to BKP Domain */
  PWR_BackupAccessCmd(ENABLE);

  /* Disable the Tamper Pin */
  BKP_TamperPinCmd(DISABLE); /* To output RTCCLK/64 on Tamper pin, the tamper
                                 functionality must be disabled */

  /* Enable RTC Clock Output on Tamper Pin */
  BKP_RTCOutputConfig(BKP_RTCOutputSource_CalibClock);
#endif

  /* Clear reset flags */
  RCC_ClearFlag();

  /* Display time in infinite loop */
  Time_Show();
}
Exemplo n.º 10
0
/**
  * @brief  Calibration of External crystal oscillator auto(through Timer
  *   
  * @param  None
  * @retval : None
  */
void AutoClockCalibration(void)
{
  RCC_ClocksTypeDef ClockValue;
  uint16_t TimerPrescalerValue=0x0003;
  uint16_t CountWait;
  uint16_t DeviationInteger;
  uint32_t CalibrationTimer;
  float f32_Deviation;
  TIM_ICInitTypeDef  TIM_ICInitStructure;
  
  TIM_DeInit(TIM2);
  BKP_TamperPinCmd(DISABLE);
  BKP_RTCOutputConfig(BKP_RTCOutputSource_CalibClock);
  
  /* TIM2 configuration: PWM Input mode ------------------------
     The external signal is connected to TIM2 CH2 pin (PA.01),
     The Rising edge is used as active edge,
     The TIM2 CCR2 is used to compute the frequency value
     The TIM2 CCR1 is used to compute the duty cycle value
  ------------------------------------------------------------ */
  TIM_PrescalerConfig(TIM2,TimerPrescalerValue,TIM_PSCReloadMode_Immediate);
  TIM_ICInitStructure.TIM_Channel = TIM_Channel_2;
  TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
  TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
  TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
  TIM_ICInitStructure.TIM_ICFilter = 0x00;
  TIM_PWMIConfig(TIM2, &TIM_ICInitStructure);
  TIM_ICInit(TIM2, &TIM_ICInitStructure);
  /* Select the TIM2 Input Trigger: TI2FP2 */
  TIM_SelectInputTrigger(TIM2, TIM_TS_TI2FP2);
  /* Select the slave Mode: Reset Mode */
  TIM_SelectSlaveMode(TIM2, TIM_SlaveMode_Reset);
  /* Enable the Master/Slave Mode */
  TIM_SelectMasterSlaveMode(TIM2, TIM_MasterSlaveMode_Enable);
  /* TIM enable Counter */
  TIM_Cmd(TIM2, ENABLE);
  LCD_Clear(Blue2);
  LCD_DisplayString(Line4,Column1,"Please Wait.....");
  /* Wait for 2 seconds */
  CalibrationTimer = RTC_GetCounter();
 
  while((RTC_GetCounter() - CalibrationTimer) < 2)
  {
  }
  
  RCC_GetClocksFreq(&ClockValue);
  TimerFrequency=(ClockValue.PCLK1_Frequency * 2)/(TimerPrescalerValue+1);
   /* Enable the CC2 Interrupt Request */
  TIM_ITConfig(TIM2, TIM_IT_CC2, ENABLE);
   /* Wait for 2 seconds */
  CalibrationTimer = RTC_GetCounter();
  
  while((RTC_GetCounter() - CalibrationTimer) < 2)
  {
  }

  if(!(TIM_GetFlagStatus(TIM2, TIM_FLAG_CC1)))
   /* There is no signal at the timer TIM2 peripheral input */
  {
    LCD_Clear(Blue2);
    LCD_DisplayString(Line3,Column0,"Please connect wire");
    LCD_DisplayString(Line4,Column0,"link between PC13");
    LCD_DisplayString(Line5,Column0,"and PA1");
    LCD_DisplayString(Line7,Column0,"No calibration done");
  }
  else
  {
    /* Calulate Deviation in ppm  using the formula :
    Deviation in ppm = (Deviation from 511.968/511.968)*1 million*/
    if(f32_Frequency > 511.968)
    {
      f32_Deviation=((f32_Frequency-511.968)/511.968)*1000000;
    }
    else
    {
      f32_Deviation=((511.968-f32_Frequency)/511.968)*1000000;
    }
     DeviationInteger = (uint16_t)f32_Deviation;
    
    if(f32_Deviation >= (DeviationInteger + 0.5))
    {
      DeviationInteger = ((uint16_t)f32_Deviation)+1;
    }
    
   CountWait=0;

   /* Frequency deviation in ppm should be les than equal to 121 ppm*/
   if(DeviationInteger <= 121)
   {
     while(CountWait<128)
     {
       if(CalibrationPpm[CountWait] == DeviationInteger)
       break;
       CountWait++;
     }

     BKP_SetRTCCalibrationValue(CountWait);
     LCD_Clear(Blue2);
     LCD_DisplayString(Line4,Column1,"Calibration Value");
     LCD_DisplayChar(Line5,Column10,(CountWait%10)+0x30);
     CountWait=CountWait/10;
     LCD_DisplayChar(Line5,Column9,(CountWait%10)+0x30);
     CountWait=CountWait/10;
   
     if(CountWait>0)
     {
       LCD_DisplayChar(Line5,Column8,(CountWait%10)+0x30);
     }
   }
   else /* Frequency deviation in ppm is more than 121 ppm, hence calibration
           can not be done */
   {
     LCD_Clear(Blue2);
     LCD_DisplayString(Line3,Column1,"Out Of Calibration");
     LCD_DisplayString(Line4,Column4,"Range");
   }
  }
  
  BKP_RTCOutputConfig(BKP_RTCOutputSource_None);
  TIM_ITConfig(TIM2, TIM_IT_CC2, DISABLE);
  TIM_Cmd(TIM2, DISABLE);
  TIM_DeInit(TIM2);
  CalibrationTimer=RTC_GetCounter();
  
  /*  Wait for 2 seconds  */
  while((RTC_GetCounter() - CalibrationTimer) < 5)
  {
  }
  
  MenuInit();
}
Exemplo n.º 11
0
/*
 * 函数名:RTC_CheckAndConfig
 * 描述  :检查并配置RTC
 * 输入  :用于读取RTC时间的结构体指针
 * 输出  :无
 * 调用  :外部调用
 */
void RTC_CheckAndConfig(struct rtc_time *tm)
{
   	  /*在启动时检查备份寄存器BKP_DR1,如果内容不是0xA5A5,
	  则需重新配置时间并询问用户调整时间*/
	if (BKP_ReadBackupRegister(BKP_DR1) != 0xA5A5)
	{
		printf("\r\n\r\n RTC not yet configured....");

		/* RTC Configuration */
		RTC_Configuration();
		
		printf("\r\n\r\n RTC configured....");

		/* Adjust time by users typed on the hyperterminal */
		Time_Adjust(tm);

		BKP_WriteBackupRegister(BKP_DR1, 0xA5A5);
	}
	else
	{
	  /*启动无需设置新时钟*/
		/*检查是否掉电重启*/
		if (RCC_GetFlagStatus(RCC_FLAG_PORRST) != RESET)
		{
		    printf("\r\n\r\n Power On Reset occurred....");
		}
		/*检查是否Reset复位*/
		else if (RCC_GetFlagStatus(RCC_FLAG_PINRST) != RESET)
		{
			printf("\r\n\r\n External Reset occurred....");
		}
	
		printf("\r\n No need to configure RTC....");
		
		/*等待寄存器同步*/
		RTC_WaitForSynchro();
		
		/*允许RTC秒中断*/
		RTC_ITConfig(RTC_IT_SEC, ENABLE);
		
		/*等待上次RTC寄存器写操作完成*/
		RTC_WaitForLastTask();
	}
	   /*定义了时钟输出宏,则配置校正时钟输出到PC13*/
	#ifdef RTCClockOutput_Enable
	  /* Enable PWR and BKP clocks */
	  RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);
	
	  /* Allow access to BKP Domain */
	  PWR_BackupAccessCmd(ENABLE);
	
	  /* Disable the Tamper Pin */
	  BKP_TamperPinCmd(DISABLE); /* To output RTCCLK/64 on Tamper pin, the tamper
	                                 functionality must be disabled */
	
	  /* Enable RTC Clock Output on Tamper Pin */
	  BKP_RTCOutputConfig(BKP_RTCOutputSource_CalibClock);
	#endif
	
	  /* Clear reset flags */
	  RCC_ClearFlag();

}
Exemplo n.º 12
0
/*******************************************************************************
* Function Name  : AutoClockCalibration
* Description    : Calibration of External crystal oscillator auto(through Timer
                   peripheral)
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
void AutoClockCalibration(void)
{
  RCC_ClocksTypeDef ClockValue;
  u16 u16_TimerPrescalerValue=0x0003;
  u16 u16_CountWait;
  u16 u16_DeviationInteger;
  u32 u32_CalibrationTimer;
  float f32_Deviation;
  TIM_ICInitTypeDef  TIM_ICInitStructure;
  
  TIM_DeInit(TIM2);
  BKP_TamperPinCmd(DISABLE);
  BKP_RTCOutputConfig(BKP_RTCOutputSource_CalibClock);
  
  /* TIM2 configuration: PWM Input mode ------------------------
     The external signal is connected to TIM2 CH2 pin (PA.01),
     The Rising edge is used as active edge,
     The TIM2 CCR2 is used to compute the frequency value
     The TIM2 CCR1 is used to compute the duty cycle value
  ------------------------------------------------------------ */
  TIM_PrescalerConfig(TIM2,u16_TimerPrescalerValue,TIM_PSCReloadMode_Immediate);
  TIM_ICInitStructure.TIM_Channel = TIM_Channel_2;
  TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
  TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
  TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
  TIM_ICInitStructure.TIM_ICFilter = 0x00;
  TIM_PWMIConfig(TIM2, &TIM_ICInitStructure);
  TIM_ICInit(TIM2, &TIM_ICInitStructure);
  /* Select the TIM2 Input Trigger: TI2FP2 */
  TIM_SelectInputTrigger(TIM2, TIM_TS_TI2FP2);
  /* Select the slave Mode: Reset Mode */
  TIM_SelectSlaveMode(TIM2, TIM_SlaveMode_Reset);
  /* Enable the Master/Slave Mode */
  TIM_SelectMasterSlaveMode(TIM2, TIM_MasterSlaveMode_Enable);
  /* TIM enable u16_Counter */
  TIM_Cmd(TIM2, ENABLE);

  /* Wait for 2 seconds */
  u32_CalibrationTimer = RTC_GetCounter();
 
  while((RTC_GetCounter() - u32_CalibrationTimer) < 2)
  {
  }
  
  RCC_GetClocksFreq(&ClockValue);
  u32_TimerFrequency=(ClockValue.PCLK1_Frequency * 2)/(u16_TimerPrescalerValue+1);
   /* Enable the CC2 Interrupt Request */
  TIM_ITConfig(TIM2, TIM_IT_CC2, ENABLE);
   /* Wait for 2 seconds */
  u32_CalibrationTimer = RTC_GetCounter();
  
  while((RTC_GetCounter() - u32_CalibrationTimer) < 2)
  {
  }

  if(!(TIM_GetFlagStatus(TIM2, TIM_FLAG_CC1)))
   /* There is no signal at the timer TIM2 peripheral input */
  {

  }
  else
  {
    /* Calulate Deviation in ppm  using the formula :
    Deviation in ppm = (Deviation from 511.968/511.968)*1 million*/
    if(f32_Frequency > 511.968)
    {
      f32_Deviation=((f32_Frequency-511.968)/511.968)*1000000;
    }
    else
    {
      f32_Deviation=((511.968-f32_Frequency)/511.968)*1000000;
    }
     u16_DeviationInteger = (u16)f32_Deviation;
    
    if(f32_Deviation >= (u16_DeviationInteger + 0.5))
    {
      u16_DeviationInteger = ((u16)f32_Deviation)+1;
    }
    
   u16_CountWait=0;

   /* Frequency deviation in ppm should be les than equal to 121 ppm*/
   if(u16_DeviationInteger <= 121)
   {
     while(u16_CountWait<128)
     {
       if(u8_CalibrationPpm[u16_CountWait] == u16_DeviationInteger)
       break;
       u16_CountWait++;
     }

     BKP_SetRTCCalibrationValue(u16_CountWait);

     u16_CountWait=u16_CountWait/10;

     u16_CountWait=u16_CountWait/10;
   
     if(u16_CountWait>0)
     {

     }
   }
   else /* Frequency deviation in ppm is more than 121 ppm, hence calibration
           can not be done */
   {

   }
  }
  
  BKP_RTCOutputConfig(BKP_RTCOutputSource_None);
  TIM_ITConfig(TIM2, TIM_IT_CC2, DISABLE);
  TIM_Cmd(TIM2, DISABLE);
  TIM_DeInit(TIM2);
  u32_CalibrationTimer=RTC_GetCounter();
  
  /*  Wait for 2 seconds  */
  while((RTC_GetCounter() - u32_CalibrationTimer) < 5)
  {
  }
  
  //MenuInit();
}
Exemplo n.º 13
0
/*******************************************************************************
* Function Name  : RTC_Config
* Description    : 上电时调用本函数,自动检查是否需要RTC初始化, 
* 					若需要重新初始化RTC,则调用RTC_Configuration()完成相应操作
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
void RTC_Config(void)
{
	NVIC_InitTypeDef NVIC_InitStructure;

   //启用PWR和BKP的时钟(from APB1)
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);

	//后备域解锁
	PWR_BackupAccessCmd(ENABLE);   //此要加,否则重启后无法更改时间

	//我们在BKP的后备寄存器1中,存了一个特殊字符0xA5A5
	//第一次上电或后备电源掉电后,该寄存器数据丢失,
	//表明RTC数据丢失,需要重新配置
	if (BKP_ReadBackupRegister(BKP_DR1) != 0xEDED)
	{
		//重新配置RTC
		RTC_Configuration();
		//配置完成后,向后备寄存器中写特殊字符0xA5A5
		BKP_WriteBackupRegister(BKP_DR1, 0xEDED);
		// Lcd_WriteString(0,1,0,Red,"ver 1.0");
	}
	else
	{
		//若后备寄存器没有掉电,则无需重新配置RTC
		//这里我们可以利用RCC_GetFlagStatus()函数查看本次复位类型
		if (RCC_GetFlagStatus(RCC_FLAG_PORRST) != RESET)
		{
			//Lcd_WriteString(0,3,0,Red,"BATTER OFF");//这是上电复位
		}
		else if (RCC_GetFlagStatus(RCC_FLAG_PINRST) != RESET)
		{
		//	Lcd_WriteString(0,3,0,Red,"RESET");//这是外部RST管脚复位
		}
		//清除RCC中复位标志
		RCC_ClearFlag();

		//虽然RTC模块不需要重新配置,且掉电后依靠后备电池依然运行
		//但是每次上电后,还是要使能RTCCLK???????
		//RCC_RTCCLKCmd(ENABLE);
		//等待RTC时钟与APB1时钟同步
		//RTC_WaitForSynchro();

		//使能秒中断
		RTC_ITConfig(RTC_IT_SEC, ENABLE);
	//	RTC_ITConfig(RTC_IT_OW, ENABLE);
		//等待操作完成
		RTC_WaitForLastTask();
	}

#ifdef RTCClockOutput_Enable
	


	/* Allow access to BKP Domain */
	PWR_BackupAccessCmd(ENABLE);

	/* Disable the Tamper Pin */
	BKP_TamperPinCmd(DISABLE); /* To output RTCCLK/64 on Tamper pin, the tamper
								 functionality must be disabled */

	/* Enable RTC Clock Output on Tamper Pin */
	BKP_RTCOutputConfig(BKP_RTCOutputSource_CalibClock);
#endif

  #ifdef  VECT_TAB_RAM
	NVIC_SetVectorTable(NVIC_VectTab_RAM, 0x0);
  #else  /* VECT_TAB_FLASH  */
	NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x0);
  #endif

  
  /* Configure one bit for preemption priority */
  NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
  
  /* Enable the RTC Interrupt */
  NVIC_InitStructure.NVIC_IRQChannel = RTC_IRQChannel;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

	return;
}
Exemplo n.º 14
0
void RtcInit(void)
{

	RTC_Configuration();
	
	if (BKP_ReadBackupRegister(BKP_DR1) != 0xA5A5)
  {
		/* Backup data register value is not correct or not yet programmed (when
			 the first time the program is executed) */
		printf("\r\n> RTC not yet configured....");
		SetRtcTime();
  }
  else
  {
    /* Check if the Power On Reset flag is set */
    if (RCC_GetFlagStatus(RCC_FLAG_PORRST) != RESET)
    {
      printf("\r\n> Power On Reset occurred....");
    }
    /* Check if the Pin Reset flag is set */
    else if (RCC_GetFlagStatus(RCC_FLAG_PINRST) != RESET)
    {
      printf("\r\n> External Reset occurred....");
    }

    printf("\r\n> No need to configure RTC....");
    /* Wait for RTC registers synchronization */
    RTC_WaitForSynchro();

    /* Enable the RTC Second */
    RTC_ITConfig(RTC_IT_SEC, ENABLE);

    /* Wait until last write operation on RTC registers has finished */
    RTC_WaitForLastTask();
  }

#ifdef RTCClockOutput_Enable
  /* Enable PWR and BKP clocks */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);

  /* Allow access to BKP Domain */
  PWR_BackupAccessCmd(ENABLE);

  /* Disable the Tamper Pin */
  BKP_TamperPinCmd(DISABLE); /* To output RTCCLK/64 on Tamper pin, the tamper
                                 functionality must be disabled */

  /* Enable RTC Clock Output on Tamper Pin */
  BKP_RTCOutputConfig(BKP_RTCOutputSource_CalibClock);
#endif

  /* Clear reset flags */
  RCC_ClearFlag();
	
	// Rx8025 对时
	time_set.tm_year	= 2000+ExRtcTime.year;
	time_set.tm_mon		= ExRtcTime.mon;
	time_set.tm_mday	= ExRtcTime.day;
	time_set.tm_hour	= ExRtcTime.hour;
	time_set.tm_min 	= ExRtcTime.min;
	time_set.tm_sec 	= ExRtcTime.sec;

	Time_SetCalendarTime(time_set);	
	
	
	
	
	
}
Exemplo n.º 15
0
// init RTC
void rtc_init(void)
{
    uint16_t WaitForOscSource;
    
		/*RTC_NVIC Configuration */
    RTC_NVIC_Configuration();
	
    /*Enables the clock to Backup and power interface peripherals    */
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_BKP | RCC_APB1Periph_PWR,ENABLE);

    /*Allow access to Backup Registers*/
    PWR_BackupAccessCmd(ENABLE);
    if(BKP_ReadBackupRegister(BKP_DR1)== (uint16_t)(~CONFIGURATION_DONE))
    {
        /*Enables the clock to Backup and power interface peripherals    */
        RCC_APB1PeriphClockCmd(RCC_APB1Periph_BKP | RCC_APB1Periph_PWR,ENABLE);

        /* Backup Domain Reset */
        BKP_DeInit();
        systime.Month=DEFAULT_MONTH;
        systime.Day=DEFAULT_DAY;
        systime.Year=DEFAULT_YEAR;

        BKP_ModifyBackupRegister(BKP_DR3, (systime.Month << 8) | systime.Day);
        BKP_ModifyBackupRegister(BKP_DR5, systime.Year);
            
        /* Wait until last write operation on RTC registers has finished */
        RTC_WaitForLastTask();
        /* enter config mode */
        RTC_EnterConfigMode();
        /*Enable 32.768 kHz external oscillator */
        RCC_LSEConfig(RCC_LSE_ON);
        /* select clock source for RTC */
        RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);
        /* RTC Enabled */
        RCC_RTCCLKCmd(ENABLE);
        /*Wait for RTC registers synchronisation */
        RTC_WaitForSynchro();
        RTC_WaitForLastTask();
        /* Setting RTC Interrupts-Seconds interrupt enabled */
        /* Enable the RTC Second */
        RTC_ITConfig(RTC_IT_SEC , ENABLE);
        /* Wait until last write operation on RTC registers has finished */
        RTC_WaitForLastTask();
        /* init prescale value*/
        RTC_SetPrescaler(32767);
        /* exit config mode */
        RTC_ExitConfigMode();

        /* Set default system time to 09 : 24 : 00 */
        SetTime(DEFAULT_HOURS,DEFAULT_MINUTES);
        BKP_ModifyBackupRegister(BKP_DR1, CONFIGURATION_DONE);
    }
    else
    {
        /* PWR and BKP clocks selection */
        RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);
        for(WaitForOscSource=0;WaitForOscSource<5000;WaitForOscSource++);
        /* Wait until last write operation on RTC registers has finished */
        RTC_WaitForLastTask();
        /* Enable the RTC Second */
        RTC_ITConfig(RTC_IT_SEC, ENABLE);
        RTC_WaitForLastTask();
    }

    /* Check if how many days are elapsed in power down/Low Power Mode-
        Updates Date that many Times*/
    CheckForDaysElapsed();
    systime.Month = (uint8_t)(BKP_ReadBackupRegister(BKP_DR3) >> 8);
    systime.Day = (uint8_t)BKP_ReadBackupRegister(BKP_DR3);
    systime.Year = (uint8_t)BKP_ReadBackupRegister(BKP_DR5);
    
    BKP_RTCOutputConfig(BKP_RTCOutputSource_None);
}