0

Neotrellis blink without delay
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

Neotrellis blink without delay

by airoptix on Tue Feb 12, 2019 7:56 am

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 | TOGGLE FULL SIZE
  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);
  }

airoptix
 
Posts: 14
Joined: Fri Apr 13, 2018 11:24 am

Re: Neotrellis blink without delay

by adafruit_support_mike on Fri Feb 15, 2019 3:00 am

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

Code: Select all | TOGGLE FULL SIZE
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 | TOGGLE FULL SIZE
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 | TOGGLE FULL SIZE
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
    }
}

adafruit_support_mike
 
Posts: 55974
Joined: Thu Feb 11, 2010 2:51 pm

Please be positive and constructive with your questions and comments.