-
Notifications
You must be signed in to change notification settings - Fork 27
/
sharp_gp2y0a51sk0f_demo.ino
77 lines (67 loc) · 2.07 KB
/
sharp_gp2y0a51sk0f_demo.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/////////////////////////////////////////////////////////////////////////////
// Sharp GP2Y0A51SK0F Distance Measuring Sensor Demo
//
// Board Connection:
// Arduino GP2Y0A51SK0F
// 5V Pin 1 - Vcc
// GND Pin 2 - GND
// A0 Pin 3 - Vo
//
// Serial monitor setting:
// 9600 baud
/////////////////////////////////////////////////////////////////////////////
// Arduino pin numbers.
const int sharpVoPin = A0; // Arduino analog pin 0 connect to sensor Vo.
// Helper functions to print a data value to the serial monitor.
void printValue(String text, unsigned int value, bool isLast = false) {
Serial.print(text);
Serial.print("=");
Serial.print(value);
if (!isLast) {
Serial.print(", ");
}
}
void printFValue(String text, float value, String units, bool isLast = false) {
Serial.print(text);
Serial.print("=");
Serial.print(value, 3);
Serial.print(units);
if (!isLast) {
Serial.print(", ");
}
}
/////////////////////////////////////////////////////////////////////////////
// Arduino setup function.
void setup() {
// Start the hardware serial port for the serial monitor.
Serial.begin(9600);
Serial.println("");
Serial.println("GP2Y0A51SK0F Demo");
Serial.println("=================");
// Wait at least 25.2ms for the first measurement to complete.
delay(26);
}
// Arduino main loop.
void loop() {
// Wait 100ms between readings.
delay(100);
// Read the output voltage.
int VoRaw = analogRead(sharpVoPin);
printValue("VoRaw", VoRaw);
// Compute the output voltage in Volts.
float Vo = (5.0 * VoRaw) / 1024.0;
printFValue("Vo", Vo, "V");
// Convert to Distance in units of mm
// by approximating datasheet graph
// using equation of form: y = a/x + b
// and two (x,y) points on the graph:
// (30mm, 1.68V) and (150mm, 0.39V)
const float a = 48.375;
const float b = 0.0675;
float dist = 0;
if ( Vo > b ) {
dist = a / (Vo - b);
}
printFValue("Distance", dist, "mm", true);
Serial.println("");
} // END PROGRAM