start with left sonar and left motor
[challenge-bot] / build-stages / c_both_sonars / c_both_sonars.ino
CommitLineData
481b24d3 1/*
2 This program is free software: you can redistribute it and/or modify
3 it under the terms of the GNU Affero General Public License as
4 published by the Free Software Foundation, either version 3 of the
5 License, or (at your option) any later version.
6
7 This program is distributed in the hope that it will be useful,
8 but WITHOUT ANY WARRANTY; without even the implied warranty of
9 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 GNU Affero General Public License for more details.
11
12 You should have received a copy of the GNU Affero General Public License
13 along with this program. If not, see <http://www.gnu.org/licenses/>.
14 */
15int right_echo_pin = 6;
16int right_trigger_pin = 7;
17
18int left_echo_pin = 11;
19int left_trigger_pin = 12;
20
481b24d3 21int count = 0;
22
23void on(int pin){
24 digitalWrite(pin, HIGH);}
25
26void off(int pin){
27 digitalWrite(pin, LOW);}
28
29int ping(int trigger, int echo){
30 int ping_time = 0;
31 // turn off trigger
32 off(trigger);
33 delayMicroseconds(2);
34 // turn on the trigger and leave it on long enough for the
35 // sonar sensor to notice
36 on(trigger);
37 delayMicroseconds(10);
38 off(trigger);
39 ping_time = pulseIn(echo, HIGH);
40 if(ping_time <= 0){
41 ping_time = 3000;}
42 // sonar needs some time to recover before pinging again,
43 // so make sure it gets enough sleep right here. 50 milliseconds
44 delay(50);
45 return ping_time;}
46
35ffc343 47double ping_to_cm(int ping_microseconds)
48{
49 double sound_cm_per_microsecond_at_sea_level = 0.034029;
50 return ping_microseconds * sound_cm_per_microsecond_at_sea_level / 2;
51}
52
481b24d3 53void setup(){
54 Serial.begin(9600);
55 pinMode(right_echo_pin, INPUT);
56 pinMode(right_trigger_pin, OUTPUT);
57 pinMode(left_echo_pin, INPUT);
58 pinMode(left_trigger_pin, OUTPUT);}
59
60void loop(){
35ffc343 61 int left_ping_microseconds;
62 int right_ping_microseconds;
63 double left_distance;
64 double right_distance;
481b24d3 65 left_ping_microseconds = ping(left_trigger_pin, left_echo_pin);
35ffc343 66 right_ping_microseconds = ping(right_trigger_pin, right_echo_pin);
67 left_distance = ping_to_cm(left_ping_microseconds);
68 right_distance = ping_to_cm(right_ping_microseconds);
481b24d3 69 // print out the pulse time
35ffc343 70 Serial.print(left_distance);
71 Serial.print(" = left distance (cm), ");
72 Serial.print(right_distance);
73 Serial.print(" = right distance (cm). line #");
481b24d3 74 Serial.println(count++);
75
76 // wait so it's easier to read the serial monitor.
77 // change delay to 0 for fullspeed.
78 // default is 333, which is about 1/3 of a second
79 delay(333);}