I am working on a project where I want to control RGB LEDS with a HC-SR04 sensor. Essentially what will happen is my RGB LEDS will go through a fade, but once my sensor detects an object within 31cm of it, the fade will stop and the leds will just be red.
I have a sketch that does what I mentioned above, but the sensor will not send or retrieve a signal as long as the fade is happening. So I have to wait for the fade to complete a cycle before the sensor will send out another signal. My professor told me I should look into interrupts but I'm not sure which one I should use or how they essentially work.
How would I go about using an interrupt in my project? Should I even use an interrupt? Does my code just need to be re-worked?
// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------
#include <NewPing.h>
#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 11 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
#define REDPIN 5
#define GREENPIN 6
#define BLUEPIN 3
#define FADESPEED 2
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
void setup() {
pinMode(REDPIN, OUTPUT);
pinMode(GREENPIN, OUTPUT);
pinMode(BLUEPIN, OUTPUT);
Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}
void loop() {
int r, g, b;
delay(1000); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
Serial.print("Ping: ");
int DIS = uS / US_ROUNDTRIP_CM;
Serial.print(DIS); // Convert ping time to distance in cm and print result (0 = outside set distance range)
Serial.println("cm");
if (31>=DIS && DIS>0) {
r = 255;
analogWrite(REDPIN, r);
}
else
{
for (r = 0; r < 256; r++) {
analogWrite(REDPIN, r);
delay(FADESPEED);
}
// fade from violet to red
for (b = 255; b > 0; b--) {
analogWrite(BLUEPIN, b);
delay(FADESPEED);
}
// fade from red to yellow
for (g = 0; g < 256; g++) {
analogWrite(GREENPIN, g);
delay(FADESPEED);
}
// fade from yellow to green
for (r = 255; r > 0; r--) {
analogWrite(REDPIN, r);
delay(FADESPEED);
}
// fade from green to teal
for (b = 0; b < 256; b++) {
analogWrite(BLUEPIN, b);
delay(FADESPEED);
}
// fade from teal to blue
for (g = 255; g > 0; g--) {
analogWrite(GREENPIN, g);
delay(FADESPEED);
}
}
}