Hai, i am developing a code to run a measurement when pushbutton is pressed and the angle must be between 0 degree and continue measure on second distance when the angle is in between 60 degree. Then use the result to compare the values. But sadly, the code is right but i guess i miss something. can anybody help me on this?
Here is the code, the part which i am having trouble.
//The measurement only occurs when pushbutton module preesed
//The gyro sensor x angle is in 0 degree, continue the second measurement
//without pressing any pushbutton while just make sure the angle angle is in 60 degree and it continue measure in the same loop.
void loop()
{
if (digitalRead(12) == 1) //if pushbutton pin 12 is pressed
{
flatness(); //void flatness
delay(1000);
if ( d2cal >= d2 + 0.1 && d2cal <= d2 - 0.1) //compare the result of d2cal and d2 measured
{
Serial.println("THE BUILDING NEED INSPECTION");
}
else if ( d2 > d2cal - 0.1 && d2 < d2cal + 0.1)
{
Serial.println("THE BUILDING IN GOOD CONDITION");
}
delay(5000);
}
}
void flatness()
{
angle(); //run the angle loop first
Serial.println(x); // serial print angle x
digitalWrite(32 , LOW); //off the push button vcc so that
digitalWrite(25 , LOW); //during process, the pushbutton will not be available
while ( x = 0) //only measure when the angle is in 0 degree
{
d1 = measure(); //read Hi-AT 50m laser module value
d2cal = d1 * 0.5; // calculate for second distance
Serial.print(d1);
Serial.print("\t");
Serial.print(d2cal);
Serial.print("\t");
}
while ( x > 59 || x < 61) //continue the process only if the angle is in 60 degree
{
d2 = measure(); // measure distance 2 in 60 degree angle
Serial.println(d2);
delay(1000);
}
digitalWrite(32 , HIGH); //activate vcc of push button
digitalWrite(25 , HIGH); //so that it can enable next measurement
}
void angle()
{
//result from gyro sensor for angle measurement
Wire.beginTransmission(MPU_addr);
Wire.write(0x3B);
Wire.endTransmission(false);
Wire.requestFrom(MPU_addr, 14, true);
AcX = Wire.read() << 8 | Wire.read();
AcY = Wire.read() << 8 | Wire.read();
AcZ = Wire.read() << 8 | Wire.read();
int xAng = map(AcX, minVal, maxVal, -90, 90);
int yAng = map(AcY, minVal, maxVal, -90, 90);
int zAng = map(AcZ, minVal, maxVal, -90, 90);
x = RAD_TO_DEG * (atan2(-yAng, -zAng) + PI);
y = RAD_TO_DEG * (atan2(-xAng, -zAng) + PI);
z = RAD_TO_DEG * (atan2(-yAng, -xAng) + PI);
}
double measure()
{
double distance = 999.0;
String response = "";
LaserSerial.println("M");
delay(2500);
while (LaserSerial.available() > 0)
LaserSerial.read();
exitloop = millis();
while (LaserSerial.available() <= 0 && (millis() < exitloop + 2000));
if (millis() < exitloop + 2000) {
while (LaserSerial.available() > 0) {
String inByte = LaserSerial.readString();
response = response + String(inByte) ;
}
if (response.indexOf('m') >= -1)
{
int hi = response.indexOf(':');
distance = response.substring(hi + 1, hi + 7).toFloat();
}
}
return distance ;
}
gyro_with_pushbutton.ino (2.9 KB)
Thank you in advance.