I am using the HC-SR04 ultra sound sensor for Arduino. I have used the following code to calculate distance and it works perfectly.
long duration;
digitalWrite(trigger, LOW);
delayMicroseconds(2);
digitalWrite(trigger, HIGH);
delayMicroseconds(10);
digitalWrite(trigger, LOW);
duration = pulseIn(echo, HIGH);
distance = (duration/2) / 29.1;
However I want to use three more of these sensors, for a total of four. This block of code will be called every time I want to find the distance of one of the sensors. I am worried however that delayMicroseconds()
pauses the entire program and that I cannot perform other tasks in while the sensors are working (e.g. driving wheels, it's a robot). The following code is object oriented for each sensor.
class distSensor{
int trigPin;
int echoPin;
int distance;
//Will be used in timer
unsigned long previousMillis;
public:
distSensor(int tPin,int ePin){
trigPin = tPin;
echoPin = ePin;
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
previousMillis = 0;
}
int calculateDistance(){
//records time since program start
unsigned long currentMillis = millis();
long duration;
digitalWrite(trigPin, LOW);
//check if the previous time the method was called is greater than the interval of 2
if(currentMillis - previousMillis > 2){
digitalWrite(trigPin, HIGH);
previousMillis = currentMillis;
}
//check if distance between current time and previous time it was called is greater than interval of 10.
if(currentMillis - previousMillis > 10){
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
}
return distance;
}
};
In the calculateDistance()
method I am trying to do the same thing as the first code but without delay()
and instead a timer. But when I run the program it does not work and distance is read as 0. Can anyone help me rewrite the HC-SR04 code from the start that doesn't delay the whole program?
pulseIn()
also blocks, so that won't help; you need an interrupt.delayMicroseconds
in your codes. ThepulseIn()
function blocks for too long, this is the one you have to avoid with interrupt as dandavis said.