Adventures in Science: Arduino Conditional Statements

We're back to exploring programming basics, and this week: if/else statements!

Favorited Favorite 0

A few weeks ago, we talked about arithmetic operators in Arduino/C. We’re back with another riveting round of programming basics, and now we’re talking about conditional statements. They’re super important in most programming languages, as they allow you to change how the program flows.

To use conditional statements (and later, loops), we first look at relational operators, which, in their basic form, compare two numbers. For example, does 5 equal 7? Here are the six basic relational operators in C:

Operator Description
== Is equals?
!= Is not equals?
> Greater than?
< Less than?
>= Greater than or equal to?
<= Less than or equal to?

In C, these operators return an integer: 1 for true and 0 for false. We can feed these into the conditional statements in order to change the flow of the program:

if ( some relational operation ) {
    if above is true, execute this
} else if ( another relational operation ) {
    if first relational operation is false but second is true, execute this
} else {
    otherwise (both are false), execute this
}

While this is old news for many of you, how would you recommend wrapping these programming basics videos up for someone who might be new to it? Would you prefer to see it in a playlist? As part of a class with homework problems and answers? I’m trying to figure out how to package these into something that could be useful for a beginner, so ideas are welcome! Please share in the comments below.


Comments 12 comments

  • Amazing and cool information. Thanks for sharing.

  • I think you’ve hit many of the core ideas. As a software engineer, a few things I find will help reduce bugs in code:

    • As mentioned elsewhere, putting constants on the left side of your conditional can help catch some errors (for instance, 7 = a rather than a = 7). This is more obvious to a human eye and compilers can flag this error.

    • Put the shorter condition block first. Rather than:

        if (condition) {
            // Really
            // Long
            // Complex
            // Block
            // Of
            // Code
        } else {
            // Short block
        }
      

      Instead do:

        if (!condition) {
            // Short block of code
        } else {
            // Really
            // Long
            // Complex
            // Block
            // Of
            // Code
        }
      
    • I have watched new programmers learn conditionals, exercises are crucial to this process. In other words, definitely yes to the home works.

    • The constant before the variable is genius! I will definitely have to start using that. I have to admin, I don’t readily see what the sorter condition block does? Is that to make it easier to read on a single screen?

  • I wanted to let you know that I am using your videos as part of the summer classes that I am doing for a High School First Robotics team. So keep churning them out :)

    What I am doing with this summer session is using the Arduino as a simple hard to mess up C++ programming environment. So I am going to do doing lessons on Pointer,Classes and, Algorithms and such. I hope to get the students to produced more structured programs, with the thought in mind that from an education point of view a FRC robot could implemented with an Arduinio controlling each of various subsystem (ball pick up, shooter, etc) but to do that we need to get a lot more kids up to speed on programming.

  • A few things from my experiences:

    1. When compilers convert the C/C++ to ASM, they will do things to optimize the pipeline of the instruction set. As an example, if you do if ( A == B) {..}, the compiler might actually do if (B != A) {…). (If you haven’t guessed, they’re the OPPOSITE of each other). This helps save on the JMP commands used (waiting a few clock cycles to go from one point of the ASM to another).
    2. Always have an “else” statement. This goes along my digital logic background that it creates latches if you don’t have a “default” conditional, and if you don’t have one, that means your conditionals have to handle ALL possible conditions, and if you don’t know the conditions of the data, have an else there to save you the headache of losing data, and possibly having improper data print out.
    3. If you have far too many if-statements in a row, you should look into using a switch/case to simplify your code (and helps the compiler optimize it).

    My biggest issue with the homework of online classes is they do not show you the bigger picture of when to use certain key features of the language. Why use an if-statement, when a unary/ternary statement can do the same thing? The times I learned a language the best was when I was given a practical application in which to code. This helps teach the specific aspects of the syntax you want to teach, but also teaches the students to test their code. Plus, as they get more familiar with the code and application, they can start doing coding optimizations themselves to meet certain specifications of the design.

    • Always have an “else” statement.

      I’m going to have to disagree with you here. While it makes sense in a digital logic context, software and hardware description languages have very different design philosophies even though the text of the code may look similar. For hardware description language coding, it certainly makes sense to have else clauses or default conditionals - without them you often end up with a latched value or erroneous logic. But for software, there are many situations where there is no need for an else clause (or even a default alternative in a case statement) and arbitrarily saying one must be there just muddies the intent.

      Shawn’s examples of printing out strings in the conditional statements do benefit from an else clause - the later examples that always print something are generally more informative than the early examples that print nothing in certain cases. But not all situations require it. You can always artificially put in an else clause even if it does nothing useful, but why would you do it if it’s not necessary? That only confuses the issue.

      Using hardware definition languages and software programming languages require two very different ways of thinking, and lessons learned in one do not necessarily translate well into the other.

      I guess the main thing I’m focusing on is the use of “always” in that statement. There are no absolute statements in software design. There may be concepts that should generally be followed, and for good reason, but there are times where it’s not only necessary, but advantageous to break the rules. Using GOTO is one of them: you should generally avoid it whenever possible, but there are a small set of circumstances where careful use of a GOTO can greatly improve the code. But I feel that saying to “always” have an else is not even close to being one of those rules that you should generally follow.

      All absolute statements are false, including this one.

  • Hi Shawn!

    I think your video does a pretty good job in several respects, though I have some “heartburn” with assuming (remember the derivation of that word!) that “true” is 1. The spec for C simply says that it’s non-zero (which is why “if ( 36 ) { Serial.println("true”);}“ works). The value for "true” may be any value that the compiler writer wants it to be. (I wrote custom compilers for a living for over 20 years.)

    For the written text, I’d start with a simple “if” statement (without the else), followed by an “if-else”, before going on to “if-else-if”. As a stylistic issue, I’ve often found that

    if ( ... ) {
      statement1;
    } else {
      if ( ... ) {
        statement2;
      } else {
        statement3;
      }
    }
    

    can be somewhat easier to follow. Putting comments on the close braces also helps!

    One other quick habit: Most (though not all) C compilers will flag “36 = A” as an error (when what you meant to type was “36 == A”). (The ones that don’t often will give really bizarre results if you later try to use the constant 36. Actually, I haven’t seen this behavior since the 1970s [and in languages other than C], but it’s one of those things you have to laugh at when you do see it!)

    • Thanks for the tips! According to the C11 spec, the relational operators return 1 for true and 0 for false, which is the point I was trying to make. Anything non-zero is “true,” which is why if (36) {...} will execute. I still run into a number of compilers that don’t flag (or if they do, it’s just a warning) assignment operations in conditional statements, and Arduino (avr-gcc) seems to be one of them.

  • I think a playlist with a companion set of ‘homework’ problems would be nice. It’s always easier for me to learn by doing. Perhaps a basic set of problems and one ‘extra credit’ challenge per video would work. You could discuss the solutions on the next video in the series.

    A small critique on the video: prior to discussing the operators, there were a few seconds of blank screen, and I had to check to make sure my video was still playing. Perhaps a background image could be used instead of a blank, black screen.

    Overall I think the videos are worth continuing. Good job!

    • You read my mind with the “homework” problems :) I’ve got about a dozen videos planned for the programming section that I’d like to get through, and then I’m considering making a tutorial (or something similar) on our site with the playlist and homework problems with solutions for people to work through.

      Thanks for the heads up on the black screen. I’ve used it before in presentations, which works well when there’s a presenter to attract visual attention, but you’re right that in a video it can off putting.

      • Something to consider for future educational content is how to write an Arduino library for a new part from start to finish. I don’t know enough about the topic to know if that’s perhaps too broad a subject, but I’d certainly like to understand more about the inner workings of what makes a library tick.

        • That’s definitely on my list of “advanced Arduino programming” topics. However, I’ve found that it helps to use good object-oriented practices and write a class for each part. That means a whole new set of videos on OOP. Looks like I’ve got my work cut out for me :)

Related Posts

Recent Posts

Tags


All Tags