4 c microcontroller operating-system
我在执行for循环时遇到问题,我创建了一个包含已定义值的静态表,然后将我的表作为参数传递给要处理的函数.基本上我的代码如下所示:
#define ID_01 0x0000
#define ID_02 0x0001
#define ID_03 0x0002
#define ID_04 0x0003
#define ID_05 0x0004
#define ID_06 0x0005
#define ID_07 0x0006
#define ID_08 0x0007
#define ID_09 0x0008
/*...
*/
#define ID_LAST 0xFFFF
static char table[]={
ID_01, ID_02 ,ID_03, ID_04, .... , ID_LAST}
void process( char *table){
int LastId=0;
char *Command;
for ( Command=table; LastId==0 ; Command++){
switch(Command)
{
case ID_01:
do_stuff01();
break;
case ID_02:
do_stuff02();
break;
...
case ID_LAST:
LastId=1;
break;
default:
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我试图打印一些消息进行调试,但程序不执行任何打印,即使是在循环之前和之后的那些.
但是当我把for循环改为:
for(i=0;i<10;i++)
Run Code Online (Sandbox Code Playgroud)
所有的信息都打印出来了.但我必须以与我一开始相同的方式处理.
PS:这部分代码是在运行到微控制器的操作系统任务中执行的,我只是一个初学者.
现在,您正在使用switch (Command),其中Command持有地址OD table变量.
更改switch到
switch (*Command) { //Use value at pointed Command.
}
Run Code Online (Sandbox Code Playgroud)
请注意,在进行*Command取消引用时char,这是1byte.您的ID有2个字节,因此您丢失了数据.
更改:
static char table[] = {ID_01, ID_02 ,ID_03, ID_04, .... , ID_LAST}
Run Code Online (Sandbox Code Playgroud)
短路以获得16位值
static unsigned short table[]={ID_01, ID_02 ,ID_03, ID_04, .... , ID_LAST}
Run Code Online (Sandbox Code Playgroud)
稍后,修改您的process功能以接受unsigned short
void process( const unsigned short *table) { //Unsigned short
int LastId = 0;
unsigned short *Command; //Unsigned short
for ( Command=table; LastId==0 ; Command++){
switch(*Command) { //Added star
//...
}
}
//...
Run Code Online (Sandbox Code Playgroud)
我会将您的process代码重写为:
void process(const unsigned short *table, size_t tableLen) {
while (tableLen--) {
switch (*table) {
case ID_1: /* Do stuff */ break;
}
table++; //Increase pointer to next ID element
}
}
//Usage then like this:
static unsigned short table[] = {ID_1, ID_2, ID_3, ..., ID_n};
//Put pointer and length of table
process(table, sizeof(table)/sizeof(table[0]));
Run Code Online (Sandbox Code Playgroud)