TI RSLK Library 0.2.2
Loading...
Searching...
No Matches
GP2Y0A21_Sensor.cpp
1#include "GP2Y0A21_Sensor.h"
2
3/* minimum threshold for object detection using 14-bit ADC resolution */
4#define MIN_THRESHOLD 1000
5
6GP2Y0A21_Sensor::GP2Y0A21_Sensor()
7{
8 ir_sensor_pin = 0;
9}
10
11bool GP2Y0A21_Sensor::begin(uint8_t pin_num, uint8_t mode)
12{
13 ir_sensor_pin = pin_num;
14 pinMode(ir_sensor_pin, mode);
15 return true;
16}
17
19{
20 return analogRead(ir_sensor_pin);
21}
22
24{
25 int16_t analogVal;
26
27 analogVal = analogRead(ir_sensor_pin);
28 if (analogVal < MIN_THRESHOLD)
29 return -1;
30 // Equation comes from https://github.com/Resaj/GP2D-GP2Y-function
31 // GP2Y0A21 (5V sensor supply & 3,3V ADC): distance = 31 * ((3000 / (adc_value + 1) - 0,8))
32 // adapted to 14-bit resolution:
33 // 31 * 3000 * 16 = 1488000
34 // 31 * 0.8 = 24.8
35 return ((long)1488000 / (analogVal + 16)) - 25;
36}
37
39{
40 int distanceMM = readMM();
41 if (distanceMM < 0)
42 return -1;
43 return (float)distanceMM / 25.4;
44}
int16_t readMM()
Read the distance from the Sharp distance sensor in millimeters.
bool begin(uint8_t pin_num, uint8_t mode=INPUT_PULLDOWN)
Initialize the distance sensor class.
float readIN()
Read the distance from the Sharp distance sensor in inches.
uint16_t read()
Read the value from distance sensor.