Why do I get avrdude: stk500v2_ReceiveMessage(): timeout error when uploading to Arduino Mega?
The error message basically means that the programmer is unable to contact the boot-loader on the device. The code you're trying to upload has no bearing on the problem.

There could be one of the four possible reason behind it. They are:


Wrong Port Selected:

If TX/RX led is not blinking, then you may have selected wrong port. If one of both of them are blinking then, you aren't using the wrong port. It might be worth checking again though, sometimes USB COM devices install on strange port numbers.
Board is not in Bootloader Mode:

The Arduino Mega is not executing the bootloader for some reason. If the programmer is not resetting the micro before attempting to connect, this might be the reason. Try to reset the board (press and release the button) while the programmer is attempting to connect. Sometimes software that runs in a tight loop will prevent the bootloader from connecting.
Barring that, the fuses might have gotten messed up or the code erased. You would need to reflash the bootloader and proper fuses, again, see the appropriate info page for your device.
Arduino Mega 2560 only: ATmega8U/16U software

Might not be working and would need reprogramming. See the Programming section on the info page, you will need the firmware and Atmel-compatible DFU (device firmware update) software on your computer toreflash the target.
Hardware damage:

There could be hardware damage to the board, AVR(s), or FTDI chip. Time to buy another board.


You can check this answer.