Using NodeMCU to control an LED in LAN network

Hi! Today let us see how to operate a LED with NodeMCU using a network protocol TCP/IP

Note: Be sure that u have some knowledge on ports, server, IP address, DHCP, TCP/IP, Telnet.

Requirements:

Arduino IDE with an esp8266 board community.
Pc with putty software installed.
NodeMCU.
led
connecting wires/cables

Construction:

Process:

Here we connect the NodeMcu to a wifi network and a mobile or a PC is also connected to the same wifi network.  When NodeMCU is connected to Wifi using DHCP an IP address is assigned to the NodeMCU by the router and this will be printed on the serial monitor.

NodeMCU listens to incoming data on a port specified (80 in a program below) until a special character ‘#’ has occurred or until the timeout reached.  If there is any String that contains ‘ON’/’OFF’ cmd it will turn ON/OFF the LED.

Now in pc open putty application and select connection type to telnet and enter the IP address and port number (check in code)  and click open. The connection is established and you can send and receive data from NodeMCU.

Type ‘ON#’  and Hit enter. You will see the LED glowing. And also you will see the status of the led on your putty screen.

CODE:

#include <ESP8266WiFi.h>  // librery for wifi
const char* ssid = "Your WiFI network name ";
const char* password = "ypur WiFi network password"; 
int ledPin = D4; // D4 (GPIO4) 
WiFiServer server(80);  //Nodemcu listining on port 80
void setup() {
Serial.begin(115200);
delay(10); 
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW); 
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid); 
WiFi.begin(ssid, password); 
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print(WiFi.localIP()); 
} 
void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
} 
// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
} 
// Read the first line of the request
String request = client.readStringUntil('#');
Serial.println(request);
client.flush(); 
// Match the request
int value = LOW;
if (request.indexOf("ON") >= 0) {
digitalWrite(ledPin, HIGH);
value = HIGH;
}
else if (request.indexOf("OFF") >= 0) // indenOf returns -1 if there is no such word in request string
{
digitalWrite(ledPin, LOW);
value = LOW;
}
client.print("Led pin is now: "); 
if(value == HIGH) {
client.print("On");
} else {
client.print("Off");
}
delay(1);
Serial.println("Client disonnected");
Serial.println(""); 
}

How to Control this LED over WAN using Public IP and Port forwarding.

We hope you learned how network protocols work with microcontrollers over wifi with NodeMCU to operate physical devices.

 

–ABHIJITH

 

 

Reading Temperature and Humidity From NodeMCU in LAN

Hi! In this project let us see how to configure NodeMCUto read Temperature and Humidity from a DHT11 sensor and forward it to a user or client on a request

Requirements:

Arduino IDE with an esp8266 board community.
Pc with putty software installed.
NodeMCU.
DHT11 sensor
connecting wires/cables

Construction:

Process:

Here we connect the DHT11 sensor to NodeMCU. This NodeMCU is connected to our wifi network and starts its server listening on port 80.   When a client is connected to the network and sends some data, immediately the data from the digital sensor DHT11  is taken and if the command or request from a client is TEMP/HUMI/GET then it sends the data to the client.

CODE:

 

#include <ESP8266WiFi.h> 
#include "DHT.h" // including the library of DHT11 temperature and humidity sensor
#define DHTTYPE DHT11 // DHT 11

#define dht_dpin D3
DHT dht(dht_dpin, DHTTYPE);

const char* ssid = "Your WiFI network name ";
const char* password = "ypur WiFi network password"; 
int ledPin = 13; // GPIO13
WiFiServer server(80); 
void setup() {
dht.begin();
Serial.begin(115200); 
delay(10); 
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid); 
WiFi.begin(ssid, password); 
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print(WiFi.localIP()); 
} 
void loop() {
// Check if a client has connected
WiFiClient client = server.available();
//while connected keep listining to packets 
if (client) { 
// Wait until the client sends some data
Serial.println("new client");
while (client.connected()) {
while(!client.available()){
delay(1);
} 
float h = dht.readHumidity();
float t = dht.readTemperature();
// Read the first line of the request
String request = client.readStringUntil('#');
Serial.println(request);
client.flush(); 
// Match the request

if (request.indexOf("TEMP") >= 0) 
{
client.print("temperature is - ");
client.println(t);
}
else if (request.indexOf("HUMI") >= 0) // indenOf returns -1 if there is no such word in request string
{
client.print("humidity is - ");
client.println(h);
}
else if (request.indexOf("GET") >= 0)
{
client.print("temperature/humidity is");
client.print(t)
client.print('/')
client.println(h)
}
}
}
}

 

–ABHIJITH

Entering into Internet of Things.

IoT

Connecting physical things to the internet to monitor and control them according to the requirement using software algorithms is called IoT.

In previous projects, You have learned how to monitor and control physical devices using Arduino or a microcontroller. Now let us see how to connect these to the Internet to monitor and control them over the internet in the following lectures.

NOTE: Before going into IoT you have to be familiar with some basics of network protocols, Internet protocol, and what is Server/Hosts/client, DNS, DHCP, PublicIP and PrivateIP, Packet format of TCP and UDP.

Arduino can be connected to the Internet using Arduino Ethernet shield or WiFi based shields (The most popular shields are esp shields and there are different models available). But this leads to some complex connections and it requires multiple programs and interfacings.  But few esp chips can be directly used for monitoring and controlling things just like an Arduino and at the same time, we can also interface it with wifi.

NodeMCU is the most popular board for this case. So In our next lectures, we deal with NodeMCU. You can use any other board as your wish and can do these projects by changing simple lines of code.

Air Quality monitoring

Problem

We observe in most cases fire accidents occur in houses due to the leakage of gas.

Solution

So to prevent these kinds of accidents we came up with a simple solution.
Here we monitor the air quality using MQ-135 sensor and when there is any leakage in the gas the air quality will be reduced and the Buzzer goes high to inform us and we take immediate action.

Requirements:

5v-2A power adapter
arduino nano or Arduino Uno
Mq-135 sensor
16*2 LCD Display
connecting wires/jumper wires
10k and 3.7k resistors
10k potentiometer/ variable resistor
buzzer
BC547 transistor

Construction:
 

 

Process:

Here we measure the air quality using the sensor MQ-135 and display it in LCD display. When LPG gas is leaked the air quality will be reduced and then the buzzer goes high to warn us.

code:

#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 8, 9, 10, 11 , 12); // pin reference - LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
int buzzer = 6;                  // buzzer to digital 6 pin
void setup() { 
  lcd.begin(16, 2);           // tell program the size of lcd display
  lcd.setCursor(0,1);         // to set s=cursor at beginning of the screen
  lcd.clear();
  lcd.write("HELLO AJ");      // Write your name to check on screen
  pinMode(buzzer, OUTPUT);
  digitalWrite(buzzer, 0); 
  Serial.begin(9600);          // serial  baud rate 
}
void loop() {
  int sensorValue = analogRead(A3);  //reading analog input from mq-135 sensor
  Serial.print("Air Quality = ");
  Serial.print(sensorValue);       
  Serial.print("*PPM");
  Serial.println();
  lcd.clear();                       // to clear the screen 
  lcd.setCursor(0,0);                // set cursor at beginning of display
  lcd.print("Air Quality = ");
  lcd.setCursor(1,0);                // set cursor at 2nd row 1 colum of display
  lcd.print(sensorValue);
  lcd.print(" PPM");
  if (sensorValue < 500){
   lcd.print("is good");   
  }
  if (sensorValue > 500){
   lcd.print("is poor");
  }
  if (sensorValue > 1000){
   lcd.print("is very poor");
   digitalWrite(buzzer, HIGH);
  }
  delay(1000);
}

 
–ABHIJITH 

Fan/Motor speed control with change in Temperature

Problem 

It’s too chilled, too hot, moderate. Its the change in mood in a single night and we get up plenty of times to control the fan speed which causes a sleep disorder.

Solution

Come on let’s solve this with the skills we developed till now. Here we start monitoring the temperature and according to the change in temperature, we adjust the speed of the fan with Arduino PWM (pulse width modulation) control

Requirements:

5v-2A power adapter
arduino nano or Arduino Uno
connecting wires/jumper wires
LM35
10k resistor
Diode Rectifier 1A-50V
N-channel MOSFET 60v 30A

Construction:

NOTE:  Here we are connecting the ground terminal of the motor to the Arduino PWM pin. The amount of  PWM to the ground is inversely proportional to the speed of the motor.

Process:

Here we continuously measure the temperature in the room using the LM35 sensor and for a particular level of change in the temperature, we adjust the speed of fan using PWM control.

Reference:

For a brief video on PWM click here.

For AC power control with PWM check here, here.

Code:

int val;
int tempPin = A3;
int fanPin = 5;   // to Digial pin 5 

void setup()
{
Serial.begin(9600);
pinMode(fanPin, OUTPUT);
pinMode(tempPin, INPUT);
}

void loop()
{
val = analogRead(tempPin);
float mv = ( val/1024.0)*5000; // measuring in milli volts
float cel = mv/10;             // converting to celcius
float farh = (cel*9)/5 + 32;   // converting to faranheat

Serial.print("TEMPRATURE = ");
Serial.print(cel);
Serial.print("*C");
Serial.println();
if(cel > 30){
 analogWrite(fanPin, 0);  
 //---------------------------- NOTE -------------------------------------- 
 //| 0 is equal to LOW, Ground pin is 0 i.e fully grounded             |
 //|(arduino output pins cotrolled with pwm and resolution is 8bit)    | 
 //---------------------------- NOTE -------------------------------------
Serial.print('running at maximum speed');
}
else if(cel <30 && cel >25){   // between 25 and 28
   analogWrite(fanPin, 100);
   Serial.print('fan is at 75% speed');
}
else if(cel >25 && cel <20){
   analogWrite(fanPin, 150);
   Serial.print('fan is at 50% speed');
}
else if(cel >15 && cel <20){
   analogWrite(fanPin, 200);
   Serial.print('fan is at 25% speed');
}
else if(cel < 15){
   analogWrite(fanPin, 255);
   Serial.print('fan is off');
}
delay(10000);
}

In this example, we showed you how to control a dc motor with MOSFET. In the same way, you can even control AC fans by changing MOSFET according to your fan specifications.

–ABHIJITH 

Automatic Plant watering System.

Problem

We most probably see a lot of indoor plants die due to lack of water.  This happens so because we humans can’t notice the amount of moisture present in the soil.

Solution

Here we come up with a simple solution. We monitor the presence of moisture levels in the soil and temperature in the air to and control the motor pump accordingly.

When the moisture is low and if the temperature is higher than the normal (33 in my case) then we water the plant for 3 mins else we just water the plant for 1 min. (change these setting as per your plants’ position, no.of  plants and requirement of water for them)

Requirements:

5v-2A power adapter
arduino nano or Arduino Uno
connecting wires/jumper wires
TIP120 Transistor
LM35 Temperature Sensor
Soil Moisture Sensor
1N4001 diode
5v DC motor pump  click here

Construction:

Process:

Here we are using a soil moisture sensor to measure the amount of moisture present in the soil and at the same time, we also measure the temperature in the atmosphere using the LM35 sensor.  When the moisture reduced to below the setpoint value and if the temperature is above the setpoint value then we water the plant for 3 min else we water the plant for 1 min.

 

code:

int moisture_sensor = A0;
int Temperature_sensor = A1;
int temperature_setpoint = 33; // in celcius
int moisture_setpoint = 50; // in 0- 100%
int Pump = 3;
void setup() {
Serial.begin(9600);
Serial.println("Reading From the Sensor ...");
pinMode(moisture_sensor, INPUT); 
pinMode(Temperature_sensor, INPUT);
pinMode(Pump, OUTPUT);
delay(2000);
}
void loop() {
int moisture = analogRead(moisture_sensor);
moisture = map(moisture,1024,10,0,100);
Serial.print("moisture : ");
Serial.print(moisture);
Serial.println("%");
int temperature = analogRead(Temperature_sensor);
float volts=(temperature/1024.0)*5.0; //conversion to volts
temperature = volts*100.0; //conversion to temp Celsius
Serial.print("Temperature : ");
Serial.print(temperature);
Serial.println(" C");
if (moisture < moisture_setpoint)
{
if (temperature > temperature_setpoint)
{
digitalWrite(Pump, HIGH);
delay(30000); // water the plant for 3 min
}
else 
{
digitalWrite(Pump,HIGH);
delay(10000); // water the plant for 1 min
}
}
digitalWrite(Pump, LOW);
delay(50000); // monitor every 5 mins 
}

 

–ABHIJITH

Automatic Urban lamp control

Problem 

We daily turn ON urban lamp during night time and we forgot to switch it OFF most of the time’s and wasting lots of power.

Solution

Here we have a simple economical solution in order to control the light automatically. It monitors the intensity of sunlight and when the intensity is low during night time it turns on automatically.

Requirements:

5v power adapter
Arduino nano (or) Arduino Uno
connecting wires/jumper wires
LDR (Photoresistor) and 10 k resistor
a single channel relay module

Construction:

NOTE:  Common pin and NO/NC pins may vary according to the type of relay manufacturer

Make sure that LDR is placed to detect sunlight but not Lamp light.

Process:

Here we monitor the intensity of the sunlight and control the urban lamp accordingly. With LDR we measure the intensity of sunlight and when it reduces we activate the relay to turn on the lamp when it increases it turn off the lamp using Relay.

Code:

 

int sensorPin= A0; //read anolog value from sensor
int sensorValue = 0; //initialize sensor value to 0
int LAMP = 3; //relay to pin 3
void setup() {
pinMode(LAMP, OUTPUT);
Serial.begin(9600);
}
void loop() {
sensorValue = analogRead(sensorPin);
Serial.print('sensor value - ');
Serial.println(sensorValue);

if (sensorValue > 200){ // if intensity of sunlight is high turn off lamp
Serial.println("LAMP light OFF");
digitalWrite(LAMP, LOW);
delay(1000);
}
if(sensorValue < 100)
{
Serial.println("LAMP light ON"); // if intensity of sunlight is high turn on lamp
digitalWrite(LAMP,HIGH);
delay(1000);
}
Serial.print('Monitoring sun light');
delay(1000);
}


Automatic water level controller

Problem

A lot of water gets wasted during tank filling and we sometimes run out of the water.

Solution

Here we have a simple economical water level controller that comes up solving all those problems. It monitors the water level in the tank and operates
the pump accordingly and saves water as well as power and prevents the tank from running out of the water.

Requirements:

5v power adapter
arduino nano or Arduino Uno
connecting wires/jumper wires
ultrasonic sensor(HC SR04)
a single channel relay module

Construction:

NOTE:  Common pin and NO/NC pins may vary according to the type of relay manufacturer

Process:

Here we continuously measure the distance of water using an ultrasonic sensor and an Arduino microcontroller.
When the distance of water is less than the minimum level, immediately microcontroller will turn on the relay and it activates the motor and waits until the water level reaches the max level and then it automatically turns it off.

Code:

const int trigPin = 3;  //arduino pin 3 to ultrasonic trig
const int echoPin = 2;  //arduino pin 2 to ultrasonic echo 
const int relay = 4;  // ardino pin 4 to relay IN pin
const int min_level = 15;  //min water distance in cm
const int max_level = 300;  // maximum water distance in cm
//note: change min and max levels according to your tank level

void setup() 
{ 
Serial.begin(9600);   // for serial monitor 
pinMode(trigPin, OUTPUT);  
pinMode(echoPin, INPUT);
pinMode(relay, OUTPUT);
} 
void loop()
{
long duration,cm;
digitalWrite(trigPin, LOW); 
delayMicroseconds(2); 
digitalWrite(trigPin, HIGH); //triger for 10us to observe eco
delayMicroseconds(10); 
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH,3); // wait for 3 sec to get the pulse 
cm = microsecondsToCentimeters(duration); // call distance measuring function
Serial.print(cm);  // print distance on monitor when connected 
Serial.print("cm"); 
Serial.println(); 
if (cm >= max_level){     // condition if level is high
digitalWrite(relay, HIGH);   
Serial.print('pump OFF');
}
if(cm <= min_level){       // condition if level is low
digitalWrite(relay, LOW);
Serial.print('pump ON');
}
delay(1000);
}

long microsecondsToCentimeters(long microseconds) // to caliculate distance in cm
{return microseconds / 29 / 2;}

 

 

–ABHIJITH