Sketch will not run on power-up

My sketch takes input from an MPU6050 and controls a single micro servo and 2 LED's. It works just fine after I upload the sketch to the Arduino Micro. But, if I power the Micro down and power it back up via USB to my computer or to an external; USB power source, it will not run; I have to reset the Micro, then it will run just fine. I have tried using a non-USB power source and get the same results.

I have loaded a simple sketch (servo "Sweep") and it works fine upon power-up, so I am confident that the problem lies within my sketch. My coding experience is fairly limited in the Arduino environment, so any help would be appreciated.

Accelerometer_on_Micro_with_MPU6050.ino (8.2 KB)

Please post your code, in code tags.

Post a few images of your project.

/*                  I N C L I N O M E T E R
                          Paul Shryock
                            Dec 2021

This app is designed to provide infomation to the operator of a vehicle as to whether or 
not the vehicle is level, ascending or descending and general information as to the 
rate of the climb/descent. It uses an MPU6050 accelerometer/gyro module as the sole sensor. 
It is calibrated at LEVEL (zero degrees) upon power up. The meter is scaled to better represent
gradual angles of ascent/descent by multiplying the actual angle by a factor (angleMult). The 
meter maxes out at 90 degree UP and 90 degree down angles. 

One drawback of using the MPU6050 is that it uses acceleration to determine the angles returned 
by the gyro. This means that the acceleration or deceleration of the vehicle will be interpreted 
by this application as a ascent or descent, but it should quickly settle down and read correctly
once the rate or htravel has settled down.

Max deflection (both UP and DOWN) is at 30 degrees.

      The library call for changing LED color uses arguments in this order:
                    GRGB( Green. Red, Blue)
      The values for RGB colors are 0-255 (out to brightest).
      
      The UP LED is GREEN, and the DOWN LED is RED
       

*/  

//------------------------------------
//        Library inclusions   
//------------------------------------

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

//------------------------------------
//       MPU6050 definitions
//------------------------------------
 
const int MPU_addr=0x68;
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
int minVal=265;
int maxVal=402;
int xAng, yAng, zAng;

//------------------------------------
//  Misc and Calculation definitions
//------------------------------------

double initialX;                              // The initial angle used as error correction thereafter
double adjX;                                  // Intermetiate angle calculation
int upAng, downAng, servoAng, busAng;         // Misc angle calculations
double upLED, downLED;                        // The intensity of each respective LED

//------------------------------------
// LED characteristic definitions
//------------------------------------

#define LED_PIN     8                           // Pin 8 is used on both the Uno and Micro
#define NUM_LEDS    2                           // How many LED's there are
CRGB leds[NUM_LEDS];  

//------------------------------------
//    Configuration Variables
//------------------------------------

double angleMult = 3;                       // Factor for amplifying the actual angle onto the servo. This allows
                                            // setting the full deflection of the needle (+ or - 90 degrees) to a
                                            // value less than 90.
                                            // 1 = 90 degrees for full deflection, 3 = 30 degrees for full deflection.
                                            // (90 / angleMult) is the angle of full deflection.
//----
                                            
int debugFlag = 0;                          // 0 = No data sent to serial monitor, 1 = send data to serial monitor

//----

int ppm = 60;                               // How many times the MPU6050 will be polled for the current angle


 
//--------------------------------------
//        Servo definitions
//--------------------------------------

double x;
double y;
double z;
Servo servo;


//========================================================
//                  S E T U P   C O D E
//========================================================
 
void setup()
{


//----------------------------------
//  Initialize the MPU6050 module 
//---------------------------------- 

Wire.begin();
Wire.beginTransmission(MPU_addr);
Wire.write(0x6B);
Wire.write(0);
Wire.endTransmission(true);

//---------------------------------------
//  Initialize the serial port (monitor) 
//---------------------------------------

if (debugFlag == 1) Serial.begin(9600);

//-------------------------
//  Initialize the servo  
//-------------------------

servo.attach(9);                        // Pin 9 on the Micro is the servo data pin
servo.write(0);

//-----------------------------------------------------------------------------
//     Read the current angle to be used as the offset (error correction)  
//-----------------------------------------------------------------------------

Wire.beginTransmission(MPU_addr);
Wire.write(0x3B);
Wire.endTransmission(false);
Wire.requestFrom(MPU_addr,14,true);
GyX=Wire.read()<<8|Wire.read();
GyY=Wire.read()<<8|Wire.read();
GyZ=Wire.read()<<8|Wire.read();
xAng = map(GyX,minVal,maxVal,-90,90);
yAng = map(GyY,minVal,maxVal,-90,90);
zAng = map(GyZ,minVal,maxVal,-90,90);
initialX= RAD_TO_DEG * (atan2(-yAng, -zAng)+PI);
y= RAD_TO_DEG * (atan2(-xAng, -zAng)+PI);
z= RAD_TO_DEG * (atan2(-yAng, -xAng)+PI);

//-----------------------------
//    Initialize LEDs
//-----------------------------

FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);       
leds[0] = CRGB(0, 0, 0);                                      
leds[1] = CRGB(0, 0, 0);
FastLED.show();

}

//=========================================================================
//                      R E P E T I T I V E   C O D E
//=========================================================================

void loop()   
{

//-------------------------------
//     Poll the MPU 6050   
//-------------------------------
Wire.beginTransmission(MPU_addr);
Wire.write(0x3B);
Wire.endTransmission(false);
Wire.requestFrom(MPU_addr,14,true);
GyX=Wire.read()<<8|Wire.read();
GyY=Wire.read()<<8|Wire.read();
GyZ=Wire.read()<<8|Wire.read();
xAng = map(GyX,minVal,maxVal,-90,90);
yAng = map(GyY,minVal,maxVal,-90,90);
zAng = map(GyZ,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);


//---------------------------------------------
//                Calculations
//---------------------------------------------

adjX = x + (360 - initialX);
if (adjX > 360)                                                 // Adjust UP angle
  {
    adjX = adjX - 360;
  }
  
if (adjX <= 90)                                                 // Adjust DOWN angle
  {
    upAng = adjX;
    downAng = 0;
  }
  
if (adjX < 360 and adjX >= 270)
  {
    upAng = 0;
    downAng = adjX - 270;
    downAng = map(downAng,0,90,-90,0) + 1;
  }

busAng = upAng + downAng;

servoAng = ((busAng * angleMult) + 90);         // Calculate servo angle adjusted for max deflection

servo.write(servoAng);                          // Move the servo

//---------------------------------------------------------
//  Set the LED's as is appropriate for the servoAngle  
//---------------------------------------------------------

upLED = (upAng / 90.0) * 255.0;                 // Set the intensity of the UP LED
downLED = (abs(downAng) / 90.0) * 255.0;        // Set the intensity of the DOWN LED
leds[1] = CRGB(int(upLED), 0, 0);               // Set the UP LED - GREEN
leds[0] = CRGB(0 , int(downLED), 0);            // Set the DOWN LED - RED
FastLED.show();
        
// ================================  D E B U G  ============================

if (debugFlag == 1)
  {
  Serial.print("GyX = ");
  Serial.println(GyX);
  Serial.print("AngleX= ");
  Serial.println(x);
  Serial.print("Initial angle (angle adjustment) = ");
  Serial.println(initialX);
  Serial.print("Corrected angle = ");
  Serial.println(adjX);
  Serial.print("Up angle = ");
  Serial.println(upAng);
  Serial.print("Down angle = ");
  Serial.println(downAng);
  Serial.print("Bus angle = ");
  Serial.println(busAng);
  Serial.print("Servo angle = ");
  Serial.println(servoAng);
  Serial.print("Up LED = ");
  Serial.println(upLED);
  Serial.print("Down LED = ");
  Serial.println(downLED);
  Serial.println("-----------------------------------------");
  }

// ==========================================================================


delay((60/ppm)*1000);

}

You can paste an image into a forum reply here.

You can drag and drop an image onto a forum reply here.

You can use the upward pointing arrow icon on the post composer toolbar and then select an image file from your computer.

Pick whichever method is most convenient for you.

Got it and posted. Thx

There are missing voltages and component ID's on the schematic. Can you fill us in please? For example, what is the voltage from the DC-DC converter? What is the "simple diode"? Never heard of such a thing before... :slight_smile: ... and why are they there? Never seen that either.... :slight_smile:

On the other hand, amazing inline documentation in the sketch! I wish everyone did that.

The image is of the "as built" final product. I currently have power supplied via USB directly to the Micro, and am pulling 5v power from the Micro to power everything else. I have run it in this development config for 2 days consecutively and it works just fine.

As for the comments in my sketch; that is the habit of MANY years writing code in almost every conceivable language.

I am using the diodes to eliminate noise from the servo motor into the rest of the system. Without them, the system will crash after anywhere from 30 minutes to 20 hours.

Mmmm. This is not good. To trouble shoot a power problem, we need to know exactly your hardware configuration.

Sorry, it's an extremely dubious solution. You need to reconsider. The simple reason that something eliminates a failure, is not sufficient. You need to know why, to protect yourself against a possibility that your fix just "moved the gate".

If the output of the dc to dc converter is 5V, that will be one of your problems. 5V does not go into VIN, put the 5V onto the 5V pin.

Assuming it is 5V. I didn't see any label (missed it?).

Here is a quickly revised diagram of the project as it is today.

As I mentioned, the project works just fine as it is wired. I would think that if there were a problem with the way it is wired it would not work after I pressed reset (which it does). I have to believe the problem has something to do with the code in my sketch.

I believe I have eliminated hardware and wiring issues. I have1 loaded and run very simple sample sketches that verified the operation of the MPU6050, LED's and the servo independently exactly as it is wired in my last diagram.

Maybe your reset circuit is broken.

? ? ? It runs just fine AFTER I press reset on the Micro. I have also used an external button to reset it with the same results. The problem is that the sketch will not run UNTIL I reset the Micro.

And those diodes on the servo, have not seen that before.

Quite strange that your the only person who has a requirement for the diodes.

Can't comment on anyone else's project, only that I tried many other remedies for the motor noise and the diodes inclusion is the only one that actually works.

Perhaps you should look around - it is considered very bad design to run any servo from the MCU 5V supply.