๐น Why Use WebSockets?
- Faster than HTTP requests (no need to reload the page).
- No freezes (Arduino doesnโt get overloaded).
- Instant response when clicking buttons.
๐ 1๏ธโฃ Arduino R4 WiFi Code
This sets up a WebSocket server on port 81 to control:
โ
SG90 servo motor
โ
28BYJ-48 stepper motor
#include <WiFiS3.h>
#include <WebSocketsServer.h>
#include <Servo.h>
#include <Stepper.h>
// Wi-Fi Settings
const char* ssid = "YOUR_WIFI_NAME";
const char* password = "YOUR_WIFI_PASS";
// Create WebSocket server
WiFiServer server(80);
WebSocketsServer webSocket = WebSocketsServer(81);
// Motors
Servo myServo;
const int stepsPerRevolution = 2048;
Stepper myStepper(stepsPerRevolution, 8, 10, 9, 11);
// WebSocket event handler
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
String message = (char*)payload;
Serial.println("Command: " + message);
if (message == "servo_up") myServo.write(180);
if (message == "servo_down") myServo.write(0);
if (message == "stepper_left") myStepper.step(-50);
if (message == "stepper_right") myStepper.step(50);
}
void setup() {
Serial.begin(115200);
myServo.attach(6);
myStepper.setSpeed(10);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to WiFi!");
Serial.println(WiFi.localIP());
// Start WebSocket server
server.begin();
webSocket.begin();
webSocket.onEvent(webSocketEvent);
}
void loop() {
webSocket.loop(); // Keep WebSocket connection active
}
๐น 2๏ธโฃ HTML + JavaScript for Web Control
This creates a simple web page with buttons to control the motors via WebSockets.
<!DOCTYPE html>
<html>
<head>
<script>
var ws = new WebSocket("ws://YOUR_IP_ADDRESS:81/");
function sendCommand(command) {
ws.send(command);
}
</script>
</head>
<body>
<h2>WiFi Motor Control</h2>
<button onclick="sendCommand('servo_up')">Servo Up</button>
<button onclick="sendCommand('servo_down')">Servo Down</button><br><br>
<button onclick="sendCommand('stepper_left')">Stepper Left</button>
<button onclick="sendCommand('stepper_right')">Stepper Right</button>
</body>
</html>
๐น Replace YOUR_IP_ADDRESS
with the IP address that Arduino prints in Serial Monitor after connecting to Wi-Fi.
๐น Why WebSockets?
โ
Instant motor control โ No delays.
โ
No freezes โ Arduino doesnโt get overloaded with HTTP requests.
โ
Smooth operation โ No need to reload the page.