I use Neopixels (64 LEDs), and I have a function called level_up that gets different led_num each time. Generally, it is a level bar; level[1] will light all the LEDs in a sequence from 0 to 28, level[2] all the LEDs from 29 to 48, etc. The function I attached works fine, but I need to change the delay to millis() and not sure how. Any thoughts?
uint8_t level[] = {0, 28, 48, 60, 64}; //levels 0 to 4
void level_up(uint8_t wait, uint8_t led_num) {
uint8_t start_point;
if (led_num == level[1]) start_point = 0; //up from level 0 to 1
if (led_num == level[2]) start_point = 28; //up from level 1 to 2
if (led_num == level[3]) start_point = 48; //up from level 2 to 3
if (led_num == level[4]) start_point = 60; //...
for (uint8_t i = start_point; i < led_num; i++) {
strip.setPixelColor(i, strip.Color(0, 0, 255));
strip.show();
delay(wait); //TODO: change it to timer
}
}
void loop() {
if (plus_btn.pressed()) {
score++;
if (score >= 4) {
score = 4;
}
}
if (minus_btn.pressed()) {
score--;
if (score <= 0) {
score = 0;
}
}
switch (score) {
case 0:
if (last_score == 1) level_down(50, level[0]);
last_score = 0;
break;
case 1:
// if last_score was 0 make the blue effect because level is up
if (last_score == 0) level_up(50, level[1]);
// if last_score was 2 make the red effect because level is down
if (last_score == 2) level_down(50, level[1]);
last_score = 1;
break;
case 2:
if (last_score == 1) level_up(50, level[2]);
if (last_score == 3) level_down(50, level[2]);
last_score = 2;
break;
case 3:
if (last_score == 2) level_up(50, level[3]);
if (last_score == 4) level_down(50, level[3]);
last_score = 3;
break;
case 4:
winning_timer.start();
winning();
digitalWrite(WINNING_SENSOR_PIN, HIGH);
break;
}
Serial.println(score);
}
This doesn't answer your question directly, but the strategy that I use gives me any number of timed events without my program blocking in millis().
Set a deadline in the future and enclose the delayed action in an if statement that polls millis() until that deadline is reached. It's not perfect because the software timing loses time due to processing, and because of the millis() overflow and wrap-around issue (look it up on arduino.cc).