0

我想知道是否有一种方法可以将开关的输出连接到一个变量中,即我有开关 1、开关 2、开关 3 和开关 4,每个开关都是单独声明的,开关上的输出是开关 1 -0 开关2 -1 开关 3 -1 开关 4 -0

我想将这些输出加入一个变量,例如 switch_output = 0110,然后我想将其更改为自然数。

这可能吗??

谢谢

PS:这只是一个例子,我实际上是在尝试用 18 个开关来做到这一点,我正在使用的程序只允许我单独声明每个开关

这是它们的声明方式

static  const gpio_pin_t SW0 = { .port = 2, .pin = 0};
static  const gpio_pin_t SW1 = { .port = 2, .pin = 1};
static  const gpio_pin_t SW2 = { .port = 2, .pin = 2};
static  const gpio_pin_t SW3 = { .port = 2, .pin = 3};
static  const gpio_pin_t SW4 = { .port = 2, .pin = 4};
static  const gpio_pin_t SW5 = { .port = 2, .pin = 5};
static  const gpio_pin_t SW6 = { .port = 2, .pin = 6};
static  const gpio_pin_t SW7 = { .port = 2, .pin = 7};
static  const gpio_pin_t SW8 = { .port = 2, .pin = 8};
static  const gpio_pin_t SW9 = { .port = 2, .pin = 9};
static  const gpio_pin_t SW10 = { .port = 2, .pin = 10};
static  const gpio_pin_t SW11 = { .port = 2, .pin = 11};
static  const gpio_pin_t SW12 = { .port = 2, .pin = 12};
static  const gpio_pin_t SW13 = { .port = 2, .pin = 13};
static  const gpio_pin_t SW14 = { .port = 2, .pin = 14};
static  const gpio_pin_t SW15 = { .port = 2, .pin = 15};
static  const gpio_pin_t SW16 = { .port = 2, .pin = 16};
static  const gpio_pin_t SW17 = { .port = 2, .pin = 17};

Mahmoud Fayez 我尝试了你的解决方案,它在一定程度上有效,我得到的是自然数而不是二进制数,这里是输出的打印屏幕打印屏幕

这是代码,我确实不得不对其进行一些修改以使其正常工作

     for (i = 0; i < SwitchesCount; i++)
 {
     temp2 = GPIO_Get(Switches[i]);
     iResult = (iResult << 1) + temp2;
     printf ("%lu, ",temp2);
 }
printf ("\n iResult =  %lu \n",iResult);

static uint32_t iResult = 0;

uint32_t 是无符号长

4

1 回答 1

1

你可以试试这个:

const int SwitchesCount = 18;
int iResult = 0;
int i = 0;

static  const gpio_pin_t switches[SwitchesCount] = {{ .port = 2, .pin = 0}, { .port = 2, .pin = 1},{ .port = 2, .pin = 2}, { .port = 2, .pin = 3}, { .port = 2, .pin = 4}, { .port = 2, .pin = 5}, { .port = 2, .pin = 6}, { .port = 2, .pin = 7}, { .port = 2, .pin = 8}, { .port = 2, .pin = 9},{ .port = 2, .pin = 10}, { .port = 2, .pin = 11}, { .port = 2, .pin = 12}, { .port = 2, .pin = 13}, { .port = 2, .pin = 14}, { .port = 2, .pin = 15}, { .port = 2, .pin = 16}, { .port = 2, .pin = 17}};

for (i = 0; i < SwitchesCount; i++)
{
    iResult = iResult << 1 + switches[i]; 
}
// you now have iResult with the value you are looking for.
于 2012-08-25T14:19:11.293 回答