我正在尝试根据陀螺仪的数据移动我的伺服系统。不幸的是,我的程序在while循环开始后停止。例如,在我的代码中,一旦gyroX值达到3000,串行监视器就会停止给我陀螺仪数据并且伺服不会运行。如何解决这个问题的任何建议将不胜感激。
#include <Wire.h>
#include <Servo.h>
Servo servo;
long accelX, accelY, accelZ;
float gForceX, gForceY, gForceZ;
long gyroX, gyroY, gyroZ;
float rotX, rotY, rotZ;
int pos1 = 90;
void setup() {
Serial.begin(9600);
Wire.begin();
setupMPU();
}
void loop() {
recordAccelRegisters();
recordGyroRegisters();
printData();
while( gyroX > 3000 ){ //problem happens here
pos1 += 5;
servo.write(pos1);
}
}
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();
}
void recordAccelRegisters() {
Wire.beginTransmission(0b1101000);
Wire.write(0x43);
Wire.endTransmission();
Wire.requestFrom(0b1101000,6);
while(Wire.available() < 6);
accelX = Wire.read()<<8|Wire.read();
accelY = Wire.read()<<8|Wire.read();
accelZ = Wire.read()<<8|Wire.read();
}
void printData() {
Serial.print("Gyro (deg)");
Serial.print(" X=");
Serial.print(gyroX);
Serial.print(" Y=");
Serial.print(gyroY);
Serial.print(" Z=");
Serial.print(gyroZ);
Serial.print(" Accel (g)");
Serial.print(" X=");
Serial.print(accelX);
Serial.print(" Y=");
Serial.print(accelY);
Serial.print(" Z=");
Serial.println(accelZ);
}
答案 0 :(得分:3)
在while循环内部没有可以改变gyroX值的命令。所以一旦你进入它就变成了一个无限循环。您需要在while循环中调用recordGyroRegisters函数,以便变量在其中更新。或者你可以利用循环函数已经循环的事实,简单地摆脱for循环并选择基于if语句的东西。