void motor_set_PWM(int left, int right) { //pwm_clock_init(); if(left==0){ pwm_duty(left_forward,left); pwm_duty(left_back,left); } else if (left > 0) { pwm_duty(left_forward,left); pwm_duty(left_back,0); } else { pwm_duty(left_forward,0); pwm_duty(left_back,-left); } if(right==0){ pwm_duty(right_forward,right); pwm_duty(right_back,right); } else if (right > 0) { pwm_duty(right_back,0); pwm_duty(right_forward,right); } else { pwm_duty(right_forward,0); pwm_duty(right_back,-right); } } 这是一段设置pwm占空比来调整小车转速的代码,请告诉我如何更好地避免小车前进的同时轮子后退,导致小车轮子不转
时间: 2024-04-10 17:27:33 浏览: 111
PWM.rar_ARM PWM_arm c语言_pwm a_pwm arm
为了避免小车前进时轮子后退,你可以在设置 PWM 占空比之前添加一些逻辑判断。下面是一个修改后的代码示例:
```cpp
void motor_set_PWM(int left, int right) {
// 判断左轮方向
if(left == 0){
pwm_duty(left_forward, left);
pwm_duty(left_back, left);
}
else if(left > 0){
pwm_duty(left_forward, left);
pwm_duty(left_back, 0);
}
else{
pwm_duty(left_forward, 0);
pwm_duty(left_back, -left);
}
// 判断右轮方向
if(right == 0){
pwm_duty(right_forward, right);
pwm_duty(right_back, right);
}
else if(right > 0){
pwm_duty(right_forward, right);
pwm_duty(right_back, 0);
}
else{
pwm_duty(right_forward, 0);
pwm_duty(right_back, -right);
}
// 额外判断,如果左右轮方向相反,则将左右轮占空比都设为0
if((left > 0 && right < 0) || (left < 0 && right > 0)){
pwm_duty(left_forward, 0);
pwm_duty(left_back, 0);
pwm_duty(right_forward, 0);
pwm_duty(right_back, 0);
}
}
```
这样,当左右轮方向相反时,会将左右轮的占空比都设置为0,从而避免小车前进时轮子后退的情况发生。
阅读全文