Distance Sensor Introduction
In this post I'll show a few examples of how you can use Marty's Infrared distance sensor add on to get Marty to react to his environment. The video above shows the examples we'll go through here
Scratch X or Scratch 3
What is the distance/proximity sensor?
The distance sensor we use with Marty is a modulated infrared sensor. It's the big black rectangular block on the circuit board:

This is the bit that actually does the sensing, so it's important to make sure it's not covered!
You'll see in the photo above that it has two circular lenses, one of these is an emitter and one is a receiver. The emitter sends out modulated infrared light - its frequency is beyond what human eyes can perceive, but if you try pointing a phone camera at it you'll probably see one off the lenses glowing!
That infrared light will reflect off of an object that's in front of the sensor, and some of it will make it back to the receiver. The sensor measures how much light makes it back to the receiver to estimate how far away an object is. The closer an object, the less light will scatter in other directions and the more will make it back to the receiver.
Because the sensor measures the intensity of the received light, you might find you get different readings for a reflective white object at the same distance as a matte black one.
The sensor can measure distances from about 1cm all the way up to about 1.5m!
Connecting the Distance Sensor
Make sure Marty is turned off when you connect the distance sensor.
Distance Sensor Examples!
Ok, let's see some things we can do with the distance sensor!
Wave Activated Wiggling
This is a really simple script that will get Marty to wiggle when something comes close:

This will only wiggle once, so you could put those blocks in a loop to make it happen whenever something gets close!
The threshold
here is set to 250, try changing that up or down to see what happens!
Run Away!
This code will make Marty maintain a distance from an approaching object. Good for avoiding homework!

We also make Marty's eyes go wide when an object is detected, then return to normal once the way is clear
Turn Around to Find an Object, then Walk to it
This is the opposite of the last set of code, and this will make your Marty super-friendly! It'll turn around until the sensor detects something, and then it'll walk towards it, stopping and wiggling once it's really close!

You could change what Marty does when he gets to the object. He could kick it, or even sidestep around it and then proceed to the next obstacle!
Suprise!
This little script gets Marty to wait somewhere where he's hidden (like inside a cupboard or behind a book), and then when somebody discovers him he'll suprise them!

In future we'll show off a few more things you could do with the distance sensor, but that doesn't stop you inventing more for yourself now!
Why not see if you can get Marty to navigate a simple maze using the sensor!