XRAD
Well-known member
I have tried many variations of FADE and BLINK non blocking code (not just what is here below), but the same issue persists. Either will work fine without the other in the loop. The FADE and BLINK functions do not work together in the loop, and the FADE seems to block the LED display. I'm confused and not sure how to correct the issue. I have reviewed in depth the libraries and there does not seem to be anything obvious that is causing this issue. I am getting accurate distance reads. I can flag the distance and that works fine. Maybe it's an internal timer conflict?? Any help much appreciated!!
Hardware: Teensy 4.0, standard 5v LEDs with 200 ohm resistors. HC-SR04 ultrasoud detector.
Hardware: Teensy 4.0, standard 5v LEDs with 200 ohm resistors. HC-SR04 ultrasoud detector.
Code:
#include <LEDFader.h>
#include <Ultrasonic.h>
Ultrasonic ultrasonic(2, 20);//trig, output
int distance;
unsigned long US_Distance_Ping_Timer = 0;
unsigned long LED_BLINK_Timer = 0;
const int LED_RIGHT_EYE = 4;
const int LED_LEFT_EYE = 3;
int ledState = LOW;
#define LED_NUM 2
LEDFader leds[LED_NUM] = {
LEDFader(LED_RIGHT_EYE),
LEDFader(LED_LEFT_EYE)
};
unsigned long currentMillis = 0;
//array of subjective milli run times
int MillisRunLengthTime[7] = { 20, 200, 800, 1000, 1500, 2000, 2500 };
//this is the key timer function, can use for MANY functions
boolean RunForThisAmountOfTime(unsigned long &startNowTimer, int runLengthTime) {
currentMillis = millis();
if (currentMillis - startNowTimer >= runLengthTime) {
startNowTimer = currentMillis;
return true;
} else return false;
}
void setup() {
pinMode(LED_RIGHT_EYE, OUTPUT);
pinMode(LED_LEFT_EYE, OUTPUT);
}
void loop() {
if (RunForThisAmountOfTime(US_Distance_Ping_Timer, MillisRunLengthTime[1])) {
distance = ultrasonic.read();
Serial.print("Distance in CM: ");
Serial.println(distance);
}
if (distance <= 25) {
BLINK();
} else {
FADER();
}
}
void BLINK() {
if (RunForThisAmountOfTime(LED_BLINK_Timer, MillisRunLengthTime[3])) {
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(LED_RIGHT_EYE, ledState);
digitalWrite(LED_LEFT_EYE, ledState);
}
}
void FADER() {
for (byte i = 0; i < LED_NUM; i++) {
LEDFader *led = &leds[i];
if (distance <= 25) {
BLINK();
} else {
led->update();
}
if (led->is_fading() == false) {
if (led->get_value() == 0) {
led->fade(255, 1000);
} else {
led->fade(0, 1000);
}
}
}
}