title: How to access the value of a local variable in a function, outside of it?
body: <p>When I run my code, It says "velocity" was not declared in the scope. I tried to add, at the top, a declaration for velocity equal to zero and the code works but then velocity never updates. How can I make it so i'm able to call velocity in my loop function?
  Code:</p>
  
  <pre><code>const int trigPin = 9;
  const int echoPin = 10;
  int trials = 0;
  bool win = true;
  
  long duration1, distance1, duration2, distance2;
  
  void setup() {
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    Serial.begin(9600);
  }
  
  void getDistance(){
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
  
    long duration1 = pulseIn(echoPin, HIGH);
    long distance1 = (duration1*.0343)/2;
  
    Serial.print("Distance: ");
    Serial.println(distance1);
    delay(100);
  
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
  
    long duration2 = pulseIn(echoPin, HIGH);
    long distance2 = (duration2*.0343)/2;
  
    Serial.print("Distance: ");
    Serial.println(distance2);
    delay(100);
  
    }
  
  
  void calculateSpeed(long dist2,long dist1,long time2,long time1){
    long numerator = dist2 - dist1;
    long denominator = time2 - time1;
    long velocity = numerator / denominator;
    return velocity;
  }
  
  void loop() {
    while (win == true){
      getDistance();
      calculateSpeed(distance2, distance1, duration2, duration1);
      Serial.println(velocity);
  
  }
  }
  </code></pre>