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.



Four climbs
- Distance as text + bar
- Processing START/STOP buttons sweep the servo
- Object closer than 50 cm rotates the servo to 90°
- Full radar:
ANGLE,DISTANCEand a green sweep
Core sketches
#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);
}#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);
}
}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.
