Hi, I was trying to interface multiple HC-SR04 ultrasonic sensors to my Arduino Uno. Since the pulsIn function is blocking the code, I tried to write the code using interrupts.
Everything went well, but when testing, the first sensor gives a good distance to a object (at a fixed distance), but the second not. The distance read with the second is much lower than the actual distance.
The distance to the first object was 10cm (measured with a ruler), what it also says. But the distance to the second object was about 20cm (not exactly measured), but the sensor says less than 10 cm. And when I moved the second object closer to the sensor (to about 10 cm), the values of the first sensor halves, but the object 1 has not moved.
This is my code.
#define trig 2
volatile unsigned long current_time, time_dist1, time_dist2;
volatile unsigned long timer1, timer2;
volatile byte last_ultra1, last_ultra2;
unsigned long timer = 0;
void setup() {
Serial.begin(9600);
pinMode(8,INPUT);
pinMode(9,INPUT);
pinMode(trig, OUTPUT);
cli();
PCICR |= B00000001;
PCMSK0 |= B00000011; // enable interupts when pin D8 or pin D9 changes.
sei();
}
void loop() {
// trigger the ultrasoon modules
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
// pause until the loop time is 50 milliseconds
while (timer + 50 > millis());
timer = millis();
// calculate and print the distance in cm
Serial.print("distance 1: ");
Serial.print((time_dist1 / 2.0) * 0.03435);
Serial.print("\tdistance 2: ");
Serial.println((time_dist2 / 2.0) * 0.03435);
}
ISR(PCINT0_vect){ // ISR for port B, PCINT0 - PCINT7, digital pin 8-13
current_time = micros();
if (PINB & B00000001) { // pin 8 high?
timer1 = current_time;
last_ultra1 = 1;
}
else if (last_ultra1 == 1){ // pin 8 again low?
last_ultra1 = 0;
time_dist1 = current_time - timer1;
}
if (PINB & B00000010) {
timer2 = current_time;
last_ultra2 = 1;
}
else if (last_ultra2 == 1){
last_ultra2 = 0;
time_dist2 = current_time - timer2;
}
}
Thanks in advance.