Announcement

Collapse
No announcement yet.

PHP error: Wrong pin?

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Homer
    replied
    Well, seems like the code will work.

    Looking at your modified code, if I get it right then you only need to read the relay state once, right after the WebSocket connected. And relay port is exactly the LED port.

    Just, I am just not sure I understand your application. At first, I thought the relay and LED ports are different, and the example code I suggested is for the case you need to read and update the relay state frequently. It may be a bit redundant for you case, but still, it may work .

    In ws_onopen(), you can see that:
    Code:
    ws.send("0"); // Send first char to server after connected
    So, right after the WebSocket is connected, the browser sends a hello message and sets LED port to OFF. Of course, you can change this value so that this hello message from browser won't change the LED state (if you need it in your scheme).

    Anw, let's try to run the code and see the result .

    Cheers

    Leave a comment:


  • Badener
    replied
    Hi Homer. Thank you for quick response and for detailed explanation. I'm using standart 5V 1-chanel Active-low Relay like on the picture. In my case digitalWrite(ledPin, LOW) = ON, and digitalWrite(ledPin, HIGH) = OFF. This is the code with some corrections that will, probably, work:

    Arduino side:


    Code:
    #include <Phpoc.h>
    
    PhpocServer server(80);
    int ledPin = 8;
    int relayState = digitalRead(ledPin);
    bool isConnected = false;
    bool lastStateIsOn = false;
    
    void setup() {
      Serial.begin(9600);
      while(!Serial)
        ;
    
      Phpoc.begin(PF_LOG_SPI | PF_LOG_NET);
    
      server.beginWebSocket("remote_led");
    
      Serial.print("WebSocket server address : ");
      Serial.println(Phpoc.localIP());
      pinMode(ledPin, OUTPUT);
    }
    
    void loop() {
    
      PhpocClient client = server.available();
    
      if (isConnected)
      {
          if (relayState == LOW)
          {
            server.write('3');
            lastStateIsOn = true;
            client.flush();
            delay(200);
          }
    
        else
        {
          if (relayState == HIGH)
          {
            server.write('2');
            lastStateIsOn = false;
            client.flush();
            delay(200);
          }
        }
      }
    
    
      if (client) {
        if (client.available() > 0) {
    
          if (!isConnected)
            isConnected = true;
    
          char thisChar = client.read();
    
          switch(thisChar)
          {
            case '0':
              Serial.println("Turn LED OFF");
              digitalWrite(ledPin, HIGH);
              server.write('0');
              break;
            case '1':
              Serial.println("Turn LED ON");
              digitalWrite(ledPin, LOW);
              server.write('1');
              break;
          }
        }
      }
    }

    And this is PHPoC:


    HTML Code:
    <html>
        <head>
            <title><?echo system("uname -i")?></title>
            <meta content="initial-scale=0.7, maximum-scale=1.0, minimum-scale=0.5, width=device-width, user-scalable=yes" name="viewport">
            <style>
                body {
                    text-align: center;
                }
    
                h2 {
                    font-weight: bold;
                    font-size: 15pt;
                    padding-bottom: 5px;
                }
    
                button {
                    font-weight: bold;
                    font-size: 15pt;
                }
    
            </style>
        </head>
        <body>
            <h2> Wallbox Schalter<br>
                <br>
                <img id="remote" src="button_pop.png">
                <br>
            </h2>
            <h2>WebSocket <span id="ws_state"><span style="color: gray">GESCHLOSSEN</span></span></h2>
            <button id="bt_connect" type="button" onclick="connect_onclick();">Verbinden</button>
            <br>
            <h3><span id="relay"><span style="color: green">EIN</span></span></h3>
    
    
    
        </body>
    
        <script>
    
        var isON;
        var ws;
        var remote;
    
        function init()
        {
            remote = document.getElementById("remote");
            remote.addEventListener("click", toogleLed);
            isON = 0;
        }
    
        function connect_onclick()
        {
            if(ws == null)
            {
                var ws_host_addr = "<?echo _SERVER("HTTP_HOST")?>";
                if((navigator.platform.indexOf("Win") != -1) && (ws_host_addr.charAt(0) == "["))
                {
                    // network resource identifier to UNC path name conversion
                    ws_host_addr = ws_host_addr.replace(/[\[\]]/g, '');
                    ws_host_addr = ws_host_addr.replace(/:/g, "-");
                    ws_host_addr += ".ipv6-literal.net";
                }
                ws = new WebSocket("ws://" + ws_host_addr + "/remote_led", "text.phpoc");
                document.getElementById("ws_state").innerHTML = "warten";
                ws.onopen = ws_onopen;
                ws.onclose = ws_onclose;
                ws.onmessage = ws_onmessage;
            }
            else
                ws.close();
        }
    
            function ws_onopen()
        {
            document.getElementById("ws_state").innerHTML = "<span style='color: blue'>VERBUNDEN</span>";
            document.getElementById("bt_connect").innerHTML = "Trennen";
            ws.send("0"); // Send first char to server after connected
            displayLEDStatus();
        }
    
    
    
    
    
    
        function ws_onclose()
        {
            document.getElementById("ws_state").innerHTML = "<span style='color: gray'>geschlossen</span>";
            document.getElementById("bt_connect").innerHTML = "Verbinden";
            ws.onopen = null;
            ws.onclose = null;
            ws.onmessage = null;
            ws = null;
            isON = 0;
            displayLEDStatus();
        }
    
        function ws_onmessage(e_msg)
        {
            e_msg = e_msg || window.event; // MessageEvent
            isON = parseInt(e_msg.data);
            //displayLEDStatus();
            if (isON < 2)
                 displayLEDStatus();
             else
                 displayRelayStatus();
    
    
            // Change the code that suits Arduino code above
            // e.g. as above, isON = 0 --> LED OFF / 1 --> LED ON / 2 --> RELAY OFF / 3 --> RELAY ON
            // then comment out displayLEDStatus(); above and replace with
    
            // if (isON < 2)
            //     displayLEDStatus();
            // else
            //     displayRelayStatus();
    
        }
    
          function displayRelayStatus() {
            // Your code to display relay state on Web browser
            // e.g. in HTML you put a new element <span id="relay"></span>
            // then here you call
          document.getElementById("relay").innerHTML = (isON ==3) ? "EIN" : "AUS";
        }  
    
    
        function toogleLed()
        {
            if (isON)
                ws.send("0");
            else
                ws.send("1");
        }
    
        function displayLEDStatus()
        {
            remote.src = (isON) ? "button_push.png" : "button_pop.png";
        }
    
        window.onload = init;
        </script>
    </html>

    Is it right?



    Leave a comment:


  • Homer
    replied
    Good to hear. my friend

    It is possible to show the current state of relay after connecting via WebSocket.

    I am not sure what kind of relay you are using, but if you are using PHPoC Smart Expansion Board PES-2601, then you can get the current state of delay by using isOn() function https://www.phpoc.com/support/manual...ion_relay_ison

    If you use any other relay, just try to get the relay state and then send it to WebSocket client.

    On Arduino (Server side):

    Code:
    #include <Phpoc.h>
    
    PhpocServer server(80);
    int ledPin = 8;
    
    
    bool isConnected = false;
    bool lastStateIsOn = false;
    
    void setup() {
      Serial.begin(9600);
      while(!Serial)
        ;
    
      // initialize PHPoC [WiFi] Shield:
      Phpoc.begin(PF_LOG_SPI | PF_LOG_NET);
      //Phpoc.begin();
    
      // start WebSocket server
      server.beginWebSocket("remote_led");
    
      // print IP address of PHPoC [WiFi] Shield to serial monitor:
      Serial.print("WebSocket server address : ");
      Serial.println(Phpoc.localIP());
      pinMode(ledPin, OUTPUT);
    }
    
    void loop() {
      // wait for a new client:
      PhpocClient client = server.available();
    
      if (isConnected)
      {
      // Probably you will put the code to send relay state around here
      // e.g.
        if (relay.isON())
        {
          if (lastStateIsOn == false)
          {
            server.write('3');
            lastStateIsOn = true;
            client.flush();
            delay(200);
          }
        }
        else
        {
          if (lastStateIsOn == true)
          {
            server.write('2');
            lastStateIsOn = false;
            client.flush();
            delay(200); // The code here looks a bit dump, but I am sure you can rearrange it :D.
          }
        }
      }
    
    
    
      if (client) {
        if (client.available() > 0) {
    
          // Set the connected state after receiving any data sent from client  
          if (!isConnected)
            isConnected = true;
    
          // read a byte incoming from the client:
          char thisChar = client.read();
    
          switch(thisChar)
          {
            case '0':
              Serial.println("Turn LED OFF");
              digitalWrite(ledPin, LOW);
              server.write('0');
              break;
            case '1':
              Serial.println("Turn LED ON");
              digitalWrite(ledPin, HIGH);
              server.write('1');
              break;
          }
        }
      }
    }


    On client side, try to update some functions:

    Code:
        function ws_onopen()
        {
            document.getElementById("ws_state").innerHTML = "<span style='color: blue'>CONNECTED</span>";
            document.getElementById("bt_connect").innerHTML = "Disconnect";
            ws.send("0"); // Send first char to server after connected
            displayLEDStatus();
        }
    
    
        function ws_onmessage(e_msg)
        {
            e_msg = e_msg || window.event; // MessageEvent
            isON = parseInt(e_msg.data);
            displayLEDStatus();
    
            // Change the code that suits Arduino code above
            // e.g. as above, isON = 0 --> LED OFF / 1 --> LED ON / 2 --> RELAY OFF / 3 --> RELAY ON
            // then comment out displayLEDStatus(); above and replace with
    
            // if (isON < 2)
            //     displayLEDStatus();
            // else
            //     displayRelayStatus();
        }
    
    
        function displayRelayStatus() {
            // Your code to display relay state on Web browser
            // e.g. in HTML you put a new element <span id="relay"></span>
            // then here you call document.getElementById("relay").innerHTML = (isON ==3) ? "ON" : "OFF";
        }
    I didn't test the code, but you can check my comment and probably figure out how to make it right .



    If you write flash files to PHPoC Shield, the shield will be rebooted and then the communication between Arduino and the shield may lose the synchronization.
    That's why it can't work properly if you don't reset Arduino board.

    I think after writing flash files to the shield, you may try to reset Arduino board by using its RESET pin, or just unplug/plug the power source for Arduino.
    That will be one workaround solution .


    Cheers.
    Last edited by Homer; 06-14-2019, 12:10 PM.

    Leave a comment:


  • Badener
    replied
    Hi Homer. Your code worked like a charm. Actually, the whole thing was, that i have a wallbox (charging station) for electric car and every time i wanted to charge the car, i had to do it with special key . The Wallbox has enough space inside, that's why i built the Arduino+PHPoC+relay in it. It's safe, because nobody knows my WiFi password and with static ip i can reach it everytime. So, thank you so much for your help.

    But after one month of use i had two questions:
    1. Is it possible, to show immediately current state of relay on php page (is it "On" or is "OFF"), after connecting via Websocket?

    2. After every time i upload files to PHPoC, i cannot connect via Websocket and i have this in Fw Log:
    Code:
    0612:15:52:40.430] php start wallbox.php RUN
    [0612:15:52:41.441] ws_find_socket: listening socket not found
    .
    After that i must physically reconnect Arduino and PHPoC and built it again in Wallbox. Is it possible to fix it somehow?

    Thank you in advance.

    Leave a comment:


  • Homer
    replied
    Hello there,

    The example above is for PHPoC board (PHPoC Black/Blue), and it is used to control a built-in LED in PHPoC board (pin 30).
    In your case, I/O pins are controlled by Arduino itself, not by PHPoC device like in the case of the example.
    So I am not surprised if it didn't work .

    The good news is you can still do the same thing on Arduino and PHPoC shield.
    Like I said, let Arduino do the I/O control stuff as it should, and PHPoC shield may help you to do the rest.
    The combination of Arduino and PHPoC shield is a Web/WebSocket server, so you can host a web script on PHPoC shield.
    The script should allow web client (yeah, a technical name for web browser ) to exchange data with the web server (Arduino with PHPoC shield), so that you can send control command to Arduino board and get the response status back to your web browser.

    Considering that you are new to PHPoC shield, I made a quick example so you can upload this script on PHPoC shield. Let's say you name it remote_led.php. Believe me, unless you want to fully customize the shield yourself, otherwise you should choose a different name with the existing built-in web apps in the shield (including index.php)

    Code:
    <html>
        <head>
            <title><?echo system("uname -i")?></title>
            <meta content="initial-scale=0.7, maximum-scale=1.0, minimum-scale=0.5, width=device-width, user-scalable=yes" name="viewport">
            <style>
                body {
                    text-align: center;
                }
    
                h2 {
                    font-weight: bold;
                    font-size: 15pt;
                    padding-bottom: 5px;
                }
    
                button {
                    font-weight: bold;
                    font-size: 15pt;
                }
    
            </style>
        </head>
        <body>
            <h2> UIO / Control LED<br>
                <br>
                <img id="remote" src="button_pop.png">
                <br>
            </h2>
            <h2>WebSocket <span id="ws_state"><span style="color: gray">CLOSED</span></span></h2>
            <button id="bt_connect" type="button" onclick="connect_onclick();">Connect</button>
        </body>
        <script>
    
        var isON;
        var ws;
        var remote;
    
        function init()
        {
            remote = document.getElementById("remote");
            remote.addEventListener("click", toogleLed);
            isON = 0;
        }
    
        function connect_onclick()
        {
            if(ws == null)
            {
                var ws_host_addr = "<?echo _SERVER("HTTP_HOST")?>";
                if((navigator.platform.indexOf("Win") != -1) && (ws_host_addr.charAt(0) == "["))
                {
                    // network resource identifier to UNC path name conversion
                    ws_host_addr = ws_host_addr.replace(/[\[\]]/g, '');
                    ws_host_addr = ws_host_addr.replace(/:/g, "-");
                    ws_host_addr += ".ipv6-literal.net";
                }
                ws = new WebSocket("ws://" + ws_host_addr + "/remote_led", "text.phpoc");
                document.getElementById("ws_state").innerHTML = "CONNECTING";
                ws.onopen = ws_onopen;
                ws.onclose = ws_onclose;
                ws.onmessage = ws_onmessage;
            }
            else
                ws.close();
        }
    
        function ws_onopen()
        {
            document.getElementById("ws_state").innerHTML = "<span style='color: blue'>CONNECTED</span>";
            document.getElementById("bt_connect").innerHTML = "Disconnect";
            displayLEDStatus();
        }
    
        function ws_onclose()
        {
            document.getElementById("ws_state").innerHTML = "<span style='color: gray'>CLOSED</span>";
            document.getElementById("bt_connect").innerHTML = "Connect";
            ws.onopen = null;
            ws.onclose = null;
            ws.onmessage = null;
            ws = null;
            isON = 0;
            displayLEDStatus();
        }
    
        function ws_onmessage(e_msg)
        {
            e_msg = e_msg || window.event; // MessageEvent
            isON = parseInt(e_msg.data);
            displayLEDStatus();
        }
    
        function toogleLed()
        {
            if (isON)
                ws.send("0");
            else
                ws.send("1");
        }
    
        function displayLEDStatus()
        {
            remote.src = (isON) ? "button_push.png" : "button_pop.png";
        }
    
        window.onload = init;
        </script>
    </html>

    And here is the Arduino code

    Code:
    #include <Phpoc.h>
    
    PhpocServer server(80);
    int ledPin = 8;
    
    void setup() {
      Serial.begin(9600);
      while(!Serial)
        ;
    
      // initialize PHPoC [WiFi] Shield:
      Phpoc.begin(PF_LOG_SPI | PF_LOG_NET);
      //Phpoc.begin();
    
      // start WebSocket server
      server.beginWebSocket("remote_led");
    
      // print IP address of PHPoC [WiFi] Shield to serial monitor:
      Serial.print("WebSocket server address : ");
      Serial.println(Phpoc.localIP());
      pinMode(ledPin, OUTPUT);
    }
    
    void loop() {
      // wait for a new client:
      PhpocClient client = server.available();
    
      if (client) {
        if (client.available() > 0) {
          // read a byte incoming from the client:
          char thisChar = client.read();
    
          switch(thisChar)
          {
            case '0':
              Serial.println("Turn LED OFF");
              digitalWrite(ledPin, LOW);
              server.write('0');
              break;
            case '1':
              Serial.println("Turn LED ON");
              digitalWrite(ledPin, HIGH);
              server.write('1');
              break;
          }
        }
      }
    }

    Then try to access the web app at http://REPLACE_YOUR_SHIELD_IP_ADDR_HERE/remote_led.php
    Don't forget to upload the two images that were used in the original example (button_push.png, button_pop.png).
    P/S: In my example I use WebSocket to exchange data between web browser and Arduino, so you may need to click the CONNECT button to initialize a WebSocket connection.
    Cheers
    Last edited by Homer; 04-25-2019, 12:39 PM.

    Leave a comment:


  • Khanh
    replied
    Hello Badener,
    You are using PHPoC Blue (P4S-342) or Black (P4S-341), NOT PHPoC Shield, right ?
    The code in the link you give is for PHPoC Blue/Black, NOT for PHPoC Shield.

    Could you please post your modified code here ?

    Leave a comment:


  • Badener
    started a topic PHP error: Wrong pin?

    PHP error: Wrong pin?

    Hi. I'm very newbe with PHPoC Shield for Adruino and today i trying to make small project like here: https://forum.phpoc.com/articles/tut...age-with-image , but when i change pin to 8 - i become a message: " UIO / On-Board User LED

    PHP error: invalid argument in file lib/sd_340.php on line 65"


    What did I do wrong?
Working...
X