# Analog Distance Sensor

(Difference between revisions)

## Sharp 4-30 cm Analog Distance Sensor

Summary

• This sensor detects reflective objects that are 4-30 cm away.
• The sensor outputs a voltage from approximately 0-3.3 volts which you can read into a microcontroller

Wiring

• This sensor has three cables coming out of it: red-power, black-ground and white-signal.
• Wire the power cable to the Arduino's 5V, the ground to the Arduino's ground
• Plug the signal cable into any of the Arduino's analog input pins (A0-A5 for the Arduino UNO) with a small pull-down resistor

Programming

• Looking at the graph on page 4 in the datasheet for the sensor, it looks like the range of 4-30 cm corresponds to a range of 2.5-0.4 volts.
• We can use the Arduino's analogRead() function to read in this signal. By using the analogRead function, our result will be a number in the range 0-1023, which corresponds to 0-5 volts.
• To calibrate and find values for our sensor, we can stream the output values of our sensor using a program similar to this example from the Arduino website:
```/*
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

This example code is in the public domain.
*/

// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
// print out the value you read:
Serial.println(sensorValue);
delay(1);        // delay in between reads for stability
}
```
• To trigger some event when an object is further than a certain distance away, instead of using Serial.println on our sensorValue variable, we could compare it to some min_value variable using an if statement:
```
int min_val=30;

void setup(){
}

void loop() {
//convert this value to a distance, consider using the "map" function

if (sensorValue > min_val)
{
// activate your event using a digitalWrite or some other function
}