在我的(个人)嵌入式项目中,全局变量正在堆积.我需要从ISR(中断服务程序)和/或菜单系统(这样它们可以由用户修改)访问这些变量,但同时我想避免使用太多的全局变量.
因为它们可以按模块分组,所以我认为我可以将它们封装在它们自己的.c文件中,声明为staticor static volatile,并向外界展示一些处理它们的函数.
沿线的东西:
在module1.c中
#include module1.h
static volatile int module1_variable;
int getModule1Var(void){
return module1_variable;
}
void setModule1Var(int i){
//some code to disable interrupts for atomic operations
module1_variable = i;
//some other code to re-enable interrupts
return;
}
Run Code Online (Sandbox Code Playgroud)
module1.h将包含函数原型,结构和所有其他元素,使模块工作除了当然的静态变量定义
在main.c中
#include module1.h
void main(){
//setting the variable value, could be done from a menu
setModule1Var(15);
//remaining application code
}
void generic_ISR(){
//trivial usage example
doSomething(getModule1Var());
return;
}
Run Code Online (Sandbox Code Playgroud)
该方案自然会扩展到其他模块.
现在我的问题是:
这是一个好方法吗?简单地拥有一堆全局变量是一样的吗?有什么主要缺点吗?
我还认为我可以使用某种混合,例如仍然具有全局变量以允许ISR直接操作(因为来自ISR的函数调用有时不受欢迎)以及其他所有情况下的函数.这会更好吗?
我这里有一个新问题.我还在学习PIC for PIC(xc8编译器),作为一个初学者项目,我正在使用流行的ds18b20温度计和我躺在的pic16f628.我的程序在允许运行时确实表现良好,但是当我正在使用指针,结构,数组等来返回函数中的多个值时,我注意到有些东西变得乱七八糟,现在PC来回不允许程序按顺序运行,至少就是我在mplabx中使用模拟器时看到的内容.我很确定我已经忘记了程序和/或内存位置,但我无法弄清楚是什么或为什么.有人能帮我吗?我在这里粘贴主要代码,你还需要什么?
/*
* File: termometro.c
* Author: zakkos
* Created on April 18, 2013, 2:20 PM
*
* /
/*ESSENTIAL DEFINITIONS*/
#define _XTAL_FREQ 4000000
/*INCLUSIONS*/
#include <xc.h>
#include <stdio.h>
#include <stdlib.h>
#include <lcd.h>
#include <1-wire.h>
/*CONFIG PRAGMA*/
#pragma config BOREN = OFF, CPD = OFF, FOSC = INTOSCIO, MCLRE = OFF, WDTE = OFF, CP = OFF, LVP = OFF, PWRTE = ON
//typedef unsigned char uint8_t;
void read_temp(void);
union {
char eratura;
char decimali;
}temps;
int main(void) …Run Code Online (Sandbox Code Playgroud) 我在函数内部遇到了这个结构(e是传递给函数的参数):
short (*tt)[][2] = (short (*)[][2])(heater_ttbl_map[e]);
Run Code Online (Sandbox Code Playgroud)
及其用法(其中i是for循环中的计数器):
(*tt)[i][0]
Run Code Online (Sandbox Code Playgroud)
我想我得到了作业的第一部分:
short (*tt)[][2]
Run Code Online (Sandbox Code Playgroud)
据我所知,tt被声明为指向一组短裤阵列的指针.第二部分令我感到困惑,看起来像是某种演员,但我不确定我理解它的作用,尤其是:(*).它是如何工作的?
heater_ttbl_map声明如下(其中pointer1和pointer2都是shortimensional shortet数组):
static void *heater_ttbl_map[2] = {(void*)pointer1, (void*)pointer2};
Run Code Online (Sandbox Code Playgroud)
至于它的使用我理解tt指向的是被解引用(并且它是数组的i索引的第三个索引的内容,这是一个简短的)但是为什么这样写:
(*tt)[i][0]
Run Code Online (Sandbox Code Playgroud)
而不是这样的:
*tt[i][0]
Run Code Online (Sandbox Code Playgroud)
是因为tt不是数组本身而是指向数组的指针?