[英]Using global variables in MSP430 code
我目前正在上一门使用MSP430g2553的微处理器课程,并且我注意到我们的教授编写的示例C代码充分利用了全局变量。
这背后的原因是什么?
(一直有人告诉我,仅在绝对必要时才使用全局变量,因此我认为有关微处理器的结构使它们成为必需。)
更新:我忘了包括示例代码。 这是我们在课堂上看到的一个早期的示例c程序:
#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")
根据MSP430数据表,它具有高达512 KB的闪存(用于程序存储)和66 KB的ram(用于数据存储)。 由于您未提供任何代码示例,因此您的教授很有可能希望以最佳方式使用ram。 可能声明了一些函数,使用相同的数据作为输入,或者他只是在全局区域中定义了变量,而没有考虑任何性能问题并且完全是无意的(我不这么认为,但这也是一种可能性)。 您应注意的重要一点是,始终尝试以有效的方式使用这些有限的资源,尤其是在嵌入式设备上。
微控制器没有什么特别的要求全局变量。 出于所有相同的原因,全局变量在嵌入式系统中是不可取的,而在其他系统中则是不可取的。 Jack Ganssle在他关于全球的博客文章中解释了原因。
是的,微控制器的RAM数量有限,但这并不是自由使用全局变量的借口。
询问您的老师为什么他/她使用全局变量。 也许您的讲师比演示良好的软件设计更关心教您有关微处理器的知识。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.