7 segment display counter without delay()

Hello, I am trying to make a display that counts down from 6 to 0. Firstly I had it working with a simple delay(), however for school we can't use the delay(). Therefore we have to use a so called "Software Timer".

The software timer is pretty simple to understand. So I thought it was pretty easy to implement it in my code, well, that wasn't true for me atleast lol

For everytime time passes the array index should up with 1, only this does not work. In the serial monitor I can see that it only goes up one index in the array, and it only does this one time. So it does not fully iterate through the whole array.

The code I was talking about could be found in the "void loop()"

Here is full code:

const int DATAPIN = 4;  
const int LATCHPIN = 3; 
const int CLOCKPIN = 2; 

byte nrOfPatterns = 7;
int display_countdown[] = {
  B10111110, //digit 6
  B10110110, //digit 5
  B01100110, //digit 4
  B11110010, //digit 3
  B11011010, //digit 2
  B01100000, //digit 1
  B11111100  //digit 0
};

const int INTERVAL = 1000;
unsigned long int previousMillis;

void setup() {
  Serial.begin(9600);

  pinMode(DATAPIN, OUTPUT);
  pinMode(LATCHPIN, OUTPUT);
  pinMode(CLOCKPIN, OUTPUT);
}

void loop() {
  unsigned long currentMillis = millis();
  int arrayIndex = 0;

  if (currentMillis - previousMillis >= INTERVAL) {
    previousMillis = currentMillis;

    //If time passed do this function and up the arrayIndex with 1
    myfnUpdateDisplay(arrayIndex);
    arrayIndex++;

    //When it goes "out of bounds" put the array index back to 0
    if (arrayIndex > 7) {
    arrayIndex = 0;
    }
    
    Serial.println(arrayIndex);
  }
}

void myfnUpdateDisplay(byte pattern) {
  digitalWrite(LATCHPIN, LOW);
  shiftOut(DATAPIN, CLOCKPIN, LSBFIRST, display_countdown[pattern]); 
  digitalWrite(LATCHPIN, HIGH); 
}

I been really struggling with this the past hours, so if someone can help me overcome this problem I would be super thankful : )

Thanks in advance!

Demonstration code for several things at the same time - Using Arduino / Project Guidance - Arduino Forum

void loop() {
  unsigned long currentMillis = millis();
  int arrayIndex = 0;

The variable arrayIndex is reset to zero every pass through loop(). Make the variable "static" to maintain it between passes

As well, this check:

    //When it goes "out of bounds" put the array index back to 0
    if (arrayIndex > 7) {
    arrayIndex = 0;

is wrong: You only have 6 entries in your table, indexed from 0 to 5. You should the index to zero on when it reaches '6'.

1 Like

Well damn, thank you!

Putting static in front of the arrayIndex worked.

And thank you for also noticing the other if statement : )