Neotrellis blink without delay

General project help for Adafruit customers

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
User avatar
airoptix
 
Posts: 14
Joined: Fri Apr 13, 2018 11:24 am

Neotrellis blink without delay

Post by airoptix »

I'd like to blink a neotrellis pixel without delay.
So far I found out this code for example, but it causes problems while going through the loop (too much delay at the same time at different buttons).

So I would need something that can blink a pixel without this long painful code and no delay command.

Code: Select all

  if (x == 4) { 
    Serial.println ("button 5 pressed");
    trellis.pixels.setPixelColor(4, 100, 255, 40);
    trellis.pixels.show();
    delay(150);
    trellis.pixels.setPixelColor(4, 0, 0, 0);
    trellis.pixels.show();
    delay(150);
  } else {
    trellis.pixels.setPixelColor(4, 10, 20, 10);
    trellis.pixels.show();
    delay(10);
    trellis.pixels.setPixelColor(4, 0, 0, 0);
    trellis.pixels.show();
    delay(10);
  }

User avatar
adafruit_support_mike
 
Posts: 67485
Joined: Thu Feb 11, 2010 2:51 pm

Re: Neotrellis blink without delay

Post by adafruit_support_mike »

The basic idea of BlinkWithoutDelay is to wrap the timed actions inside a conditional that checks the value of millis():

Code: Select all

uint32_t next_blink = 0;
uint32_t blink_interval = 1000;

void loop () {
    uint32_t now = millis();
    
    if ( now > next_blink ) {
        next_blink += blink_interval;
        //  control the LEDs
    }
}
One nice feature of that approach is that you can have multiple timers operating in parallel:

Code: Select all

uint32_t next_2_per_second = 0;
uint32_t half_second = 1000 / 2;

uint32_t next_3_per_second = 0;
uint32_t third_second = 1000 / 3;

void loop () {
    uint32_t now = millis();
    
    if ( now > next_2_per_second ) {
        next_2_per_second = now + half_second;
        //  toggle LED 1 on or off
    }
    if ( now > next_3_per_second ) {
        next_3_per_second = now + third_second;
        // toggle LED 2 on or off
    }
}
You can also use multiple timers to control different parts of an operation:

Code: Select all

uint32_t next_on = 0;
uint32_t time_on = 200;

uint32_t next_off = 0xffffffff;
uint32_t time_off = 300;

void loop () {
    uint32_t now = millis();
    
    if ( now > next_on ) {
        next_on = 0xffffffff;  // don't enter this block again until next_on has been set to a lower value
        next_off = now + time_on;
        //  turn the LED on
    }
    if ( now > next_off ) {
        next_off = 0xffffffff;  // don't enter this block again until next_off has been set to a lower value
        next_on = now + time_off
        // turn the LED off
    }
}

Locked
Please be positive and constructive with your questions and comments.

Return to “General Project help”