#include <UltrasonicSensor.h>
#include <WiFi.h>
#include <WebServer.h>
const char* ssid = "amit";
const char* password = "a1b2c3d4e5";
UltrasonicSensor ultrasonic(18, 17);
WebServer server(80);
String htmlContent = R"rawliteral(
<!DOCTYPE HTML>
<html>
<head>
<title>ESP32 Joystick Direction and Button</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html { font-family: Arial; display: inline-block; text-align: center; }
h2 { font-size: 2.0rem; }
p { font-size: 1.5rem; }
</style>
</head>
<body>
<h2>Distance</h2>
<p>Distance <span id="button">0</span></p>
<script>
setInterval(function() {
fetch('/status')
.then(response => response.json())
.then(data => {
document.getElementById('button').innerText = data.distance;
});
}, 1000);
</script>
</body>
</html>
)rawliteral"
void handleRoot() {
server.send(200, "text/html", htmlContent);
}
// Handle status URL
void handleStatus() {
int distance = ultrasonic.distanceInCentimeters();
String json = "{\"distance\":\"" + distance}";
server.send(200, "application/json", json);
}
void setup() {
// put your setup code here, to run once:
void setup() {
// Serial port for debugging
Serial.begin(115200);
// Initialize the joystick pins
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Print the IP address
Serial.println(WiFi.localIP());
// Route for root / web page
server.on("/", handleRoot);
// Route to get joystick status
server.on("/status", handleStatus);
// Start server
server.begin();
}
void loop() {
server.handleClient();
}
}