【问题标题】:Program execution flow alternative to switch(){...} statementswitch(){...} 语句的替代程序执行流程
【发布时间】:2019-10-28 11:41:55
【问题描述】:

我正在尝试实现一个具有以下功能的程序。

SPI-Master 向 SPI-Slave 发送 3 个字节的数据。对于这些数据字节的某个值,将调用某些函数。例如FF FF FF调用函数A,FF FF FE调用函数B等等。

一种可能的解决方案可能是使用 switch case 语句,但是切换每个可能的情况会太长。有没有其他方法可以做到这一点?

例如,最后一个数据字节必须设置 PWM 占空比。

10 = 0000 1010
20 = 0001 0100
30 = 0001 1110
40 = 0010 1000
50 = 0011 0010
60 = 0011 1100
70 = 0100 0110
80 = 0101 0000
90 = 0101 1010 

从机接收最后一个字节,并且对于每种情况,它都必须设置占空比。第二个字节确定预分频器。例如:

0000 00001 0000 1010 将预分频器设置为1,将占空比设置为10
0000 00010 0000 1010 将预分频器设置为8,将占空比设置为10

等等。

所以可能有许多不同的组合,处理所有可能情况的最佳方法是什么?

【问题讨论】:

  • 没有足够的信息来回答。有哪些可能性?例如,如果它们只是两个 if 语句就足够了。如果有模式,您可以使用按位运算符。帮助我们,以便我们为您提供帮助。
  • 为什么会“太长”?您必须处理每种情况,因此任何处理的长度都是 O(N)。 (即:在其他情况下的数量)。
  • 请解释“每种可能的情况”。那里有多少?格式是什么?
  • 如果可能的话,您能否提供一些您目前拥有的代码?
  • 根据格式,您可以使用掩码来获取相关位并为这些(现在有限)数量的情况使用开关/大小写。

标签: c


【解决方案1】:

"...一个可能的解决方案可能是使用 switch case 语句,但是切换每个可能的情况会太长。有没有其他方法 这样做?”

对于您正在自动化的流程所需的每个独特但必需的功能,您将需要一个独特的方法(或方法系列)来完成它。 100 个不同的要求将需要实施 100 个不同的方法来满足这些要求。使用的构造取决于开发人员。状态机 (such as a switch statement within a while loop) 是一种常见的构造,用于通过许多不同的操作来控制执行流程。如果使用这个结构,它可能需要 100 个case: 部分。

如果由于某种原因不能接受 switch 语句,则不同的选项可能是函数指针数组。但是请注意,尽管此方法可能优于 switch/while 组合,但仍需要 独特功能之间的 1:1 相关性:要求:

int op0(int b1, int b2, int b3);
int op1(int b1, int b2, int b3);
int op2(int b1, int b2, int b3);
int op3(int b1, int b2, int b3);
//.... and so on depending on how many operations needed

enum {  // mnemonics with which to call array of function pointers.
   OP0,
   OP1,
   OP2,
   OP3,
   ....
};



int (*op[4]) (int b1, int b2, int b3);

int main(void) //or (int argc, char *argv[])
{
   //initialize function pointer address to implementations:
   op[0] = &op0;   
   op[1] = &op0;   
   op[2] = &op0;   
   op[3] = &op0;
   // and so on for every operation needed
   // other code in main
   return 0;
}

int op0(int b1, int b2, int b3)
{
    // code using b3 to set duty cycle
    // ...
    // code using b2 to set pre-scaler
    // ...
    // implement unique requirement of op0
    return 0;
}

int op1(int b1, int b2, int b3)
{
    // code using b3 to set duty cycle
    // ...
    // code using b2 to set pre-scaler
    // ...
    // implement unique requirement of op1
    return 0;
}

/// and so on...

【讨论】:

    【解决方案2】:

    简单的state machines?

    逐字节读取。如果第一个字节是0xff,则进入特定状态。如果下一个字节也是0xff,则进入另一个状态。如果下一个字节是0xff,则调用函数A,否则如果是0xfe,则调用函数B等。在第三个字节之后,回到原来的起始状态。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-19
      • 1970-01-01
      • 1970-01-01
      • 2022-07-18
      • 2019-06-18
      • 1970-01-01
      • 2019-09-16
      相关资源
      最近更新 更多