Saturday, October 22, 2016

ESP8266 SoftwareSerial Library & Level Shifter for ESP8266 - Arduino

Hello everyone,

I have found a very usefull software library for esp8266. Library works well with Arduino IDE.
In this tutorial, I will show you how you can send data between arduino running at 5V and ESP8266 running at 3.3V.

I use :
- Arduino UNO ( You can use another boards .)
- ESP8266 - 07 (You can use another version.)
- 4 x 10k resistor.
- 2 x BS138 Mosfet or ( I will explain which types of mosfets you can use.)
- Some Wires ,breadboards etc.
- Software Serial Library for ESP8266 - Download

Library on Gitbub - Go Github

Using Softwareserial library:
Import the library and open any example wich you want to use.

3.3V - 5V Level Shifter
The Circuit that we use shows in Fig1 and Fig2.

Fig1





I use BSS138 mosfet for my circuit. You can see details on arduino offical web site. (Go Orginal Site)




Fig2

Connection ESP8266 and Arduino :

3.3V SDA -> ESP8266 GPIO-12 as TX
3.3V SCL -> ESP8266 GPIO-14 as RX

5V SDA -> Arduino RX
5V SCL -> Arduino TX

Here is the code that i use : 

#include <SoftwareSerial.h>
//RX Pin 14
//TX Pin 12
#BufferSize 256;
#BAUDRATE 9600
SoftwareSerial mSerial(14, 12, false, BufferSize);

void setup() {
  Serial.begin(9600);
  mSerial.begin(BAUDRATE);
}

void loop() {
  while (mSerial.available() > 0) {
    Serial.write(mSerial.read());
  }
  while (Serial.available() > 0) {
    mSerial.write(Serial.read());
  }
}


If your code is slow and your loop time is too longer, You can increase buffer size and you can keep data for longer.

Why we use BSS138 ? What types of mosfets i can use ?

I test that circuit and software serial library @9600 baudrate. It works very well with very very low bit erros.  You can use different mosfet if you cant find bss138. BSS138 is N-Channel Logic Level Enhancement Mode Field Effect Transistor. You need to be carefull that the mosfet you use should be fast enough.





Tuesday, October 18, 2016

Arduino - ESP8266 Digital Smoothing Filter for Analog Readings

Hello everyone,

In this tutorial i will show you how can read more stable , more accurate and more smooth analog values with arduino or esp8266. Our methods are same for both of them.


Method 1: AveragingMethod.

We will smooth the values by using below equation (Eq. 1)



Eq. 1   





Where ;
Y : Output of filter
X : Signal

What we are doing now ?
X [k] is the signal value and X[k-1] is the old signal value.
When you use that notation,  you can decrease noise effect or unwanted instantenious effects.

Arduino Code :
 
#define SensorPin A0

int nowValue = 0;
int pastValue = 0;
int filteredValue = 0;
void setup() {
  Serial.begin(115200);

}

void loop() {
 
  pastValue = nowValue;
  nowValue = analogRead(SensorPin);
  filteredValue = (pastValue + nowValue) / 2;
  Serial.print("Now Value = ");
  Serial.print(nowValue);
  Serial.print(" Filtered Value = ");
  Serial.println(filteredValue);

  delay(500);

}

 

Method 2 : More sampling ...

This method assumes that if we samples more, we can eliminate analog reading noise. I write a function hat is very common for analog readings. My function samples 30 times and it takes ~31ms. If your signal is at high frequency. You can change delay with delayMicroseconds. You can use 10uS with your project.


int AnalogRead(volatile int AnalogPin) {
  unsigned int RawData = 0;
  for(int = 0; i < 30; i++) {
    RawData = analogRead(AnalogPin);
    delay(1);
  }
  RawData = RawData / 30;
  return RawData;
}


Complete Arduino Code : with method 1.

#define SensorPin A0

int nowValue = 0;
int pastValue = 0;
int filteredValue = 0;
void setup() {
  Serial.begin(115200);

}

void loop() {
 
  pastValue = nowValue;
  nowValue = AnalogRead(SensorPin);
  filteredValue = (pastValue + nowValue) / 2;
  Serial.print("Now Value = ");
  Serial.print(nowValue);
  Serial.print(" Filtered Value = ");
  Serial.println(filteredValue);

  delay(500);

}

int AnalogRead(volatile int AnalogPin) {
  unsigned int RawData = 0;
  for(int = 0; i < 30; i++) {
    RawData = analogRead(AnalogPin);
    delay(1);
  }
  RawData = RawData / 30;
  return RawData;
}

 


Now you have a smoothing filter. If you say my signal has too much noise , You can continue with method 3.

Method 3 : Method 1 with more sample

In this part, we have a signal array where its size is k and filter outpur is average of signal array each value. Also, i use special AnalogRead function.

#define SensorPin A0

int nowValue = 0;
int pastValue = 0;
int filteredValue = 0;

const int ArraySize = 10;
int SignalArray[ArraySize];
void setup() {
  Serial.begin(115200);

}

void loop() {

  //Shifting Array
  for(int i = 0; i < ArraySize - 1; i++) {
    SignalArray[i] = SignalArray[i+1];
  }
 
  SignalArray[ArraySize - 1] = AnalogRead(SensorPin);

  //Average
  unsigned int ArraySum = 0;

  for(int i = 0; i < ArraySize; i++) {
    ArraySum = AnalogRead(SensorPin);
  }

  filteredValue = ArraySum / ArraySize;
  filteredValue = (pastValue + nowValue) / 2;

 
  Serial.print("Now Value = ");
  Serial.print(SignalArray[ArraySize - 1]);
  Serial.print(" Filtered Value = ");
  Serial.println(filteredValue);

  delay(500);

}

int AnalogRead(volatile int AnalogPin) {
  unsigned int RawData = 0;
  for(int i = 0; i < 30; i++) {
    RawData = analogRead(AnalogPin);
    delay(1);
  }
  RawData = RawData / 30;
  return RawData;
}

 



Complete Project Code : Download

Tuesday, October 11, 2016

ESP8266 UDP Server Example

Hello everyone,

In this tutorial, i will show you how to receive UDP Packets via ESP8266.

I assume that you know something about UDP and i will not show you to how udp is working.

In this tutorial, will sent an UDP packet via pc that connected to same network with esp8266 and we show the UDP packets on Serial Port Screen.

This tutorial contains 3 simple steps. 2 of steps are main and final step is for testing.

We need :

Hardware :
1 x Esp8266 Board (I am using ESP8266 -07)
1 x USB to RS232 Chip for programming (FTDI)


Software :
Packet Sender ( for sending UDP Packets) Download

Step 1 : Connecting Wi-Fi Network

#include <ESP8266WiFi.h>

const char* ssid     = "KeyTech-1";
const char* password = "TOBB_Muhendis";


void setup() {
  Serial.begin(115200);
  delay(10);

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
 
  WiFi.begin(ssid, password);
  WiFi.config(IPAddress(192, 168, 1, 60), IPAddress(192, 168, 1, 1), IPAddress(255, 255, 255, 0));
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected"); 
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

int value = 0;

void loop() {

}


 
I dont explain this step because this is very common part for esp8266.

Note: I set my ip address static 192.168.1.60
WiFi.config(IPAddress(192, 168, 1, 60), IPAddress(192, 168, 1, 1), IPAddress(255, 255, 255, 0)); //This line is optional... 

Step 2 : Starting UDP Server

We use WifiUDP library for setting an UDP Server.

Firstly, we create a WiFiUDP Object and i have selected udp server port 2807. You can change your port number whatever you want or which port yo need to listen. Also i created a packet buffer and i selected its size as 2. You can change it to how many bytes you need in your project.

//Creating UDP Listener Object.
WiFiUDP UDPTestServer;
unsigned int UDPPort = 2807;


//Packet Buffer
const int packetSize = 2;
byte packetBuffer[packetSize];



Secondly, in void setup() , starting udp listener ...

 UDPTestServer.begin(UDPPort); 



Thirdly, creating a udp message handle. You Can access your data in myData variable. I selected to it as string. You can change it what you need or what you are sending. I will sent String type packets for testing ...

void handleUDPServer() {
  int cb = UDPTestServer.parsePacket();

  if (cb) {
    UDPTestServer.read(packetBuffer, packetSize);

    String myData = "";
   
    for(int i = 0; i < packetSize; i++) {
      myData += (char)packetBuffer[i];
    }

    Serial.println(myData);

  }
}


 Complete Project Code : 

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

const char* ssid     = "XXX";
const char* password = "XXX";

WiFiUDP UDPTestServer;
unsigned int UDPPort = 2807;

const int packetSize = 2;
byte packetBuffer[packetSize];

void setup() {
  Serial.begin(115200);
  delay(10);

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
 
  WiFi.begin(ssid, password);
  WiFi.config(IPAddress(192, 168, 1, 60), IPAddress(192, 168, 1, 1), IPAddress(255, 255, 255, 0));
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected"); 
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  UDPTestServer.begin(UDPPort);
 
}

int value = 0;

void loop() {
   handleUDPServer();
   delay(1);
}

void handleUDPServer() {
  int cb = UDPTestServer.parsePacket();
  if (cb) {
    UDPTestServer.read(packetBuffer, packetSize);
    String myData = "";
    for(int i = 0; i < packetSize; i++) {
      myData += (char)packetBuffer[i];
    }
    Serial.println(myData);
  }
}



 Download Complete Project

 Step 3 : Testing UDP Server ...

In this step we will test our esp8266 udp listener ... Run the packetsender program that you downloaded before.  On below picture, i explain how you can use the program. Program will send UDP Packets when press the Send button.



Here is the final result ...




 
 
You can see your UDP Packets on Serial Port Screen.

I hope it will helps you on your projects.  You download complete project on below link. 



Download Complete Project



Monday, October 10, 2016

ESP8266 Firmware Update in 3 Simple Steps

Hello everyone,

This tutorial shows how you can update your ESP8266 Chip Firmware in 3 simple steps.

I use :

Hardware :
1 x ESP8266 Board (01 to 12 which you have ...)
1 x USB to Serial Converter (FTDI Module)
5-10 Jumper for Wiring ..


Software :
ESP8266 Flasher Tool : Download
ESP8266 Firmware (v0.9.2.2) : Download

Step 1 : Wiring

I am using ESP8266 01 Board.



Note : GPIO 0 and GPIO15 and must be connect to GND. On ESP01 Board GPIO 15 already connected to GND. If you are using ESP 07 or ESP 12, you have to connect GPIO 15 to GND.

Step 2 : Setting flasher tool.


Now Select your firmware ... Press "Bin" Button and select firmware on your pc.




You can check your com port number on Arduino IDE Ports Sections.




Now write your port number to ESP8266 Flasher Program.






Step 3 : Ready to Update !

Press download button and update your firmware ...







Note : After programming, Flash tool says : failed to leave flash mode, that is not a problem !

I hope it will helps you.

Tuesday, September 27, 2016

Esp8266 NTC (Temperature) Thermistor Analog Reading with Arduino IDE

Hello Everyone,

In this lesson, i will show you reading temperature with an esp8266 and a ntc (thermister) sensor.

Note : 
You need an ESP board having ADC pin. Only ESP8266 - 07 and ESP8266 - 12 boards have ADC pin.

I used :
-ESP8266 - 07
-10k NTC
-150k ohm resistor.

We will use very simple and basic resistor-ntc circuit. Circuit is in figure1.


Figure-1

Normally, if you search on internet you will see circuits that uses 10k ntc with a 10k resistor. On my circuit i use 150k resistor. Now i will explain why i am doing it.

In figure-2, there is a graph that explaint resistance and temperature for a ntc sensor.
This sensor says NTC resistor high value is about 18-20k and 3-4k for (room temp).

Figure-2
If we use 10k resistor with 10k NTC,

Assume :
NTC max resistance = 18kohm
NTC min resistance = 3k ohm
VCC = 3.3V

 
Here is the problem. ESP8266 ADC pin Reference is 1V.
What is that mean?
That mean is your analog voltage highest value must be 1V. So, for that reason, i will use 150k resistor and wtih 150k resistor maximum and minumum analog values are below.


Theese values are good for our project. You can use a lower resistor for higher temperature resolution. In my project temperature resoulution is not very important.

ESP8266 Analog Resolution per Volts :

1V = 1024
1 / 1024 = 0.00097 V  resolution.

0.3535 V / 0.00097 V= 364
0.0647 V / 0.00097 V = 66

That means, we have 298 different temperature values. As i sad this is enough for my project.

Now we have solved hardware problem. But with this solution we have a problem with software. Functions that you can find on internet is for 10k ntc and 10k resistor and there is not enough explaniton about it.

Firstly,

We need to find instantenious resistance of NTC. You can use ESP8266 ADC pin as A0 on Arduino IDE.

Simple analog read code : 

int RawData = analogRead(A0);

Filtered analog read code : 


int AnalogRead() {
  int val = 0;
  for(int i = 0; i < 20; i++) {
    val += analogRead(A0);
    delay(1);
  }

  val = val / 20;
  return val;
}


In my project i use filtered analog read code. This is very effective and more stable. We have read analog voltage on NTC. Now we will calculate instantenious resistance of NTC.

void loop() {
  double Vcc = 3.3V;
  unsigned int Rs = 150000;
  double V_NTC = (double)AnalogRead()
  double R_NTC = (Rs * V_NTC) / (Vcc - V_NTC);  

  Serial.println(R_NTC);
}

We have successfuly completed first step. We have calculated resistance of NTC. You can check your paramters with your multimeter but you need to now that when you touch your ntc sensor, ntc resistance will change instantly.

Second step is about calculating temperature with using instantenious resistance of ntc .

The Steinhart–Hart equation is a model of the resistance of a semiconductor at different temperatures. The equation is:

1T=A+Bln(R)+C(ln(R))3
where:
  • Tis the temperature (in kelvins)
  • Ris the resistance at T(in ohms)
  • A, B, and C are the Steinhart–Hart coefficients which vary depending on the type and model of thermistor and the temperature range of interest. (The most general form of the applied equation contains a (ln(R))2
    • term, but this is frequently neglected because it is typically much smaller than the other coefficients, and is therefore not shown above.)
    Steinhart-Hart equation - Wikipedia, The Free Encyclopedia

    A = 0.001129148
    B = 0.000234125
    C = 0.0000000876741

    Now we are ready for calculate temperature.

    Where:
    Rs = 150000;  //150k ohm resistor
    Vcc = 3.3;

    double Thermister(int val) {

      double V_NTC = (double)val / 1024;
      double R_NTC = (Rs * V_NTC) / (Vcc - V_NTC);
      R_NTC = log(R_NTC);
      double Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * R_NTC * R_NTC ))* R_NTC );
      Temp = Temp - 273.15;        
      return Temp;


    }
Here is the complete project code .

#include <math.h>

unsigned int Rs = 150000;
double Vcc = 3.3;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:

  Serial.println(Thermister(AnalogRead()));
  delay(1000);

}

int AnalogRead() {
  int val = 0;
  for(int i = 0; i < 20; i++) {
    val += analogRead(A0);
    delay(1);
  }

  val = val / 20;
  return val;
}

double Thermister(int val) {
  double V_NTC = (double)val / 1024;
  double R_NTC = (Rs * V_NTC) / (Vcc - V_NTC);
  R_NTC = log(R_NTC);
  double Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * R_NTC * R_NTC ))* R_NTC );
  Temp = Temp - 273.15;         
  return Temp;

}






You can change Rs and Vcc paramters with your own values.


Note (Important !) : If you want to use different Rs, make sure your instantenious analog input voltage value is lower than 1V.

You can download project on that link.
Download here


Hope it will help you.
See you soon.






ESP8266 SoftwareSerial Library & Level Shifter for ESP8266 - Arduino

Hello everyone, I have found a very usefull software library for esp8266. Library works well with Arduino IDE. In this tutorial, I will s...