0
votes

I have an Arduino UNO hooked up to an ultrasonic rangefinder which reads into the variable distance. However, I need to, on one second intervals, read the current distance and then store the previous distance (from the last second). I also need to be able to use these variables (Dprev and Dcurr) other places in my code.

I am presuming I need to put it into some sort of while loop that iterates every second, but I don't know how to put it all together, or use time in a loop.

1

1 Answers

0
votes

The idea is simple. Two global variables for storing distance and two fases. Arduinouse the function setup at the begining of execution, then loop infinite the function loop. So in setup, just initialize variables and in loop take distances.

#define trigPin 13
#define echoPin 12

long duration, distance, distance_prev;
void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  duration = 0;
  distance = 0;
  distance_prev= 0;
}

void loop() {

  distance_prev = distance;

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW); //Send ultrasonic pulse

  duration = pulseIn(echoPin, HIGH);//Time for ultrasonic pulse to go and back
  distance = (duration/2) / 29.1;//Conversion to cm

  /*CODE USING DISTANCES HERE*/

  delay(1000); //One second delay 
}