Created
March 21, 2013 16:06
-
-
Save ericjforman/5214240 to your computer and use it in GitHub Desktop.
Graph smoothed and converted sensor value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* reads a sensor on pin A0 and sends raw and smoothed values via serial, comma-separated. | |
Sends COMMA-SEPARATED values in the range 0 to 1023, followed by a newline, or newline and carriage return. | |
Use with "graphMultiple" processing code | |
Created April 2011 by Eric Forman | |
Updated March 21 2013 by Eric Forman | |
*/ | |
const int PinA = A0; | |
int A, B, C; // values to send over serial port | |
// # of past samples to average by, higher = smoother but less responsive | |
int smoothSamples = 10; // normal = 10 | |
int smoothedVal = 0; | |
void setup() { | |
Serial.begin(9600); | |
} | |
void loop() { | |
// in this example we read only one sensor and send: | |
// the actual value, the smoothed value, and the value converted to millimeters | |
A = analogRead(PinA); | |
B = smooth(A); | |
C = getSharp2Y0A21(A); | |
Serial.print(A); | |
Serial.print(","); | |
Serial.print(B); | |
Serial.print(","); | |
Serial.print(C); | |
Serial.println(); | |
} | |
int smooth(int newVal) { | |
smoothedVal = smoothedVal + ((newVal - smoothedVal) / smoothSamples); | |
return smoothedVal; | |
} | |
unsigned int getSharp2Y0A21(int rawVal) { | |
// read Sharp 2Y0A21 sensor on analog pin "pin" | |
// Sharp IR Sensor: GP2Y0A02YK, marked 2Y0A21 on the unit | |
// convert voltage to distance in millimeters, still NON-LINEAR | |
int dist_mm = 0; | |
int voltage_mv = rawVal / 1023.0 * 5000; // 0 = 0v, 1023 = 5v | |
// simple but processor-intensive method: | |
dist_mm = 1085534.81 * (float)pow((float)voltage_mv, -1.2); | |
/* | |
// complex but processor-efficient method: | |
dist_mm = dist_mm / 4.; | |
for(int i=0; i<=25; i++) { | |
dist_mm = (4*dist_mm + voltage_mv/(dist_mm^4)) / 5.; | |
} | |
dist_mm = 1085534.81 * 1. / (voltage_mv*dist_mm); | |
*/ | |
// keep result within limits of this particular sensor | |
constrain(dist_mm, 40, 800); | |
return dist_mm; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment