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 hourglass code!

Step 1: Introduction

In this lesson you will learn how to write the code that lights up the LEDs at regular time intervals. To reset the Digital Hour glass, you will tip the tilt sensor and detect a change the voltage on its digital pin.

Our version of the Digital Hourglass 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: Declare a Named Constant

You’re going to need a number of global variables in your program to get this all working. To start, create a constant named switchPin. This will be the name of the pin your tilt switch is on.

  1. Copy the code below into the Code Editor.

    const int switchPin = 8;

  2. Continue to the next step.

Step 3: Create a Variable to Hold the Time

Create a variable of type "unsigned long." This will hold the time that an LED was last turned on.

  1. Copy the code below into the Code Editor:

    unsigned long previousTime = 0;

  2. Continue to the next step.

Step 4: Name Variables for Inputs and Outputs

Create a variable for the switch state, and another to hold the previous switch state. You’ll use these two to compare the switch’s position from one loop to the next.

Next create a variable named led. This will be used to count which LED is the next one to be turned on. We'll start out with the LED on digital pin 2.

  1. Copy the code below into the Code Editor.
    int switchState = 0; 
    int prevSwitchState = 0; 
    int led = 2;
  2. Continue to the next step.
  3. Stuck? HINT: Remember, we don't need to know the exact position of the switch -- we just need to know if it has changed.

Step 5: Declare Time Interval

The last variable you’re creating is going to be the interval between each LED turning on. This will be be a long datatype.

In 10 minutes (the time between each LED turning on) 600,000 milliseconds pass.

  1. Copy the code below into the Code Editor.
    long interval = 600000;
  2. If you want the delay between lights to be longer or shorter, this is the number you change!
  3. This is the last line in the header of the code!
  4. Continue to the next step.

Step 6: Set Direction of Digital Pins

In your setup(), you need to declare the LED pins 2-7 as outputs. A for() loop declares all six as OUTPUT with just 3 lines of code.

In pseudocode, the for loop() and its argument reads: Starting with a value of x = 2, assign the pin mode to pin x. When the loop repeats, add 1 to x using the ++ operator. Keep repeating as long as x remains less than 8.

You also need to declare switchPin as an INPUT.

  1. Copy the code below into the Code Editor.
    void setup(){ 
    	for(int x = 2; x < 8 ;x++){ 
    		pinMode(x, OUTPUT); 
    	} //end of for() 
    	pinMode(switchPin, INPUT); 
    } //end of setup()
  2. Notice that this is the entire setup() function!
  3. Continue to the next step.
  4. Stuck? HINT: This is the entire setup() function!

Step 7: Check Time Since Start of Program

When the loop() function starts, you’re going to get the amount of time the Arduino has been running with millis() and store it in a local variable named currentTime.

  1. Copy the code below into the Code Editor.
    void loop() { 
    	unsigned long currentTime = millis();
  2. Recall that millis() simply returns the amount of time since the start of the program. So currentTime is the total amount of time that the program has been running so far, counting one millisecond (ms) at a time.
  3. Continue to the next step.
  4. Stuck? HINT: A local variable is declared within a function. In this case, it is declared and used only within the loop() function.

Step 8: Find Out If 10 Minutes Have Passed

Using an if() statement, you’ll check to see if enough time has passed to turn on the next LED.

Subtract the previousTime from the currentTime and check to see if it is greater than the interval variable. If 600,000 milliseconds have passed (10 minutes), you’ll update the variable previousTime to the value of currentTime.

Notice that this is NOT the end of the if() statement. It will continue in the next step.

  1. Copy the code below into the Code Editor.

    	if(currentTime - previousTime > interval){  
    		previousTime = currentTime;

  2. Using this method, the current time becomes the new previous time, which will be used for the next comparison. The value of previousTime only updates every ten minutes.
  3. Continue to the next step..

Step 9: Turn on an LED

When previousTime updates (every 10 minutes, or "interval"), you'll also turn on the LED and increment the led variable. The next time you pass the time interval, the next LED will be ready to light up.

  1. Copy the code into the Code Editor.

    		digitalWrite(led, HIGH); 

  2. Remember that LEDs are attached to the Arduino starting with pin 2. This code sets pin 2 high (turning on first LED), then updates the value of led to get the next pin (3) ready to go.

  3. Continue to the next step.

Step 10: See If All Lights Are On

Add one more if statement in the program to check if the LED on pin 7 (the last LED) is turned on. Don’t do anything with this yet. You’ll decide what happens at the end of the hour later!

When all of your code is written, you will see that there is one if() statement nested inside the other!

  1. Copy the code below into the Code Editor.

    		if(led == 7){  
    			//your code goes here! 
    		} //end of nested if() 
    	} //end of outer if()

  2. You can replace the comment with something creative later on.

  3. Continue to the next step.

Step 11: Read the Switch Value

Now that you’ve checked the time, you’ll want to see if the switch has changed its state in the meantime. Read the switch value into the switchState variable.

  1. Copy the code below into the Code Editor.

    	switchState = digitalRead(switchPin);

  2. Continue to the next step.

Step 12: Reset Variables, If Needed

With an if() statement, check to see if the switch is in a different position than it was previously. The != evaluation checks to see if switchState does not equal prevSwitchState.

If they are different, that means you tilted the sensor. Then you will do the following:

Turn the LEDs off

Return the led variable to the first pin

Reset the timer for the LEDs by setting previousTime to currentTime

  1. Copy the code below into the Code Editor.

    	if(switchState != prevSwitchState){ //switch has changed position 
    		for(int x = 2; x < 8; x++){ 
    			digitalWrite(x, LOW); 
    		led = 2; 
    		previousTime = currentTime; 

  2. We recommend adding some of your own comments to this section of code!

  3. Continue to the next step.

Step 13: Update Switch State

At the end of the loop(), save the switch state in prevSwitchState, so you can compare it to the value you get for switchState in the next loop().

This is the end of your program!

  1. Copy the code below into the Code Editor.

    	prevSwitchState = switchState; 
    } //end of loop()

  2. Continue to the next step.

Step 14: Use It! (simulator)

Before you upload and run the code, you might want to make your time interval lower. One hour is a long time to

long interval = 15000;
Now upload and run the code!

  1. Modify the time interval and press Upload & Run. The simulation will start.
  2. Once you’ve programmed the board, the first LED should turn on after 15 seconds (or whatever interval value you set). Every 15 seconds after that, a new light will turn on. After a minute and a half, all six light should be on.
  3. When you flip the tilt switch to change its state, the lights will turn off and the timer will start again. To operate this sensor in the simulator, click on the sensor to highlight it, then move the slider in one direction or the other (see picture above).
  4. Continue to the next step.

Step 15: Use It! (Arduino Kit)

When using the Arduino kit, follow the basic instructions from the previous step. Like you did in the simulator, you can shorten the interval time while you are trying the project for the first time.

  1. Plug in your Arduino Uno and upload the sketch, then keep time with your Digital Hourglass!

  2. The Arduino kit lets you physically interact with the digital hourglass: to change the state of the tilt sensor, literally tilt your breadboard upside down.

  3. You don’t need to have your Arduino tethered to the computer for this to work. Try building a stand with some cardboard or styrofoam and power the Arduino with a 9V battery to make a portable version. You can create a cover with some numeric indicators alongside the lights.

  4. Continue to the next step.

Step 16: Think About It...

When the clock runs out and all six lights are on, they just stay on. Can you think of a way to get your attention when the hour is up? Sound or flashing the lights are both good indicators. This is the line of code you will want to edit is shown below:

  1. Unlike an hourglass filled with sand, the lights go either up or down depending on the orientation of the switch. Can you figure out how you can use the switchState variable to indicate what direction the lights should go?

  2. Continue to the next step.

Step 17: Review

Congratulations on completing the the Digital Hourglass project!

In addition to using a new component, the tilt sensor, you also used a new function called millis() to keep track of the total time that a program has been running (i.e. the total elapsed time).

To measure the amount of time between events in milliseconds, you should use the millis() function. It's a good idea to use the datatype 'unsigned long' for storing its extremely large values.

Check out other great projects here.



    • Sweet Treats Challenge

      Sweet Treats Challenge
    • Remix Contest

      Remix Contest
    • Epilog X Contest

      Epilog X Contest