Analog Distance Sensor

From Mech
Jump to navigationJump to search

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:
/*
  AnalogReadSerial
  Reads an analog input on pin 0, prints the result to the serial monitor.
  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:
  int sensorValue = analogRead(A0);
  // 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() {
 //read sensor value
 int sensorValue= analogRead(A0)
 //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
 }

 delay(1); //delay between readings
}
  • Try using this distance sensor with a few RGB LEDs to "show" how far away an object is with the intensity of the color of the LEDs!
    • Try using the RGB LEDs with this sensor like a red/yellow/green stoplight