Arduino WebClient Switch bounce problem

Hi Folks,
I'm designing a webpage dashboard which utilizes toggle switches to control relays remotely.
The problem I'm encountering is that when I click the switch on the webpage, it momentarily goes on, then goes off, and then goes back on. When I click it again to turn it off, it goes off, then momentarily back on and then back off.

I'm using an Arduino Uno with an Ethernet Shield and a 4-channel relay board.
Here is the code for both the webpage (index.htm) which gets installed on the SD card in the Ethernet Shield as well as the C++ sketch:

Arduino-Web-Client-Switches

Here's a visual of the problem for more clarity using the actual toggle switches: Video of bouncing toggles

Note: The problem is even more apparent when using Toggle Switches, but I've left out the CSS for these as its still obvious with the default checkbox. Also, the 4 channel relay board is not required to reproduce the issue.

I've tried to minimize the problem by changing the setTimeout('GetArduinoInputs()', 1000); from 1000 microseconds to 100 microsecond and although this helps, there is still a bounce.

I'm wondering if there is anything I can change in the code to eliminate this bounce?
Any suggestions would be greatly appreciated...
Thanks !

Here's the index.htm and Sketch code which is also downloadable from the github link above:

Webpage:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Switches</title>
        <script>
            strSW1 = "";
		    strSW2 = "";
		    strSW3 = "";
		    strSW4 = "";
            function GetArduinoInputs()
            {
                nocache = "&nocache=" + Math.random() * 1000000;
                var request = new XMLHttpRequest();
                request.onreadystatechange = function()
                {
                    if (this.readyState == 4) {
                        if (this.status == 200) {
                            if (this.responseXML != null) {
                                <!-- switch values -->
                                // SWITCH 1
							    if (this.responseXML.getElementsByTagName('SW')[0].childNodes[0].nodeValue === "checked") {
								    document.SW_form.SW1.checked = true;
							    }
							    else {
								    document.SW_form.SW1.checked = false;
							    }
							    // SWITCH 2
							    if (this.responseXML.getElementsByTagName('SW')[1].childNodes[0].nodeValue === "checked") {
								    document.SW_form.SW2.checked = true;
							    }
							    else {
								    document.SW_form.SW2.checked = false;
							    }
							    // SWITCH 3
							    if (this.responseXML.getElementsByTagName('SW')[2].childNodes[0].nodeValue === "checked") {
								    document.SW_form.SW3.checked = true;
							    }
							    else {
								    document.SW_form.SW3.checked = false;
							    }
							    // SWITCH 4
							    if (this.responseXML.getElementsByTagName('SW')[3].childNodes[0].nodeValue === "checked") {
								    document.SW_form.SW4.checked = true;
							    }
							    else {
								    document.SW_form.SW4.checked = false;
							    }
                            }
                        }
                    }
                }
                request.open("GET", "ajax_inputs" + strSW1 + strSW2 + strSW3 + strSW4 + nocache, true);
                request.send(null);
                setTimeout('GetArduinoInputs()', 1000);
				strSW1 = "";
		    	strSW2 = "";
		    	strSW3 = "";
		    	strSW4 = "";
            }
            // service SWITCHES when toggles checked/unchecked
	        function SwitchCheck()
	        {
				if (SW_form.SW1.checked) {
					strSW1 = "&SW1=1";
			    }
			    else {
					strSW1 = "&SW1=0";
			    }
			    if (SW_form.SW2.checked) {
					strSW2 = "&SW2=1";
			    }
			    else {
					strSW2 = "&SW2=0";
			    }
			    if (SW_form.SW3.checked) {
					strSW3 = "&SW3=1";
			    }
			    else {
					strSW3 = "&SW3=0";
			    }
			    if (SW_form.SW4.checked) {
					strSW4 = "&SW4=1";
			    }
			    else {
					strSW4 = "&SW4=0";
			    }
			}
        </script>
    	<style>
            html,
    		body {
        		width: 100%;
        		height: 100%;
        		background-color: black;
        		display: table-cell;
        		vertical-align: middle;
				}
    		html {
        		display: table;
    			}
			h1 {
	            font-family: arial, verdana, sans-serif;
	            text-align:center;
	            color:white;
	            font-size:18px;
	            letter-spacing:1px;
	            }
            #table_S{
        		table-layout: auto;
				margin-left: auto;
    			margin-right: auto;
				width: 45%;
        		height: 100px;
        		border: 0px solid white;
				text-align:center;
        		}

        </style>
    </head>

    <div id="body">
    <body onload="GetArduinoInputs()">
				
        <table id="table_S">
			<tr>
			<form name="SW_form">
			<td><center><input type="checkbox" name="SW1" value="0" onclick="SwitchCheck()" /><br /><br /></center></td>
			<td width="75"></td>
			<td><center><input type="checkbox" name="SW2" value="0" onclick="SwitchCheck()" /><br /><br /></center></td>
			<td width="75"></td>
			<td><center><input type="checkbox" name="SW3" value="0" onclick="SwitchCheck()" /><br /><br /></center></td>
			<td width="75"></td>
			<td><center><input type="checkbox" name="SW4" value="0" onclick="SwitchCheck()" /><br /><br /></center></td>
            </form>
			</tr>
            <tr><td><H1>Switch 1</H1><td width=75></td><td><H1>Switch 2</H1></td><td width=75></td><td><H1>Switch 3</H1></td><td width=75></td><td><H1>Switch 4</H1></td></tr>
 		</table>
    </body>
    </div>
</html>

Skertch:

#include <SD.h>                                               // The SD library allows for reading from and writing to SD cards
#include <SPI.h>
#include <Ethernet.h>

#define REQ_BUF_SZ   50                                       

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };          
IPAddress ip(192, 168, 50, 141);                        // IMPORTANT: replace with your IP address                           
EthernetServer server(80);

File SdCardFile;                                              
boolean SWITCH_state[4] = {0};                                
char HTTP_request[REQ_BUF_SZ] = {0};                          
char request_index = 0;                                       

void setup()
{
  
    pinMode(10, OUTPUT);
    digitalWrite(10, HIGH);

    pinMode(5, OUTPUT);     // Switch #1
    pinMode(6, OUTPUT);     // Switch #2
    pinMode(7, OUTPUT);     // Switch #3
    pinMode(8, OUTPUT);     // Switch #4
    // Initialize Switches 
    digitalWrite(5, HIGH);
    digitalWrite(6, HIGH);
    digitalWrite(7, HIGH);
    digitalWrite(8, HIGH);
    Serial.begin(9600);                                       
    Ethernet.begin(mac, ip);                                  
    server.begin();
    // initialize SD card
    Serial.println("Initializing SD card...");
    if (!SD.begin(4)) {
        Serial.println("ERROR - Bad or missing SD card");
        return;    
    }
    Serial.println("SUCCESS - SD card found");
    
    if (!SD.exists("index.htm"))  {                           
        Serial.println("ERROR - Can't find index.htm file!");
        return;                                             
    }
    Serial.println("SUCCESS - Found index.htm file.");
}

void loop()
{
    EthernetClient client = server.available();           
    if (client) {                                         
        // an http request ends with a blank line
        boolean currentLineIsBlank = true;
        while (client.connected()) {
            if (client.available()) {                          
                char c = client.read();                       
                if (request_index < (REQ_BUF_SZ - 1)) {        
                    HTTP_request[request_index] = c;          
                    request_index++;
                }
                if (c == '\n' && currentLineIsBlank) {
                    // send a standard http response header
                    client.println("HTTP/1.1 200 OK");
                    // remainder of header follows below, depending on if
                    // web page or XML page is requested
                    // Ajax request - send XML file
                    if (StrContains(HTTP_request, "ajax_inputs")) {
                        // send rest of HTTP header
                        client.println("Content-Type: text/xml");
                        client.println("Connection: keep-alive");
                        client.println();
                        // send XML file containing input states
                        XML_response(client);
                        SetSWITCHES();
                    }
                    else  {
                        // web page request
                        // send rest of HTTP header 
                        client.println("Content-Type: text/html");
                        client.println("Connection: close");
                        client.println();
                        // send web page
                        SdCardFile = SD.open("index.htm");        // open web page file
                        if (SdCardFile) {
                          while(SdCardFile.available()) {
                            client.write(SdCardFile.read());      // send web page to client
                          }
                        SdCardFile.close();
                      }
                    }
                    // display received HTTP request on serial port
                    Serial.println(HTTP_request);
                    // reset buffer index and all buffer elements to 0
                    request_index = 0;
                    StrClear(HTTP_request, REQ_BUF_SZ);
                    break;
                }
                if (c == '\n') {
                    // you're starting a new line
                    currentLineIsBlank = true;
                } 
                else if (c != '\r') {
                    // you've gotten a character on the current line
                    currentLineIsBlank = false;
                }
            } // end of client.available
        } // end of client.connected
        delay(1); // give the web browser time to receive the data
        client.stop(); // close the connection
    } 
}

char StrContains(char *str, char *sfind)
// searches for the string sfind in the string str, returns 1 if string found or returns 0 if string not found.
{
    char found = 0;
    char index = 0;
    char len;
    len = strlen(str);
    if (strlen(sfind) > len) {
        return 0;
    }
    while (index < len) {
        if (str[index] == sfind[found]) {
            found++;
            if (strlen(sfind) == found) {
                return 1;
            }
        }
        else {
            found = 0;
        }
        index++;
    }
    return 0;
}

void XML_response(EthernetClient cl)
{
    // Sending Switch Values to webclient 
    cl.print("<?xml version = \"1.0\" ?>");
    cl.print("<inputs>");
    // Sending SWITCH states to dashboard 
    // SWITCH #1
    cl.print("<SW>");           
    if (SWITCH_state[0]) {
        cl.print("checked");
    }
    else {
        cl.print("unchecked");
    }
    cl.println("</SW>");
    // SWITCH #2
    cl.print("<SW>");
    if (SWITCH_state[1]) {
        cl.print("checked");
    }
    else {
        cl.print("unchecked");
    }
    cl.println("</SW>");    
    // SWITCH #3
    cl.print("<SW>");
    if (SWITCH_state[2]) {
        cl.print("checked");
    }
    else {
        cl.print("unchecked");
    }
    cl.println("</SW>");
    // SWITCH #4
    cl.print("<SW>");
    if (SWITCH_state[3]) {
        cl.print("checked");
    }
    else {
        cl.print("unchecked");
    }
    cl.println("</SW>");
    cl.print("</inputs>"); 
}

void SetSWITCHES(void)
// checks if received HTTP request is switching any of our switches
{
    // SWITCH #1
    if (StrContains(HTTP_request, "SW1=1")) {
        SWITCH_state[0] = 1;  // save SWITCH state
        digitalWrite(5, LOW);
    }
    else if (StrContains(HTTP_request, "SW1=0")) {
        SWITCH_state[0] = 0;  // save SWITCH state
        digitalWrite(5, HIGH);
    }
    // SWITCH #2
    if (StrContains(HTTP_request, "SW2=1")) {
        SWITCH_state[1] = 1;  // save SWITCH state
        digitalWrite(6, LOW);
    }
    else if (StrContains(HTTP_request, "SW2=0")) {
        SWITCH_state[1] = 0;  // save SWITCH state
        digitalWrite(6, HIGH);
    }
    // SWITCH #3 (
    if (StrContains(HTTP_request, "SW3=1")) {
        SWITCH_state[2] = 1;  // save SWITCH state
        digitalWrite(7, LOW);
    }
    else if (StrContains(HTTP_request, "SW3=0")) {
        SWITCH_state[2] = 0;  // save SWITCH state
        digitalWrite(7, HIGH);
    }
    // SWITCH #4 
    if (StrContains(HTTP_request, "SW4=1")) {
        SWITCH_state[3] = 1;  // save SWITCH state
        digitalWrite(8, LOW);
    }
    else if (StrContains(HTTP_request, "SW4=0")) {
        SWITCH_state[3] = 0;  // save SWITCH state
        digitalWrite(8, HIGH);
    }
}

void StrClear(char *str, char length)
// sets every element of str to 0 (clears array)
{
    for (int i = 0; i < length; i++) {
        str[i] = 0;
    }
}

Sorry, word salad.

What do you think is bouncing?

Is the Arduino getting multiple actions from the PC web thing that has some virtual buttons?

Can you add some print statements to your setSWITCHES() function to see what it is doing?

a7

I added some print statements to the setSWITCHES() function and the behavior seems normal.
I then went through the logic one more time step by step and had the idea to change the sequence of two functions, i.e. run setSWITCHES() first and then run XML_response(). This solved the problem. Thanks

Yay! Good work.

a7