This circuit is designed to measure distances using an ultrasonic sensor and control a servo motor to simulate radar movement. The NodeMCU ESP8266 microcontroller is used for communication and control, connecting to Wi-Fi to potentially transmit data. The circuit is powered by a LiPo battery, which is managed by a TP4056 charging module.
TP4056
Ultrasonic Sensor
Lipo Battery
ESP8266 NodeMCU
Tower Pro SG90 Servo
/*
* NodeMCU ESP8266 for communication and control.
* Connects to Wi-Fi, uses an ultrasonic sensor (HC-SR04) to measure distances,
* and a servo motor to sweep and simulate radar movement.
* The servo motor sweeps from 0° to 180° in 10° increments and pauses briefly
* to capture distance data.
*/
#include <ESP8266WiFi.h>
#include <Servo.h>
#define TRIG_PIN D1
#define ECHO_PIN D2
#define SERVO_PIN D5
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
Servo myservo;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
// Wi-Fi connection timeout
unsigned long startAttemptTime = millis();
while (WiFi.status() != WL_CONNECTED && millis() - startAttemptTime < 30000) { // 30 seconds timeout
delay(1000);
Serial.println("Connecting to WiFi...");
}
if (WiFi.status() != WL_CONNECTED) {
Serial.println("Failed to connect to WiFi");
// Handle the error, e.g., retry or enter a low-power mode
} else {
Serial.println("Connected to WiFi");
}
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
myservo.attach(SERVO_PIN);
}
long measureDistance() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH);
long distance = duration * 0.034 / 2;
return distance;
}
void loop() {
for (int pos = 0; pos <= 180; pos += 10) {
myservo.write(pos);
delay(500);
long distance = measureDistance();
Serial.print("Angle: ");
Serial.print(pos);
Serial.print(" Distance: ");
Serial.print(distance);
Serial.println(" cm");
}
for (int pos = 180; pos >= 0; pos -= 10) {
myservo.write(pos);
delay(500);
long distance = measureDistance();
Serial.print("Angle: ");
Serial.print(pos);
Serial.print(" Distance: ");
Serial.print(distance);
Serial.println(" cm");
}
}
This code initializes the NodeMCU ESP8266, connects it to Wi-Fi, and sets up the ultrasonic sensor and servo motor. The measureDistance
function triggers the ultrasonic sensor and calculates the distance based on the echo time. The loop
function sweeps the servo motor from 0° to 180° and back, measuring and printing the distance at each step.