I am new to programming so bear with me. I am writing a simple code to control a motor such that the motor will turn at full speed as long as the sensor does not detect an object within 5" of the sensor. If it does see something at 5 inches or less, then I want to motor to stop. My question is this: When using an IF statement, do you have to have the ELSE, or can you simply do two IF statements with no ELSE?
Here is my example:
int motorpin1 = 10 , motorpin2 = 11;
int trig = 12;
int echo = 9;
float distance;
float time;
void setup()
{
pinMode (motorpin1, OUTPUT);
//yellow wire
pinMode (motorpin2, OUTPUT);
//blue wire
pinMode (trig, OUTPUT);
pinMode (echo, INPUT);
Serial.begin (9600);
}
void loop()
{
// setup ultrasonic sensor to control
//motor
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
time = pulseIn(echo, HIGH);
distance = time/148.1;
Serial.println(distance);
if distance <5,digitalWrite (motorpin1, LOW);
digitalWrite (motorpin2, LOW);
if distance >=5, digitalWrite (motorpin1, HIGH);
digitalWrite (motorpin2, LOW);
delay (1000); //wait for 1 second
Is there a better way to do this with an ELSE statement? I want to capture the parameter where the code controls the specific parameters of >5 and then <or=5. Also, my next thing is to pause, and reverse the motor if after 1 second, the sensor still sees an object <=5.
Definitely a learning curve for this old brain of mine!
if
statements in your everyday life ... they happen all the time ... for exampleif (red light) {stop car};
... then think if there would be anelse
block .... don't forget that you can put any command in theelse
block ...else if
is useful