2

I have a Script in my HTML document that detects when one of the arrow keys is detected then it changes the URL of an iframe. When the key is released the iframe is changed again.

This works except during the time that the key is being held down it keeps repeating the action to set the iframe's url.

Is there a way so when its held down it only changes the iframe url once? Then when its released it changes the url back?

Extra: Iv created a page to control a remote control car over the web. It works great except for this problem. Basicly it changes the iframe url to a PHP page with a diffrent get variable for each arrow key. The PHP page then uses PHP Serial to send data to the serial port based on what ever variable was sent from the iframe (using GET).

Thanks for any help!!!

Edit: Here's a picture of the car. http://oi41.tinypic.com/21cimms.jpg

Edit 2

Heres the index.html

<!doctype html>
<html lang="en">
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
        <script type="text/javascript">
        function pause(ms) {
           ms += new Date().getTime();
           while (new Date() < ms){}
          } 
            var keyBeingHeld = new Array();
            keyBeingHeld[0] = false;//left
            keyBeingHeld[1] = false;//right
            keyBeingHeld[2] = false;//up
            keyBeingHeld[3] = false;//down

            function setControllerState(action){
                leftPressState="up";
                rightPressState="up";
                upPressState="up";
                downPressState="up";
                if (keyBeingHeld[0]){
                    leftPressState="down";

                }
                if (keyBeingHeld[1]){
                    rightPressState="down";
                }
                if (keyBeingHeld[2]){
                    upPressState="down";
                }
                if (keyBeingHeld[3]){
                    downPressState="down";
                }
                var stateStr = "?upPressState="+upPressState+"&downPressState="+downPressState+"&leftPressState="+leftPressState+"&rightPressState="+rightPressState;
                iframe = document.getElementById('stateFrame');
                iframe.src = "BackEnd.php"+stateStr+"&action="+action;

            }

            $(document).keydown(function(event) {
                if (!event) var event = window.event;
                switch (event.keyCode) {
                    case 37: 
                        if (!keyBeingHeld[0]){
                            keyBeingHeld[0] = true;
                            setControllerState ("leftArrowPress");
                        } 
                        break;
                    case 38: 
                        if (!keyBeingHeld[2]){
                            keyBeingHeld[2] = true;
                            setControllerState ("upArrowPress");
                        } 
                        break;
                    case 39: 
                        if (!keyBeingHeld[1]){
                            keyBeingHeld[1] = true;
                            setControllerState ("rightArrowPress");
                        } 
                        break;
                    case 40: 
                        if (!keyBeingHeld[3]){
                            keyBeingHeld[3] = true;
                            setControllerState ("downArrowPress");

                        } 
                        break;
                }
            });

            $(document).keyup(function(event) {
                if (!event) var event = window.event;
                switch (event.keyCode) {
                    case 37: 
                        if (keyBeingHeld[0]){
                            keyBeingHeld[0] = false;
                            setControllerState ("leftArrowRelease");    
                        } 
                        break;
                    case 38: 
                        if (keyBeingHeld[2]){
                            keyBeingHeld[2] = false;
                            setControllerState ("upArrowRelease");

                        } 
                        break;
                    case 39: 
                        if (keyBeingHeld[1]){
                            keyBeingHeld[1] = false;
                            setControllerState ("rightArrowRelease");

                        } 
                        break;
                    case 40: 
                        if (keyBeingHeld[3]){
                            keyBeingHeld[3] = false;
                            setControllerState ("downArrowRelease");
                        } 
                        break;
                }
            });
        </script>
    </head>
    <body>
       <p>Press one of the arrow keys.</p>
       <iframe id="stateFrame" name="stateFrame" style="width:160px;height:180px;" src="BackEnd.php?upPressState=up&downPressState=up&leftPressState=up&downPressState=up&action=none"></iframe>
       <p>Thanks vdbuilder!</p>
    </body>
</html>

Heres the backend.php

<?php
    $opened = false;

    $upPressState = cleanupSpecialChars($_GET['upPressState']) or $upPressState = 'up';   
    $downPressState = cleanupSpecialChars($_GET['downPressState']) or $downPressState = 'up';
    $leftPressState = cleanupSpecialChars($_GET['leftPressState']) or $leftPressState = 'up';   
    $rightPressState = cleanupSpecialChars($_GET['rightPressState']) or $rightPressState = 'up';
    $action = cleanupSpecialChars($_GET['action']) or $action = 'none';

    // build your message from states and action, and send to serial port here 

    //the rest is to display the state
    $pressedColor = "bbffbb";
    $releasedColor = "bbbbbb";

    $upArrowColor = $releasedColor;
    $downArrowColor = $releasedColor;
    $leftArrowColor = $releasedColor;
    $rightArrowColor = $releasedColor;





    if($upPressState == "down"){ 
        sendCMD(25);
        $upArrowColor = $pressedColor;
    }
    if($downPressState == "down"){
        sendCMD(24);
        $downArrowColor = $pressedColor;
    }
    if($leftPressState == "down"){
        sendCMD(28);
        $leftArrowColor = $pressedColor;
    }
    if($rightPressState == "down"){
        sendCMD(29);
        $rightArrowColor = $pressedColor;
    }
    //--- Up
     if($upPressState == "up"){ 
        sendCMD(15);
        $upArrowColor = $releasedColor; 
    }
         if($downPressState == "up"){ 
        sendCMD(14);
        $downArrowColor = $releasedColor;   
    }
         if($leftPressState == "up"){ 
         sendCMD(18);
        $leftArrowColor = $releasedColor;   
    }
         if($rightPressState == "up"){ 
         sendCMD(19);
        $rightArrowColor = $releasedColor;  
    }

    echo("<html><head><style>");
    echo("body{background-color:#000000;}
          div#container{position:absolute;left:10px;top:10px;background-color:#eeeeee;
              font-size:20px;padding:20px;width:100px;height:92px;text-align:center;}
          div.arrow{position:absolute;width:30px;padding-top:2px;padding-bottom:2px;}
          div#upArrow{left:55px;top:20px;background-color:#".$upArrowColor.";}
          div#downArrow{left:55px;top:82px;background-color:#".$downArrowColor.";}
          div#leftArrow{left:20px;top:50px;background-color:#".$leftArrowColor.";}
          div#rightArrow{left:90px;top:50px;background-color:#".$rightArrowColor.";}
          div#lastAction{position:absolute;left:0px;bottom:2px;font-size:14px;color:#ffffee;}");
    echo("</style></head><body>");
    echo("<div id='container'>
          <div class='arrow' id='upArrow'>&uarr;</div><div class='arrow' id='downArrow'>&darr;</div>
          <div class='arrow' id='leftArrow'>&larr;</div><div class='arrow' id='rightArrow'>&rarr;</div>
          </div><div id='lastAction'>Last Action:<br />".$action."</div>");
    echo("</body></html>");

//cleanup input
    function cleanupSpecialChars($inStr){
        $tempStr = htmlentities(stripslashes($inStr));
        $retStr = str_replace(array('\\','/'), '', $tempStr);
        return $retStr;
    }
    function sendCMD($cmd){
        if($opened == false){
        $fp =fopen("com4", "wb");
         } 
        fwrite($fp,$cmd);
        fclose($fp);
        }


?>
  • Iv tried so much. None are working correctly. Ill try to get my original code back and post it. Thanks for your reply. – Mitchell4500 Jan 05 '12 at 03:15
  • I was using this. http://stackoverflow.com/questions/2217553/detecting-arrow-key-press-in-ie-via-javascript-jquery. Then I made a copy of that script for keyup too. – Mitchell4500 Jan 05 '12 at 03:22
  • Thanks for your anwser. I did post code cause I barely had any. I didn't really know where to start. – Mitchell4500 Jan 05 '12 at 11:21
  • I don't have enough reputation but I set it as the answer. – Mitchell4500 Jan 05 '12 at 11:31
  • No rush. Im just reading lots of things on this site. I understand the concept of what your talking about but I have no idea how to do that. Ill google it some. – Mitchell4500 Jan 06 '12 at 01:58
  • Finally got a minute to add event buffering and synchronization of the frontend and backend code should work better now, this does come at a cost of a slight delay in the firing of events but it's negligible. I guess that's the price you pay. : ) – vdbuilder Jan 06 '12 at 09:05

2 Answers2

2

Set a flag on keydown, clear it on keyup. Only fire the action if the flag isn't set.

Zeta Two
  • 1,776
  • 1
  • 18
  • 37
1

Short answer:

Set a flag and test if it's set before you send the request.

Long answer:

Two files are required.
The two files below work as follows:

You navigate to FrontEnd.html. It maintains state and contains an iframe. The iframe is loaded with BackEnd.php (with its state variables set to default values and passed via the get method). When a key is pressed or released FrontEnd.html reloads the iframe with BackEnd.php (passing state via get method).

BackEnd.php sends the message to the serial port and displays the state of the arrow keys, based on the variables passed to it from FrontEnd.html.

<!doctype html>
<html lang="en">
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
        <script type="text/javascript">
            var controllerIsReady = false;
            var keyEventBuffer = new Array();
            var keyBeingHeld = new Array();
            keyBeingHeld[0] = false;//left
            keyBeingHeld[1] = false;//right
            keyBeingHeld[2] = false;//up
            keyBeingHeld[3] = false;//down

            function controllerReady(){
                controllerIsReady = false;
                if(keyEventBuffer.length > 0){
                    bufferDiv = document.getElementById('eventBuffer');
                    buffHtmlStr = " ";
                    for (i=0;i<keyEventBuffer.length;i++){
                        tempStr = keyEventBuffer[i];
                        index = tempStr.indexOf("action", 0)+7;
                        keyEventStr = tempStr.substr(index,(tempStr.length-index));
                        buffHtmlStr = buffHtmlStr + "<br />" + keyEventStr;
                    }
                    bufferDiv.innerHTML = buffHtmlStr;
                    //shift event off and make request
                    stateStr = keyEventBuffer.shift(); 
                    iframe = document.getElementById('stateFrame');
                    iframe.src = "http://www.vdstudios.net/robotics/BackEnd.php"+stateStr; 
                }
                else{
                    controllerIsReady = true;//alert("ready");
                    bufferDiv = document.getElementById('eventBuffer');
                    bufferDiv.innerHTML = "empty";
                }

            }

            function setControllerState(action){
                leftPressState="up";
                rightPressState="up";
                upPressState="up";
                downPressState="up";
                if (keyBeingHeld[0]){
                    leftPressState="down";
                }
                if (keyBeingHeld[1]){
                    rightPressState="down";
                }
                if (keyBeingHeld[2]){
                    upPressState="down";
                }
                if (keyBeingHeld[3]){
                    downPressState="down";
                }
                var stateStr = "?upPressState="+upPressState+"&downPressState="+downPressState+"&leftPressState="+leftPressState+"&rightPressState="+rightPressState+"&action="+action;

                //add stateStr to fifo and if controllerIsReady call controllerReady
                keyEventBuffer.push(stateStr);
                if(controllerIsReady){
                    controllerReady();
                }
            }

            $(document).keydown(function(event) {
                if (!event) var event = window.event;
                switch (event.keyCode) {
                    case 37: 
                        if (!keyBeingHeld[0]){
                            keyBeingHeld[0] = true;
                            setControllerState ("leftArrowPress");
                        } 
                        break;
                    case 38: 
                        if (!keyBeingHeld[2]){
                            keyBeingHeld[2] = true;
                            setControllerState ("upArrowPress");
                        } 
                        break;
                    case 39: 
                        if (!keyBeingHeld[1]){
                            keyBeingHeld[1] = true;
                            setControllerState ("rightArrowPress");
                        } 
                        break;
                    case 40: 
                        if (!keyBeingHeld[3]){
                            keyBeingHeld[3] = true;
                            setControllerState ("downArrowPress");
                        } 
                        break;
                }
            });

            $(document).keyup(function(event) {
                if (!event) var event = window.event;
                switch (event.keyCode) {
                    case 37: 
                        if (keyBeingHeld[0]){
                            keyBeingHeld[0] = false;
                            setControllerState ("leftArrowRelease");
                        } 
                        break;
                    case 38: 
                        if (keyBeingHeld[2]){
                            keyBeingHeld[2] = false;
                            setControllerState ("upArrowRelease");
                        } 
                        break;
                    case 39: 
                        if (keyBeingHeld[1]){
                            keyBeingHeld[1] = false;
                            setControllerState ("rightArrowRelease");
                        } 
                        break;
                    case 40: 
                        if (keyBeingHeld[3]){
                            keyBeingHeld[3] = false;
                            setControllerState ("downArrowRelease");
                        } 
                        break;
                }
            });
        </script>
    </head>
    <body>
       <p>Press one of the arrow keys.</p>
       <iframe id="stateFrame" name="stateFrame" style="width:160px;height:180px;" src="http://www.vdstudios.net/robotics/BackEnd.php?upPressState=up&downPressState=up&leftPressState=up&rightPressState=up&action=none"></iframe>
       <div style="width:160px;padding:2px;padding-top:5px;background-color:#cccccc;text-align:center;">Event buffer<hr /><div id="eventBuffer" style="width:100%;">text</div></div> 
    </body>
</html>

BackEnd.php

<?php
    header("Cache-Control: no-store, no-cache, must-revalidate"); 
    header("Cache-Control: post-check=0, pre-check=0", false); 
    // HTTP/1.0 
    header("Pragma: no-cache");

    $upPressState = cleanupSpecialChars($_GET['upPressState']) or $upPressState = 'up';   
    $downPressState = cleanupSpecialChars($_GET['downPressState']) or $downPressState = 'up';
    $leftPressState = cleanupSpecialChars($_GET['leftPressState']) or $leftPressState = 'up';   
    $rightPressState = cleanupSpecialChars($_GET['rightPressState']) or $rightPressState = 'up';
    $action = cleanupSpecialChars($_GET['action']) or $action = 'none';

    //send message to serial port 
    if($action == "upArrowPress"){
        sendCMD(25);
    }
    else if($action == "downArrowPress"){
        sendCMD(24);
    }
    else if($action == "leftArrowPress"){
        sendCMD(28);
    }
    else if($action == "rightArrowPress"){
        sendCMD(29);
    }
    else if($action == "upArrowRelease"){
        sendCMD(15);
    }
    else if($action == "downArrowRelease"){
        sendCMD(14);
    }
    else if($action == "leftArrowRelease"){
        sendCMD(18);
    }
    else if($action == "rightArrowRelease"){
        sendCMD(19);
    }

    //the rest is to display the state
    $pressedColor = "bbffbb";
    $releasedColor = "bbbbbb";

    $upArrowColor = $releasedColor;
    $downArrowColor = $releasedColor;
    $leftArrowColor = $releasedColor;
    $rightArrowColor = $releasedColor;

    if($upPressState == "down"){
        $upArrowColor = $pressedColor;
    }
    if($downPressState == "down"){
        $downArrowColor = $pressedColor;
    }
    if($leftPressState == "down"){
        $leftArrowColor = $pressedColor;
    }
    if($rightPressState == "down"){
        $rightArrowColor = $pressedColor;
    }

    echo("<html><head><style>");
    echo("body{background-color:#000000;}
          div#container{position:absolute;left:10px;top:10px;background-color:#eeeeee;
              font-size:20px;padding:20px;width:100px;height:92px;text-align:center;}
          div.arrow{position:absolute;width:30px;padding-top:2px;padding-bottom:2px;}
          div#upArrow{left:55px;top:20px;background-color:#".$upArrowColor.";}
          div#downArrow{left:55px;top:82px;background-color:#".$downArrowColor.";}
          div#leftArrow{left:20px;top:50px;background-color:#".$leftArrowColor.";}
          div#rightArrow{left:90px;top:50px;background-color:#".$rightArrowColor.";}
          div#lastAction{position:absolute;left:0px;bottom:2px;font-size:14px;color:#ffffee;}");
    echo("</style></head><body onload='parent.controllerReady();'>");
    echo("<div id='container'>
          <div class='arrow' id='upArrow'>&uarr;</div><div class='arrow' id='downArrow'>&darr;</div>
          <div class='arrow' id='leftArrow'>&larr;</div><div class='arrow' id='rightArrow'>&rarr;</div>
          </div><div id='lastAction'>Last Action:<br />".$action."</div>");
    echo("</body></html>");

//cleanup input
    function cleanupSpecialChars($inStr){
        $tempStr = htmlentities(stripslashes($inStr));
        $retStr = str_replace(array('\\','/'), '', $tempStr);
        return $retStr;
    }
    function sendCMD($cmd){
        if($fp =fopen("com4", "wb")){//windows server
            fwrite($fp,$cmd);
            usleep(15000);
            fclose($fp);
        }
        else if($fp =fopen("/dev/ttyS3", "wb")){//linux server
            fwrite($fp,$cmd);
            usleep(15000);
            fclose($fp);
        }
    }
?>

You can see them running on my server here: http://www.vdstudios.net/robotics/FrontEnd.html

I can help you with building the message for the serial port if you give me details on what the device expects.

EDIT:

Added the code to build/send the message to the serial port. Also updated the running example with the same. You can see it at the link above.

Edit 2:

Added the code for buffering the keyEvents.
Added the code for sync'ing the backend and frontend states.

vdbuilder
  • 12,254
  • 2
  • 25
  • 29
  • Awesome thanks! Ill try this when I get home from school. I already got the code for the serial port (backend) and everything setup. This JavaScript was the one thing I had trouble with. After this I have to setup a line/turn system so only 1 person at a time can drive. Oh and I get the wireless camera too today :) your all welcome to try it out when its done. – Mitchell4500 Jan 05 '12 at 11:19
  • I added a picture if your interested. – Mitchell4500 Jan 05 '12 at 11:25
  • So this code works great but im faced with another problem. When I add the serial communication its not as responsive as before without the serial. I assume its because everytime it must open and close the serial. Sending the first command is fine but sometimes when I release a button it fails to send stop command. Any ideas? Let me know If you want me to post anything. – Mitchell4500 Jan 05 '12 at 21:01
  • Not sure what you mean. But I need when an arrow is pressed it sends a number (ex 25) to the controller. And then when the button is released it sends another number (ex 15). It also needs to be able to function when 2 keys are pressed at once(not necessarily the exact same time), so it can turn. – Mitchell4500 Jan 05 '12 at 22:20
  • I was also thinking using another iframe. The second iframe could just be to send the serial port command. No interface. I think part of the problem could possible be that when the button is pushed then released quickly the last command isnt sent. Maybe. Im not sure. – Mitchell4500 Jan 05 '12 at 22:30
  • @Mitchell4500 Updated my answer to show the serial port code. Tested this on my server (the link to it is in the answer), works well there. More problems/ questions post them I'll be glad to provide further help. ; ) – vdbuilder Jan 05 '12 at 23:08
  • Seems to work nice! The problem im having iv managed to narrow down to sending the commands to the arduino. I belive when you tap a arrow key real fast it sends 25 and then 15 really fast. My controller is programmed to wait 50milsec before it stops reading the serial so it can recive all the data. I think thats why tapping the Arrow key dosent turn of the motor when its releases. Is their anyway we can make this program pause before it sends down 15? – Mitchell4500 Jan 05 '12 at 23:35
  • Thank you so much. Youv pretty much done this whole program for me! I really appreciate it. – Mitchell4500 Jan 05 '12 at 23:51
  • I tried adding a pause to function setControllerState. Didnt work :( – Mitchell4500 Jan 06 '12 at 01:39
  • Awesome ill try it when I get home. – Mitchell4500 Jan 06 '12 at 16:30