diff --git a/main.c b/main.c index 30a3680..29a00a3 100644 --- a/main.c +++ b/main.c @@ -1,4 +1,5 @@ #include "system.h" +#include "timer.h" #include "uart.h" #include #include @@ -15,7 +16,14 @@ static void gpio_setup(void) { /* Setup GPIO6 and 7 (in GPIO port A) for LED use. */ gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO12); + + /* + * Set TIM1 channel output pins to + * 'output alternate function push-pull'. + */ + gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, GPIO_TIM2_CH1_ETR); } + static void clock_setup(void) { rcc_clock_setup_pll(&rcc_hse_configs[RCC_CLOCK_HSE8_72MHZ]); @@ -35,12 +43,15 @@ int main(void) { gpio_setup(); sys_tick_setup(); usart_setup(); + timer_setup(); printf("Printf is working!\n"); gpio_clear(GPIOC, GPIO13); gpio_set(GPIOC, GPIO13); + timer_pwm_set_duty(75.0); + uint64_t init = sys_ticks_get(); while (sys_ticks_get() == init); diff --git a/timer.c b/timer.c new file mode 100644 index 0000000..ef52638 --- /dev/null +++ b/timer.c @@ -0,0 +1,19 @@ +#include "timer.h" +#include +#include + +void timer_setup(void) { + rcc_periph_clock_enable(RCC_TIM2); + timer_set_mode(TIM2, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP); + timer_set_oc_mode(TIM2, TIM_OC1, TIM_OCM_PWM1); + timer_enable_counter(TIM2); + timer_enable_oc_output(TIM2, TIM_OC1); + + timer_set_prescaler(TIM2, PRESCALER - 1); + timer_set_period(TIM2, ARR_VAL - 1); +} + +void timer_pwm_set_duty(float duty) { + const float raw = (float)ARR_VAL * (duty / 100.0f); + timer_set_oc_value(TIM2, TIM_OC1, (uint32_t)raw); +} diff --git a/timer.h b/timer.h new file mode 100644 index 0000000..14d9b54 --- /dev/null +++ b/timer.h @@ -0,0 +1,9 @@ +#pragma once +#include +#include + +#define PRESCALER (72) +#define ARR_VAL (1000) + +void timer_setup(void); +void timer_pwm_set_duty(float duty);