Hi All,
I am using the below code to turn a relay on and off
I am having a problem as the server will refuse connection every now and again i can refresh 40 times or so and it will work every time but then sometime it wont get a response!
Any ideas why this would be I want it to always accept the connections made to it and respond.
Using a MEGA 2560 (MEGA ADK) and an Ethernet shield I have also tested the code on the UNO and it does the same.
#include <SPI.h>
#include <Ethernet.h>
EthernetServer server(5411);// Server port
byte mac[] = { 0x00, 0x08, 0xDC, 0xAB, 0xCD, 0xEF };// Physical MAC address
byte ip[] = { 192, 168, 0, 125 };// Fixed IP address
byte gateway[] = { 192, 168, 0, 1 };// Router Gateway Internet access
byte subnet[] = { 255, 255, 255, 0 };// Subnet mask
const int relay1 = 14; pin 14
String readString;
void setup()
{
pinMode(relay1, OUTPUT); // this is relay 1
//start Ethernet
Ethernet.begin(mac, ip, gateway, subnet);
server.begin();
//enable serial data print
// Serial.begin(9600);
}
void loop()
{
// Create a client connection
EthernetClient client = server.available();
if (client) {
while (client.connected()) {
if (client.available()) {
char c = client.read();
//read char by char HTTP request
if (readString.length() < 200) {
//store characters to string
readString += c;
//Serial.print(c);
}
//if HTTP request has ended
if (c == '\n') {
/* Start OF HTML Section. Here Keep everything as it is unless you understands its working */
client.println(F("HTTP/1.1 200 OK")); //send new page
client.println(F("Content-Type: text/html"));
client.println();
//start relay 1
if (readString.indexOf("?r1on") > 0)
{
digitalWrite(relay1, HIGH);
}
if (readString.indexOf("?r1off") > 0)
{
digitalWrite(relay1, LOW );
}
//start
if (digitalRead(relay1))
{
//on
client.print(F("r1on,"));
} else {
//off
client.print(F("r1off,"));
}
//end
//clearing string for next read
readString = "";
//stopping client
//client.print('A');
delay(1);
client.stop();
Serial.println("client disconnected");
}
}
}
}
}
Cheers James