I'm mostly self taught in C. I program embedded micro controllers. (dsPIC33fj128gp804 for example) I generally use global variable and everything I've ever read denounces using global variables like they are a plague. I've been working on using less but there is a scenario that i don't know how not to use global variables.
The micro controller is equipped with interrupts. An interrupt is an event triggered externally in hardware. When the interrupts is triggered the execution of the main code stops, the current working variables are saved, a preassigned function is executed and then the main code picks back up where it left off. Because the interrupt is a stand alone function that can trigger at any time nothing can be passed into or out of the function.
For example when the UART hardware receives a byte of data, that data needs moved out of the hardware buffer before it gets over written.
void __attribute__((interrupt, no_auto_psv)) _U2RXInterrupt(void)
{
GlobalVariable = U2RXREG; // Move data to global variable
IFS4bits.U2RXIF = 0; // Clear the UART2 Receive Interrupt Flag
}
Is there a way to do this without global variables or is this an exception?