Arduino Ethernet loses connection after 30s - arduino

I have an Arduino Uno with a Wiznet Ethernet Shield and it connects fine to the router. But after some time (most 30s) it loses the connection to the router and goes offline. Do somebody see the reason for it in the code?
#include <Ethernet.h>
#include <SPI.h>
boolean reading = false;
////////////////////////////////////////////////////////////////////////
//CONFIGURE
////////////////////////////////////////////////////////////////////////
byte ip[] = { 192, 168, 178, 99 };
//byte gateway[] = { 192, 168, 178, 1 };
//byte subnet[] = { 255, 255, 255, 0 };
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // if need to change the MAC address (Very Rare)
EthernetServer server = EthernetServer(80); //port 80
const int ledPin = 2; // LED Pin
////////////////////////////////////////////////////////////////////////
void setup(){
pinMode(ledPin, OUTPUT); //Pins 10,11,12 & 13 are used by the ethernet shield
digitalWrite(ledPin, LOW);
Ethernet.begin(mac);
server.begin();
}
void loop(){
checkForClient(); // listen for incoming clients, and process qequest.
}
void checkForClient(){
EthernetClient client = server.available();
if (client) {
// an http request ends with a blank line
boolean currentLineIsBlank = true;
boolean sentHeader = false;
while (client.connected()) {
if (client.available()) {
if(!sentHeader){
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
sentHeader = true;
}
char c = client.read();
if(reading && c == ' ') reading = false;
if(c == '?') reading = true; //found the ?, begin reading the info
if(reading){
switch (c) {
case 'on':
digitalWrite(ledPin, HIGH);
break;
case 'off':
digitalWrite(ledPin, LOW);
break;
}
}
if (c == '\n' && currentLineIsBlank) break;
if (c == '\n') {
currentLineIsBlank = true;
}else if (c != '\r') {
currentLineIsBlank = false;
}
}
}
delay(1); // give the web browser time to receive the data
client.stop(); // close the connection:
}
}

Does your Arduino answer incoming ARP requests from router? Seems like it doesn't, but it should.

Related

Single command relay on/off

Hey I have a home automation project I've been working on recently, in which I have an Arduino Mega with an Ethernet shield.
The Mega is waiting for Telnet commands. When a command is received, it turns a relay on. I then have an auto-hotkey script that sends Telnet commands when I press specific keys on my Windows PC.
My problem is that I plan to use 4 relays and right now I have to assign two keys per relay(one for on and for off).
I researched and found about impulse relays, but due to the lockdown, I can't buy any. I tried to find/write code that implemented the same idea in a simple relay but failed.
So, my question is, How do you trigger a relay on/off with a single command?
The code I am using:
#include <SPI.h>
#include <Ethernet.h>
int backlight = 7;
int fan = 6;
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network.
// gateway and subnet are optional:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,21,108);
IPAddress gateway(192,168,21,21);
IPAddress subnet(255, 255, 255, 0);
// telnet defaults to port 23
EthernetServer server(23);
boolean alreadyConnected = false; // whether or not the client was connected previously
String commandString;
void setup() {
pinMode(fan, OUTPUT);
pinMode(backlight, OUTPUT);
Ethernet.begin(mac, ip, gateway, subnet);
// start listening for clients
server.begin();
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
Serial.print("Chat server address:");
Serial.println(Ethernet.localIP());
}
void loop() {
// wait for a new client:
EthernetClient client = server.available();
// when the client sends the first byte, say hello:
if (client) {
if (!alreadyConnected) {
// clear out the input buffer:
client.flush();
commandString = ""; //clear the commandString variable
server.println("--> Please type your command and hit Return...");
alreadyConnected = true;
}
while (client.available()) {
// read the bytes incoming from the client:
char newChar = client.read();
if (newChar == 0x0D) { //If a 0x0D is received, a Carriage Return, then evaluate the command
server.print("Received this command: ");
server.println(commandString);
processCommand(commandString);
} else {
Serial.println(newChar);
commandString += newChar;
}
}
}
}
void processCommand(String command)
{
server.print("Processing command ");
server.println(command);
if (command.indexOf("backlight1") > -1){
server.println("Backlight On command received");
digitalWrite(backlight, HIGH); // sets the LED on
server.println("Backlight was turned on");
commandString = "";
return;
}
if (command.indexOf("backlight0") > -1){
Serial.println("Backlight Off command received");
digitalWrite(backlight, LOW); // sets the LED off
server.println("Backlight was turned off");
commandString = "";
return;;
}
if (command.indexOf("fan1") > -1){
server.println("fan On command received");
digitalWrite(fan, HIGH); // sets the LED on
server.println("Fan was turned on");
commandString = "";
return;
}
if (command.indexOf("fan0") > -1 ){
Serial.println("fan Off command received");
digitalWrite(fan, LOW); // sets the LED off
server.println("Fan was turned off");
commandString = "";
return;
}
commandString = "";
instructions();
}
void instructions()
{
server.println("Please use one of these commands:");
server.println("* backlight1, to turn backlight on");
server.println("* backlight0, to turn off the backligt");
server.println("* fan1, to turn on the fan");
server.println("* fan0, to turn off the fan");
}
If you want to have a single command (= toggle) you need a global bool var for each relay:
bool fanIsOn = false;
// The toggle command is fan
if (command.indexOf("fan") > -1 && fanIsOn == false){
server.println("fan On command received");
digitalWrite(fan, HIGH); // sets the LED on
server.println("Fan was turned on");
fanIsOn = true;
commandString = "";
return;
}
if (command.indexOf("fan") > -1 && fanIsOn == true){
Serial.println("fan Off command received");
digitalWrite(fan, LOW); // sets the LED off
server.println("Fan was turned off");
fanIsOn = false;
commandString = "";
return;
}
Hope this was what you meant

Ethernet Shield Stops After a While

I use Ethernet shield (W5100) and RC522 on my Arduino Uno. It works 1 or 2 hours (sometimes 15 minutes - sometimes 2 days) After this random time, it stops working. I mean stop with, RC-522 module don't read cards, and ethernet shield can't connect server. When i unplug power (1.5A - 12 V power suply) and re-plug it, it starts working successfully.
I need to this system works forever... This system reads mifare card, and sends to the server, after that it checks reply, and if the reply is "1", it triggers relay. (relay is 5V simple relay)
Some people said "Change your adaptor", and i changed it, nothing changed.
Some people said " use 10 microfarad capasitor between rst and gnd pin" and nothing changed.
and some people said, "this is arduino dude, it is for just studend give up and use stm32", and i didn't apply this suggestion yet. I want to know why this happens.
#include <SPI.h>
#include <Ethernet.h>
#include <MFRC522.h>
//Mac address of ethernet shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEA };
//My Network info, i use static ip
byte ip[] = { 172, 16, 64, 78 };
byte gateway[] = { 172, 16, 64, 1 };
byte myserver[] = { 172, 16, 64, 46 };
byte subnet[] = { 255, 255, 255, 0 };
String CardInfo = "";
EthernetClient client;
String GateNo = "0";
String DeviceNo = "100";
String Answer = "";
MFRC522 mfrc522;
byte Key[] = { 0xff,0xff,0xff,0xff,0xff,0xff };
MFRC522::MIFARE_Key key;
void setup(){
//Disabling SD Card
pinMode(4,OUTPUT);
digitalWrite(4,HIGH);
Ethernet.begin(mac, ip, subnet, gateway);
KeyCreate();
mfrc522.PCD_Init(2, 8);
mfrc522.PCD_DumpVersionToSerial();
}
void sendGET()
{
//I used this line to guarantee the disconnect from server
client.stop();
Answer = "";
if (client.connect(myserver, 81)) {
client.println("GET /AccessCheck/CardNo=" + CardInfo + "&GateNo=" + GateNo + "&DeviceNo=" + DeviceNo + " HTTP/1.0");
client.println("Authorization: Basic xxxxxxxxxxxx");
client.println();
}
else {
//Ethernet.begin(mac, ip, subnet, gateway);
return;
}
int connectLoop = 0;
while(client.connected())
{
while(client.available())
{
char c = client.read();
Answer = Answer + c;
connectLoop = 0;
}
delay(1);
connectLoop++;
if(connectLoop > 5000)
{
client.stop();
return;
}
}
client.stop();
}
//This function disables eth and enable rc522 (and reverse)
void Switch(int i)
{
switch (i)
{
case 0:
digitalWrite(10, HIGH);
digitalWrite(2, LOW);
break;
case 1:
digitalWrite(2, HIGH);
digitalWrite(10, LOW);
break;
}
}
void AccessControl()
{
int AnswerLength = Answer.length();
pinMode(5, OUTPUT);
digitalWrite(5, HIGH);
if(Answer[AnswerLength-1] == 49)
{
digitalWrite(5, LOW);
delay(100);
digitalWrite(5, HIGH);
}
pinMode(5, INPUT);
pinMode(6, INPUT);
delay(1000);
}
void ReadCard()
{
byte len = 18;
MFRC522::StatusCode status;
byte MyBuffer[18];
status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 10, &key, &(mfrc522.uid));
status = mfrc522.MIFARE_Read(10, MyBuffer, &len);
int counter = 0;
//This line is check for turkish character
if(MyBuffer[0] == 221)
{
CardInfo = "X";
for (int i = 1; i < 16; i++)
{
if (MyBuffer[i] != 32)
{
CardInfo = CardInfo + (char)MyBuffer[i];
}
}
}
else
{
CardInfo = "";
for (int i = 0; i < 16; i++)
{
if (MyBuffer[i] != 32)
{
CardInfo = CardInfo + (char)MyBuffer[i];
}
}
}
mfrc522.PICC_HaltA();
mfrc522.PCD_StopCrypto1();
return;
}
void KeyCreate()
{
for (int i = 0; i < 6; i++)
{
key.keyByte[i] = Key[i];
}
}
void loop(){
Switch(0);
if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) {
ReadCard();
Switch(1);
sendGET();
AccessControl();
}
}
I expect it runs without freezing
Actual result is ethernet shield freezes after a while
I am using watchdog in some script . This functionality could reset auomatically your arduino if you dont reset the watchdog during the lapse.
you execute wdt_enable() in the setup() and wd_reset() at the beginning of the loop
time before watchdog firing argument of wdt_enable()
-------------------------------------------------------
15mS WDTO_15MS
30mS WDTO_30MS
60mS WDTO_60MS
120mS WDTO_120MS
250mS WDTO_250MS
500mS WDTO_500MS
1S WDTO_1S
2S WDTO_2S
4S WDTO_4S
8S WDTO_8S
example of use:
#include <avr/wdt.h>
void setup()
{
wdt_enable(WDTO_4S); // enable the watchdog
// will fire after 4s without reset
}
void loop(){
wdt_reset(); // resets the watchdog timer count
:
:
// if program hangs more than 4s, launch the reset of arduino
}

There are no GPS data after connecting to the server

I'm trying to get GPS data and send it to the server via socket.
I'm using Arduino Uno and GPS/GSM module A7 Ai-Thinker.
And for Internet I use Ethernet shield connected to Wi-Fi router.
But I got trouble when I joined getting GPS data and sending it.
Separately that functions work fine. How I start A7, there is a loop where I type AT commands and send it to A7. About socket, I want to set connection at start function and keep it alive all the time.
But the problem is that when I initialized A7 and set socket connection, I go to the loop function and after first iteration there are no data at A7.
If I try to set connection with server first, and start A7 after it, A7 doesn't react to AT commands.
How can I keep connection with my server and don't lost connection with A7?
Code:
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#include <SPI.h>
#include <Ethernet.h>
//-------------------------------------------------------
static const int RXPin = 10, TXPin = 11;
static const uint32_t GPSBaud = 4800;
const String START_GPS = "START_GPS";
TinyGPSPlus gps;
SoftwareSerial gps_serial(RXPin, TXPin);
//-------------------------------------------------------
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
char server[] = "192.168.0.100";
int port = 8090;
IPAddress ip(192, 168, 0, 177);
EthernetClient client;
//-------------------------------------------------------
void initGpsConnection();
void startGps();
void initSocketConnection();
void sendData();
void setup()
{
Serial.begin(9600);
Serial.println();
initSocketConnection();
initGpsConnection();
sendData();
}
void loop()
{
while (gps_serial.available() > 0) {
if (gps.encode(gps_serial.read())) {
displayInfo();
//delay(1000);
}
}
if (millis() > 120000 && gps.charsProcessed() < 10)
{
Serial.println(F("No GPS detected: check wiring."));
//while(true);
}
if (!client.connected()) {
Serial.println();
Serial.println("Socket connection has been lost.");
client.stop();
//while (true);
}
}
void displayInfo()
{
Serial.print(F("Location: "));
if (gps.location.isValid())
{
Serial.print(gps.location.lat(), 6);
Serial.print(F(","));
Serial.print(gps.location.lng(), 6);
}
else
{
Serial.print(F("INVALID"));
}
Serial.print(F(" Date/Time: "));
if (gps.date.isValid()) {
Serial.print(gps.date.month() + "/" gps.date.day() + "/" + gps.date.year();
} else {
Serial.print(F("INVALID"));
}
Serial.print(F(" "));
if (gps.time.isValid()) {
Serial.print(gps.time.hour() + ":" + gps.time.minute() + ":" + gps.time.second());
} else {
Serial.print(F("INVALID"));
}
Serial.println();
}
void initGpsConnection() {
Serial.println("In init gps");
gps_serial.begin(GPSBaud);
Serial.println("after gps begin");
delay(1000);
startGps();
Serial.println("GPS connection has been set");
}
void startGps() {
Serial.println("Enter at commands, after that enter `start_gps`");
String response = "";
while (true) {
if (gps_serial.available()) {
Serial.write(gps_serial.read());
}
if (Serial.available()) {
char c = Serial.read();
response += c;
if (response.indexOf(START_GPS) > 0)
break;
gps_serial.write(c);
}
}
}
void initSocketConnection() {
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
Ethernet.begin(mac, ip);
}
delay(1000);
Serial.println("connecting...");
if (client.connect(server, port)) {
Serial.println("Connection with server has been set");
} else {
Serial.println("Connection with server has been failed");
}
}
void sendData(){
client.print("TEst ard");
}
The problem was at A7 connection. It was connected via 10, 11 pins at Ethernet shield. But 10-13 pins are reserved by A7. It's just needed connect A7 vie 8, 9 or others pins.

Arduino returning wrong integer value

I have some code, that turns a LED on/off based on a value on a website (blank page containing a number. The number on the page indicate the number of times the LED should flash.
The problem is that the loop keep running.
I can fix the problem by setting the integer value manually (int c = 3).
Not sure what my problem is.
Maybe one of you can point me in the right direction.
Url: http://b2b.as/lan.php?pid=8855
Code:
#include <Ethernet.h>
#include <SPI.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 104 };
char server[] = "b2b.as";
void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
Serial.println(Ethernet.localIP());
Serial.println();
// Set digital pin as output
// 5V
pinMode(8, OUTPUT);
}
void loop()
{
//
Serial.print("\n-----\n");
// Connect to the server
Serial.print("connecting to URL ...");
// Start LAN connection
EthernetClient client;
if (client.connect(server, 80)) {
Serial.println("connected");
client.println("GET /lan.php?pid=8855");
client.println();
} else {
Serial.println("connection failed");
}
// Wait a moment for data to arrive
// Note: This is NOT a reliable way of doing this!
delay(1000);
if (client.available() > 0) {
char c = atoi(client.read());
Serial.print("page value (pick): ");
Serial.print(c, DEC);
Serial.print("\n");
for (int x = 1; x <= int(c); x++) {
Serial.print("picking: #");
Serial.println(x);
digitalWrite(8, HIGH);
Serial.println("8 HIGH ...");
delay(5000); // Add switch
digitalWrite(8, LOW);
Serial.println("8 LOW ...");
delay(1000);
}
Serial.print("end");
}
// Disconnect the client
if (client.connected()) {
//Serial.println();
Serial.print("disconnecting");
client.stop();
}
// Wait another 9s, which will give us a delay of roughly 10s
delay(9000);
}
I assume that the call to lan.php?pid=8855 will just return the value without any formatting, e.g., HTML, XML, JSON. Then your code basically converts the ASCII character 3 to an integer which gives you the integer value 33 (see ASCII Table). Therefore, your loop won't stop.
Solution
Just use the atoi function to convert it to an integer.
char c = atoi(client.read());
It seems that toInt() was the function I was looking for. It convert a string to integer and fixes the loop.
https://www.arduino.cc/en/Reference/StringToInt
Code has been updated and it seems to work:
#include <Ethernet.h>
#include <SPI.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 104 };
char server[] = "b2b.as";
void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
Serial.println(Ethernet.localIP());
Serial.println();
// Set digital pin as output
// 5V
pinMode(8, OUTPUT);
}
void loop()
{
//
Serial.print("\n-----\n");
// Connect to the server
Serial.print("connecting to URL ...");
// Start LAN connection
EthernetClient client;
if (client.connect(server, 80)) {
Serial.println("connected");
client.println("GET /lan.php?pid=8855");
client.println();
} else {
Serial.println("connection failed");
}
// Wait a moment for data to arrive
// Note: This is NOT a reliable way of doing this!
delay(1000);
if (client.available() > 0) {
String pickNum;
while (client.available()) {
char c = client.read(); // gets one byte from serial buffer
pickNum += c; // count
delay(2); // delay for buffer
}
Serial.print("page value (pick): ");
Serial.println(pickNum);
for (int x = 1; x <= pickNum.toInt(); x++) {
Serial.print("picking: #");
Serial.println(x);
digitalWrite(8, HIGH);
Serial.println("8 HIGH ...");
delay(1000); // Add switch
digitalWrite(8, LOW);
Serial.println("8 LOW ...");
delay(1000);
}
Serial.print("end");
}
// Disconnect the client
if (client.connected()) {
//Serial.println();
Serial.print("disconnecting");
client.stop();
}
// Wait another 9s, which will give us a delay of roughly 10s
delay(9000);
}

Hold button more than 5 seconds, do something. Arduino

I have a hobby project that sends a string "1" or a string "0" to my webserver. My arduino work as a client, and It works, but now I want to add another statement.
If the button is held down 5 sec or longer, send string "5" to my webserver. I do not know how I can get the button to count the seconds I have hold the button. Can you please help?
Here is the code:
#include <SPI.h>
#include <WiFi.h>
byte mac[] = { 0xDE, 0xFD, 0xBE, 0xEF, 0xFE, 0xED }; // MAC adresse
char ssid[] = "test";
char pass[] = "123456789";
IPAddress ip(192, 168, 0, 143); // Klient IP
IPAddress server(192,168,0,100); // Server IP
int port = 2056;
boolean btnpressed = false;
int status = WL_IDLE_STATUS;
WiFiClient client;
unsigned long lastConnectionTime = 0;
boolean lastConnected = false;
const unsigned long postingInterval = 1000;
void setup() {
attachInterrupt(0, AlarmPressed, RISING);
// Opne serial port
Serial.begin(9600);
while (!Serial) {
;
}
while ( status != WL_CONNECTED) {
Serial.print(" SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
delay(1000); //
printWifiStatus();
Serial.println("Connecting to server");
}
}
void loop() {
if (client.available()) {
char c = client.read();
Serial.print(c);
client.stop();
}
if (!client.connected() && lastConnected) {
Serial.println("Disconnecting.");
Serial.println();
client.stop();
}
if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
SendData();
}
lastConnected = client.connected();
} // Slutten paa loop
void AlarmPressed() {
btnpressed = true;
}
void SendData() {
// if there's a successful connection:
if (client.connect(server, port)) {
Serial.println("Connecting...");
// Send data til server:
if (btnpressed == false){
client.write("0");
Serial.print("No Alarm");
Serial.println();
btnpressed = false;
}
else {
client.write("1");
Serial.print("Alarm !");
Serial.println();
}
// note the time that the connection was made:
lastConnectionTime = millis();
}
else {
// if you couldn't make a connection:
Serial.println("Connection failed");
Serial.println("Disconnecting.");
Serial.println();
client.stop();
}
}
void printWifiStatus() {
Serial.print(" SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("Signalstyrke til forbindelsen (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}

Resources