Writing the Code

About: Learn electronics and Arduino with Tinkercad Circuits!

The following information is a single lesson in a larger project. Find more great projects here.

Return to Previous Lesson: Setting Up the Circuit

Lesson Overview:

Now we'll write our spaceship code!

Step 1: Introduction

In this lesson you will learn how to write the code that connects the button input to the LED outputs.

Our version of the Spaceship Interface circuit is already in the Workplane -- it should look a lot like the circuit that you created in the previous lesson.

  1. Continue to the next step.

Step 2: Some Notes Before You Start

You will see that in every Arduino program there are two main sections marked setup() and loop(). These are called "functions."

Functions are a part of computer programs that perform very specific tasks. In this lesson we will introduce many functions including pinMode(), digitalRead(), digitalWrite(), and delay() that are already part of the Arduino environment. setup() and loop() are the two main functions that you will define yourself. These functions and their definitions are shown below.

  1. setup() is a function that only runs once. Within this section you can define variables or assign pins as inputs or outputs.
  2. loop() is a function that repeats itself continuously. This is where the bulk of you program will be written. Mainly it will be used to check the status of an input pin (such as a button), and translate it to a specific output (such as flashing lights).
  3. Continue to the next step.

Step 3: Leaving Comments

In the Code Editor you will notice some tan or gray colored text in it that always begins with a double slash //. These are called comments.

If you ever want to include natural language in your program that provides an explanation of the code, you can leave a comment. In this case, the computer will ignore anything that starts with //. It is a good idea to get in the habit of commenting your code. Then when you come back to a project later, you will know exactly what your thought process was when you created it!

  1. Read the comments in the Code Editor beginning with the double slash //. We left comments describing the setup() and loop() functions.
  2. Continue to the next step.

Step 4: Let's Start Coding!

The first thing that you will do is create a variable. Variables simply store values that can change depending on your program’s instructions. For example, a variable named switchState could have a value of HIGH or LOW depending on whether a button is pressed.

To create a variable, you need to declare a datatype. The datatype int will hold an integer. That’s any positive or negative number without a decimal point. When you declare a variable, you usually give it an initial value as well. Every statement in the code must also end with a semicolon (;) as shown below.

  1. Copy the code into the Code Editor. The comments are already there. //header //define variables and constants int switchState = 0;
  2. Continue to the next step.
  3. Stuck? HINT: Try to make your variable names descriptive of what they represent. For example, 'switchState' stores the status of a switch. A variable called 'x' doesn't tell you much about what it does.

Step 5: Configure Pin Modes

The setup() runs once, when the Arduino is first powered on. This is where you configure the digital pins to be either inputs or outputs using a function named pinMode(). The pins connected to LEDs will be OUTPUTs and the button's pin will be an INPUT.

  1. Copy the code, into the code editor. The comments are already there. //setup // the setup routine runs once when upload the sketch:\u200b void setup() { pinMode(3, OUTPUT); pinMode(4, OUTPUT); pinMode(5, OUTPUT); pinMode(2, INPUT); }
  2. pinMode() is the first built-in function that you have used! Functions take an "argument" in the parentheses. Arguments are the values, variables, names of pins, etc that the function takes action on.
  3. In this case, the function pinMode(A,B) needs to know A: what pin we are considering, and B: whether we want the pin to be an input our output. The function then tells the program to make that pin mode assignment!
  4. Continue to the next step.
  5. Stuck? HINT: Pay attention to the case sensitivity in your code. For example, pinMode is the name of a command, but pinmode will produce an error!

Step 6: Create the Loop Function

The loop() runs continuously after the setup() has completed. The loop() is where you’ll check for voltage on the inputs, and turn outputs on and off.

To check the voltage level on a digital input pin, you use the function digitalRead(). This function expects one argument: the pin that it is checking.

If there’s voltage on the pin when digitalRead() is called, it will return a value of HIGH or 1. If there is no voltage on the pin, it will return the value LOW (or 0). The returned value is stored in the variable switchState in your program.

  1. Copy the code into the Code Editor. //loop // the loop routine runs over and over again forever: void loop() { switchState = digitalRead(2);
  2. Notice that function names are colored purple or orange in the Code Editor and Arduino IDE, respectively.
  3. Continue to the next step.

Step 7: If Statement Pseudocode

In the previous step, we used the word 'if' in natural language to check the state of something (the switch position). An if()...then statement in programming checks to see if some condition is true before performing an action.

Before continuing, It can be helpful to write out the flow of your program in pseudocode: a way of describing what you want the program to do in plain language. The Pseudocode for the if statement, and an explanation, are shown below.

If the switchState is LOW: turn on the green LED, turn the red LEDs off.

If the switchState is HIGH: turn the green LED off, turn the red LEDs on and blink them.

  1. In the next step, you will want to determine if switchState is HIGH or LOW (meaning that the button is pressed) or not, and change the lights based on this.
  2. In pseudocode this looks like: if the switchState is LOW: turn on the green LED, turn the red LEDs off. if the switchState is HIGH: turn the green LED off, turn the red LEDs on and blink them.
  3. Continue to the next step.

Step 8: If the Button Is Open

Now you can write the actual 'if statement' code! Notice in the code below that two equal signs (==) are used to check if the switchState is LOW (i.e. if the button is not pressed).

digitalWrite() is the command that allows you to send 5V or 0V to an output pin. digitalWrite() takes two arguments: what pin to control, and what value to set that pin. The following code turns the green LED on and the red LEDs off if the button is not pressed.

  1. Copy the code into the Code Editor. //if the button is not pressed if (switchState == LOW) { digitalWrite(3, HIGH); // green LED on digitalWrite(4, LOW); // red LED off digitalWrite(5, LOW); // red LED off }
  2. Remember to include all of the curly brackets! When the code is complete you will see how different sections, like the if() section, are contained between brackets { }.
  3. The if() statements will continue in the next step.
  4. Continue to the next step.
  5. Stuck? HINT: Remember to always use the double == for comparisons. If you use only one sign, you will be setting a value instead of comparing it.

Step 9: If the Button Is Pressed

You’ve told the Arduino what to do when the button is open. Now define what happens when the button is closed. The if() statement has an optional "else" component that allows for something to happen if the original condition is not met.

In this case, you already checked to see if the switch was LOW. So write code for the HIGH condition after the else statement.

  1. Copy the code into the Code Editor //if the button is pressed else { digitalWrite(3, LOW); digitalWrite(4, LOW); digitalWrite(5, HIGH);
  2. We're not quite done with the else statement. In the next step you will learn how to blink the red LEDs.
  3. Continue to the next step.

Step 10: Blink the Red LEDs

To get the red LEDs to blink when the button is pressed, you’ll turn the lights off and on in the else statement you just wrote.

You’ll want the Arduino to pause for a moment before changing the LED pin between high and low. If you don’t wait, the lights will go back and forth so fast that it will just appear dim instead. This is because the Arduino runs its loop() thousands of times each second, and we can't perceive that blinking rate! The delay() function lets you stop the Arduino from executing anything for a period of time, equal to the function's argument. delay(250) will pause for 250 milliseconds, or 0.25 seconds (a quarter second).

  1. Copy the code into the Code Editor. delay (250); //wait a quarter second //toggle the red LEDs digitalWrite(4, HIGH); digitalWrite(5, LOW); delay (250); } //end of else statement } //end of loop()
  2. The last bracket that you type into the Code Editor does not go with the if() statements -- it is to end the loop() function as a whole.
  3. Continue to the next step.
  4. Stuck HINT: There are 1000 milliseconds in 1 second. The prefix "milli" means "one thousandth."

Step 11: Use It!

Now that your code is written, click the Upload & Run button to run the simulated circuit. If you are using the Arduino kit, plug in your Arduino Uno and upload the sketch.

We used the delay function to set the blinking rate. When you call a delay() in your program, it stops all other functionality. No sensor readings will happen during that time. While delays are often useful, when designing your own projects make sure they are not unnecessarily interfering with your project.

  1. Click the Upload & Run button or upload the sketch to your Arduino Uno from Arduino IDE.
  2. Once your Arduino is programmed, you should see the green light turn on. When you press the button, the red lights will start flashing, and the green light will turn off.
  3. Next, try changing the time of the two delay() functions; notice what happens to the lights and how the response of the system changes depending on the speed of the flashing. Example code is shown below.
  4. Continue to the next step.

Step 12: Think About It...

In your time remaining, try making more modifications to the code. How would you get the red LEDs to be blinking when your program starts? How could you make a larger, or more complex interface for your interstellar adventures with LEDs and buttons?

  1. Continue to the next step.

Step 13: Review

Congratulations on completing the Spaceship Interface circuit and code! This project linked a digital input (button) to digital outputs (solid and blinking lights).

When designing interfaces for future projects, think about a user's expectations. When they press a button, will they want immediate feedback? Should there be a delay between their action and what the Arduino does? Try and place yourself in the shoes of a different user while you design, and see if your expectations match up to the reality of your project.

  1. Continue on the next lesson to learn more about resistor color codes and how to build a paper cover for your Spaceship Interface.

Next Lesson:How to Read Resistor Color Codes



    • Faux-Real Contest

      Faux-Real Contest
    • Remix Contest

      Remix Contest
    • Build a Tool Contest

      Build a Tool Contest