Code Check: Ping sensor and Dc motors

So the goal of this code is to drive forward unless an object is detected within 20 cm, then it will turn left. The code posted below does work, however I want to consolidate the void loop. I would like to take the part of code in the void loop() from “long duration, cm;” to “Serial.println(cm)” and put it in after the loop, much like I did with the drive_forward() part. The problem I am having is that I can’t get the value “cm” to be recalled during the rest of the program. Any suggestions?

// SN754410NE Quad Half H-Bridge IC to control two DC Motors.
// Integrated Ping))) sensor
// Go forward unless an object is within the avoid distance (centimeters), then turn 
// left for the avoid time (microseconds).

int motor_left[] = {2, 3};
int motor_right[] = {4, 5};
int pingPin = 10;
int ledPin1 = 9;
int ledPin2 = 7;
int ledPin3 = 6;
int ledPin4 = 8;
const int avoidTime = 1000;
const int avoidDistanceCm = 20;

long duration, cm;

void setup()
{
  Serial.begin(9600);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);
  
  //setup motors
  int i;
  for (i = 0; i < 2; i++)  {
    pinMode(motor_left[i], OUTPUT);
    pinMode(motor_right[i], OUTPUT);
  }
}

void loop()
{
  long duration, cm;
  
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);
  
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);
  cm = microsecondsToCentimeters(duration);
  Serial.println(cm);

  drive_forward();
  
  if (cm <= avoidDistanceCm)  {
    avoid_left();
  }
  delay(100);
}

void drive_forward()
{
  digitalWrite(ledPin1, HIGH);
  digitalWrite(ledPin2, HIGH);
  digitalWrite(ledPin3, LOW);
  digitalWrite(motor_right[0], HIGH);
  digitalWrite(motor_right[1], LOW);
  digitalWrite(motor_left[0], HIGH);
  digitalWrite(motor_left[1], LOW);
  delay(25);
}

void avoid_left()
{
  digitalWrite(ledPin1, HIGH);
  digitalWrite(ledPin2, LOW);
  digitalWrite(ledPin3, HIGH);
  digitalWrite(motor_right[0], HIGH);
  digitalWrite(motor_right[1], LOW);
  digitalWrite(motor_left[0], LOW);
  digitalWrite(motor_left[1], HIGH);
  delay(avoidTime);
}

long microsecondsToCentimeters (long microseconds) 
{
  return microseconds / 29 / 2;
}

Can you also post your “working” code (e.g. before the change)

Can you also explain why you have global and local variables of the same name?

[glow]long duration, cm;[/glow]

void setup()
{
   // Snipped all the setup stuff
}

void loop()
{
  [glow]long duration, cm;[/glow]

I got it working! The problem I was having was with the repetition of the variable definitions. I took out the local variable definition and left the global one. Thank you so much for the help. This forum never disappoints me!