I'm an idiot with C / Arduino with "if" statement and I cannot figure it out

I am an absolutely beginner that has read everything and tried cut and paste and still can't get an if statement to work. I am not a C programmer.

I'm using an ultrasonic sensor, LCD and UNO R3 board with a single channel relay.

I can't get my code to process my if statement after measuring distance to turn my relay on or off based on distance of less than or greater than.

Here's my code. I'm at wits end and I'm so frustrated with Arduino coding... I keep on getting basic error of "exit status 1
expected unqualified-id before 'if' and I don't have a clue what that means because I have no experience with C language.

I realize I am a total idiot but please tell me where I've gone so simplistically wrong. I don't even want to try to start and shut off my buzzer until I figure out what I've done wrong with relay.

:frowning:

#include <LiquidCrystal.h> //http://www.arduino.cc/en/Tutorial/LiquidCrystal
int RS=A5, E=A4, D4=A3, D5=A2, D6=A1, D7=A0;
LiquidCrystal LCD(RS, E, D4, D5, D6, D7); // initialize the library with the numbers of the interface pins

int trigPin=12; //Sensor Trip pin connected to Arduino pin 13
int echoPin=11; //Sensor Echo pin connected to Arduino pin 11

float pingTime; //time for ping to travel from sensor to target and return
float targetDistance; //Distance to Target in inches
float speedOfSound=776.5; //Speed of sound in miles per hour when temp is 77 degrees.
int Buzzer = 13;
int Relay = 10;
int val=0;

void setup() {

Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode (Buzzer, OUTPUT);
pinMode (Relay, OUTPUT);

LCD.begin(16,2); //Tell Arduino to start your 16 column 2 row LCD
LCD.setCursor(0,0); //Set LCD cursor to upper left corner, column 0, row 0
LCD.print("Target Distance:"); //Print Message on First Row
}

void loop() {
delay(50);
digitalWrite(trigPin, LOW); //Set trigger pin low
delayMicroseconds(2000); //Let signal settle
digitalWrite(trigPin, HIGH); //Set trigPin high
delayMicroseconds(15); //Delay in high state
digitalWrite(trigPin, LOW); //ping has now been sent
delayMicroseconds(10); //Delay in high state

pingTime = pulseIn(echoPin, HIGH); //pingTime is presented in microceconds
pingTime=pingTime/1000000; //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
pingTime=pingTime/3600; //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
targetDistance=speedOfSound * pingTime; //This will be in miles, since speed of sound was miles per hour
targetDistance=targetDistance/2; //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
targetDistance=targetDistance*63360; //Convert miles to inches by multipling by 63360 (inches per mile)

LCD.setCursor(0,1); //Set cursor to first column of second row
LCD.print(" "); //Print blanks to clear the row
LCD.setCursor(0,1); //Set Cursor again to first column of second row
LCD.print(targetDistance); //Print measured distance
LCD.print(" inches"); //Print your units.
delay(500);
}

// targetDistance=(inches);

if (targetDistance < 4 )

{
digitalWrite(Relay,HIGH);

}

else

{
(targetDistance >= 4 )

{

digitalWrite(Relay,LOW);

} //Water level reaches the Top of the Tank

delay(50);
}

}

It looks to me like your "if" is outside your loop function.
C doesn't allow this, and the compiler should have told you this.
Try moving loop's closing } to the bottom of your code.

Please use code tags (</> button on the toolbar) when you post code or warning/error messages. The reason is that the forum software can interpret parts of your code as markup, leading to confusion, wasted time, and a reduced chance for you to get help with your problem. This will also make it easier to read your code and to copy it to the IDE or editor. If your browser doesn't show the posting toolbar then you can just manually add the code tags:

[code]

[color=blue]// your code is here[/color]

[/code]

Using code tags and other important information is explained in the How to use this forum post. Please read it.

Please remove unnecessary blank lines from your code before posting to the forum. One or two to separate code into logical sections is fine but large spaces for no reason or random blank lines just make for more scrolling when we're trying to read your code. Do not post double spaced code.

Please always do a Tools > Auto Format on your code before posting it. This will make it easier for you to spot bugs and make it easier for us to read. If you're using the Arduino Web Editor you will not have access to this useful tool but it's still unacceptable to post poorly formatted code. I recommend you to use the standard IDE instead.

After you do the Auto Format, look over your code to see if the automatic indentation matches your intended program structure. Auto Format is a very helpful troubleshooting tool.

What do you think this is doing?

else 

{
    (targetDistance >= 4 ) 

{

digitalWrite(Relay,LOW);

All I want is to have the ultrasonic sensor measure distance then;

once it reaches a threshold (4" or less) than I want the relay to turn on.

if the distance is greater than 4" than I want the relay to turn off.

that's it.

Nothing more.

I can get the ultrasonic sensor to measure properly on the LCD, why can't I get the measurement to trigger the relay on or off.

Sorry for not putting my code in quotes.

If that's all you want, why have you got all the LCD stuff?

CtrlAltElite:
If that's all you want, why have you got all the LCD stuff?

Because that way I do not have to keep my laptop connected to detect if ultrasonic sensor is working or not.

DHanchard:
All I want is to have the ultrasonic sensor measure distance then;

once it reaches a threshold (4" or less) than I want the relay to turn on.

if the distance is greater than 4" than I want the relay to turn off.

that's it.

Nothing more.

I can get the ultrasonic sensor to measure properly on the LCD, why can't I get the measurement to trigger the relay on or off.

Sorry for not putting my code in quotes.

Compare the use of your 'if/else' to that written in the reference section of this web site.

larryd:
Compare the use of your 'if/else' to that written in the reference section of this web site.

I did read the if and else reference sections and I guess I do not understand it - because I'm an idiot. I need some help. I got a real world problem trying to avoid water coming up through a stand pipe in the basement of my home.

As the water rises, I want to small electric pump to turn on via a relay to make sure it does not flow onto my basement floor. (Spring thaw run off).

I beg you, I'm not a programmer and I'm not good at C language. I just want to have some help from the community. I'm not looking to become a rocket engineer. I just thought Arduino could solve a problem with some simple sensors and some software hacks. If it cannot be accomplished, just please tell me and I will throw away the arduino idea.

thanks.

Have another look at reply 1

because I'm an idiot

There is no need for this kind of talk.

Format your code with and repost it.

larryd:
There is no need for this kind of talk.

Format your code with and repost it.

But I am a total amateur so I might as well be. And I don't know what you want with Ctrl T. Clearly I am out of my depth and I shouldn't bother you all. I just wanted some help and all I seem to do is break all the rules about posting. Sorry. I will try somewhere else.

Jesus H Christ

void loop() {
  delay(50);
  digitalWrite(trigPin, LOW); //Set trigger pin low
  delayMicroseconds(2000); //Let signal settle
  digitalWrite(trigPin, HIGH); //Set trigPin high
  delayMicroseconds(15); //Delay in high state
  digitalWrite(trigPin, LOW); //ping has now been sent
  delayMicroseconds(10); //Delay in high state
 
  pingTime = pulseIn(echoPin, HIGH);  //pingTime is presented in microceconds
  pingTime=pingTime/1000000; //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
  pingTime=pingTime/3600; //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
  targetDistance=speedOfSound * pingTime;  //This will be in miles, since speed of sound was miles per hour
  targetDistance=targetDistance/2; //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
  targetDistance=targetDistance*63360;    //Convert miles to inches by multipling by 63360 (inches per mile)
 
  LCD.setCursor(0,1);  //Set cursor to first column of second row
  LCD.print("                "); //Print blanks to clear the row
  LCD.setCursor(0,1);   //Set Cursor again to first column of second row
  LCD.print(targetDistance); //Print measured distance
  LCD.print(" inches");  //Print your units.
  delay(500);
}  <<<--- THIS IS THE END OF THE loop FUNCTION

Pushing formats your sketch to make it easy to read.

Try this:

#include <LiquidCrystal.h> //http://www.arduino.cc/en/Tutorial/LiquidCrystal


int RS = A5, E = A4, D4 = A3, D5 = A2, D6 = A1, D7 = A0;
LiquidCrystal LCD(RS, E, D4, D5, D6, D7); // initialize the library with the numbers of the interface pins

int trigPin = 12;           //Sensor Trip pin connected to Arduino pin 13
int echoPin = 11;           //Sensor Echo pin connected to Arduino pin 11

float pingTime;             //time for ping to travel from sensor to target and return
float targetDistance;       //Distance to Target in inches
float speedOfSound = 776.5; //Speed of sound in miles per hour when temp is 77 degrees.
int Buzzer = 13;
int Relay = 10;
int val = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode (Buzzer, OUTPUT);
  pinMode (Relay, OUTPUT);

  LCD.begin(16, 2);               //Tell Arduino to start your 16 column 2 row LCD
  LCD.setCursor(0, 0);            //Set LCD cursor to upper left corner, column 0, row 0
  LCD.print("Target Distance:");  //Print Message on First Row
}

void loop()
{
  delay(50);
  digitalWrite(trigPin, LOW);   //Set trigger pin low
  delayMicroseconds(2000);      //Let signal settle
  digitalWrite(trigPin, HIGH);  //Set trigPin high
  delayMicroseconds(15);        //Delay in high state
  digitalWrite(trigPin, LOW);   //ping has now been sent
  delayMicroseconds(10);        //Delay in high state

  pingTime = pulseIn(echoPin, HIGH);  //pingTime is presented in microceconds
  pingTime = pingTime / 1000000;      //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
  pingTime = pingTime / 3600;         //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
  targetDistance = speedOfSound * pingTime; //This will be in miles, since speed of sound was miles per hour
  targetDistance = targetDistance / 2;      //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
  targetDistance = targetDistance * 63360;  //Convert miles to inches by multipling by 63360 (inches per mile)

  LCD.setCursor(0, 1);           //Set cursor to first column of second row
  LCD.print("                "); //Print blanks to clear the row
  LCD.setCursor(0, 1);           //Set Cursor again to first column of second row

  Serial.println(targetDistance);

  LCD.print(targetDistance); //Print measured distance
  LCD.print(" inches");      //Print your units.
  // targetDistance=(inches);

  if (targetDistance < 4 )
  {
    digitalWrite(Relay, HIGH);
  }

  else
  {
    digitalWrite(Relay, LOW);
  } //Water level reaches the Top of the Tank

  delay(500);
}

larryd:
Pushing formats your sketch to make it easy to read.

Try this: etc.


So I made 2 major mistakes in loop section;

made two different if statements that made no sense and did not need to use = symbol

Used too many closing brackets at start and did not properly use one to end the loop.

Thank you, this seems to work. I will try to add my buzzer next but keep this file for safe use without it. I have a second arduino board with extra sensors. I will try to fool around with that one while the main one with sensor is put into stand pipe.

The water has risen from 12" deep to now only 8". I shall see if my relay and motor can handle this.

Thanks again.

So I made 2 major mistakes in loop section;
made two different if statements that made no sense and did not need to use = symbol
Used too many closing brackets at start and did not properly use one to end the loop.

So you aren't an idiot. :slight_smile:
We try to help you write code rather than write code ourselves.

How will you be connecting your relay to the Arduino.
Please supply a schematic of your circuit.

You should have a fallback circuit if the water comes in faster than it can be pumped out.

.

larryd:
So you aren't an idiot. :slight_smile:
We try to help you write code rather than write code ourselves.

How will you be connecting your relay to the Arduino.
Please supply a schematic of your circuit.

You should have a fallback circuit if the water comes in faster than it can be pumped out.

.

Oh do not be so sure of that. I'm not one that is good with language and logic when english allows spanner and wrench to mean the same thing.

Your point is a good one. The water flow I estimate is roughly a gallon every thirty minutes if the rain and thaw are really bad. It is a 4" inside diameter pipe. I have on other thing I have yet to realize that must be solved.

Just because the sensor is now going to measure the water height and turn on the relay, it will quickly turn itself off once it falls back down past 4". So now I must make the relay stay "on" for certain amount of time for the pump to pump out the water. Having the relay turn on for 2 seconds is probably not a good idea. The pump is a simple aquarium type, with a 7/16" inside diameter port that a tube will be connected that will then flow the water to my main sump well tank.

So now I have to figure out what the delay time should be (5 - 7 seconds?) and how to make sure the "Relay, HIGH" function remains on for that interval before the next measurement.

A circuit diagram... what APP do you suggest I use for that? There is no way to post a picture of my arduino set up is there.

larryd:
We try to help you write code rather than write code ourselves.

And, properly formatting and posting your code (with code tags) the first time greatly increases the chances of someone taking enough interest to help you. It shows you’re willing to put in the effort to help those who can help you.

Once posted with code tags, someone can easily copy / paste your code into the IDE and try compiling it. Making people look at code posted as text greatly reduces the chance someone will go to the effort. Even worse, if you just post a link to your code, or attach a .zip file, then forget about it -- that drastically cuts down on the number of people who will to look at your code hand help.

So now I must make the relay stay "on" for certain amount of time for the pump to pump out the water.

Try:

  if (targetDistance < 4 )
  {
    digitalWrite(Relay, HIGH);  //Pump ON
  }

  else if (targetDistance > 10) 
  {
    digitalWrite(Relay, LOW);  //Pump OFF
  }

A circuit diagram... what APP do you suggest I use for that? There is no way to post a picture of my arduino set up is there.

Yes.
If you press Preview you will then see Attachments and other options

Use a pencil and paper :wink:

DHanchard:
So now I have to figure out what the delay time should be (5 - 7 seconds?) and how to make sure the "Relay, HIGH" function remains on for that interval before the next measurement.

Adding some Hysteresis to your control algorithm is a much better idea than using a delay.