基于stm32f103,写一段利用PA6输出pwm的代码
时间: 2024-01-24 22:04:18 浏览: 96
以下是基于STM32F103的PA6引脚输出PWM的代码:
```c
#include "stm32f10x.h"
int main(void)
{
//开启GPIOA时钟
RCC->APB2ENR |= RCC_APB2ENR_IOPAEN;
//PA6引脚配置为复用推挽输出
GPIOA->CRL &= ~(GPIO_CRL_MODE6 | GPIO_CRL_CNF6);
GPIOA->CRL |= GPIO_CRL_MODE6_1 | GPIO_CRL_CNF6_1;
//使能TIM3时钟
RCC->APB1ENR |= RCC_APB1ENR_TIM3EN;
//设置TIM3的时钟分频为72MHz,计数器自动重载值为1000
TIM3->PSC = 71;
TIM3->ARR = 999;
//设置TIM3的PWM模式为模式1
TIM3->CCMR1 |= TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_2;
//设置TIM3的预装载使能
TIM3->CCMR1 |= TIM_CCMR1_OC1PE;
//设置TIM3的输出比较通道1的占空比为50%
TIM3->CCR1 = 500;
//使能TIM3的输出比较通道1
TIM3->CCER |= TIM_CCER_CC1E;
//使能TIM3的计数器
TIM3->CR1 |= TIM_CR1_CEN;
while(1)
{
//do something
}
}
```
以上代码将TIM3的通道1配置为PWM输出,输出频率为72000000 / 72 / 1000 = 1kHz,占空比为50%。可以根据需求修改计数器时钟分频、自动重载值和占空比等参数。
阅读全文