LESSON 14: If Statements and Conditionals in Arduino

In our LED project in Lesson 13, we controlled the color of the LED by changing lines of code in the program. As you know, you really want to do that sort of thing by interacting with the user over the serial port. So, in this project, we are going to have the user set the color by indicating his preferred color in the serial monitor. Notice in our new picture below we have covered the LED with a ping pong ball. We did this so the LED will show better in the video, but after doing it, I really like it! It makes a cool little lamp. You can do this by creating a small hole the size of the LED in the ping pong ball, and then just mounting the ball on the LED. Cool stuff!

We have added a ping pong ball to the top of our RGB LED.

This project uses the same circuit we set up in Project 13. We will just be changing the code.

RGB LED Circuit
Circuit used to control RGB LED from an arduino

So, for this project, we will want the user to input his desired color for the LED. Then we will make the LED change to the color he requested. In order to do this, we need to learn a new programming command called the if statement. The if statement has a clause, or group of commands between a set of curly brackets. It executes those commands only if a condition is met. An if statement in arduino would look like this:


The commands between the curly brackets will be executed if the condition inside the parenthesis is true. Lets consider you had two variables, a and b. Lets say you only wanted to execute the commands in the clause if a is > or = to b. In that case you would put that condition in the parenthesis and your code would look like this:

The arduino would only execute the code if the condition was true. Otherwise it would jump to the first line of code after the closing curly bracket. There are a number of different condition tests that can be used in the parenthesis:

You can combine more than one condition by using the logical operators “and” or “or”. In arduino the symbol for “and” operation is && and the symbol for “or” operator is ||. (This is the symbol above the backslash on the keyboard). So you could have a condition where a is greater than b AND a is greater than c. This would look like:

 OK, so that is how if statements and conditional work. A key thing is that you have to remember than when you are testing for equality in an if statement, you use two equal signs. One of the common mistakes I see students make is to forget and just use one equal sign in a conditional.

What you will want to do now is write a program that will ask the user what color he would like the LED to be. In the prompt let him know that his choices are Red, Green, or Blue. Then turn the LED that color. You should also include a “test” . . . if he does not choose one of the allowed choices, he must choose again. Do your best to develop the code on your own, but if you get stuck, peak at my code below. You should not copy and paste my code, but just use it as a guide if you get stuck.

 OK, now your assignment is to move forward and have the program have more options for colors. Have it where you can turn the LED Red, Green, Blue, Cyan, Magenta, Yellow, Orange, Purple, Pink. Do some research on the internet to make sure you are really hitting these colors. Part of your grade will be how well you match the colors.

31 thoughts on “LESSON 14: If Statements and Conditionals in Arduino”

  1. I have watching your arduino tutorials for a few months, and I want to say thank you because your tutorials to make me very interest to learn about arduino. Now I have project to control lifghting 220 v using arduino, relay 8 channel and modem serial wavecom and I will control this light using sms. for example if I send sms “on 1” lamp 1 on, “on 2” lamp 2 on, “off 1” lamp 1 off, “off 2” lamp 2 off and etc. And now I hope You can help me to make code program and you can send to my email nixons294@gmail.com.

      1. Good Day!

        Sir, I’m using arduino uno interface with rtc (DS3231), i found the code in setting the time of rtc through arduino and here it is:


        // Init the DS3231 using the hardware interface
        DS3231 rtc(SDA, SCL);

        void setup()
        // Setup Serial connection
        // Uncomment the next line if you are using an Arduino Leonardo
        //while (!Serial) {}

        // Initialize the rtc object

        // The following lines can be uncommented to set the date and time
        rtc.setDOW(WEDNESDAY); // Set Day-of-Week to SUNDAY
        rtc.setTime(12, 0, 0); // Set the time to 12:00:00 (24hr format)
        rtc.setDate(1, 1, 2014); // Set the date to January 1st, 2014

        void loop()
        // Send Day-of-Week
        Serial.print(” “);

        // Send date
        Serial.print(” — “);

        // Send time

        // Wait one second before repeating 🙂
        delay (1000);

        My question is that, how can i set a specific time using (if and else if) condition that can turn on/off a certain device? How can i insert that command code in the above code…Thank you sir in advance!!! I hope you find time in helping me with my project.

  2. Hi Paul

    I have been struggling with this lesson because I have a common anode LED. I have searched and search and tried every trick in the book to control the colour from the serial port with the common anode setup. Please can you guide me through getting this to work. I would be very grateful if you could.

    Kind Regards


    I have set up

    1. Hi James,

      I tried this out cause I like a challenge. After a couple of hours i cam up with a work around. Its messy. So the setup is 5v to 330r resistor to anode, the rest of the pins the same. Now i was finding it very hard to read the string as it wasn’t matching so I used a char read and then i got the char into an int. Here is the code. It is not pretty but it will light when you write green, red, or blue.

      int redPin=11; //set red LED pin to 11
      int greenPin=10; //set green LED pin to 10
      int bluePin=6; //set blue LED pin to 6
      int brightness=1; //Set brightness to 1

      void setup() {
      // put your setup code here, to run once:

      Serial.begin(9600); //Turn on Serial port
      pinMode(redPin, OUTPUT); //Set redPin to be an output
      pinMode(greenPin, OUTPUT); //Set greenPin to be an output
      pinMode(bluePin, OUTPUT); //set bluePin to be an output

      digitalWrite (redPin,HIGH);
      digitalWrite (greenPin,HIGH);
      digitalWrite (bluePin,HIGH);

      void loop() {

      Serial.println(“What color would you like the LED? (red, green, or blue)”); //Prompt user for color
      while (Serial.available()==0) { } //Wait for input
      char dump1 = Serial.read();
      char colorChoice = Serial.read();
      char dump2 = Serial.read();
      int Choice = colorChoice – ‘0’;

      if (Choice == 53) {
      analogWrite(redPin, 255); //turn off red pin
      analogWrite(greenPin, 255); //turn off green pin
      analogWrite(bluePin, 0); //write on blue pin

      if (Choice == -35) {
      analogWrite(redPin, 0); //turn on red pin
      analogWrite(greenPin, 255); //turn off green pin
      analogWrite(bluePin, 255); //write off blue pin

      if (Choice == -49) {
      analogWrite(redPin, 255); //turn off red pin
      analogWrite(greenPin, 0); //turn on green pin
      analogWrite(bluePin, 255); //write off blue pin

      1. To figure out the values (e.g. -49) add

        Serial.println (Choice);

        to the code and when you write something like ‘green’ in serial monitor it will give you a few values, then use the last number displayed on the monitor (can be negative or positive) in the corresponding If loop.

      2. thanks, however my code : if(range==15){ stop();
        } does not run unless i remove the if , any help?

  3. Thank you very much for your awesome videos , really i had learn to much from you and i am going to learn more

    1. Thanks for the kind words. The lessons are free because I want people to learn useful stuff instead of sitting around watching TV or playing video games.

      1. myLesson does not work at all,
        do you have any info like mabe changes in 1.8.5
        in arduino that I can make it work?

  4. WELL THAT is A GOOD REASON!!! I’m a grade sixer in Canada and i can understand this comprehensive set of lessons. I recommended you to my teachers who teach a Arduino class.
    Want some maple syrup.
    PS:We live in igloos

  5. thank you very very much for all your videos im from saudi in saudi we dont have institute that techs codeing so you was my one way to learn codeing hope one day i can thank you for that personally.

  6. I am from mechanical engineering,abd i don’t even know ABC of electronics.i know c++ language.
    I am making self balancing segway using ardiuno-uno ,mpu6050 sensor,and motor control ic. I don’t know how to get data from sensor and control motor.
    Can you explain me please…..its humble request.my email id:-pmech11111@gmail.com

  7. Hi I only had a anode RGB led so I thought I’d share how to use it,
    all you need is three 2n2222 transistors (well I suppose you don’t necessarily have to use those , but I had them lying around)
    1, connect 5v to your common with a 220 ohm resistor
    2, connect each colour to the emitter of the NPN transistor
    3, output pin (which ever ones used) to the base
    4,the collector to ground.

  8. This is very useful! What if I want to input a string of characters, say “rbgbrrr” and have the led flash red, blue, green, blue, red, red, red? And maybe go dark when it hits the end of the string?

  9. This lesson is pretty straight forward, but for some reason I cannot get it to work. Here is my code, which is a bit different from Paul’s:

    const int redPin = 11;
    const int greenPin = 10;
    const int bluePin = 6;
    int brightness = 255;
    String colorChoice;

    void setup() {

    pinMode(redPin, OUTPUT);
    pinMode(greenPin, OUTPUT);
    pinMode(bluePin, OUTPUT);

    void loop() {

    Serial.println(“Please Input Your Color Choice (Red, Green, or Blue): “);
    while (Serial.available() == 0) { }
    colorChoice = Serial.readString();

    Serial.print(“You entered: “);

    if (colorChoice==”red”) {

    analogWrite(redPin, brightness);
    analogWrite(greenPin, 0);
    analogWrite(bluePin, 0);

    else if (colorChoice==”green”) {

    analogWrite(redPin, 0);
    analogWrite(greenPin, brightness);
    analogWrite(bluePin, 0);

    else if (colorChoice==”blue”) {

    analogWrite(redPin, 0);
    analogWrite(greenPin, 0);
    analogWrite(bluePin, brightness);

    else if ((colorChoice != “red”) && (colorChoice != “green”) && (colorChoice != “blue”)) {

    Serial.println(“I’m sorry, you made an invalid choice. Please try again.”);


    Even if I replace the “else if” statements with “if”, it does not work. When I input a color choice it invariably falls through to the last else if: the choice being invalid. Both Serial.println() statements show that colorChoice is set to a valid color, yet the program never recognizes it.


    1. Good to know I am not the only one with this fault . i have also put print statement to see if i am inputting correctly and it says i am

      i guess the truly great thing is a week ago i would not have understood your problem , it would be nice to find out what i am doing wrong
      Cheers Ron

    2. I had a problem like this and spent ages trying to find what was going wrong. Evenually I decided that read.string was adding something to the text entered ( I.E red) so that it did not match the word red entered in the program text. The substring command reads only the specified characters in the string so any added on by readstring can be elliminated. I did that and my porogram now works properly. This is the code I used :-
      substringColorChoice=colorChoiceA.substring(0,3); // substring(0,3) evaluates the first three letters of the word entered. I.E red of the word red and no more. I expect you recognise my use of colorchoice etc. This is how it was used in the void loop and from then on my program used the variable substringColorChoice in place of colorchoiceA.

      My Code :-

      Serial.println(“What color would you like the LED? (red, green, or blue)”);
      while (Serial.available()==0){ }
      colorChoiceA=Serial.readString(); // string read in by serial read string.
      Serial.print(colorChoiceA); Serial.print(” = the string as entered “);
      substringColorChoice=colorChoiceA.substring(0,3);// evaluate the first three letters of the word entered
      Serial.print(substringColorChoice);Serial.println(” =substringColorChoice”);
      brightnessRed=25; //Set brightness of Red LED
      analogWrite(redPin, brightnessRed); //turn on red pin
      analogWrite(greenPin, 0); //turn off green pin
      analogWrite(bluePin, 0); //turn off blue pin

  10. I have to readjust the colour, because they don’t work so well if i just use the values from internet, i have to set white to be all 3 with full brightness, although it looks a bit bluish
    these are my codes
    int redPin=11; //Set red LED pin to 11
    int greenPin=10; //Set green LED pin to 10
    int bluePin=6; //Set blue LED pin to 6
    int brightness=255; //Set brightness
    String colorchoice; //Set up variable to hold user input

    void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600); //Turn on Serial Port
    pinMode(redPin, OUTPUT); //Set red pin to be an output
    pinMode(greenPin, OUTPUT); //Set green pin to be an output
    pinMode(bluePin, OUTPUT); //Set blue pin to an output


    void loop() {
    // put your main code here, to run repeatedly:
    Serial.println(“Please input your color choice with code “); //prompting user for input
    Serial.println(“0 – white”);
    Serial.println(“1 – red”);
    Serial.println(“2 – green”);
    Serial.println(“3 – blue”);
    Serial.println(“4 – cyan”);
    Serial.println(“5 – magenta”);
    Serial.println(“6 – yellow”);
    Serial.println(“7 – pink”);
    Serial.println(“8 – violet”);
    Serial.println(“9 – orange”);

    } //wait for user input

    colorchoice = Serial.readString(); //read string from serial port
    if (colorchoice==”0″){

    if (colorchoice==”1″){

    analogWrite(redPin, brightness);
    analogWrite(greenPin, 0);
    if (colorchoice==”2″){
    analogWrite(greenPin, brightness);

    if (colorchoice==”3″){
    analogWrite(greenPin, 0);

    if (colorchoice==”4″){
    analogWrite(greenPin, brightness);

    if (colorchoice==”5″){
    analogWrite(greenPin, 0);

    if (colorchoice==”6″){
    analogWrite(greenPin, 100);

    if (colorchoice==”7″){
    analogWrite(greenPin, 0);

    if (colorchoice==”8″){
    analogWrite(greenPin, 50);
    if (colorchoice==”9″){

    else { //test for valid input
    Serial.println(” “);
    Serial.println(“You have not entered a valid code, Please try again”);


  11. well i have no idea what is wrong as i have now copied your script into a new sketch and upload it with exactly the same results , therefore it is nothing that i have done wrong as such .
    but clearly the program will not accept the input , I am wondering if i have different version from you Admin, I have been trying to identify the problem from search arduino reference files but no luck so far
    cheers Ron

    1. just thinking now perhaps my bootloader is out of date my uno is at least 3 years old
      be nice to get some input back

      1. ok doing more work on this i have added a println to see if my input is right
        see code
        Serial.println(“Please input your colourchoice (red, Green,or Blue )”); //promt user for input
        while (Serial.available()==0){ } //wait for user input
        colourChoice = Serial.readString();
        Serial.println(colourChoice); // prints what i write into
        if (colourChoice==”red” ){

        analogWrite (redPin,200 );
        analogWrite (greenPin,0 );
        analogWrite (bluePin,0 );


  12. The program works and the LED responds correctly and only to the nine color selections. However, the “not a valid color” prints every time.
    Please help me find stupid mistake.

    if (colorChoice !=”red” && colorChoice !=”green” && colorChoice !=”blue”);
    (colorChoice !=”cyan” && colorChoice !=”magenta” && colorChoice !=”yellow”);
    (colorChoice !=”pink” && colorChoice !=”purple” && colorChoice !=”orange”);
    Serial.println(“Your choice is”);
    Serial.println(colorChoice); {

    Serial.println(“That is not a valid color choice, please try again”);

  13. Excellent videos. I am a newbie, copying your sketches very carefully. Lesson 14 has me and my local resource person stumped. The monitor does not accept red,green,blue selections. Consider answer invalid. How to correct?

Comments are closed.