Permalink
Browse files

added chapter 8 IR sensor reader

  • Loading branch information...
tigoe committed Oct 23, 2016
1 parent 02254d9 commit 3c674c3b4332ff6f8a53214a06a1589a190042a0
Showing with 15 additions and 22 deletions.
  1. +15 −22 chapter8/project15/IRSensorReader/IRSensorReader.ino
@@ -1,31 +1,24 @@
/*
Sharp GP2xx IR ranger reader
Context: Arduino
Reads the value from a Sharp GP2Y0A21 IR ranger and sends
it out serially.
*/
Context: Arduino
Reads the value from a Sharp GP2Y0A21 IR ranger and sends
it out serially.
*/
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
Serial.begin(9600); // initialize serial communications
}
void loop() {
int sensorValue = analogRead(A0); // read the sensor value
// convert to a voltage:
float voltage = map(sensorValue, 0, 5, 0, 1023);
// the sensor actually gives results that aren't linear.
// This formula is derived from the datasheet's graph
// of voltage over 1/distance. The slope of that line
// is approximately 27:
float distance = 27.0 /voltage;
// print the sensor value
Serial.print(distance);
Serial.println(" cm");
// wait 10 milliseconds before the next reading
delay(10);
float voltage = sensorValue * (5.0 / 1024.0);
// calculate the distance:
float distance = 21.7 / voltage;
Serial.print(voltage);
Serial.print(" V\t");
Serial.print(distance);
Serial.println(" cm");
// wait 39 milliseconds before the next reading
delay(39);
}

0 comments on commit 3c674c3

Please sign in to comment.