Radar sweep: ultrasonic on 10 and 11, servo on 12, on an Arduino Uno
An HC-SR04 (TRIG 10, ECHO 11) rides a servo on pin 12 that sweeps from 15 to 165 degrees and back, sending each angle and distance to the serial port as "angle,distance." The whole build, an Arduino Uno and 2 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Intermediate Runs in your browser. Free, and no account needed.
The parts retail for about $36. On Mokxi they're free.
The code
The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.
// A radar: a servo sweeps an ultrasonic sensor and reports what it sees.
//
// HC-SR04 VCC -> 5V TRIG -> pin 10 ECHO -> pin 11 GND -> GND
// servo signal -> pin 12 red -> 5V brown -> GND
//
// At each degree of the sweep the sketch measures the distance and prints
// "angle,distance." on one line. A program on the computer reads those lines
// and draws the radar screen; here the serial monitor shows them.
//
// Drag the distance slider on the sensor while it sweeps.
#include <Servo.h>
const int TRIG = 10;
const int ECHO = 11;
const int SERVO_PIN = 12;
Servo turret;
long distanceCm() {
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
long echo = pulseIn(ECHO, HIGH, 30000UL);
return echo / 58;
}
void report(int angle) {
turret.write(angle);
delay(30);
Serial.print(angle);
Serial.print(",");
Serial.print(distanceCm());
Serial.print(".");
Serial.println();
}
void setup() {
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
turret.attach(SERVO_PIN);
turret.write(90);
Serial.begin(9600);
Serial.println("Mokxi Uno: radar sweep, sensor on 10 and 11, servo on 12");
}
void loop() {
for (int a = 15; a <= 165; a++) report(a);
for (int a = 165; a > 15; a--) report(a);
}
Parts list
4 parts, plus the jumper wires. They retail for about $36; on Mokxi they're free.
- 1 × Arduino Uno R3
- 1 × Half breadboard
- 1 × Ultrasonic ranger
- 1 × Hobby servo
How it is wired
5 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.
- Ground: Arduino Uno R3 pin GND; Ultrasonic ranger pin GND; Hobby servo pin GND
- Arduino Uno R3 pin 12; Hobby servo pin PWM
- Arduino Uno R3 pin 11; Ultrasonic ranger pin ECHO
- Arduino Uno R3 pin 10; Ultrasonic ranger pin TRIG
- Arduino Uno R3 pin 5V; Ultrasonic ranger pin VCC; Hobby servo pin VCC
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.