Marta
Marta

Reputation: 1

Can I simplify my C code for checking if the pin is set?

The first pin of PortD is HIGH at the beginning. When the first 4 pins of PortA are HIGH, set the second pin of PORTD HIGH, and the first LOW.

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

Upvotes: 0

Views: 1129

Answers (3)

sunriax
sunriax

Reputation: 821

Maybe an other solution would be to use a switch e.g:

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

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

Upvotes: 0

Ibram Reda
Ibram Reda

Reputation: 2820

//..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...
}

Upvotes: 1

Terje D.
Terje D.

Reputation: 6315

You can test the 4 lower pins of port A simultaneously with (PINA & 0x0f) == 0x0f. Then you can set the lower 2 bits of PORT D to 01 using PORTD = (PORTD & ~3) | 2; Thus the code becomes

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

or equally

if((PINA & 0x0f) == 0x0f){
    PORTD = (PORTD & ~3) | 2;
}

Upvotes: 1

Related Questions