Skip to content

Commit ad2ca5d

Browse files
authored
Create arduino-radar-output.ino
Arduino code that controls servo and read HC-SR04 ultrasonic module and outputs angular displacement and distance to serial port
1 parent 8a4bd2f commit ad2ca5d

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

arduino-radar-output.ino

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// Arduino servo + HC-SR04 code that outputs angle and distance to serial port for Python to read
2+
3+
#include <Servo.h>
4+
5+
Servo servo_1; // servo controller (multiple can exist)
6+
7+
int trig = 4; // trig pin for HC-SR04
8+
int echo = 5; // echo pin for HC-SR04
9+
int servo_pin = 3; // PWM pin for servo control
10+
11+
int pos = 0; // servo starting position
12+
float duration,distance;
13+
14+
void setup() {
15+
Serial.begin(115200);
16+
Serial.println("Radar Start");
17+
servo_1.attach(servo_pin); // start servo control
18+
pinMode(trig,OUTPUT);
19+
pinMode(echo,INPUT);
20+
}
21+
22+
void loop() {
23+
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
24+
// in steps of 1 degree
25+
servo_1.write(pos); // tell servo to go to position in variable 'pos'
26+
delay(60); // delay to allow the servo to reach the desired position
27+
dist_calc(pos);
28+
}
29+
30+
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
31+
servo_1.write(pos); // tell servo to go to position in variable 'pos'
32+
delay(60);
33+
dist_calc(pos);
34+
}
35+
}
36+
37+
float dist_calc(int pos){
38+
// trigger 40kHz pulse for ranging
39+
digitalWrite(trig,LOW);
40+
delayMicroseconds(2);
41+
digitalWrite(trig,HIGH);
42+
delayMicroseconds(10);
43+
digitalWrite(trig,LOW);
44+
// convert from duration for pulse to reach detector (microseconds) to range (in cm)
45+
duration = pulseIn(echo,HIGH); // duration for pulse to reach detector (in microseconds)
46+
distance = 100.0*(343.0*(duration/2.0))/1000000.0; // 100.0*(speed of sound*duration/2)/microsec conversion
47+
48+
Serial.print(pos); // position of servo motor
49+
Serial.print(","); // comma separate variables
50+
Serial.println(distance); // print distance in cm
51+
}

0 commit comments

Comments
 (0)