I'm trying to determine the best way to connect eight Vivotech HC-SR04 Ultrasonic Distance sensors to the Due.
A document that shows how to communicate with this sensor is here:
http://www.micropik.com/PDF/HCSR04.pdf
Eight green and eight red LEDs will also be connected to the Due as outputs. The immediate goal is to have a red LED light up when an object comes within 20cm of the corresponding sensor. The ultimate goal is to have code that makes intelligent decisions on which LED to light up based on the the distances of objects from each sensor. The decision making algorithm needs to know the readings from each sensor continuously or as much as possible. Obviously, this is much more advanced.
Here is the code I have now, which I haven't had a chance to test yet. I'm sure it is not the most efficient. Please help me improve this code, so that I can more easily update it for the decision making algorithm. (The code only accounts for 2 sensors right now to make the wiring easier)
#define trigPin 13
#define echoPin1 12
#define echoPin2 4
#define red1 11
#define green1 10
#define red2 3
#define green2 2
long threshold = 20; //Distance under which the red LEDs will turn on
long trigTime, duration, distance;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(red1, OUTPUT);
pinMode(green1, OUTPUT);
pinMode(red2, OUTPUT);
pinMode(green2, OUTPUT);
attachInterrupt(echoPin1, sensor1, RISING);
attachInterrupt(echoPin2, sensor2, RISING);
}
void loop() {
//Trigger sensors
noInterrupts();
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
trigTime = micros();
interrupts();
while(micros() - trigTime < 100000) {
//Wait for interrupts
//Trigger sensors 10 times per second
}
}
void sensor1(){
//Calculate sound signal duration
duration = micros() - trigTime;
//Calculate distance
distance = duration/58;
//If object within threshold of sensor 1
if (distance < threshold) {
digitalWrite(red1,HIGH); //Turn red LED on
digitalWrite(green1,LOW); //Turn green LED off
}
else {
digitalWrite(red1,LOW); //Turn red LED off
digitalWrite(green1,HIGH); //Turn green LED on
}
}
void sensor2(){
//Calculate sound signal duration
duration = micros() - trigTime;
//Calculate distance
distance = duration/58;
//If object within threshold of sensor 2
if (distance < threshold) {
digitalWrite(red2,HIGH); //Turn red LED on
digitalWrite(green2,LOW); //Turn green LED off
}
else {
digitalWrite(red2,LOW); //Turn red LED off
digitalWrite(green2,HIGH); //Turn green LED on
}
}