Hi,
I'm doing a project involving 4 ultrasonic sensors (input, HC-SR04) and an RGB LED (output). I'm wanting the sensors to know when and if one is sensing something, and to always take the closest sensors value to the output.
I'm also wanting to use the full spectrum of the RGB LED hence the map function. And I am using 'if', 'else' to outline the scenarios for the sensors. I have looked at arrays here:
http://forum.arduino.cc/index.php?topic=57664.0
But it doesn't help me in applying the sensor values to the LED.
There is tons of examples online of sensors and RGB LED's but after tinkering with code for a long time I had to post for some help.
Here's the code I have so far, it is working perfectly with 1 sensor but would like some help in adding more. Thanks.
#define echoPin 6 // Echo Pin
#define trigPin 7 // Trigger Pin
#define LEDPin1 3 // Onboard LED1
#define LEDPin2 4 // Onboard LED2
#define LEDPin3 5 // Onboard LED3
int maximumRange = 200; // Maximum range needed
int minimumRange = 0; // Minimum range needed
int ultraValue = 0; // sensors numerical value
long duration, distance; // Duration used to calculate distance
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LEDPin1, OUTPUT); // Use LED indicator (if required)
pinMode(LEDPin2, OUTPUT);
pinMode(LEDPin3, OUTPUT);
}
void loop() {
/* The following trigPin/echoPin cycle is used to determine the
distance of the nearest object by bouncing soundwaves off of it. */
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
//Calculate the distance (in cm) based on the speed of sound.
distance = duration/58.2;
if (distance >= maximumRange || distance <= minimumRange){
/* Send a negative number to computer and Turn LED ON
to indicate "out of range" /
Serial.println("-1");
digitalWrite(LEDPin1, HIGH);
}
else {
/ Send the distance to the computer using Serial protocol, and
turn LED OFF to indicate successful reading. */
Serial.println(distance);
digitalWrite(LEDPin1, LOW);
}
if (distance > 20) {
digitalWrite(LEDPin1, LOW);
} else {
analogWrite(LEDPin1, map(distance, 40, 0, 0, 255));
}
if (distance > 60) {
digitalWrite(LEDPin2, LOW);
} else if (distance < 15) {
digitalWrite(LEDPin2, LOW);
}
else {
analogWrite(LEDPin2, map(distance, 60, 20, 0, 255));
}
if (distance > 100) {
digitalWrite(LEDPin3, LOW);
} else if (distance < 40) {
digitalWrite(LEDPin3, LOW);
}
else {
analogWrite(LEDPin3, map(distance, 100, 40, 0, 255));
}
//Delay 50ms before next reading.
delay(100);
}