#define Leftmotor0 3 #define Leftmotor1 4 #define STBY 8 #define PWM 9 void setup() { // put your setup code here, to run once: Serial.begin(38400); pinMode(Leftmotor0,OUTPUT); pinMode(Leftmotor1,OUTPUT); digitalWrite(STBY,HIGH); } void loop() { // put your main code here, to run repeatedly: if(Serial.available()) { int read = Serial.parseInt(); int output=read*255/80; if(read>=0&&read<81) { digitalWrite(Leftmotor0,1); analogWrite(PWM,output); delay(500); output=0; } if(read<0) { digitalWrite(Leftmotor0,0); digitalWrite(Leftmotor1,1); analogWrite(PWM,0-output); delay(500); } } }我这个代码我想要在我每一次输入一个数据后在延时之后可以跳出我的if语句并且返回我的read 为0
时间: 2024-01-25 08:02:21 浏览: 80
您可以在每个if语句后加上`return 0;`来跳出if语句并返回read为0。修改后的代码如下:
```
#define Leftmotor0 3
#define Leftmotor1 4
#define STBY 8
#define PWM 9
void setup() {
// put your setup code here, to run once:
Serial.begin(38400);
pinMode(Leftmotor0,OUTPUT);
pinMode(Leftmotor1,OUTPUT);
digitalWrite(STBY,HIGH);
}
void loop() {
// put your main code here, to run repeatedly:
if(Serial.available()) {
int read = Serial.parseInt();
int output=read*255/80;
if(read>=0&&read<81) {
digitalWrite(Leftmotor0,1);
analogWrite(PWM,output);
delay(500);
output=0;
return 0;
}
if(read<0) {
digitalWrite(Leftmotor0,0);
digitalWrite(Leftmotor1,1);
analogWrite(PWM,0-output);
delay(500);
return 0;
}
}
}
```
请注意,`return 0;`会直接退出`loop()`函数,因此下一次循环将从头开始执行。如果您希望程序能够保持运行状态并等待下一个输入,请将`return 0;`改为`read = 0;`。
阅读全文