Project 03 · HC-SR04 + SG90

Build a radar the class can see.

Distance from echo time, then a servo sweep, then polar dots on a black Processing canvas. This is the open-day project.

3 × 45 minPhysics of soundServo currentShowcase
HC-SR04 wired to Arduino
Exercise 1: VCC 5V, GND, TRIG D3, ECHO D2.
SG90 servo on pin 9
Signal (orange) → D9, red → 5V, brown → GND. Later: mount the sensor on the horn.
Sonar, servo and USB on Arduino Uno
Combined radar wiring from the source document.

Four climbs

  1. Distance as text + bar
  2. Processing START/STOP buttons sweep the servo
  3. Object closer than 50 cm rotates the servo to 90°
  4. Full radar: ANGLE,DISTANCE and a green sweep

Core sketches

distance.ino
#define trigPin 3
#define echoPin 2

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  long duration = pulseIn(echoPin, HIGH);
  float distance = duration * 0.0343 / 2;
  Serial.println(distance);
  delay(200);
}
radar_sweep.ino
#include <Servo.h>
Servo myServo;
#define trigPin 9
#define echoPin 10

void setup() {
  Serial.begin(9600);
  myServo.attach(6);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  for (int angle = 0; angle <= 180; angle += 2) {
    myServo.write(angle);
    delay(50);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    long duration = pulseIn(echoPin, HIGH);
    float distance = duration * 0.0343 / 2;
    Serial.print(angle);
    Serial.print(",");
    Serial.println(distance);
  }
}
radar_display.pde
import processing.serial.*;

Serial myPort;
int angle;
float distance;

void setup() {
  size(600, 600);
  myPort = new Serial(this, Serial.list()[0], 9600);
  background(0);
}

void draw() {
  // persistent dots: do not clear every frame
}

void serialEvent(Serial p) {
  String data = p.readStringUntil('\n');
  if (data != null && data.contains(",")) {
    String[] parts = split(trim(data), ",");
    if (parts.length == 2) {
      angle = int(parts[0]);
      distance = float(parts[1]);
      float r = map(distance, 0, 100, 0, 250);
      float x = width / 2 + r * cos(radians(angle));
      float y = height - r * sin(radians(angle));
      stroke(0, 255, 0);
      fill(0, 255, 0);
      ellipse(x, y, 5, 5);
    }
  }
}
Basic Distance as text.
Intermediate Grid rings on the radar.
Advanced Color by range (green / yellow / red).
Challenge Sweep line + sound alert. Project-worthy.
Next: Ohm meter