static inline void Car_forward(u8 speed) { TIM1->CCR1 = 20; // PA8 TIM1->CCR2 = 0; // PA9 TIM1->CCR3 = 20; // PA10 TIM1->CCR4 = 0; // PA11 TIM4->CCR1 = 20; // PB6 TIM4->CCR2 = 0; // PB7 TIM4->CCR3 = 20; // PB8 TIM4->CCR4 = 0; // PB9 } static inline void Car_Backward(u8 speed) { TIM1->CCR1 = 0; // PA8 TIM1->CCR2 = 20; // PA9 TIM1->CCR3 = 0; // PA10 TIM1->CCR4 = 20; // PA11 TIM4->CCR1 = 0; // PB6 TIM4->CCR2 = 20; // PB7 TIM4->CCR3 = 0; // PB8 TIM4->CCR4 = 20; // PB9 } static inline void Car_Turn_Left(u8 speed) { TIM1->CCR1 = 0; // PA8 TIM1->CCR2 = 20; // PA9 TIM1->CCR3 = 0; // PA10 TIM1->CCR4 = 20; // PA11 TIM4->CCR1 = 20; // PB6 TIM4->CCR2 = 0; // PB7 TIM4->CCR3 = 20; // PB8 TIM4->CCR4 = 0; // PB9 delay_ms(500); TIM1->CCR1 = 20; // PA8 TIM1->CCR2 = 0; // PA9 TIM1->CCR3 = 20; // PA10 TIM1->CCR4 = 0; // PA11 TIM4->CCR1 = 20; // PB6 TIM4->CCR2 = 0; // PB7 TIM4->CCR3 = 20; // PB8 TIM4->CCR4 = 0; // PB9 } static inline void Car_Turn_Right(u8 speed) { TIM1->CCR1 = 20; // PA8 TIM1->CCR2 = 0; // PA9 TIM1->CCR3 = 20; // PA10 TIM1->CCR4 = 0; // PA11 TIM4->CCR1 = 0; // PB6 TIM4->CCR2 = 20; // PB7 TIM4->CCR3 = 0; // PB8 TIM4->CCR4 = 20; // PB9 delay_ms(500); TIM1->CCR1 = 20; // PA8 TIM1->CCR2 = 0; // PA9 TIM1->CCR3 = 20; // PA10 TIM1->CCR4 = 0; // PA11 TIM4->CCR1 = 20; // PB6 TIM4->CCR2 = 0; // PB7 TIM4->CCR3 = 20; // PB8 TIM4->CCR4 = 0; // PB9 } static inline void Car_Stop(u8 speed) { TIM1->CCR1 = 0; // PA8 TIM1->CCR2 = 0; // PA9 TIM1->CCR3 = 0; // PA10 TIM1->CCR4 = 0; // PA11 TIM4->CCR1 = 0; // PB6 TIM4->CCR2 = 0; // PB7 TIM4->CCR3 = 0; // PB8 TIM4->CCR4 = 0; // PB9 }优化这段代码
时间: 2023-12-06 22:39:46 浏览: 157
可以考虑将重复的代码提取为函数或宏定义,以减少重复代码和提高可读性。
```
#define SET_TIM1_CCR(val1, val2, val3, val4) do { \
TIM1->CCR1 = (val1); \
TIM1->CCR2 = (val2); \
TIM1->CCR3 = (val3); \
TIM1->CCR4 = (val4); \
} while(0)
#define SET_TIM4_CCR(val1, val2, val3, val4) do { \
TIM4->CCR1 = (val1); \
TIM4->CCR2 = (val2); \
TIM4->CCR3 = (val3); \
TIM4->CCR4 = (val4); \
} while(0)
static inline void Car_forward(u8 speed) {
SET_TIM1_CCR(20, 0, 20, 0);
SET_TIM4_CCR(20, 0, 20, 0);
}
static inline void Car_Backward(u8 speed) {
SET_TIM1_CCR(0, 20, 0, 20);
SET_TIM4_CCR(0, 20, 0, 20);
}
static inline void Car_Turn_Left(u8 speed) {
SET_TIM1_CCR(0, 20, 0, 20);
SET_TIM4_CCR(20, 0, 20, 0);
delay_ms(500);
SET_TIM1_CCR(20, 0, 20, 0);
SET_TIM4_CCR(20, 0, 20, 0);
}
static inline void Car_Turn_Right(u8 speed) {
SET_TIM1_CCR(20, 0, 20, 0);
SET_TIM4_CCR(0, 20, 0, 20);
delay_ms(500);
SET_TIM1_CCR(20, 0, 20, 0);
SET_TIM4_CCR(20, 0, 20, 0);
}
static inline void Car_Stop(u8 speed) {
SET_TIM1_CCR(0, 0, 0, 0);
SET_TIM4_CCR(0, 0, 0, 0);
}
```
可以看到,通过宏定义和函数提取,代码变得更为简洁,可读性也更好。
阅读全文