LITTLEBOTS ARDUINO KITS
  • Store
    • LittleArm V3
    • Buddy Social Robot
    • LittleArm 2C
    • LittleArm BIG
    • LittleBot Budget
    • Robot Parts
    • Our Old Kits >
      • Walker Biped
      • LittleArm Original
      • LittleBot
      • Critter
      • Waterbot
  • Resources
    • Youtube Channel
    • Our Instructables
    • Downloads >
      • LittleBot Budget Codes
      • All LittleBots Software Downloads
    • Tutorials >
      • Buddy Setup
      • Budget Example Projects
    • Troubleshooting
  • Contact
    • About
  • Blog

Blog

What is an "IF" Statement and How Does it Work

2/2/2017

2 Comments

 
IF something is too heavy, then drop it. IF snow is falling, then get a snow shovel. IF the robot hits the wall, then turn and go someplace else. IF the computer has sent a signal to an Arduino, then read the signal and interpret it.

In this beginner programming tutorial we are going to go through IF statements and how they work. We will start out with very a basic introduction to the syntax and operation of an IF statement in the  Arduino programming language and then discuss several examples in the LittleArm Arduino code.
Picture
What is an IF Statement
In programming, IF statements are used all of the time. They are a lot like a fork in the road. When the computer comes to an IF statement it must decide which direction it is going to go based on information it has.. 

If statements can make code much more effiecient because they let the computer skip over work that might not be necessary, or do the extra work to do the job right. IF statements let a computer make a decision just like we do.  IF we are looking to get a good grade, then we will show up to work early, else we will be tardy. IF the computer the computer needed to check an answer, then it will calculate it again, else it will just give it to you.
Picture
So, how does a computer decide which direction to turn at an IF statement. Well there much be some condition that it references.  A condition is some "Yes/No" question that the computer must answer. Something like, "Is the computer in a hurry?" Yes. Then skip this code and do something else.

In a computer the condition generally appears as a Relational Operation. Something like: x < 1. Which reads as "Is x less than 1? Yes or No?"  You can use this operation in an IF Statement.
How to Program a basic IF Statement

Now that you know the basic functionality of the IF statement, let's see the actual code..

//define the values that will be in the condition

if (condition) {
     // do something
}

// rest of program


Here is a concrete example in pseudocode.

peopleInCar = Joe + Jerry +Bob;
Joe = likesMexicanFood;
Jerry = likesFastFood;
Bob = likesMexicanFood;

peopleWhoLikeMexicanFood = Joe + Bob;
peopleWhoLikeFastFood = Jerry

if (peopleWhoLikeMexicanFood > peopleWhoLikeFastFood) {
     // go to restaurant that serves Mexican food
}

// Drive Home

In the example we create three variables (Joe, Jerry, and Bob).  We add count how many people like Mexican food and how many people like fast food. Then we compare which group has more people. 

The question in the conditions can be said "Do more people like Mexican food than people who like fast food? Yes or No"

If the answer is "Yes" then Joe, Jerry, and Bob will go to a Mexican Restaurant, and then drive home. If the answer is "No" then they will just drive home (too bad for Jerry).

Picture
Picture
How to Program an IF-ELSE statement.

Now we know how the basic if statement works. But you might notice in the picture above that there is the Else. You might also notice that, in the last example, there was no situation where the people who like fast food would get a to go to their restaurant.

Sometimes you don't want to just include or skip code. Sometimes you want to make a decision between a few pieces of code. You want to give the computer several options.  This is what the else statement is for. Here is an example with pseudo-code

peopleInCar = Joe + Jerry +Bob;
Joe = likesMexicanFood;
Jerry = likesFastFood;
Bob = likesMexicanFood;

peopleWhoLikeMexicanFood = Joe + Bob;
peopleWhoLikeFastFood = Jerry

if (peopleWhoLikeMexicanFood > peopleWhoLikeFastFood) {
     // go to restaurant that serves Mexican food
}
else{
    // go to a restaurant that Serves Fast Food
}

// Drive Home

In this case we allow for other alternatives. If there are more people who like fast food then the group will go to a fast food restaurant. Or if there were four people in the car and two like fast food and two liked Mexican food then they would go to a fast food restaurant. This is much better code because it can handle more situations.
Even More If Statements

Now what if you had a bus load of people, with many more preferences. Well you need to let the program make more choices. What you can do is create a long line of IF statements so that each can handle a situation. 

Here is the proper syntax.

if (condition){
    //do something
}
else if (condition){
    // do something
}
else if (condition){
​    // do something
}
else (condition){

​    // do anything else that was not considered in the last situations
}

Here is a better example with real code. It for the situation of a bus-load of people deciding where to eat lunch.


peopleWhoLikeMexican = 10;
peopleWhoLikeFastFood = 8;
peopleWhoDoNotCare = 3;

numForMexican = peopleWhoLikeMexicanFood + peopleWhoDoNotCare;
numForFastFood = peopleWhoLikeFastFood +peopleWhoDoNotCare;

if (numForMexican > numForFastFood)) {
     // go to restaurant that serves Mexican food
}
else if (numForFastFood > numForMexican){
     // go to s fast food place
}

else{
   // this will only happen if there is a tie or no one like either mexican or fast food

    // Order Pizza
}

// Drive Home

So now we have written a program that can take care of all of your restaurant decisions. You can expand on it and turn it into a smartphone app so you never have to make a decision about where to eat again.

Picture
In the Case of the LittleArm

Now that we know how all these IF statements work let's look at a very real example in the code for the LittleArm.

The LittleArm  code ​actually has several IF statements in it., Most programs have many, many IF statements. For this tutorial we are going to focus on the Serial IF statements. These let the Arduino read commands coming from the smartphone app or Windows application through bluetooth or USB (both are Serial communication devices). Here is the full code.

 if (Serial.available()){
    ready = 1;
    desiredAngle.base = Serial.parseInt();
    desiredAngle.shoulder = Serial.parseInt();
    desiredAngle.elbow = Serial.parseInt();
    desiredGrip = Serial.parseInt();
    desiredDelay = Serial.parseInt();

    if(Serial.read() == '\n'){              // if last byte is 'd' stop reading and execute command. 'd' stands for 'done'
        Serial.flush();                     //clear all other commands piled in the buffer
        Serial.print('d');                  //send completion of the command
    }
  }


Now lest's look at the first statment

 if (Serial.available()){

In this line we ask the question "If there information coming through the serial device? Yes or No?" If the answer is No then we will skip over all of the code that is enclosed between the first and last  {}. But we are going to assume that the computer just sent a command to the Arduino, so the answer is "Yes."

So now we go through the code. All the Serial.parseInt() commands read off a piece of the command. They are a bit like a bite of a hot dog. Each parseInt bites the hot dog so that there is less after each bite.

The hot dog is the Position Command sent in this form:
("basePositionInt, shoulderPositionInt, elbowPositionInt, gripperPositionInt, servoDelayInt, \n ")

Now the computer is not very smart, so it might keep trying to bite the hotdog even after it is gone, or it might start eating a hamburger when it finishes the hotdog. So we need an IF statement to check for when the hot dog is totally eaten. That is this statement

 if(Serial.read() == '\n')

The statement can be read as "Did the computer just see a newline character? Yes or No?" The "\n" is called a newline character. It is the same as pressing enter in Microsoft Word.  When we reach this character in the command we know that the entire command has been read, or the entire hotdog has been eaten. So since the entire command has been read, then we can print "d" for done, so an observer can see that the program has read the command and then move on with moving the servos later in the program.

This "\n" is technically called a parity byte. A Parity Byte is an error checking method to make sure that garbage data is not collected. Sometime where information is sent through USB it can become garbled and trashy, things like parity bytes make sure that the Arduino reads just the right amount of data and in the right order.

What you have just seen in this snippet of code is called a Nested IF statement. A Nested Statement is when one statement is inside of another. Here we have an IF statement inside of a larger IF statement.
Picture
Well, that is all we have for the IF statement. Hope this clears up some of the usage of IF. Just remember that is is a way to put a fork in your program where a computer can decide to use a piece of code or skip a piece of code based on some condition.
2 Comments
visit site link
3/3/2017 05:43:22 am

Those results are terrific! I hope to see here more possible spheres of usage. It will be nice if you'll add here more overviews on that topic.

Reply
keith flint net worth link
6/18/2019 11:39:44 pm

I found your this post while searching for some related information on blog search…Its a good post.

Reply



Leave a Reply.

    Visit the Store

    Archives

    November 2020
    September 2020
    February 2020
    January 2020
    November 2019
    September 2019
    May 2019
    March 2019
    January 2019
    December 2018
    November 2018
    September 2018
    July 2018
    November 2017
    September 2017
    August 2017
    July 2017
    June 2017
    May 2017
    April 2017
    March 2017
    February 2017
    January 2017
    December 2016
    November 2016
    October 2016
    September 2016
    August 2016

    RSS Feed

Products

LittleArm Original
LittleArm 2C
LittleArm Big
LittleBot Budget
​Walker Biped
Critter
Waterb ot

Business

About
The Company
Blog

Resources

Contact
Tutorials
Downloads

© COPYRIGHT 2017. ALL RIGHTS RESERVED.
  • Store
    • LittleArm V3
    • Buddy Social Robot
    • LittleArm 2C
    • LittleArm BIG
    • LittleBot Budget
    • Robot Parts
    • Our Old Kits >
      • Walker Biped
      • LittleArm Original
      • LittleBot
      • Critter
      • Waterbot
  • Resources
    • Youtube Channel
    • Our Instructables
    • Downloads >
      • LittleBot Budget Codes
      • All LittleBots Software Downloads
    • Tutorials >
      • Buddy Setup
      • Budget Example Projects
    • Troubleshooting
  • Contact
    • About
  • Blog