Hi Friend!
Thank you to be a new small part of this great community.
I may ask for help instantly because I cannot find a mistake in my sketch.
The goal: Arduino is controlling via Ethernet Shield a Relay shield, remotely operated by a simple web page.
The problem: On the web page, the push button who should trigger one of the relays, also is triggered by opening the page or by refreshing the page.
I have no idea what could be the problem: Syntax? Wrong placement of code segments? Missing or wrong code?
I like to show the complete code here, maybe somebody is able to find the bug? I am not, sorry
#include <SPI.h>
#include <Ethernet.h>
// MAC-Adresse des Ethernet-Shields
byte mac[] = {0xA8, 0x0A, 0xAE, 0xDE, 0xD9};
// IP-Adresse, Subnetzmaske und Gateway
IPAddress ip(11, 9, 69, 222);
IPAddress subnet(255, 0, 0, 0);
IPAddress gateway(11, 9, 69, 1);
EthernetServer server = EthernetServer(80);
const int relayPin = 8;
void setup() {
pinMode(relayPin, OUTPUT);
Ethernet.begin(mac, ip, gateway, gateway, subnet);
server.begin();
}
void loop() {
EthernetClient client = server.available();
if (client) {
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
if (c == '\n' && currentLineIsBlank) {
// HTTP-Header senden
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
// HTML-Seite senden
client.println(" <!DOCTYPE html><html>");
client.println(" <head><title>GM2000 Bootbutton</title></head>");
client.println(" <body bgcolor=\"#6E6E6E\">");
client.println(" <div style=\"text-align: center; font: Arial; size: 16pt\">");
client.println(" <br><br><br><br>");
client.println(" <br><br><br><br>");
client.println(" <br><br><br><br>");
client.println(" <h1>10Micron GM2000-HPSII</h1>");
client.println(" <br>");
client.println(" <button style=\"height: 70px; width: 190px; font-size: 14pt; background-color: #d57800; border-radius: 10px; cursor: pointer; \" onclick=\"activateRelay()\">Boot / Shutdown</button>");
client.println(" <br>");
client.println(" <br>");
client.println(" <span style=\"color: #393939;\">Feste IP: 11.9.69.222</span>");
client.println(" </div>");
client.println(" <script>");
client.println(" function activateRelay() {");
client.println(" var xhttp = new XMLHttpRequest();");
client.println(" xhttp.open(\"GET\", \"/trigger\", true);");
client.println(" xhttp.send();");
client.println("}");
client.println(" </script>");
client.println(" </body></html>");
// Wenn der Button auf der Webseite gedrückt wurde, Relais für 1500 ms aktivieren
if (client.find("trigger") != -1) {
activateRelay();
}
break;
}
if (c == '\n') {
currentLineIsBlank = true;
} else if (c != '\r') {
currentLineIsBlank = false;
}
}
}
delay(1);
client.stop();
}
}
void activateRelay() {
digitalWrite(relayPin, HIGH);
delay(1500); // Relais für 1500 ms aktivieren
digitalWrite(relayPin, LOW);
}
Thank you for watching!
Jens