Program only works correctly after re-uploading at each start-up. Why?

I have two pieces of code, one for testing whether the gyro/accelerometer works correctly and the other for using the accelerometer to play a simple game. My problem is when I have uploaded my game code and want to start-up (either by powering by USB or through battery) the game seems unable to pick-up the accelerometer data. Only when I upload my test code first (and see that the accelerometer gives the correct values) and upload the game code after that, it works correctly.

Does any of this sound familiar to anyone? I would like to be able to demonstrate the game without the need of first re-uploading the two codes at each start-up. Please help :astonished:

A wild guess is that you missed a setup function for your game, a function that setups the accelerometer accordingly. That's why you need to upload the testing sketch first, it setups the hardware. Configuration is lost at power cycles.

Abfahrt's suggestion seems like a good one - I suggest you look to see what initialisation the test sketch is doing that your game sketch is not doing.

PeterH: Abfahrt's suggestion seems like a good one - I suggest you look to see what initialisation the test sketch is doing that your game sketch is not doing.

I had similar experiences in the past XD

Something else worth mentioning is that some boards (especially those that have capacitors on them) might store enough power to keep the electronics powered for some seconds even though you unplug the cord. You will either have to wait a little longer or short the power rails using a resistor (after you unplug the power).

You might experiment with adding a delay to the beginning of your game code.

Never used an accelerometer, so not qualified here, but could it be that there is an initialisation sequence problem?

If the arduino is asking the accelerometer questions before it has fully started up, “normally”. When uploading the program while everything is powered up means that the accelerometer has initialised it’s self before your code connects, what happens if:

  1. You power up the board, observe it fail to work, wait a few seconds, then reset the Arduino?

  2. (as already suggested) you add a delay(1000) into the start of your setup function?

Thingomy

Abfahrt: A wild guess is that you missed a setup function for your game, a function that setups the accelerometer accordingly. That's why you need to upload the testing sketch first, it setups the hardware. Configuration is lost at power cycles.

Yep, this fixed my problem! It made sense and after going through the code I noticed I somehow left out the "accelgyro.initialize();" from my game code.

Thanks for your input everybody!