Skip to content

4. Step By Step

Thomas edited this page Oct 14, 2025 · 10 revisions

Simple program

Let's keep expanding on the program you started in the last step, and learn about some more capabilities of the Circuit Playground. At the bottom of the main method, add the line board.setRedLED(true);. I've also removed the print statement from before, so my code looks like this:

import org.mythicalrobotics.JavaPlayground;

public class App {
    public static void main(String[] args) throws Exception {
        JavaPlayground board = new JavaPlayground("COM4");
        board.setRedLED(true);
    }
}

Now when you run the code, you should see a red light next to the USB port turn on. In this example, you've called a function named setRedLED that belongs to the board object you created. This function takes a boolean input which is either true or false, and it uses that input to decide how to control the light. What do you think happens if the input is false instead?

Maybe we want the LED to blink instead of just being permanently on. To achieve this we can use a delay function built in to Java named Thread.sleep.

import org.mythicalrobotics.JavaPlayground;

public class App {
    public static void main(String[] args) throws Exception {
        JavaPlayground board = new JavaPlayground("COM4");
        board.setRedLED(true);
        Thread.sleep(500);
        board.setRedLED(false);
    }
}

The sleep function here takes a number in milliseconds as an input. There are 1000 milliseconds in 1 second, so sleeping for 500 will be a half-second delay. So the red LED turns on, stays on for a half second, and then gets turned off by the line board.setRedLED(false);. How could you change this so that the red LED stays on for 1 second? What about a quarter second?

This is all well and good, but the LED only flashes once, not repeatedly. That's because the main method here is only run once, and once it reaches the end of the statements within it, the program ends as well. In order to keep our program running, we'll use a while loop.

import org.mythicalrobotics.JavaPlayground;

public class App {
    public static void main(String[] args) throws Exception {
        JavaPlayground board = new JavaPlayground("COM4");

        while(true) {
            board.setRedLED(true);
            Thread.sleep(500);
            board.setRedLED(false);
            Thread.sleep(500);
        }
    }
}

The while loop will continue running the code within its curly braces as long as the boolean condition within the parentheses evaluates to true. If we put true in there, this code will continue running forever (or until we stop it). Now we have an LED that is blinking, as it gets turned on for a half second, and then turned off for a half second repeatedly. You may have also noticed a new bar appear at the top of your screen that looks like this:

The most important icon here is the red square which stops your program. After all, we just created a program that runs forever! Whenever you want to restart or run new code, make sure to stop your previous program otherwise the Circuit Playground may not receive commands properly.

Now, experiment with modifying the two numbers in the Thread.sleep calls and see how the blinking pattern changes. Remember to stop your program before running it again, or you can change the code and click the green restart button.

Control Flow

Now it's time to learn about one of the most common structures in programming, the if statement. if statements allow our program to make decisions on its own, mainly running different sections of code depending on some condition. In Java, if statement syntax looks like this:

if(condition) {
    put code to run here...
}

If the boolean (true or false) condition within the parentheses evaluates to true, then the code inside the curly braces will be run. Otherwise the program will skip to after the closing brace }. As an example, I've changed my code to make use of an if statement:

import org.mythicalrobotics.JavaPlayground;

public class App {
    public static void main(String[] args) throws Exception {
        JavaPlayground board = new JavaPlayground("COM4");

        while(true) {
            if(true) {
                board.setRedLED(true);
            }
        }
    }
}

In this code, the condition inside the if statement is true, so the code will run and the light turns on. Although, this condition isn't very interesting, as it is always true, so the line board.setRedLED(true); will always run.

The Circuit Playground boards have lots of ways that we can provide input to them, but we'll start with the two black buttons in the middle. The functions board.getLeftButton and board.getRightButton will return true if the respective button is pressed, and false if it is not. Change the condition inside the if statement from true to either of those function calls, remembering that you need to use parentheses after a function name to run it.

import org.mythicalrobotics.JavaPlayground;

public class App {
    public static void main(String[] args) throws Exception {
        JavaPlayground board = new JavaPlayground("COM4");

        while(true) {
            if(board.getLeftButton()) {
                board.setRedLED(true);
            }
        }
    }
}

With this code, the LED should not turn on right away. What do you need to do to make the LED light up? If you want to learn more about the functions present in the Java Playground library, you can hover over the function name in the editor, and a little window will pop up with more information. Alternatively, you can check the included documentation by opening index.html in the docs folder.

After the LED turns on, it never turns off again-- can you guess why?

Else

If you guessed that we never turned it off, you are correct. How would we turn it off if the button isn't pressed? We add an else to our if statement. It is just as the name implies, the code that is run if the condition in the if statement is false. In Java, the syntax looks like this:

if(condition) {
    code to run if true...
}
else {
    code to run if false...
}

Here is my code using an if-else statement to turn the LED on and off depending on the left button, but it doesn't work. Can you fix it so that the LED turns off when the button is not being pressed? Hint: the mistake is in the else section of code...

import org.mythicalrobotics.JavaPlayground;

public class App {
    public static void main(String[] args) throws Exception {
        JavaPlayground board = new JavaPlayground("COM4");

        while(true) {
            if(board.getLeftButton()) {
                board.setRedLED(true);
            }
            else {
                board.setRedLED(true);
            }
        }
    }
}

Can you modify this code to use the right button instead of the left? What about have the LED turn on whenever the button isn't pressed?

Double your fun

How about getting multiple lights to turn on? So far we've been using the red LED next to the USB port, but there are 10 RGB LEDs in a ring around the board. We can control those using the board.setLED function. This function has 4 parameters, or inputs that it needs to turn on an LED. The first is the index, or which LED to control. This index can be a number from 0-9, where 0 indicates the first LED. The second, third, and fourth inputs are the red, green, and blue values for the color, which can be in the range of 0-255 each.

import org.mythicalrobotics.JavaPlayground;

public class App {
    public static void main(String[] args) throws Exception {
        JavaPlayground board = new JavaPlayground("COM4");

        while(true) {
            if(board.getLeftButton()) {
                board.setLED(0, 255, 0, 0);
                board.setLED(1, 0, 255, 0);
                board.setLED(2, 0, 0, 255);
            }
        }
    }
}

Now we have three LEDs turning on when you press the button, but they're not turning off when you release it-- can you fix that using an else? In order to turn one of these LEDs off, set each of its color components to 0. Can you change it so that LED 5 turns on instead of LED 2? Can you make it purple instead of blue?

How about all the LEDs-- can you write a program to get them all to turn on?

  • Turn on all the left side LEDs with the left button. Turn on the right side with the right button.
  • Make all turn on red with the left button. Make all turn on green with the right button.

Lots of repeated lines

If you were turning all the lights on and off, you may have had code that looked very much like this:

import org.mythicalrobotics.JavaPlayground;

public class App {
    public static void main(String[] args) throws Exception {
        JavaPlayground board = new JavaPlayground("COM4");

        while(true) {
            if(board.getLeftButton()) {
                board.setLED(0, 255, 0, 0);
                board.setLED(1, 255, 0, 0);
                board.setLED(2, 255, 0, 0);
                board.setLED(3, 255, 0, 0);
                board.setLED(4, 255, 0, 0);
                board.setLED(5, 255, 0, 0);
                board.setLED(6, 255, 0, 0);
                board.setLED(7, 255, 0, 0);
                board.setLED(8, 255, 0, 0);
                board.setLED(9, 255, 0, 0);
            }
            else {
                board.setLED(0, 0, 0, 0);
                board.setLED(1, 0, 0, 0);
                board.setLED(2, 0, 0, 0);
                board.setLED(3, 0, 0, 0);
                board.setLED(4, 0, 0, 0);
                board.setLED(5, 0, 0, 0);
                board.setLED(6, 0, 0, 0);
                board.setLED(7, 0, 0, 0);
                board.setLED(8, 0, 0, 0);
                board.setLED(9, 0, 0, 0);
            }
        }
    }
}

Whew. That was a lot of typing. I hope you at least copy and pasted the lines. But you can always make mistakes that way, or maybe forget to increase the pixel index.

We want to reduce the amount of code we write. We are doing the same thing over and over with one very small change. Loops are a way we can accomplish this. But first, a quick intro to variables.

Variables

If you have done any algebra, you know about variables. Look at this math equation and substitution of x:

x = 1
y = 2x + 3
y = 2(1) + 3
y = 5

We used variable x to solve for y. Programming variables work very similarly, but they can be boolean, strings, or numbers (or other things we will get to). Check out this version of turning on one neopixel. Note the very simple change.

import org.mythicalrobotics.JavaPlayground;

public class App {
    public static void main(String[] args) throws Exception {
        JavaPlayground board = new JavaPlayground("COM4");

        int index = 0;

        while(true) {
            if(board.getLeftButton()) {
                board.setLED(index, 255, 0, 0);
            }
            else {
                board.setLED(index, 0, 0, 0);
            }
        }
    }
}

Here, I've created an int variable called index. int means integer, so this variable can hold numbers like 0, 12, -5928, but not 3.14. There are many different data types in Java, and you will become familiar with them over time. There is some good information about types on this page. index is just a name I picked. Choosing clear variable names is another useful programming skill that will help you write code that is easy to understand.

We didn't say to turn on pixel 0, we said to turn on pixel index. We had set it to zero, so this does the same thing. Can you change this to set neopixel 4 on and off instead of 0? What happens if you try to turn on pixel -2, or 1000?

Variables, as indicated by their name, can be changed while the program is running.

import org.mythicalrobotics.JavaPlayground;

public class App {
    public static void main(String[] args) throws Exception {
        JavaPlayground board = new JavaPlayground("COM4");

        int index = 0;

        while(true) {
            if(board.getLeftButton()) {
                board.setLED(index, 255, 0, 0);
                index = 1;
                board.setLED(index, 0, 255, 0);
                index = index + 1;
                board.setLED(index, 0, 0, 255);
            }
        }
    }
}

We can set variables directly to a value, such as index = 1, or we can use Java's math and logical operators to configure some more complicated expressions like index = index + 1. Can you change this code to light up LEDs 2, 3, and 4 instead?

Besides just addition, Java has other arithmetic operators:

+ : addition 2+5 = 7
- : subtraction 5-1 = 4
* : multiplication 5*5 = 25
/ : division 10 / 2 = 5
% : modulo (remainder) 8 % 3 = 2

If you need more complicated math like exponents, square roots, or trigonometric functions, we can import them from Java's math library.

However, simply using a variable doesn't make this process any less tedious... Is there a better way?

Loop-de-loop

Now that we see how variables work, and that they can change values, we can talk about loops. We are going to start with a while loop. You have already seen a while loop where the condition was always true but now we will experiment with conditions that can end the loop. The syntax for a while loop looks like this:

while(condition) {
    run the code in here...
}

After each time the code inside the curly braces completes, the program will check the condition again. If the condition is still true, the code inside the block will run again. If the condition is now false, the loop will stop and the program can move to the next section of code. Check out this next example!

import org.mythicalrobotics.JavaPlayground;

public class App {
    public static void main(String[] args) throws Exception {
        JavaPlayground board = new JavaPlayground("COM4");

        int index = 0;

        while(true) {
            if(board.getLeftButton()) {
                index = 0;
                while(index < 10) {
                    board.setLED(index, 0, 0, 255);
                    index = index + 1;
                }
            }
            else {
                index = 0;
                while(index < 10) {
                    board.setLED(index, 0, 0, 0);
                    index = index + 1;
                }
            }
        }
    }
}

Here you can see the first use of a comparison operator < which is "less than" just like in math. The comparison operators all evaluate to one of the boolean values true or false. There are several others too:

< : less than : 3 < 5 is true
> : greater than : 3 > 4 is false
== : is equal to : 8 == 8 is true
!= : not equal to : 7 != 7 is false
<= less than or equal: 3 <= 3 is true
>= greater than or equal: 10 >= 6 is true

Since these evaluate to a boolean result, we can use them inside the conditions of loops and if statements.

When we press the left button, index gets set to 0. Then we set LED 0 to be blue, and increase the index variable by 1. Now index equals 1, which is still less than 10, so the while loop runs again. This time we turn LED 1 blue, and increase the index variable up to 2. This process repeats until index equals 10, which turns on every LED on the board!

Notice how much smaller and faster to type this code was than the previous version that turned on every LED. What happens if you increase index by 2 each time instead of 1? Can you predict what happens if you decrease the number in the loop condition from 10 to 8?

There is another more advanced kind of loop called the for loop, which you can read about here.

Functions - Repeatable sections of code

When we first started talking about variables, we talked about a math function to calculate y. y = 2x + 3 We make functions in programming like that too. They don't need to solve math problems, but they can. Let's learn about functions by using the thermometer on the Circuit Playground.

import org.mythicalrobotics.JavaPlayground;

public class App {
    public static void main(String[] args) throws Exception {
        JavaPlayground board = new JavaPlayground("COM4");

        while(true) {
            System.out.println(board.getTemperature());
            Thread.sleep(1000);
        }
    }
}

Here is some code that prints out the temperature of the board once every second. You'll see from the output that the number is a decimal number, which we call a float in programming. The number also seems a little low, that's because it is in degrees Celsius, not Fahrenheit! Let's write a function in order to convert from Celsius to Fahrenheit.

The formula for converting from Celsius to Fahrenheit is to multiply by 9, divide by 5, and then add 32. We can do the same thing in our code.

static float celsiusToFahrenheit(float tempInC) {
    return ((tempInC * 9) / 5) + 32;
}

In this example, celsiusToFahrenheit is the name of the function, which takes one float type input called tempInC. The function's return type is indicated by the keyword float right before the function name, so this function takes in one decimal number, and gives us back another decimal. Notice the use of parentheses to make sure that the order of operations is correct. The keyword static is easier to explain a little later in your Java journey, but feel free to look it up or ask someone if you are curious.

In order to add this function to your code, copy (or re-type) it outside of the main method curly braces, but inside of the App class braces. Like so:

import org.mythicalrobotics.JavaPlayground;

public class App {
    public static void main(String[] args) throws Exception {
        JavaPlayground board = new JavaPlayground("COM4");

        while(true) {
            System.out.println(board.getTemperature());
            Thread.sleep(1000);
        }
    }

    static float celsiusToFahrenheit(float tempInC) {
        return ((tempInC * 9) / 5) + 32;
    }
}

You may have now realized that main is itself a function, and it is generally a bad idea to try and create functions inside of other functions.

We can test our function by adding System.out.println(celsiusToFahrenheit(0)); before the while(true) loop. 0 degrees Celsius should give you back 32 degrees Fahrenheit. Typing a function name followed by parentheses containing any required inputs is "calling" a function. You have already been calling a lot of functions, like board.setRedLED(true) or board.getLeftButton().

We write functions in order to make our code easy to re-use. Imagine if you had to re-type a mathematical formula for converting Celsius to Fahrenheit 15 different times throughout your code!

Let's modify the code above in order to convert the board's temperature to Fahrenheit before printing it out. In order to do this, you will need to pass the board temperature into the conversion function you just added before calling System.out.println. You might find it easier if you create a variable first, though you do not have to.

float tempInF = celsiusToFahrenheit(board.getTemperature());

Now, if you replace the board.getTemperature() within the System.out.println call with the variable tempInF, you should get some more familiar numbers. What happens if you touch the thermometer icon on the Circuit Playground, or blow on it?

Tada!

Guess what? You are now a programmer. Most of what we do as programmers we have just discussed. We create functions, we call them, we do a bit of math, we do loops, we use other libraries, and we troubleshoot when things go wrong. Is there more to learn? Of course. Check out the challenges page.

Clone this wiki locally