1
13int s;
14int state=0;
15void setup() {
16
17 Serial.begin(9600);
18 pinMode(8, INPUT);
19 pinMode(9, OUTPUT);
20 pinMode(12, OUTPUT);
21 digitalWrite(9, LOW);
22 digitalWrite(8, LOW);
23}
24
25void loop() {
26
27 long duration, inches, cm;
28
29
30
31 digitalWrite(9, HIGH);
32 delayMicroseconds(5);
33 digitalWrite(9, LOW);
34 delayMicroseconds(5);
35
36
37 duration = pulseIn(8, HIGH);
38
39
40 inches = microsecondsToInches(duration);
41 cm = microsecondsToCentimeters(duration);
42
43 Serial.print(inches);
44 Serial.print("in, ");
45 Serial.print(cm);
46 Serial.print("cm");
47 Serial.println();
48
49
50 if(inches<12){
51 digitalWrite(12, HIGH);
52 delay(10000);
53 }else{
54 digitalWrite(12, LOW);
55 }
56
57 delay(100);
58}
59
60long microsecondsToInches(long microseconds) {
61
62 return microseconds / 74 / 2;
63}
64
65long microsecondsToCentimeters(long microseconds) {
66
67 return microseconds / 29 / 2;
68}