We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
I have a strange problem in interrupt, I am incrementing a variable in interrupt and displayng in main program, the code is working fine for some time , latter the system gets hanged , i dont know why??
if there is any solution to this problem plz let me know, I am using Silabs C8051F120
int var=0; void PCA_Timer_Interrupt(void) interrupt 9 using 2 { var++; } void main() { sprintf(buffer,"%d",(int)var); display(buffer,LINE1); }
"I am incrementing a variable in interrupt and displayng in main program"
Consider your situation: you have a multibyte variable that is being changed in the interrupt. This means that the interrupt will break in the middle of any operation you may be doing with the variable in the main program. That alone will not necessarily crash your program, but might, depending for example on how you are relying on domain values in your variable.
For instance, if you var is 0x00ff, your main program begins to process it by taking the LSB (0xFF). Then the interrupt kicks in and change the value to 0x0100. On return, the main program takes the MSB, which is now 0x01, thus getting the value 0x01FF, instead of 0x0100. Now let's say you use the value as an array subscript, or pointer offset. That will shure produce a wild pointer and if you are lucky will crash your program.
This is NOT a 'problem' with the compiler or the CPU, it is an effect of shared variables in multitasking systems. You should never share variables in this manner. Search the internet for "atomic operations" for detailed descriptions of what to do.
Another warning: your handler is compiled with register bank 2 function usage. If you have other functions with bank2 in the main program, your system may crash, and that has nothing to do with the shared var problem.
Now let's say you use the value as an array subscript, or pointer offset.
He isn't using the var as an array subscript or a pointer offset,is he?
"He isn't using the var as an array subscript or a pointer offset,is he?"
Well, he hasn't shown any code that does that - but then the code that he has shown doesn't make sense, does it?
Jonny was just proposing an example of one way that could lead to crashing the program