key_scan(); if(k1==1){while(pwm<500) { pwm++; __HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_1, pwm); HAL_Delay(1); } while (pwm) { pwm--; __HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_1, pwm); HAL_Delay(1); } HAL_Delay(200); } if(k2>0){while (pwm<500) { pwm=pwm+k2; __HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_1, pwm); HAL_Delay(1); } while (pwm) { pwm=pwm-k2; __HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_1, pwm); HAL_Delay(1); } HAL_Delay(200); if(pwm==0) k2=0; } if(k3>0){while (pwm<500) { pwm=pwm-k3; __HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_1, pwm); HAL_Delay(1); } while (pwm) { pwm=pwm+k3; __HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_1, pwm); HAL_Delay(1); } HAL_Delay(200); if(pwm==0) k3=0; } if(k4==1){while (pwm<500) { pwm=1000; __HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_1, pwm); HAL_Delay(1); } while (pwm) { pwm=1000; __HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_1, pwm); HAL_Delay(1); } HAL_Delay(200); }修改代码 让按键之间可以独立作用 能够跳出循环
时间: 2024-04-17 15:25:01 浏览: 302
要让按键之间可以独立作用并能够跳出循环,您可以使用标志变量来控制每个按键的执行情况。在按下某个按键时,将该按键对应的标志变量设置为1,在每次循环迭代时检查标志变量的值,如果为1,则执行相应的操作,并在操作完成后将标志变量重置为0。
以下是修改后的代码示例:
```c
key_scan();
if (k1 == 1) {
int k1Pressed = 1; // 按键1的标志变量
while (k1Pressed) {
while (pwm < 500 && k1 == 1) {
pwm++;
__HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_1, pwm);
HAL_Delay(1);
}
while (pwm && k1 == 1) {
pwm--;
__HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_1, pwm);
HAL_Delay(1);
}
HAL_Delay(200);
if (k1 != 1) {
k1Pressed = 0; // 跳出循环
}
}
}
if (k2 > 0) {
int k2Pressed = 1; // 按键2的标志变量
while (k2Pressed) {
while (pwm < 500 && k2 > 0) {
pwm = pwm + k2;
__HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_1, pwm);
HAL_Delay(1);
}
while (pwm && k2 > 0) {
pwm = pwm - k2;
__HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_1, pwm);
HAL_Delay(1);
}
HAL_Delay(200);
if (k2 == 0) {
k2Pressed = 0; // 跳出循环
}
}
}
if (k3 > 0) {
int k3Pressed = 1; // 按键3的标志变量
while (k3Pressed) {
while (pwm < 500 && k3 > 0) {
pwm = pwm - k3;
__HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_1, pwm);
HAL_Delay(1);
}
while (pwm && k3 > 0) {
pwm = pwm + k3;
__HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_1, pwm);
HAL_Delay(1);
}
HAL_Delay(200);
if (k3 == 0) {
k3Pressed = 0; // 跳出循环
}
}
}
if (k4 == 1) {
int k4Pressed = 1; // 按键4的标志变量
while (k4Pressed) {
while (pwm < 500 && k4 == 1) {
pwm = 1000;
__HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_1, pwm);
HAL_Delay(1);
}
while (pwm && k4 == 1) {
pwm = 1000;
__HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_1, pwm);
HAL_Delay(1);
}
HAL_Delay(200);
if (k4 != 1) {
k4Pressed = 0; // 跳出循环
}
}
}
```
通过使用标志变量,每个按键的操作将独立作用,并且在按键状态发生变化时能够及时跳出循环。请注意,这里假设按键状态是通过外部的key_scan()函数进行更新的。
阅读全文