Code 1: WiFi Test (no circuit needed)
#include <WiFi.h>
#include <WebServer.h>
const char* ssid = "ESP32-Test";
WebServer server(80);
void handleRoot() {
server.send(200, "text/html",
"<h1>ESP32 Working</h1>"
"<p>If you see this, your phone is connected to an ESP32.</p>");
}
void setup() {
Serial.begin(115200);
delay(2000);
Serial.println("Starting AP...");
WiFi.softAP(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.softAPIP());
server.on("/", handleRoot);
server.begin();
Serial.println("Web server started");
}
void loop() {
server.handleClient();
}
Code 2: Print distance to browser using ultrasonic sensor.
Use the same ultrasonic sensor circuit you used in Part 2.
#include <WiFi.h>
#include <WebServer.h>
const char* ssid = "ESP32-Distance";
WebServer server(80);
// HC-SR04 connections
const int triggerPin = 6;
const int echoPin = 5;
long readUltrasonicDistance(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT);
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Wait up to 30 ms for an echo
return pulseIn(echoPin, HIGH);
}
void handleRoot()
{
long duration = readUltrasonicDistance(triggerPin, echoPin);
float distanceCM = duration * 0.0343 / 2.0;
String message = "Distance = ";
message += String(distanceCM, 1);
message += " cm";
Serial.println(distanceCM);
server.send(200, "text/plain", message);
}
void setup()
{
Serial.begin(115200);
delay(2000);
Serial.println("Starting Access Point...");
WiFi.softAP(ssid);
Serial.print("Connect to WiFi: ");
Serial.println(ssid);
Serial.print("Open browser at: http://");
Serial.println(WiFi.softAPIP());
server.on("/", handleRoot);
server.begin();
Serial.println("Server started");
}
void loop()
{
server.handleClient();
}
Bonus: Use buttons in browser to control LED
Use the circuit you put together for the LED in Part 1.
This sketch is based on this project: https://randomnerdtutorials.com/esp32-web-server-arduino-ide/
#include <WiFi.h>
#include <WebServer.h>
const int ledPin = 4;
WebServer server(80);
void handleRoot() {
String page =
"<html><body>"
"<h1>ESP32 LED Control</h1>"
"<a href='/on'><button>ON</button></a>"
"<br><br>"
"<a href='/off'><button>OFF</button></a>"
"</body></html>";
server.send(200, "text/html", page);
}
void setup() {
Serial.begin(115200);
delay(2000);
pinMode(ledPin, OUTPUT);
WiFi.softAP("ESP32-Test");
Serial.print("IP: ");
Serial.println(WiFi.softAPIP());
server.on("/", handleRoot);
server.on("/on", []() {
digitalWrite(ledPin, HIGH);
server.sendHeader("Location", "/");
server.send(303);
});
server.on("/off", []() {
digitalWrite(ledPin, LOW);
server.sendHeader("Location", "/");
server.send(303);
});
server.begin();
}
void loop() {
server.handleClient();
}