我可以简化我的 C 代码来检查是否设置了引脚吗?

问题描述

PortD 的第一个管脚一开始是高电平。当PortA的前4脚为HIGH时,将PORTD的第二脚置为HIGH,第一个置为LOW。

 `PORTD=0b00000001;
      
      if (PINA & (1<<0))
      {
          if (PINA &(1<<1))
          {
              if(PINA &(1<<2))
              {
                  if(PINA &(1<<3))
                  {
                      PORTD=0b00000001;
                  }
              }
          }
      }`

解决方法

您可以用(PINA & 0x0f) == 0x0f同时测试端口A的4个较低引脚。 然后你可以使用 PORTD = (PORTD & ~3) | 2; 将 PORT D 的低 2 位设置为 01 这样代码就变成了

if((PINA & 0b00001111) == 0b00001111){
    PORTD = (PORTD & 0b11111100) | 0b00000010;
}

或同等

if((PINA & 0x0f) == 0x0f){
    PORTD = (PORTD & ~3) | 2;
}
,
//..intialization code...
PORTD=0b00000001; // initialize of port D
while(true){
  //... your code body...
  if((PINA & 0x0f) == 0x0f){ // if first 4 bit are high
      PORTD |=(1<<PD1); //set pd1 to high
      PORTD &=~(1<<PD0); // set pd0 to low
  }
  else{
      // here put what you like to do if the 4 bit not High
      // if there is nothing to do delete the else

  }
  //... your code body...
}
,

也许另一种解决方案是使用开关,例如:

DDRD = (1<<PIND1) | (1<<PIND0);

switch ((PINA & 0x0F))
{
    case 0x0F:
      PORTD = (1<<PIND1);
      break;
    default:
      PORTD = (1<<PIND0);
      break;
}