Exemplo n.º 1
0
static void set_baud_rate(USART_TypeDef *usart, int baud)
{
    if (usart->CR1 & USART_CR1_OVER8) {
        if (usart == USART1 || usart == USART6) {
            usart->BRR = __UART_BRR_SAMPLING8(HAL_RCC_GetPCLK2Freq(), baud);
        } else {
            usart->BRR = __UART_BRR_SAMPLING8(HAL_RCC_GetPCLK1Freq(), baud);
        }
    } else {
        if (usart == USART1 || usart == USART6) {
            usart->BRR = __UART_BRR_SAMPLING16(HAL_RCC_GetPCLK2Freq(), baud);
        } else {
            usart->BRR = __UART_BRR_SAMPLING16(HAL_RCC_GetPCLK1Freq(), baud);
        }
    }
}
Exemplo n.º 2
0
/**
  * @brief  Configures the IRDA peripheral. 
  * @param  hirda: Pointer to a IRDA_HandleTypeDef structure that contains
  *                the configuration information for the specified IRDA module.
  * @retval None
  */
static void IRDA_SetConfig(IRDA_HandleTypeDef *hirda)
{
  /* Check the parameters */
  assert_param(IS_IRDA_BAUDRATE(hirda->Init.BaudRate));  
  assert_param(IS_IRDA_WORD_LENGTH(hirda->Init.WordLength));
  assert_param(IS_IRDA_PARITY(hirda->Init.Parity));
  assert_param(IS_IRDA_MODE(hirda->Init.Mode));
  
  /*------- IRDA-associated USART registers setting : CR2 Configuration ------*/
  /* Clear STOP[13:12] bits */
  CLEAR_BIT(hirda->Instance->CR2, USART_CR2_STOP);
  
  /*------- IRDA-associated USART registers setting : CR1 Configuration ------*/
  /* Configure the USART Word Length, Parity and mode: 
     Set the M bits according to hirda->Init.WordLength value 
     Set PCE and PS bits according to hirda->Init.Parity value
     Set TE and RE bits according to hirda->Init.Mode value */
  MODIFY_REG(hirda->Instance->CR1,
             ((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE)),
             (uint32_t)hirda->Init.WordLength | hirda->Init.Parity | hirda->Init.Mode);
  
  /*------- IRDA-associated USART registers setting : CR3 Configuration ------*/
  /* Clear CTSE and RTSE bits */
  CLEAR_BIT(hirda->Instance->CR3, (USART_CR3_RTSE | USART_CR3_CTSE));
  
  /*------- IRDA-associated USART registers setting : BRR Configuration ------*/
  if(hirda->Instance == USART1)
  {
    hirda->Instance->BRR = IRDA_BRR(HAL_RCC_GetPCLK2Freq(), hirda->Init.BaudRate);
  }
  else
  {
    hirda->Instance->BRR = IRDA_BRR(HAL_RCC_GetPCLK1Freq(), hirda->Init.BaudRate);
  }
}
Exemplo n.º 3
0
/*
 * Only the frequency is managed in the family specific part
 * the rest of SPI management is common to all STM32 families
 */
int spi_get_clock_freq(spi_t *obj) {
    struct spi_s *spiobj = SPI_S(obj);
	int spi_hz = 0;

	/* Get source clock depending on SPI instance */
    switch ((int)spiobj->spi) {
        case SPI_1:
#if defined SPI4_BASE
        case SPI_4:
#endif
#if defined SPI5_BASE
        case SPI_5:
#endif
#if defined SPI6_BASE
        case SPI_6:
#endif
            /* SPI_1, SPI_4, SPI_5 and SPI_6. Source CLK is PCKL2 */
            spi_hz = HAL_RCC_GetPCLK2Freq();
            break;
        case SPI_2:
#if defined SPI3_BASE
        case SPI_3:
#endif
            /* SPI_2 and SPI_3. Source CLK is PCKL1 */
            spi_hz = HAL_RCC_GetPCLK1Freq();
            break;
        default:
            error("CLK: SPI instance not set");
            break;
    }
    return spi_hz;
}
Exemplo n.º 4
0
/**
  * @brief  Conversion complete callback in non blocking mode 
  * @param  htim: TIM handle
  * @retval None
  */
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
  if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_2)
  {
    if(uhCaptureIndex == 0)
    {
      /* Get the 1st Input Capture value */
      uwIC2Value1 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_2);
      uhCaptureIndex = 1;
    }
    else if(uhCaptureIndex == 1)
    {
      /* Get the 2nd Input Capture value */
      uwIC2Value2 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_2); 
      
      /* Capture computation */
      if (uwIC2Value2 > uwIC2Value1)
      {
        uwDiffCapture = (uwIC2Value2 - uwIC2Value1); 
      }
      else  /* (uwIC2Value2 <= uwIC2Value1) */
      {
        uwDiffCapture = ((0xFFFF - uwIC2Value1) + uwIC2Value2); 
      }

      /* Frequency computation: for this example TIMx (TIM1) is clocked by
         2xAPB2Clk */      
      uwFrequency = (2*HAL_RCC_GetPCLK2Freq()) / uwDiffCapture;
      uhCaptureIndex = 0;
    } 
  }
}
Exemplo n.º 5
0
uint32_t uart_get_baudrate(pyb_uart_obj_t *self) {
    uint32_t uart_clk = 0;

    #if defined(STM32F0)
    uart_clk = HAL_RCC_GetPCLK1Freq();
    #elif defined(STM32F7)
    switch ((RCC->DCKCFGR2 >> ((self->uart_id - 1) * 2)) & 3) {
        case 0:
            if (self->uart_id == 1 || self->uart_id == 6) {
                uart_clk = HAL_RCC_GetPCLK2Freq();
            } else {
                uart_clk = HAL_RCC_GetPCLK1Freq();
            }
            break;
        case 1:
            uart_clk = HAL_RCC_GetSysClockFreq();
            break;
        case 2:
            uart_clk = HSI_VALUE;
            break;
        case 3:
            uart_clk = LSE_VALUE;
            break;
    }
    #elif defined(STM32H7)
    uint32_t csel;
    if (self->uart_id == 1 || self->uart_id == 6) {
        csel = RCC->D2CCIP2R >> 3;
    } else {
Exemplo n.º 6
0
void spi_frequency(spi_t *obj, int hz)
{
    int spi_hz = 0;
	uint8_t prescaler_rank = 0;

	/* Get source clock depending on SPI instance */
    switch ((int)obj->spi) {
        case SPI_1:
			/* SPI_1. Source CLK is PCKL2 */
			spi_hz = HAL_RCC_GetPCLK2Freq();
			break;
		case SPI_2:
			/* SPI_2. Source CLK is PCKL1 */
			spi_hz = HAL_RCC_GetPCLK1Freq();
			break;
		default:
			error("SPI instance not set");
    }

	/* Define pre-scaler in order to get highest available frequency below requested frequency */
	while ((spi_hz > hz) && (prescaler_rank < sizeof(baudrate_prescaler_table)/sizeof(baudrate_prescaler_table[0]))){
		spi_hz = spi_hz / 2;
		prescaler_rank++;
	}

	if (prescaler_rank <= sizeof(baudrate_prescaler_table)/sizeof(baudrate_prescaler_table[0])) {
		obj->br_presc = baudrate_prescaler_table[prescaler_rank-1];
	} else {
		error("Couldn't setup requested SPI frequency");
	}

    init_spi(obj);
}
Exemplo n.º 7
0
void initTimers()
{
    TIM_HandleTypeDef TIM_Handle;

    // 10 kHz timer.
#if defined STM32F1
    __TIM8_CLK_ENABLE();
    TIM_Handle.Instance = TIM8;
    TIM_Handle.Init.Prescaler = (uint16_t)(HAL_RCC_GetPCLK2Freq() / 10000) - 1;
#elif defined STM32F2
    __TIM4_CLK_ENABLE();
    TIM_Handle.Instance = TIM4;
    TIM_Handle.Init.Prescaler = (uint16_t)(HAL_RCC_GetPCLK2Freq() / 100000) - 1;
#elif defined STM32F4
    __TIM3_CLK_ENABLE();
    TIM_Handle.Instance = TIM3;
    // TIM3 Clocked from SYSCLK = 168 MHz
    TIM_Handle.Init.Prescaler = (uint16_t)(HAL_RCC_GetSysClockFreq() / 10000) - 1;
#endif
    // 1 Hz blinking
    TIM_Handle.Init.Period = 10000;
    TIM_Handle.Init.ClockDivision = 0;
    TIM_Handle.Init.CounterMode = TIM_COUNTERMODE_UP;

    HAL_TIM_Base_Init(&TIM_Handle);
    HAL_TIM_PWM_Init(&TIM_Handle);

    TIM_OC_InitTypeDef TIM_OCConfig;

    TIM_OCConfig.OCMode = TIM_OCMODE_PWM1;
    // 5000 / 10000 = 50% duty cycle.
    TIM_OCConfig.Pulse = 4999;
    TIM_OCConfig.OCPolarity = TIM_OCPOLARITY_HIGH;
    TIM_OCConfig.OCFastMode = TIM_OCFAST_DISABLE;

#if defined STM32F1
    HAL_TIM_PWM_ConfigChannel(&TIM_Handle, &TIM_OCConfig, TIM_CHANNEL_3);
    HAL_TIM_PWM_Start(&TIM_Handle, TIM_CHANNEL_3);
#elif defined STM32F2
    HAL_TIM_PWM_ConfigChannel(&TIM_Handle, &TIM_OCConfig, TIM_CHANNEL_1);
    HAL_TIM_PWM_Start(&TIM_Handle, TIM_CHANNEL_1);
#elif defined STM32F4
    HAL_TIM_PWM_ConfigChannel(&TIM_Handle, &TIM_OCConfig, TIM_CHANNEL_1);
    HAL_TIM_PWM_Start(&TIM_Handle, TIM_CHANNEL_1);
#endif
}
Exemplo n.º 8
0
/// \function freq()
/// Return a tuple of clock frequencies: (SYSCLK, HCLK, PCLK1, PCLK2).
// TODO should also be able to set frequency via this function
STATIC mp_obj_t pyb_freq(void) {
    mp_obj_t tuple[4] = {
       mp_obj_new_int(HAL_RCC_GetSysClockFreq()),
       mp_obj_new_int(HAL_RCC_GetHCLKFreq()),
       mp_obj_new_int(HAL_RCC_GetPCLK1Freq()),
       mp_obj_new_int(HAL_RCC_GetPCLK2Freq()),
    };
    return mp_obj_new_tuple(4, tuple);
}
/**
  * @brief Configure the IRDA peripheral 
  * @param hirda: irda handle
  * @retval None
  */
static HAL_StatusTypeDef IRDA_SetConfig(IRDA_HandleTypeDef *hirda)
{
  uint32_t tmpreg                     = 0x00000000;
  IRDA_ClockSourceTypeDef clocksource = IRDA_CLOCKSOURCE_UNDEFINED;
  HAL_StatusTypeDef ret               = HAL_OK;  
  
  /* Check the communication parameters */ 
  assert_param(IS_IRDA_BAUDRATE(hirda->Init.BaudRate));  
  assert_param(IS_IRDA_WORD_LENGTH(hirda->Init.WordLength));
  assert_param(IS_IRDA_PARITY(hirda->Init.Parity));
  assert_param(IS_IRDA_TX_RX_MODE(hirda->Init.Mode));
  assert_param(IS_IRDA_PRESCALER(hirda->Init.Prescaler)); 
  assert_param(IS_IRDA_POWERMODE(hirda->Init.PowerMode)); 

  /*-------------------------- USART CR1 Configuration -----------------------*/        
  /* Configure the IRDA Word Length, Parity and transfer Mode: 
     Set the M bits according to hirda->Init.WordLength value 
     Set PCE and PS bits according to hirda->Init.Parity value
     Set TE and RE bits according to hirda->Init.Mode value */
  tmpreg = (uint32_t)hirda->Init.WordLength | hirda->Init.Parity | hirda->Init.Mode ;
  
  MODIFY_REG(hirda->Instance->CR1, IRDA_CR1_FIELDS, tmpreg);
  
  /*-------------------------- USART CR3 Configuration -----------------------*/
  MODIFY_REG(hirda->Instance->CR3, USART_CR3_IRLP, hirda->Init.PowerMode);
    
  /*-------------------------- USART GTPR Configuration ----------------------*/  
  MODIFY_REG(hirda->Instance->GTPR, USART_GTPR_PSC, hirda->Init.Prescaler);
  
  /*-------------------------- USART BRR Configuration -----------------------*/ 
  __HAL_IRDA_GETCLOCKSOURCE(hirda, clocksource);
  switch (clocksource)
  {
    case IRDA_CLOCKSOURCE_PCLK1: 
      hirda->Instance->BRR = (uint16_t)(HAL_RCC_GetPCLK1Freq() / hirda->Init.BaudRate);
      break;
    case IRDA_CLOCKSOURCE_PCLK2: 
      hirda->Instance->BRR = (uint16_t)(HAL_RCC_GetPCLK2Freq() / hirda->Init.BaudRate);
      break;
    case IRDA_CLOCKSOURCE_HSI: 
      hirda->Instance->BRR = (uint16_t)(HSI_VALUE / hirda->Init.BaudRate); 
      break; 
    case IRDA_CLOCKSOURCE_SYSCLK:  
      hirda->Instance->BRR = (uint16_t)(HAL_RCC_GetSysClockFreq() / hirda->Init.BaudRate);
      break;  
    case IRDA_CLOCKSOURCE_LSE:                
      hirda->Instance->BRR = (uint16_t)(LSE_VALUE / hirda->Init.BaudRate); 
      break;      
    case IRDA_CLOCKSOURCE_UNDEFINED:                
    default:                
      ret = HAL_ERROR; 
      break;              
  } 
  
  return ret;  
}
Exemplo n.º 10
0
mp_obj_t py_cpufreq_get_current_frequencies()
{
    mp_obj_t tuple[4] = {
        mp_obj_new_int(cpufreq_get_cpuclk()   / (1000000)),
        mp_obj_new_int(HAL_RCC_GetHCLKFreq()  / (1000000)),
        mp_obj_new_int(HAL_RCC_GetPCLK1Freq() / (1000000)),
        mp_obj_new_int(HAL_RCC_GetPCLK2Freq() / (1000000)),
    };
    return mp_obj_new_tuple(4, tuple);
}
Exemplo n.º 11
0
/**
  * @brief  Configures the SMARTCARD peripheral. 
  * @param  hsc: Pointer to a SMARTCARD_HandleTypeDef structure that contains
  *                the configuration information for the specified SMARTCARD module.
  * @retval None
  */
static void SMARTCARD_SetConfig(SMARTCARD_HandleTypeDef *hsc)
{
  /* Check the parameters */
  assert_param(IS_SMARTCARD_INSTANCE(hsc->Instance));
  assert_param(IS_SMARTCARD_POLARITY(hsc->Init.CLKPolarity));
  assert_param(IS_SMARTCARD_PHASE(hsc->Init.CLKPhase));
  assert_param(IS_SMARTCARD_LASTBIT(hsc->Init.CLKLastBit));
  assert_param(IS_SMARTCARD_BAUDRATE(hsc->Init.BaudRate));  
  assert_param(IS_SMARTCARD_WORD_LENGTH(hsc->Init.WordLength));
  assert_param(IS_SMARTCARD_STOPBITS(hsc->Init.StopBits));
  assert_param(IS_SMARTCARD_PARITY(hsc->Init.Parity));
  assert_param(IS_SMARTCARD_MODE(hsc->Init.Mode));
  assert_param(IS_SMARTCARD_NACK_STATE(hsc->Init.NACKState));

  /* The LBCL, CPOL and CPHA bits have to be selected when both the transmitter and the
     receiver are disabled (TE=RE=0) to ensure that the clock pulses function correctly. */
  CLEAR_BIT(hsc->Instance->CR1, (uint32_t)(USART_CR1_TE | USART_CR1_RE));
  
  /*-------------------------- SMARTCARD CR2 Configuration ------------------------*/
  /* Clear CLKEN, CPOL, CPHA and LBCL bits */
  /* Configure the SMARTCARD Clock, CPOL, CPHA and LastBit -----------------------*/
  /* Set CPOL bit according to hsc->Init.CLKPolarity value */
  /* Set CPHA bit according to hsc->Init.CLKPhase value */
  /* Set LBCL bit according to hsc->Init.CLKLastBit value */
  MODIFY_REG(hsc->Instance->CR2, 
             ((uint32_t)(USART_CR2_CPHA | USART_CR2_CPOL | USART_CR2_CLKEN | USART_CR2_LBCL)),
             ((uint32_t)(USART_CR2_CLKEN | hsc->Init.CLKPolarity | hsc->Init.CLKPhase| hsc->Init.CLKLastBit)) );
  
  /* Set Stop Bits: Set STOP[13:12] bits according to hsc->Init.StopBits value */
  MODIFY_REG(hsc->Instance->CR2, USART_CR2_STOP,(uint32_t)(hsc->Init.StopBits));

  /*-------------------------- SMARTCARD CR1 Configuration -----------------------*/
  /* Clear M, PCE, PS, TE and RE bits */
  /* Configure the SMARTCARD Word Length, Parity and mode: 
     Set the M bits according to hsc->Init.WordLength value 
     Set PCE and PS bits according to hsc->Init.Parity value
     Set TE and RE bits according to hsc->Init.Mode value */
  MODIFY_REG(hsc->Instance->CR1, 
             ((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE)),
             ((uint32_t)(hsc->Init.WordLength | hsc->Init.Parity | hsc->Init.Mode)) );

  /*-------------------------- USART CR3 Configuration -----------------------*/  
  /* Clear CTSE and RTSE bits */
  CLEAR_BIT(hsc->Instance->CR3, (USART_CR3_RTSE | USART_CR3_CTSE));

  /*-------------------------- USART BRR Configuration -----------------------*/
  if(hsc->Instance == USART1)
  {
    hsc->Instance->BRR = SMARTCARD_BRR(HAL_RCC_GetPCLK2Freq(), hsc->Init.BaudRate);
  }
  else
  {
    hsc->Instance->BRR = SMARTCARD_BRR(HAL_RCC_GetPCLK1Freq(), hsc->Init.BaudRate);
  }
}
Exemplo n.º 12
0
/**
 * print RCC freq information
 *
 * for example:
 *
 * SYSCLK_Frequency is 48000000HZ
 * PCLK_Frequency is 48000000HZ
 * HCLK_Frequency is 48000000HZ
 * CECCLK_Frequency is 32786HZ
 * ADCCLK_Frequency is 14000000HZ
 * USART1CLK_Frequency is 48000000HZ
 * I2C1CLK_Frequency is 8000000HZ
 * SystemCoreClock is 48000000HZ
 *
 */
void print_rcc_freq_info(void)
{
    rt_uint32_t clkval;

    clkval = HAL_RCC_GetSysClockFreq();//sysclk
    rt_kprintf("\nSYSCLK_Frequency is %dHZ", clkval);
    clkval = HAL_RCC_GetHCLKFreq();    //Hclk
    rt_kprintf("\nHCLK_Frequency is %dHZ", clkval);
    clkval = HAL_RCC_GetPCLK1Freq();   //pclk1
    rt_kprintf("\nPCLK1_Frequency is %dHZ", clkval);
    clkval = HAL_RCC_GetPCLK2Freq();   //pclk2
    rt_kprintf("\nPCLK2_Frequency is %dHZ", clkval);
}
Exemplo n.º 13
0
/**
  * @brief  return clock freq of an SPI instance
  * @param  spi_inst : SPI instance
  * @retval clock freq of the instance else SystemCoreClock
  */
uint32_t spi_getClkFreqInst(SPI_TypeDef * spi_inst)
{
  uint32_t spi_freq = SystemCoreClock;

#ifdef STM32F0xx
  UNUSED(spi_inst);
  /* SPIx source CLK is PCKL1 */
  spi_freq = HAL_RCC_GetPCLK1Freq();
#else
  if(spi_inst != NP) {
    /* Get source clock depending on SPI instance */
    switch ((uint32_t)spi_inst) {
#if defined(SPI1_BASE) || defined(SPI4_BASE) || defined(SPI5_BASE) || defined(SPI16_BASE)
      /* Some STM32's (eg. STM32F302x8) have no SPI1, but do have SPI2/3. */
#if defined SPI1_BASE
      case (uint32_t)SPI1:
#endif
#if defined SPI4_BASE
      case (uint32_t)SPI4:
#endif
#if defined SPI5_BASE
      case (uint32_t)SPI5:
#endif
#if defined SPI6_BASE
      case (uint32_t)SPI6:
#endif
        /* SPI1, SPI4, SPI5 and SPI6. Source CLK is PCKL2 */
        spi_freq = HAL_RCC_GetPCLK2Freq();
        break;
#endif  /* SPI[1456]_BASE */

#if defined(SPI2_BASE) || defined (SPI3_BASE)
#if defined SPI2_BASE
      case (uint32_t)SPI2:
#endif
#if defined SPI3_BASE
      case (uint32_t)SPI3:
#endif
        /* SPI_2 and SPI_3. Source CLK is PCKL1 */
        spi_freq = HAL_RCC_GetPCLK1Freq();
        break;
#endif
      default:
        printf("CLK: SPI instance not set");
        break;
    }
  }
#endif
  return spi_freq;
}
Exemplo n.º 14
0
void platform_init(void)
{
    printf("clocks:\n");
    printf("\tsysclk %u\n", HAL_RCC_GetSysClockFreq());
    printf("\thclk %u\n", HAL_RCC_GetHCLKFreq());
    printf("\tpclk1 %u\n", HAL_RCC_GetPCLK1Freq());
    printf("\tpclk2 %u\n", HAL_RCC_GetPCLK2Freq());

    printf("unique id: 0x%08x%08x%08x\n", stm32_unique_id[0], stm32_unique_id[1], stm32_unique_id[2]);

    stm32_timer_init();

    stm32_flash_init();

//    ITM_SendChar('2');
}
int timer_init(hacs_timer_t tim, hacs_timer_mode_t mode)
{
  uint32_t clock_freq;
  uint32_t presc;
  TIM_HandleTypeDef *htim = &tim_handles[tim];
  TIM_TypeDef *inst = hacs_tim_instances[tim];

  tim_overflow_cb[tim] = NULL;

  // First, find the appropriate prescaler to achieve microsecond resolution
  if (inst == TIM1 || inst == TIM10 || inst == TIM11) {
    // For stm32f411, these 3 timers are on the APB2 bus
    clock_freq = HAL_RCC_GetPCLK2Freq();
  } else {
    clock_freq = HAL_RCC_GetPCLK1Freq();
  }
  presc = clock_freq / TIMER_RESOLUTION_FREQ;

  // Setup timer base
  htim->Instance = inst;
  htim->Init.Prescaler = presc;
  htim->Init.CounterMode = TIM_COUNTERMODE_UP;
  htim->Init.Period = 0;
  htim->Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim->Init.RepetitionCounter = 0;
  HAL_TIM_Base_Init(htim);

  if (mode == HACS_TIMER_MODE_PWM) {
    TIM_OC_InitTypeDef sConfigOC;

    sConfigOC.OCMode = TIM_OCMODE_PWM1;
    sConfigOC.Pulse = 0;
    sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
    sConfigOC.OCNPolarity = TIM_OCNPOLARITY_HIGH;
    sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
    sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET;
    sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET;

    // NOTE: Assume there are 4 PWM channels on each timer, and that all of them are used.
    HAL_TIM_PWM_ConfigChannel(htim, &sConfigOC, TIM_CHANNEL_1);
    HAL_TIM_PWM_ConfigChannel(htim, &sConfigOC, TIM_CHANNEL_2);
    HAL_TIM_PWM_ConfigChannel(htim, &sConfigOC, TIM_CHANNEL_3);
    HAL_TIM_PWM_ConfigChannel(htim, &sConfigOC, TIM_CHANNEL_4);
  }

  return HACS_NO_ERROR;
}
Exemplo n.º 16
0
/**
  * @brief  This function configures the TIM1 as a time base source. 
  *         The time source is configured  to have 1ms time base with a dedicated 
  *         Tick interrupt priority. 
  * @note   This function is called  automatically at the beginning of program after
  *         reset by HAL_Init() or at any time when clock is configured, by HAL_RCC_ClockConfig(). 
  * @param  TickPriority: Tick interrupt priorty.
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority)
{
  RCC_ClkInitTypeDef    clkconfig;
  uint32_t              uwTimclock = 0;
  uint32_t              uwPrescalerValue = 0;
  uint32_t              pFLatency;
  
  /*Configure the TIM1 IRQ priority */
  HAL_NVIC_SetPriority(TIM1_UP_TIM16_IRQn, TickPriority ,0); 
  
  /* Enable the TIM1 global Interrupt */
  HAL_NVIC_EnableIRQ(TIM1_UP_TIM16_IRQn); 
  
  /* Enable TIM1 clock */
  __HAL_RCC_TIM1_CLK_ENABLE();
  
  /* Get clock configuration */
  HAL_RCC_GetClockConfig(&clkconfig, &pFLatency);
  
  /* Compute TIM1 clock */
  uwTimclock = HAL_RCC_GetPCLK2Freq();
   
  /* Compute the prescaler value to have TIM1 counter clock equal to 1MHz */
  uwPrescalerValue = (uint32_t) ((uwTimclock / 1000000) - 1);
  
  /* Initialize TIM1 */
  htim1.Instance = TIM1;
  
  /* Initialize TIMx peripheral as follow:
  + Period = [(TIM1CLK/1000) - 1]. to have a (1/1000) s time base.
  + Prescaler = (uwTimclock/1000000 - 1) to have a 1MHz counter clock.
  + ClockDivision = 0
  + Counter direction = Up
  */
  htim1.Init.Period = (1000000 / 1000) - 1;
  htim1.Init.Prescaler = uwPrescalerValue;
  htim1.Init.ClockDivision = 0;
  htim1.Init.CounterMode = TIM_COUNTERMODE_UP;
  if(HAL_TIM_Base_Init(&htim1) == HAL_OK)
  {
    /* Start the TIM time Base generation in interrupt mode */
    return HAL_TIM_Base_Start_IT(&htim1);
  }
  
  /* Return function status */
  return HAL_ERROR;
}
Exemplo n.º 17
0
/**
  * @brief  Configures the IRDA peripheral. 
  * @param  hirda: pointer to a IRDA_HandleTypeDef structure that contains
  *                the configuration information for the specified IRDA module.
  * @retval None
  */
static void IRDA_SetConfig(IRDA_HandleTypeDef *hirda)
{
  uint32_t tmpreg = 0x00;
  
  /* Check the parameters */
  assert_param(IS_IRDA_INSTANCE(hirda->Instance));
  assert_param(IS_IRDA_BAUDRATE(hirda->Init.BaudRate));  
  assert_param(IS_IRDA_WORD_LENGTH(hirda->Init.WordLength));
  assert_param(IS_IRDA_PARITY(hirda->Init.Parity));
  assert_param(IS_IRDA_MODE(hirda->Init.Mode));
  
  /*-------------------------- IRDA CR2 Configuration ------------------------*/
  /* Clear STOP[13:12] bits */
  hirda->Instance->CR2 &= (uint32_t)~((uint32_t)USART_CR2_STOP);
  
  /*-------------------------- USART CR1 Configuration -----------------------*/
  tmpreg = hirda->Instance->CR1;
  
  /* Clear M, PCE, PS, TE and RE bits */
  tmpreg &= (uint32_t)~((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | \
    USART_CR1_RE));
  
  /* Configure the USART Word Length, Parity and mode: 
     Set the M bits according to hirda->Init.WordLength value 
     Set PCE and PS bits according to hirda->Init.Parity value
     Set TE and RE bits according to hirda->Init.Mode value */
  tmpreg |= (uint32_t)hirda->Init.WordLength | hirda->Init.Parity | hirda->Init.Mode;
  
  /* Write to USART CR1 */
  hirda->Instance->CR1 = (uint32_t)tmpreg;
  
  /*-------------------------- USART CR3 Configuration -----------------------*/  
  /* Clear CTSE and RTSE bits */
  hirda->Instance->CR3 &= (uint32_t)~((uint32_t)(USART_CR3_RTSE | USART_CR3_CTSE));
  
  /*-------------------------- USART BRR Configuration -----------------------*/
  if((hirda->Instance == USART1) || (hirda->Instance == USART6))
  {
    hirda->Instance->BRR = __IRDA_BRR(HAL_RCC_GetPCLK2Freq(), hirda->Init.BaudRate);
  }
  else
  {
    hirda->Instance->BRR = __IRDA_BRR(HAL_RCC_GetPCLK1Freq(), hirda->Init.BaudRate);
  }
}
Exemplo n.º 18
0
static int
stm32_spi_resolve_prescaler(uint8_t spi_num, uint32_t baudrate, uint32_t *prescaler)
{
    uint32_t candidate_br;
    uint32_t apbfreq;
    int i;

    /* SPIx {1,4,5,6} use PCLK2 on the STM32F4/F7, otherwise use PCKL1.
     * The numbers in the switch below are offset by 1, because the HALs index
     * SPI ports from 0.
     */
    switch (spi_num) {
    case 0:
    case 3:
    case 4:
    case 5:
        apbfreq = HAL_RCC_GetPCLK2Freq();
        break;
    default:
        apbfreq = HAL_RCC_GetPCLK1Freq();
        break;
    }

    if (baudrate == 0) {
        *prescaler = 0;
        return 0;
    }

    /* Calculate best-fit prescaler: divide the clock by each subsequent
     * prescaler until we reach the highest prescaler that generates at
     * _most_ the baudrate.
     */
    *prescaler = SPI_BAUDRATEPRESCALER_256;
    for (i = 0; i < 8; i++) {
        candidate_br = apbfreq >> (i + 1);
        if (candidate_br <= baudrate) {
            *prescaler = i << SPI_CR1_BR_Pos;
            break;
        }
    }

    return (0);
}
uint16_t TM_SPI_GetPrescalerFromMaxFrequency(SPI_TypeDef* SPIx, uint32_t MAX_SPI_Frequency) {
	uint32_t APB_Frequency;
	uint8_t i;
	
	/* Prevent false input */
	if (MAX_SPI_Frequency == 0) {
		return SPI_BAUDRATEPRESCALER_256;
	}
	
	/* Calculate max SPI clock */
	if (0
#ifdef SPI1	
		|| SPIx == SPI1
#endif
#ifdef SPI4
		|| SPIx == SPI4
#endif
#ifdef SPI5
		|| SPIx == SPI5
#endif
#ifdef SPI6
		|| SPIx == SPI6
#endif
	) {
		APB_Frequency = HAL_RCC_GetPCLK2Freq();
	} else {
		APB_Frequency = HAL_RCC_GetPCLK1Freq();
	}
	
	/* Calculate prescaler value */
	/* Bits 5:3 in CR1 SPI registers are prescalers */
	/* 000 = 2, 001 = 4, 002 = 8, ..., 111 = 256 */
	for (i = 0; i < 8; i++) {
		if (APB_Frequency / (1 << (i + 1)) <= MAX_SPI_Frequency) {
			/* Bits for BP are 5:3 in CR1 register */
			return (i << 3);
		}
	}
	
	/* Use max prescaler possible */
	return SPI_BAUDRATEPRESCALER_256;
}
Exemplo n.º 20
0
STATIC mp_obj_t pyb_timer_init_helper(pyb_timer_obj_t *self, mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
    // parse args
    mp_arg_val_t vals[PYB_TIMER_INIT_NUM_ARGS];
    mp_arg_parse_all(n_args, args, kw_args, PYB_TIMER_INIT_NUM_ARGS, pyb_timer_init_args, vals);

    // set the TIM configuration values
    TIM_Base_InitTypeDef *init = &self->tim.Init;

    if (vals[0].u_int != 0xffffffff) {
        // set prescaler and period from frequency

        if (vals[0].u_int == 0) {
            nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "can't have 0 frequency"));
        }

        // work out TIM's clock source
        uint tim_clock;
        if (self->tim_id == 1 || (8 <= self->tim_id && self->tim_id <= 11)) {
            // TIM{1,8,9,10,11} are on APB2
            tim_clock = HAL_RCC_GetPCLK2Freq();
        } else {
            // TIM{2,3,4,5,6,7,12,13,14} are on APB1
            tim_clock = HAL_RCC_GetPCLK1Freq();
        }

        // Compute the prescaler value so TIM triggers at freq-Hz
        // On STM32F405/407/415/417 there are 2 cases for how the clock freq is set.
        // If the APB prescaler is 1, then the timer clock is equal to its respective
        // APB clock.  Otherwise (APB prescaler > 1) the timer clock is twice its
        // respective APB clock.  See DM00031020 Rev 4, page 115.
        uint32_t period = MAX(1, 2 * tim_clock / vals[0].u_int);
        uint32_t prescaler = 1;
        while (period > TIMER_CNT_MASK(self)) {
            period >>= 1;
            prescaler <<= 1;
        }
        init->Prescaler = prescaler - 1;
        init->Period = period - 1;
    } else if (vals[1].u_int != 0xffffffff && vals[2].u_int != 0xffffffff) {
Exemplo n.º 21
0
/** @brief: set registers acc to info in huart
 *  @details: used in HAL_UART3Debug_Init, private
 ****************************************************************/
static void MyUARTSetConfig(UART_HandleTypeDef * huart) {
	uint32_t tmpreg = 0x00;

	/* Check the parameters */
	assert_param(IS_UART_BAUDRATE(huart->Init.BaudRate));
	assert_param(IS_UART_STOPBITS(huart->Init.StopBits));
	assert_param(IS_UART_PARITY(huart->Init.Parity));
	assert_param(IS_UART_MODE(huart->Init.Mode));

	/*------- UART-associated USART registers setting : CR2 Configuration ------*/
	/* Configure the UART Stop Bits: Set STOP[13:12] bits according
	 * to huart->Init.StopBits value */
	MODIFY_REG(huart->Instance->CR2, USART_CR2_STOP, huart->Init.StopBits);

	/*------- UART-associated USART registers setting : CR1 Configuration ------*/
	/* Configure the UART Word Length, Parity and mode:
	 Set the M bits according to huart->Init.WordLength value
	 Set PCE and PS bits according to huart->Init.Parity value
	 Set TE and RE bits according to huart->Init.Mode value */
	tmpreg = (uint32_t) huart->Init.WordLength | huart->Init.Parity
			| huart->Init.Mode;
	MODIFY_REG(huart->Instance->CR1,
			(uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE),
			tmpreg);

	/*------- UART-associated USART registers setting : CR3 Configuration ------*/
	/* Configure the UART HFC: Set CTSE and RTSE bits according to huart->Init.HwFlowCtl value */
	MODIFY_REG(huart->Instance->CR3, (USART_CR3_RTSE | USART_CR3_CTSE),
			huart->Init.HwFlowCtl);

	/*------- UART-associated USART registers setting : BRR Configuration ------*/
	if ((huart->Instance == USART1)) {
		huart->Instance->BRR = UART_BRR_SAMPLING16(HAL_RCC_GetPCLK2Freq(),
				huart->Init.BaudRate);
	} else {
		huart->Instance->BRR = UART_BRR_SAMPLING16(HAL_RCC_GetPCLK1Freq(),
				huart->Init.BaudRate);
	}
}
Exemplo n.º 22
0
static void extclk_config(int frequency)
{
    /* TCLK (PCLK2 * 2) */
    int tclk  = HAL_RCC_GetPCLK2Freq() * 2;

    /* SYSCLK/TCLK = No prescaler */
    int prescaler = (uint16_t) (HAL_RCC_GetSysClockFreq()/ tclk) - 1;

    /* Period should be even */
    int period = (tclk / frequency)-1;

    /* Timer base configuration */
    TIMHandle.Instance          = DCMI_TIM;
    TIMHandle.Init.Period       = period;
    TIMHandle.Init.Prescaler    = prescaler;
    TIMHandle.Init.ClockDivision = 0;
    TIMHandle.Init.CounterMode   = TIM_COUNTERMODE_UP;

    /* Timer channel configuration */
    TIM_OC_InitTypeDef TIMOCHandle;
    TIMOCHandle.Pulse       = period/2;
    TIMOCHandle.OCMode      = TIM_OCMODE_PWM1;
    TIMOCHandle.OCPolarity  = TIM_OCPOLARITY_HIGH;
    TIMOCHandle.OCFastMode  = TIM_OCFAST_DISABLE;
    TIMOCHandle.OCIdleState = TIM_OCIDLESTATE_RESET;
    if (HAL_TIM_PWM_Init(&TIMHandle) != HAL_OK) {
        /* Initialization Error */
        BREAK();
    }

    if (HAL_TIM_PWM_ConfigChannel(&TIMHandle, &TIMOCHandle, DCMI_TIM_CHANNEL) != HAL_OK) {
        BREAK();
    }

    if (HAL_TIM_PWM_Start(&TIMHandle, DCMI_TIM_CHANNEL) != HAL_OK) {
        BREAK();
    }
}
Exemplo n.º 23
0
/*
 * Only the frequency is managed in the family specific part
 * the rest of SPI management is common to all STM32 families
 */
int spi_get_clock_freq(spi_t *obj) {
    struct spi_s *spiobj = SPI_S(obj);
    int spi_hz = 0;

    /* Get source clock depending on SPI instance */
    switch ((int)spiobj->spi) {
    case SPI_1:
        /* SPI_1. Source CLK is PCKL2 */
        spi_hz = HAL_RCC_GetPCLK2Freq();
        break;
#if defined(SPI2_BASE)
    case SPI_2:
#endif
    case SPI_3:
        /* SPI_2, SPI_3. Source CLK is PCKL1 */
        spi_hz = HAL_RCC_GetPCLK1Freq();
        break;
    default:
        error("CLK: SPI instance not set");
        break;
    }
    return spi_hz;
}
Exemplo n.º 24
0
/**
  * @brief  Conversion complete callback in non blocking mode 
  * @param  htim : hadc handle
  * @retval None
  */
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
  if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_2)
  {
    if(uhCaptureIndex == 0)
    {
      /* Get the 1st Input Capture value */
      uwIC2Value1 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_2);
      uhCaptureIndex = 1;
    }
    else if(uhCaptureIndex == 1)
    {
      /* Get the 2nd Input Capture value */
      uwIC2Value2 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_2); 
      
      /* Capture computation */
      if (uwIC2Value2 > uwIC2Value1)
      {
        uwDiffCapture = (uwIC2Value2 - uwIC2Value1); 
      }
      else if (uwIC2Value2 < uwIC2Value1)
      {
        uwDiffCapture = ((0xFFFF - uwIC2Value1) + uwIC2Value2); 
      }
      else
      {
        /* If capture values are equal, we have reached the limit of frequency
           measures */
        Error_Handler();
      }
      /* Frequency computation: for this example TIMx (TIM1) is clocked by
         APB2Clk */      
      uwFrequency = HAL_RCC_GetPCLK2Freq() / uwDiffCapture;
      uhCaptureIndex = 0;
    }
  }
}
Exemplo n.º 25
0
STATIC mp_obj_t pyb_timer_init_helper(pyb_timer_obj_t *self, uint n_args, const mp_obj_t *args, mp_map_t *kw_args) {
    // parse args
    mp_arg_val_t vals[PYB_TIMER_INIT_NUM_ARGS];
    mp_arg_parse_all(n_args, args, kw_args, PYB_TIMER_INIT_NUM_ARGS, pyb_timer_init_args, vals);

    // set the TIM configuration values
    TIM_Base_InitTypeDef *init = &self->tim.Init;

    if (vals[0].u_int != 0xffffffff) {
        // set prescaler and period from frequency

        if (vals[0].u_int == 0) {
            nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "can't have 0 frequency"));
        }

        // work out TIM's clock source
        uint tim_clock;
        if (self->tim_id == 1 || (8 <= self->tim_id && self->tim_id <= 11)) {
            // TIM{1,8,9,10,11} are on APB2
            tim_clock = HAL_RCC_GetPCLK2Freq();
        } else {
            // TIM{2,3,4,5,6,7,12,13,14} are on APB1
            tim_clock = HAL_RCC_GetPCLK1Freq();
        }

        // compute the prescaler value so TIM triggers at freq-Hz
        // dpgeorge: I don't understand why we need to multiply tim_clock by 2
        uint32_t period = MAX(1, 2 * tim_clock / vals[0].u_int);
        uint32_t prescaler = 1;
        while (period > 0xffff) {
            period >>= 1;
            prescaler <<= 1;
        }
        init->Prescaler = prescaler - 1;
        init->Period = period - 1;
    } else if (vals[1].u_int != 0xffffffff && vals[2].u_int != 0xffffffff) {
static uint32_t calc_prescaler_from_freq(hacs_spi_t bus, uint32_t freq)
{
  SPI_TypeDef* spi = hacs_spi_instances[bus];
  uint32_t pclk;
  uint32_t ratio;
  uint8_t presc = 0;

  if (spi == SPI2 || spi == SPI3) { // on APB1
    pclk = HAL_RCC_GetPCLK1Freq();
  } else { // on APB2
    pclk = HAL_RCC_GetPCLK2Freq();
  }

  ratio = pclk / freq;

  do {
    presc++;
    ratio = ratio >> 1;
  } while (ratio > 0);

  if (presc > 8) presc = 8;

  return (presc - 1) & 0x7;
}
Exemplo n.º 27
0
/// \function info([dump_alloc_table])
/// Print out lots of information about the board.
STATIC mp_obj_t pyb_info(uint n_args, const mp_obj_t *args) {
    // get and print unique id; 96 bits
    {
        byte *id = (byte*)0x1fff7a10;
        printf("ID=%02x%02x%02x%02x:%02x%02x%02x%02x:%02x%02x%02x%02x\n", id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7], id[8], id[9], id[10], id[11]);
    }

    // get and print clock speeds
    // SYSCLK=168MHz, HCLK=168MHz, PCLK1=42MHz, PCLK2=84MHz
    {
        printf("S=%lu\nH=%lu\nP1=%lu\nP2=%lu\n", 
               HAL_RCC_GetSysClockFreq(),
               HAL_RCC_GetHCLKFreq(),
               HAL_RCC_GetPCLK1Freq(),
               HAL_RCC_GetPCLK2Freq());
    }

    // to print info about memory
    {
        printf("_etext=%p\n", &_etext);
        printf("_sidata=%p\n", &_sidata);
        printf("_sdata=%p\n", &_sdata);
        printf("_edata=%p\n", &_edata);
        printf("_sbss=%p\n", &_sbss);
        printf("_ebss=%p\n", &_ebss);
        printf("_estack=%p\n", &_estack);
        printf("_ram_start=%p\n", &_ram_start);
        printf("_heap_start=%p\n", &_heap_start);
        printf("_heap_end=%p\n", &_heap_end);
        printf("_ram_end=%p\n", &_ram_end);
    }

    // qstr info
    {
        uint n_pool, n_qstr, n_str_data_bytes, n_total_bytes;
        qstr_pool_info(&n_pool, &n_qstr, &n_str_data_bytes, &n_total_bytes);
        printf("qstr:\n  n_pool=%u\n  n_qstr=%u\n  n_str_data_bytes=%u\n  n_total_bytes=%u\n", n_pool, n_qstr, n_str_data_bytes, n_total_bytes);
    }

    // GC info
    {
        gc_info_t info;
        gc_info(&info);
        printf("GC:\n");
        printf("  " UINT_FMT " total\n", info.total);
        printf("  " UINT_FMT " : " UINT_FMT "\n", info.used, info.free);
        printf("  1=" UINT_FMT " 2=" UINT_FMT " m=" UINT_FMT "\n", info.num_1block, info.num_2block, info.max_block);
    }

    // free space on flash
    {
        DWORD nclst;
        FATFS *fatfs;
        f_getfree("0:", &nclst, &fatfs);
        printf("LFS free: %u bytes\n", (uint)(nclst * fatfs->csize * 512));
    }

    if (n_args == 1) {
        // arg given means dump gc allocation table
        gc_dump_alloc_table();
    }

    return mp_const_none;
}
Exemplo n.º 28
0
uint8_t TIM_Reconfig(uint32_t samplingFreq,TIM_HandleTypeDef* htim_base,uint32_t* realFreq){
	
	int32_t clkDiv;
	uint16_t prescaler;
	uint16_t autoReloadReg;
	uint32_t errMinRatio = 0;
	uint8_t result = UNKNOW_ERROR;
	


	clkDiv = ((2*HAL_RCC_GetPCLK2Freq() / samplingFreq)+1)/2; //to minimize rounding error
	
	if(clkDiv == 0){ //error
		result = GEN_FREQ_MISMATCH;
	}else if(clkDiv <= 0x0FFFF){ //Sampling frequency is high enough so no prescaler needed
		prescaler = 0;
		autoReloadReg = clkDiv - 1;
		result = 0;
	}else{	// finding prescaler and autoReload value
		uint32_t errVal = 0xFFFFFFFF;
		uint32_t errMin = 0xFFFFFFFF;
		uint16_t ratio = clkDiv>>16; 
		uint16_t div;
		
		while(errVal != 0){
			ratio++;
			div = clkDiv/ratio;
			errVal = clkDiv - (div*ratio);

			if(errVal < errMin){
				errMin = errVal;
				errMinRatio = ratio;
			}
		
			if(ratio == 0xFFFF){ //exact combination wasnt found. we use best found
				div = clkDiv/errMinRatio;
				ratio = errMinRatio;
				break;
			}			
		}

		if(ratio > div){
			prescaler = div - 1;
			autoReloadReg = ratio - 1;		
		}else{
			prescaler = ratio - 1;
			autoReloadReg = div - 1;
		}	

		if(errVal){
			result = GEN_FREQ_IS_INACCURATE;
		}else{
			result = 0;
		}
	}
	
	*realFreq=HAL_RCC_GetPCLK2Freq()/((prescaler+1)*(autoReloadReg+1));
  htim_base->Init.Prescaler = prescaler;
  htim_base->Init.Period = autoReloadReg;
  HAL_TIM_Base_Init(htim_base);
	return result;

}
Exemplo n.º 29
0
bool UART_config(uart *uart, u32_t baud, UART_databits databits,
    UART_stopbits stopbits, UART_parity parity, UART_flowcontrol flowcontrol,
    bool activate) {
  UART_HW(uart)->CR1 &= ~USART_CR1_UE; // disable uart

  if (activate) {
    u32_t sdatabits = 0;
    u32_t sstopbits = 0;
    u32_t sparity = 0;
    u32_t sflowcontrol = 0;
    uint16_t usartdiv                   = 0x0000;

    UART_ClockSourceTypeDef clocksource = UART_CLOCKSOURCE_UNDEFINED;
    switch (databits) {
    case UART_DATABITS_8: sdatabits = USART_WORDLENGTH_8B; break;
    case UART_DATABITS_9: sdatabits = USART_WORDLENGTH_9B; break;
    default: return FALSE;
    }
    switch (stopbits) {
    case UART_STOPBITS_0_5: sstopbits = USART_STOPBITS_1; break;
    case UART_STOPBITS_1: sstopbits = USART_STOPBITS_1; break;
    case UART_STOPBITS_1_5: sstopbits = USART_STOPBITS_1_5; break;
    case UART_STOPBITS_2: sstopbits = USART_STOPBITS_2; break;
    default: return FALSE;
    }
    switch (parity) {
    case UART_PARITY_NONE: sparity = USART_PARITY_NONE; break;
    case UART_PARITY_EVEN: sparity = USART_PARITY_EVEN; break;
    case UART_PARITY_ODD: sparity = USART_PARITY_ODD; break;
    default: return FALSE;
    }
    switch (flowcontrol) {
    case UART_FLOWCONTROL_NONE: sflowcontrol = UART_HWCONTROL_NONE; break;
    case UART_FLOWCONTROL_CTS: sflowcontrol = UART_HWCONTROL_CTS; break;
    case UART_FLOWCONTROL_RTS: sflowcontrol = UART_HWCONTROL_RTS; break;
    case UART_FLOWCONTROL_RTS_CTS: sflowcontrol = UART_HWCONTROL_RTS_CTS; break;
    default: return FALSE;
    }
    UART_HW(uart)->CR1 = 0;
    UART_HW(uart)->CR2 = 0;
    UART_HW(uart)->CR3 = 0;
    /*-------------------------- USART CR1 Configuration -----------------------*/
    MODIFY_REG(UART_HW(uart)->CR1, USART_CR1_FIELDS,
        sdatabits | sparity | USART_CR1_OVER8 | USART_CR1_RE | USART_CR1_TE);

    /*---------------------------- USART CR2 Configuration ---------------------*/
    MODIFY_REG(UART_HW(uart)->CR2, USART_CR2_STOP,
        sstopbits);

    UART_HW(uart)->CR2 &= ~USART_CR2_LINEN;

    /*-------------------------- USART CR3 Configuration -----------------------*/
    MODIFY_REG(UART_HW(uart)->CR3, (USART_CR3_RTSE | USART_CR3_CTSE | USART_CR3_ONEBIT),
        sflowcontrol);

    _UART_GETCLOCKSOURCE(UART_HW(uart), clocksource);

    switch (clocksource)
    {
    case UART_CLOCKSOURCE_PCLK1:
        usartdiv = (uint16_t)(_UART_DIV_SAMPLING8(HAL_RCC_GetPCLK1Freq(), baud));
      break;
    case UART_CLOCKSOURCE_PCLK2:
        usartdiv = (uint16_t)(_UART_DIV_SAMPLING8(HAL_RCC_GetPCLK2Freq(), baud));
      break;
    case UART_CLOCKSOURCE_HSI:
        usartdiv = (uint16_t)(_UART_DIV_SAMPLING8(HSI_VALUE, baud));
      break;
    case UART_CLOCKSOURCE_SYSCLK:
        usartdiv = (uint16_t)(_UART_DIV_SAMPLING8(HAL_RCC_GetSysClockFreq(), baud));
      break;
    case UART_CLOCKSOURCE_LSE:
        usartdiv = (uint16_t)(_UART_DIV_SAMPLING8(LSE_VALUE, baud));
      break;
      case UART_CLOCKSOURCE_UNDEFINED:
    default:
        return FALSE;
      break;
    }

    u32_t brrtemp = usartdiv & 0xFFF0;
    brrtemp |= (uint16_t)((usartdiv & (uint16_t)0x000F) >> 1U);
    UART_HW(uart)->BRR = brrtemp;
    // enable usart interrupts
    _UART_ENABLE_IT(UART_HW(uart), USART_IT_TC);
    _UART_ENABLE_IT(UART_HW(uart), USART_IT_TXE);
    _UART_ENABLE_IT(UART_HW(uart), USART_IT_RXNE);
    UART_HW(uart)->CR1 |= USART_CR1_UE; // enable uart
  } else {
Exemplo n.º 30
0
/**
  * @brief Configure the SMARTCARD associated USART peripheral 
  * @param hsc: SMARTCARD handle
  * @retval None
  */
static void SMARTCARD_SetConfig(SMARTCARD_HandleTypeDef *hsc)
{
  uint32_t tmpreg = 0x00000000;
  uint32_t clocksource = 0x00000000;
  
  /* Check the parameters */ 
  assert_param(IS_SMARTCARD_INSTANCE(hsc->Instance));
  assert_param(IS_SMARTCARD_BAUDRATE(hsc->Init.BaudRate)); 
  assert_param(IS_SMARTCARD_WORD_LENGTH(hsc->Init.WordLength));  
  assert_param(IS_SMARTCARD_STOPBITS(hsc->Init.StopBits));   
  assert_param(IS_SMARTCARD_PARITY(hsc->Init.Parity));
  assert_param(IS_SMARTCARD_MODE(hsc->Init.Mode));
  assert_param(IS_SMARTCARD_POLARITY(hsc->Init.CLKPolarity));
  assert_param(IS_SMARTCARD_PHASE(hsc->Init.CLKPhase));
  assert_param(IS_SMARTCARD_LASTBIT(hsc->Init.CLKLastBit));    
  assert_param(IS_SMARTCARD_ONE_BIT_SAMPLE(hsc->Init.OneBitSampling));
  assert_param(IS_SMARTCARD_NACK(hsc->Init.NACKState));
  assert_param(IS_SMARTCARD_TIMEOUT(hsc->Init.TimeOutEnable));
  assert_param(IS_SMARTCARD_AUTORETRY_COUNT(hsc->Init.AutoRetryCount)); 

  /*-------------------------- USART CR1 Configuration -----------------------*/
  /* In SmartCard mode, M and PCE are forced to 1 (8 bits + parity).
   * Oversampling is forced to 16 (OVER8 = 0).
   * Configure the Parity and Mode: 
   *  set PS bit according to hsc->Init.Parity value
   *  set TE and RE bits according to hsc->Init.Mode value */
  tmpreg = (uint32_t) hsc->Init.Parity | hsc->Init.Mode;
  /* in case of TX-only mode, if NACK is enabled, the USART must be able to monitor 
     the bidirectional line to detect a NACK signal in case of parity error. 
     Therefore, the receiver block must be enabled as well (RE bit must be set). */
  if((hsc->Init.Mode == SMARTCARD_MODE_TX) && (hsc->Init.NACKState == SMARTCARD_NACK_ENABLE))
  {
    tmpreg |= USART_CR1_RE;   
  }
  tmpreg |= (uint32_t) hsc->Init.WordLength;
  MODIFY_REG(hsc->Instance->CR1, USART_CR1_FIELDS, tmpreg);

  /*-------------------------- USART CR2 Configuration -----------------------*/
  /* Stop bits are forced to 1.5 (STOP = 11) */
  tmpreg = hsc->Init.StopBits;
  /* Synchronous mode is activated by default */
  tmpreg |= (uint32_t) USART_CR2_CLKEN | hsc->Init.CLKPolarity; 
  tmpreg |= (uint32_t) hsc->Init.CLKPhase | hsc->Init.CLKLastBit;
  tmpreg |= (uint32_t) hsc->Init.TimeOutEnable;
  MODIFY_REG(hsc->Instance->CR2, USART_CR2_FIELDS, tmpreg); 
    
  /*-------------------------- USART CR3 Configuration -----------------------*/
  /* Configure 
   * - one-bit sampling method versus three samples' majority rule 
   *   according to hsc->Init.OneBitSampling 
   * - NACK transmission in case of parity error according 
   *   to hsc->Init.NACKEnable   
   * - autoretry counter according to hsc->Init.AutoRetryCount     */
  tmpreg =  (uint32_t) hsc->Init.OneBitSampling | hsc->Init.NACKState;
  tmpreg |= (uint32_t) (hsc->Init.AutoRetryCount << SMARTCARD_CR3_SCARCNT_LSB_POS);
  MODIFY_REG(hsc->Instance-> CR3,USART_CR3_FIELDS, tmpreg);
  
  /*-------------------------- USART GTPR Configuration ----------------------*/
  tmpreg = (uint32_t) (hsc->Init.Prescaler | (hsc->Init.GuardTime << SMARTCARD_GTPR_GT_LSB_POS));
  MODIFY_REG(hsc->Instance->GTPR, (uint32_t)(USART_GTPR_GT|USART_GTPR_PSC), tmpreg); 
  
  /*-------------------------- USART RTOR Configuration ----------------------*/ 
  tmpreg =   (uint32_t) (hsc->Init.BlockLength << SMARTCARD_RTOR_BLEN_LSB_POS);
  if(hsc->Init.TimeOutEnable == SMARTCARD_TIMEOUT_ENABLE)
  {
    assert_param(IS_SMARTCARD_TIMEOUT_VALUE(hsc->Init.TimeOutValue));
    tmpreg |=  (uint32_t) hsc->Init.TimeOutValue;
  }
  MODIFY_REG(hsc->Instance->RTOR, (USART_RTOR_RTO|USART_RTOR_BLEN), tmpreg);
  
  /*-------------------------- USART BRR Configuration -----------------------*/
  SMARTCARD_GETCLOCKSOURCE(hsc, clocksource);
  switch (clocksource)
  {
  case SMARTCARD_CLOCKSOURCE_PCLK1: 
    hsc->Instance->BRR = (uint16_t)(HAL_RCC_GetPCLK1Freq() / hsc->Init.BaudRate);
    break;
  case SMARTCARD_CLOCKSOURCE_PCLK2: 
    hsc->Instance->BRR = (uint16_t)(HAL_RCC_GetPCLK2Freq() / hsc->Init.BaudRate);
    break;
  case SMARTCARD_CLOCKSOURCE_HSI: 
    hsc->Instance->BRR = (uint16_t)(HSI_VALUE / hsc->Init.BaudRate); 
    break; 
  case SMARTCARD_CLOCKSOURCE_SYSCLK:  
    hsc->Instance->BRR = (uint16_t)(HAL_RCC_GetSysClockFreq() / hsc->Init.BaudRate);
    break;  
  case SMARTCARD_CLOCKSOURCE_LSE:                
    hsc->Instance->BRR = (uint16_t)(LSE_VALUE / hsc->Init.BaudRate); 
    break;
  default:
    break;
  } 
}