# code stops a few seconds after starting

I was writing this code to decode a signal which comes in a cable of 18bits, but when executing it it suddenly stops after 14-18 seconds of starting, what am i doing wrong?

``````const int pin_de_entrada = 2; //el 2 o el 3
const int margen = 20;

unsigned long ahora;

unsigned long ult_01;

unsigned long duracion;
bool siguiente_bit = 0;

bool paquete[18];
int indice;

void setup() {
Serial.begin(115200);
pinMode(7, INPUT);
}

void loop() {

for (int x = 0; x < 18; x++) {
if (paquete[x] == 1) {
Serial.print("1");
} else {
Serial.print("0");
}
}
Serial.println();
//delay(200);
//}
Serial.println(ahora);

}

void cambio() {
ahora = micros();

ult_01 = ahora;

if (siguiente_bit == 0) {
siguiente_bit = 1;
} else {
siguiente_bit = 0;
}

}
duracion = ahora - ult_01;

if (duracion <= 28) {
paquete[indice] = 0;
indice++;
}

if (duracion > 60 && duracion < 120) {
paquete[indice] = 1;
indice++;
}

if (indice == 19) {
indice = 0;
}
}
``````

initialize indice to 0 or your first call to cambio is unpredictable.

You assume that indice will become exactly equal to 19 at some point,

if (indice == 19) { indice = 0; } but what if it starts out at 32? you will increment it until you get to integer overflow.

Also, indice should only take on values 0 through 17. paquete[18] is array overflow!!!!

test limit with

if(indice == 17) indice = 0;

otherwise, you will attempt to access paquete[18] one time

initialize indice to 0 or your first call to cambio is unpredictable.

Global variables are initialized. While the first part of the statement is good advice, the second part is not true.