[SOLVED] Why are this code destroying the bootloader??

Dear all... I have bought 2 new arduino Mega's, and both came good to my hands. To prove it, I have burn the "Blink" example succhessfully.

But then, when I tried to load following code, the bootloader wrecks, and the red "L" Led are flashing fast.
Can yoy tell me, what's wrong with the code??
And can you tell me a GOOD tutorial to load the bootloader again through another arduino? I have googled a lot about this, and many tutorials say the same, but ever with parts or steps missing.

Thank you!!

// Configuración de puertos de comunicación
#include <Wire.h>                          // Librería de comunicaciones I2C. Por defecto: 100kHz.

// Configuración de la tarjeta SD
#include <SD.h>                            // Librería de la tarjeta SD que incluye SPI. No compatible con librería SPI, si es que se usa.
#define CS_SD 53                           // ChipSelect Pin = 53, para la tarjeta SD en el arduino MEGA.

// Configuración del RTC
#define DS1307 (0x68)                      // Dirección I2C del RTC DS1307

// Configuración del WDT
#include <avr/wdt.h>                       // Librería del WatchDog Timer

// Configuración de los ADLX
#define ADLX_A (0x1D)                      // Dirección I2C del Acelerómetro 1
#define ADLX_B (0x53)                      // Dirección I2C del Acelerómetro 2
#define BW_RATE (0x2C)                     // Data rate and power mode control
#define POWER_CTL (0x2D)                   // Power Control Register
#define DATA_FORMAT (0x31)                 // Data format control
#define DATAZ0 (0x36)                      // Z-Axis Data 0
#define DATAZ1 (0x37)                      // Z-Axis Data 1

// Configuración de comandos especiales
#include <avr/io.h>
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif

#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

// Configuración general
#define ActivityLed 13                     // LED indicador está en Pin 13
#define ProcessingLed 12                   // LED indicador de procesamiento de datos en Pin 12
#define InitSensor 6                       // Primer sensor en Pin5 (sensores simulables por un interruptor común)
#define SecondSensor 7                     // Segundo sensor en Pin4
#define SwitchG2 2                         // Pin para elegir rango +-2G
#define SwitchG4 3                         // Pin para elegir rango +-4G
#define SwitchG8 4                         // Pin para elegir rango +-8G
#define SwitchG16 5                        // Pin para elegir rango +-16G
#define DistanciaSensores 1                // Distancia en [m] entre sensores.

// Variables
String Rang,Hora,Fecha,NombreArchivo;
int Rango,Range,NumArch=99;
char Values_Z[2];                          // Arreglo de 2 espacios para el dato del eje Z de los acelerómetros
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
char buffer[15];                           // Se utiliza para crear un archivo nuevo, nombre.extensión
unsigned long Tiempo1,Tiempo2,Tiempo,Velocidad;

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void setup(){
  // Configuración de la RAM externa
//  XMCRA = _BV(SRE);                        // Enable external memory interface
  pinMode(38, OUTPUT);
  digitalWrite(38, LOW);                   // Enable RAM device
  pinMode(42, OUTPUT);                     // Make the bank selection bits output pins
  pinMode(43, OUTPUT);                     // Make the bank selection bits output pins
  pinMode(44, OUTPUT);                     // Make the bank selection bits output pins
  
  // Inicialización de puertos
  Serial.begin(115200);                    // 57600 es la velocidad de programación para el UNO. Para lo demás podría ser hasta 1000000 o 2000000(no probado).
  Serial1.begin(115200);                   // RX / TX 1 inicialización
  Wire.begin();                            // Predeterminado: 100(kHz) de comunicación
  Serial.write("aaa");
  TWBR=72;                                 // 72 para 100kHz y 12 para 400kHz de velocidad de comunicación I2C.
  
  // Configuración del WDT
  wdt_enable(WDTO_1S);                     // Puede ser tambén: _15MS _30MS _60MS _120MS _250MS _500MS _1S _2S _4S _8S
  
  // Configuración de los ADLX
  //Leer configuración de rango de G
  if(digitalRead(SwitchG2)==1) {
    Rang="+-2[g]";                         // Para escribir esto en el archivo
    Range=2;                               // Para calcular cuanto es es m/s2
    Rango=0x00;                            // Rango: 0x00=2, 0x01=4, 0x02=8, 0x03=16[g]
  }
  if(digitalRead(SwitchG4)==1) {
    Rang="+-4[g]";
    Range=4;
    Rango=0x01;
  }
  if(digitalRead(SwitchG8)==1) {
    Rang="+-8[g]";
    Range=8;
    Rango=0x02;
  }
  if(digitalRead(SwitchG16)==1) {
    Rang="+-16[g]";
    Range=16;
    Rango=0x03;
  }
  Serial.print("Rango elegido: ");
  Serial.println(Rang);
  
  writeTo(ADLX_A, BW_RATE, 0x0F);          // 0x0F = 3200Hz and 1600 Bandwidth, máximo. I2C a 400kHz
  writeTo(ADLX_B, BW_RATE, 0x0F);
  writeTo(ADLX_A, DATA_FORMAT, Rango);
  writeTo(ADLX_B, DATA_FORMAT, Rango);
  writeTo(ADLX_A, POWER_CTL, 0x08);
  writeTo(ADLX_B, POWER_CTL, 0x08);
  
  // Configuración de la tarjeta SD
  pinMode(CS_SD, OUTPUT);
  digitalWrite(CS_SD, HIGH);
    if (!SD.begin(CS_SD)) {
    Serial.println("Falla de carga de tarjeta SD.");
    Led(5);
  }
  else {
    Serial.println("Tarjeta SD inicializada - OK.");
    Led(1);
  }
  
  // Configuración general

}
void loop(){
  File Archivo;
  
  while(digitalRead(InitSensor)==0) wdt_reset();  // Mientras el primer sensor de llegada del tren no indique nada...
  Tiempo1=millis();
  Serial.println("Tren entrando.");
  
  // Ver fecha y hora de suceso
  getDateDs1307(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);  // Extraer datos del reloj
  Hora=hour+":";
  Hora=Hora+minute+":";
  Hora=Hora+second;
  Fecha=dayOfMonth+"/";
  Fecha=Fecha+month+"/";
  Fecha=Fecha+year;

  // Abrir archivo nuevo
  NumArch=NumArch+1;
  NombreArchivo="vibra"+NumArch;
  NombreArchivo=NombreArchivo+".csv";
  NombreArchivo.toCharArray(buffer,15);
  Archivo = SD.open(buffer,FILE_WRITE);  //Otra cosa es: SD.remove("Datos.csv");
  
  while(digitalRead(SecondSensor)==0) wdt_reset();  // Mientras el segundo sensor de llegada del tren no indique nada...
  Tiempo2=millis();
  Tiempo=(Tiempo2-Tiempo1)/1000;
  Velocidad=(DistanciaSensores/Tiempo)*3.6;         // V=d/t en [km/h]
  
  digitalWrite(ActivityLed,HIGH);    // Inicio de mediciones  
  Tiempo1=millis();

  for(int med=0;med<=1000;med++) {
    // Medición
  }

  Tiempo2=millis();
  Serial.println("FIN Medición");
}

// Hacer parpadear LED "e" veces.
void Led(int e) {
  for(int i=0;i<e;i++) {
    digitalWrite(ActivityLed,LOW);
    delay(100);
    digitalWrite(ActivityLed,HIGH);
    delay(100);
    digitalWrite(ActivityLed,LOW);
  }
}

// Para comunicarse con el RTC
// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val) {
  return ((val/10*16)+(val%10));
}

// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val) {
  return ((val/16*10)+(val%16));
}
void getDateDs1307(byte *second,    // Función para extraer hora y fecha del reloj
  byte *minute,
  byte *hour,
  byte *dayOfWeek,
  byte *dayOfMonth,
  byte *month,
  byte *year) {
  // Reset the register pointer
  Wire.beginTransmission(DS1307);
  Wire.write(0);
  Wire.endTransmission();

  Wire.requestFrom(DS1307, 7);

  // A few of these need masks because certain bits are control bits
  *second     = bcdToDec(Wire.read() & 0x7f);
  *minute     = bcdToDec(Wire.read());
  *hour       = bcdToDec(Wire.read() & 0x3f);  // Need to change this if 12 hour am/pm
  *dayOfWeek  = bcdToDec(Wire.read());
  *dayOfMonth = bcdToDec(Wire.read());
  *month      = bcdToDec(Wire.read());
  *year       = bcdToDec(Wire.read());
}

// Write commands via I2C
void writeTo(int DEVICE, byte address, byte val) {
  Wire.beginTransmission(DEVICE); // start transmission to device
  Wire.write(address); // send register address
  Wire.write(val); // send value to write
  Wire.endTransmission(); // end transmission
}

// Reads num bytes starting from address register on device in to _buff array
void readFrom(int DEVICE, byte address, int Bytes_A_Leer) {
  Wire.beginTransmission(DEVICE); // start transmission to device
  Wire.write(address); // sends address to read from
  Wire.endTransmission(); // end transmission

  Wire.beginTransmission(DEVICE); // start transmission to device
  Wire.requestFrom(DEVICE, Bytes_A_Leer); // request X bytes from device

  int i = 0;
  while(Wire.available()) // device may send less than requested (abnormal)
  {
    Values_Z[i] = Wire.read(); // receive a byte
    i++;
  }
  Wire.endTransmission(); // end transmission
}

Do these pins have something external that keeps them at a High or Low level when their switch is not pressed?
#define SwitchG2 2 // Pin para elegir rango +-2G
#define SwitchG4 3 // Pin para elegir rango +-4G
#define SwitchG8 4 // Pin para elegir rango +-8G
#define SwitchG16 5 // Pin para elegir rango +-16G

Normally one would declare this:
pinMode (SwitchG16, INPUT_PULLUP); // input with internal pullup

and then test for the pin being connected to ground to show the switch was pressed/closed:

if(digitalRead(SwitchG16)==0) { // 0, or LOW
Rang="+-16[g]";
Range=16;
Rango=0x03;
}

Dear CrossRoads, this is surely not the problem...

The switches are jumpers to configure the rest of the program's function, and have pull-down resistors (10k) each. Only one jumper is connected.

Thank you!

Why do you think it is the bootloader?

Can you reload blink? If so, it is not the bootloader.

Are you getting any serial output?

It was hard to tell, do you have any "!!!" in your code?

Dear Keith.

I can't reload any sketch. The L led are flashing fast from the beginning without anyother reaction. No serial data in any direction. What do you mean with "!!!"?

No serial data in any direction. What do you mean with "!!!"?

The !!! are some special characters that Arduino IDE send to the board in order to the bootloader know "hei you have a new program here" and the the bootloader grabs all the incoming data and burn it in the flash.
So if you have one of these in you code you could messing the boottloader

Aha? Interesting.

And what must I do, to send the "!!!" characters? In which placeexactly of the code?

It generally prevents uploading. And the "!!!" could occur anywhere in the code. It is probably not your problem.

What specific error message do you get when you try to upload a new sketch?

And HugoPT, my understanding was that the !!! put the arduino bootloader in some sort of console/debug mode, stopping any download dead in its tracks.

The same typical error...

avrdude: stk500_getsync(): not in sync: resp=0x00

But I have checked many times:
Correct COM Port,
Correct Board,
Nothing connected to the board (except USB)
and red L Led flashing fast...........

But my question are why te code above let me the arduino unusable...

Try this - press & hold the reset button.
Start the download process - when the IDE shows "Compiled xxx of 32xxx bytes" (or whatever the number is for a mega), release the button. Might take a couple of tries to get the timing right.
Can be easier if you select File:Preferences, and turn on the Verbose outputs.

This was easy to do (the right timing)... but nothing (I have tryed at least 30 times). I knew this trick...
Thank you for your intention...

but the question is, why have my posted code make the brand new arduino unusable... and not only this one...

May be the WDT library? (I mean, a misshandle of the WDT function?)

Some bootloaders do not handle the WDT correctly. I believe the one on my page below will upload the correct bootloader:

Dear all,

I have fixed my problem.
The problem in the code is the WDT function. Should NEVER be used with the 1280 and 2560 chips. I was told that Atmel made a mistake to implement the WDT in these chips.
Consequences are: Broken fuses and broken Bootloader.

Dear Nick: I don't have proved your bootloader yet... my problem was first to solve this gread headache...

Loading a new Bootloader an fix the fuses, is the solution.
Thank you all!!!

I was told that Atmel made a mistake to implement the WDT in these chips.

Who told you that? The bootloader which is uploaded by my bootloader-uploader works even if you use the WDT.

The bootloader doesn't get "broken" by the code nor are the fuses. The problem is simply that the WDT cuts in during the bootloader operation. A change to the bootloader to prevent that is all that is required.