Exemple #1
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
void DAC_SignalsGeneration(void)
{
    /*!< At this stage the microcontroller clock setting is already configured,
         this is done through SystemInit() function which is called from startup
         file (startup_stm32f30x.s) before to branch to application main.
         To reconfigure the default setting of SystemInit() function, refer to
         system_stm32f30x.c file
       */

    /* Preconfiguration before using DAC----------------------------------------*/
    DAC_Config();

    /* TIM2 configuration to trigger DAC */
    TIM_Config();

    /* Configures Key Button EXTI Line */
    STM_EVAL_PBInit(BUTTON_KEY, BUTTON_MODE_EXTI);

    /* Infinite loop */
    while (1)
    {
        /* If the wave form is changed */
        if (WaveChange == 1)
        {
            /* Switch the selected waves forms according the Button status */
            if (SelectedWavesForm == 1)
            {
                /* The sine wave and the escalator wave has been selected */
                /* Sine Wave generator ---------------------------------------------*/

                /* DAC channel2 Configuration */
                DAC_DeInit();
                DAC_InitStructure.DAC_Trigger = DAC_Trigger_T2_TRGO;
                DAC_InitStructure.DAC_WaveGeneration = DAC_WaveGeneration_None;
                DAC_InitStructure.DAC_OutputBuffer = DAC_OutputBuffer_Disable;

                /* DAC Channel2 Init */
                DAC_Init(DAC_Channel_2, &DAC_InitStructure);

                /* Enable DAC Channel2 */
                DAC_Cmd(DAC_Channel_2, ENABLE);

                /* DMA2 channel3 configuration */
                DMA_DeInit(DMA2_Channel3);
                DMA_InitStructure.DMA_PeripheralBaseAddr = DAC_DHR12R2_ADDRESS;
                DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)&Sine12bit;
                DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;
                DMA_InitStructure.DMA_BufferSize = 32;
                DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
                DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
                DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
                DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
                DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
                DMA_InitStructure.DMA_Priority = DMA_Priority_High;
                DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
                DMA_Init(DMA2_Channel3, &DMA_InitStructure);

                /* Enable DMA2 Channel3 */
                DMA_Cmd(DMA2_Channel3, ENABLE);

                /* Enable DMA for DAC Channel2 */
                DAC_DMACmd(DAC_Channel_2, ENABLE);

                /* Escalator Wave generator ----------------------------------------*/

                /* DAC channel1 Configuration */
                DAC_InitStructure.DAC_OutputBuffer = DAC_OutputBuffer_Enable;
                DAC_Init(DAC_Channel_1, &DAC_InitStructure);

                /* DMA2 channel4 configuration */
                DMA_DeInit(DMA2_Channel4);
                DMA_InitStructure.DMA_PeripheralBaseAddr = DAC_DHR8R1_ADDRESS;
                DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)&Escalator8bit;
                DMA_InitStructure.DMA_BufferSize = 6;
                DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
                DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
                DMA_Init(DMA2_Channel4, &DMA_InitStructure);

                /* Enable DMA2 Channel4 */
                DMA_Cmd(DMA2_Channel4, ENABLE);

                /* Enable DAC1 Channel1: Once the DAC1 channel1 is enabled, PA.05 is
                   automatically connected to the DAC converter. */
                DAC_Cmd(DAC_Channel_1, ENABLE);

                /* Enable DMA for DAC Channel1 */
                DAC_DMACmd(DAC_Channel_1, ENABLE);
            }
            /* The triangle wave and the noise wave has been selected */
            else
            {
                /* Noise Wave generator --------------------------------------------*/

                /* DAC channel1 Configuration */
                DAC_DeInit();
                DAC_InitStructure.DAC_Trigger = DAC_Trigger_T2_TRGO;
                DAC_InitStructure.DAC_WaveGeneration = DAC_WaveGeneration_Noise;
                DAC_InitStructure.DAC_LFSRUnmask_TriangleAmplitude = DAC_LFSRUnmask_Bits11_0;
                DAC_InitStructure.DAC_OutputBuffer = DAC_OutputBuffer_Enable;
                DAC_Init(DAC_Channel_1, &DAC_InitStructure);

                /* Enable DAC Channel1: Once the DAC channel1 is enabled, PA.05 is
                   automatically connected to the DAC converter. */
                DAC_Cmd(DAC_Channel_1, ENABLE);

                /* Set DAC Channel1 DHR12L register */
                DAC_SetChannel1Data(DAC_Align_12b_L, 0x7FF0);

                /* Enable DAC channel1 wave generator */
                DAC_WaveGenerationCmd(DAC_Channel_1, DAC_Wave_Noise , ENABLE);

                /* Triangle Wave generator -----------------------------------------*/

                /* DAC channel2 Configuration */
                DAC_InitStructure.DAC_Trigger = DAC_Trigger_T2_TRGO;
                DAC_InitStructure.DAC_WaveGeneration = DAC_WaveGeneration_Triangle;
                DAC_InitStructure.DAC_LFSRUnmask_TriangleAmplitude = DAC_TriangleAmplitude_1023;
                DAC_InitStructure.DAC_OutputBuffer = DAC_OutputBuffer_Enable;
                DAC_Init(DAC_Channel_2, &DAC_InitStructure);

                /* Enable DAC Channel2: Once the DAC channel2 is enabled, PA.05 is
                   automatically connected to the DAC converter. */
                DAC_Cmd(DAC_Channel_2, ENABLE);

                /* Set DAC channel2 DHR12RD register */
                DAC_SetChannel2Data(DAC_Align_12b_R, 0x100);
            }
            WaveChange = !WaveChange;
        }
    }
}
Exemple #2
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
         files (startup_stm32f40_41xxx.s/startup_stm32f427_437xx.s/startup_stm32f429_439xx.s)
         before to branch to application main.
         To reconfigure the default setting of SystemInit() function, refer to
         system_stm32f4xx.c file
       */

    /* TIM Configuration */
    TIM_Config();

    /* ---------------------------------------------------------------------------
       TIM9 Configuration: Output Compare Toggle Mode:

      In this example TIM9 input clock (TIM9CLK) is set to 2 * APB2 clock (PCLK2),
      since APB2 prescaler is different from 1.
        TIM9CLK = 2 * PCLK2
        PCLK2 = HCLK / 2
        => TIM9CLK = HCLK = SystemCoreClock

      To get TIM9 counter clock at 15 MHz, the prescaler is computed as follows:
         Prescaler = (TIM9CLK / TIM9 counter clock) - 1
         Prescaler = (SystemCoreClock /15 MHz) - 1

      CC1 update rate = TIM9 counter clock / CCR1_Val = 366.2 Hz
      ==> So the TIM9 Channel 1 generates a periodic signal with
          a frequency equal to 183.1 Hz

      CC2 update rate = TIM9 counter clock / CCR2_Val = 732.4 Hz
      ==> So the TIM9 channel 2 generates a periodic signal with
          a frequency equal to 366.3 Hz

      Note:
       SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
       Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
       function to update SystemCoreClock variable value. Otherwise, any configuration
       based on this variable will be incorrect.
    --------------------------------------------------------------------------- */


    /* Compute the prescaler value */
    PrescalerValue = (uint16_t) (SystemCoreClock / 15000000) - 1;

    /* Time base configuration */
    TIM_TimeBaseStructure.TIM_Period = 65535;
    TIM_TimeBaseStructure.TIM_Prescaler = PrescalerValue;
    TIM_TimeBaseStructure.TIM_ClockDivision = 0;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

    TIM_TimeBaseInit(TIM9, &TIM_TimeBaseStructure);

    /* Output Compare Toggle Mode configuration: Channel1 */
    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Toggle;
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStructure.TIM_Pulse = CCR1_Val;
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
    TIM_OC1Init(TIM9, &TIM_OCInitStructure);

    TIM_OC1PreloadConfig(TIM9, TIM_OCPreload_Disable);

    /* Output Compare Toggle Mode configuration: Channel2 */
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStructure.TIM_Pulse = CCR2_Val;

    TIM_OC2Init(TIM9, &TIM_OCInitStructure);

    TIM_OC2PreloadConfig(TIM9, TIM_OCPreload_Disable);

    /* TIM enable counter */
    TIM_Cmd(TIM9, ENABLE);

    /* TIM IT enable */
    TIM_ITConfig(TIM9, TIM_IT_CC1 | TIM_IT_CC2, ENABLE);

    while (1)
    {}
}
Exemple #3
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
       files (startup_stm32f40_41xxx.s/startup_stm32f427_437xx.s/startup_stm32f429_439xx.s)
       before to branch to application main. 
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f4xx.c file
     */

  /* TIM Configuration */
  TIM_Config();
  
  /* -----------------------------------------------------------------------
    TIM3 Configuration: generate 4 PWM signals with 4 different duty cycles.
    
    In this example TIM3 input clock (TIM3CLK) is set to 2 * APB1 clock (PCLK1), 
    since APB1 prescaler is different from 1.   
      TIM3CLK = 2 * PCLK1  
      PCLK1 = HCLK / 4 
      => TIM3CLK = HCLK / 2 = SystemCoreClock /2
          
    To get TIM3 counter clock at 21 MHz, the prescaler is computed as follows:
       Prescaler = (TIM3CLK / TIM3 counter clock) - 1
       Prescaler = ((SystemCoreClock /2) /21 MHz) - 1
                                              
    To get TIM3 output clock at 30 KHz, the period (ARR)) is computed as follows:
       ARR = (TIM3 counter clock / TIM3 output clock) - 1
           = 665
                  
    TIM3 Channel1 duty cycle = (TIM3_CCR1/ TIM3_ARR)* 100 = 50%
    TIM3 Channel2 duty cycle = (TIM3_CCR2/ TIM3_ARR)* 100 = 37.5%
    TIM3 Channel3 duty cycle = (TIM3_CCR3/ TIM3_ARR)* 100 = 25%
    TIM3 Channel4 duty cycle = (TIM3_CCR4/ TIM3_ARR)* 100 = 12.5%

    Note: 
     SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
     Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
     function to update SystemCoreClock variable value. Otherwise, any configuration
     based on this variable will be incorrect.    
  ----------------------------------------------------------------------- */   


  /* Compute the prescaler value */
  PrescalerValue = (uint16_t) ((SystemCoreClock /2) / 21000000) - 1;

  /* Time base configuration */
  TIM_TimeBaseStructure.TIM_Period = 665;
  TIM_TimeBaseStructure.TIM_Prescaler = PrescalerValue;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

  /* PWM1 Mode configuration: Channel1 */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR1_Val;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;

  TIM_OC1Init(TIM3, &TIM_OCInitStructure);

  TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);

  /* PWM1 Mode configuration: Channel2 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR2_Val;

  TIM_OC2Init(TIM3, &TIM_OCInitStructure);

  TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);

  /* PWM1 Mode configuration: Channel3 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR3_Val;

  TIM_OC3Init(TIM3, &TIM_OCInitStructure);

  TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Enable);

  /* PWM1 Mode configuration: Channel4 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR4_Val;

  TIM_OC4Init(TIM3, &TIM_OCInitStructure);

  TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Enable);

  TIM_ARRPreloadConfig(TIM3, ENABLE);

  /* TIM3 enable counter */
  TIM_Cmd(TIM3, ENABLE);

  while (1)
  {}
}
Exemple #4
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
       files (startup_stm32f40_41xxx.s/startup_stm32f427_437xx.s/startup_stm32f429_439xx.s)
       before to branch to application main. 
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f4xx.c file
     */

  /* SysTick Configuration */
  SysTickConfig();

  /* TIM1 Configuration */
  TIM_Config();
  
  /*----------------------------------------------------------------------------
  The STM32F4xx TIM1 peripheral offers the possibility to program in advance the 
  configuration for the next TIM1 outputs behaviour (step) and change the configuration
  of all the channels at the same time. This operation is possible when the COM 
  (commutation) event is used.
  The COM event can be generated by software by setting the COM bit in the TIM1_EGR
  register or by hardware (on TRC rising edge).
  In this example, a software COM event is generated each 100 ms: using the SysTick 
  interrupt.
  The TIM1 is configured in Timing Mode, each time a COM event occurs, a new TIM1 
  configuration will be set in advance.

  The following Table  describes the TIM1 Channels states:
              -----------------------------------------------
             | Step1 | Step2 | Step3 | Step4 | Step5 | Step6 |
   ----------------------------------------------------------
  |Channel1  |   1   |   0   |   0   |   0   |   0   |   1   |
   ----------------------------------------------------------
  |Channel1N |   0   |   0   |   1   |   1   |   0   |   0   |
   ----------------------------------------------------------
  |Channel2  |   0   |   0   |   0   |   1   |   1   |   0   |
   ----------------------------------------------------------
  |Channel2N |   1   |   1   |   0   |   0   |   0   |   0   |
   ----------------------------------------------------------
  |Channel3  |   0   |   1   |   1   |   0   |   0   |   0   |
   ----------------------------------------------------------
  |Channel3N |   0   |   0   |   0   |   0   |   1   |   1   |
   ----------------------------------------------------------
  ----------------------------------------------------------------------------*/

  /* Time Base configuration */
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
  TIM_TimeBaseStructure.TIM_Period = 4095;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;

  TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);

  /* Channel 1, 2,3 and 4 Configuration in PWM mode */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Timing;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 2047;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
  TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_High;
  TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;
  TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCNIdleState_Set;

  TIM_OC1Init(TIM1, &TIM_OCInitStructure);

  TIM_OCInitStructure.TIM_Pulse = 1023;
  TIM_OC2Init(TIM1, &TIM_OCInitStructure);

  TIM_OCInitStructure.TIM_Pulse = 511;
  TIM_OC3Init(TIM1, &TIM_OCInitStructure);

  /* Automatic Output enable, Break, dead time and lock configuration*/
  TIM_BDTRInitStructure.TIM_OSSRState = TIM_OSSRState_Enable;
  TIM_BDTRInitStructure.TIM_OSSIState = TIM_OSSIState_Enable;
  TIM_BDTRInitStructure.TIM_LOCKLevel = TIM_LOCKLevel_OFF;
  TIM_BDTRInitStructure.TIM_DeadTime = 1;
  TIM_BDTRInitStructure.TIM_Break = TIM_Break_Enable;
  TIM_BDTRInitStructure.TIM_BreakPolarity = TIM_BreakPolarity_High;
  TIM_BDTRInitStructure.TIM_AutomaticOutput = TIM_AutomaticOutput_Enable;

  TIM_BDTRConfig(TIM1, &TIM_BDTRInitStructure);

  TIM_CCPreloadControl(TIM1, ENABLE);

  TIM_ITConfig(TIM1, TIM_IT_COM, ENABLE);

  /* TIM1 counter enable */
  TIM_Cmd(TIM1, ENABLE);

  /* Main Output Enable */
  TIM_CtrlPWMOutputs(TIM1, ENABLE);

  while (1)
  {}
}
/**
  * @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_stm32f0xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f0xx.c file
     */ 

  /* TIM Configuration */
  TIM_Config();
  
  /* -----------------------------------------------------------------------
    TIM3 Configuration: Output Compare Timing Mode:
    
    In this example TIM3 input clock (TIM3CLK) is set to APB1 clock (PCLK1),  
      => TIM3CLK = PCLK1 = SystemCoreClock = 48 MHz
          
    To get TIM3 counter clock at 6 MHz, the prescaler is computed as follows:
       Prescaler = (TIM3CLK / TIM3 counter clock) - 1
       Prescaler = (PCLK1 /6 MHz) - 1
                                              
    CC1 update rate = TIM3 counter clock / CCR1_Val = 146.48 Hz
    ==> Toggling frequency = 73.24 Hz
    
    C2 update rate = TIM3 counter clock / CCR2_Val = 219.7 Hz
    ==> Toggling frequency = 109.8 Hz
    
    CC3 update rate = TIM3 counter clock / CCR3_Val = 439.4 Hz
    ==> Toggling frequency = 219.7 Hz
    
    CC4 update rate = TIM3 counter clock / CCR4_Val = 878.9 Hz
    ==> Toggling frequency = 439.4 Hz

    Note: 
     SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f0xx.c file.
     Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
     function to update SystemCoreClock variable value. Otherwise, any configuration
     based on this variable will be incorrect.    
  ----------------------------------------------------------------------- */   


  /* Compute the prescaler value */
  PrescalerValue = (uint16_t) (SystemCoreClock  / 6000000) - 1;

  /* Time base configuration */
  TIM_TimeBaseStructure.TIM_Period = 65535;
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

  /* Prescaler configuration */
  TIM_PrescalerConfig(TIM3, PrescalerValue, TIM_PSCReloadMode_Immediate);

  /* Output Compare Timing Mode configuration: Channel1 */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Timing;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR1_Val;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;

  TIM_OC1Init(TIM3, &TIM_OCInitStructure);

  TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Disable);

  /* Output Compare Timing Mode configuration: Channel2 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR2_Val;

  TIM_OC2Init(TIM3, &TIM_OCInitStructure);

  TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Disable);

  /* Output Compare Timing Mode configuration: Channel3 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR3_Val;

  TIM_OC3Init(TIM3, &TIM_OCInitStructure);

  TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Disable);

  /* Output Compare Timing Mode configuration: Channel4 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR4_Val;

  TIM_OC4Init(TIM3, &TIM_OCInitStructure);

  TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Disable);
   
  /* TIM Interrupts enable */
  TIM_ITConfig(TIM3, TIM_IT_CC1 | TIM_IT_CC2 | TIM_IT_CC3 | TIM_IT_CC4, ENABLE);

  /* TIM3 enable counter */
  TIM_Cmd(TIM3, ENABLE);

  /* Infinite loop */
  while (1)
  {
  }
}
Exemple #6
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
       files (startup_stm32f40_41xxx.s/startup_stm32f427_437xx.s/startup_stm32f429_439xx.s)
       before to branch to application main. 
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f4xx.c file
     */     
       
  /* TIM Configuration */
  TIM_Config();

  /* --------------------------------------------------------------------------
    TIM4 configuration: One Pulse mode
    The external signal is connected to TIM4_CH2 pin (PB.07), 
    The Rising edge is used as active edge,
    The One Pulse signal is output on TIM4_CH1 pin (PB.06)
    The TIM_Pulse defines the delay value 
    The (TIM_Period -  TIM_Pulse) defines the One Pulse value.
     
    TIM4 input clock (TIM4CLK) is set to 2 * APB1 clock (PCLK1), 
    since APB1 prescaler is different from 1.   
      TIM4CLK = 2 * PCLK1  
      PCLK1 = HCLK / 4 
      => TIM4CLK = HCLK / 2 = SystemCoreClock /2

    TIM2CLK = SystemCoreClock/2, we want to get TIM2 counter clock at 42 MHz:
     Prescaler = (TIM2CLK / TIM2 counter clock) - 1
     Prescaler = ((SystemCoreClock /2) /42 MHz) - 1
     
    The Autoreload value is 65535 (TIM4->ARR), so the maximum frequency value 
    to trigger the TIM4 input is 42000000/65535 = 641 Hz.

    The TIM_Pulse defines the delay value, the delay value is fixed 
    to 390 us:
    delay =  CCR1/TIM4 counter clock 
          = 16383 / 42000000 = 390 us. 
    The (TIM_Period - TIM_Pulse) defines the One Pulse value, 
    the pulse value is fixed to 1.170 ms:
    One Pulse value = (TIM_Period - TIM_Pulse) / TIM4 counter clock 
                    = (65535 - 16383) / 42000000 = 1.170 ms.

    Note: 
     SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
     Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
     function to update SystemCoreClock variable value. Otherwise, any configuration
     based on this variable will be incorrect.    

  --------------------------------------------------------------------------- */

  /* Compute the prescaler value */
  uhPrescalerValue = (uint16_t) ((SystemCoreClock / 2) / 42000000) - 1;
  
  /* Time base configuration */
  TIM_TimeBaseStructure.TIM_Period = 65535;
  TIM_TimeBaseStructure.TIM_Prescaler = uhPrescalerValue;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);

  /* TIM4 PWM2 Mode configuration: Channel1 */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 16383;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;

  TIM_OC1Init(TIM4, &TIM_OCInitStructure);

  /* TIM4 configuration in Input Capture Mode */

  TIM_ICStructInit(&TIM_ICInitStructure);

  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 = 0;

  TIM_ICInit(TIM4, &TIM_ICInitStructure);

  /* One Pulse Mode selection */
  TIM_SelectOnePulseMode(TIM4, TIM_OPMode_Single);

  /* Input Trigger selection */
  TIM_SelectInputTrigger(TIM4, TIM_TS_TI2FP2);

  /* Slave Mode selection: Trigger Mode */
  TIM_SelectSlaveMode(TIM4, TIM_SlaveMode_Trigger);

  while (1)
  {
  }
}
Exemple #7
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_stm32f4xx.s) before to branch to application main.
         To reconfigure the default setting of SystemInit() function, refer to
         system_stm32f4xx.c file
       */

    /* TIM Configuration */
    TIM_Config();

    /* ---------------------------------------------------------------------------
      TIM10 Configuration: generate 1 PWM signal:

      In this example TIM10 input clock (TIM10CLK) is set to 2 * APB2 clock (PCLK2),
      since APB2 prescaler is different from 1.
        TIM10CLK = 2 * PCLK2
        PCLK2 = HCLK / 2
        => TIM10CLK = HCLK = SystemCoreClock

      To get TIM10 counter clock at 21 MHz, the prescaler is computed as follows:
         Prescaler = (TIM10CLK / TIM10 counter clock) - 1
         Prescaler = (SystemCoreClock /21 MHz) - 1

      To get TIM10 output clock at 31.530 KHz, the period (TIM10_ARR) is computed as follows:
         ARR = (TIM10 counter clock / TIM10 output clock) - 1
             = 665

      TIM10 Channel1 duty cycle = (TIM10_CCR1/ TIM10_ARR)* 100 = 50%

      Note:
       SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
       Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
       function to update SystemCoreClock variable value. Otherwise, any configuration
       based on this variable will be incorrect.
    --------------------------------------------------------------------------- */


    /* Compute the prescaler value */
    PrescalerValue = (uint16_t) (SystemCoreClock / 21000000) - 1;

    /* Time base configuration */
    TIM_TimeBaseStructure.TIM_Period = 665;
    TIM_TimeBaseStructure.TIM_Prescaler = PrescalerValue;
    TIM_TimeBaseStructure.TIM_ClockDivision = 0;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

    TIM_TimeBaseInit(TIM10, &TIM_TimeBaseStructure);

    /* PWM1 Mode configuration: Channel1 */
    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStructure.TIM_Pulse = CCR1_Val;
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;

    TIM_OC1Init(TIM10, &TIM_OCInitStructure);

    TIM_OC1PreloadConfig(TIM10, TIM_OCPreload_Enable);

    TIM_ARRPreloadConfig(TIM10, ENABLE);

    /* TIM10 enable counter */
    TIM_Cmd(TIM10, ENABLE);

    while (1)
    {}
}
Exemple #8
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F3xx HAL library initialization:
       - Configure the Flash prefetch
       - Configure the Systick to generate an interrupt each 1 msec
       - Set NVIC Group Priority to 4
       - Low Level Initialization
     */
  HAL_Init();
  
  /* Configure the system clock to 64 MHz */
  SystemClock_Config();
  
  /*## Configure peripherals #################################################*/
  /* Initialize LED on board */
  BSP_LED_Init(LED2);

  /* Configure User push-button in Interrupt mode */
  BSP_PB_Init(BUTTON_USER, BUTTON_MODE_EXTI);

  /* Configure the ADC peripheral */
  ADC_Config();
  
  /* Run the ADC calibration in single-ended mode */  
  if (HAL_ADCEx_Calibration_Start(&AdcHandle, ADC_SINGLE_ENDED) != HAL_OK)
  {
    /* Calibration Error */
    Error_Handler();
  }

  /* Configure the TIM peripheral */
  TIM_Config();
  
  /* Configure the DAC peripheral */
  DAC_Config();
  

  /*## Enable peripherals ####################################################*/

  /* Timer counter enable */
  if (HAL_TIM_Base_Start(&TimHandle) != HAL_OK)
  {
    /* Counter Enable Error */
    Error_Handler();
  }
  
  /* Set DAC Channel data register: channel corresponding to ADC channel CHANNELa */
  /* Set DAC output to 1/2 of full range (4095 <=> Vdda=3.3V): 2048 <=> 1.65V              */
  if (HAL_DAC_SetValue(&DacHandle, DACx_CHANNEL_TO_ADCx_CHANNELa, DAC_ALIGN_12B_R, RANGE_12BITS/2) != HAL_OK)
  {
    /* Setting value Error */
    Error_Handler();
  }
  
  /* Enable DAC Channel: channel corresponding to ADC channel CHANNELa */
  if (HAL_DAC_Start(&DacHandle, DACx_CHANNEL_TO_ADCx_CHANNELa) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }
    
  /*## Start ADC conversions #################################################*/
  
  /* Start ADC conversion on regular group with transfer by DMA */
  if (HAL_ADC_Start_DMA(&AdcHandle,
                        (uint32_t *)aADCxConvertedValues,
                        ADCCONVERTEDVALUES_BUFFER_SIZE
                       ) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }
  
  
  /* Infinite loop */
  while (1)
  {
    /* Turn-on/off LED2 in function of ADC conversion result */
    /*  - Turn-off if voltage is into AWD window */ 
    /*  - Turn-on if voltage is out of AWD window */

    /* Variable of analog watchdog status is set into analog watchdog         */
    /* interrupt callback                                                     */
    if (ubAnalogWatchdogStatus == RESET)
    {
      BSP_LED_Off(LED2);
    }
    else
    {
      BSP_LED_On(LED2);
      
      /* Reset analog watchdog status for next loop iteration */
      ubAnalogWatchdogStatus = RESET;
    }
  
    /* For information: ADC conversion results are stored into array          */
    /* "aADCxConvertedValues" (for debug: check into watch window)            */
  
  
    /* Wait for event on push button to perform following actions */
    while ((ubUserButtonClickEvent) == RESET)
    {
      __NOP();
    }
    /* Reset variable for next loop iteration */
    ubUserButtonClickEvent = RESET;

    /* Set DAC voltage on channel corresponding to ADCx_CHANNELa              */
    /* in function of user button clicks count.                               */
    /* Set DAC output successively to:                                        */
    /*  - minimum of full range (0 <=> ground 0V)                             */
    /*  - 1/4 of full range (4095 <=> Vdda=3.3V): 1023 <=> 0.825V             */
    /*  - 1/2 of full range (4095 <=> Vdda=3.3V): 2048 <=> 1.65V              */
    /*  - 3/4 of full range (4095 <=> Vdda=3.3V): 3071 <=> 2.475V             */
    /*  - maximum of full range (4095 <=> Vdda=3.3V)                          */
    if (HAL_DAC_SetValue(&DacHandle,
                         DACx_CHANNEL_TO_ADCx_CHANNELa,
                         DAC_ALIGN_12B_R,
                         (RANGE_12BITS * ubUserButtonClickCount / USERBUTTON_CLICK_COUNT_MAX)
                        ) != HAL_OK)
    {
      /* Start Error */
      Error_Handler();
    }
  }
}
Exemple #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_stm32f0xx.s) before to branch to application main.
  To reconfigure the default setting of SystemInit() function, refer to
  system_stm32f0xx.c file
  */ 
  
  /* SPI configuration ------------------------------------------------------*/
  SPI_Config();
  
  /* SysTick configuration ---------------------------------------------------*/
  SysTickConfig();
  
  /* Initialize LEDs mounted on STM320518-EVAL board */
  STM_EVAL_LEDInit(LED1);
  STM_EVAL_LEDInit(LED2);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED4);
  
  /* Master board configuration ------------------------------------------------*/
#ifdef SPI_MASTER
  /* Initialize push-buttons mounted on STM320518-EVAL board */
  STM_EVAL_PBInit(BUTTON_RIGHT, BUTTON_MODE_GPIO);
  STM_EVAL_PBInit(BUTTON_LEFT, BUTTON_MODE_GPIO);
  STM_EVAL_PBInit(BUTTON_UP, BUTTON_MODE_GPIO);
  STM_EVAL_PBInit(BUTTON_DOWN, BUTTON_MODE_GPIO);
  STM_EVAL_PBInit(BUTTON_SEL, BUTTON_MODE_GPIO);
  
  /* Initializes the SPI communication */
  SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
  SPI_Init(SPIx, &SPI_InitStructure);
  
  /* Initialize the FIFO threshold */
  SPI_RxFIFOThresholdConfig(SPIx, SPI_RxFIFOThreshold_QF);
  
  /* TIM configuration ------------------------------------------------------*/
  TIM_Config(); 
  
  /* Enable the SPI peripheral */
  SPI_Cmd(SPIx, ENABLE);
  
  /* Enable NSS output for master mode */
  SPI_SSOutputCmd(SPIx, ENABLE);
  
  /* TIM Capture Compare DMA Request enable */
  TIM_DMACmd(TIMx, TIMx_DMA_CHANNEL, ENABLE);
  
  while (1)
  {
    /* DMA channel Rx of SPI Configuration */
    DMA_InitStructure.DMA_BufferSize = (uint16_t)1;
    DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)SPIx_DR_ADDRESS;
    DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t) &CommandReceived;
    DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
    DMA_InitStructure.DMA_Priority = DMA_Priority_High;
    DMA_Init(SPIx_RX_DMA_CHANNEL, &DMA_InitStructure);
    
    /* DMA TIM trigger channel Configuration */
    DMA_InitStructure.DMA_BufferSize = (uint16_t)1;
    DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)SPIx_DR_ADDRESS;
    DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t) &CommandTransmitted;
    DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;
    DMA_InitStructure.DMA_Priority = DMA_Priority_Low;
    DMA_Init(TIMx_CHANNEL_DMA_CHANNEL, &DMA_InitStructure);
    
    /* Enable the SPI Rx DMA request */
    SPI_I2S_DMACmd(SPIx, SPI_I2S_DMAReq_Rx, ENABLE);
    
    CommandTransmitted = 0x00;
    CommandReceived = 0x00;
    
    /* Clear the RxBuffer */
    Fill_Buffer(RxBuffer, TXBUFFERSIZE);
    
    PressedButton = Read_Joystick();
    while (PressedButton == JOY_NONE)
    {
      PressedButton = Read_Joystick();
    }
    
    switch (PressedButton)
    {
      /* JOY_RIGHT button pressed */
    case JOY_RIGHT:
      CommandTransmitted = CMD_RIGHT;
      NumberOfByte = CMD_RIGHT_SIZE;
      break;
      /* JOY_LEFT button pressed */ 
    case JOY_LEFT:
      CommandTransmitted = CMD_LEFT;
      NumberOfByte = CMD_LEFT_SIZE;
      break;
      /* JOY_UP button pressed */
    case JOY_UP:
      CommandTransmitted = CMD_UP;
      NumberOfByte = CMD_UP_SIZE;
      break;
      /* JOY_DOWN button pressed */
    case JOY_DOWN:
      CommandTransmitted = CMD_DOWN;
      NumberOfByte = CMD_DOWN_SIZE;
      break;
      /* JOY_SEL button pressed */
    case JOY_SEL:
      CommandTransmitted = CMD_SEL;
      NumberOfByte = CMD_SEL_SIZE;
      break;
    default:
      break;
    }
    
    /* Enable the DMA channel */
    DMA_Cmd(SPIx_RX_DMA_CHANNEL, ENABLE);
    
    /* Enable DMA1 TIM Trigger Channel */
    DMA_Cmd(TIMx_CHANNEL_DMA_CHANNEL, ENABLE);
    
    /* TIM enable counter */
    TIM_Cmd(TIMx, ENABLE);
    
    /* Wait the SPI DMA Rx transfer complete or time out*/
    TimeOut = USER_TIMEOUT;
    while ((DMA_GetFlagStatus(SPIx_RX_DMA_FLAG_TC) == RESET)&&(TimeOut != 0x00))
    {}
    if(TimeOut == 0)
    {
      TimeOut_UserCallback();
    }
    /* The BSY flag can be monitored to ensure that the SPI communication is complete.
    This is required to avoid corrupting the last transmission before disabling 
    the SPI or entering the Stop mode. The software must first wait until TXE=1
    and then until BSY=0.*/
    TimeOut = USER_TIMEOUT;
    while ((SPI_I2S_GetFlagStatus(SPIx, SPI_I2S_FLAG_TXE) == RESET)&&(TimeOut != 0x00))
    {}
    if(TimeOut == 0)
    {
      TimeOut_UserCallback();
    }
    
    TimeOut = USER_TIMEOUT;
    while ((SPI_I2S_GetFlagStatus(SPIx, SPI_I2S_FLAG_BSY) == SET)&&(TimeOut != 0x00))
    {}
    if(TimeOut == 0)
    {
      TimeOut_UserCallback();
    } 
    
    /* Clear DMA1 global flags*/
    DMA_ClearFlag(TIMx_CHANNEL_DMA_FLAG_GL);
    DMA_ClearFlag(SPIx_RX_DMA_FLAG_GL);
    
    /* disable the DMA channels */
    DMA_Cmd(SPIx_RX_DMA_CHANNEL, DISABLE);
    DMA_Cmd(TIMx_CHANNEL_DMA_CHANNEL, DISABLE);
    
    /* disable the SPI Rx DMA request */
    SPI_I2S_DMACmd(SPIx, SPI_I2S_DMAReq_Rx, DISABLE);
    
    /* TIM disable counter */
    TIM_Cmd(TIMx, DISABLE);
    
    if (CommandReceived == CMD_ACK)
    {
      /* DMA channel Rx of SPI Configuration */
      DMA_InitStructure.DMA_BufferSize = (uint16_t)NumberOfByte;
      DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)SPIx_DR_ADDRESS;
      DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)RxBuffer;
      DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
      DMA_InitStructure.DMA_Priority = DMA_Priority_High;
      DMA_Init(SPIx_RX_DMA_CHANNEL, &DMA_InitStructure);
      
      /* DMA channel Tx of SPI Configuration */
      DMA_InitStructure.DMA_BufferSize = (uint16_t)NumberOfByte;
      DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)SPIx_DR_ADDRESS;
      DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)TxBuffer;
      DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;
      DMA_InitStructure.DMA_Priority = DMA_Priority_Low;
      DMA_Init(TIMx_CHANNEL_DMA_CHANNEL, &DMA_InitStructure);
      
      /* Enable the SPI Rx DMA request */
      SPI_I2S_DMACmd(SPIx, SPI_I2S_DMAReq_Rx, ENABLE);
      
      /* Enable the DMA channel */
      DMA_Cmd(SPIx_RX_DMA_CHANNEL, ENABLE);
      
      /* Enable DMA1 TIM Trigger Channel */
      DMA_Cmd(TIMx_CHANNEL_DMA_CHANNEL, ENABLE);
      
      /* TIM enable counter */
      TIM_Cmd(TIMx, ENABLE);
      
      /* Wait the SPI Rx DMA transfer complete or time out */
      TimeOut = USER_TIMEOUT;
      while ((DMA_GetFlagStatus(SPIx_RX_DMA_FLAG_TC) == RESET)&&(TimeOut != 0x00))
      {}
      if(TimeOut == 0)
      {
        TimeOut_UserCallback();
      }
      /* The BSY flag can be monitored to ensure that the SPI communication is complete.
      This is required to avoid corrupting the last transmission before disabling 
      the SPI or entering the Stop mode. The software must first wait until TXE=1
      and then until BSY=0.*/
      TimeOut = USER_TIMEOUT;
      while ((SPI_I2S_GetFlagStatus(SPIx, SPI_I2S_FLAG_TXE) == RESET)&&(TimeOut != 0x00))
      {}
      if(TimeOut == 0)
      {
        TimeOut_UserCallback();
      }
      
      TimeOut = USER_TIMEOUT;
      while ((SPI_I2S_GetFlagStatus(SPIx, SPI_I2S_FLAG_BSY) == SET)&&(TimeOut != 0x00))
      {}
      if(TimeOut == 0)
      {
        TimeOut_UserCallback();
      }
      
      /* Clear DMA1 global flags */
      DMA_ClearFlag(TIMx_CHANNEL_DMA_FLAG_GL);
      DMA_ClearFlag(SPIx_RX_DMA_FLAG_GL);
      
      /* Disable the DMA channels */
      DMA_Cmd(SPIx_RX_DMA_CHANNEL, DISABLE);
      DMA_Cmd(TIMx_CHANNEL_DMA_CHANNEL, DISABLE);
      
      /* Disable the SPI Rx and Tx DMA requests */
      SPI_I2S_DMACmd(SPIx, SPI_I2S_DMAReq_Rx, DISABLE);
      
      /* TIM disable counter */
      TIM_Cmd(TIMx, DISABLE);
      
      switch (NumberOfByte)
      {
        /* CMD_RIGHT command received */
      case CMD_RIGHT_SIZE:
        if ((Buffercmp(TxBuffer, RxBuffer, CMD_RIGHT_SIZE, SPI_DATAMASK) != FAILED) && (CommandReceived == CMD_ACK))
        {
          /* Turn ON LED2 and LED3 */
          STM_EVAL_LEDOn(LED2);
          STM_EVAL_LEDOn(LED3);
          /* Turn OFF LED4 */
          STM_EVAL_LEDOff(LED4);
        }
        break;
        /* CMD_LEFT command received */
      case CMD_LEFT_SIZE:
        if ((Buffercmp(TxBuffer, RxBuffer, CMD_LEFT_SIZE, SPI_DATAMASK) != FAILED) && (CommandReceived == CMD_ACK))
        {
          /* Turn ON LED4 */
          STM_EVAL_LEDOn(LED4);
          /* Turn OFF LED2 and LED3 */
          STM_EVAL_LEDOff(LED2);
          STM_EVAL_LEDOff(LED3);
        }
        break;
        /* CMD_UP command received */
      case CMD_UP_SIZE:
        if ((Buffercmp(TxBuffer, RxBuffer, CMD_UP_SIZE, SPI_DATAMASK) != FAILED) && (CommandReceived == CMD_ACK))
        {
          /* Turn ON LED2 */
          STM_EVAL_LEDOn(LED2);
          /* Turn OFF LED3 and LED4 */
          STM_EVAL_LEDOff(LED3);
          STM_EVAL_LEDOff(LED4);
        }
        break;
        /* CMD_DOWN command received */
      case CMD_DOWN_SIZE:
        if ((Buffercmp(TxBuffer, RxBuffer, CMD_DOWN_SIZE, SPI_DATAMASK) != FAILED) && (CommandReceived == CMD_ACK))
        {
          /* Turn ON LED3 */
          STM_EVAL_LEDOn(LED3);
          /* Turn OFF LED2 and LED4 */
          STM_EVAL_LEDOff(LED2);
          STM_EVAL_LEDOff(LED4);
        }
        break;
        /* CMD_SEL command received */
      case CMD_SEL_SIZE:
        if ((Buffercmp(TxBuffer, RxBuffer, CMD_SEL_SIZE, SPI_DATAMASK) != FAILED) && (CommandReceived == CMD_ACK))
        {
          /* Turn ON LED2, LED3 and LED4 */
          STM_EVAL_LEDOn(LED2);
          STM_EVAL_LEDOn(LED3);
          STM_EVAL_LEDOn(LED4);
        }
        break;
      default:
        break;
      }
    }
  }
#endif /* SPI_MASTER */
  
  /* Slave board configuration -----------------------------------------------*/
#ifdef SPI_SLAVE
  
  /* Initializes the SPI communication */
  SPI_I2S_DeInit(SPIx);
  SPI_InitStructure.SPI_Mode = SPI_Mode_Slave;
  SPI_Init(SPIx, &SPI_InitStructure);
  
  /* Initialize the FIFO threshold */
  SPI_RxFIFOThresholdConfig(SPIx, SPI_RxFIFOThreshold_QF);
  
  CommandTransmitted = CMD_ACK;
  
  /* Infinite Loop */
  while (1)
  {
    /* DMA channel Rx of SPI Configuration */
    DMA_InitStructure.DMA_BufferSize = 1;
    DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)SPIx_DR_ADDRESS;
    DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t) &CommandReceived;
    DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
    DMA_InitStructure.DMA_Priority = DMA_Priority_High;
    DMA_Init(SPIx_RX_DMA_CHANNEL, &DMA_InitStructure);
    
    /* DMA channel Tx of SPI Configuration */
    DMA_InitStructure.DMA_BufferSize = 1;
    DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)SPIx_DR_ADDRESS;
    DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t) &CommandTransmitted;
    DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;
    DMA_InitStructure.DMA_Priority = DMA_Priority_Low;
    DMA_Init(SPIx_TX_DMA_CHANNEL, &DMA_InitStructure);
    
    /* Enable the SPI Rx and Tx DMA requests */
    SPI_I2S_DMACmd(SPIx, SPI_I2S_DMAReq_Rx, ENABLE);
    SPI_I2S_DMACmd(SPIx, SPI_I2S_DMAReq_Tx, ENABLE);
    
    /* Enable the SPI peripheral */
    SPI_Cmd(SPIx, ENABLE);
    
    CommandReceived = 0x00;
    
    /* Enable the DMA channels */
    DMA_Cmd(SPIx_RX_DMA_CHANNEL, ENABLE);
    DMA_Cmd(SPIx_TX_DMA_CHANNEL, ENABLE);
    
    /* Wait the SPI DMA transfers complete or time out */
    while (DMA_GetFlagStatus(SPIx_RX_DMA_FLAG_TC) == RESET)
    {}
    
    TimeOut = USER_TIMEOUT;
    while ((DMA_GetFlagStatus(SPIx_TX_DMA_FLAG_TC) == RESET)&&(TimeOut != 0x00))
    {}
    if(TimeOut == 0)
    {
      TimeOut_UserCallback();
    }  
    
    /* The BSY flag can be monitored to ensure that the SPI communication is complete.
    This is required to avoid corrupting the last transmission before disabling 
    the SPI or entering the Stop mode. The software must first wait until TXE=1
    and then until BSY=0.*/
    TimeOut = USER_TIMEOUT;
    while ((SPI_I2S_GetFlagStatus(SPIx, SPI_I2S_FLAG_TXE) == RESET)&&(TimeOut != 0x00))
    {}
    if(TimeOut == 0)
    {
      TimeOut_UserCallback();
    }
    
    TimeOut = USER_TIMEOUT;
    while ((SPI_I2S_GetFlagStatus(SPIx, SPI_I2S_FLAG_BSY) == SET)&&(TimeOut != 0x00))
    {}
    if(TimeOut == 0)
    {
      TimeOut_UserCallback();
    } 
    
    /* Clear DMA1 global flags */
    DMA_ClearFlag(SPIx_TX_DMA_FLAG_GL);
    DMA_ClearFlag(SPIx_RX_DMA_FLAG_GL);
    
    /* Disable the DMA channels */
    DMA_Cmd(SPIx_RX_DMA_CHANNEL, DISABLE);
    DMA_Cmd(SPIx_TX_DMA_CHANNEL, DISABLE);
    
    /* Disable the SPI peripheral */
    SPI_Cmd(SPIx, DISABLE);
    
    /* Disable the SPI Rx and Tx DMA requests */
    SPI_I2S_DMACmd(SPIx, SPI_I2S_DMAReq_Rx, DISABLE);
    SPI_I2S_DMACmd(SPIx, SPI_I2S_DMAReq_Tx, DISABLE);
    
    
    switch (CommandReceived)
    {
      /* CMD_RIGHT command received */
    case CMD_RIGHT:
      NumberOfByte = CMD_RIGHT_SIZE;
      break;
      /* CMD_LEFT command received */  
    case CMD_LEFT:
      NumberOfByte = CMD_LEFT_SIZE;
      break;
      /* CMD_UP command received */ 
    case CMD_UP:
      NumberOfByte = CMD_UP_SIZE;
      break;
      /* CMD_DOWN command received */
    case CMD_DOWN:
      NumberOfByte = CMD_DOWN_SIZE;
      break;
      /* CMD_SEL command received */
    case CMD_SEL:
      NumberOfByte = CMD_SEL_SIZE;
      break;
    default:
      break;
    }   
    
    /* DMA channel Rx of SPI Configuration */
    DMA_InitStructure.DMA_BufferSize = NumberOfByte;
    DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)SPIx_DR_ADDRESS;
    DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)RxBuffer;
    DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
    DMA_InitStructure.DMA_Priority = DMA_Priority_High;
    DMA_Init(SPIx_RX_DMA_CHANNEL, &DMA_InitStructure);
    
    /* DMA channel Tx of SPI Configuration */
    DMA_InitStructure.DMA_BufferSize = NumberOfByte;
    DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)SPIx_DR_ADDRESS;
    DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)TxBuffer;
    DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;
    DMA_InitStructure.DMA_Priority = DMA_Priority_Low;
    DMA_Init(SPIx_TX_DMA_CHANNEL, &DMA_InitStructure);
    
    /* Enable the SPI Rx and Tx DMA requests */
    SPI_I2S_DMACmd(SPIx, SPI_I2S_DMAReq_Rx, ENABLE);
    SPI_I2S_DMACmd(SPIx, SPI_I2S_DMAReq_Tx, ENABLE);
    
    /* Enable the SPI peripheral */
    SPI_Cmd(SPIx, ENABLE);
    
    /* Enable the DMA channels */
    DMA_Cmd(SPIx_RX_DMA_CHANNEL, ENABLE);
    DMA_Cmd(SPIx_TX_DMA_CHANNEL, ENABLE);
    
    /* Wait the SPI DMA transfers complete or time out */
    while (DMA_GetFlagStatus(SPIx_RX_DMA_FLAG_TC) == RESET)
    {}
    
    TimeOut = USER_TIMEOUT;
    while ((DMA_GetFlagStatus(SPIx_TX_DMA_FLAG_TC) == RESET)&&(TimeOut != 0x00))
    {}
    if(TimeOut == 0)
    {
      TimeOut_UserCallback();
    } 
    
    /* The BSY flag can be monitored to ensure that the SPI communication is complete.
    This is required to avoid corrupting the last transmission before disabling 
    the SPI or entering the Stop mode. The software must first wait until TXE=1
    and then until BSY=0.*/
    TimeOut = USER_TIMEOUT;
    while ((SPI_I2S_GetFlagStatus(SPIx, SPI_I2S_FLAG_TXE) == RESET)&&(TimeOut != 0x00))
    {}
    if(TimeOut == 0)
    {
      TimeOut_UserCallback();
    }
    
    TimeOut = USER_TIMEOUT;
    while ((SPI_I2S_GetFlagStatus(SPIx, SPI_I2S_FLAG_BSY) == SET)&&(TimeOut != 0x00))
    {}
    if(TimeOut == 0)
    {
      TimeOut_UserCallback();
    }
    
    switch (NumberOfByte)
    {
      /* CMD_RIGHT command received */
    case CMD_RIGHT_SIZE:
      if (Buffercmp(TxBuffer, RxBuffer, CMD_RIGHT_SIZE, SPI_DATAMASK) != FAILED)
      {
        /* Turn ON LED2 and LED3 */
        STM_EVAL_LEDOn(LED2);
        STM_EVAL_LEDOn(LED3);
        /* Turn OFF LED4 */
        STM_EVAL_LEDOff(LED4);
      }
      break;
      /* CMD_LEFT command received */ 
    case CMD_LEFT_SIZE:
      if (Buffercmp(TxBuffer, RxBuffer, CMD_LEFT_SIZE, SPI_DATAMASK) != FAILED)
      {
        /* Turn ON LED4 */
        STM_EVAL_LEDOn(LED4);
        /* Turn OFF LED2 and LED3 */
        STM_EVAL_LEDOff(LED2);
        STM_EVAL_LEDOff(LED3);
      }
      break;
      /* CMD_UP command received */
    case CMD_UP_SIZE:
      if (Buffercmp(TxBuffer, RxBuffer, CMD_UP_SIZE, SPI_DATAMASK) != FAILED)
      {
        /* Turn ON LED2 */
        STM_EVAL_LEDOn(LED2);
        /* Turn OFF LED3 and LED4 */
        STM_EVAL_LEDOff(LED3);
        STM_EVAL_LEDOff(LED4);
      }
      break;
      /* CMD_DOWN command received */
    case CMD_DOWN_SIZE:
      if (Buffercmp(TxBuffer, RxBuffer, CMD_DOWN_SIZE, SPI_DATAMASK) != FAILED)
      {
        /* Turn ON LED3 */
        STM_EVAL_LEDOn(LED3);
        /* Turn OFF LED2 and LED4 */
        STM_EVAL_LEDOff(LED2);
        STM_EVAL_LEDOff(LED4);
      }
      break;
      /* CMD_SEL command received */
    case CMD_SEL_SIZE:
      if (Buffercmp(TxBuffer, RxBuffer, CMD_SEL_SIZE, SPI_DATAMASK) != FAILED)
      {
        /* Turn ON LED2, LED3 and LED4 */
        STM_EVAL_LEDOn(LED2);
        STM_EVAL_LEDOn(LED3);
        STM_EVAL_LEDOn(LED4);
      }
      break;
    default:
      break;
    }
    
    /* Clear DMA1 global flags */
    DMA_ClearFlag(SPIx_TX_DMA_FLAG_GL);
    DMA_ClearFlag(SPIx_RX_DMA_FLAG_GL);
    
    /* Disable the DMA channels */
    DMA_Cmd(SPIx_RX_DMA_CHANNEL, DISABLE);
    DMA_Cmd(SPIx_TX_DMA_CHANNEL, DISABLE);
    
    /* Disable the SPI peripheral */
    SPI_Cmd(SPIx, DISABLE);
    
    /* Disable the SPI Rx and Tx DMA requests */
    SPI_I2S_DMACmd(SPIx, SPI_I2S_DMAReq_Rx, DISABLE);
    SPI_I2S_DMACmd(SPIx, SPI_I2S_DMAReq_Tx, DISABLE);
  }
#endif /* SPI_SLAVE */
}
Exemple #10
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F1xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
         can eventually implement his proper time base source (a general purpose 
         timer for example or other time source), keeping in mind that Time base 
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
         handled in milliseconds basis.
       - Set NVIC Group Priority to 4
       - Low Level Initialization
     */
  HAL_Init();
  
  /* Configure the system clock to 24 MHz */
  SystemClock_Config();
  
  /*## Configure peripherals #################################################*/
  
  /* Initialize LEDs on board */
  BSP_LED_Init(LED4);
  BSP_LED_Init(LED3);
  
  /* Configure User push-button in Interrupt mode */
  BSP_PB_Init(BUTTON_USER, BUTTON_MODE_EXTI);
  
  /* Configure the ADC peripheral */
  ADC_Config();
  
  /* Run the ADC calibration */  
  if (HAL_ADCEx_Calibration_Start(&AdcHandle) != HAL_OK)
  {
    /* Calibration Error */
    Error_Handler();
  }

#if defined(ADC_TRIGGER_FROM_TIMER)
  /* Configure the TIM peripheral */
  TIM_Config();
#endif /* ADC_TRIGGER_FROM_TIMER */
#if defined(WAVEFORM_VOLTAGE_GENERATION_FOR_TEST)
  /* Configure the DAC peripheral */
  DAC_Config();
#endif /* WAVEFORM_VOLTAGE_GENERATION_FOR_TEST */

  /*## Enable peripherals ####################################################*/
#if defined(ADC_TRIGGER_FROM_TIMER)
  /* Timer enable */
  if (HAL_TIM_Base_Start(&TimHandle) != HAL_OK)
  {
    /* Counter Enable Error */
    Error_Handler();
  }
#endif /* ADC_TRIGGER_FROM_TIMER */

#if defined(WAVEFORM_VOLTAGE_GENERATION_FOR_TEST)
  /* Set DAC Channel data register: channel corresponding to ADC channel CHANNELa */
  /* Set DAC output to 1/2 of full range (4095 <=> Vdda=3.3V): 2048 <=> 1.65V              */
  if (HAL_DAC_SetValue(&DacHandle, DACx_CHANNEL_TO_ADCx_CHANNELa, DAC_ALIGN_12B_R, RANGE_12BITS/2) != HAL_OK)
  {
    /* Setting value Error */
    Error_Handler();
  }
  
  /* Enable DAC Channel: channel corresponding to ADC channel CHANNELa */
  if (HAL_DAC_Start(&DacHandle, DACx_CHANNEL_TO_ADCx_CHANNELa) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }
#endif /* WAVEFORM_VOLTAGE_GENERATION_FOR_TEST */

  /*## Start ADC conversions #################################################*/
  
  /* Start ADC conversion on regular group with transfer by DMA */
  if (HAL_ADC_Start_DMA(&AdcHandle,
                        (uint32_t *)aADCxConvertedValues,
                        ADCCONVERTEDVALUES_BUFFER_SIZE
                       ) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }
  
  
  /* Infinite loop */
  while (1)
  {

    /* Wait for event on push button to perform following actions */
    while ((ubUserButtonClickEvent) == RESET)
    {
    }
    /* Reset variable for next loop iteration */
    ubUserButtonClickEvent = RESET;
    
    /* Start ADC conversion on injected group */
    if (HAL_ADCEx_InjectedStart_IT(&AdcHandle) != HAL_OK)
    {
      /* Start Conversation Error */
      Error_Handler();
    }
    

#if defined(WAVEFORM_VOLTAGE_GENERATION_FOR_TEST)
    /* Set DAC voltage on channel corresponding to ADCx_CHANNELa              */
    /* in function of user button clicks count.                               */
    /* Set DAC output successively to:                                        */
    /*  - minimum of full range (0 <=> ground 0V)                             */
    /*  - 1/4 of full range (4095 <=> Vdda=3.3V): 1023 <=> 0.825V             */
    /*  - 1/2 of full range (4095 <=> Vdda=3.3V): 2048 <=> 1.65V              */
    /*  - 3/4 of full range (4095 <=> Vdda=3.3V): 3071 <=> 2.475V             */
    /*  - maximum of full range (4095 <=> Vdda=3.3V)                          */
    if (HAL_DAC_SetValue(&DacHandle,
                         DACx_CHANNEL_TO_ADCx_CHANNELa,
                         DAC_ALIGN_12B_R,
                         (RANGE_12BITS * ubUserButtonClickCount / USERBUTTON_CLICK_COUNT_MAX)
                        ) != HAL_OK)
    {
      /* Start Error */
      Error_Handler();
    }
#endif /* WAVEFORM_VOLTAGE_GENERATION_FOR_TEST */

    /* Wait for acquisition time of ADC samples on regular and injected       */
    /* groups:                                                                */
    /* wait time to let 1/2 buffer of regular group to be filled (in ms)      */
    HAL_Delay(16);
    
    /* Turn-on/off LED3 in function of ADC conversion result */
    /* - Turned-off if voltage measured by injected group is below voltage    */
    /*   measured by regular group (average of results table)                 */
    /* - Turned-off if voltage measured by injected group is above voltage    */
    /*   measured by regular group (average of results table)                 */
    
    /* Variables of conversions results are updated into ADC conversions      */
    /* interrupt callback.                                                    */
    if (uhADCxConvertedValue_Injected < *puhADCxConvertedValue_Regular_Avg)
    {
      BSP_LED_Off(LED3);
    }
    else
    {
      BSP_LED_On(LED3);
    }
  
    /* For information: ADC conversion results are stored into array          */
    /* "aADCxConvertedValues" (for debug: check into watch window)            */
    
  }
}
Exemple #11
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_stm32f40xx.s/startup_stm32f427x.s) before to branch to 
       application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f4xx.c file
     */     
       
  /* TIM Configuration */
  TIM_Config();

  /* ---------------------------------------------------------------------------
     Timers synchronisation in parallel mode
     1/TIM2 is configured as Master Timer:
         - PWM Mode is used
         - The TIM2 Update event is used as Trigger Output  
     2/TIM3 and TIM4 are slaves for TIM2,
         - PWM Mode is used
         - The ITR1(TIM2) is used as input trigger for both slaves
         - Gated mode is used, so starts and stops of slaves counters
           are controlled by the Master trigger output signal(update event).
  
    TIM2 input clock (TIM2CLK) is set to 2 * APB1 clock (PCLK1), 
    since APB1 prescaler is different from 1.   
      TIM2CLK = 2 * PCLK1  
      PCLK1 = HCLK / 4 
      => TIM2CLK = HCLK / 2 = SystemCoreClock /2
     
    To get Master Timer TIM2 output clock at 328.125 KHz running at  and the 
    duty cycle is equal to 25% :
    
    The period (TIM2_ARR) is computed as follows:
    ARR = (TIM2 counter clock / TIM2 output clock) - 1
        = 255

    The dutu cycle (TIM2_CCR1) is computed as follows:
    CCR1 = ((TIM2_ARR + 1) * 25)/100
         = 64
     
    The TIM3 is running:
    - At (TIM2 frequency)/ (TIM3 period + 1) = 32.815 KHz and a duty cycle
      equal to TIM3_CCR1/(TIM3_ARR + 1) = 30%
     
    The TIM4 is running:
    - At (TIM2 frequency)/ (TIM4 period + 1) = 65.630 KHz and a duty cycle
      equal to TIM4_CCR1/(TIM4_ARR + 1) = 60%
      
    Note: 
     SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
     Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
     function to update SystemCoreClock variable value. Otherwise, any configuration
     based on this variable will be incorrect.    
     
  ----------------------------------------------------------------------------*/

  /* Time base configuration */
  TIM_TimeBaseStructure.TIM_Period = 255;
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

  TIM_TimeBaseStructure.TIM_Period = 9;
  TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

  TIM_TimeBaseStructure.TIM_Period = 4;
  TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);

  /* Master Configuration in PWM1 Mode */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 64;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;

  TIM_OC1Init(TIM2, &TIM_OCInitStructure);

  /* Select the Master Slave Mode */
  TIM_SelectMasterSlaveMode(TIM2, TIM_MasterSlaveMode_Enable);

  /* Master Mode selection */
  TIM_SelectOutputTrigger(TIM2, TIM_TRGOSource_Update);

  /* Slaves Configuration: PWM1 Mode */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 3;

  TIM_OC1Init(TIM3, &TIM_OCInitStructure);

  TIM_OC1Init(TIM4, &TIM_OCInitStructure);

  /* Slave Mode selection: TIM3 */
  TIM_SelectSlaveMode(TIM3, TIM_SlaveMode_Gated);
  TIM_SelectInputTrigger(TIM3, TIM_TS_ITR1);
  
  /* Slave Mode selection: TIM4 */
  TIM_SelectSlaveMode(TIM4, TIM_SlaveMode_Gated);
  TIM_SelectInputTrigger(TIM4, TIM_TS_ITR1);
  
  /* TIM enable counter */
  TIM_Cmd(TIM3, ENABLE);
  TIM_Cmd(TIM2, ENABLE);
  TIM_Cmd(TIM4, ENABLE);

  while (1)
  {}
}
Exemple #12
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void) {
  __IO uint16_t i;
  __IO uint16_t *ptr;
  __IO uint16_t tmp1;
  __IO uint16_t tmp2;
  uint32_t scpcnt;
  uint32_t scpwait;
  uint32_t scptpos;
  /* RCC Configuration */
  RCC_Config();
  /* GPIO Configuration */
  GPIO_Config();
  /* TIM Configuration */
  TIM_Config();
  /* NVIC Configuration */
  NVIC_Config();
  /* DAC Configuration */
  DAC_Config();
  /* SPI Configuration */
  SPI_Config();
  /* USART Configuration */
  USART_Config(115200);
  /* Calibrate LC Meter */
  LCM_Calibrate();

  // /* Update bluetooth baudrate */
  // STM32_CMD.Cmd = STM32_CMD.TickCount;
  // while (STM32_CMD.Cmd == STM32_CMD.TickCount);
  // STM32_CMD.Cmd = STM32_CMD.TickCount;
  // while (STM32_CMD.Cmd == STM32_CMD.TickCount);
  // USART3_puts("AT\0");
  // STM32_CMD.Cmd = STM32_CMD.TickCount;
  // while (STM32_CMD.Cmd == STM32_CMD.TickCount)
  // {
    // if ((USART3->SR & USART_FLAG_RXNE) != 0)
    // {
      // STM32_CMD.BTBuff[i] = USART3->DR;
      // i++;
    // }
  // }
  // STM32_CMD.Cmd = STM32_CMD.TickCount;
  // while (STM32_CMD.Cmd == STM32_CMD.TickCount);
  // STM32_CMD.Cmd = STM32_CMD.TickCount;
  // while (STM32_CMD.Cmd == STM32_CMD.TickCount);
  // USART3_puts("AT+BAUD8\0");
  // STM32_CMD.Cmd = STM32_CMD.TickCount;
  // while (STM32_CMD.Cmd == STM32_CMD.TickCount)
  // {
    // if ((USART3->SR & USART_FLAG_RXNE) != 0)
    // {
      // STM32_CMD.BTBuff[i] = USART3->DR;
      // i++;
    // }
  // }
  // while (1)
  // {
  // }

  while (1) {
    USART3_getdata((uint8_t *)&STM32_CMD.Cmd,4);
    switch (STM32_CMD.Cmd)
    {
      case CMD_LCMCAL:
        LCM_Calibrate();
        USART3_putdata((uint8_t *)&STM32_CMD.STM32_LCM.FrequencyCal0,sizeof(STM32_LCMTypeDef));
        break;
      case CMD_LCMCAP:
        GPIO_ResetBits(GPIOD, GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_6 | GPIO_Pin_7);
        USART3_putdata((uint8_t *)&STM32_CMD.STM32_FRQ.Frequency,sizeof(STM32_FRQTypeDef));
        USART3_putdata((uint8_t *)&STM32_CMD.STM32_LCM.FrequencyCal0,sizeof(STM32_LCMTypeDef));
        break;
      case CMD_LCMIND:
        GPIO_ResetBits(GPIOD, GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_7);
        GPIO_SetBits(GPIOD, GPIO_Pin_6);
        USART3_putdata((uint8_t *)&STM32_CMD.STM32_FRQ.Frequency,sizeof(STM32_FRQTypeDef));
        USART3_putdata((uint8_t *)&STM32_CMD.STM32_LCM.FrequencyCal0,sizeof(STM32_LCMTypeDef));
        break;
      case CMD_FRQCH1:
        GPIO_ResetBits(GPIOD, GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_6 | GPIO_Pin_7);
        GPIO_SetBits(GPIOD, GPIO_Pin_0);
        USART3_putdata((uint8_t *)&STM32_CMD.STM32_FRQ.Frequency,sizeof(STM32_FRQTypeDef));
        break;
      case CMD_FRQCH2:
        GPIO_ResetBits(GPIOD, GPIO_Pin_0 | GPIO_Pin_2 | GPIO_Pin_6 | GPIO_Pin_7);
        GPIO_SetBits(GPIOD, GPIO_Pin_1);
        USART3_putdata((uint8_t *)&STM32_CMD.STM32_FRQ.Frequency,sizeof(STM32_FRQTypeDef));
        break;
      case CMD_FRQCH3:
        GPIO_ResetBits(GPIOD, GPIO_Pin_2 | GPIO_Pin_6 | GPIO_Pin_7);
        GPIO_SetBits(GPIOD, GPIO_Pin_0 | GPIO_Pin_1);
        USART3_putdata((uint8_t *)&STM32_CMD.STM32_FRQ.Frequency,sizeof(STM32_FRQTypeDef));
        break;
      case CMD_SCPSET:
        USART3_putdata((uint8_t *)&STM32_CMD.STM32_FRQ.Frequency,sizeof(STM32_FRQTypeDef));
        USART3_getdata((uint8_t *)&STM32_CMD.STM32_SCP.ADC_Prescaler,sizeof(STM32_SCPTypeDef));
        /* Scope magnify */
        i = (STM32_CMD.STM32_SCP.ScopeMag & 0x07) << 3;
        GPIO_SetBits(GPIOE,(i ^ 0x38));
        GPIO_ResetBits(GPIOE,i);
        /* Set V-Pos */
        DAC_SetChannel1Data(DAC_Align_12b_R, STM32_CMD.STM32_SCP.ScopeVPos);
        /* Set Trigger level */
        DAC_SetChannel2Data(DAC_Align_12b_R, STM32_CMD.STM32_SCP.ScopeTriggerLevel);
        if (STM32_CMD.STM32_SCP.ADC_TripleMode) {
          /* DMA Configuration */
          DMA_TripleConfig(STM32_CMD.STM32_SCP.ADC_SampleSize);
          /* ADC Configuration */
          ADC_TripleConfig(STM32_CMD.STM32_SCP.ADC_Prescaler, STM32_CMD.STM32_SCP.ADC_TwoSamplingDelay);
        } else {
          /* DMA Configuration */
          DMA_SingleConfig(STM32_CMD.STM32_SCP.ADC_SampleSize);
          /* ADC Configuration */
          ADC_SingleConfig(STM32_CMD.STM32_SCP.ADC_Prescaler,STM32_CMD.STM32_SCP.ADC_SampleTime);
        }
        if (STM32_CMD.STM32_SCP.ScopeTrigger == 2) {
          /* Rising edge */
          TIM5->CCER &= ~0x2;
        } else {
          /* Falling edge */
          TIM5->CCER |= 0x2;
        }
        if (STM32_CMD.STM32_SCP.ScopeTrigger) {
          /* Wait for trigger */
          scpcnt = TIM5->CNT;
          scpwait = STM32_CMD.TickCount + 2;
          while (scpcnt == TIM5->CNT && scpwait != STM32_CMD.TickCount);
        }
        /* Start ADC1 Software Conversion */
        ADC1->CR2 |= (uint32_t)ADC_CR2_SWSTART;
        i = 0;
        while (i < 30000) {
          i++;
        }
        /* Since BlueTooth is slower than the lowest sampling rate there is no need to wait */
        SendCompressedBuffer((uint32_t *)SCOPE_DATAPTR, STM32_CMD.STM32_SCP.ADC_SampleSize / 4);
        /* Done */
        ADC->CCR=0;
        ADC1->CR2=0;
        ADC2->CR2=0;
        ADC3->CR2=0;
        break;
      case CMD_SCP2SET:
        STM_EVAL_LEDToggle(LED4);
        USART3_putdata((uint8_t *)&STM32_CMD.STM32_FRQ.Frequency,sizeof(STM32_FRQTypeDef));
        USART3_getdata((uint8_t *)&STM32_CMD.STM32_SCP2.SampleRateSet,sizeof(STM32_SCP2TypeDef));
        /* Scope magnify */
        i = ((uint32_t)STM32_CMD.STM32_SCP2.Mag & 0x07) << 3;
        GPIO_SetBits(GPIOE,(i ^ 0x38));
        GPIO_ResetBits(GPIOE,i);
        /* Set V-Pos */
        DAC_SetChannel1Data(DAC_Align_12b_R, STM32_CMD.STM32_SCP2.VPos);
        /* Set Trigger level */
        DAC_SetChannel2Data(DAC_Align_12b_R, STM32_CMD.STM32_SCP2.TriggerLevel);
        /* Get number of samples needed */
        SampleSize = GetScopeSampleSize();
        if (STM32_CMD.STM32_SCP2.Triple) {
          /* DMA Configuration */
          DMA_TripleConfig(SampleSize);
          /* ADC Configuration */
          ADC_TripleConfig((uint32_t)STM32_CMD.STM32_SCP2.SampleRateSet >> 4,(uint32_t)STM32_CMD.STM32_SCP2.SampleRateSet & 0xF);
        } else {
          /* DMA Configuration */
          DMA_SingleConfig(SampleSize);
          /* ADC Configuration */
          ADC_SingleConfig(((uint32_t)STM32_CMD.STM32_SCP2.SampleRateSet >> 3) & 0x3,(uint32_t)STM32_CMD.STM32_SCP2.SampleRateSet & 0x7);
        }
        /* Trigger configuration */
        if (STM32_CMD.STM32_SCP2.Trigger == 2) {
          /* Rising edge */
          TIM5->CCER &= ~0x2;
        } else {
          /* Falling edge */
          TIM5->CCER |= 0x2;
        }
        if (STM32_CMD.STM32_SCP2.Trigger) {
          /* Wait for trigger */
          scpcnt = TIM5->CNT;
          scpwait = STM32_CMD.TickCount + 2;
          while (scpcnt == TIM5->CNT && scpwait != STM32_CMD.TickCount);
        }
        /* Start ADC1 Software Conversion */
        ADC1->CR2 |= (uint32_t)ADC_CR2_SWSTART;
        /* Reset wavedata */
        ScopeResetWave((uint32_t *)SCOPE_WAVEPTR,SCOPE_MAXWAVESIZE);
        ScopeResetWave((uint32_t *)SCOPE_COUNTPTR,SCOPE_MAXWAVESIZE);
        /* Wait until DMA transfer complete */
        while (DMA_GetFlagStatus(DMA2_Stream0, DMA_FLAG_TCIF0) == RESET);
        /* Done sampling */
        ADC->CCR=0;
        ADC1->CR2=0;
        ADC2->CR2=0;
        ADC3->CR2=0;
        ScopeSetWaveData((uint32_t *)SCOPE_WAVEPTR, (uint32_t *)SCOPE_COUNTPTR, (uint16_t *)SCOPE_DATAPTR);
        scptpos =  0;
        if (STM32_CMD.STM32_SCP2.Trigger) {
          scptpos = ScopeFindTrigger((uint16_t *)SCOPE_DATAPTR);
        }
        /* Send wave data */
        SendCompressedBuffer((uint32_t *)(SCOPE_DATAPTR + scptpos * 2), (uint32_t)STM32_CMD.STM32_SCP2.PixDiv * (uint32_t)STM32_CMD.STM32_SCP2.nDiv * 2 / 4);
        STM_EVAL_LEDToggle(LED4);
        break;
      case CMD_HSCSET:
        GPIO_ResetBits(GPIOD, GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_6 | GPIO_Pin_7);
        GPIO_SetBits(GPIOD, GPIO_Pin_0);
        USART3_getdata((uint8_t *)&STM32_CMD.STM32_HSC.HSCSet,sizeof(STM32_HSCTypeDef));
        TIM4->ARR = STM32_CMD.STM32_HSC.HSCSet;
        TIM4->CCR2 = (STM32_CMD.STM32_HSC.HSCSet+1) / 2;
        TIM4->PSC = STM32_CMD.STM32_HSC.HSCDiv;
        USART3_putdata((uint8_t *)&STM32_CMD.STM32_FRQ.Frequency,sizeof(STM32_FRQTypeDef));
        break;
      case CMD_DDSSET:
        USART3_getdata((uint8_t *)&STM32_CMD.STM32_DDS.DDS_Cmd,sizeof(STM32_DDSTypeDef));
        if (STM32_CMD.STM32_DDS.DDS_Cmd == DDS_PHASESET) {
          SPISendData(DDS_PHASESET);
          SPISendData32(STM32_CMD.STM32_DDS.DDS__PhaseAdd);
        }
        else if (STM32_CMD.STM32_DDS.DDS_Cmd == DDS_WAVESET) {
          SPISendData(DDS_WAVESET);
          SPISendData(STM32_CMD.STM32_DDS.DDS_Wave);
          SPISendData(STM32_CMD.STM32_DDS.DDS_Amplitude);
          SPISendData(STM32_CMD.STM32_DDS.DDS_DCOffset);
        } else if (STM32_CMD.STM32_DDS.DDS_Cmd == DDS_SWEEPSET) {
          SPISendData(DDS_SWEEPSET);
          SPISendData(STM32_CMD.STM32_DDS.SWEEP_Mode);
          SPISendData(STM32_CMD.STM32_DDS.SWEEP_Time);
          SPISendData32(STM32_CMD.STM32_DDS.SWEEP_Step);
          SPISendData32(STM32_CMD.STM32_DDS.SWEEP_Min);
          SPISendData32(STM32_CMD.STM32_DDS.SWEEP_Max);
        }
        break;
      case CMD_LGASET:
        USART3_getdata((uint8_t *)&STM32_CMD.STM32_LGA.DataBlocks,sizeof(STM32_LGATypeDef));
        /* Set the Prescaler value */
        TIM8->PSC = STM32_CMD.STM32_LGA.LGASampleRateDiv;
        /* Set the Autoreload value */
        TIM8->ARR = STM32_CMD.STM32_LGA.LGASampleRate;
        TIM8->CNT =  STM32_CMD.STM32_LGA.LGASampleRate-1;
        DMA_LGAConfig();
        TIM_DMACmd(TIM8, TIM_DMA_Update, ENABLE);
        /* DMA2_Stream1 enable */
        DMA_Cmd(DMA2_Stream1, ENABLE);
        /* Enable timer */
        TIM8->CR1 |= TIM_CR1_CEN;
        while (DMA_GetFlagStatus(DMA2_Stream1,DMA_FLAG_HTIF1) == RESET);
        /* Half done */
        USART3_putdata((uint8_t *)LGA_DATAPTR, STM32_CMD.STM32_LGA.DataBlocks * 1024 / 2);
        while (DMA_GetFlagStatus(DMA2_Stream1,DMA_FLAG_TCIF1) == RESET);
        /* Done */
        USART3_putdata((uint8_t *)(LGA_DATAPTR + STM32_CMD.STM32_LGA.DataBlocks * 1024 / 2), STM32_CMD.STM32_LGA.DataBlocks * 1024 / 2);
        TIM_Cmd(TIM8, DISABLE);
        DMA_DeInit(DMA2_Stream1);
        break;
      case CMD_WAVEUPLOAD:
        USART3_getdata((uint8_t *)WAVE_DATAPTR,4096);
        SPISendData(DDS_WAVEUPLOAD);
        ptr = (uint16_t *)WAVE_DATAPTR;
        i = 2048;
        while (i--) {
          SPISendData(*ptr);
          ptr++;
        }
        STM_EVAL_LEDToggle(LED4);
        break;
    }
Exemple #13
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
       files (startup_stm32f40_41xxx.s/startup_stm32f427_437xx.s/startup_stm32f429_439xx.s)
       before to branch to application main. 
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f4xx.c file
     */     
       
  /* TIM2/3/4 Configuration */
  TIM_Config();

  /* Timers synchronisation in cascade mode ------------------------------------
     1/TIM2 is configured as Master Timer:
         - PWM Mode is used
         - The TIM2 Update event is used as Trigger Output  

     2/TIM3 is slave for TIM2 and Master for TIM4,
         - PWM Mode is used
         - The ITR1(TIM2) is used as input trigger 
         - Gated mode is used, so start and stop of slave counter
           are controlled by the Master trigger output signal(TIM2 update event).
         - The TIM3 Update event is used as Trigger Output. 

     3/TIM4 is slave for TIM3,
         - PWM Mode is used
         - The ITR2(TIM3) is used as input trigger
         - Gated mode is used, so start and stop of slave counter
           are controlled by the Master trigger output signal(TIM3 update event).

     In this example TIM2 input clock (TIM2CLK) is set to 2 * APB1 clock (PCLK1), 
     since APB1 prescaler is different from 1.   
     TIM2CLK = 2 * PCLK1  
     PCLK1 = HCLK / 4 
     => TIM2CLK = HCLK / 2 = SystemCoreClock /2

     The Master Timer TIM2 is running at TIM2 counter clock:
     TIM2 frequency = (TIM2 counter clock)/ (TIM2 period + 1) = 328.125 KHz 
     and the duty cycle = TIM2_CCR1/(TIM2_ARR + 1) = 25%.

     The TIM3 is running:
     - At (TIM2 frequency)/ (TIM3 period + 1) = 82.02 KHz and a duty cycle
       equal to TIM3_CCR1/(TIM3_ARR + 1) = 25%

     The TIM4 is running:
     - At (TIM3 frequency)/ (TIM4 period + 1) = 20.5 KHz and a duty cycle
       equal to TIM4_CCR1/(TIM4_ARR + 1) = 25%
  
     Note: 
     SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
     Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
     function to update SystemCoreClock variable value. Otherwise, any configuration
     based on this variable will be incorrect. 
  --------------------------------------------------------------------------- */

  /* Time base configuration */
  TIM_TimeBaseStructure.TIM_Period = 255;
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
  TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

  TIM_TimeBaseStructure.TIM_Period = 3;
  TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

  TIM_TimeBaseStructure.TIM_Period = 3;
  TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);

  /* Master Configuration in PWM1 Mode */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 64;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;

  TIM_OC1Init(TIM2, &TIM_OCInitStructure);

  /* Select the Master Slave Mode */
  TIM_SelectMasterSlaveMode(TIM2, TIM_MasterSlaveMode_Enable);

  /* Master Mode selection */
  TIM_SelectOutputTrigger(TIM2, TIM_TRGOSource_Update);

  /* Slaves Configuration: PWM1 Mode */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 1;

  TIM_OC1Init(TIM3, &TIM_OCInitStructure);

  TIM_OC1Init(TIM4, &TIM_OCInitStructure);

  /* Slave Mode selection: TIM3 */
  TIM_SelectSlaveMode(TIM3, TIM_SlaveMode_Gated);
  TIM_SelectInputTrigger(TIM3, TIM_TS_ITR1);

  /* Select the Master Slave Mode */
  TIM_SelectMasterSlaveMode(TIM3, TIM_MasterSlaveMode_Enable);

  /* Master Mode selection: TIM3 */
  TIM_SelectOutputTrigger(TIM3, TIM_TRGOSource_Update);

  /* Slave Mode selection: TIM4 */
  TIM_SelectSlaveMode(TIM4, TIM_SlaveMode_Gated);
  TIM_SelectInputTrigger(TIM4, TIM_TS_ITR2);
  
  /* TIM enable counter */
  TIM_Cmd(TIM3, ENABLE);
  TIM_Cmd(TIM2, ENABLE);
  TIM_Cmd(TIM4, ENABLE);

  while (1)
  {
  }
}
Exemple #14
0
uint32_t Syringe_Size(void)
{
	uint32_t adc_value;
	uint32_t adc_valuetest=0;
 ADC_Config();
	
	
	  if (HAL_ADCEx_Calibration_Start(&AdcHandle) != HAL_OK)
  {
    /* Calibration Error */
    Error_Handler();
  }
	
	#if defined(ADC_TRIGGER_FROM_TIMER)
  /* Configure the TIM peripheral */
  TIM_Config();
#endif /* ADC_TRIGGER_FROM_TIMER */
	
	 /*## Enable peripherals ####################################################*/
#if defined(ADC_TRIGGER_FROM_TIMER)
  /* Timer enable */
  if (HAL_TIM_Base_Start(&TimHandle) != HAL_OK)
  {
    /* Counter Enable Error */
    Error_Handler();
  }
#endif /* ADC_TRIGGER_FROM_TIMER */
  /* Note: This example, on some other STM32 boards, is performing            */
  /*       DAC signal generation here.                                        */
  /*       On STM32F103RB-Nucleo, the device has no DAC available,            */
  /*       therefore analog signal must be supplied externally.               */

  /*## Start ADC conversions #################################################*/
  
  /* Start ADC conversion on regular group with transfer by DMA */
//   if (HAL_ADC_Start_DMA(&AdcHandle,
//                         (uint32_t *)aADCxConvertedValues,
//                         ADCCONVERTEDVALUES_BUFFER_SIZE
//                        ) != HAL_OK)
//   {
//     /* Start Error */
//     Error_Handler();
//   }
   if (HAL_ADC_Start(&AdcHandle) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }
	
	if (HAL_ADC_PollForConversion(&AdcHandle,10) != HAL_OK)
		  {
    /* Start Error */
    Error_Handler();
  }
	
	adc_value= HAL_ADC_GetValue(&AdcHandle);
	if(adc_value<=0x400) return(10);
	else if(adc_value>0x400 && adc_value<=0x800) return(20); 
	else if(adc_value>0x800 && adc_value<=0xc00) return(30); 
	else if(adc_value>0xc00)
	return(50);

}
Exemple #15
0
/**
  * @brief   Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  USART3_Config();
  uint8_t ctrl = 0;
  
  LIS302DL_InitTypeDef  LIS302DL_InitStruct;
  LIS302DL_InterruptConfigTypeDef LIS302DL_InterruptStruct;  
  
  /* SysTick end of count event each 10ms */
  SysTick_Config(SystemCoreClock/ 100);
  
  /* Set configuration of LIS302DL*/
  LIS302DL_InitStruct.Power_Mode = LIS302DL_LOWPOWERMODE_ACTIVE;
  LIS302DL_InitStruct.Output_DataRate = LIS302DL_DATARATE_100;
  LIS302DL_InitStruct.Axes_Enable = LIS302DL_X_ENABLE | LIS302DL_Y_ENABLE | LIS302DL_Z_ENABLE;
  LIS302DL_InitStruct.Full_Scale = LIS302DL_FULLSCALE_2_3;
  LIS302DL_InitStruct.Self_Test = LIS302DL_SELFTEST_NORMAL;
  LIS302DL_Init(&LIS302DL_InitStruct);
    
  /* Set configuration of Internal High Pass Filter of LIS302DL*/
  LIS302DL_InterruptStruct.Latch_Request = LIS302DL_INTERRUPTREQUEST_LATCHED;
  LIS302DL_InterruptStruct.SingleClick_Axes = LIS302DL_CLICKINTERRUPT_Z_ENABLE;
  LIS302DL_InterruptStruct.DoubleClick_Axes = LIS302DL_DOUBLECLICKINTERRUPT_Z_ENABLE;
  LIS302DL_InterruptConfig(&LIS302DL_InterruptStruct);

  /* Required delay for the MEMS Accelerometre: Turn-on time = 3/Output data Rate 
                                                             = 3/100 = 30ms */
  Delay(30);
  
  /* Configure Interrupt control register: enable Click interrupt1 */
  ctrl = 0x07;
  LIS302DL_Write(&ctrl, LIS302DL_CTRL_REG3_ADDR, 1);
  
  /* Enable Interrupt generation on click/double click on Z axis */
  ctrl = 0x70;
  LIS302DL_Write(&ctrl, LIS302DL_CLICK_CFG_REG_ADDR, 1);
  
  /* Configure Click Threshold on X/Y axis (10 x 0.5g) */
  ctrl = 0xAA;
  LIS302DL_Write(&ctrl, LIS302DL_CLICK_THSY_X_REG_ADDR, 1);
  
  /* Configure Click Threshold on Z axis (10 x 0.5g) */
  ctrl = 0x0A;
  LIS302DL_Write(&ctrl, LIS302DL_CLICK_THSZ_REG_ADDR, 1);
  
  /* Configure Time Limit */
  ctrl = 0x03;
  LIS302DL_Write(&ctrl, LIS302DL_CLICK_TIMELIMIT_REG_ADDR, 1);
    
  /* Configure Latency */
  ctrl = 0x7F;
  LIS302DL_Write(&ctrl, LIS302DL_CLICK_LATENCY_REG_ADDR, 1);
  
  /* Configure Click Window */
  ctrl = 0x7F;
  LIS302DL_Write(&ctrl, LIS302DL_CLICK_WINDOW_REG_ADDR, 1);
  
  /* TIM configuration -------------------------------------------------------*/
  TIM_Config(); 
  LIS302DL_Read(Buffer, LIS302DL_OUT_X_ADDR, 6);
  XOffset = (int8_t)Buffer[0];
  YOffset = (int8_t)Buffer[2];
  ZOffset = (int8_t)Buffer[4];
  while(1)
  {
a=(int8_t)(Buffer[0]);
if(a<0){
a=-a;
printf("\r\n X = -%d \r\n", a);
}
else{
printf("\r\n X = %d \r\n", a);
}
//printf("\r\n Y =%d \r\n", (int8_t)Buffer[2]);
//printf("\r\n Z =%d \r\n", (int8_t)Buffer[4]);

/*
temp=XOffset/sqrt((YOffset*YOffset+ZOffset*ZOffset));
angle_x=atan(temp);
angle_x=((angle_x*180)/3.14);

temp1=(int16_t)angle_x;
temp2=(angle_x-temp1)*1000;

printf("\r\n Angle_X=%d.%d \r\n", temp1,temp2);//use sqrt & atan
//原子教你玩的方法*/

/*
angle_ax=(XOffset-1100)/64;
angle_ax=(angle_ax*1.2*180/3.14);

temp1=(int16_t)angle_ax;
temp2=(angle_ax-temp1)*1000;
if(temp1<0){
a=-temp1;
b=-temp2;
printf("\r\n Angle_ax=%d.%d \r\n",a,b);
}
//網路上的方法*/

b=(float)((int8_t)Buffer[0]-XOffset)*(int32_t)LIS302DL_SENSITIVITY_2_3G/1000*180/3.14;
if(b<0){
x_acc=-b;
temp1=(int8_t)x_acc;
temp2=(x_acc-temp1)*10000;
if(temp2<0){temp2=-temp2;}
printf("\r\n X_Acc= -%d.%d \r\n", temp1,temp2);
}

else{
x_acc=b;
temp1=(int8_t)x_acc;
temp2=(x_acc-temp1)*10000;
if(temp2<0){temp2=-temp2;}
printf("\r\n X_Acc= %d.%d \r\n", temp1,temp2);
}
//openbox
        Delay(100);   
  }
}
Exemple #16
0
/**
  * @brief   Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  USART3_Config();  //USART3 init
  uint8_t ctrl = 0;
  
  LIS302DL_InitTypeDef  LIS302DL_InitStruct;
  LIS302DL_InterruptConfigTypeDef LIS302DL_InterruptStruct;  
  
  /* SysTick end of count event each 10ms */
  SysTick_Config(SystemCoreClock/ 100);
  
  /* Set configuration of LIS302DL*/
  LIS302DL_InitStruct.Power_Mode = LIS302DL_LOWPOWERMODE_ACTIVE;
  LIS302DL_InitStruct.Output_DataRate = LIS302DL_DATARATE_100;
  LIS302DL_InitStruct.Axes_Enable = LIS302DL_X_ENABLE | LIS302DL_Y_ENABLE | LIS302DL_Z_ENABLE;
  LIS302DL_InitStruct.Full_Scale = LIS302DL_FULLSCALE_2_3;
  LIS302DL_InitStruct.Self_Test = LIS302DL_SELFTEST_NORMAL;
  LIS302DL_Init(&LIS302DL_InitStruct);
    
  /* Set configuration of Internal High Pass Filter of LIS302DL*/
  LIS302DL_InterruptStruct.Latch_Request = LIS302DL_INTERRUPTREQUEST_LATCHED;
  LIS302DL_InterruptStruct.SingleClick_Axes = LIS302DL_CLICKINTERRUPT_Z_ENABLE;
  LIS302DL_InterruptStruct.DoubleClick_Axes = LIS302DL_DOUBLECLICKINTERRUPT_Z_ENABLE;
  LIS302DL_InterruptConfig(&LIS302DL_InterruptStruct);

  /* Required delay for the MEMS Accelerometre: Turn-on time = 3/Output data Rate 
                                                             = 3/100 = 30ms */
  Delay(30);
  
  /* Configure Interrupt control register: enable Click interrupt1 */
  ctrl = 0x07;
  LIS302DL_Write(&ctrl, LIS302DL_CTRL_REG3_ADDR, 1);
  
  /* Enable Interrupt generation on click/double click on Z axis */
  ctrl = 0x70;
  LIS302DL_Write(&ctrl, LIS302DL_CLICK_CFG_REG_ADDR, 1);
  
  /* Configure Click Threshold on X/Y axis (10 x 0.5g) */
  ctrl = 0xAA;
  LIS302DL_Write(&ctrl, LIS302DL_CLICK_THSY_X_REG_ADDR, 1);
  
  /* Configure Click Threshold on Z axis (10 x 0.5g) */
  ctrl = 0x0A;
  LIS302DL_Write(&ctrl, LIS302DL_CLICK_THSZ_REG_ADDR, 1);
  
  /* Configure Time Limit */
  ctrl = 0x03;
  LIS302DL_Write(&ctrl, LIS302DL_CLICK_TIMELIMIT_REG_ADDR, 1);
    
  /* Configure Latency */
  ctrl = 0x7F;
  LIS302DL_Write(&ctrl, LIS302DL_CLICK_LATENCY_REG_ADDR, 1);
  
  /* Configure Click Window */
  ctrl = 0x7F;
  LIS302DL_Write(&ctrl, LIS302DL_CLICK_WINDOW_REG_ADDR, 1);
  
  /* TIM configuration -------------------------------------------------------*/
  TIM_Config(); 
  LIS302DL_Read(Buffer, LIS302DL_OUT_X_ADDR, 6);
  XOffset = (int8_t)Buffer[0];
  YOffset = (int8_t)Buffer[2];
  ZOffset = (int8_t)Buffer[4];
  while(1)
  {

b=(float)((int8_t)Buffer[0]-XOffset)*(int32_t)LIS302DL_SENSITIVITY_2_3G/1000*180/3.14;  //把X軸裡面的值轉換成角度
if(b<0){
x_acc=-b;
temp1=(int8_t)x_acc;
temp2=(x_acc-temp1)*10000;  //把小數點部分乘上10000,以便程式印出(usart3的printf功能無法印出float)
if(temp2<0){temp2=-temp2;}
printf("\r\n X_Acc= -%d.%d \r\n", temp1,temp2);
}

else{
x_acc=b;
temp1=(int8_t)x_acc;
temp2=(x_acc-temp1)*10000;
if(temp2<0){temp2=-temp2;}
printf("\r\n X_Acc= %d.%d \r\n", temp1,temp2);
}
        Delay(100);   
  }
}
Exemple #17
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_stm32f40xx.s/startup_stm32f427x.s) before to branch to 
       application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f4xx.c file
     */     
       
  /* TIM1 Configuration */
  TIM_Config();
  
  /* ---------------------------------------------------------------------------
    TIM1 and Timers(TIM3 and TIM4) synchronisation in parallel mode.
     1/TIM1 is configured as Master Timer:
         - PWM Mode is used
         - The TIM1 Update event is used as Trigger Output
    
     2/TIM3 and TIM4 are slaves for TIM1,
         - PWM Mode is used
         - The ITR0(TIM1) is used as input trigger for both slaves
         - Gated mode is used, so starts and stops of slaves counters
           are controlled by the Master trigger output signal(update event).
    
    In this example TIM1 input clock (TIM1CLK) is set to 2 * APB2 clock (PCLK2), 
    since APB2 prescaler is different from 1.   
      TIM1CLK = 2 * PCLK2  
      PCLK2 = HCLK / 2 
      => TIM1CLK = HCLK = SystemCoreClock
          
    The TIM1 counter clock is equal to SystemCoreClock = 168 Mhz.
                                                               
    The Master Timer TIM1 is running at:
    TIM1 frequency = TIM1 counter clock / (TIM1_Period + 1) = 656 KHz
    TIM1_Period = (TIM1 counter clock / TIM1 frequency) - 1 = 255
    and the duty cycle is equal to: TIM1_CCR1/(TIM1_ARR + 1) = 50%

    The TIM3 is running at: 
    (TIM1 frequency)/ ((TIM3 period +1)* (Repetition_Counter+1)) = 43.730 KHz and
    a duty cycle equal to TIM3_CCR1/(TIM3_ARR + 1) = 33.3%

    The TIM4 is running at:
    (TIM1 frequency)/ ((TIM4 period +1)* (Repetition_Counter+1)) = 65.600 KHz and
    a duty cycle equal to TIM4_CCR1/(TIM4_ARR + 1) = 50%

    Note: 
     SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
     Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
     function to update SystemCoreClock variable value. Otherwise, any configuration
     based on this variable will be incorrect.    
  --------------------------------------------------------------------------- */   


  /* TIM3 Peripheral Configuration ----------------------------------------*/
  /* TIM3 Slave Configuration: PWM1 Mode */
  TIM_TimeBaseStructure.TIM_Period = 2;
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 1;

  TIM_OC1Init(TIM3, &TIM_OCInitStructure);

  /* Slave Mode selection: TIM3 */
  TIM_SelectSlaveMode(TIM3, TIM_SlaveMode_Gated);
  TIM_SelectInputTrigger(TIM3, TIM_TS_ITR0);
  
  /* TIM4 Peripheral Configuration ----------------------------------------*/
  /* TIM4 Slave Configuration: PWM1 Mode */
  TIM_TimeBaseStructure.TIM_Period = 1;
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);

  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 1;

  TIM_OC1Init(TIM4, &TIM_OCInitStructure);

  /* Slave Mode selection: TIM4 */
  TIM_SelectSlaveMode(TIM4, TIM_SlaveMode_Gated);
  TIM_SelectInputTrigger(TIM4, TIM_TS_ITR0);
  
  /* TIM1 Peripheral Configuration ----------------------------------------*/
  /* Time Base configuration */
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
  TIM_TimeBaseStructure.TIM_Period = 255;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_RepetitionCounter = 4;

  TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);

  /* Channel 1 Configuration in PWM mode */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 127;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
  TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_Low;
  TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;
  TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset;

  TIM_OC1Init(TIM1, &TIM_OCInitStructure);

  /* Automatic Output enable, Break, dead time and lock configuration*/
  TIM_BDTRInitStructure.TIM_OSSRState = TIM_OSSRState_Enable;
  TIM_BDTRInitStructure.TIM_OSSIState = TIM_OSSIState_Enable;
  TIM_BDTRInitStructure.TIM_LOCKLevel = TIM_LOCKLevel_1;
  TIM_BDTRInitStructure.TIM_DeadTime = 5;
  TIM_BDTRInitStructure.TIM_Break = TIM_Break_Disable;
  TIM_BDTRInitStructure.TIM_BreakPolarity = TIM_BreakPolarity_High;
  TIM_BDTRInitStructure.TIM_AutomaticOutput = TIM_AutomaticOutput_Disable;

  TIM_BDTRConfig(TIM1, &TIM_BDTRInitStructure);

  /* Master Mode selection */
  TIM_SelectOutputTrigger(TIM1, TIM_TRGOSource_Update);

  /* Select the Master Slave Mode */
  TIM_SelectMasterSlaveMode(TIM1, TIM_MasterSlaveMode_Enable);
  
  /* TIM1 counter enable */
  TIM_Cmd(TIM1, ENABLE);

  /* TIM enable counter */
  TIM_Cmd(TIM3, ENABLE);
  TIM_Cmd(TIM4, ENABLE);

  /* Main Output Enable */
  TIM_CtrlPWMOutputs(TIM1, ENABLE);

  while (1)
  {}
}
Exemple #18
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
       files (startup_stm32f40_41xxx.s/startup_stm32f427_437xx.s/startup_stm32f429_439xx.s)
       before to branch to application main. 
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f4xx.c file
     */    

  /* Initialize LEDs mounted on EVAL board */
  STM_EVAL_LEDInit(LED1);
  STM_EVAL_LEDInit(LED2);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED4);

  /* Initialize the KEY/WAKEUP and Tamper buttons mounted on EVAL board */
#ifdef USE_STM324x9I_EVAL
  STM_EVAL_PBInit(BUTTON_WAKEUP, BUTTON_MODE_GPIO);
#else
  STM_EVAL_PBInit(BUTTON_KEY, BUTTON_MODE_GPIO);
#endif /* USE_STM324x9I_EVAL */
  
  STM_EVAL_PBInit(BUTTON_TAMPER, BUTTON_MODE_EXTI);
    
  /* TIM configuration -------------------------------------------------------*/
  TIM_Config();

  while (1)
  { 
    /* Wait until KEY/WAKEUP button is pressed */
    while(STM_EVAL_PBGetState(BUTTON_WAKEUP_KEY) == RESET)
    {
    }
    while(STM_EVAL_PBGetState(BUTTON_WAKEUP_KEY) != RESET)
    {
    }

    /* This instruction raises the execution priority to 0. This prevents all 
       exceptions with configurable priority from activating, other than through 
       the HardFault fault escalation mechanism. */
    __disable_irq();

    /* Turn LED4 ON */
    STM_EVAL_LEDOn(LED4);

    /* Wait until KEY/WAKEUP button is pressed */
    while(STM_EVAL_PBGetState(BUTTON_WAKEUP_KEY) == RESET)
    {
    }
    while(STM_EVAL_PBGetState(BUTTON_WAKEUP_KEY) != RESET)
    {
    }

    /* This instruction will allow all exceptions with configurable priority to 
       be activated. */
    __enable_irq();

    /* Turn LED4 OFF */
    STM_EVAL_LEDOff(LED4);
  }
}
Exemple #19
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
       files (startup_stm32f40xx.s/startup_stm32f427x.s) before to branch to 
       application main. 
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f4xx.c file
     */     

  /* TIM1 Configuration */
  TIM_Config();       
  
  /* Time base configuration */
  /* -----------------------------------------------------------------------
    TIM1 Configuration: generate 1 PWM signal using the DMA burst mode:
  
    TIM1 input clock (TIM1CLK) is set to 2 * APB2 clock (PCLK2), 
    since APB2 prescaler is different from 1.   
      TIM1CLK = 2 * PCLK2  
      PCLK2 = HCLK / 2 
      => TIM1CLK = 2 * (HCLK / 2) = HCLK = SystemCoreClock
    
    To get TIM1 counter clock at 24 MHz, the prescaler is computed as follows:
      Prescaler = (TIM1CLK / TIM1 counter clock) - 1
      Prescaler = (SystemCoreClock /24 MHz) - 1
  
    The TIM1 period is 5.8 KHz: TIM1 Frequency = TIM1 counter clock/(ARR + 1)
                                               = 24 MHz / 4096 = 5.85 KHz
    TIM1 Channel1 duty cycle = (TIM1_CCR1/ TIM1_ARR)* 100 = 33.33%
  
    Note: 
     SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
     Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
     function to update SystemCoreClock variable value. Otherwise, any configuration
     based on this variable will be incorrect.  
  ----------------------------------------------------------------------- */  
  TIM_TimeBaseStructure.TIM_Period = 0xFFFF;          
  TIM_TimeBaseStructure.TIM_Prescaler = (uint16_t) (SystemCoreClock / 24000000) - 1;       
  TIM_TimeBaseStructure.TIM_ClockDivision = 0x0;    
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;   
  TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);

  /* TIM Configuration in PWM Mode */
  TIM_OCInitStructure.TIM_OCMode =  TIM_OCMode_PWM1;    
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;          
  TIM_OCInitStructure.TIM_Pulse = 0xFFF;  
  TIM_OC1Init(TIM1, &TIM_OCInitStructure); 

  /* TIM1 DMAR Base register and DMA Burst Length Config */
  TIM_DMAConfig(TIM1, TIM_DMABase_ARR, TIM_DMABurstLength_3Transfers);

  /* TIM1 DMA Update enable */
  TIM_DMACmd(TIM1, TIM_DMA_Update, ENABLE);

  /* TIM1 enable */
  TIM_Cmd(TIM1, ENABLE);
  
  /* TIM1 PWM Outputs Enable */
  TIM_CtrlPWMOutputs(TIM1, ENABLE);

  /* Enable DMA2 Stream5  */
  DMA_Cmd(DMA2_Stream5, ENABLE);

  /* Wait until DMA2 Stream5 end of Transfer */
  while (!DMA_GetFlagStatus(DMA2_Stream5, DMA_FLAG_TCIF5))
  {
  }

  /* Infinite loop */ 
  while(1)
  {
  }
}
Exemple #20
0
/***项目定时器配置***/
void app_tim(void)
{
	TIM_Config(TIM2);
 	TIM_Config(TIM3);
 	TIM_Config(TIM4);
}
Exemple #21
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
       files (startup_stm32f40_41xxx.s/startup_stm32f427_437xx.s/startup_stm32f429_439xx.s)
       before to branch to application main. 
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f4xx.c file
     */     
       
  /* TIM1 Configuration */
  TIM_Config();

  /* ---------------------------------------------------------------------------
  TIM1 Configuration to:

  1/ Generate 3 complementary PWM signals with 3 different duty cycles:
  
    TIM1 input clock (TIM1CLK) is set to 2 * APB2 clock (PCLK2), since APB2 
    prescaler is different from 1.   
    TIM1CLK = 2 * PCLK2  
    PCLK2 = HCLK / 2 
    => TIM1CLK = 2 * (HCLK / 2) = HCLK = SystemCoreClock
  
    TIM1CLK is fixed to SystemCoreClock, the TIM1 Prescaler is equal to 0 so the 
    TIM1 counter clock used is SystemCoreClock (168MHz).

    The objective is to generate PWM signal at 17.57 KHz:
    - TIM1_Period = (SystemCoreClock / 17570) - 1

    The Three Duty cycles are computed as the following description: 

    The channel 1 duty cycle is set to 50% so channel 1N is set to 50%.
    The channel 2 duty cycle is set to 25% so channel 2N is set to 75%.
    The channel 3 duty cycle is set to 12.5% so channel 3N is set to 87.5%.
    
    The Timer pulse is calculated as follows:
      - ChannelxPulse = DutyCycle * (TIM1_Period - 1) / 100

  2/ Insert a dead time equal to (11/SystemCoreClock) ns

  3/ Configure the break feature, active at High level, and using the automatic 
     output enable feature

  4/ Use the Locking parameters level1. 
  
  Note: 
    SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
    Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
    function to update SystemCoreClock variable value. Otherwise, any configuration
    based on this variable will be incorrect. 
  --------------------------------------------------------------------------- */

  /* Compute the value to be set in ARR register to generate signal frequency at 17.57 Khz */
  TimerPeriod = (SystemCoreClock / 17570) - 1;

  /* Compute CCR1 value to generate a duty cycle at 50% for channel 1 */
  Channel1Pulse = (uint16_t) (((uint32_t) 5 * (TimerPeriod - 1)) / 10);

  /* Compute CCR2 value to generate a duty cycle at 25%  for channel 2 */
  Channel2Pulse = (uint16_t) (((uint32_t) 25 * (TimerPeriod - 1)) / 100);

  /* Compute CCR3 value to generate a duty cycle at 12.5%  for channel 3 */
  Channel3Pulse = (uint16_t) (((uint32_t) 125 * (TimerPeriod - 1)) / 1000);

  /* Time Base configuration */
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
  TIM_TimeBaseStructure.TIM_Period = TimerPeriod;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;

  TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);

  /* Channel 1, 2 and 3 Configuration in PWM mode */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable;
  TIM_OCInitStructure.TIM_Pulse = Channel1Pulse;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
  TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_Low;
  TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;
  TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset;

  TIM_OC1Init(TIM1, &TIM_OCInitStructure);

  TIM_OCInitStructure.TIM_Pulse = Channel2Pulse;
  TIM_OC2Init(TIM1, &TIM_OCInitStructure);

  TIM_OCInitStructure.TIM_Pulse = Channel3Pulse;
  TIM_OC3Init(TIM1, &TIM_OCInitStructure);

  /* Automatic Output enable, Break, dead time and lock configuration*/
  TIM_BDTRInitStructure.TIM_OSSRState = TIM_OSSRState_Enable;
  TIM_BDTRInitStructure.TIM_OSSIState = TIM_OSSIState_Enable;
  TIM_BDTRInitStructure.TIM_LOCKLevel = TIM_LOCKLevel_1;
  TIM_BDTRInitStructure.TIM_DeadTime = 11;
  TIM_BDTRInitStructure.TIM_Break = TIM_Break_Enable;
  TIM_BDTRInitStructure.TIM_BreakPolarity = TIM_BreakPolarity_High;
  TIM_BDTRInitStructure.TIM_AutomaticOutput = TIM_AutomaticOutput_Enable;

  TIM_BDTRConfig(TIM1, &TIM_BDTRInitStructure);

  /* TIM1 counter enable */
  TIM_Cmd(TIM1, ENABLE);

  /* Main Output Enable */
  TIM_CtrlPWMOutputs(TIM1, ENABLE);

  while (1)
  {
  }
}
Exemple #22
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
         files (startup_stm32f40_41xxx.s/startup_stm32f427_437xx.s/startup_stm32f429_439xx.s)
         before to branch to application main.
         To reconfigure the default setting of SystemInit() function, refer to
         system_stm32f4xx.c file
       */

    /* TIM Configuration */
    TIM_Config();

    /* TIM1 DMA Transfer example -------------------------------------------------

    TIM1 input clock (TIM1CLK) is set to 2 * APB2 clock (PCLK2), since APB2
    prescaler is different from 1.
      TIM1CLK = 2 * PCLK2
      PCLK2 = HCLK / 2
      => TIM1CLK = 2 * (HCLK / 2) = HCLK = SystemCoreClock

    TIM1CLK = SystemCoreClock, Prescaler = 0, TIM1 counter clock = SystemCoreClock
    SystemCoreClock is set to 168 MHz for STM32F4xx devices.

    The objective is to configure TIM1 channel 3 to generate complementary PWM
    signal with a frequency equal to 17.57 KHz:
       - TIM1_Period = (SystemCoreClock / 17570) - 1
    and a variable duty cycle that is changed by the DMA after a specific number of
    Update DMA request.

    The number of this repetitive requests is defined by the TIM1 Repetion counter,
    each 3 Update Requests, the TIM1 Channel 3 Duty Cycle changes to the next new
    value defined by the aSRC_Buffer.

    Note:
      SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
      Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
      function to update SystemCoreClock variable value. Otherwise, any configuration
      based on this variable will be incorrect.
    -----------------------------------------------------------------------------*/

    /* Compute the value to be set in ARR regiter to generate signal frequency at 17.57 Khz */
    uhTimerPeriod = (SystemCoreClock / 17570 ) - 1;
    /* Compute CCR1 value to generate a duty cycle at 50% */
    aSRC_Buffer[0] = (uint16_t) (((uint32_t) 5 * (uhTimerPeriod - 1)) / 10);
    /* Compute CCR1 value to generate a duty cycle at 37.5% */
    aSRC_Buffer[1] = (uint16_t) (((uint32_t) 375 * (uhTimerPeriod - 1)) / 1000);
    /* Compute CCR1 value to generate a duty cycle at 25% */
    aSRC_Buffer[2] = (uint16_t) (((uint32_t) 25 * (uhTimerPeriod - 1)) / 100);

    /* TIM1 Peripheral Configuration -------------------------------------------*/
    /* TIM1 clock enable */
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);

    /* Time Base configuration */
    TIM_TimeBaseStructure.TIM_Prescaler = 0;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseStructure.TIM_Period = uhTimerPeriod;
    TIM_TimeBaseStructure.TIM_ClockDivision = 0;
    TIM_TimeBaseStructure.TIM_RepetitionCounter = 3;

    TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);

    /* Channel 3 Configuration in PWM mode */
    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable;
    TIM_OCInitStructure.TIM_Pulse = aSRC_Buffer[0];
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
    TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_Low;
    TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;
    TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset;

    TIM_OC3Init(TIM1, &TIM_OCInitStructure);

    /* Enable preload feature */
    TIM_OC3PreloadConfig(TIM1, TIM_OCPreload_Enable);

    /* TIM1 counter enable */
    TIM_Cmd(TIM1, ENABLE);

    /* DMA enable*/
    DMA_Cmd(DMA2_Stream6, ENABLE);

    /* TIM1 Update DMA Request enable */
    TIM_DMACmd(TIM1, TIM_DMA_CC3, ENABLE);

    /* Main Output Enable */
    TIM_CtrlPWMOutputs(TIM1, ENABLE);

    while (1)
    {
    }
}
Exemple #23
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_stm32f2xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f2xx.c file
     */

  /* TIM Configuration */
  TIM_Config();

  /* TIM1 Configuration ---------------------------------------------------
   Generate 7 PWM signals with 4 different duty cycles:
   TIM1 input clock (TIM1CLK) is set to 2 * APB2 clock (PCLK2), since APB2 
    prescaler is different from 1.   
    TIM1CLK = 2 * PCLK2  
    PCLK2 = HCLK / 2 
    => TIM1CLK = 2 * (HCLK / 2) = HCLK = SystemCoreClock
   TIM1CLK = SystemCoreClock, Prescaler = 0, TIM1 counter clock = SystemCoreClock
   SystemCoreClock is set to 120 MHz for STM32F2xx devices
   
   The objective is to generate 7 PWM signal at 17.57 KHz:
     - TIM1_Period = (SystemCoreClock / 17570) - 1
   The channel 1 and channel 1N duty cycle is set to 50%
   The channel 2 and channel 2N duty cycle is set to 37.5%
   The channel 3 and channel 3N duty cycle is set to 25%
   The channel 4 duty cycle is set to 12.5%
   The Timer pulse is calculated as follows:
     - ChannelxPulse = DutyCycle * (TIM1_Period - 1) / 100
   
   Note: 
    SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
    Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
    function to update SystemCoreClock variable value. Otherwise, any configuration
    based on this variable will be incorrect. 
  ----------------------------------------------------------------------- */
  /* Compute the value to be set in ARR regiter to generate signal frequency at 17.57 Khz */
  TimerPeriod = (SystemCoreClock / 17570 ) - 1;
  /* Compute CCR1 value to generate a duty cycle at 50% for channel 1 and 1N */
  Channel1Pulse = (uint16_t) (((uint32_t) 5 * (TimerPeriod - 1)) / 10);
  /* Compute CCR2 value to generate a duty cycle at 37.5%  for channel 2 and 2N */
  Channel2Pulse = (uint16_t) (((uint32_t) 375 * (TimerPeriod - 1)) / 1000);
  /* Compute CCR3 value to generate a duty cycle at 25%  for channel 3 and 3N */
  Channel3Pulse = (uint16_t) (((uint32_t) 25 * (TimerPeriod - 1)) / 100);
  /* Compute CCR4 value to generate a duty cycle at 12.5%  for channel 4 */
  Channel4Pulse = (uint16_t) (((uint32_t) 125 * (TimerPeriod- 1)) / 1000);

  /* TIM1 clock enable */
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1 , ENABLE);
  
  /* Time Base configuration */
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
  TIM_TimeBaseStructure.TIM_Period = TimerPeriod;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;

  TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);

  /* Channel 1, 2,3 and 4 Configuration in PWM mode */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable;
  TIM_OCInitStructure.TIM_Pulse = Channel1Pulse;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
  TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_High;
  TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;
  TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset;

  TIM_OC1Init(TIM1, &TIM_OCInitStructure);

  TIM_OCInitStructure.TIM_Pulse = Channel2Pulse;
  TIM_OC2Init(TIM1, &TIM_OCInitStructure);

  TIM_OCInitStructure.TIM_Pulse = Channel3Pulse;
  TIM_OC3Init(TIM1, &TIM_OCInitStructure);

  TIM_OCInitStructure.TIM_Pulse = Channel4Pulse;
  TIM_OC4Init(TIM1, &TIM_OCInitStructure);

  /* TIM1 counter enable */
  TIM_Cmd(TIM1, ENABLE);

  /* TIM1 Main Output Enable */
  TIM_CtrlPWMOutputs(TIM1, ENABLE);

  while (1)
  {}
}
Exemple #24
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_stm32f4xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f4xx.c file
     */
       
  /* TIM Configuration */
  TIM_Config();

  /* ---------------------------------------------------------------------------
    TIM3 Configuration: Output Compare Toggle Mode:
    
    In this example TIM3 input clock (TIM3CLK) is set to 2 * APB1 clock (PCLK1), 
    since APB1 prescaler is different from 1.   
      TIM3CLK = 2 * PCLK1  
      PCLK1 = HCLK / 4 
      => TIM3CLK = HCLK / 2 = SystemCoreClock /2
          
    To get TIM3 counter clock at 21 MHz, the prescaler is computed as follows:
       Prescaler = (TIM3CLK / TIM3 counter clock) - 1
       Prescaler = ((SystemCoreClock /2) /21 MHz) - 1
                                              
     CC1 update rate = TIM3 counter clock / uhCCR1_Val = 512.68 Hz
	   ==> So the TIM3 Channel 1 generates a periodic signal with a 
	       frequency equal to 256.35 Hz.

     CC2 update rate = TIM3 counter clock / uhCCR2_Val = 1025.39 Hz
	   ==> So the TIM3 Channel 2 generates a periodic signal with a 
	       frequency equal to 512.7 Hz.

     CC3 update rate = TIM3 counter clock / uhCCR3_Val = 2050.8 Hz
	   ==> So the TIM3 Channel 3 generates a periodic signal with a 
	       frequency equal to 1025.4 Hz.

     CC4 update rate = TIM3 counter clock / uhCCR4_Val = 4101.56 Hz
	   ==> So the TIM3 Channel 4 generates a periodic signal with a 
	       frequency equal to 2050.78 Hz.

    Note: 
     SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
     Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
     function to update SystemCoreClock variable value. Otherwise, any configuration
     based on this variable will be incorrect.    
  --------------------------------------------------------------------------- */   

  /* Compute the prescaler value */
  uhPrescalerValue = (uint16_t) ((SystemCoreClock / 2) / 21000000) - 1;

  /* Time base configuration */
  TIM_TimeBaseStructure.TIM_Period = 65535;
  TIM_TimeBaseStructure.TIM_Prescaler = uhPrescalerValue;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

  /* Output Compare Toggle Mode configuration: Channel1 */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Toggle;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = uhCCR1_Val;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
  TIM_OC1Init(TIM3, &TIM_OCInitStructure);

  TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Disable);

  /* Output Compare Toggle Mode configuration: Channel2 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = uhCCR2_Val;

  TIM_OC2Init(TIM3, &TIM_OCInitStructure);

  TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Disable);

  /* Output Compare Toggle Mode configuration: Channel3 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = uhCCR3_Val;

  TIM_OC3Init(TIM3, &TIM_OCInitStructure);

  TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Disable);

  /* Output Compare Toggle Mode configuration: Channel4 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = uhCCR4_Val;

  TIM_OC4Init(TIM3, &TIM_OCInitStructure);

  TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Disable);

  /* TIM enable counter */
  TIM_Cmd(TIM3, ENABLE);

  /* TIM IT enable */
  TIM_ITConfig(TIM3, TIM_IT_CC1 | TIM_IT_CC2 | TIM_IT_CC3 | TIM_IT_CC4, ENABLE);

  while (1)
  {
  }
}
Exemple #25
0
    int main()
  {
    
    
    RCC_Config();  // to read and write to AFIO_remap AFIO_clock must first be eanble
    NVIC_Config();
    TIM_Config(); 
    GPIO_Config();
    EXTI_Configuration();
    initUsart();
    //initBT();
    
              // Only for debug the clock tree  *********************************************** 
          // Put the clock configuration into RCC_APB2PeriphClockCmd 
          RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); 
          /* Output clock on MCO pin ---------------------------------------------*/ 
          GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8; 
          GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; 
          GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; 
          GPIO_Init(GPIOA, &GPIO_InitStructure); 
          //  RCC_MCOConfig(RCC_MCO_HSE); // Put on MCO pin the: freq. of external crystal 
          RCC_MCOConfig(RCC_MCO_SYSCLK);  // Put on MCO pin the: System clock selected  
          // 
    //RTCInit();
    
    RCC_GetClocksFreq(&RCC_Clocks);   
    
    writeStringUSART2("\033[2J"); //clear usart 2 screen
    writeStringUSART1("\033[2J");  //clear usart 1 screen
    writeStringUSART1("     <<<<- Welcome To Hinkens Cobra Bluetooth ->>>>\n\n\r");


    
    

    while(1)
    {

        if(GPIO_ReadInputDataBit(GPIOB, COBRA_BOARDSWITCH)== false) writeStringUSART1("On Hook\n\r");
        else            //Luren är lyft
        {
            writeStringUSART1("Phone is off hook!\n\r Dial: \n\r");
            acceptCall(); //accept incoming call
            Delay(Delay_10ms);
            //for(counter = 0 ; counter < 10 ; counter++)
            while(TIM_GetITStatus(TIM2, TIM_IT_Update) == RESET) //
            {
                
                dialed_number = 0;
                while(GPIO_ReadInputDataBit(GPIOB, COBRA_DIALING)== true && GPIO_ReadInputDataBit(GPIOB, COBRA_BOARDSWITCH)== true)//Wait for user to start dialing
                {
                  //writeStringUSART1("Timer Counter: %d\r\n",TIM_GetCounter(TIM2));
                  if(state == 1 && dialingFlag == true) //check if timer has run out and user has started a call
                  {
                    writeStringUSART1("time is up dialing number: ");
                    for (int x = 0; x < counter; x++)
                    {
                      //printf("%d", number[x] );
                    }
                    sendPhoneNumber(number, counter);
                    writeStringUSART1("\r\n");
                    dialingFlag = false;
                    state =  0;
                    counter = 0;
                  }
                    
                }
                Delay(Delay_100ms); //Wait for switch to debounce
          
                while(GPIO_ReadInputDataBit(GPIOB, COBRA_DIALING) == false)
                {    
                     dialingFlag = true;
                     state = 0;
                     TIM_SetCounter(TIM2, 0);
                     TIM_Cmd(TIM2, ENABLE); //Start timer
                     
                     //RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
                     Delay(Delay_10ms);
                     Delay(Delay_10ms);
                      //Now count how many times the mechnical switch toggles
                     if(GPIO_ReadInputDataBit(GPIOB, COBRA_PULSE)== false && pulseFlag == 1)
                     {
                       pulseFlag = 0;
                       dialed_number ++;
                     }
                     else if(GPIO_ReadInputDataBit(GPIOB, COBRA_PULSE) == true && pulseFlag == 0)
                     {
                       pulseFlag = 1;
                        //Do notthing just idle..
                     }
                     
                  Delay(Delay_10ms);   

                }
                Delay(Delay_100ms);
                if(dialed_number != 0) // to handle the error of a extra loop after dialed number
                {
                  dialed_number--; //Rotary always has one extra closure that must be taken off
                  number[counter] = dialed_number;
                  counter ++;
                }

                if(GPIO_ReadInputDataBit(GPIOB, COBRA_BOARDSWITCH)== false) //Hunng upp
                {
                  hangUp(); //hang-up command to bluettooh
                  writeStringUSART1("Hung up!\n\r");
                  counter = 0;
                  break;
                }

              
                //printf("%d\n\r", dialed_number);
                    
            }//end for loop
        }
        
        Delay(Delay_100ms);
    
    }//end while(1)

  }//end main()
Exemple #26
0
/*====================================================================================================*/
void System_Init( void )
{
  HAL_Init();
  GPIO_Config();
  TIM_Config();
}
Exemple #27
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
       files (startup_stm32f40_41xxx.s/startup_stm32f427_437xx.s/startup_stm32f429_439xx.s)
       before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f4xx.c file
     */

  /* TIM Configuration */
  TIM_Config();

  /* Time base default values configuration */
  TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);

  /* Output compare default values configuration */
  TIM_OCStructInit(&TIM_OCInitStructure);


  /* ---------------------------------------------------------------------------
    TIM3 Configuration: Output Compare Active Mode:
    In this example TIM3 input clock (TIM3CLK) is set to 2 * APB1 clock (PCLK1),
    since APB1 prescaler is different from 1.
      TIM3CLK = 2 * PCLK1
      PCLK1 = HCLK / 4
      => TIM3CLK = HCLK / 2 = SystemCoreClock /2

    To get TIM3 counter clock at 2 KHz, the prescaler is computed as follows:
       Prescaler = (TIM3CLK / TIM3 counter clock) - 1
       Prescaler = ((SystemCoreClock /2) /1 KHz) - 1

    Generate 4 signals with 4 different delays:
    TIM3_CH1 delay = uhCCR1_Val/TIM3 counter clock = 500 ms
    TIM3_CH2 delay = uhCCR2_Val/TIM3 counter clock = 250 ms
    TIM3_CH3 delay = uhCCR3_Val/TIM3 counter clock = 125 ms
    TIM3_CH4 delay = uhCCR4_Val/TIM3 counter clock = 62.5 ms

    Note:
     SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
     Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
     function to update SystemCoreClock variable value. Otherwise, any configuration
     based on this variable will be incorrect.

  --------------------------------------------------------------------------- */

  /* Compute the prescaler value */
  uhPrescalerValue = (uint16_t) ((SystemCoreClock / 2) / 2000) - 1;

  /* Time base configuration */
  TIM_TimeBaseStructure.TIM_Period = 65535;
  TIM_TimeBaseStructure.TIM_Prescaler = uhPrescalerValue;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

  /* Output Compare Active Mode configuration: Channel1 */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Active;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = uhCCR1_Val;
  TIM_OC1Init(TIM3, &TIM_OCInitStructure);

  TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Disable);
  TIM_ARRPreloadConfig(TIM3, DISABLE);
  /* Output Compare Active Mode configuration: Channel2 */
  TIM_OCInitStructure.TIM_Pulse = uhCCR2_Val;
  TIM_OC2Init(TIM3, &TIM_OCInitStructure);

  TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Disable);

  /* Output Compare Active Mode configuration: Channel3 */
  TIM_OCInitStructure.TIM_Pulse = uhCCR3_Val;
  TIM_OC3Init(TIM3, &TIM_OCInitStructure);

  TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Disable);

  /* Output Compare Active Mode configuration: Channel4 */
  TIM_OCInitStructure.TIM_Pulse = uhCCR4_Val;
  TIM_OC4Init(TIM3, &TIM_OCInitStructure);

  TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Disable);

  /* TIM3 enable counter */
  TIM_Cmd(TIM3, ENABLE);

  TIM_GenerateEvent(TIM3, TIM_EventSource_Update);

  /* Turn on LED1 */
  STM_EVAL_LEDOn(LED1);

  while (1)
  {
  }
}
Exemple #28
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F0xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
         can eventually implement his proper time base source (a general purpose 
         timer for example or other time source), keeping in mind that Time base 
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
         handled in milliseconds basis.
       - Low Level Initialization
     */
  HAL_Init();
  
  /* Configure the system clock to 48 MHz */
  SystemClock_Config();
  
  
  /*## Configure peripherals #################################################*/
  
  /* Initialize LED on board */
  BSP_LED_Init(LED2);
  
  /* Configure User push-button in Interrupt mode */
  BSP_PB_Init(BUTTON_USER, BUTTON_MODE_EXTI);
  
  /* Configure the ADCx peripheral */
  ADC_Config();
  
  /* Run the ADC calibration */
  if (HAL_ADCEx_Calibration_Start(&AdcHandle) != HAL_OK)
  {
    /* Calibration Error */
    Error_Handler();
  }

#if defined(ADC_TRIGGER_FROM_TIMER)
  /* Configure the TIM peripheral */
  TIM_Config();
#endif /* ADC_TRIGGER_FROM_TIMER */

#if defined(WAVEFORM_VOLTAGE_GENERATION_FOR_TEST)
  /* Configure the DAC peripheral and generate a constant voltage of Vdda/2.  */
  WaveformVoltageGenerationForTest_Config();
#endif /* WAVEFORM_VOLTAGE_GENERATION_FOR_TEST */
  
  
  /*## Enable peripherals ####################################################*/
  
#if defined(ADC_TRIGGER_FROM_TIMER)
  /* Timer enable */
  if (HAL_TIM_Base_Start(&TimHandle) != HAL_OK)
  {
    /* Counter Enable Error */
    Error_Handler();
  }
#endif /* ADC_TRIGGER_FROM_TIMER */
  
  
  /*## Start ADC conversions #################################################*/
  
  /* Start ADC conversion on regular group with transfer by DMA */
  if (HAL_ADC_Start_DMA(&AdcHandle,
                        (uint32_t *)aADCxConvertedValues,
                        ADCCONVERTEDVALUES_BUFFER_SIZE
                       ) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }
  
  
  /* Infinite loop */
  while (1)
  {
  
    /* Turn-on/off LED2 in function of ADC conversion result */
    /* - Turn-off if voltage is into AWD window */
    /* - Turn-on if voltage is out of AWD window */

    /* Variable of analog watchdog status is set into analog watchdog         */
    /* interrupt callback                                                     */
    if (ubAnalogWatchdogStatus == RESET)
    {
      BSP_LED_Off(LED2);
    }
    else
    {
      BSP_LED_On(LED2);
      
      /* Reset analog watchdog status for next loop iteration */
      ubAnalogWatchdogStatus = RESET;
    }
  
    /* For information: ADC conversion results are stored into array          */
    /* "aADCxConvertedValues" (for debug: check into watch window)            */
  
  
    /* Wait for event on push button to perform following actions */
    while ((ubUserButtonClickEvent) == RESET)
    {
    }
    /* Reset variable for next loop iteration */
    ubUserButtonClickEvent = RESET;

#if defined(WAVEFORM_VOLTAGE_GENERATION_FOR_TEST)
    /* Modifies the voltage level incrementally from 0V to Vdda at each call. */
    /* Circular waveform of ramp: When the maximum level is reaches,          */
    /* restart from 0V.                                                       */
    WaveformVoltageGenerationForTest_Update();
#endif /* WAVEFORM_VOLTAGE_GENERATION_FOR_TEST */
  }
}
/**
  * @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
       files (startup_stm32f40_41xxx.s/startup_stm32f427_437xx.s/startup_stm32f429_439xx.s)
       before to branch to application main. 
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f4xx.c file
     */    
       
  /* TIM Configuration */
  TIM_Config();

  /* Timers synchronisation in cascade mode with an external trigger -----
    1/TIM1 is configured as Master Timer:
       - Toggle Mode is used
       - The TIM1 Enable event is used as Trigger Output 

    2/TIM1 is configured as Slave Timer for an external Trigger connected
      to TIM1 TI2 pin (TIM1 CH2 configured as input pin):
       - The TIM1 TI2FP2 is used as Trigger Input
       - Rising edge is used to start and stop the TIM1: Gated Mode.

    3/TIM3 is slave for TIM1 and Master for TIM4,
       - Toggle Mode is used
       - The ITR1(TIM1) is used as input trigger 
       - Gated mode is used, so start and stop of slave counter
         are controlled by the Master trigger output signal(TIM1 enable event).
       - The TIM3 enable event is used as Trigger Output. 

    4/TIM4 is slave for TIM3,
       - Toggle Mode is used
       - The ITR2(TIM3) is used as input trigger
       - Gated mode is used, so start and stop of slave counter
         are controlled by the Master trigger output signal(TIM3 enable event).
  
    TIM1 input clock (TIM1CLK) is set to 2 * APB2 clock (PCLK2), 
    since APB2 prescaler is different from 1.   
      TIM1CLK = 2 * PCLK2  
      PCLK2 = HCLK / 2 
      => TIM1CLK = 2 * (HCLK / 2) = HCLK = SystemCoreClock 
    
    TIM3/TIM4 input clock (TIM3CLK/TIM4CLK) is set to 2 * APB1 clock (PCLK1), 
    since APB1 prescaler is different from 1.   
      TIM3CLK/TIM4CLK = 2 * PCLK1  
      PCLK1 = HCLK / 4 
      => TIM3CLK/TIM4CLK = HCLK / 2 = SystemCoreClock /2

      The TIM1CLK is fixed to 168 MHZ, the Prescaler is equal to 5 so the TIMx clock 
      counter is equal to 28 MHz.
      The TIM3CLK  and TIM4CLK are fixed to 84 MHZ, the Prescaler is equal to 5 
      so the TIMx clock counter is equal to 14 MHz.      
      The Three Timers are running at: 
      TIMx frequency = TIMx clock counter/ 2*(TIMx_Period + 1) = 189.1 KHz.

    The starts and stops of the TIM1 counters are controlled by the 
    external trigger.
    The TIM3 starts and stops are controlled by the TIM1, and the TIM4 
    starts and stops are controlled by the TIM3.  
    
    Note: 
     SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
     Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
     function to update SystemCoreClock variable value. Otherwise, any configuration
     based on this variable will be incorrect.  
  -------------------------------------------------------------------- */

  /* Time base configuration for TIM1, TIM3 & TIM4 */
  TIM_TimeBaseStructure.TIM_Period = 73;
  TIM_TimeBaseStructure.TIM_Prescaler = 5;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);

  TIM_TimeBaseStructure.TIM_Period = 36;
  TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

  TIM_TimeBaseStructure.TIM_Period = 36;
  TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);

  /* Master Configuration in Toggle Mode */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Toggle;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 64;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;

  TIM_OC1Init(TIM1, &TIM_OCInitStructure);

  /* TIM1 Input Capture Configuration */
  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 = 0;

  TIM_ICInit(TIM1, &TIM_ICInitStructure);

  /* TIM1 Input trigger configuration: External Trigger connected to TI2 */
  TIM_SelectInputTrigger(TIM1, TIM_TS_TI2FP2);
  TIM_SelectSlaveMode(TIM1, TIM_SlaveMode_Gated);

  /* Select the Master Slave Mode */
  TIM_SelectMasterSlaveMode(TIM1, TIM_MasterSlaveMode_Enable);

  /* Master Mode selection: TIM1 */
  TIM_SelectOutputTrigger(TIM1, TIM_TRGOSource_Enable);

  /* Slaves Configuration: Toggle Mode */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Toggle;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 10;
  TIM_OC1Init(TIM3, &TIM_OCInitStructure);

  TIM_OC1Init(TIM4, &TIM_OCInitStructure);

  /* Slave Mode selection: TIM3 */
  TIM_SelectInputTrigger(TIM3, TIM_TS_ITR0);
  TIM_SelectSlaveMode(TIM3, TIM_SlaveMode_Gated);

  /* Select the Master Slave Mode */
  TIM_SelectMasterSlaveMode(TIM3, TIM_MasterSlaveMode_Enable);

  /* Master Mode selection: TIM3 */
  TIM_SelectOutputTrigger(TIM3, TIM_TRGOSource_Enable);

  /* Slave Mode selection: TIM4 */
  TIM_SelectInputTrigger(TIM4, TIM_TS_ITR2);
  TIM_SelectSlaveMode(TIM4, TIM_SlaveMode_Gated);
  
  /* TIM1 Main Output Enable */
  TIM_CtrlPWMOutputs(TIM1, ENABLE);

  /* TIM enable counter */
  TIM_Cmd(TIM1, ENABLE);
  TIM_Cmd(TIM3, ENABLE);
  TIM_Cmd(TIM4, ENABLE);

  while (1)
  {
  }
}
Exemple #30
0
Fichier : main.c Projet : jwag/BCI
//***************************************************************************************
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_stm32f4xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
        system_stm32f4xx.c file
     */

  /* Initialize Leds mounted on STM32F4-Discovery board */
  STM_EVAL_LEDInit(LED4);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED5);
  STM_EVAL_LEDInit(LED6);

  init_USART1(9600); // initialize USART1 @ 9600 baud

  char hello[]  = "Init complete! Hello World!/n";
  USART_puts_chars(USART1, hello); // just send a message to indicate that it works


  /* ADC3 configuration *******************************************************/
  /*  - Enable peripheral clocks                                              */
  /*  - DMA2_Stream0 channel2 configuration                                   */
  /*  - Configure ADC Channel12 pin as analog input                           */
  /*  - Configure ADC3 Channel12                                              */
  ADC3_CH12_DMA_Config();

  /* Start ADC3 Software Conversion */
  ADC_SoftwareStartConv(ADC3);

  DMA_ITConfig(DMA2_Stream0,DMA_IT_TC,ENABLE);

  /* TIM Configuration */
  TIM_Config();

  PWM_Config();

  /* Setup SysTick Timer for 1 msec interrupts.
     ------------------------------------------
    1. The SysTick_Config() function is a CMSIS function which configure:
       - The SysTick Reload register with value passed as function parameter.
       - Configure the SysTick IRQ priority to the lowest value (0x0F).
       - Reset the SysTick Counter register.
       - Configure the SysTick Counter clock source to be Core Clock Source (HCLK).
       - Enable the SysTick Interrupt.
       - Start the SysTick Counter.

    2. You can change the SysTick Clock source to be HCLK_Div8 by calling the
       SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8) just after the
       SysTick_Config() function call. The SysTick_CLKSourceConfig() is defined
       inside the misc.c file.

    3. You can change the SysTick IRQ priority by calling the
       NVIC_SetPriority(SysTick_IRQn,...) just after the SysTick_Config() function
       call. The NVIC_SetPriority() is defined inside the core_cm4.h file.

    4. To adjust the SysTick time base, use the following formula:

         Reload Value = SysTick Counter Clock (Hz) x  Desired Time base (s)

       - Reload Value is the parameter to be passed for SysTick_Config() function
       - Reload Value should not exceed 0xFFFFFF
   */
  if (SysTick_Config(SystemCoreClock / (6250)))
  {
    /* Capture error */
    while (1);
  }

  set_PWM_duty( 75, LEFT_LED_880);
  static uint8_t duty_cycle = 0;
  while (1)
  {
    /* Toggle LED3 and LED6 */
    //STM_EVAL_LEDToggle(LED3);
    //Delay(100);
    STM_EVAL_LEDToggle(LED4);
    Delay(100);
    STM_EVAL_LEDToggle(LED6);
    Delay(100);
    STM_EVAL_LEDToggle(LED5);
    Delay(100);
  }
}