Help with IF ELSE and serial comm please

Hi, I am new to Arduino and C++. I attempted to combine the button program with the ping program so that it would only send serial when the button is switched. I have the switch wired correctly it works with the basic program but nothing is written to the serial monitor when the switch is on.

Thank you in advance for your suggestions

//pin which triggers ultrasonic sound
const int pingPin = 7;
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
int buttonState = 0; // variable for reading the pushbutton status

void setup() {
// initialize serial communication
Serial.begin(9600);
}

void loop()
{
//raw duration in milliseconds, cm is the
//converted amount into a distance
long duration, cm;

//initializing the pin states
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);

//sending the signal, starting with LOW for a clean signal
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);

//setting up the input pin, and receiving the duration in
//microseconds for the sound to bounce off the object infront
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);

// convert the time into a distance
cm = microsecondsToCentimeters(duration);

//checking if anything is within the safezone, if not, keep
//green LED on if safezone violated, activate red LED instead
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);

//printing the current readings to the serial display
Serial.print(cm);
Serial.print("cm");
Serial.println();
// digitalWrite(greenLed, HIGH);
// digitalWrite(redLed, LOW);
}
else
{
// turn LED off:
digitalWrite(ledPin, LOW);
}

delay(100);
}

long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}

Where are you reading the switch condition?

Hi Larry,

I was reading at the beginning of the if statement if (buttonState == HIGH) {

am I missing something prior to that?

Thanks

You need a:
buttonState = digitalRead(buttonPin);

Then you can do your test to see if buttonState is HIGH

Larry, thank you. It was the obvious that hits ya in the face. It works now. Now I am going to start on getting it to write to the SD card.

Thank you again for your help.

Paul