Am trying to get my Arduino UNO WiFi rev 2 to work as a server and send the tempretur as a js package to a client.
When using the WebSockets Library 1.3.0 by Markus Sattler I always get the message that the client is not connected and the Loop repeat it.
am new to this so i tried this as well just to see what it can do but also did not work.
KayPebble/WebSocket_WiFiRev2
this is my Code
#include <WiFiNINA.h>
#include <WebSocketsServer.h>
#include <ArduinoJson.h>
// Constants
char ssid[] = "POC";
char password[] = "1213";
const int WEBSOCKET_PORT = 80;
const int sensorPin = A0; // Pin, an dem der Temperatursensor angeschlossen ist
// Globals
WebSocketsServer webSocket = WebSocketsServer(WEBSOCKET_PORT);
// Function declarations
void connectToWiFi();
void printWiFiStatus();
void startWebSocketServer();
void handleWebSocketEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length);
void sendTemperatureJSON(uint8_t num);
void setup() {
// Start Serial port
Serial.begin(9600);
// Connect to WiFi
connectToWiFi();
// Print WiFi status and IP address
printWiFiStatus();
// Start WebSocket server and assign callback
startWebSocketServer();
}
void loop() {
// Look for and handle WebSocket data
webSocket.loop();
// Read temperature and send to connected clients
sendTemperatureJSON(0); // Change to the actual client number if needed
delay(5000); // Adjust delay as needed
}
void connectToWiFi() {
Serial.println("\nConnecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
}
void printWiFiStatus() {
Serial.println("\nConnected to WiFi");
Serial.print("My IP address: ");
Serial.println(WiFi.localIP());
}
void startWebSocketServer() {
webSocket.begin();
webSocket.onEvent(handleWebSocketEvent);
}
void handleWebSocketEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length) {
// Figure out the type of WebSocket event
switch (type) {
case WStype_DISCONNECTED:
Serial.println("Client disconnected!");
break;
case WStype_CONNECTED:
Serial.println("Client connected!");
break;
case WStype_TEXT:
Serial.print("Text received: ");
Serial.println(reinterpret_cast<char*>(payload));
break;
default:
break;
}
}
void sendTemperatureJSON(uint8_t num) {
// Read temperature from sensor
int sensorValue = analogRead(sensorPin);
float temperature = (sensorValue / 1024.0) * 5000 / 10; // LM35 sensor calibration
// Create a JSON object
StaticJsonDocument<128> jsonDocument;
jsonDocument["temperature"] = temperature;
// Serialize the JSON object to a string
String jsonString;
serializeJson(jsonDocument, jsonString);
// Send the JSON string to the client
webSocket.sendTXT(num, jsonString);
}