Hi, Im trying to keep a log of events in an array and use it to display messages to an lcd, but Im stuck finding the mistake in the following, the full example is attached. When a new item is added, it appears in both of the last two positions
void udpateMSGLog(int msgKey){ //FIFO, cycle the msglog and append new msgKey
Serial.println("udpateMSGLog");
for (int x=0; x<=(lcdLines); x++){
if(x==lcdLines){
msgLog[lcdLines] = msgKey;
Serial.print(lcdLines);Serial.print(" ");Serial.println(msgLog[lcdLines]);
}else{
msgLog[x]=msgLog[x+1];
Serial.print(x);Serial.print(" ");Serial.println(msgLog[x]);
}
}
}
Please point out my glaring mistakes I cant see them
Thanks
itnoworking:
Hi, Im trying to keep a log of events in an array
}else{
msgLog[x]=msgLog[x+1];
}
That looks as if you are trying to move values along in the array. That is not the best way to do things. You should create a circular buffer and update the indices that point to the head and tail of the buffer. That way there is no need to move the actual values.
The index for the tail should always point to the array element that can next be written to. Consequently the function to place a new value in the buffer would be as simple as
Many thanks, your method is clearly much more efficient.
My requirement is to monitoring temperatures and display an lcd message log detailing what previous condition occurred at the last x events. Each condition has char[] message in a 2d array, the index for the message is stored in the log and each log entry displayed on the appropriate lcd line. I think I would want to include a headNdx to keep a rolling log.
My original, now redundant, piece of code had a bug where new events were entered on the last two msgLog[] cells, I had ASSumed that this was due to incorrectly referencing the cells but was not able to find the cause. Can anyone point out where I have make the mistake as I would like to understand where I was going wrong.
itnoworking:
My original, now redundant, piece of code had a bug where new events were entered on the last two msgLog[] cells, I had ASSumed that this was due to incorrectly referencing the cells but was not able to find the cause. Can anyone point out where I have make the mistake as I would like to understand where I was going wrong.
The original problem was caused by your code exceeding the bounds of the msgLog array. When you declared msgLog as having three elements, those elements are 0, 1, and 2, but in your code, in the for() statements, you are setting x to 0, 1, 2, and 3. You got lucky, and the code doesn't crash when you write a value to msgLog[3], but it would appear that the value you were appending to the array just happened to be stored at that memory location, so got copied to msgLog[2] when you were shifting the array, creating the duplicate entry at the end.