control an LED & send a midi signal with an LDR (very strange behaviour)

Hi community!

I am working on a project where I use LDR´s to measure light, and when the light goes below certain threshold, trigger a MIDI signal and turn on an LED. I am using an Arduino Mega 2560, and a java-based “serial-midi converter” from Spikenzielabs. (

The sketch that I will attach is a simplified version of what I am using.

The problem that I am facing is that once in a while, the arduino stops sending the MIDI signals, but it remains working fine for the LEDs.

I have the feeling that it has to do with the electricity net. I had this problem several months ago in a venue, where when you turn on a certain light the arduino sttoped sending the midi signals. I had the problem again last week in another venue several times, but when I disconnected my laptop from the electricity net (meaning that the arduino was being fed by the computer´s battery) the system remained working fine MUCH longer than with the computer plugged to the electricity. Actually, it work alright the whole time, but I dont want to discard that this was a coincidence and that sooner or later it could also fail.

When failing, I have to turn of the serial-midi converter in order to allow arduino ide access to the board, but it wouldn´t allow me to upload the sketch unless I disconnect the board from the usb socket in the computer. If I try to upload the sketch without previously disconnect the board from the computer, the following 2 errors would appear:

avrdude: stk500v2_getsync(): timeout communicating with programmer

Arduino: 1.6.1 (Windows 7), Board: “Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)”

Sketch uses 6,252 bytes (2%) of program storage space. Maximum is 253,952 bytes.Global variables use 336 bytes (4%) of dynamic memory, leaving 7,856 bytes for local variables. Maximum is 8,192 bytes.avrdude: ser_open(): can’t set com-state for "\.\COM15"avrdude: ser_drain(): read error: The handle is invalid.
Problem uploading to board. See for suggestions.

This report would have more information with
“Show verbose output during compilation”
enabled in File > Preferences.

ok. I will stop writing from now, and lets see how this develops. Thanks in advance for your support!

ldr_midi_led.ino (7.84 KB)