Skip to content

Instantly share code, notes, and snippets.

@rixth
Last active August 29, 2015 14:25
Show Gist options
  • Save rixth/2acb275697169a6e1d0b to your computer and use it in GitHub Desktop.
Save rixth/2acb275697169a6e1d0b to your computer and use it in GitHub Desktop.
// Enable GPIOB & TIM3 clocks
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_TIM3_CLK_ENABLE();
// Set up GPIOB1 (timer 3, channel 4) in alternate function (AF) mode
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_HIGH;
GPIO_InitStruct.Pin = GPIO_PIN_1;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
// Set up the counter itself.
TIM_Base_InitTypeDef TIM_BaseStruct;
TIM_HandleTypeDef TIM_HandleStruct;
TIM_HandleStruct.Instance = TIM3;
// No prescaler (PSC), so the count (CNT) will count up 64 million times per second
TIM_BaseStruct.Prescaler = 0;
TIM_BaseStruct.CounterMode = TIM_COUNTERMODE_UP;
// When the counter hits the Period value, it will reset back to 0.
// This is the ARR register. In this case, the clock is 64mhz so:
// 64,000,000 / 842 / 2 = 38,005hz
// The divide by two is because it takes two toggles to create one wave
TIM_BaseStruct.Period = 842;
TIM_HandleStruct.Init = TIM_BaseStruct;
TIM_HandleStruct.Channel = HAL_TIM_ACTIVE_CHANNEL_4;
// Initialize the timer hardware in output compare mode
HAL_TIM_OC_Init(&TIM_HandleStruct);
// Set the parameters for output compare
TIM_OC_InitTypeDef TIM_OCStruct;
// Toggle the associated pin when CNT >= CCR
TIM_OCStruct.OCMode = TIM_OCMODE_TOGGLE;
// This is the counter value when the the channel will be toggled
// For this simple case, the value here does not matter.
TIM_OCStruct.Pulse = 0;
// Configure the channel.
HAL_TIM_OC_ConfigChannel(&TIM_HandleStruct, &TIM_OCStruct, TIM_CHANNEL_4);
// Start the timer comparing
HAL_TIM_OC_Start(&TIM_HandleStruct, TIM_CHANNEL_4);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment