I am using a fairly simple code using Arduino UNO and Ethernet Shield W5100. The task is to connect the shield with the server and if it gets connected read the reading from the sensor (Rotary Encoder in my case), but after a few seconds approximately 20~30 sec the client gets disconnected. My Code is below, so Help is requested.
My Code
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //Setting MAC Address
IPAddress server(192,168,8,118); //Setting IP Address of the Server i.e this machine
IPAddress ip(192,168,8,117); // Setting IP address of the LAN Card
EthernetClient client; //Setting the Client Object
// Arduino Pin defiinations
#define encoder0PinA 2
#define encoder0PinB 3
#define encoder0Btn 4
//Global Variable definations
int encoder0Pos = 0;
const float pi = 3.14;
const float R = 3.25;
const int N = 40;
float distance = 0;
//Setting up One Time Procedures
void setup() {
Serial.begin(9600);
Ethernet.begin(mac, ip);
delay(1000);
pinMode(encoder0PinA, INPUT_PULLUP);
pinMode(encoder0PinB, INPUT_PULLUP);
pinMode(encoder0Btn, INPUT_PULLUP);
//Setting up Server Conection with Arduino Ehternet Shield
if (client.connect(server,8888)) {
Serial.println("connected");
}else{
Serial.println("Not connected");
}
attachInterrupt(0, doEncoder, CHANGE);
}
void loop() {
}
void doEncoder()
{
if (client.connected())
{
if (digitalRead(encoder0PinA) == digitalRead(encoder0PinB))
{
encoder0Pos++;
}
else
{
encoder0Pos--;
}
/* The rotary encoder measures the number of the rotation but we have to convert the rotation into travelled distance.
* Travelled distance depends on the diameter of the wheel. Rotary encoder moves 40 steps in one complete rotation (360 degree).
* Steps per rotation depends on the rotary encoder which can be changed from 8 to 48, but in our case it is 40.
* Suppose N is the steps per rotation and R is the radius of wheel. therefore,
* Travelled distance in one Rotation is = 2xπxR
* Travelled distance in one Step is = 2xπxR/N
*/
distance = ((2*pi*R)/N) * encoder0Pos;
Serial.print( distance);
Serial.println("cm ");
}
else{
Serial.println("Client Disconnected...");
}
}
Thanks
loop()
... only updateencoder0Pos
and set a flag inside ISR ... run code insideloop()
if flag is set, and then clear the flag