Go Down

Topic: Arduino if else statement . . . . (Read 7940 times) previous topic - next topic


Hi all, I'm new to the whole Arduino/Programming thing as well as electronics. I've played around with the Arduino succesfully and thought I'd start building(trying) to build a robot, a simple robot , one that detects objects via IR and avoiding them.

I did/tryed this by using an Arduino Uno, Ardumoto, tank track sistem and 2 IR sensors. The plan was to mount the to sensors on the front of the tank sistem, each looking "outwarts", I used the 2 sensors this way because I don't have a servo to sweep 1 sensor. I've succesfully written code to operate the motor aswell as the IR sensor.

I need help with a basic " if else " statement, I can't seem to get the if else statement working( the statement should read the value from the IR sensors and then be used to control the motors...) So I tried just reading the IR sensors and if it reeches a sertain value, it has to turn a LED on(HIGH), just to see if I could that. But I failed.

What I'm asking is that if anybody can help me with this basic if else statement, even some ex. code would realy be appreciated.

Any comments wil be greatly appreciated.


Code: [Select]
int sensorPin1 = 2; // Change to match where you sensors are connected
int sensorPin2 = 3;

int sensorVal1;
int sensorVal2;

void loop()
  sensorVal1 = analogRead(sensorPin1);
  sensorVal2 = analogRead(sensorPin2);
  if(sensorVal1 < sensorVal2)
     // Do one thing
     // Do the other thing
The art of getting good answers lies in asking good questions.


Dec 30, 2010, 09:12 am Last Edit: Dec 30, 2010, 02:24 pm by mvj Reason: 1
Thank  you PaulS for the code , it's appreciated very much and it worked. The only question that I want to ask is if I would like to compare ex sensorVal1 against a preset value and not the other sensor, how will I write that value,where and should I map that value ?

I'm asking this because I'll be conrolling motor's with the value and if the value from the the sensor is for ex. < than the preset value to put the motor in reverse and so on.

Thanx all, as I said, just starting out with the programming and sorry for all the questions . . .


The if statement contains two operands and a comparison operator.

if(sensorVal1 < 100)
if(sensorVal2 >= 39)

The operators are listed under Comparison Operators here:

Time with this page would be time well spent.
The art of getting good answers lies in asking good questions.

Go Up