CYTHEIA AIOpen the editor

Radar Sweep

A servo sweeps an ultrasonic sensor while an OLED reports what it sees, sensing, motion and display working together.

Open this circuit and run it

Opens in your browser with the parts, wiring and code already in place. Press Run to watch it work, then change anything you like.

How it works

Three parts work together. A servo carries an HC-SR04 ultrasonic sensor, so turning the servo points the sensor in different directions. The sensor measures the distance straight ahead by timing an echo, as in the Ultrasonic Distance Meter. An OLED shows the current angle and distance. The servo is on pin 9, the sensor’s TRIG and ECHO are on pins 7 and 6, and the OLED is on the I2C pins A4 and A5.

Each pass of loop() points the servo at angle, waits 40 milliseconds for it to arrive, then measures the distance with readDistanceCm(), a function of its own that fires the pulse and converts the echo time to centimetres. The result goes to the Serial tab as “angle deg -> distance cm” and to the OLED, redrawn from scratch each time. Then the angle moves by direction, 5 degrees; when it reaches 180 or 0 the sign of direction flips, so the servo sweeps back and forth. In the editor, drag the sensor’s distance control while it runs to place an object in front of the radar.

Parts

Wiring

Arduino code

// Radar Sweep
// A servo turns the ultrasonic sensor; each reading is printed to the
// serial monitor and shown on the OLED. Drag the sensor's distance slider
// while it runs to "place an object" in front of the radar.
#include <Servo.h>
#include <Wire.h>
#include <Adafruit_SSD1306.h>

#define TRIG 7
#define ECHO 6

Servo scanner;
Adafruit_SSD1306 display(128, 64, &Wire, -1);

int angle = 0;
int direction = 5;

// Fire a 10 microsecond pulse, then time how long the echo takes to return
long readDistanceCm() {
  digitalWrite(TRIG, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG, LOW);
  long duration = pulseIn(ECHO, HIGH);
  return round(duration * 0.034 / 2);
}

void setup() {
  Serial.begin(9600);
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);
  scanner.attach(9);
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
}

void loop() {
  scanner.write(angle);
  delay(40);
  long cm = readDistanceCm();

  Serial.print(angle);
  Serial.print(" deg -> ");
  Serial.print(cm);
  Serial.println(" cm");

  display.clearDisplay();
  display.setTextSize(1);
  display.setCursor(0, 0);
  display.print("Angle: ");
  display.println(angle);
  display.print("Dist:  ");
  display.print(cm);
  display.println(" cm");
  display.display();

  angle = angle + direction;
  if (angle >= 180 || angle <= 0) {
    direction = -direction;
  }
}

Try changing it

Open this circuit and run it

Next challenge

More projects in Sensors