Skip to content

Create a program using sensor data

Learn how to code a simple program and use sensor data to control outputs.

In this tutorial, we're going to build a program to output a message when a light sensor detects darkness. Though this tutorial is written specifically for a light sensor, you can use alternative sensors by making some minor modifications to the code.

Set up the sensor

  1. Connect the sensor to SPARKvue using the Sensor Data path.
  2. Select the digits and graph template.
  3. Click the Code button to open the Code tool.

Add a block to the workspace

  1. Select the Logic category in the toolbox.
  2. Drag an if block from the toolbox to the workspace.

Modify the block

  1. Click the gear in the block.
  2. Drag the else block and connect it to the if block.
  3. Click the gear to close it.

Connect a second block

  1. Select the Logic category.
  2. Drag the equality block and connect it to the if block.

Create a condition using data from a sensor

  1. Select the Hardware category. Drag the value of block and insert it into the equality block's first space.
  2. Select the Math category. Drag a number block and insert it into the equality block's last space.
  3. Click inside the number block, then enter the number 1.
  4. Click the equal sign =, then select the less than sign < from the list.

Create an output

  1. Select the Code Output category, then click Create text output.
  2. In the window, enter message, then click OK. This creates a text output block.
  3. Drag the text output block and connect to do in the if block.
  4. Click inside the text block, then enter It's dark.
  5. Drag another text output block and connect it to else in the if block.

    Tip

    Alternatively, right-click the first text output block and select Duplicate.

  6. Click inside the text block, then enter It's bright.

Create a loop

  1. Select the Loops category. Drag the repeat while block and place it over the if block so it surrounds the if block.
  2. Select the Logic category. Drag the true block and connect it to the repeat while block.
  3. Select the Loops category. Drag the break out of loop block and connect it to the bottom of the do statement in the if block.
  4. Click Code again to exit the Code tool.

Run the program

  1. In the Digits display, click the Brightness measurement.
  2. Select the User-entered tab, then select message.
  3. Click Start .
  4. Cover the sensor to see the message change. This also stops the program.

    Tip

    You can also click Stop to stop the program manually.

Next steps

Now that you've created your first program, here are some further topics you can explore to take your coding to the next step.