Last active
May 29, 2020 18:29
-
-
Save skhameneh/105a9c55130c8b798408def2c9925a3d to your computer and use it in GitHub Desktop.
ESP32 Websocket Servo Demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <WiFi.h> | |
#include <WiFiMulti.h> | |
#include <WebSocketsClient.h> // WebSockets by Markus Sattler | |
#include <Servo.h> // ServoESP32 by Jaroslav Paral | |
static const int servoPin = 17; | |
/* settings.h | |
char ssid[] = "wifi_name"; | |
char pass[] = "wifi_password"; | |
char nodeRedWsIp[] = "192.168.1.101"; | |
int nodeRedWsPort = 1880; | |
char nodeRedWsPath[] = "/ws/"; | |
*/ | |
#include "settings.h" | |
Servo servo1; | |
WiFiMulti WiFiMulti; | |
WebSocketsClient webSocket; | |
void webSocketEvent(WStype_t type, uint8_t *payload, size_t length) | |
{ | |
switch (type) | |
{ | |
case WStype_DISCONNECTED: | |
Serial.printf("[WSc] Disconnected!\n"); | |
break; | |
case WStype_CONNECTED: | |
Serial.printf("[WSc] Connected to url: %s\n", payload); | |
break; | |
case WStype_TEXT: | |
{ | |
Serial.printf("[WSc] get text: %s\n", payload); | |
String payloadString((char *)payload); | |
servo1.write(payloadString.toInt()); | |
break; | |
} | |
case WStype_BIN: | |
Serial.printf("[WSc] get binary length: %u\n", length); | |
break; | |
case WStype_PING: | |
Serial.printf("[WSc] get ping\n"); | |
break; | |
case WStype_PONG: | |
Serial.printf("[WSc] get pong\n"); | |
break; | |
} | |
} | |
void setup() | |
{ | |
Serial.begin(9600); | |
delay(10); | |
WiFiMulti.addAP(ssid, pass); | |
Serial.println(); | |
Serial.print("Waiting for WiFi... "); | |
while (WiFiMulti.run() != WL_CONNECTED) | |
{ | |
Serial.print("."); | |
delay(500); | |
} | |
Serial.println(""); | |
Serial.println("WiFi connected"); | |
Serial.println("IP address: "); | |
Serial.println(WiFi.localIP()); | |
delay(500); | |
webSocket.begin(nodeRedWsIp, nodeRedWsPort, nodeRedWsPath); | |
webSocket.onEvent(webSocketEvent); | |
webSocket.setReconnectInterval(5000); | |
webSocket.enableHeartbeat(15000, 3000, 2); | |
servo1.attach(servoPin); | |
} | |
void loop() | |
{ | |
webSocket.loop(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment