Ultrasonic Sensor Lab

Step 1.

Keep the stage open so you can see the Panda.  You need the stage open to see variables you will make later.

Start the program by going to the Events category and pulling out when Flag clicked.

Step 2.

Go to the Control category and pull out a forever loop.

Step 3.

Go to Data&Blocks.  Click on Make a Variable.  Call the variable "Distance".  Leave it on For all sprites.  Click ok.

This variable will tell us the reading from the ultrasonic sensor.

Step 4.

Pull out "set Distance to 0" into the forever loop.

Step 5.

Go to the Robot category.  Past the mid-way point, pull out "ultrasonic sensor Port 1 distance" and put it into the 0 of "set Distance".

Change Port 1 to the Port you have connected your ultrasonic sensor to.

Step 6.

Click on the Green flag to see the Distance variable change.  Play with it so you understand the max and minimum readings.

Listen closely to see if you hear the "chirping".

Step 7.

Step 8.

Steps 1-7 was just so you could see what the values were for the distance sensor.

Now we'll make a program to make the lights change when you are too close.

Pull out another "when Flag is clicked" from the Events category.

Then go to the Control category and pull our a Forever, and then an if-then-else and put it inside the Forever.

Step 9.

Go to the Operators category.  Pull out a < symbol or "less-than" symbol and put it into the if-then condition box.

Step 10.

Go to the Data&Blocks category and drag the variable called Distance into the left side of the < condition (less-than condition).

Enter 4 into the right side or a number representing the range at which you want the color to change if your hand is too close to the sensor.

Step 11.

Go to the Robots category.  Pull out "set led led on board" and put it in both spots of the if-then-else statement.

Change the first "set led" to 60 in the red category.  This is the color if you're too close.

Change the second "set led" to 60 in the green category.  This is the color if you're not too close.

You are done!  Click the Green flag and move your hand closer to the ultrasonic sensor until the color changes from green to red!

(Remember to connect your mBot and turn it on as standard).

Short Version

If you wish, there is a shorter way to do this program.  Instead of making a variable called Distance, if you know the value that you want to change the color at already, you can just put the "ultrasonic sensor Port 1 distance" script into the < (less than) area.  But you won't be able to monitor the actual distance value.

Remember that you still will have to change the port to the correct one!  This is a common mistake.