繁体   English   中英

您将如何使用结合了 3 个二进制输入的 switch 语句? (C)

[英]How would you use a switch statement with a combination of 3 binary inputs? (C)

我在 C 中编写 PIC18F252 微控制器。 该程序应从传感器获取 3 个单独的输入(首先通过 ADC 运行),然后根据这 3 个输入的组合,它将来自 switch 语句的 select 和 output。 因此,例如,如果每个传感器输出一个 0,我想 select 案例 '000' 并执行其指令。 如果中间传感器输出 1,我想要 case 010 等。

我已经研究过使用 arrays 或字符串来存储 3 个字符值,但我似乎无法正确使用 switch 语句来比较输入与案例。

似乎 if/else 语句会是一种更简单的方法,但我需要使用 switch。

那么谁能告诉我是否可以将数组或字符串与案例进行比较,或者是否有其他方法可以做到这一点? 我能想到的唯一其他方法是将输入组合分配给一个单词变量,但这需要一个 switch 或 if/else 自己的语句。

如果输入值是数字值(0 或 1),您可以通过位移和按位或将这些位组合成一个数字。

例子:

int input1 = 0;
int input2 = 1;
int input3 = 1;
int combined;

/* assuming the values can be 0 or 1 only */
combined = input1 | ( input2 << 1 ) | ( input3 << 2 );
/* or with any non-zero value as TRUE */
combined = (input1 ? 1 << 0 : 0) | (input2 ? 1 << 1 : 0) | ( input3 ? 1 << 2 : 0);

switch(combined)
{
case 0x0: // or GCC extension 0xb000
case 0x1: // or GCC extension 0xb001
case 0x2: // or GCC extension 0xb010
case 0x3: // or GCC extension 0xb011
/* ... */
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM