Search code examples
arduinovoid

Arduino Void Loop


For class, I developed the following code. My teacher, on the other hand, wants me to condense it. If anyone has any recommendations, I would be grateful. Thanks.

    void setup()
{
  DDRD = 0b11111111;
  DDRB = 0b00000001;
}

void loop()
 
{
  PORTD = 0b00000001;
  PORTB = 0b00000000;
  delay(t);
  PORTD = 0b00000010;
  PORTB = 0b00000000;
  delay(t);
  PORTD = 0b00000100;
  PORTB = 0b00000000;
  delay(t);
  PORTD = 0b00001000;
  PORTB = 0b00000000;
  delay(t);
  PORTD = 0b00010000;
  PORTB = 0b00000000;
  delay(t);
  PORTD = 0b00100000;
  PORTB = 0b00000000;
  delay(t);
  PORTD = 0b01000000;
  PORTB = 0b00000000;
  delay(t);
  PORTD = 0b10000000;
  PORTB = 0b00000000;
  delay(;
  PORTD = 0b00000000;
  PORTB = 0b00000001;
  delay(t);
  
}


Solution

  • This should loop through the values you want to set PORTD to. It shifts the '1' bit once for every loop, and because bitval can only hold a byte (8 bits) the eighth shift will make bitval zero, ending the loop.

    void loop()
    {
        for (byte bitval = 1; bitval != 0; bitval <<= 1)
        {
            PORTD = bitval;
            PORTB = 0;
            delay(t);
        }
        PORTD = 0;
        PORTB = 1;
        delay(t);
    }