Arduino WiFi Shield

This code is a robust solution to connecting to a web server with your Arduino WiFi shield.   It uses two LEDs (red and green) to indicate the status of the shield at all times.   If the WiFi connection is lost, it will revert to a loop in sub ConnectToWiFi() that waits until the WiFi connection is re-established, and then begin connecting to the server again.   Note also the undocumented information included and the subroutine printWiFiStatus() that provides useful diagnostic information.  

Important note - must use with Arduino IDE 1.5.2 and library.   The Arduino 1.0.6 IDE will not work correctly with the WiFi shield (even with the 1.5.2 WiFi library).   It is possible this problem may be resolved with a firmware update on the WiFi (unknown - I didn't want to get into performing the fw update). 


/*
  
 Repeating WiFi Web client
  
 This sketch connects to a a web server and makes a request
 using an Arduino Wifi shield.  
 
 I have added verification of connection to WiFi and the server
 with indication of status via red and green LEDs.  If WiFi is lost, the
 code will continue to attempt to connect to the WiFi and recover if a
 connection is successful.  
 
 WARNING:  Must use Arduino 1.5.2 IDE & library.  
           The Arduino 1.0.6 IDE will not work correctly with the WiFi shield.
 
 Shield Model WIFI R3
   90-A2-DA-0D-C8-BB
   SPI bus (through the ICSP header), DIO 11,12,13
   pin 10 is used to select the HDG204
   DIO 7 is used for handshake between WiFi shield & Arduino
   LED  L9 (yellow) : this is tied to DIO 9 
 
 micro-SD card slot
   SS on DIO4
   
 ** Only the WiFi shield or SD card may use the SPI bus
    at any moment in time. **

WiFi MAC address: (your MAC address)
  
Resources
    DIO13  SPI
    DIO12  SPI
    DIO11  SPI
    DIO10  SPI  SS
    DIO9  LED L9 (yellow)
    DIO7  WiFi - Arduino handshake
    DIO4  micro-SD card slot
    DIO6  Red LED
    A0    Green LED
    
LED status & meaning:
    Red off, green off                            WiFi shield not connected
    Red on, green off, green blinks every 10 sec  No connection to WiFi (or in process)
    Green on                                      WiFi shield connected. Connected to WiFi network.
    Red blink every 10 sec, green on              Server connection failed; WiFi.status() == WL_CONNECTED
    Red off, green blinking                       Connecting to server
  
*/


/////////////////////////////////////////////////////////////////
//  WiFi shield

#include "SPI.h"
#include "WiFi.h"

// Connect to WPA/WPA2 network 
char ssid[] = "your-ssid";     //  your network SSID (name) 
char pass[] = "your-password";  // your network password

int WiFiStatus = WL_IDLE_STATUS;

// Initialize the Wifi client library
WiFiClient client;

// server address:
char server[] = "www.google.com";

unsigned long lastConnectionTime = 0;         // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 10000;  // delay between updates, in milliseconds

//
// max url length is 2048 chars including the path
/////////////////////////////////////////////////////////////////

//  Status LEDs
const byte pinGreenLED = A0;
const byte pinRedLED = 6;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600); 
  delay(5000);
  Serial.println("Arduino WiFi shield");

  pinMode(pinRedLED, OUTPUT);
  delay(1);
  pinMode(pinGreenLED, OUTPUT);
  delay(1);

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present"); 
    digitalWrite(pinRedLED, LOW);
    delay(1);
    digitalWrite(pinGreenLED, LOW);
    delay(1);
    while(true) {
    }
  } 

  // connect to Wifi network:
  ConnectToWiFi();
  
  Serial.println("Setup complete");
}

void loop() {   
  
  // if millis() or timer wraps around, we'll just reset it
  if (lastConnectionTime > millis())  lastConnectionTime = millis();
  
  if (millis() - lastConnectionTime > postingInterval) { 
    lastConnectionTime = millis(); // reset the timer
    httpRequest();
  }
   
}

void httpRequest() {
  // Make a HTTP connection to the server.
  if (client.connect(server, 80)) {
    Serial.print("connecting to ");
    Serial.print(server);
    Serial.println("..");
    blinkLED(pinGreenLED);
    
    // Do your GET or PUT here..
    
    lastConnectionTime = millis();
    // after all done flush & stop in order to avoid consumption of all sockets.
    client.flush();
    client.stop();
  } else {
    Serial.print("Server connection to ");
    Serial.print(server);
    Serial.println(" failed");
    printWiFiStatus();
    blinkLED(pinRedLED);
    // flush & stop in order to avoid consumption of all sockets.
    client.flush();
    client.stop();
    //  Verify the WiFi is still connected..
    WiFiStatus = WiFi.status();
    if (WiFiStatus != WL_CONNECTED) {
      // WiFi NOT connected.  Try to re-connect.
      ConnectToWiFi();
    }
  }  
}


void ConnectToWiFi() {
  digitalWrite(pinGreenLED, LOW);
  digitalWrite(pinRedLED, HIGH);
  while (WiFiStatus != WL_CONNECTED) { 
    Serial.print("Attempting to connect to Wi-Fi SSID: ");
    Serial.println(ssid);
    
    // See printWiFiStatus() for possible values of WiFiStatus
    
    // Connect to WPA/WPA2 network 
    WiFiStatus = WiFi.begin(ssid, pass);
    
    // Connect to WEP network 
    //WiFiStatus = WiFi.begin(ssid, keyIndex, key);
        
    blinkLED(pinGreenLED);
    // wait 10 seconds for connection:
    delay(10000);
  }   
  digitalWrite(pinGreenLED, HIGH);
  digitalWrite(pinRedLED, LOW);
}

void printWiFiStatus() {
  // WiFi.status()
  //WL_NO_SHIELD = 255,
  //WL_IDLE_STATUS = 0
  //WL_NO_SSID_AVAIL = 1
  //WL_SCAN_COMPLETED = 2
  //WL_CONNECTED = 3
  //WL_CONNECT_FAILED = 4
  //WL_CONNECTION_LOST = 5
  //WL_DISCONNECTED = 6
  switch (WiFi.status()) {
      case 255:
        Serial.println("WiFi status = WL_NO_SHIELD");
        break;
      case 0:
        Serial.println("WiFi status = WL_IDLE_STATUS");
        break;
      case 1:
        Serial.println("WiFi status = WL_NO_SHIELD");
        break;
      case 2:
        Serial.println("WiFi status = WL_NO_SSID_AVAIL");
        break;
      case 3:
        digitalWrite(pinGreenLED, HIGH); 
        Serial.println("WiFi status = WL_CONNECTED");
        Serial.print("  Wi-Fi SSID: ");
        Serial.println(WiFi.SSID());
        Serial.print("  IP Address: ");
        Serial.println(WiFi.localIP());
        Serial.print("  signal strength (RSSI):");
        Serial.print(WiFi.RSSI());
        Serial.println(" dBm");
        break;
      case 4:
        Serial.println("WiFi status = WL_CONNECT_FAILED");
        break;
      case 5:
        Serial.println("WiFi status = WL_CONNECTION_LOST");
        break;
      case 6:
        Serial.println("WiFi status = WL_DISCONNECTED");
        break;
  }
  Serial.println("  ");
  
  if (WiFi.status() != WL_CONNECTED) {
    blinkLED(pinRedLED);
  }
}

void blinkLED(byte ledPIN){
  //  consumes 300 ms.
  for(int i = 5; i>0; i--){
    digitalWrite(ledPIN, HIGH);
    delay(30);
    digitalWrite(ledPIN, LOW);
    delay(30);
  }    
}

 


Do you need help developing or customizing a IoT product for your needs?   Send me an email requesting a free one hour phone / web share consultation.  

 

The information presented on this website is for the author's use only.   Use of this information by anyone other than the author is offered as guidelines and non-professional advice only.   No liability is assumed by the author or this web site.