添加更多if语句后程序停止

时间:2017-10-05 20:45:04

标签: if-statement arduino gyroscope servo

最近我遇到了一个问题,我在其中再添加2个if语句,它会一起停止我的代码。例如,下面的代码将使用两个gyroX if语句,但是一旦我添加了这两个gyroY if语句,整个代码将无法运行。如何解决这个问题的任何建议将不胜感激。

#include <Wire.h>
#include <Servo.h>

Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;

int pos1 = 0;
int pos2 = 0;

long gyroX, gyroY, gyroZ;

void setup() {
  Serial.begin(9600);
  Wire.begin();
  setupMPU();
  servo1.attach(4);
  servo2.attach(5);
  servo3.attach(6);
  servo4.attach(7);
}

void loop() { 
  recordGyroRegisters();
  if(gyroX <= 0)
  {
      pos1 += 1;
      servo1.writeMicroseconds(pos1);
      servo3.writeMicroseconds(pos1);
  }
  if(gyroX > 0)
  {
      pos1 -= 1;
      servo1.writeMicroseconds(pos1);
      servo3.writeMicroseconds(pos1);
  }
  if(gyroY <= 0)  //PROBLEM OCCURS WHEN I ADD THIS FUNCTION
  {
      pos2 += 1;
      servo2.writeMicroseconds(pos2);
      servo4.writeMicroseconds(pos2);
  }
  if(gyroY > 0)   //PROBLEM OCCURS WHEN I ADD THIS FUNCTION
  {
      pos2 -= 1;
      servo2.writeMicroseconds(pos2);
      servo4.writeMicroseconds(pos2);
  }
}

void setupMPU(){
  Wire.beginTransmission(0b1101000); 
  Wire.write(0x6B); 
  Wire.write(0b00000000); 
  Wire.endTransmission();  
  Wire.beginTransmission(0b1101000); 
  Wire.write(0x1B); 
  Wire.write(0x00000000); 
  Wire.endTransmission(); 
  Wire.beginTransmission(0b1101000);
  Wire.write(0x1C);  
  Wire.write(0b00000000); 
  Wire.endTransmission(); 
}

void recordGyroRegisters() {
  Wire.beginTransmission(0b1101000);
  Wire.write(0x3B); 
  Wire.endTransmission();
  Wire.requestFrom(0b1101000,6);
  while(Wire.available() < 6);
  gyroX = Wire.read()<<8|Wire.read();
  gyroY = Wire.read()<<8|Wire.read(); 
  gyroZ = Wire.read()<<8|Wire.read(); 
}

1 个答案:

答案 0 :(得分:-1)

为什么不使用else if? 它会更快地运作。

if(gyroX <= 0)
{
  ...
}
else if(gyroX > 0)
{
}

if(gyroY <= 0)  //PROBLEM OCCURS WHEN I ADD THIS FUNCTION
{
}
else if(gyroY > 0)   //PROBLEM OCCURS WHEN I ADD THIS FUNCTION
{
}