Go Down

Topic: Using the last element of an array cause me troubles (Read 1 time) previous topic - next topic

hugo007

Jun 08, 2012, 12:22 am Last Edit: Jun 08, 2012, 12:24 am by HugoPT Reason: 1
Hello
I have a function that computes an CRC code using this code
Code: [Select]


byte dataBusOut[5]= {0x01,0x7b,0x7f,0x00,0x04};//start byte , ID, message, CRC ,End Byte --max usable values

byte checkCrc( byte startByte, byte id, byte message , byte endByte)
{  
 Serial.println(startByte,HEX);//To test the element
 Serial.println(id,HEX);//To test the element
 Serial.println(message,HEX);//To test the element
 Serial.println(endByte,HEX);//Bad element sometimes
 byte crcCalc = startByte +id + message + endByte;  
 return crcCalc;  
 
}

This code works but what is bugging me is the array elements.I just need 5 elements to put data but if I declared the array byte dataBusOut[4] which will have space for 5 elements the last element gets changed somehow causing the CRC to get diferent values from the same data.If I declare it byte dataBusOut[5] it works well.
what I am missing here
Debian,Mint,Ubuntu
Arduino Mega 2560
Arduino Nano
Arduino Duemilanove
MAC OS Montain Lion
Raspberry PI Model B

Arrch

byte data[4] gives you four elements: 0, 1, 2, & 3
byte data[5] gives you five elements: 0, 1, 2, 3, & 4

majenko

byte dataBusOut[4] has space for 4 elements (0 to 3).

byte dataBusOut[5] has space for 5 elements (0 to 4).

You are getting confused between the array size and the array range.

hugo007

Debian,Mint,Ubuntu
Arduino Mega 2560
Arduino Nano
Arduino Duemilanove
MAC OS Montain Lion
Raspberry PI Model B

Go Up