1

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!

sempaiscuba
  • 1,042
  • 9
  • 21
  • 32
Pilot Ken
  • 19
  • 2

1 Answers1

1

You can do something along the line of

if (distance < 5) {
    digitalWrite (motorpin1, LOW);
}
else {
    digitalWrite (motorpin1, HIGH);
}

It seems like you only set motorpin2 to LOW and never to HIGH. If you don't want to set it HIGH, move that line to the setup() section. There is no need to keep setting it LOW.

chicks
  • 227
  • 4
  • 10
jkp
  • 174
  • 3