Here’s the WebSockets version for smooth, real-time motor control via Wi-Fi. ๐Ÿš€


๐Ÿ”น 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.


๐Ÿ“กBroadcast the signal โ€” amplify the connection.

Leave a Reply