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
- Connect the sensor to SPARKvue using the Sensor Data path.
- Select the digits and graph template.
- Click the Code button to open the Code tool.
Add a block to the workspace
- Select the Logic category in the toolbox.
- Drag an if block from the toolbox to the workspace.
Modify the block
- Click the gear in the block.
- Drag the else block and connect it to the if block.
- Click the gear to close it.
Connect a second block
- Select the Logic category.
- Drag the equality block and connect it to the if block.
Create a condition using data from a sensor
- Select the Hardware category. Drag the value of block and insert it into the equality block's first space.
- Select the Math category. Drag a number block and insert it into the equality block's last space.
- Click inside the number block, then enter the number
1
. - Click the equal sign
=
, then select the less than sign<
from the list.
Create an output
- Select the Code Output category, then click Create text output.
- In the window, enter
message
, then click OK. This creates a text output block. - Drag the text output block and connect to do in the if block.
- Click inside the text block, then enter
It's dark
. -
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.
-
Click inside the text block, then enter
It's bright
.
Create a loop
- Select the Loops category. Drag the repeat while block and place it over the if block so it surrounds the if block.
- Select the Logic category. Drag the true block and connect it to the repeat while block.
- 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.
- Click Code again to exit the Code tool.
Run the program
- In the Digits display, click the Brightness measurement.
- Select the User-entered tab, then select message.
- Click Start .
-
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.
- Explore the Code tool features by looking at the Code tool overview.
- Learn more about how the blocks in this lesson are used, or learn about some new blocks, in the Blockly toolbox.
- If you have a //code.Node or //control.Node, import programs provided in the PASCO Code Library.
- Download a Blockly Extension experiment from the PASCO Experiment Library.