Advertisement
microrobotics

Pololu Sharp Distance Sensor (GP2Y0D810Z0F)

Apr 21st, 2023
578
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. The Pololu Sharp Distance Sensor (GP2Y0D810Z0F) with a sensing range of 10 cm is an analog sensor, so you will need to use an analog input pin on your Arduino or similar microcontroller to read the sensor output. Here's a simple code example for Arduino that reads the distance value and prints it to the Serial Monitor:
  3.  
  4. To use the code, connect the sensor's output to the analog pin A0 on your Arduino board, and upload the code using the Arduino IDE. Open the Serial Monitor to see the distance readings.
  5.  
  6. Remember to connect the sensor's VCC to the 5V pin on the Arduino and the GND to the GND pin on the Arduino.
  7.  
  8. Please note that the threshold value of 2.8 V is just an example and may not be precise for all situations. You may need to adjust this value based on your specific sensor and application. It's also a good idea to consult the sensor's datasheet for more information on the output voltage-to-distance relationship.
  9. */
  10.  
  11. // Pololu Sharp Distance Sensor - 10 cm example for Arduino
  12.  
  13. const int sensorPin = A0; // Connect the sensor's output to analog pin A0 on the Arduino
  14.  
  15. void setup() {
  16.   pinMode(sensorPin, INPUT); // Set the sensorPin as input
  17.   Serial.begin(9600); // Start the Serial Monitor with a baud rate of 9600
  18. }
  19.  
  20. void loop() {
  21.   int sensorValue = analogRead(sensorPin); // Read the sensor's output
  22.   float voltage = sensorValue * (5.0 / 1023.0); // Convert the sensor value to voltage
  23.  
  24.   if (voltage > 2.8) { // If the voltage is greater than 2.8 V, the distance is less than 10 cm
  25.     Serial.println("Distance is less than 10 cm");
  26.   } else { // If the voltage is less than or equal to 2.8 V, the distance is greater than or equal to 10 cm
  27.     Serial.println("Distance is greater than or equal to 10 cm");
  28.   }
  29.  
  30.   delay(1000); // Wait for 1 second (1000 milliseconds) before reading the sensor again
  31. }
  32.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement