Advertisement
microrobotics

Sharp GP2Y0A21YK0F

Apr 24th, 2023
2,399
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. The Sharp GP2Y0A21YK0F is an analog distance sensor with a range of 10-80 cm. It uses an infrared LED and a photodiode to measure the amount of reflected light, which can be used to estimate the distance to an object. You can connect it to an Arduino's analog input pin to read the sensor value.
  3.  
  4. To use this code:
  5.  
  6. Connect the Sharp GP2Y0A21YK0F distance sensor to your Arduino. Connect the sensor's GND pin to the Arduino's GND, the sensor's Vcc pin to the Arduino's 5V, and the sensor's Vo pin to the Arduino's A0 pin.
  7. Copy and paste the code above into a new Arduino sketch.
  8. Upload the code to your Arduino board.
  9. Open the Serial Monitor to view the estimated distance to the nearest object.
  10. Please note that the conversion equation provided in the readDistanceInCm function is specific to the Sharp GP2Y0A21YK0F sensor. If you use a different Sharp distance sensor, you might need to adjust the coefficients in the equation to match the sensor's datasheet. Additionally, the equation provides an estimation, and the actual measured distance may vary due to environmental factors or the characteristics of the reflecting surface.
  11. Here's an example code to read distance values from the Pololu Sharp GP2Y0A21YK0F Analog Distance Sensor:
  12. */
  13.  
  14. // Define the pin connected to the Sharp GP2Y0A21YK0F sensor
  15. const int sharpSensorPin = A0;
  16.  
  17. // Function to convert the raw sensor value to centimeters
  18. float readDistanceInCm(int sensorPin) {
  19.   int rawValue = analogRead(sensorPin);
  20.   float voltage = (float)rawValue * (5.0 / 1023.0); // Convert the raw value to voltage
  21.   float distance = 27.728 * pow(voltage, -1.2045); // Convert the voltage to distance in cm using the inverse equation found in the datasheet
  22.   return distance;
  23. }
  24.  
  25. void setup() {
  26.   Serial.begin(9600);
  27.   pinMode(sharpSensorPin, INPUT);
  28. }
  29.  
  30. void loop() {
  31.   float distance = readDistanceInCm(sharpSensorPin);
  32.  
  33.   // Print the distance to the serial monitor
  34.   Serial.print("Distance: ");
  35.   Serial.print(distance);
  36.   Serial.println(" cm");
  37.  
  38.   delay(500); // Add a small delay to avoid flooding the serial monitor
  39. }
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement