So this is the code that I've been working on so far. My current problem is that the conditions in the main loop only work when the serial monitor is open. How can I solve this problem? I'd be grateful for your help.
#include<AFMotor.h>
#include "SR04.h"
#include <Wire.h>
#include <MPU6050.h>
//for gyro
MPU6050 mpu;
// Timers
unsigned long timer = 0;
float timeStep = 0.01;
// Pitch, Roll and Yaw values
float pitch = 0;
float roll = 0;
float yaw = 0;
AF_DCMotor motor1(1); // left motor
AF_DCMotor motor2(2); // right motor
void setup() {
// run once at startup
Serial.begin(115200);
delay(1000);
// Initialize MPU6050
while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
{
Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
delay(500);
}
// Calibrate gyroscope. The calibration must be at rest.
// If you don't want calibrate, comment this line.
mpu.calibrateGyro();
// Set threshold sensivty. Default 3.
// If you don't want use threshold, comment this line or set 0.
mpu.setThreshold(3);
delay(5000);
}
void loop(){
calculateYaw();
if ( yaw <= 0.5 && yaw >= -0.5 ) { // you can increse the range to suit your sensor's accuracy
motor1.setSpeed(225);
motor2.setSpeed(225);
motor1.run(FORWARD);
motor2.run(FORWARD);
}
else {
if(yaw > 0.5){
motor1.setSpeed(200);
motor2.setSpeed(200);
motor1.run(FORWARD);
motor2.run(BACKWARD);
if(yaw < 0.2 && yaw > -1) {
motor1.setSpeed(100);
motor2.setSpeed(100);
motor1.run(FORWARD);
motor2.run(FORWARD);
delay(100);
}
}
if(yaw < -5){
motor1.setSpeed(200);
motor2.setSpeed(200);
motor1.run(BACKWARD);
motor2.run(FORWARD);
delay(100);
if(yaw > -1 && yaw < 0.5) {
motor1.setSpeed(100);
motor2.setSpeed(100);
motor1.run(FORWARD);
motor2.run(FORWARD);
}
}
}
}
void calculateYaw(){
timer = millis();
// Read normalized values
Vector norm = mpu.readNormalizeGyro();
// Calculate Pitch, Roll and Yaw
pitch = pitch + norm.YAxis * timeStep;
roll = roll + norm.XAxis * timeStep;
yaw = yaw + norm.ZAxis * timeStep;
// Wait to full timeStep period
delay((timeStep*1000) - (millis() - timer));
// Output raw
Serial.println(" Pitch = ");
Serial.println(pitch);
Serial.println(" Roll = ");
Serial.println(roll);
Serial.println(" Yaw = ");
Serial.println(yaw);
}