September 2017
Intermediate to advanced
206 pages
4h 34m
English
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(" ...Read now
Unlock full access