Not running code before if statement... !?

Hey! :smiley:

I seem to be having a problem with the compiler. Or not. Hopefully you guys can help me.

I'm trying to read a value from a Ping ultrasonic sensor when serial is available and if the value is over 120 - print 'd' to serial and turn on a relay. At this point, the Arduino should wait to read 'f' from the serial port and turn off the relay.

When I compile and upload the code, it appears to wait for me to type 'f' first, then run the start of the code...

Here's my code:

int incomingByte = 0;      // for incoming serial data
const int pingPin = 9;       // Ping sensor pin.
int relay = 3;                   // Relay pin.

void setup() 
{ 
  Serial.begin(9600);
  pinMode(relay, OUTPUT);  
  digitalWrite(relay, HIGH);
} 
 
 
void loop() 
{   
      if (Serial.available() > 0) {
                 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); //Conversion for Ping

                delay(50);
                
                if (cm <= 120){
                    Serial.print("d");
                    digitalWrite(relay, LOW);
                    
                    incomingByte = Serial.read();
    
                    if (incomingByte == 111){ // Off (o)
                         digitalWrite(relay, HIGH);
                    } else if (incomingByte == 102){ //On (f)
                         digitalWrite(relay, LOW);
                    }
                }
        }
} 

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;
}

Also, how can I make it so that when I send 'o' through serial, it'll run what's in the "off" if statement without checking the Ping?

Thanks for your help if you can! I really appreciate it!!! :slight_smile:

After you determine that there IS serial data, you need to read the serial data. If the value received is not 'o', then ping and reply.

You are pinging and replying first, then checking what is on the serial port.