File tree Expand file tree Collapse file tree 1 file changed +82
-0
lines changed Expand file tree Collapse file tree 1 file changed +82
-0
lines changed Original file line number Diff line number Diff line change 1+ #include < Servo.h>
2+ #define PWM_TRIG 5
3+ #define PWM_ECHO 6
4+ #define PWM_SERVO_RIGHT 9
5+ #define PWM_SERVO_LEFT 10
6+
7+ Servo motor_right;
8+ Servo motor_left;
9+
10+ void setup () {
11+
12+ motor_right.attach (PWM_SERVO_RIGHT);
13+ motor_left.attach (PWM_SERVO_LEFT);
14+ motor_right.write (90 );
15+ motor_left.write (90 );
16+
17+ pinMode (PWM_TRIG, OUTPUT);
18+ pinMode (PWM_ECHO, INPUT);
19+
20+ delay (2000 );
21+ }
22+
23+ int get_closest_distance (){
24+
25+ long duration;
26+ int distance;
27+
28+ // reset trigger
29+ digitalWrite (PWM_TRIG, LOW);
30+ delayMicroseconds (10 );
31+
32+ // trigger for 10μs,
33+ // signaling to the sensor to do a 10μs sonic bursts
34+ digitalWrite (PWM_TRIG, HIGH);
35+ delayMicroseconds (10 ); // the sensor generates sonic bursts during this time
36+ digitalWrite (PWM_TRIG, LOW);
37+
38+ // Compute duration
39+ // Read the time when the echo comes back
40+ duration = pulseIn (PWM_ECHO, HIGH); // in μs
41+ distance = duration * 0.034 / 2 ; // in cm
42+
43+ return distance;
44+ }
45+
46+ void go_forward () {
47+ motor_right.write (70 );
48+ motor_left.write (117 );
49+ }
50+
51+
52+ void go_backwards () {
53+ motor_right.write (117 );
54+ motor_left.write (63 );
55+ }
56+
57+ void turn () {
58+ motor_right.write (170 );
59+ motor_left.write (170 );
60+ delay (200 );
61+ }
62+
63+ void go_stop () {
64+ motor_right.write (90 );
65+ motor_left.write (90 );
66+ }
67+
68+ void loop () {
69+
70+ if (get_closest_distance () < 5 ) {
71+ go_stop ();
72+ delay (100 );
73+ go_backwards ();
74+ delay (200 );
75+ turn ();
76+ } else {
77+ go_forward ();
78+ }
79+
80+ delay (50 );
81+
82+ }
You can’t perform that action at this time.
0 commit comments