# Building A Robot: The Proximity Sensor

The Theory
This section will focus on two main theory topics: how the IR Proximity Sensor works and how the Headphone Speaker beek is generated. Most of the theory focus will be on the sensor since that is what we're primarily here to learn about.

The IR Proximity Sensor
The sensor we are using can accurately detect objects 10cm to 80 cm away. When an object in that range is detected an analog signal is output with a steady voltage level. The short animation below gives you a graphical idea for how the detection distance correlates to a steady output voltage.

For a better view of the Output Voltage(V) to Distance(cm) please see the graph below. When programming our robot for distances, we can use this graph to find out what voltage output to our microcontroller correlates to what exact distance.

In order to understand the analog voltage output, our microcontroller will need to use an analog to digital converter. The PIC 18F252 microcontroller has a 10-bit analog to digital converter that we will use. If we use our battery's +5v for the A/D reference then our PIC's analog to digital converter will see that same +5v as 1023 (in binary: 1111111111) and +0v as 0. Using a simple formula:   X = (Voltage/5)*1023   we can now find a voltage for anywhere on the graph above.
For example, if we want to know how the PIC would 'see' an analog voltage of +2.5v or 10cm, we plug in +2.5v to the formula:   X = (2.5/5)*1023 = 511

Speaker Beeping
We'll add a speaker to this project just because it doesn't take much extra effort, just a speaker with 2 wires and a few extra lines of code in the firmware. The way we will output tones to the speaker will be using a 50% duty cycle PWM at different sequential frequencies that repeat. This will give a siren effect, and a bit of a freaky noise. A digital timer with interrupt will be used to update the tone PWM frequency. To learn more about generating proper tones, the Mini IR Theremin project, that I built is a good place to see how to accurately generate music tones.

;