Hi everyone
I have a Arduino nano connected to the Blynk android app with a HC-05 bluetooth module. I also have a MPU5060 which i’m using to read gyro data.
For testing I am printing the current milli and the gyro data to the serial monitor. I am also sending the milli to the Blynk app every 1 second to see whether the bluetooth connection is still active.
My code runs fine and then seems to totally freeze randomly. This freeze sometimes happens after 23 seconds and then at other times the program runs fine for 500 seconds or more. I cant seem to figure out why this is happening. Please see my code below as reference.
Any advice on what might be causing the issue would really be appreciated. I have been tearing my hair out trying to trouble shoot this and at this point a nudge in the right direction would be amazing.
//PRO - gets MPU data, button works, nooo freezing!
//Bluetooth
#define BLYNK_PRINT Serial
#include <AltSoftSerial.h>
#include <BlynkSimpleSerialBLE.h>
char auth[] = "8e9354f3c75148acb8eb2efb56e221c7";
AltSoftSerial altSerial;
//Bluetooth
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif
MPU6050 mpu;
#define OUTPUT_READABLE_YAWPITCHROLL
#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;
// MPU control/status vars
bool dmpReady = false; // set true if DMP init was successful
uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU
uint8_t devStatus; // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize; // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount; // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer
// orientation/motion vars
Quaternion q; // [w, x, y, z] quaternion container
VectorInt16 aa; // [x, y, z] accel sensor measurements
VectorInt16 aaReal; // [x, y, z] gravity-free accel sensor measurements
VectorInt16 aaWorld; // [x, y, z] world-frame accel sensor measurements
VectorFloat gravity; // [x, y, z] gravity vector
float euler[3]; // [psi, theta, phi] Euler angle container
float ypr[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector
//Calibration
float RollCalibrationReading; // initial roll reading before calibration, this value is used for calibrtion
float RollValue; // Roll angle
float CallibrationAdjustment; // Calibration adjustment
boolean RunCalibration = false; // has calibration run yet
// Handstand
boolean standStatus;
int HandStandCount = 0;
// timing
unsigned long startMillis;
unsigned long currentMillis;
unsigned long strandStartTime;
unsigned long standDuration;
// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '
, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x00, ‘\r’, ‘\n’ };
volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
mpuInterrupt = true;
}
BlynkTimer timer;
void myTimerEvent()
{
// You can send any value at any time.
// Please don’t send more that 10 values per second.
Blynk.virtualWrite(V5, millis() / 1000);
}
void setup()
{
//Bluetooth
Serial.begin(9600);
altSerial.begin(9600);
Blynk.begin(altSerial, auth);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
Blynk.virtualWrite(V5, 0);
//Bluetooth
//Timers
timer.setInterval(1000L, myTimerEvent);
//timers
startMillis = millis();
// join I2C bus (I2Cdev library doesn’t do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
Wire.begin();
TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
Fastwire::setup(400, true);
#endif
Serial.begin(9600);
while (!Serial); // wait for Leonardo enumeration, others continue immediately
mpu.initialize();
devStatus = mpu.dmpInitialize();
mpu.setXGyroOffset(138);
mpu.setYGyroOffset(-37);
mpu.setZGyroOffset(41);
mpu.setZAccelOffset(1338); // 1688 factory default for my test chip
mpu.setDMPEnabled(true);
attachInterrupt(0, dmpDataReady, RISING);
mpuIntStatus = mpu.getIntStatus();
dmpReady = true;
packetSize = mpu.dmpGetFIFOPacketSize();
}
void loop()
{
currentMillis = millis();
Blynk.run();
timer.run();
// if programming failed, don’t try to do anything
if (!dmpReady) return;
// reset interrupt flag and get INT_STATUS byte
mpuInterrupt = false;
mpuIntStatus = mpu.getIntStatus();
// get current FIFO count
fifoCount = mpu.getFIFOCount();
// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
// reset so we can continue cleanly
mpu.resetFIFO();
Serial.println(F(“FIFO overflow!”));
// otherwise, check for DMP data ready interrupt (this should happen frequently)
} else if (mpuIntStatus & 0x02) {
// wait for correct available data length, should be a VERY short wait
while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
// read a packet from FIFO
mpu.getFIFOBytes(fifoBuffer, packetSize);
// track FIFO count here in case there is > 1 packet available
// (this lets us immediately read more without waiting for an interrupt)
fifoCount -= packetSize;
// display Euler angles in degrees
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
RollValue = (ypr[2] * 180 / M_PI);
}
if ((RunCalibration == false) && (currentMillis - startMillis >= 2000)) //optimum millis 5000
{
Calibration();
}
else if (RunCalibration == true) {
TestMeasurements();
//MeasureHandstand();
}
}
// ================================================================
// === TEST MEAUSREMENTS ===
// ================================================================
void TestMeasurements() {
//current angle after calibration
Serial.println(RollValue);
Serial.println(currentMillis);
}
// ================================================================
// === CALIBRATION FUNCTION ===
// ================================================================
void Calibration()
{
RollCalibrationReading = (ypr[2] * 180 / M_PI);
if ((RollCalibrationReading >= 0) && (RollCalibrationReading <= 180)) {
CallibrationAdjustment = RollCalibrationReading;
}
else if ((RollCalibrationReading > 180) && (RollCalibrationReading <= 360)) {
CallibrationAdjustment = RollCalibrationReading - 360;
}
//Take calibration reading once
Serial.print(“Calibdarion value”);
Serial.println(CallibrationAdjustment);
Serial.print(“Time”);
Serial.println(currentMillis);
Serial.println("");
RunCalibration = true;
}
// ================================================================
// === HANDSTAND MEASUREMENT ===
// ================================================================
void MeasureHandstand()
{
if (((RollValue > (100 + CallibrationAdjustment)) && (RollValue < (200 + CallibrationAdjustment))) && (standStatus == false)) {
// Doing handstand
Serial.print(“Stand start”);
standStatus = true;
//start timer
strandStartTime = currentMillis - startMillis;
//standDuration = 0;
}
else if (((RollValue < (20 + CallibrationAdjustment)) || (RollValue > (300 + CallibrationAdjustment))) && (standStatus == true)) {
// Not doing handstand
Serial.println(" - Stand end");
standStatus = false;
// Duration of stand
standDuration = currentMillis - strandStartTime;
Serial.print(“Stand duration: “);
Serial.print(standDuration);
Serial.println(” milliseconds”);
Blynk.virtualWrite(V0, standDuration);
// Stand counter
HandStandCount++;
Serial.print("Handstand count: ");
Serial.println(HandStandCount);
Blynk.virtualWrite(V1, HandStandCount);
}
}