Search code examples
cglobal-variablesmicrocontrollermicroprocessors

Using global variables in MSP430 code


I'm currently taking a microprocessors course that uses the MSP430g2553 and I've noticed that the example C code our professor writes makes extensive use of global variables.

What would be the reasoning behind this?

(I've always been told to use globals only when absolutely necessary, so I assume something about the structure of microprocessors makes them necessary.)

UPDATE: I forgot to include sample code. Here's an early example c program we saw in class:

#include <msp430g2553.h>

volatile unsigned int blink_interval;  // number of WDT interrupts per blink of LED
volatile unsigned int blink_counter;   // down counter for interrupt handler

int main(void) {
  // setup the watchdog timer as an interval timer
  WDTCTL =(WDTPW + // (bits 15-8) password
                   // bit 7=0 => watchdog timer on
                   // bit 6=0 => NMI on rising edge (not used here)
                   // bit 5=0 => RST/NMI pin does a reset (not used here)
           WDTTMSEL + // (bit 4) select interval timer mode
           WDTCNTCL +  // (bit 3) clear watchdog timer counter
                  0 // bit 2=0 => SMCLK is the source
                  +1 // bits 1-0 = 01 => source/8K
           );
  IE1 |= WDTIE;     // enable the WDT interrupt (in the system interrupt register IE1)

  P1DIR |= 0x01;                    // Set P1.0 to output direction

  // initialize the state variables
  blink_interval=67;                // the number of WDT interrupts per toggle of P1.0
  blink_counter=blink_interval;     // initialize the counter

  _bis_SR_register(GIE+LPM0_bits);  // enable interrupts and also turn the CPU off!
}

// ===== Watchdog Timer Interrupt Handler =====
// This event handler is called to handle the watchdog timer interrupt,
//    which is occurring regularly at intervals of about 8K/1.1MHz ~= 7.4ms.

interrupt void WDT_interval_handler(){
  if (--blink_counter==0){          // decrement the counter and act only if it has reached 0
    P1OUT ^= 1;                   // toggle LED on P1.0
    blink_counter=blink_interval; // reset the down counter
  }
}
ISR_VECTOR(WDT_interval_handler, ".int10")

Solution

  • There is nothing special about microcontrollers that makes global variables necessary. Global variables are undesirable in embedded systems for all the same reasons they're undesirable in other systems. Jack Ganssle explains the reasons in his blog post on globals.

    Yes, microcontrollers have a limited amount of RAM but that's not an excuse to use global variables freely.

    Ask your instructor why he/she is using global variables. Perhaps your instructor is more concerned with teaching you about microprocessors than demonstrating good software design.