Building upon my previously solved question Ultrasonic Sensor range finder help (Solved).
Is there a better way to make the LED blink than using a delay and stopping all the rest of the code? For example, the LED is set to turn on, then shortly after turn off. Is there a better way to do this?
For example, if the LED is turned on, it then delays the code, which means it has to wait for the delay to be over, turn off, then change its pattern. For example, allow the Arduino to interrupt the blink with a new interval blink, mid blink? I'm sorry if this is confusing, it's tough to explain.
Simply put, is there a better function than delay()
that can allow the Arduino to suddenly change the state of the LED while it is waiting on a delay()
to finish?
The code I'm working on is this:
#include <NewPing.h>
#define TRIGGER_PIN 15
#define ECHO_PIN 2
#define MAX_DISTANCE 500
int LED1 = 3;
int LED2 = 16;
int LED3 = 9;
int LED4 = 6;
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
pinMode(LED4, OUTPUT);
}
void loop() {
delay(50);
unsigned int uS = sonar.ping_median(10);
int IN = sonar.convert_in(uS);
if (IN <= 5) {
analogWrite(LED4, 255);
delay(100);
analogWrite(LED4, 0);
} else if (IN >= 5 && IN <= 12) {
analogWrite(LED4, 1);
delay(200);
analogWrite(LED4, 0);
} else if (IN >= 13) {
analogWrite(LED4, 100);
delay(300);
analogWrite(LED4, 0);
}
}