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 Capstone.
  2. Create an experiment page that contains a digits and graph display.
  3. Select Code in the Tools palette 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 a sensor data

  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 <.

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 it 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, you can right-click the first text output block, select Duplicate, and drag the duplicated block to else.

  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 it.
  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 to close the Code tool.

Run the program

  1. Click <Select Measurement> in the Digits display, then select message.
  2. Click <Select Measurement> in the y-axis of the Graph display, then select Brightness.
  3. Click Record .
  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.