Struggling with Arduino code/Javascript

Hi ,
I've downloaded some code from YouTube that allows my Wemos D1R1 to be controlled via a webpage and the JS changes the CSS to reflect the status on the web-server graphically
However it only controls one GPI0.

I can fumble my way around basic Arduino code and a little HTML and CSS but I'm struggling with the interface between JS and Arduino.
There's a JSONobj that gets the status of the button displayed on the webpage and there's a JSONtxt variable that sends that toggles the status.

i'm wondering if i need a new 'JSONobj" & 'JSONtxt' for each button or can I loop or concatenate all input and output states into an input variable/array and an ouput /v/a.

I'm not asking to be wet nursed, but feel free if you want. I've learnt quite a bit struggling through this last week and want to learn, if you can steer me in the right direction i'd much appreciate that.

I may have butchered the code a little , the original can be found at

[/code]

#include <ESP8266WiFi.h>
#include <WebSocketsServer.h>
#include <ESP8266WebServer.h>
/* thanks to https://www.youtube.com/channel/UCsQBF-5bXjNU69Uga5j_-bQ
for comments on https://www.youtube.com/watch?v=vCL7drj6r8w

murshedul hasan
5 months PRIOR TO 14/3/2021
 @Anibal Vilela  Thanks mate for the code. I have compiled Ulas Dikme's code successfully and sharing it here.

c[0].style.background='#111111';

*/

const char* ssid="VM1923921";
const char* password="fg3yvYqwgztn";
int RELAY1 = D4;
int LED = D13;
int websokMillis=50;

ESP8266WebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(88);
String webSite, JSONtxt;
boolean RELAYonoff = true;
const char webSiteCont[] PROGMEM = 
R"aaa(

<!DOCTYPE HTML>
<html lang="en"> 
<head>
<meta charset="utf-8"/>
<META name='viewport' content='width=device-width, initial-scale=1'>
<script>

InitWebSocket()
function InitWebSocket()
{
  websock = new WebSocket('ws://'+window.location.hostname+':88/');
  websock.onmessage=function(evt)
  {
    JSONobj = JSON.parse(evt.data);
    document.getElementById("myDIV").children[0].innerHTML = JSONobj.RELAYonoff;
    if(JSONobj.RELAYonoff == 'ON')
    {
      document.getElementById("myDIV").children[0].style.backgroundColor="#FFA200";
      document.getElementById("myDIV").children[0].style["boxShadow"] = "0px 0px 0px 8px #FFA200";
      document.getElementById("myDIV").children[1].style.backgroundColor="#FFA200";
      document.getElementById("myDIV").children[1].style["boxShadow"] = "0px 0px 0px 8px #FFA200";
    }
    else
    {
      document.getElementById("myDIV").children[0].style.backgroundColor="black";
      document.getElementById("myDIV").children[0].style["boxShadow"] = "0px 0px 0px 8px black";
      document.getElementById("myDIV").children[1].style.backgroundColor="purple";
      document.getElementById("myDIV").children[1].style["boxShadow"] = "0px 0px 0px 8px red";
    }
    
  } // end of onmessage
} // end of InitWebSocket
//-----------------
function button1(){
  btn1 = 'RELAYonoff=ON';
  if(document.getElementById("myDIV").children[0].innerHTML === 'ON')
  {
    btn1 = 'RELAYonoff=OFF';
  }
    websock.send(btn1);
}
//-------------------
function button2(){
  btn2 = 'RELAYonoff=ON';
   if(document.getElementById("myDIV").children[1].innerHTML === 'ON')
  {
    btn2 = 'RELAYonoff=OFF';
  }
    websock.send(btn2);
}

//-------------------
</script>

<style>
#btn{
  display: inline-block;
  text-decoration:none;
  background: #8cd460;
  color: rgba(255,255,255,0.80);
  font-weight:bold;
  font: 30px arial, sans-serif;
  width: 60px;
  height: 60px;
  line-height: 60px;
  border-radius: 50%;
  margin:30%;
  margin-top:10px;
  margin-bottom:10px;
  text-align: center;
  vertical-align: middle;
  overflow: hidden;
  box-shadow: 0px 0px 0px 2px #8cd460;
  border: solid 2px rgba(255,255,255, 0.47);
  transition: 0.4s;
}
</style>
</head>
<body>


<div id="myDIV">
<a href="#" id="btn" ONCLICK='button1()'> </a>
<a href="#" id="btn" ONCLICK='button2()'> </a>
<a href="#" id="btn" ONCLICK='button3()'> </a>
<a href="#" id="btn" ONCLICK='button4()'> </a>
<a href="#" id="btn" ONCLICK='button5()'> </a>
</div>
</body>
</html>
)aaa";
void WebSite(){
server.send(200, "text/html", webSiteCont);
}
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length)
{
  String payloadString = (const char *)payload;
  Serial.print("payloadString= ");
  Serial.println(payloadString);

  if(type == WStype_TEXT) // receive text from client
  {

    byte separator=payloadString.indexOf('=');

    
    Serial.print("separator= ");
    Serial.println(separator);
    String var = payloadString.substring(0,separator);
    Serial.print("var= ");
    Serial.println(var);
    String val = payloadString.substring(separator+1);
    Serial.print("val =");
    Serial.println(val);
    Serial.println(" ");

    if(var = "RELAYonoff")
    {
      RELAYonoff = false;
      if(val=="ON")RELAYonoff = true;
        Serial.print("l152:   in webSocketEvent");
        Serial.println(RELAYonoff);
      
    }
  }
}

void setup() {
Serial.begin(115200);
pinMode(RELAY1,OUTPUT);
pinMode(LED,OUTPUT);
WiFi.begin(ssid,password);

while(WiFi.status() !=WL_CONNECTED)
{
Serial.print("-");
    delay(500);
  }
  //WiFi.mode(WIFI_STA);
  Serial.println(" Start ESP ");
  Serial.println(WiFi.localIP());
  server.on("/",WebSite);
  server.begin();
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);

}


void loop() {
  webSocket.loop();
  server.handleClient();
  if(RELAYonoff ==  true)
  {
    digitalWrite(RELAY1,LOW);
    digitalWrite(LED,LOW);
     }
  else
  {
    digitalWrite(RELAY1,HIGH);
    digitalWrite(LED,HIGH);
  }
  String RELAYswitch = "OFF";
  if(RELAYonoff == true) RELAYswitch = "ON";
  JSONtxt = "{\"RELAYonoff\":\""+RELAYswitch+"\"}";
  webSocket.broadcastTXT(JSONtxt);
  
 
}

I suggest you visit: https://www.w3schools.com/ and spend some time learning HTML, it is a great website for that. That will give you an understanding of what your code does. It is extremely difficult to take somebody else's code and modify it if you do not understand it.

craiginboro:
i'm wondering if i need a new 'JSONobj" & 'JSONtxt' for each button

New 'JSONobj': yes.
New 'JSONtxt': no.

I played with your code for a little while because it looked interesting. You did not answer or provide feedback to the help in your first post so I will keep this very brief. I am happy to share more details if you want.

Here are the issues I found and have some idea of how to fix them.

  • currently you create a constant data stream of about 450kbits/s even if nothing happens

  • there are syntax errors in your code e.g.
    -- if() with one equal sign
    -- use of a unsigned data type (byte) for the indexOf function that can return negative values

  • there is some error handling missing

  • the code is not well formatted and has bad variable naming consistency

  • there are unused variables

  • the JavaScript code could be more generic for instance to have one function to handle all buttons

  • the JSON data could be restructured to allow better/simpler JavaScript code

  • there are code fragments that seem short and smart but I am not sure they are e.g.

String RELAYswitch = "OFF";
if(RELAYonoff == true) RELAYswitch = "ON";

Wouldn't this code fill a String unnecessarily in 50% of the cases just to save an else?

craiginboro:
However it only controls one GPI0.

Could you please describe what you would like from the application? e.g.

  • number of GPIO's
  • do you want only outputs (relays or LEDs) or would you like inputs (switches, analog) as well?
  • are all the outputs identical e.g. one output per button?
  • if it helps you can draw a picture of what the web page should look like (you can attach images to your post)
  • ...

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.