Rob013
Rob013

Reputation: 1

Arduino bitwise runninglight with a single delay

I have the assignment to create a running light on my Arduino with the following requirements/constraints

Requirements

Constraints

I have tried the following code

    #include <Arduino.h>
    
    //mask for setting correct bits in register to setup leds to 1
    #define DDBMASK 0x07
    
    //masks for setting correct bits in register for led control to 1
    #define LEDMASK 0x01
    
    byte *ddBPtr;   //point to ddB register (data direction)
    byte *portBPtr; //point to portB resiger (data register)
    
    void setup() {
      //setup data direction register to set pins to output
      ddBPtr = (byte *) 0x24;
      *ddBPtr |= DDBMASK; // 0b0000 0111
    
      //assign pointer to right register
      portBPtr = (byte *) 0x25;
    }
    
    void loop() {
      //use data register (portB) for controlling leds
      *portBPtr ^= LEDMASK;
      delay(500);
      *portBPtr ^= LEDMASK;
    
      *portBPtr ^= LEDMASK << 1;
      delay(500);
      *portBPtr ^= LEDMASK << 1;
    
      *portBPtr ^= LEDMASK << 2;
      delay(500);
      *portBPtr ^= LEDMASK << 2;
}

Apparently this is possible with only one delay function and following the requirements and constrains. I have been stuck on this for hours and cant figure it out.

I tried the following which also does not work because I'm unable to reset my counter back to zero

void loop() {
  //use data register (portB) for controlling leds
  *portBPtr ^= (LEDMASK << ledCount);
  delay(500);
  *portBPtr ^= (LEDMASK << ledCount);
  ledCount++;
  //cant figure out a way to reset ledCount back to 0 after 3 iterations
  //running light only runs once so first led does not light after third led is lit
}

What am I missing?

Upvotes: 0

Views: 175

Answers (1)

Paul Hankin
Paul Hankin

Reputation: 58339

Perhaps this:

*portBPtr |= (1 << ledCount);
delay(500);
*portBPtr &= ~(1 << ledCount);
ledCount = (9 >> (ledCount << 1)) & 3;

This also avoids ^ which is not in your list of allowed symbols.

The line ledCount = (9 >> (ledCount << 1)) & 3 is like a lookup table with each entry taking up two bits. It maps 0 to 1, 1 to 2, 2 to 0. The normal way to write this code is ledCount = (1 + ledCount) % 3;

This might also work, being a little simpler:

delay(500);
*portBPtr = (1 << ledCount);
ledCount = (9 >> (ledCount << 1)) & 3;

By using assignment rather than | or & or ^, all the other bits will be zero, presumably causing the non-current leds to turn off.

Upvotes: 0

Related Questions