members
Basics: Project 070u ESP8266 ESP-12E module with PIR sensor, LDR and 5V relay module - mini sensor s
of Lex C. in ESP8266 ESP-12
Basics: Project 070u
Project name: ESP8266 ESP-12E module with PIR sensor, LDR and 5V relay module - mini sensor shield
Tags: ESP, ESP8266, WI FI module, ESP-12E, Ai Thinker, AI-Cloud, SOC, GPIO, General Purpose Input Output, System On a Chip, IOT, internet of things, FTDI232, FTDI 232, how to upload sketch, LoLin NODEMCU V3, NODEMCU, V3, Development Board with USB-to-Serial Onboard, NodeMCU DevKit, PIR sensor, LDR, Photoresistor, Photocell, motion, luminosity, PIR sensor module, mini sensor shield
Attachments: sketch1
In this project, you need these parts :
1. ESP8266 ESP-12E module with micro USB cable 1pc
2.Arduino IDE ( you can download it from here )
3.Jumper cables F-F, F-M, M-M
4. Mini PIR Motion Sensor Module SC0322 1pc
5. Resistor 3 pcs (2pcs - 220 Ohm and 1 pc - 10 KOhm)
6. Breadboard 1 pc
7. Photoresistor (Photocell or LDR) 1pc
8. 5V Relay module 1 pc
9. Light bulb 60 W 220 V with connector 1pc
10. LED 2 pcs (green and red)
General
We will learn how to design and make a mini sensor shield for the ESP8266 ESP-12E module (LoLin NODEMCU V3). The shield has the PIR motion sensor, the photocell, leds and the 5V relay module.
Understanding PIR sensor module
You can read more about it here.
Understanding the Relay module
You can read more about relay here.
Understanding Photocell (Photoresistor or Light dependent resistor)
You can read more about it here.
Understanding the ESP8266 ESP-12E WI FI module (LoLin NODEMCU V3)
You can read more about it here.
Signals and connections of the 5V relay module
The SRD-05 VDC-SL-C relay has three high voltage terminals (NC, C, and NO) which connect to the device you want to control. The other side has three low voltage pins (Ground, Vcc, and Signal) which connect to the Arduino.
NC: Normally closed 120-240V terminal
NO: Normally open 120-240V terminal
C: Common terminal
Signals and connections of photocell
Attach one end of photoresistor to power. On the otherside, attach a 10-kilohm resistor to ground. This resistor is in series with the photoresistor, and together they form a voltage divider. The voltage at the point where they meet is proportionalto the ratio of their resistances, according to Ohm’s Law.
Signals and connections of LED
The operating voltage of the LED is 1.8V and the operating current is 10mA-20mA. The Arduino Uno board can supply 5V or 3.3V power. We will use 5V for this project, so the minimum resistance of the current limiting resistor should be (5 V to 1.8 V)/20 = 160 Om. The 220 Om offered in the kit is suitable and you can also choose other resistors that meet the condition. The larger the resistance is, the dimmer the LED will get.
Signals and connections of the PIR sensor module
We are goinig to use Mini PIR Motion Sensor Module SC0322 in this project.
Signals and connections of the ESP8266 ESP-12E WI FI module (LoLin NODEMCU V3)
TX - transmit pin. GPIO pin
RX - receive pin. GPIO pin
3V3 (or 3V or 3.3V) - power supply pin (3-3.6V).
GND ( or G) - ground pin.
RST - reset pin. Keep it on high (3.3V) for normal operation. Put it on 0V to reset the chip.
EN - Chip enable. Keep it on high (3.3V) for normal operation.
Vin - External power supply 5VDC.
D0-D8 - GPIO (General Purpose Input Output) pins
D5-D8 - SPI interface
D1-D2– I²C/TWI Interface
SC (or CMD) - (Chip Select) - the pin that the master can use to enable and disable specific devices. GPIO pin
SO (or SDO) - Master In Slave Out (MISO) - SPI communication. The Slave line for sending data to the master. GPIO pin
SK (or CLK) - SCK (Serial Clock) - SPI communication.The clock pulses which synchronize data transmission generated by the master. GPIO pin
S1 (or SD1) - Master Out/Slave In (MOSI). SPI communication. The Master line for sending data to the peripherals. GPIO pin
S2 (or SD2) - GPIO pin
S3 (or SD3) - GPIO pin
VU (or VUSB) - external power 5VDC.
A0 - ADC output.
RSV - reserved
Wiring
Sensors/Leds ESP8266 ESP-12E module
red LED GPIO 5
green LED GPIO 4
PIR GPIO 14
LDR A0 (ADC)
5V Relay module GPIO 12
Step by Step instruction
1. Adding ESP8266 platform to Arduino IDE
The Arduino environment has to be set up to make it compatible with the ESP8266 ESP-12E module.
We are using PC with Windows 10 OS.
1. Installation of ESP8266 add-on in Arduino IDE on Windows OS.
- Download and install the Arduino IDE version 1.6.13 Windows Installer. You can download it here.
- Open Arduino IDE.
- Open the Preferences window from the Arduino IDE. Go to File -> Preferences.
- Enter http://arduino.esp8266.com/stable/package_esp8266com_index.json into Additional Board Manager URLs field and click the “OK” button. If you already have a URL in there, and want to keep it, you can separate multiple URLs by placing a comma between them. (Arduino 1.6.5 added an expanded text box, separate links in here by line.)
- Open Boards manager. Go to Tools -> Board -> Boards Manager…
- There should be a couple new entries in addition to the standard Arduino boards. Look for esp8266. or scroll down to the ESP8266 entry (usually at the bottom). Select the ESP8266 entry. When you click it an install option will appear. Select the latest version and click install.
- The board definitions and tools for the ESP8266 include a whole new set of gcc, g++, and other reasonably large, compiled binaries, so it may take a few minutes to download and install (the archived file is ~110MB). Once the installation has completed, an Arduino-blue “INSTALLED” will appear next to the entry.
2. Uploading sketch to ESP32 development board
If you’re using an ESP-12E NodeMCU Kit, uploading the sketch is very simple, since it has built-in programmer.
Before use ESP8266 ESP-12E WI FI module (LoLin NODEMCU V3), you need to download the manufacture's driver (CH340) for this chip and install it in your PC. Here is the link. See the description of driver installation package below: CH340 / CH341 USB to serial WINDOWS driver installation package that supports 32/64 bit Windows 10 / 8.1 / 8/7 / VISTA / XP, SERVER 2016/2012/2008/2003, 2000 / ME / 98, through Microsoft digital signature authentication, support USB to 3-wire and 9-wire serial port, with the product release To the end user. Applicable scope: CH340G, CH340C, CH340B, CH340E, CH340T, CH340R, CH341A, CH341T, CH341H chips.
If you have CP2102 chip then you need to download the manufacture's driver for this chip and install it in your PC. Driver for Mac, Windows, Linux or more..
- Do wiring.
- Open Arduino IDE.
- Plug your ESP8266 ESP-12E module into your PC USB port.
- Choose your NodeMCU board. Go to Tools -> Board -> NodeMCU 1.0 (ESP-12E Module
)
- Select the correct com port.
- Open sketch1 . Modify sketch with your SSID and password for WiFi network which you are going to use.
- Compile and upload the sketch1 to your ESP8266 ESP-12E module. If everything went as expected, you should see a “Done uploading” message.
- Open the Serial Monitor at a baud rate of 115200 to verify that the ESP8266 ESP-12E module is properly connected to the Wi-Fi network.
- Press RST button on your ESP8266 ESP-12E module to reset it.
- When your ESP8266 ESP-12E module restarts, you will see the IP address of your ESP8266 ESP-12E module in Serial monitor (in our case it’s 192.168.0.118).
- You can access your web server, if you type your ESP8266 ESP-12E module IP address in your browser. In our case it is http://http://192.168.0.118.
the web server we’ll build allows you to choose between 4 different modes to control the relay:The web server allows you to choose between 4 different modes to control the 5v relay module: 1. Manual: in which you have a button to turn the relay on and off; 2. PIR: turns the relay on when motion is detected. In this mode there is a field in which you can set the number of seconds the output will be on after motion is detected; 3. LDR: the relay turns on when the luminosity goes below a certain threshold. You can set an LDR threshold value between 0 and 100%; 4. PIR and LDR: this mode combines the PIR motion sensor and the LDR. When this mode is selected, the relay turns on when the PIR sensor detects motion and if the luminosity value is below the threshold. In this mode you can set the timer and the LDR threshold value. There is a button that you can press to request the LDR reading too. After requesting the LDR readings, you can press Hide Sensor Readings button to hide the readings to optimize the web server performance. In every mode there is a label that shows the selected mode, as well as the current output state.
- Manual mode - you can turn the device on and off.
- PIR mode - the device will be on for the number of seconds you set, when motion is detected.
- LDR mode - you can set the threshold value that will switch on device connected to 5V relay module. When I cover the LDR, the luminosity goes below the threshold and the device will be on.
- PIR and LDR mode - you can set the timer and the LDR threshold. If motion is detected, but the light intensity is above the threshold, nothing happens. But if you cover the LDR, which means there’s no light, and motion is detected, the device will be on for the number of seconds you have defined in the settings. You can also press View Sensor Readings button to request the latest LDR readings.
Code
We want the ESP8266 ESP-12E module to remember the last output state and the settings, in case it resets or suddenly loses power. So, we need to save those parameters in the ESP8266 EEPROM.
We start by including the required libraries. The ESP8266WiFi library is needed to use the ESP Wi-Fi capabilities. The EEPROM library allows you to read and write permanent data on the ESP8266 EEPROM.
We add the network data in these two variables: const char* ssid = ""; const char* password = "";
Then we define variable to hold LDR reading: String ldrString = "";
We define the EEPROM size we want to access: #define EEPROM_SIZE 4. We will need to save four values in the flash memory: the last output state on address 0, the selected mode on address 1, the timer value on address 2, and the LDR threshold value on address 3. So, we need 4 bytes in the flash memory.
Address 0: Last output state (0 = off or 1 = on)
Address 1: Selected mode (0 = Manual, 1 = PIR, 2 = LDR, or 3 = PIR and LDR)
Address 2: Timer (time 0 to 255 seconds)
Address 3: LDR threshold value (luminosity in percentage 0 to 100%)
Then we define the GPIOs for the output (5V relay module), the status LEDs, the PIR sensor and the LDR.
We also create a String variable to hold the outputState to be displayed on the web server: String outputState = "off";
Next we create variables for the timers:
unsigned long now = millis();
unsigned long lastMeasure = 0;
boolean startTimer = false;
Then we initialize variables to store the selected mode, settings and do setup for web server.
// decode HTTP GET value
String valueString = "0";
int pos1 = 0;
int pos2 = 0;
//variable to store the HTTP request
String header;
//set web server port number to 80
WiFiServer server(80);
In the setup () we initialize the serial communication at a baud rate of 115200 for debugging purposes: Serial.begin(115200);
Then we set the PIR sensor as an INPUT_PULLUP, and define it as an interrupt in RISING mode.
We initialize the flash memory with the EEPROM size defined earlier: EEPROM.begin(EEPROM_SIZE);
We set the status LEDs and the output pin as outputs. We set 5V relay module to HIGH by default to have the device off when we start: digitalWrite(output, HIGH);
Then we set the output to the last saved state. The output state is saved on position 0, so use EEPROM.read(0). We check if the state saved is on or off to update the output state accordingly, update all variables that hold settings with the values saved in the EEPROM, like the selected mode, timer and LDR threshold value.
We call the configureMode() function to assign the right values to each mode. Let's have a look how it works: If the selected mode is Manual, the motion is not activated (armMotion), neither the LDR (armLdr). Green LED is on, red LED is off.
if (selectedMode == 0) {
armMotion = 0;
armLdr = 0;
digitalWrite(greenLedPin, HIGH);
digitalWrite(redLedPin, LOW);
}
A similar setup done to configure the other modes. You change the arm variables to activate or deactivate a sensor.
Then in setup() we connect to the Wi-Fi network and print the ESP8266 ESP-12E IP address in the Serial Monitor.
In the loop() we display the web server. We have explained how to do webserver before in previous projects, just check the on our website.
If you select Manual mode, the following part of the code is being executed:
if(header.indexOf("GET /?mode=") >= 0) {
pos1 = header.indexOf('=');
pos2 = header.indexOf('&');
valueString = header.substring(pos1+1, pos2);
selectedMode = valueString.toInt();
EEPROM.write(1, selectedMode);
EEPROM.commit();
configureMode();
}
It saves the selected mode in the selectedMode variable and stores it in the flash memory with: EEPROM.write(1, selectedMode);
The web page changes accordingly to the selected mode. The manual mode corresponds to 0, the following if statement is true and the web page will display two buttons to control the output:
if(selectedMode == 0) {
if(outputState == "off") {
client.println("
");
}
else {
client.println("
");
}
}
When you click the on and off buttons, the following code runs and one of these two else if statements turns the output on or off.
else if(header.indexOf("GET /?state=on") >= 0) {
outputOn();
}
else if(header.indexOf("GET /?state=off") >= 0) {
outputOff();
}
When you change the number of seconds the output should remain on after motion is detected n PIR mode it calls the following part of the code and changes the timer variable:
else if(header.indexOf("GET /?timer=") >= 0) {
pos1 = header.indexOf('=');
pos2 = header.indexOf('&');
valueString = header.substring(pos1+1, pos2);
timer = valueString.toInt();
EEPROM.write(2, timer);
EEPROM.commit();
Serial.println(valueString);
}
In PIR mode it only displays the input field for the timer:
else if(selectedMode == 1) {
client.println("
Timer (0 and 255 in seconds):
String(EEPROM.read(2)) + "\" onchange=\"setTimer(this.value)\" min=\"0\" max=\"255\">
");
} In LDR mode when you change the LDR threshold value it calls the following part of the code to update the LDR threshold value: else if(header.indexOf("GET /?ldrthreshold=") >= 0) { pos1 = header.indexOf('='); pos2 = header.indexOf('&'); valueString = header.substring(pos1+1, pos2); ldrThreshold = valueString.toInt(); EEPROM.write(3, ldrThreshold); EEPROM.commit(); Serial.println(valueString); } LDR mode will display the LDR theshold input field: else if(selectedMode == 2) { client.println(" LDR Threshold (0 and 100%): String(EEPROM.read(3)) + "\" onchange=\"setThreshold(this.value)\" min=\"0\" max=\"100\">
}
PIR and LDR mode activates both the PIR and LDR. It loads a new web page with two input fields which we described before. There are buttons to request, display and hide LDR readings: if (header.indexOf("GET /?sensor") >= 0) { int ldrValue = map(analogRead(LDRPin), 0, 1023, 0, 100); ldrString = " LDR output (Luminosity): " + String(ldrValue) + " %"; client.println(" "); client.println(ldrString); client.println(" client.println(" } else { client.println(" } Depending on the mode and settings selected another part of the loop() is running to check whether the output should be on or off. When motion is detected it calls the detectsMovement() function that starts a timer: void detectsMovement() { if(armMotion || (armMotion && armLdr)) { Serial.println("ALARM!!!MOTION DETECTED!!!"); startTimer = true; lastMeasure = millis(); } } Then, depending on the elapsed time, it turns the output on or off. if (startTimer && armMotion && !armLdr) { if (outputState == "off") { outputOn(); } else if ((now - lastMeasure > (timer * 1000))) { outputOff(); startTimer = false; } } The following section of the code to turn the output on or off depending on the luminosity of the threshold value in LDR mode: if (armLdr && !armMotion) { int ldrValue = map(analogRead(LDRPin), 0, 1023, 0, 100); Serial.println(ldrValue); if (ldrValue > ldrThreshold && outputState == "on") { outputOff(); } else if (ldrValue < ldrThreshold && outputState == "off") { outputOn(); } delay(100); } When the PIR and LDR mode is selected and motion is detected: if (startTimer && armMotion && armLdr) { int ldrValue = map(analogRead(LDRPin), 0, 1023, 0, 100); Serial.println(ldrValue); if (ldrValue > ldrThreshold) { outputOff(); startTimer = false; } else if (ldrValue < ldrThreshold && outputState == "off") { outputOn(); } else if (now - lastMeasure > (timer * 1000)) { outputOff(); startTimer = false; } } Summary We have learnt how to design and make a mini sensor shield for the ESP8266 ESP-12E module. The shield has the PIR motion sensor, the photocell, leds and the 5V relay module. Libraries Sketch
Other projects of Lex C.










Viewed: 7786 times