First, we declare our sensor and servo. Then, we initialize our setup() function.
#include <Servo.h> Servo servo; #define Svo_Pin 9 #define GP2Y0A21 A0 void setup() { servo.attach(Svo_Pin); Serial.begin(9600); }
In the loop() function, we move our servo from degree 0 to 180. On each degree change, we read a distance value from the sensor. Then, we calculate the distance by calling the get_gp2d12() function, defined in this sketch. Lastly, we print the resulting measurement to the serial port.
void loop() { for (int i=0;i<180;i++) { servo.write(i); uint16_t value = analogRead(GP2Y0A21); uint16_t range = get_gp2d12(value); Serial.print("Distance. Value: "); Serial.print(value); Serial.print(". Range: "); Serial.print(range); Serial.println(" mm"); delay(200); } delay(2000); }
To calculate a distance, we can refer to the datasheet. We'll implement the get_gp2d12() function to obtain a distance value:
uint16_t get_gp2d12 (uint16_t value) { if (value < 10) value = 10; return ((67870.0 / (value - 3.0)) - 40.0); }