Tag Archives: Arduino

Unsigned Int, Mathematical operations and pitfalls in Arduino or C

Let’s consider the below code:


unsigned long startTime = 1940, stopTime = 0;

if( (stopTime - startTime) > 5000ul)
{
Serial.println("Hello World!");
}

Will this say Hello World?

Yes, it will. If this sounds new or surprising to you, please continue reading below.

Note the variables have been defined as unsigned long. So the result of mathematical operations will also be in unsigned value. Hence though the result of the operation apparently looks to be -1940 but in practise it will be 4294965356

And thus the comparison in the if() will evaluate to true.

Websites for buying electronics parts in India

Amazon.in – exorbitant prices. Often 3 or 4 times. There are sellers who will send wrong products. Amazon will initiate a replacement which has little chance of happening if the price of item is low.

Calcuttaelectronics.com — very reliable, parts quality good. But since 2020 (after the first lockdown) their variety and stock has gone down and as of date of writing many parts are “out of stock” for many weeks. Good packaging. Support was a little disappointing.

Electroncomponents.com — has a good collection and very cheap. But the price and variety made me a bit curious (and cautious), so checked the internet and found they had a very bad reputation in the recent past. But still I ordered and got my items in time.
Parts quality mixed – some are of good quality some are cheap ones. Packaging okay. Delivery time is good.

Iotwebplanet.com — parts are good, delivery times is good, variety is good, but orders may get cancelled silently. Has COD facility. Good packaging.

Robomart.com — They are reliable. Collection is okay sort of.  Parts are often good but not always or some parts can be quite cheap quality. Packaging good.

Tanotis.com — this is in a different league from the rest including Amazon. Most parts which are not available in any other websites can be found here. Quality is very good. But the delivery time is long and sometimes order gets cancelled (but they do inform and give refund). Though costly but is still reasonable than other sites in that league. Very good packaging.
Continue reading Websites for buying electronics parts in India

Using a 1.44″ Color LCD with Arduino as a display

Recently purchased a cheap color LCD from Ebay (http://www.ebay.com/itm/1-44-Red-Serial-128X128-SPI-Color-TFT-LCD-Module-Display-Replace-Nokia-5110-LCD-/310876068105?hash=item4861a85909:g:9LoAAOSwpzdWqdY~). They are really good for displaying anything (from an Arduino perspective) in color.

Though the are cheap and nice, but finding the proper library for them can be a pain. It would be wise to check the details of the LCD and availability of it’s library first before buying.

What I found so far is there are mainly two types of LCDs that are cheaply available on Ebay. One based on the ILI9163 chipset and another based on the ST7735 chipset.

Arduino IDE from version 1.0.5 onwards comes with a LCD library, which is based on the ST7735 chipset and an advancement of the Adafruit Libraries. Please see this article for more details.

Using the LCD is not much complicated but only thing to remember is there is a huge lot of confusion with which one supports what voltage and I/O levels. So with mine I started with 3.3v and things are working fine.

LED         Connect to +ve supply through a resistor
SCK         13 (fixed as per library)
SDA         11 (fixed as per library)
A0/DC        7 (can be any)
RESET        4   (can be any)
CS           5 (can be any)
GND         GND   
VCC         3.3v

There is one limitation to all libraries (I tested) at the moment, updating the texts on the display. The only way to clear the LCD is by calling the background function and painting the LCD with a color. This gives flicker, as a full screen text takes a bit time to get written fully. Yet to find a solution to this. In the below code only the area that needs to be updated is being cleared.

#include <SFE_BMP180.h> //from sparkfun 
#include <Wire.h>
#include <SoftwareSerial.h>

//#include <Adafruit_GFX.h>
#include <TFT.h> //comes with Arduino IDE 1.0.5 onwards
#include <SPI.h>

// Define pins for ILI9163 SPI myDisplay
#define __CS 5
#define __DC 7 // Labeled as A0 in some modules
#define __RST 6
// Connect SDA to Arduino pin 11 (MOSI), and SCK to 13 (SCK)

char printBuffer[32];

// Color definitions
#define BLACK 0,0,0
#define BLUE 0,0,255
#define RED 255,0,0
#define GREEN 0,255,0
#define CYAN 0,255,255
#define MAGENTA 255,0,255
#define YELLOW 255,255,0 
#define WHITE 255,255,255
#define TRANSPARENT -1
TFT myDisplay = TFT(__CS, __DC, __RST);


//#include <dht11.h>
//dht11 DHT11;


#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
DHT dht(DHTPIN, DHTTYPE);


#define _SS_MAX_RX_BUFF 128 // RX buffer size //BEFORE WAS 64


SoftwareSerial esp8266(8,7); //RX,TX

String inputBuffer = "";
String slength;
String sTemp;
boolean stringComplete = false;
int inputBufferIndex;

String data1 = ""; 
String data2 = "";
String data3 = "";
String data5 = "";

SFE_BMP180 pressure;

char status;
double T,P,temp,paH,paM, tempHighest = 0.00, tempLowest = 100.00;

float humHighest = 0.00, humTemp = 0.00, humMin = 100.00;

float lmHighest = 0.00, lmTemp = 0.00, lmMin = 100.00;

unsigned long startTimeDataCapture = 0;
unsigned long lastCapture = 0;

void setup() {
  // put your setup code here, to run once:  
  inputBuffer.reserve(256); //to be optimized
  
  pressure.begin();

  dht.begin();

  pinMode(A0,INPUT);
  analogReference(INTERNAL);

 myDisplay.begin();
 myDisplay.setRotation(4);
 myDisplay.setTextSize(1);
 //myDisplay.setBitrate(24000000);
 //myDisplay.clearScreen();
 myDisplay.background(0,0,0);

 myDisplay.stroke(CYAN);
 myDisplay.setCursor(5,40);
 myDisplay.print("Cur :");
 myDisplay.setCursor(5,50);
 myDisplay.print("Min :");
 myDisplay.setCursor(5,60);
 myDisplay.print("Max :");

 myDisplay.stroke(YELLOW);
 myDisplay.setCursor(5,75);
 myDisplay.print("Hum :");
 myDisplay.setCursor(5,85);
 myDisplay.print("Min :");
 myDisplay.setCursor(5,95);
 myDisplay.print("Max :");

 myDisplay.stroke(WHITE); 
 myDisplay.setCursor(5,110);
 myDisplay.print("PAH :");
 myDisplay.setCursor(5,120);
 myDisplay.print("PAM :");

 myDisplay.stroke(GREEN); 
 myDisplay.setCursor(5,135);
 myDisplay.print("L_C :");
 myDisplay.setCursor(5,145);
 myDisplay.print("L_M :");
  
  Serial.begin(9600);

  esp8266.begin(115200);
  esp8266.println("AT");  delay(100);
  esp8266.println("AT+UART_CUR=4800,8,1,0,0"); esp8266.flush(); delay(100);
  while(esp8266.available())
  {
      //Serial.write(esp8266.read());
      esp8266.read();
      delay(80);
  }
  esp8266.end();

  esp8266.begin(4800);
  esp8266.println("AT"); delay(100);
  
  esp8266.println("AT+CIPMUX=1"); delay(100);
  esp8266.println("AT+CWMODE=1"); delay(100);
  //esp8266.println("AT+CWJAP="xxxxxxxxxxxxx","xxxxxxxxxxxxx""); esp8266.flush(); delay(1000);  
  //esp8266.println("AT+CWJAP="xxxxxxxxxxxxxxxx","xxxxxxxxxxxxxx""); esp8266.flush();  delay(1000);  
  
  while(esp8266.available())
  {
      //Serial.write(esp8266.read());
      esp8266.read();
      delay(80);
  }
    
  delay(1000);
}



void loop() {

  //myDisplay.setCursor(0,40);
  
  while(esp8266.available())
  {
      //Serial.write(esp8266.read());
      esp8266.read();
      delay(10);
  }

  inputBuffer = "";
  stringComplete = false;
  
  status = pressure.startTemperature();
  if (status != 0)
  {
    // Wait for the measurement to complete:
    delay(status);

    // Retrieve the completed temperature measurement:
    // Note that the measurement is stored in the variable T.
    // Function returns 1 if successful, 0 if failure.

    status = pressure.getTemperature(T);
    if (status != 0)
    {
      // Print out the measurement:
      temp = T;
            
      // Start a pressure measurement:
      // The parameter is the oversampling setting, from 0 to 3 (highest res, longest wait).
      // If request is successful, the number of ms to wait is returned.
      // If request is unsuccessful, 0 is returned.

      status = pressure.startPressure(3);
      if (status != 0)
      {
        // Wait for the measurement to complete:
        delay(status);

        // Retrieve the completed pressure measurement:
        // Note that the measurement is stored in the variable P.
        // Note also that the function requires the previous temperature measurement (T).
        // (If temperature is stable, you can do one temperature measurement for a number of pressure measurements.)
        // Function returns 1 if successful, 0 if failure.

        status = pressure.getPressure(P,T);
        if (status != 0)
        {
          // Print out the measurement:
          paM = P;
          paH = P*0.0295333727;
        }
        else
        {
          paM = -1;
          paH = -1;
        }
      }
      else
      {
          paM = -1;
          paH = -1;
      }
    }
    else
    {
      temp = -1;
    }
  }
  else
  {
    temp = -1;
  }

  if(tempLowest > temp)
    tempLowest = temp;

  if(tempHighest < temp)
    tempHighest = temp;

  myDisplay.fill(BLACK);
  myDisplay.stroke(BLACK);
  myDisplay.rect(45,40,75,10);
  myDisplay.setCursor(45,40);
  myDisplay.stroke(CYAN);
  myDisplay.println(String(temp) + (char)248 +"C");
  //delay(100);
  myDisplay.fill(BLACK);
  myDisplay.stroke(BLACK);
  myDisplay.rect(45,50,75,10);
  myDisplay.setCursor(45,50);
  myDisplay.stroke(CYAN);
  myDisplay.println(String(tempLowest) + (char)248 +"C");
  //delay(100);
  myDisplay.fill(BLACK);
  myDisplay.stroke(BLACK);
  myDisplay.rect(45,60,75,10);
  myDisplay.setCursor(45,60);
  myDisplay.stroke(CYAN);
  myDisplay.println(String(tempHighest) + (char)248 +"C");

  delay(500);

  humTemp = dht.readHumidity();
  if(humHighest < humTemp)
    humHighest = humTemp;
  if(humMin > humTemp)
    humMin = humTemp;  
  sTemp = String(humTemp) + "%  " + dht.readTemperature();
  myDisplay.fill(BLACK);
  myDisplay.stroke(BLACK);
  myDisplay.rect(45,75,80,10);
  myDisplay.setCursor(45,75);
  myDisplay.stroke(YELLOW);
  myDisplay.println(sTemp);
  myDisplay.fill(BLACK);
  myDisplay.stroke(BLACK);
  myDisplay.rect(45,85,80,10);
  myDisplay.stroke(YELLOW);
  myDisplay.setCursor(45,85);
  myDisplay.println(humMin);
  myDisplay.fill(BLACK);
  myDisplay.stroke(BLACK);
  myDisplay.rect(45,95,80,10);
  myDisplay.stroke(YELLOW);
  myDisplay.setCursor(45,95);
  myDisplay.println(humHighest);

  delay(500);

  myDisplay.fill(BLACK);
  myDisplay.stroke(BLACK);
  myDisplay.rect(45,110,75,10);
  myDisplay.stroke(WHITE);
  myDisplay.setCursor(45,110);
  myDisplay.println(String(paH));
  //delay(500);
  myDisplay.fill(BLACK);
  myDisplay.stroke(BLACK);
  myDisplay.rect(45,120,75,10);
  myDisplay.stroke(WHITE);
  myDisplay.setCursor(45,120);
  myDisplay.println(String(paM));

  
  lmTemp=analogRead(A0); // reads the sensor output
  lmTemp=lmTemp*0.10546875;
  // converts the sensor reading to temperature
  if(lmHighest < lmTemp)
    lmHighest = lmTemp;
  if(lmMin > lmTemp)
    lmMin = lmTemp;  
  myDisplay.fill(BLACK);
  myDisplay.stroke(BLACK);
  myDisplay.rect(45,135,75,10);
  myDisplay.stroke(GREEN);
  myDisplay.setCursor(45,135);
  myDisplay.println(String(lmTemp));
  //delay(500);
  myDisplay.fill(BLACK);
  myDisplay.stroke(BLACK);
  myDisplay.rect(45,145,75,10);
  myDisplay.stroke(GREEN);
  myDisplay.setCursor(45,145);
  myDisplay.println(String(lmMin));
     
 
  if(millis() - lastCapture >  300000)
  {
    lastCapture = millis();
    
    esp8266.println("AT+CWJAP="xxxxxxxxxxxxxxxx","xxxxxxxxxxxxxxxxxx""); esp8266.flush();  delay(5000);
    
    data1 = "GET /interface_1.php?action=1&temp="+String(temp)+"&paM="+String(paM)+"&paH="+String(paH)+" HTTP/1.1";
    data2 = "Host: 128.199.183.127";
    data3 = "User-Agent: IOT";
    data5 = "Connection: close";
    
    Serial.println(data1);
    //Serial.println(data1.length()+data2.length()+data3.length()+data4.length()+data5.length());
       
    esp8266.println("AT+CIPSTART=4,"TCP","xxx.xxx.xxx.xxx",nn");  delay(1000); 
    while(esp8266.available())
    {
        //Serial.write(esp8266.read());
        esp8266.read();
        delay(10);
    }
  
    slength = String(data1.length()+data2.length()+data3.length()+data5.length()+12);
    esp8266.println("AT+CIPSEND=4,"+slength);
    delay(1000);
    while(esp8266.available())
    {
        //Serial.write(esp8266.read());
        esp8266.read();
        delay(10);
    }
    
    // put your main code here, to run repeatedly:
    esp8266.println(data1); delay(1);
    esp8266.println(data2); delay(1);
    esp8266.println(data3); delay(1);
    esp8266.println(data5); delay(1);
    esp8266.println();  delay(1); esp8266.flush();
  
    while(1)
    {
      if(esp8266.available())
        inputBuffer += (char)esp8266.read();
        
      if(inputBuffer.indexOf("CLOSED")> 0 || millis() - startTimeDataCapture > 10000) //don't wait more than 20 seconds
      {
        stringComplete = true;
        Serial.println(inputBuffer);
        delay(1);
        break;
      }
    }
    esp8266.println("AT+CIPCLOSE=4");
    delay(10);
    esp8266.println("AT+CWQAP");
  }
  
  delay(1000);
  
  
}

An Arduino Pro Mini running at 3.3v will be suitable for this. There will be no need of the logic level converters.

Voltmeter using Arduino

Using precisely calculated resistors and a stable power supply, Arduino can be used to work as a voltmeter.

Below is the schematic

Arduino Voltmeter

Though I used an Arduino Uno, but any Arduino can be used. (If the 3.3v versions are used then calculations will have to be done accordingly).

The resister for voltage divider has been chosen such that at 20 volts (measurement) supply the voltage at Arduino input pin is 5.0v. Greater than 5v at the input pin can damage the pin.

Here is the code

#define READINGS 5

int sensorPin = A0;
short int readingsTaken = 0;
float voltage = 0.0, readingTotal = 0.0;

void setup() {
  // put your setup code here, to run once:
  pinMode(sensorPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  readingTotal = 0.0;
  readingsTaken = 0;
  
  // we will take 5 readings at 1 sec interval and then do an average of that
  while(readingsTaken < READINGS) 
  {
    readingTotal += analogRead(sensorPin);
    readingsTaken++;
    delay(1000); //at every 1 second interval
  }

  voltage = (readingTotal/READINGS) * (5.0/1024); // the value in voltage at this point is what Arduino read based on input from voltage divider network. Need to calculate the original // 5.0 - is the ref voltage used by ADC. It is the default configuration and uses the voltage supplied to the board. To change the ref voltage/source please see this article

  voltage = (20/4.992) * voltage; //unitary method to calculate the actual voltage that is read. When voltage read is 4.922 (or 5.0v), the input is 20v. With the resistor divider at the input, the voltage at I/O will be 4.992

  Serial.println(voltage);
}

This is a simple and basic way. Where the precision will not be very good. Because the reference voltage being used by the ADC, which is actually the supply voltage can vary depending on the load to the circuit. To make it more precise an external reference voltage can be supplied to the Arduino. How to use an external reference voltage and the use of the AREF pin has been described in this article

Arduino – Communicate With Server – Part 2 – Server Code for Saving Data

This article shows the server side code for a server which is gathering or sending data by polling method to an Arduino device.

This method or code is putting less load on the server (compared to socket) but data transmission is slower than socket.

<?php
date_default_timezone_set("Asia/Kolkata");
$conn = mysql_connect("localhost","root","**********");
if(!$conn)
{
    echo "Error: failed to connect DB Server";
    die();
}

if(!mysql_select_db("database_name",$conn))
{
    echo "Error: failed to connect DB";
    die();
}
$action = intval(strip_tags($_GET['action']));

if($action == 1)
{
    $temp = floatval(strip_tags($_GET['temp']));
    $paH = floatval(strip_tags($_GET['paH']));
    $paM = floatval(strip_tags($_GET['paM']));
    
    mysql_query("insert into weather (temperature, paH, paM, time) values(".$temp.",".$paH.",".$paM.",".time().")");
    //mysql_query("update led_status set led_1 = ".$led_1.", led_2 = ".$led_2);
    
    echo "success";
}
else
    if($action == 2)
    {
        $output = "";
        $result = mysql_query("select * from led_status");
        $rows = mysql_fetch_array($result);
        if($rows['led_1'] == 1)
        {
           $output = "led_1=1|";    
        }
        else
        {
           $output = "led_1=0|";    
        }
        
        if($rows['led_2'] == 1)
        {
           $output .= "led_2=1";    
        }
        else
        {
           $output .= "led_2=0";    
        }
        echo $output;
    }
    mysql_close($conn);
?>

 

The else part ( if($action == 2) ) output from the above will be

HTTP/1.1 200 OK
Date: Sun, 14 Feb 2016 20:33:16 GMT
Server: Apache/2.4.7 (Ubuntu)
X-Powered-By: PHP/5.5.9-1ubuntu4.14
Content-Length: 15
Connection: close
Content-Type: text/html

led_1=0|led_2=1

Arduino – Communicate With Server – Part 1 – Arduino code

The below code send some data (temperature and pressure here) to a server and reads back some data from server. The send part works every 5 minutes and the read part works every 5 seconds. This code works by polling method.

All delays might have room for optimization

#include <SFE_BMP180.h> //from sparkfun 
#include <Wire.h>
#include <SoftwareSerial.h>

#define _SS_MAX_RX_BUFF 512 // RX buffer size //Default is 64

SoftwareSerial esp8266(2,3);

String inputBuffer = "";
boolean stringComplete = false;
int inputBufferIndex;

int led1Pin = 9;
int led2Pin = 10;

byte led1Status, led2Status;

String data1 = ""; 
String data2 = "";
String data3 = "";
String data4 = "";
String data5 = "";

unsigned long startTimeDataCapture = 0;
unsigned long lastDataSent = 0;

SFE_BMP180 pressure;

char status;
double T,P,temp,paH,paM;


void setup() {
  // put your setup code here, to run once:
  
  inputBuffer.reserve(1024); //to be optimized
  
  pinMode(led1Pin, OUTPUT);
  pinMode(led2Pin, OUTPUT);
  
  pressure.begin();
  
  
  //Serial.begin(19200);

  esp8266.begin(9600);
  esp8266.println("AT");  delay(100);
  esp8266.println("AT+UART_CUR=4800,8,1,0,0"); //set the Baud rate 
  esp8266.flush(); delay(100);
  while(esp8266.available())
  {
      //Serial.write(esp8266.read());
      esp8266.read();  //clear the buffer
      delay(80);
  }
  esp8266.end();

  esp8266.begin(4800);
  esp8266.println("AT"); delay(100);
  
  esp8266.println("AT+CIPMUX=1"); delay(100);
  esp8266.println("AT+CWMODE=1"); delay(100); 
  esp8266.println("AT+CWJAP="TP-LINK_POCKET_3020_304764","password""); esp8266.flush();  delay(1000);  
  
  while(esp8266.available())
  {
      //Serial.write(esp8266.read());
      esp8266.read(); //clear the buffer
      delay(80);
  }
    
  delay(5000);
}


void loop() {

  while(esp8266.available())
  {
      //Serial.write(esp8266.read());
      esp8266.read();
      delay(10);
  }

  inputBuffer = "";
  stringComplete = false;
  
  /***** Read the LED status for sending to server  -- will be implemented later */
  if(digitalRead(led1Pin) == HIGH)
  {
    led1Status = 1;
  }
  else
  {
    led1Status = 0;
  }

  if(digitalRead(led2Pin) == HIGH)
  {
    led2Status = 1;
  }
  else
  {
    led2Status = 0;
  }
  
  status = pressure.startTemperature();
  if (status != 0)
  {
    // Wait for the measurement to complete:
    delay(status);

    // Retrieve the completed temperature measurement:
    // Note that the measurement is stored in the variable T.
    // Function returns 1 if successful, 0 if failure.

    status = pressure.getTemperature(T);
    if (status != 0)
    {
      temp = T;

      
      // Start a pressure measurement
      status = pressure.startPressure(3);
      if (status != 0)
      {
        // Wait for the measurement to complete:
        delay(status);


        // Note also that the function requires the previous temperature measurement (T).
        // (If temperature is stable, you can do one temperature measurement for a number of pressure measurements.)
        // Function returns 1 if successful, 0 if failure.

        status = pressure.getPressure(P,T);
        if (status != 0)
        {
          paM = P;
          paH = P*0.0295333727;
        }
        else
        {
          paM = -1;
          paH = -1;
        }
      }
      else
      {
          paM = -1;
          paH = -1;
      }
    }
    else
    {
      temp = -1;
    }
  }
  else
  {
    temp = -1;
  }

   
   //send the data to server
  
  if(millis() - lastDataSent > 300000) //send data every 5 minutes 
  {
      lastDataSent = millis();
      data1 = "GET /webservice.php?action=1&temp="+String(temp)+"&paM="+String(paM)+"&paH="+String(paH)+" HTTP/1.1";
  }
  else
  {
      data1 = "GET /webservice.php?action=2 HTTP/1.1";
  }
  //Serial.println(data1);
  data2 = "Host: xxx.xxx.xxx.xxx";
  data3 = "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0";
  data4 = "Accept: text/html";
  data5 = "Connection: close";
  //Serial.println(data1.length()+data2.length()+data3.length()+data4.length()+data5.length());
  
  esp8266.println("AT+CIPSTART=4,"TCP","xxx.xxx.xxx.xxx",80");  delay(1000); 
   while(esp8266.available())
  {
      //Serial.write(esp8266.read());
      esp8266.read();
      delay(10);
  }
  esp8266.println("AT+CIPSEND=4,"+String(data1.length()+data2.length()+data3.length()+data4.length()+data5.length()+12)); // the 12 here is related to the data being sent below. Each dataline is sent using println (required to sent) which adds a \r\n after every line. \r and \n makes 2 chars. So for every data sent using println 2 count is increased in the total data length paramter of AT+CIPSEND
  delay(1000);
  while(esp8266.available())
  {
      //Serial.write(esp8266.read());
      esp8266.read();
      delay(10);
  }
  
  
  esp8266.println(data1); delay(1);
  esp8266.println(data2); delay(1);
  esp8266.println(data3); delay(1);
  esp8266.println(data4); delay(1);
  esp8266.println(data5); delay(1);
  esp8266.println();  delay(1); esp8266.flush();

  startTimeDataCapture = millis();
  while(1)
  {
    if(esp8266.available())
      inputBuffer += (char)esp8266.read();
      
    if(inputBuffer.indexOf("CLOSED")> 0 || millis() - startTimeDataCapture > 10000) //The server sends a close after a successful transmission. In case that didn't come (net failure, server failure whatever) then don't wait more than 20 seconds
    {
      stringComplete = true;
      //Serial.println(inputBuffer);
      //delay(1);
      break;
    }
  }

  //check if data came from server
  if(stringComplete)
  {
    inputBufferIndex = inputBuffer.indexOf("led_1=");
    if(inputBufferIndex > -1)
      led1Status = (int)(inputBuffer[inputBufferIndex+6]-'0');  // int conversion required else it was being considered as string by the codes
          
    inputBufferIndex = inputBuffer.indexOf("led_2=");
    if(inputBufferIndex > -1)
      led2Status = (int)(inputBuffer[inputBufferIndex+6]-'0');

    if(led1Status == 1)
    {
      led1Status = 1;
    }
    else
       if(led1Status == 0)
        {
          led1Status = 0;
        }
    
    if(led2Status == 1)
    {
      led2Status = 1;
    }
    else
       if(led2Status == 0)
        {
          led2Status = 0;
        }
  
    digitalWrite(led1Pin,led1Status);
    digitalWrite(led2Pin,led2Status);

    stringComplete = false;
    inputBuffer = "";
  }  
  else
  {
    esp8266.println("AT+CIPCLOSE=4"); // if for any reason  the server didn't reply properly, then close the connection
  }
  delay(5000); // wait 5 secs before making next server call
}

In future revision will implement exception handling (e.g – if the wi-fi is not found then go to sleep and try after certain intervals till connection is established, and only after connection is established move to the next step)

ESP8266 ESP-01 – Part 1 – Flashing and AT commands

This article is about the one that looks like this (aka ESP-01).

esp8266-esp-01-wifi-module-for-iot

 

Flasher version is 2.3
Firmware version is 1.5

Firmware update might be necessary just after purchase. Without firmware update mine was not able to connect to Wi-fi routers (though they were able to find them)

The current firmware available for this is “ESP8266_AT_v0.51”. The direct link to the download http://bbs.espressif.com/viewtopic.php?f=46&t=1451 . The download is at the bottom of the page as an Attachment.

firware files and readme

The flasher (for flashing firmware) can be found here http://bbs.espressif.com/viewtopic.php?f=57&t=433. The .rar version contains the necessary files to update the firmware.

WARNING: read the readme file that came with the firmware.

esp8266-flasher

Please note New chips need DOUT specifically, whereas old ones work with both QIO and DOUT

 Latest Flasher and Firmware Downloads (6th Feb, 2016):

 

Pin configuration of the module

esp8266 - pin

IMPORTANT NOTES:

  • This board runs on 3.3v
  • The default Baud rate is 115200
  • Boot errors are output over 74800. This is default and fixed.
  • For the RX TX line voltage divider using resistors doesn’t work. Using a 150 ohms in series for now, waiting for my Logic Level converter. But then so far (many years now) direct connection didn’t damage the ESP-01.

 

Flashing

  1. Used an Arduino Uno to flash the firmware.
  2. Upload a blank sketch to the Arduino.
  3. The module’s RX will go to Arduino RX and similarly TX will go TX.
  4. GPIO_0 will go to GND
  5. VCC and CH_PD will go to the 3.3v supply line
  6. Load the flasher
  7. Mine one came with “Ai-Cloud insid8” written. This module has a Flash size of 8Mbit: 512KB+512KB. QuadIO and 26MHZ crystal.
  8. Select the appropriate files in the “Download Path Config” section in the flasher tool. Some of the addresses might also need to be adjusted. READ the readme file that came with the firmware.
  9. Select the COM port on which Arduino is connected and the set the Baud rate to 115200 (the default of this board)
  10. Press start. If all goes well it will show finish to the left of the “Start” and “Stop” button
  11. If it fails – press “Stop”. Reset the board by Grounding RESET pin. And press Start again
  12. If the flashing is going on properly then the TX light of Arduino and the Blue light of the module will flash.
  13. Once firmware has been flashed disconnect the GPIO_0 pin from GND. Reset the module and start working

Useful links:
http://www.electrodragon.com/w/Category:ESP8266_Firmware_and_SDK

 

AT Commands

  1. Used Arduino Serial monitor for sending AT commands to the Module.
  2. The RX and TX pin configuration will remain same as above.
  3. Start with the AT command.
  4. List of some useful AT commands : http://www.pridopia.co.uk/pi-doc/ESP8266ATCommandsSet.pdf

 

Notes

  • After flashing the default baud rate becomes 115200. And also the CWMODE might need to be changed to 1 or 3 manually (mine somehow went to mode 2 that is AP mode)
  • If the RTOS firmware is flashed then the “user1.1024.new.2.bin” file inside the AT directory cannot be flashed – it makes the chip non-responsive.
  • The required files for RTOS firmware comes in the zip file named “AT_V0.60_on_ESP8266_NONOS_SDK_V1.5.2_20160203” and is inside “noboot” folder.

 

Updated version of this here: https://www.kolkataonweb.com/code-bank/arduino/esp-01-burning-at-rom-new-and-updated/