Merge pull request #93 from zyp/master
[fw/stlink] / example / stm32f4 / Projects / IO_Toggle / system_stm32f4xx.c
1 /**
2   ******************************************************************************
3   * @file    system_stm32f4xx.c
4   * @author  MCD Application Team
5   * @version V1.0.0
6   * @date    19-September-2011
7   * @brief   CMSIS Cortex-M4 Device Peripheral Access Layer System Source File.
8   *          This file contains the system clock configuration for STM32F4xx devices,
9   *          and is generated by the clock configuration tool
10   *          stm32f4xx_Clock_Configuration_V1.0.0.xls
11   *             
12   * 1.  This file provides two functions and one global variable to be called from 
13   *     user application:
14   *      - SystemInit(): Setups the system clock (System clock source, PLL Multiplier
15   *                      and Divider factors, AHB/APBx prescalers and Flash settings),
16   *                      depending on the configuration made in the clock xls tool. 
17   *                      This function is called at startup just after reset and 
18   *                      before branch to main program. This call is made inside
19   *                      the "startup_stm32f4xx.s" file.
20   *
21   *      - SystemCoreClock variable: Contains the core clock (HCLK), it can be used
22   *                                  by the user application to setup the SysTick 
23   *                                  timer or configure other parameters.
24   *                                     
25   *      - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must
26   *                                 be called whenever the core clock is changed
27   *                                 during program execution.
28   *
29   * 2. After each device reset the HSI (16 MHz) is used as system clock source.
30   *    Then SystemInit() function is called, in "startup_stm32f4xx.s" file, to
31   *    configure the system clock before to branch to main program.
32   *
33   * 3. If the system clock source selected by user fails to startup, the SystemInit()
34   *    function will do nothing and HSI still used as system clock source. User can 
35   *    add some code to deal with this issue inside the SetSysClock() function.
36   *
37   * 4. The default value of HSE crystal is set to 8 MHz, refer to "HSE_VALUE" define
38   *    in "stm32f4xx.h" file. When HSE is used as system clock source, directly or
39   *    through PLL, and you are using different crystal you have to adapt the HSE
40   *    value to your own configuration.
41   *
42   * 5. This file configures the system clock as follows:
43   *=============================================================================
44   *=============================================================================
45   *        Supported STM32F4xx device revision    | Rev A
46   *-----------------------------------------------------------------------------
47   *        System Clock source                    | PLL (HSE)
48   *-----------------------------------------------------------------------------
49   *        SYSCLK(Hz)                             | 168000000
50   *-----------------------------------------------------------------------------
51   *        HCLK(Hz)                               | 168000000
52   *-----------------------------------------------------------------------------
53   *        AHB Prescaler                          | 1
54   *-----------------------------------------------------------------------------
55   *        APB1 Prescaler                         | 4
56   *-----------------------------------------------------------------------------
57   *        APB2 Prescaler                         | 2
58   *-----------------------------------------------------------------------------
59   *        HSE Frequency(Hz)                      | 8000000
60   *-----------------------------------------------------------------------------
61   *        PLL_M                                  | 8
62   *-----------------------------------------------------------------------------
63   *        PLL_N                                  | 336
64   *-----------------------------------------------------------------------------
65   *        PLL_P                                  | 2
66   *-----------------------------------------------------------------------------
67   *        PLL_Q                                  | 7
68   *-----------------------------------------------------------------------------
69   *        PLLI2S_N                               | NA
70   *-----------------------------------------------------------------------------
71   *        PLLI2S_R                               | NA
72   *-----------------------------------------------------------------------------
73   *        I2S input clock                        | NA
74   *-----------------------------------------------------------------------------
75   *        VDD(V)                                 | 3.3
76   *-----------------------------------------------------------------------------
77   *        High Performance mode                  | Enabled
78   *-----------------------------------------------------------------------------
79   *        Flash Latency(WS)                      | 5
80   *-----------------------------------------------------------------------------
81   *        Prefetch Buffer                        | OFF
82   *-----------------------------------------------------------------------------
83   *        Instruction cache                      | ON
84   *-----------------------------------------------------------------------------
85   *        Data cache                             | ON
86   *-----------------------------------------------------------------------------
87   *        Require 48MHz for USB OTG FS,          | Enabled
88   *        SDIO and RNG clock                     |
89   *-----------------------------------------------------------------------------
90   *=============================================================================
91   ****************************************************************************** 
92   * @attention
93   *
94   * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
95   * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
96   * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
97   * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
98   * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
99   * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
100   *
101   * <h2><center>&copy; COPYRIGHT 2011 STMicroelectronics</center></h2>
102   ******************************************************************************
103   */
104
105 /** @addtogroup CMSIS
106   * @{
107   */
108
109 /** @addtogroup stm32f4xx_system
110   * @{
111   */  
112   
113 /** @addtogroup STM32F4xx_System_Private_Includes
114   * @{
115   */
116
117 #include "stm32f4xx.h"
118
119 /**
120   * @}
121   */
122
123 /** @addtogroup STM32F4xx_System_Private_TypesDefinitions
124   * @{
125   */
126
127 /**
128   * @}
129   */
130
131 /** @addtogroup STM32F4xx_System_Private_Defines
132   * @{
133   */
134
135 /*!< Uncomment the following line if you need to use external SRAM mounted
136      on STM324xG_EVAL board as data memory  */
137 /* #define DATA_IN_ExtSRAM */
138
139 /*!< Uncomment the following line if you need to relocate your vector Table in
140      Internal SRAM. */
141 /* #define VECT_TAB_SRAM */
142 #define VECT_TAB_OFFSET  0x00 /*!< Vector Table base offset field. 
143                                    This value must be a multiple of 0x200. */
144
145
146 /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLL_M) * PLL_N */
147 #define PLL_M      8
148 #define PLL_N      336
149
150 /* SYSCLK = PLL_VCO / PLL_P */
151 #define PLL_P      2
152
153 /* USB OTG FS, SDIO and RNG Clock =  PLL_VCO / PLLQ */
154 #define PLL_Q      7
155
156 /**
157   * @}
158   */
159
160 /** @addtogroup STM32F4xx_System_Private_Macros
161   * @{
162   */
163
164 /**
165   * @}
166   */
167
168 /** @addtogroup STM32F4xx_System_Private_Variables
169   * @{
170   */
171
172   uint32_t SystemCoreClock = 168000000;
173
174   __I uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9};
175
176 /**
177   * @}
178   */
179
180 /** @addtogroup STM32F4xx_System_Private_FunctionPrototypes
181   * @{
182   */
183
184 static void SetSysClock(void);
185 #ifdef DATA_IN_ExtSRAM
186   static void SystemInit_ExtMemCtl(void); 
187 #endif /* DATA_IN_ExtSRAM */
188
189 /**
190   * @}
191   */
192
193 /** @addtogroup STM32F4xx_System_Private_Functions
194   * @{
195   */
196
197 /**
198   * @brief  Setup the microcontroller system
199   *         Initialize the Embedded Flash Interface, the PLL and update the 
200   *         SystemFrequency variable.
201   * @param  None
202   * @retval None
203   */
204 void SystemInit(void)
205 {
206   /* Reset the RCC clock configuration to the default reset state ------------*/
207   /* Set HSION bit */
208   RCC->CR |= (uint32_t)0x00000001;
209
210   /* Reset CFGR register */
211   RCC->CFGR = 0x00000000;
212
213   /* Reset HSEON, CSSON and PLLON bits */
214   RCC->CR &= (uint32_t)0xFEF6FFFF;
215
216   /* Reset PLLCFGR register */
217   RCC->PLLCFGR = 0x24003010;
218
219   /* Reset HSEBYP bit */
220   RCC->CR &= (uint32_t)0xFFFBFFFF;
221
222   /* Disable all interrupts */
223   RCC->CIR = 0x00000000;
224
225 #ifdef DATA_IN_ExtSRAM
226   SystemInit_ExtMemCtl(); 
227 #endif /* DATA_IN_ExtSRAM */
228          
229   /* Configure the System clock source, PLL Multiplier and Divider factors, 
230      AHB/APBx prescalers and Flash settings ----------------------------------*/
231   SetSysClock();
232
233   /* Configure the Vector Table location add offset address ------------------*/
234 #ifdef VECT_TAB_SRAM
235   SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */
236 #else
237   SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */
238 #endif
239 }
240
241 /**
242    * @brief  Update SystemCoreClock variable according to Clock Register Values.
243   *         The SystemCoreClock variable contains the core clock (HCLK), it can
244   *         be used by the user application to setup the SysTick timer or configure
245   *         other parameters.
246   *           
247   * @note   Each time the core clock (HCLK) changes, this function must be called
248   *         to update SystemCoreClock variable value. Otherwise, any configuration
249   *         based on this variable will be incorrect.         
250   *     
251   * @note   - The system frequency computed by this function is not the real 
252   *           frequency in the chip. It is calculated based on the predefined 
253   *           constant and the selected clock source:
254   *             
255   *           - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*)
256   *                                              
257   *           - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(**)
258   *                          
259   *           - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(**) 
260   *             or HSI_VALUE(*) multiplied/divided by the PLL factors.
261   *         
262   *         (*) HSI_VALUE is a constant defined in stm32f4xx.h file (default value
263   *             16 MHz) but the real value may vary depending on the variations
264   *             in voltage and temperature.   
265   *    
266   *         (**) HSE_VALUE is a constant defined in stm32f4xx.h file (default value
267   *              25 MHz), user has to ensure that HSE_VALUE is same as the real
268   *              frequency of the crystal used. Otherwise, this function may
269   *              have wrong result.
270   *                
271   *         - The result of this function could be not correct when using fractional
272   *           value for HSE crystal.
273   *     
274   * @param  None
275   * @retval None
276   */
277 void SystemCoreClockUpdate(void)
278 {
279   uint32_t tmp = 0, pllvco = 0, pllp = 2, pllsource = 0, pllm = 2;
280   
281   /* Get SYSCLK source -------------------------------------------------------*/
282   tmp = RCC->CFGR & RCC_CFGR_SWS;
283
284   switch (tmp)
285   {
286     case 0x00:  /* HSI used as system clock source */
287       SystemCoreClock = HSI_VALUE;
288       break;
289     case 0x04:  /* HSE used as system clock source */
290       SystemCoreClock = HSE_VALUE;
291       break;
292     case 0x08:  /* PLL used as system clock source */
293
294       /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLL_M) * PLL_N
295          SYSCLK = PLL_VCO / PLL_P
296          */    
297       pllsource = (RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) >> 22;
298       pllm = RCC->PLLCFGR & RCC_PLLCFGR_PLLM;
299       
300       if (pllsource != 0)
301       {
302         /* HSE used as PLL clock source */
303         pllvco = (HSE_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6);
304       }
305       else
306       {
307         /* HSI used as PLL clock source */
308         pllvco = (HSI_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6);      
309       }
310
311       pllp = (((RCC->PLLCFGR & RCC_PLLCFGR_PLLP) >>16) + 1 ) *2;
312       SystemCoreClock = pllvco/pllp;
313       break;
314     default:
315       SystemCoreClock = HSI_VALUE;
316       break;
317   }
318   /* Compute HCLK frequency --------------------------------------------------*/
319   /* Get HCLK prescaler */
320   tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)];
321   /* HCLK frequency */
322   SystemCoreClock >>= tmp;
323 }
324
325 /**
326   * @brief  Configures the System clock source, PLL Multiplier and Divider factors, 
327   *         AHB/APBx prescalers and Flash settings
328   * @Note   This function should be called only once the RCC clock configuration  
329   *         is reset to the default reset state (done in SystemInit() function).   
330   * @param  None
331   * @retval None
332   */
333 static void SetSysClock(void)
334 {
335 /******************************************************************************/
336 /*            PLL (clocked by HSE) used as System clock source                */
337 /******************************************************************************/
338   __IO uint32_t StartUpCounter = 0, HSEStatus = 0;
339   
340   /* Enable HSE */
341   RCC->CR |= ((uint32_t)RCC_CR_HSEON);
342  
343   /* Wait till HSE is ready and if Time out is reached exit */
344   do
345   {
346     HSEStatus = RCC->CR & RCC_CR_HSERDY;
347     StartUpCounter++;
348   } while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT));
349
350   if ((RCC->CR & RCC_CR_HSERDY) != RESET)
351   {
352     HSEStatus = (uint32_t)0x01;
353   }
354   else
355   {
356     HSEStatus = (uint32_t)0x00;
357   }
358
359   if (HSEStatus == (uint32_t)0x01)
360   {
361     /* Enable high performance mode, System frequency up to 168 MHz */
362     RCC->APB1ENR |= RCC_APB1ENR_PWREN;
363     PWR->CR |= PWR_CR_PMODE;  
364
365     /* HCLK = SYSCLK / 1*/
366     RCC->CFGR |= RCC_CFGR_HPRE_DIV1;
367       
368     /* PCLK2 = HCLK / 2*/
369     RCC->CFGR |= RCC_CFGR_PPRE2_DIV2;
370     
371     /* PCLK1 = HCLK / 4*/
372     RCC->CFGR |= RCC_CFGR_PPRE1_DIV4;
373
374     /* Configure the main PLL */
375     RCC->PLLCFGR = PLL_M | (PLL_N << 6) | (((PLL_P >> 1) -1) << 16) |
376                    (RCC_PLLCFGR_PLLSRC_HSE) | (PLL_Q << 24);
377
378     /* Enable the main PLL */
379     RCC->CR |= RCC_CR_PLLON;
380
381     /* Wait till the main PLL is ready */
382     while((RCC->CR & RCC_CR_PLLRDY) == 0)
383     {
384     }
385    
386     /* Configure Flash prefetch, Instruction cache, Data cache and wait state */
387     FLASH->ACR = FLASH_ACR_ICEN |FLASH_ACR_DCEN |FLASH_ACR_LATENCY_5WS;
388
389     /* Select the main PLL as system clock source */
390     RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW));
391     RCC->CFGR |= RCC_CFGR_SW_PLL;
392
393     /* Wait till the main PLL is used as system clock source */
394     while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS ) != RCC_CFGR_SWS_PLL);
395     {
396     }
397   }
398   else
399   { /* If HSE fails to start-up, the application will have wrong clock
400          configuration. User can add here some code to deal with this error */
401   }
402
403 }
404
405 /**
406   * @brief  Setup the external memory controller. Called in startup_stm32f4xx.s 
407   *          before jump to __main
408   * @param  None
409   * @retval None
410   */ 
411 #ifdef DATA_IN_ExtSRAM
412 /**
413   * @brief  Setup the external memory controller.
414   *         Called in startup_stm32f4xx.s before jump to main.
415   *         This function configures the external SRAM mounted on STM324xG_EVAL board
416   *         This SRAM will be used as program data memory (including heap and stack).
417   * @param  None
418   * @retval None
419   */
420 void SystemInit_ExtMemCtl(void)
421 {
422 /*-- GPIOs Configuration -----------------------------------------------------*/
423 /*
424  +-------------------+--------------------+------------------+------------------+
425  +                       SRAM pins assignment                                   +
426  +-------------------+--------------------+------------------+------------------+
427  | PD0  <-> FSMC_D2  | PE0  <-> FSMC_NBL0 | PF0  <-> FSMC_A0 | PG0 <-> FSMC_A10 | 
428  | PD1  <-> FSMC_D3  | PE1  <-> FSMC_NBL1 | PF1  <-> FSMC_A1 | PG1 <-> FSMC_A11 | 
429  | PD4  <-> FSMC_NOE | PE3  <-> FSMC_A19  | PF2  <-> FSMC_A2 | PG2 <-> FSMC_A12 | 
430  | PD5  <-> FSMC_NWE | PE4  <-> FSMC_A20  | PF3  <-> FSMC_A3 | PG3 <-> FSMC_A13 | 
431  | PD8  <-> FSMC_D13 | PE7  <-> FSMC_D4   | PF4  <-> FSMC_A4 | PG4 <-> FSMC_A14 | 
432  | PD9  <-> FSMC_D14 | PE8  <-> FSMC_D5   | PF5  <-> FSMC_A5 | PG5 <-> FSMC_A15 | 
433  | PD10 <-> FSMC_D15 | PE9  <-> FSMC_D6   | PF12 <-> FSMC_A6 | PG9 <-> FSMC_NE2 | 
434  | PD11 <-> FSMC_A16 | PE10 <-> FSMC_D7   | PF13 <-> FSMC_A7 |------------------+
435  | PD12 <-> FSMC_A17 | PE11 <-> FSMC_D8   | PF14 <-> FSMC_A8 | 
436  | PD13 <-> FSMC_A18 | PE12 <-> FSMC_D9   | PF15 <-> FSMC_A9 | 
437  | PD14 <-> FSMC_D0  | PE13 <-> FSMC_D10  |------------------+
438  | PD15 <-> FSMC_D1  | PE14 <-> FSMC_D11  |
439  |                   | PE15 <-> FSMC_D12  |
440  +-------------------+--------------------+
441 */
442    /* Enable GPIOD, GPIOE, GPIOF and GPIOG interface clock */
443   RCC->AHB1ENR   = 0x00000078;
444   
445   /* Connect PDx pins to FSMC Alternate function */
446   GPIOD->AFR[0]  = 0x00cc00cc;
447   GPIOD->AFR[1]  = 0xcc0ccccc;
448   /* Configure PDx pins in Alternate function mode */  
449   GPIOD->MODER   = 0xaaaa0a0a;
450   /* Configure PDx pins speed to 100 MHz */  
451   GPIOD->OSPEEDR = 0xffff0f0f;
452   /* Configure PDx pins Output type to push-pull */  
453   GPIOD->OTYPER  = 0x00000000;
454   /* No pull-up, pull-down for PDx pins */ 
455   GPIOD->PUPDR   = 0x00000000;
456
457   /* Connect PEx pins to FSMC Alternate function */
458   GPIOE->AFR[0]  = 0xc00cc0cc;
459   GPIOE->AFR[1]  = 0xcccccccc;
460   /* Configure PEx pins in Alternate function mode */ 
461   GPIOE->MODER   = 0xaaaa828a;
462   /* Configure PEx pins speed to 100 MHz */ 
463   GPIOE->OSPEEDR = 0xffffc3cf;
464   /* Configure PEx pins Output type to push-pull */  
465   GPIOE->OTYPER  = 0x00000000;
466   /* No pull-up, pull-down for PEx pins */ 
467   GPIOE->PUPDR   = 0x00000000;
468
469   /* Connect PFx pins to FSMC Alternate function */
470   GPIOF->AFR[0]  = 0x00cccccc;
471   GPIOF->AFR[1]  = 0xcccc0000;
472   /* Configure PFx pins in Alternate function mode */   
473   GPIOF->MODER   = 0xaa000aaa;
474   /* Configure PFx pins speed to 100 MHz */ 
475   GPIOF->OSPEEDR = 0xff000fff;
476   /* Configure PFx pins Output type to push-pull */  
477   GPIOF->OTYPER  = 0x00000000;
478   /* No pull-up, pull-down for PFx pins */ 
479   GPIOF->PUPDR   = 0x00000000;
480
481   /* Connect PGx pins to FSMC Alternate function */
482   GPIOG->AFR[0]  = 0x00cccccc;
483   GPIOG->AFR[1]  = 0x000000c0;
484   /* Configure PGx pins in Alternate function mode */ 
485   GPIOG->MODER   = 0x00080aaa;
486   /* Configure PGx pins speed to 100 MHz */ 
487   GPIOG->OSPEEDR = 0x000c0fff;
488   /* Configure PGx pins Output type to push-pull */  
489   GPIOG->OTYPER  = 0x00000000;
490   /* No pull-up, pull-down for PGx pins */ 
491   GPIOG->PUPDR   = 0x00000000;
492   
493 /*-- FSMC Configuration ------------------------------------------------------*/
494   /* Enable the FSMC interface clock */
495   RCC->AHB3ENR         = 0x00000001;
496
497   /* Configure and enable Bank1_SRAM2 */
498   FSMC_Bank1->BTCR[2]  = 0x00001015;
499   FSMC_Bank1->BTCR[3]  = 0x00010603;//0x00010400;
500   FSMC_Bank1E->BWTR[2] = 0x0fffffff;
501 /*
502   Bank1_SRAM2 is configured as follow:
503
504   p.FSMC_AddressSetupTime = 3;//0;
505   p.FSMC_AddressHoldTime = 0;
506   p.FSMC_DataSetupTime = 6;//4;
507   p.FSMC_BusTurnAroundDuration = 1;
508   p.FSMC_CLKDivision = 0;
509   p.FSMC_DataLatency = 0;
510   p.FSMC_AccessMode = FSMC_AccessMode_A;
511
512   FSMC_NORSRAMInitStructure.FSMC_Bank = FSMC_Bank1_NORSRAM2;
513   FSMC_NORSRAMInitStructure.FSMC_DataAddressMux = FSMC_DataAddressMux_Disable;
514   FSMC_NORSRAMInitStructure.FSMC_MemoryType = FSMC_MemoryType_PSRAM;
515   FSMC_NORSRAMInitStructure.FSMC_MemoryDataWidth = FSMC_MemoryDataWidth_16b;
516   FSMC_NORSRAMInitStructure.FSMC_BurstAccessMode = FSMC_BurstAccessMode_Disable;
517   FSMC_NORSRAMInitStructure.FSMC_AsynchronousWait = FSMC_AsynchronousWait_Disable;  
518   FSMC_NORSRAMInitStructure.FSMC_WaitSignalPolarity = FSMC_WaitSignalPolarity_Low;
519   FSMC_NORSRAMInitStructure.FSMC_WrapMode = FSMC_WrapMode_Disable;
520   FSMC_NORSRAMInitStructure.FSMC_WaitSignalActive = FSMC_WaitSignalActive_BeforeWaitState;
521   FSMC_NORSRAMInitStructure.FSMC_WriteOperation = FSMC_WriteOperation_Enable;
522   FSMC_NORSRAMInitStructure.FSMC_WaitSignal = FSMC_WaitSignal_Disable;
523   FSMC_NORSRAMInitStructure.FSMC_ExtendedMode = FSMC_ExtendedMode_Disable;
524   FSMC_NORSRAMInitStructure.FSMC_WriteBurst = FSMC_WriteBurst_Disable;
525   FSMC_NORSRAMInitStructure.FSMC_ReadWriteTimingStruct = &p;
526   FSMC_NORSRAMInitStructure.FSMC_WriteTimingStruct = &p;
527 */
528   
529 }
530 #endif /* DATA_IN_ExtSRAM */
531
532
533 /**
534   * @}
535   */
536
537 /**
538   * @}
539   */
540   
541 /**
542   * @}
543   */    
544 /******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
545