Arduino stalls, have to reset to start recieveing data again

I have an Arduino nano connected to an MMA 8452 accelerometer and an amplified speaker. I am looking to collect data from the accelerometer and play sounds through a speaker connnected to the amplifier. I am using 330 Ohms pull up resistors across I2C lines.The problem is that after a while the arduino stops receiving data from the accelerometer. I have to replug the power supply to get it to work again.

I did something similar earlier with an arduino Uno and adxl 345 accelerometer and it was working perfectly. In that instance I used a sparkfun musical instrument shield which communicated over software serial. Now I am using another synth library which uses the hardware serial.

Here's my code :-

#include <Wire.h> // Must include Wire library for I2C
#include <SFE_MMA8452Q.h> // Includes the SFE_MMA8452Q library
#include <synth.h> // Include the synth library


synth edgar; // Create a synth instance

MMA8452Q accel; // Create an accelerometer instance

// Declare the variables for Co-ordinates
double x = 0.0;
double y = 0.0;
double z = 0.0;


void setup()
{
  Serial.begin(9600);

  if(!accel.init(SCALE_8G)) 
  { // Initialize the accelerometer
     Serial.println("Ooops, no accelerometer detected ... Check your wiring!");
     while(1);
  }
  
  edgar.begin(); // Initialize the synth
  
  //Set up the voices:
  //setupVoice( voice[0-3] , waveform[SINE,TRIANGLE,SQUARE,SAW,RAMP,NOISE] , pitch[0-127], envelope[ENVELOPE0-ENVELOPE3], length[0-127], mod[0-127, 64=no mod])

  edgar.setupVoice(0,SQUARE,60,ENVELOPE1,60,64);
  edgar.setupVoice(1,RAMP,0,ENVELOPE3,60,64);
  edgar.setupVoice(2,TRIANGLE,0,ENVELOPE2 ,60,64);
  edgar.setupVoice(3,NOISE,0,ENVELOPE3,20,64);
  
  
}

// The loop function will simply check for new data from the
//  accelerometer and print it out if it's available.
void loop()
{
  // Use the accel.available() function to wait for new data
  //  from the accelerometer.
  if (accel.available())
  {
    // First, use accel.read() to read the new variables:
    accel.read();
    
    // Getting the values from the accelerometer
    x = accel.cx;
    y = accel.cy;
    z = accel.cz;
    
    if (abs(y) > 0.5 /*&& abs(y) < 4.0 */) {
      edgar.setLength(3,60);
      edgar.setMod(3, x*10 +64);
      edgar.mTrigger(3,20);
      delay(150);
    }
	

    if (abs(z) > 0.5 /* && abs(z) < 4.0 */) {
      edgar.setMod(0, x*10 + 64);
      edgar.setMod(1, x*10 + 64);      edgar.mTrigger(0, 40);
      edgar.mTrigger(1, 40);
    
      delay(150);
    }	

	
	
}
  
  
  
    printCalculatedAccels();
    //printAccels(); // Uncomment to print digital readings
    
    
    Serial.println(); // Print new line every time.
  }


void printAccels()
{
  Serial.print(accel.x, 3);
  Serial.print("\t");
  Serial.print(accel.y, 3);
  Serial.print("\t");
  Serial.print(accel.z, 3);
  Serial.print("\t");
}


void printCalculatedAccels()
{ 
  Serial.print(accel.cx, 3);
  Serial.print("\t");
  Serial.print(accel.cy, 3);
  Serial.print("\t");
  Serial.print(accel.cz, 3);
  Serial.print("\t");
}


void printOrientation()
{
  // accel.readPL() will return a byte containing information
  // about the orientation of the sensor. It will be either
  // PORTRAIT_U, PORTRAIT_D, LANDSCAPE_R, LANDSCAPE_L, or
  // LOCKOUT.
  byte pl = accel.readPL();
  switch (pl)
  {
  case PORTRAIT_U:
    Serial.print("Portrait Up");
    break;
  case PORTRAIT_D:
    Serial.print("Portrait Down");
    break;
  case LANDSCAPE_R:
    Serial.print("Landscape Right");
    break;
  case LANDSCAPE_L:
    Serial.print("Landscape Left");
    break;
  case LOCKOUT:
    Serial.print("Flat");
    break;
  }
}

Does it have anything to do with serial library?

Does it have anything to do with serial library?

Are you using the Serial instance to talk to the speaker? If connecting the speaker causes problems, the problems can't possibly be related to the Serial instance/library.

What kind of battery?

330 ohms for the I2C resistors sounds way too low. Typically, they are around 4700 Ohms.

If connecting the speaker causes problems, the problems can't possibly be related to the Serial instance/library

The reason I say that the problem might have something to do with serial is that when I increase the rate to 57600 the crash is almost immediate as compared to 9600 which does work for a little while.

330 ohms for the I2C resistors sounds way too low. Typically, they are around 4700 Ohms.

I've tried that aswell, doesn't seem to make any difference. I am using 330 ohms because the the test code suggested that.

Edit :- I was wrong, I took out the code which outputs the sound and still the code stalls. It only starts running again when I close and restart the serial monitor

It only starts running again when I close and restart the serial monitor

Which resets the Arduino.

You didn't answer the question about the battery, nor have you explained why you are using a battery AND a USB cable at the same time.

You haven't shown the serial output, so we'd have a clue where the problem might be.

You didn't answer the question about the battery, nor have you explained why you are using a battery AND a USB cable at the same time.

I am sorry I meant the power supply (resetting the arduino. I've edited the title now)

You haven't shown the serial output, so we'd have a clue where the problem might be

The serial output only has x, y, z acceleration values, nothing special.

There's another interesting thing, when I comment out the synth parts of the code it doesn't stall. Here's the code for the library:-

#ifndef _SYNTH
#define _SYNTH
//**************************************************************
//  Arduino synth V4.1
//  Optimized audio driver, modulation engine, envelope engine.
//
//  Dzl/Illutron 2014
//
//***********************************************
#include <avr/pgmspace.h>
#include <avr/interrupt.h> 
#include "tables.h"

#define DIFF 1
#define CHA 2
#define CHB 3

#define SINE     0
#define TRIANGLE 1
#define SQUARE   2
#define SAW      3
#define RAMP     4
#define NOISE    5

#define ENVELOPE0 0
#define ENVELOPE1 1
#define ENVELOPE2 2
#define ENVELOPE3 3

#define FS 20000.0           //-Sample     rate (NOTE: must match tables.h)

#define SET(x,y) (x |=(1<<y))                       //-Bit set/clear macros
#define CLR(x,y) (x &= (~(1<<y)))                   // |
#define CHK(x,y) (x & (1<<y))                       // |
#define TOG(x,y) (x^=(1<<y))                        //-+

volatile unsigned int PCW[4] = {0, 0, 0, 0};            //-Wave phase accumolators
volatile unsigned int FTW[4] = {1000, 200, 300, 400};           //-Wave frequency tuning words
volatile unsigned char AMP[4] = {255, 255, 255, 255};           //-Wave amplitudes [0-255]
volatile unsigned int PITCH[4] = {500, 500, 500, 500};          //-Voice pitch
volatile int MOD[4] = {20, 0, 64, 127};                         //-Voice envelope modulation [0-1023 512=no mod. <512 pitch down >512 pitch up]
volatile unsigned int wavs[4];                                  //-Wave table selector [address of wave in memory]
volatile unsigned int envs[4];                                  //-Envelopte selector [address of envelope in memory]
volatile unsigned int EPCW[4] = {0x8000, 0x8000, 0x8000, 0x8000}; //-Envelope phase accumolator
volatile unsigned int EFTW[4] = {10, 10, 10, 10};               //-Envelope speed tuning word
volatile unsigned char divider = 4;                             //-Sample rate decimator for envelope
volatile unsigned int tim = 0;
volatile unsigned char tik = 0;
volatile unsigned char output_mode;


    //*********************************************************************************************
//  Audio driver interrupt
//*********************************************************************************************

 SIGNAL(TIMER1_COMPA_vect)
{
  //-------------------------------
  // Time division
  //-------------------------------
  divider++;
  if(!(divider&=0x03))
    tik=1;

  //-------------------------------
  // Volume envelope generator
  //-------------------------------

  if (!(((unsigned char*)&EPCW[divider])[1]&0x80))
    AMP[divider] = pgm_read_byte(envs[divider] + (((unsigned char*)&(EPCW[divider]+=EFTW[divider]))[1]));
  else
     AMP[divider] = 0;

  //-------------------------------
  //  Synthesizer/audio mixer
  //-------------------------------

  OCR2A = OCR2B = 127 +(((((signed char)pgm_read_byte(wavs[0] + ((unsigned char *)&(PCW[0] += FTW[0]))[1]) * AMP[0]) >> 8) + (((signed char)pgm_read_byte(wavs[1] + ((unsigned char *)&(PCW[1] += FTW[1]))[1]) * AMP[1]) >> 8) + (((signed char)pgm_read_byte(wavs[2] + ((unsigned char *)&(PCW[2] += FTW[2]))[1]) * AMP[2]) >> 8) +
(((signed char)pgm_read_byte(wavs[3] + ((unsigned char *)&(PCW[3] += FTW[3]))[1]) * AMP[3]) >> 8)
) >> 2);

//************************************************
//  Modulation engine
//************************************************
//  FTW[divider] = PITCH[divider] + (int)   (((PITCH[divider]/64)*(EPCW[divider]/64)) /128)*MOD[divider];
  FTW[divider] = PITCH[divider] + (int)   (((PITCH[divider]>>6)*(EPCW[divider]>>6))/128)*MOD[divider];
tim++;
}

class synth
{
 private:

 public:

 synth()
 {
 }

  //*********************************************************************
  //  Startup default
  //*********************************************************************

  void begin()
  {
    output_mode=CHA;
    TCCR1A = 0x00;                                  //-Start audio interrupt
    TCCR1B = 0x09;
    TCCR1C = 0x00;
    OCR1A=16000000.0 / FS;              //-Auto sample rate
    SET(TIMSK1, OCIE1A);                            //-Start audio interrupt
    sei();                                          //-+

    TCCR2A = 0x83;                                  //-8 bit audio PWM
    TCCR2B = 0x01;                                  // |
    OCR2A = 127;                                    //-+
    SET(DDRB, 3);                   //-PWM pin
  }

   //*********************************************************************
   //  Startup fancy selecting varoius output modes
   //*********************************************************************

  void begin(unsigned char d)
  {
    TCCR1A = 0x00;                                  //-Start audio interrupt
    TCCR1B = 0x09;
    TCCR1C = 0x00;
    OCR1A=16000000.0 / FS;              //-Auto sample rate
    SET(TIMSK1, OCIE1A);                            //-Start audio interrupt
    sei();                                          //-+

    output_mode=d;

    switch(d)
    {
    case DIFF:                                        //-Differntial signal on CHA and CHB pins (11,3)
      TCCR2A = 0xB3;                                  //-8 bit audio PWM
      TCCR2B = 0x01;                                  // |
      OCR2A = OCR2B = 127;                            //-+
      SET(DDRB, 3);                   //-PWM pin
      SET(DDRD, 3);                   //-PWM pin
      break;

    case CHB:                                         //-Single ended signal on CHB pin (3)
      TCCR2A = 0x23;                                  //-8 bit audio PWM
      TCCR2B = 0x01;                                  // |
      OCR2A = OCR2B = 127;                            //-+
      SET(DDRD, 3);                   //-PWM pin
      break;

    case CHA:
    default:
      output_mode=CHA;                                //-Single ended signal in CHA pin (11)
      TCCR2A = 0x83;                                  //-8 bit audio PWM
      TCCR2B = 0x01;                                  // |
      OCR2A = OCR2B = 127;                            //-+
      SET(DDRB, 3);                   //-PWM pin
      break;

    }
  }

  //*********************************************************************
  //  Timing/sequencing functions
  //*********************************************************************


  //*********************************************************************
  //  Setup all voice parameters in MIDI range


// More Code follows

Now I am guessing an interrupt is the main culprit here. because even if I just initialize the synth object, the program stops.

anath2:
I am using 330 Ohms pull up resistors across I2C lines.

Why?

You are drawing 15 mA constantly, per pin, doing that.

Now I am guessing an interrupt is the main culprit here. because even if I just initialize the synth object, the program stops.

What interrupt?

Can you provide links to the exact libraries you are using?

Can you provide links to the exact libraries you are using?

Here's the link to the library for synthesizer

Here's the link to the library for the accelerometer

What interrupt?

I think the synth library generates an interrupt when it is initialized. Not sure though, I am a newbie

Finally got my program working. I used an adxl345 accelerometer and the program now seems to work fine. However I am still curious why the previous accelerometer mma 8452Q had the issue. I tried atleast 5 of them and all of them had the same problem.

However I am still curious why the previous accelerometer mma 8452Q had the issue. I tried atleast 5 of them and all of them had the same problem.

The Arduino UNO and Nano are 5V.
The MMA8452Q by sparkfun is 3.3V and has no level-shifting.
The ADXL345 by adafruit has level-shifting and works with 5V.