Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
malikmaky authored Jul 7, 2024
1 parent 31aae99 commit 5c9a847
Show file tree
Hide file tree
Showing 2 changed files with 304 additions and 0 deletions.
131 changes: 131 additions & 0 deletions iot-rgb-led-controller.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <WebSocketsServer.h>
#include <ESP8266mDNS.h>
#include "webPageCode.h"

// Set web server port number to 80
ESP8266WebServer server(80);
// Set WebSockets server on port 81 for real-time communication
WebSocketsServer webSocket = WebSocketsServer(81);

const char* ssid = "Firat IoT";
const char* password = "firatIoT";
const int redLED = 0; // D3
const int greenLED = 4; // D2
const int blueLED = 5; // D1

void setup() {
pinMode(redLED, OUTPUT);
pinMode(greenLED, OUTPUT);
pinMode(blueLED, OUTPUT);
analogWriteRange(255);
Serial.begin(115200);

// Connect to Wi-Fi network with SSID and password
Serial.println("\n\nConnecting to ");
Serial.print(ssid);
WiFi.begin(ssid, password);
Serial.println("");

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address
Serial.print("\n\nWiFi connected to ");
Serial.print(ssid);
Serial.println(".\nIP address: ");
Serial.println(WiFi.localIP());

// Initialize mDNS : Local DNS
if (!MDNS.begin("FiratIoT")) {
Serial.println("Error setting up mDNS");
return;
}
Serial.println("mDNS responder started");

// Start the WebSockets server to begin listening for incoming connections
webSocket.begin();
// Callback function to handle WebSocket events
webSocket.onEvent(webSocketEvent);

server.on("/", webPage);
// Start the web server to begin handle HTTP requests
server.begin();
}

void loop() {
MDNS.update();
// Handle incoming WebSocket messages and events
webSocket.loop();
// Handle incoming HTTP client requests
server.handleClient();
}

void webPage() {
server.send(200, "text/html", webP ageCode);
}

void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length) {
switch (type) {
// Client disconnects
case WStype_DISCONNECTED:
Serial.printf("[%u] Disconnected!\n", num);
break;
// Client connects
case WStype_CONNECTED:
{
// Client IP adress
IPAddress ip = webSocket.remoteIP(num);
Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
}
break;
// Client sends message
case WStype_TEXT:
Serial.printf("[%u] Received text: %s\n", num, payload);
// Character array to hold the formatted payload
char formattedPayload[50];

// Format the payload
sprintf(formattedPayload, "%s", (char*)payload);

// If the LED is turned on
// If the message starts with LED ON
if (std::strncmp(formattedPayload, "LED ON", std::strlen("LED ON")) == 0) {
char* commaPos = strchr(formattedPayload, ',');

if (commaPos != NULL) {
// Move to the next character after the comma to get the HEX RGB string
char* rgbStr = commaPos + 1;

// Convert the RGB hex string to integer values
unsigned int r, g, b;
sscanf(rgbStr, "#%2x%2x%2x", &r, &g, &b);

// Print the extracted RGB values (Optional)
Serial.printf("Received RGB: R=%u, G=%u, B=%u\n", r, g, b);

// Set the RGB LED colors
analogWrite(redLED, r);
analogWrite(greenLED, g);
analogWrite(blueLED, b);
}
// Sends a message to all the clients to update
webSocket.broadcastTXT(formattedPayload, length);
// If the LED is turned off
}
else if (strcmp(formattedPayload, "LED OFF") == 0) {
analogWrite(redLED, 0);
analogWrite(greenLED, 0);
analogWrite(blueLED, 0);
digitalWrite(BUILTIN_LED, HIGH);
// Sends a message to all the clients to update
webSocket.broadcastTXT(formattedPayload, length);
}

break;
default:
break;
}
}
173 changes: 173 additions & 0 deletions webPageCode.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
const char webPageCode[] =
R"=====(
<!DOCTYPE html>
<html>
<head>
<title>RGB LED Control</title>
<style>
body {
margin: 10px;
font-family: 'Trebuchet MS';
text-align: center;
background-color: #f4f4f4;
}

.container {
max-width: 600px;
margin: 50px auto;
padding: 20px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
display: flex;
flex-direction: column;
align-items: center;
}

.row-container {
width: 100%;
margin-bottom: 20px;
display: flex;
justify-content: space-evenly;
}

h1 {
font-family: 'Trebuchet MS';
color: #9c4464;
}

.led {
width: 40px;
height: 40px;
border-radius: 50%;
background-color: #F00;
box-shadow: rgba(0, 0, 0, 0.15) 0 0 10px,
inset rgba(0, 0, 0, 100) 0 0 5px,
#F00 0 2px 5px 1px;
}

.color-picker {
margin-top: 5px;
padding-top: 2px;
border: 1px solid #ccc;
border-radius: 2px;
}

button{
margin-right: 15px;
padding: 5px 10px;
min-width: 130px;
height: 40px;
font-family: 'Trebuchet MS';
cursor: pointer;
transition: all 0.3s ease;
position: relative;
display: inline-block;
outline: none;
border-radius: 5px;
border: 2px solid #9c4464;
background: #9c4464;
color: #fff;
}

button:hover {
background: #fff;
color: #9c4464
}
</style>
</head>

<body>
<div class="container">
<!-- Header -->
<h1>RGB LED Control</h1>
<br>
<div class="row-container">
<!-- LED -->
<div class="led"></div>
<!-- Color Picker-->
<input type="color" id="colorPicker" class="color-picker" value="#ff0000">
</div>
<br>

<!-- Buttons -->
<div class="row-container">
<button onclick="turnOn()" >Turn On</button>
<button onclick="turnOff()" >Turn Off</button>
</div>
</div>

<script>
const colorPicker = document.getElementById('colorPicker');
const led = document.querySelector('.led');

// Change LED color when color picker changes values
colorPicker.addEventListener('input', function() {
const color = colorPicker.value;
updateLedColor(color);
});

function updateLedColor(color) {

// Calculate HEX -> RGB
const r = Math.floor(parseInt(color.substring(1, 3), 16));
const g = Math.floor(parseInt(color.substring(3, 5), 16));
const b = Math.floor(parseInt(color.substring(5, 7), 16));

// Update LED background color
led.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;

// Update LED box shadow
led.style.boxShadow = `0 0 10px rgba(0, 0, 0, 0.15), inset 0 0 5px rgba(0, 0, 0, 100), 0 2px 5px 1px rgba(${r}, ${g}, ${b})`;

colorPicker.value = color;
}

function turnOn() {
updateLedColor(colorPicker.value);
// Sends information regarding turning the led on and its color
connection.send("LED ON,"+colorPicker.value);
console.log("Led is turned on.");
}

function turnOff() {
led.style.backgroundColor = '#fff';
led.style.boxShadow = `0 0 10px rgba(0, 0, 0, 0.15), inset 0 0 5px #fff, 0 2px 5px 1px #fff`;
// Sends information regarding turning the led off
connection.send("LED OFF");
console.log("Led is turned off.");
}

// Connection between client and the NodeMCU
var connection = new WebSocket('ws://'+location.hostname+':81/', ['arduino']);

// When first connected
connection.onopen = function (){ connection.send('Connect ' + new Date()); };

// When a message is received
connection.onmessage = function (e){
console.log('Server: ', e.data);

if (e.data.startsWith("LED ON")) { // If LED is turned on

const parts = e.data.split(',');

// Color in HEX form
const color = parts[1];

// Update the color
updateLedColor(color);
console.log("Led is turned on with color:", color);

}else if (e.data === "LED OFF") { // If LED is turned off
led.style.backgroundColor = '#fff';
led.style.boxShadow = `0 0 10px rgba(0, 0, 0, 0.15), inset 0 0 5px #fff, 0 2px 5px 1px #fff`;
}
};

// When a WebSocket error comes up
connection.onerror = function (error) { console.log('WebSocket Error ', error);};
</script>
</body>
</html>
)=====";

0 comments on commit 5c9a847

Please sign in to comment.