写stm 32c8t6小车电机减速程序,PB6输出PWMPB 8 PB 9控制左侧电机,PB7输出PWM控制PC13PC 14控制右侧电机
时间: 2024-01-13 10:04:15 浏览: 152
PWM常用于电机调速.rar_51_597_STC_stc pwm_电机控制程序
以下是一个简单的 STM32C8T6 小车电机减速程序,使用 PB6、PB8、PB9、PB7、PC13 和 PC14 控制两个电机:
```
#include "stm32c8t6.h"
void delay(int n)
{
for(int i=0;i<n;i++);
}
void pwm_init()
{
RCC_APB2ENR |= (1<<0); // Enable GPIOB clock
RCC_APB2ENR |= (1<<4); // Enable GPIOC clock
// Configure PB6 as PWM output
GPIOB_CRL &= ~(0xF << 24);
GPIOB_CRL |= (0xB << 24);
// Configure PB8 and PB9 as general purpose output
GPIOB_CRH &= ~(0xFF << 0);
GPIOB_CRH |= (0x33 << 0);
// Configure PB7 as PWM output
GPIOB_CRL &= ~(0xF << 28);
GPIOB_CRL |= (0xB << 28);
// Configure PC13 and PC14 as general purpose output
GPIOC_CRH &= ~(0xFF << 20);
GPIOC_CRH |= (0x33 << 20);
// Configure TIM3 for PWM
RCC_APB1ENR |= (1<<1); // Enable TIM3 clock
TIM3_PSC = 0; // Set prescaler to 1
TIM3_ARR = 9999; // Set auto-reload value to 9999
TIM3_CCMR1 |= (0x6<<4) | (0x6<<12); // Set PWM mode on channels 1 and 2
TIM3_CCMR2 |= (0x6<<4) | (0x6<<12); // Set PWM mode on channels 3 and 4
TIM3_CCER |= (1<<0) | (1<<4); // Enable PWM on channels 1 and 2
TIM3_CCER |= (1<<8) | (1<<12); // Enable PWM on channels 3 and 4
TIM3_CR1 |= (1<<0); // Enable TIM3
}
void motor_forward()
{
// Set PB8 and PC14 high
GPIOB_BSRR |= (1<<8);
GPIOC_BSRR |= (1<<14);
// Set PB9 and PC13 low
GPIOB_BRR |= (1<<9);
GPIOC_BRR |= (1<<13);
// Set PWM duty cycle on PB8 and PC14
TIM3_CCR1 = 5000;
TIM3_CCR3 = 5000;
// Wait for a short time
delay(100000);
}
void motor_backward()
{
// Set PB8 and PC14 low
GPIOB_BRR |= (1<<8);
GPIOC_BRR |= (1<<14);
// Set PB9 and PC13 high
GPIOB_BSRR |= (1<<9);
GPIOC_BSRR |= (1<<13);
// Set PWM duty cycle on PB9 and PC13
TIM3_CCR2 = 5000;
TIM3_CCR4 = 5000;
// Wait for a short time
delay(100000);
}
void motor_stop()
{
// Set PB8, PB9, PC13 and PC14 low
GPIOB_BRR |= (1<<8) | (1<<9);
GPIOC_BRR |= (1<<13) | (1<<14);
// Set PWM duty cycle on all channels to 0
TIM3_CCR1 = 0;
TIM3_CCR2 = 0;
TIM3_CCR3 = 0;
TIM3_CCR4 = 0;
// Wait for a short time
delay(100000);
}
int main()
{
pwm_init();
while(1)
{
motor_forward();
motor_stop();
motor_backward();
motor_stop();
}
return 0;
}
```
阅读全文