Saturday, June 21, 2014

Cheap Ethernet connection to Arduino using ENC28J60 module

      While working on Ethernet projects with Arduino the basic hardware we require along with Arduino is the Ethernet Shield. But the problem is that in a constrained budget the buying one Ethernet Shield is not possible which leads to other options and a good one is ENC28J60 Ethernet chip by Microchip.This is not as smart as the Wiznet W5100 chip based Ethernet shields but are quite useful as those.This post i am going to write all about interfacing the ENC28J60 module to Arduino UNO as well as Arduino mini Pro.I have used EtherCard library for the coding to interact with the module.
     
          Below is the wiring diagram for Arduino UNO.

    
  Code:
#include <EtherCard.h>
#define PATH    "temp.php"

byte mymac[] = { 
  0x74,0x69,0x69,0x2D,0x30,0x31 };
uint8_t ip[] = { 
  192, 168, 0, 8 };          // The fallback board address.
uint8_t dns[] = { 
  192, 168, 0, 1 };        // The DNS server address.
uint8_t gateway[] = { 
  192, 168, 0, 1 };    // The gateway router address.
uint8_t subnet[] = { 
  255, 255, 255, 0 };

char website[] PROGMEM = "192.168.0.10";
static byte session;
byte Ethernet::buffer[800];
uint32_t timer;
Stash stash;
float temp_R=0;
int tempPinR = A0;
String cont="";
int led = 9;
int sw1 = A1;
int sw2 = A2;
int sw3 = A3;
String sReply="";

void setup () {
  Serial.begin(57600);
  if (ether.begin(sizeof Ethernet::buffer, mymac,10) == 0)
    Serial.println( "Failed to access Ethernet controller");//10 is the CS pin of EC28J60 connected to change if required.

  ether.staticSetup(ip, gateway, dns);
  ether.parseIp(ether.hisip,"192.168.0.10");//Raspberry Pi IP Change it if required
  ether.printIp("SRV: ", ether.hisip);
  delay(5000);
  pinMode(9, OUTPUT);
  pinMode(led, OUTPUT);  
  analogReference(INTERNAL);
}

void loop () {
  word pos=ether.packetLoop(ether.packetReceive());

  if (millis() > timer) {

    byte sd = stash.create();
    stash.print("data=hello");//change value of data to send different data

    timer = millis() + 10000;

    Serial.println("in");
    stash.save();

    Stash::prepare(PSTR("POST http://192.168.0.10/API/index.php HTTP/1.0" "\r\n"
      "Host: 192.168.0.10 \r\n"
      "Content-Length: $D" "\r\n"
      "Content-Type: application/x-www-form-urlencoded \r\n"
      "\r\n"
      "$H"),
    stash.size(), sd);//change IP path acccordingly

    session= ether.tcpSend();

  }
  const char* reply=ether.tcpReply(session);
  if(reply!=0)
  {
    int i;
    for(i=13;i<strlen(reply);i++)
    {
      sReply=sReply+reply[i];
    }
   
    Serial.println(sReply);
    sReply=" ";
  }
}