/elec/quadcopter

To get this branch, use:
bzr branch http://bzr.ed.am/elec/quadcopter

« back to all changes in this revision

Viewing changes to test/ultrasonic-prox/main.ino

  • Committer: dan
  • Date: 2014-02-05 19:30:09 UTC
  • Revision ID: dan-20140205193009-r1fy3n31e4tfilo8
Added Ultra Sonic Prox sensor test prog

Show diffs side-by-side

added added

removed removed

 
1
/* Ping))) Sensor
 
2
 
 
3
   This sketch reads a PING))) ultrasonic rangefinder and returns the
 
4
   distance to the closest object in range. To do this, it sends a pulse
 
5
   to the sensor to initiate a reading, then listens for a pulse
 
6
   to return.  The length of the returning pulse is proportional to
 
7
   the distance of the object from the sensor.
 
8
     
 
9
   based on the original code from the tutorial at:
 
10
   http://www.arduino.cc/en/Tutorial/Ping
 
11
   
 
12
   This example code is in the public domain.
 
13
 
 
14
 */
 
15
 
 
16
int pingPin = 13;
 
17
int inPin = 12;
 
18
 
 
19
long duration, inches, cm;
 
20
 
 
21
void setup() {
 
22
  //pinMode(13, OUTPUT);
 
23
  pinMode(pingPin, OUTPUT);
 
24
  pinMode(inPin, INPUT);
 
25
  Serial.begin(9600);
 
26
}
 
27
 
 
28
long microsecondsToInches(long microseconds)
 
29
{
 
30
  // According to Parallax's datasheet for the PING))), there are
 
31
  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
 
32
  // second).  This gives the distance travelled by the ping, outbound
 
33
  // and return, so we divide by 2 to get the distance of the obstacle.
 
34
  return microseconds / 74 / 2;
 
35
}
 
36
 
 
37
long microsecondsToCentimeters(long microseconds)
 
38
{
 
39
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
 
40
  // The ping travels out and back, so to find the distance of the
 
41
  // object we take half of the distance travelled.
 
42
  return microseconds / 29 / 2;
 
43
}
 
44
 
 
45
void loop()
 
46
{
 
47
  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
 
48
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
 
49
  //pinMode(pingPin, OUTPUT);
 
50
  digitalWrite(pingPin, LOW);
 
51
  delayMicroseconds(2);
 
52
  digitalWrite(pingPin, HIGH);
 
53
  delayMicroseconds(10);
 
54
  digitalWrite(pingPin, LOW);
 
55
  //delayMicroseconds(2);
 
56
 
 
57
  // a HIGH
 
58
  // pulse whose duration is the time (in microseconds) from the sending
 
59
  // of the ping to the reception of its echo off of an object.
 
60
 
 
61
  duration = pulseIn(inPin, HIGH);
 
62
 
 
63
  // convert the time into a distance
 
64
  inches = microsecondsToInches(duration);
 
65
  cm = microsecondsToCentimeters(duration);
 
66
 
 
67
  Serial.print("Distance: [");
 
68
  Serial.print(inches);
 
69
  Serial.print("]inches. [");
 
70
  Serial.print(cm);
 
71
  Serial.print("]cm\r\n");
 
72
  delay(50);
 
73
}
 
74