GP2Y0A21YK Distance Sensor sample.
About GP2Y0A21YK
GP2Y0A21YK is a distance sensor and can be controlled by using the AnalogIn.
The range of this sensor is 10-80cm.
- Datasheet of GP2Y0A21YK
https://www.sparkfun.com/datasheets/Components/GP2Y0A21YK.pdf
About sample program
This program outputs distance between the object to the terminal.
Please use in the range of 10-80cm because of the sensor specifications.
Even if the distance is less than 10cm, this program outputs the distance to the terminal.
However, since the output value is not a correct value, note the malfunction.
About wiring
| Sensor | GR-PEACH |
| White wire | A0 |
| Orange wire | GND |
| Black wire | 3.0V |
Revision 1:da6118c4da1f, committed 2016-04-20
- Comitter:
- 1050186
- Date:
- Wed Apr 20 04:19:13 2016 +0000
- Parent:
- 0:f8c34fd5e223
- Commit message:
- Modify main.cpp
Changed in this revision
| main.cpp | Show annotated file Show diff for this revision Revisions of this file |
--- a/main.cpp Tue Apr 19 10:00:38 2016 +0000
+++ b/main.cpp Wed Apr 20 04:19:13 2016 +0000
@@ -2,27 +2,38 @@
AnalogIn ain(A0);
DigitalOut led1(LED_RED);
-DigitalOut led2(LED_GREEN);
-DigitalOut led3(LED_BLUE);
-DigitalOut led4(LED_USER);
+Ticker flipper;
+int f_sen = 0;
-int main() {
+void flip() {
float tmp1 = 0;
float tmp2 = 0;
float data;
+ float distance;
+
+ tmp1 = ain;
+ tmp2 = ain;
+ data = (tmp1 + tmp2) / 2.0f;
+
+ if ((0.121 <= data) && (data <= 0.970)) {
+ distance = 26.663 * pow((data * 3.3),-1.25);
+ printf("Distance : %4.3f[cm]\n",distance);
+ f_sen = 1;
+ } else {
+ printf("Distance : ------[cm]\n");
+ f_sen = 0;
+ }
+}
+
+int main() {
printf("Sensor start!\n");
+ flipper.attach_us(&flip, 500000);//500ms
while(1) {
- tmp1 = ain;
- tmp2 = ain;
- data = (tmp1 + tmp2) / 2.0f;
-
- data = ain.read();
- if ((0.121 <= data) && (data <= 0.970)) {
- float range = 26.663 * pow((data * 3.3),-1.25);
- printf("Distance : %4.2f[cm]\n",range) ;
+ if(f_sen == 1){
+ led1 = 1;
} else {
- printf("Distance : -----[cm]\n");
+ led1 = 0;
}
wait(0.5);
}