Friday, September 22, 2023
Google search engine
Home Blog

ESP32 MQTT with MicroPython Programming

0

ESP32 MQTT with MicroPython Programming

ESP32 is a system on chip microcontroller that comes with multiple inbuilt features like Wi-Fi, BLE, dual-core processor, inbuilt sensors, OTA programming, low power consumption etc. which makes it stand apart from its predecessors.

ESP32 is a system on chip microcontroller that comes with multiple inbuilt features like Wi-Fi, BLE, dual-core processor, inbuilt sensors, OTA programming, low power consumption etc. which makes it stand apart from its predecessors.

The IoT (or Internet of Things) is a network of interconnected computing devices like automobiles, digital machines with inbuilt sensors and each with a unique identifier along with the ability to communicate data over a network without any human intervention.

In this tutorial, we will learn how to program ESP32 to implement the MQTT protocol using the MicroPython programming language. We will publish the Hall sensor readings/values from ESP32 to ThingSpeak over the MQTT protocol.

MQTT (or Message Queuing Telemetry Protocol)

MQTT is a communication/messaging protocol for IoT applications. It is a Publish and Subscribe protocol to communicate data between the internet-enabled devices.
A broker is a kind of handler or acts as an interface medium between the publisher device or transmitter and the subscriber device that is the receiver. The broker’s role is to handle or filter all the incoming data from the publisher and distribute them to the subscribers in the most efficient way.

Role of a broker in MQTT protocol:

  • Receiving data or messages from the publisher or transmitter (i.e., ESP32)
  • Filtering the received data.
  • Determining the interested subscriber in each information packet or message.
  • Forwarding the data to the interested subscriber or receiver device.

There are multiple brokers available to handle and distribute the information and in this tutorial, we are using the ThingSpeak as an MQTT broker.

Hall Effect Sensor
The ESP32 module offers some inbuilt sensors and the Hall Effect sensor is one of them. It is a transducer that responds with a change in its Hall voltage (or output voltage) when placed in a magnetic field.
The Hall-effect comes into existence when the magnetic field makes the current (flowing inside a conductor) deviate from its path.

Software and Hardware requirements

  • uPyCraft IDE
  • MQTT Broker (ThingSpeak)
  • ESP32 development board.

Installing uPyCraft IDE for MicroPython programming in ESP32 (Windows)
To program the ESP32 using the Micropython firmware, it is recommended to use either uPyCraft IDE or Thonny IDE. In this tutorial, we are using the uPyCraft IDE.
Note: Before installing the uPyCraft IDE it is required to install the latest version of Python.

  • Once the Python installation file is downloaded successfully. Open the file.
  • Enable the Add Python 3.10 to Path at the bottom and click on Install Now.
  • Click ‘OK’ once it is installed successfully.
    Flashing the MicroPython firmware to ESP32 module:
Whether you are using the ESP32 or ESP8266, for each module it is required to install the Micropython firmware into ESP32 (because MicroPython is not flashed into the ESP32 by default).
● Click on the .bin file to download the ESP32 MicroPython firmware.

Interface OLED Display with ESP32 using MICROPYTHON

2

Introduction of OLED Display

The new generation of small, interactive displays is a great way to add user-interactivity and interactivity with your favourite IoT project. The 0.96 inch OLED panel has been growing in popularity because it can be used as an input device or output screen for any application that requires these features such as
Health tracking systems where people wearables might monitor heart rates 24/7 without bothering you while sleeping at night!
Air quality monitoring system.
Tracking Bitcoin
Weather forecasting and many more.
One such oled display module is SSD1306.
Youtube link

Oled display Pins and Specifications

Add image related to pin diagram for oled display>>
  • 3V-5V Supply input Voltage
  • 2ma -24ma current consumption
  • 128 pixel wide and 64 pixel Tall
  • Wide Viewing angle.
  • Oled display will either use I2C or SPI. write about I2C or SPI accordingly.
The OLED display  maps 18×64 pixels into 0 or 1 value. Each pixel is represented by a single bit , this leads to 8192 bits of data being written to the OLED display in single Write operation 8192 bits = 1024 bytes = 1KB. ESP32 with OLED display Connectivity diagram.

Add image>>
Add a fritzing file link.

MicroPython based
Code:
Driver Code: || Src Code.
MicroPython Driver Code:
 
# MicroPython SSD1306 OLED driver, I2C and SPI interfaces
 
from micropython import const
import framebuf
 
 
# register definitions
SET_CONTRAST = const(0x81)
SET_ENTIRE_ON = const(0xA4)
SET_NORM_INV = const(0xA6)
SET_DISP = const(0xAE)
SET_MEM_ADDR = const(0x20)
SET_COL_ADDR = const(0x21)
SET_PAGE_ADDR = const(0x22)
SET_DISP_START_LINE = const(0x40)
SET_SEG_REMAP = const(0xA0)
SET_MUX_RATIO = const(0xA8)
SET_IREF_SELECT = const(0xAD)
SET_COM_OUT_DIR = const(0xC0)
SET_DISP_OFFSET = const(0xD3)
SET_COM_PIN_CFG = const(0xDA)
SET_DISP_CLK_DIV = const(0xD5)
SET_PRECHARGE = const(0xD9)
SET_VCOM_DESEL = const(0xDB)
SET_CHARGE_PUMP = const(0x8D)
 
# Subclassing FrameBuffer provides support for graphics primitives
# http://docs.micropython.org/en/latest/pyboard/library/framebuf.html
class SSD1306(framebuf.FrameBuffer):
    def __init__(self, width, height, external_vcc):
        self.width = width
        self.height = height
        self.external_vcc = external_vcc
        self.pages = self.height // 8
        self.buffer = bytearray(self.pages * self.width)
        super().__init__(self.buffer, self.width, self.height, framebuf.MONO_VLSB)
        self.init_display()
 
    def init_display(self):
        for cmd in (
            SET_DISP,  # display off
            # address setting
            SET_MEM_ADDR,
            0x00,  # horizontal
            # resolution and layout
            SET_DISP_START_LINE,  # start at line 0
            SET_SEG_REMAP | 0x01,  # column addr 127 mapped to SEG0
            SET_MUX_RATIO,
            self.height – 1,
            SET_COM_OUT_DIR | 0x08,  # scan from COM[N] to COM0
            SET_DISP_OFFSET,
            0x00,
            SET_COM_PIN_CFG,
            0x02 if self.width > 2 * self.height else 0x12,
            # timing and driving scheme
            SET_DISP_CLK_DIV,
            0x80,
            SET_PRECHARGE,
            0x22 if self.external_vcc else 0xF1,
            SET_VCOM_DESEL,
            0x30,  # 0.83*Vcc
            # display
            SET_CONTRAST,
            0xFF,  # maximum
            SET_ENTIRE_ON,  # output follows RAM contents
            SET_NORM_INV,  # not inverted
            SET_IREF_SELECT,
            0x30,  # enable internal IREF during display on
            # charge pump
            SET_CHARGE_PUMP,
            0x10 if self.external_vcc else 0x14,
            SET_DISP | 0x01,  # display on
        ):  # on
            self.write_cmd(cmd)
        self.fill(0)
        self.show()
 
    def poweroff(self):

        self.write_cmd(SET_DISP)

 

    def poweron(self):

        self.write_cmd(SET_DISP | 0x01)

 

    def contrast(self, contrast):

        self.write_cmd(SET_CONTRAST)

        self.write_cmd(contrast)

 

    def invert(self, invert):

        self.write_cmd(SET_NORM_INV | (invert & 1))

 

    def rotate(self, rotate):

        self.write_cmd(SET_COM_OUT_DIR | ((rotate & 1) << 3))

        self.write_cmd(SET_SEG_REMAP | (rotate & 1))

 

    def show(self):

        x0 = 0

        x1 = self.width – 1

        if self.width != 128:

            # narrow displays use centred columns

            col_offset = (128 – self.width) // 2

            x0 += col_offset

            x1 += col_offset

        self.write_cmd(SET_COL_ADDR)

        self.write_cmd(x0)

        self.write_cmd(x1)

        self.write_cmd(SET_PAGE_ADDR)

        self.write_cmd(0)

        self.write_cmd(self.pages – 1)

        self.write_data(self.buffer)

 

 

class SSD1306_I2C(SSD1306):

    def __init__(self, width, height, i2c, addr=0x3C, external_vcc=False):

        self.i2c = i2c

        self.addr = addr

        self.temp = bytearray(2)

        self.write_list = [b”\x40″, None]  # Co=0, D/C#=1

        super().__init__(width, height, external_vcc)

 

    def write_cmd(self, cmd):

        self.temp[0] = 0x80  # Co=1, D/C#=0

        self.temp[1] = cmd

        self.i2c.writeto(self.addr, self.temp)

 

    def write_data(self, buf):

        self.write_list[1] = buf

        self.i2c.writevto(self.addr, self.write_list)

 

 

class SSD1306_SPI(SSD1306):

    def __init__(self, width, height, spi, dc, res, cs, external_vcc=False):

        self.rate = 10 * 1024 * 1024

        dc.init(dc.OUT, value=0)

        res.init(res.OUT, value=0)

        cs.init(cs.OUT, value=1)

        self.spi = spi

        self.dc = dc

        self.res = res

        self.cs = cs

        import time

 

        self.res(1)

        time.sleep_ms(1)

        self.res(0)

        time.sleep_ms(10)

        self.res(1)

        super().__init__(width, height, external_vcc)

 

    def write_cmd(self, cmd):

        self.spi.init(baudrate=self.rate, polarity=0, phase=0)

        self.cs(1)

        self.dc(0)

        self.cs(0)

        self.spi.write(bytearray([cmd]))

        self.cs(1)

 

    def write_data(self, buf):

        self.spi.init(baudrate=self.rate, polarity=0, phase=0)

        self.cs(1)

        self.dc(1)

        self.cs(0)

        self.spi.write(buf)

        self.cs(1)

Micropython Src Code

from machine import Pin, I2C
import ssd1306
from time import sleep

# ESP32 Pin assignment
i2c = I2C(-1, scl=Pin(5), sda=Pin(4))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
oled.text(‘Welcome’, 0, 0)
oled.text(‘OLED Display’, 0, 10)
oled.text(‘welcome to iottrends.tech’, 0, 20)
oled.text(‘I am READY!! When you are?’, 0, 30)
oled.show()

Sample Output.

Welcome

OLED Display

Welcome to iottrends.tech

I am READY!! When you are?

Code Explanation

import ssd1306

This imports the OLED Library that was uploaded previously to the Board.

i2c = I2C(-1, scl=Pin(5), sda=Pin(4))

We are defining the I2C Pins of ESP32 Board here. The ESP32 default I2C pins are GPIO22 (SCL) and GPIO21 (SDA). In case of MakePython ESP32 Board, the GPIO Pins are GPIO5 (SCL) and GPIO4 (SDA)

oled_width = 128

oled_height = 64

This line defines the OLED height and width

oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)

Then we create an SSD1306_I2C object called oled. This object accepts the OLED width, height, and the I2C pins defined earlier.

oled.text(‘Welcome’, 0, 0)

oled.text(‘OLED Display’, 0, 10)

Using oled we are initializing the OLED display & using the text() function we are write text.
oled.show()

Using this line we call the show() method to update the OLED.

ESP32 – MicroSD

0

1. Introduction

With little data, we can store them in flash memory or eeprom of microcontrollers. But in the process of working with applications and projects that require storing large amounts of data, they must have memory expansion modules. A microSD card is one of the easiest ways to expand memory with a large capacity, at an affordable price. In this article, I will guide you to connect as well as write and read microSD card data with ESP32 using visual studio code included with IO IDE platform.

2. Prepare

2.1. Hardware

In this project, they will need to use the esp32 module, specifically I chose esp32 wroom devkit v1. Picture below
The choice of the microSD card module is also very important, there are many forms of communication between the microSD card module and the microcontroller such as SDIO or SPI. We’re using the microSD card module shown in the following figure – it communicates using SPI communication protocol. You can use any other microSD card module with an SPI interface.

The microSD card is the smallest consumer-focused flash memory card in use today. It’s a variation of the standard SD card (short for Secure Digital) and uses a similar set of electrical connections. That makes it possible to use microSD cards in standard SD card slots with the use of an adapter. MicroSD was introduced as a smaller alternative for portable electronics (picture below).

As you might expect, the microSD card is used to hold large volumes of data in devices that benefit from its miniature design. Larger devices still rely on regular SD cards when practical because they support much larger capacities, but in particular, devices like smartphones, dash cams, and small cameras (like action cameras) rely on the microSD card for its tiny shape.

3. SENSOR-MODULE/EXPANSION BOARD PINOUT DIAGRAM

3.1. Hardware

3.1.1. ESP32

ESP32-WROOM-32 is a powerful, generic Wi-Fi+BT+BLE MCU module that targets a wide variety of applications, ranging from low-power sensor networks to the most demanding tasks, such as voice encoding, music streaming and MP3 decoding.

 At the core of this module is the ESP32-D0WDQ6 chip*. The chip embedded is designed to be scalable and adaptive. There are two CPU cores that can be individually controlled, and the CPU clock frequency is adjustable from 80 MHz to 240 MHz. The chip also has a low-power co-processor that can be used instead of the CPU to save power while performing tasks that do not require much computing power, such as monitoring of peripherals. ESP32 integrates a rich set of peripherals, ranging from capacitive touch sensors, Hall sensors, SD card interface, Ethernet, high-speed SPI, UART, I²S and I²C.

3.1.2. Module microSD card

The micro- SD Card Module is a simple solution for transferring data to and from a standard SD card. The pin out is directly compatible with Arduino, but can also be used with other microcontrollers. It allows you to add mass storage and data logging to your project.

This module has SPI interface which is compatible with any sd card and it use 5V or 3.3V power supply which is compatible with Arduino UNO/Mega, ESP8266, ESP32.

SD module has various applications such as data logger, audio, video, graphics. This module will greatly expand the capability an Arduino can do with their poor limited memory.

Specifications

+ Working Voltage: 5V/3.3V

+ Size:20x28mm

+ Interface: SPI

+ Compatible: MicroSD

3.2. Software tool

Instead of choosing to work with the Arduino IDE project, in this project I chose the visual studio code with the PlatformIO IDE extension.It offers convenience as well as accompanying support.

4. Progress

Connection between ESP32 and microSD card module

The microSD card module communicates using SPI communication protocol. You can connect it to the ESP32 using the default SPI pins.

+ VCC pin supplies power for the module and should be connected to 5V pin on the Arduino.

+ GND should be connected to the ground of Arduino.

+ MISO (Master In Slave Out) is SPI output from the Micro SD Card Module.

+ MOSI (Master Out Slave In) is SPI input to the Micro SD Card Module.

+ SCK (Serial Clock) pin accepts clock pulses which synchronize data transmission generated by Arduino

+ SS (Slave Select) pin is used by Arduino(Master) to enable and disable specific devices on SPI bus.

Wiring Diagram

Source code

+ Copy folder SD in library previously downloaded into folder lib of project
+ Choose example do you want in forder example to play with microSD card

Program output
SD- card Data rate(read/write) like sending file over ftp or something.

ESP32-ESP8266 – DTH11 SENSOR

0

1. Introduction

Currently, with the continuous development of science and technology, all daily activities are automated, robots gradually take over many positions in our daily lives. In order to have the correct and efficient operation of automation devices, sensors are one of the key components. Motion sensors are one of them, which can help detect the movement of people or objects, thereby helping mechanical devices have the correct control signals.

In this article, we will show you how to connect and operate the PIR motion sensor with ESP32-ESP8266 using visual studio code included with the IO IDE platform. Through this tutorial, you will be able to apply motion sensors to your projects, making your products smarter.

2. SENSOR-MODULE/EXPANSION BOARD PINOUT DIAGRAM

2.1. Hardware Introduction

2.1.1. Module ESP32

In this project, they will need to use the esp32 module, specifically I chose esp32 wroom devkit v1. Picture below

ESP32-WROOM-32 is a powerful, generic Wi-Fi+BT+BLE MCU module that targets a wide variety of applications, ranging from low-power sensor networks to the most demanding tasks, such as voice encoding, music streaming and MP3 decoding.

At the core of this module is the ESP32-D0WDQ6 chip*. The chip embedded is designed to be scalable and adaptive. There are two CPU cores that can be individually controlled, and the CPU clock frequency is adjustable from 80 MHz to 240 MHz. The chip also has a low-power co-processor that can be used instead of the CPU to save power while performing tasks that do not require much computing power, such as monitoring of peripherals. ESP32 integrates a rich set of peripherals, ranging from capacitive touch sensors, Hall sensors, SD card interface, Ethernet, high-speed SPI, UART, I²S and I²C.

2.1.2. ESP8266

Espressif’s ESP8266EX delivers highly integrated Wi-Fi SoC solution to meet users’ continuous demands for efficient power usage, compact design and reliable performance in the Internet of Things industry.
With the complete and self-contained Wi-Fi networking capabilities, ESP8266EX can perform either as a standalone application or as the slave to a host MCU. When ESP8266EX hosts the application, it promptly boots up from the flash. The integrated highspeed cache helps to increase the system performance and optimize the system memory. Also, ESP8266EX can be applied to any microcontroller design as a Wi-Fi adaptor through SPI/SDIO or UART interfaces.

ESP8266EX integrates antenna switches, RF balun, power amplifier, low noise receive amplifier, filters and power management modules. The compact design minimizes the PCB size and requires minimal external circuitries.

Besides the Wi-Fi functionalities, ESP8266EX also integrates an enhanced version of Tensilica’s L106 Diamond series 32-bit processor and on-chip SRAM. It can be interfaced with external sensors and other devices through the GPIOs. Software Development Kit (SDK) provides sample codes for various applications.

Espressif Systems’ Smart Connectivity Platform (ESCP) enables sophisticated features including:

  • Fast switch between sleep and wakeup mode for energy-efficient purpose;
  • Adaptive radio biasing for low-power operation
  • Advance signal processing
  • Spur cancellation and RF co-existence mechanisms for common cellular, Bluetooth, DDR, LVDS, LCD interference mitigation

ESP8266 Specifications

2.1.3. DHT11

DHT11 output calibrated digital signal. It applies exclusive digital-signal-collecting-technique and humidity sensing technology, assuring its reliability and stability. Its sensing elements is connected with 8-bit single-chip computer.

Every sensor of this model is temperature compensated and calibrated in accurate calibration chamber and the calibration-coefficient is saved in type of programmer in OTP memory, when the sensor is detecting, it will cite coefficient from memory.

Small size & low consumption & long transmission distance(100m) enable DHT11 to be suited in all kinds of harsh application occasions. Single-row packaged with four pins, making the connection very convenient.

Operating specifications:

Power and Pins : Power’s voltage should be 3.3-5.5V DC. When power is supplied to sensor, don’t send any instruction to the sensor within one second to pass unstable status. One capacitor valued 100nF can be added between VDD and GND for wave filtering.
Communication and signal: 1-wire bus is used for communication between MCU and DHT11.

2.1.4. LCD 16x2 – I2C

The term LCD stands for liquid crystal display. It is one kind of electronic display module used in an extensive range of applications like various circuits & devices like mobile phones, calculators, computers, TV sets, etc. These displays are mainly preferred for multi-segment light-emitting diodes and seven segments. The main benefits of using this module are inexpensive; simply programmable, animations, and there are no limitations for displaying custom characters, special and even animations, etc.

Features of LCD16x2:

+ The operating voltage of this LCD is 4.7V-5.3V
+ It includes two rows where each row can produce 16-characters.
+ The utilization of current is 1mA with no backlight
+ Every character can be built with a 5×8 pixel box
+ The alphanumeric LCDs alphabets & numbers
+ Is display can work on two modes like 4-bit & 8-bit
+ These are obtainable in Blue & Green Backlight
+ It displays a few custom generated characters

I2C Serial Interface Adapter

It is also known as I2C Module. It has total of 20 male pins. 16 pins are faced to rear side and 4 pins faced towards front side. The 16 pins for connect to 16×2 LCD and the 2 pins out of 4 pins are SDA and SCL. SDA is the serial data pin and SCL is the clock pin. The rest 2 pins for power supply (Vcc and ground).There is a POT on the I2C Module. We can control the contrast of the LCD display by rotating this POT. And there is a jumber fixed on the module. When we remove the jumber, the backlight of the LCD display will go OFF.

2.2. How to connect

Source code:

Source esp32:

#include <Arduino.h>

#include <DHT.h>

#include <Wire.h>

#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,16,2);

 const int DHTPIN = 15;

const int DHTTYPE = DHT11;

DHT dht(DHTPIN, DHTTYPE);

 byte degree[8] = {

  0B01110,

  0B01010,

  0B01110,

  0B00000,

  0B00000,

  0B00000,

  0B00000,

  0B00000

};

void setup() {

  lcd.init(); 

  lcd.backlight();

  lcd.print(“Temper: “);

  lcd.setCursor(0,1);

  lcd.print(“Humidity: “);

  lcd.createChar(1, degree);

  dht.begin(); 

}

void loop() {

  float h = dht.readHumidity();

  float t = dht.readTemperature();

  if (isnan(t) || isnan(h)) {

  }

  else { lcd.setCursor(10,0);
 lcd.print(round(t));

    lcd.print(” “);

    lcd.write(1);

    lcd.print(“C”);

 lcd.setCursor(10,1);

    lcd.print(round(h));

    lcd.print(” %”);   

  }

}

Source Code esp8266

#include <Arduino.h>

#include <DHT.h>

#include <Wire.h>

#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,16,2);

const int DHTPIN = D4;

const int DHTTYPE = DHT11;

DHT dht(DHTPIN, DHTTYPE);

byte degree[8] = {

  0B01110,

  0B01010,

  0B01110,

  0B00000,

  0B00000,

  0B00000,

  0B00000,

  0B00000

};

 void setup() {

  lcd.init(); 

  lcd.backlight();

  lcd.print(“Temper: “);

  lcd.setCursor(0,1);

  lcd.print(“Humidity: “);

  lcd.createChar(1, degree);

  dht.begin(); 

}

void loop() {

  float h = dht.readHumidity();

  float t = dht.readTemperature();

if (isnan(t) || isnan(h)) {

}

else

{

lcd.setCursor(10,0);

lcd.print(round(t));

lcd.print(” “);

lcd.write(1);

lcd.print(“C”);

lcd.setCursor(10,1);

lcd.print(round(h));

lcd.print(” %”);

}

}

ESP32-ESP8266 – MOTION SENSOR

0

1. Introduction

Currently, with the continuous development of science and technology, all daily activities are automated, robots gradually take over many positions in our daily lives. In order to have the correct and efficient operation of automation devices, sensors are one of the key components. Motion sensors are one of them, which can help detect the movement of people or objects, thereby helping mechanical devices have the correct control signals.
In this article, we will show you how to connect and operate the PIR motion sensor with ESP32-ESP8266 using visual studio code included with the IO IDE platform. Through this tutorial, you will be able to apply motion sensors to your projects, making your products smarter.

2. SENSOR-MODULE/EXPANSION BOARD PINOUT DIAGRAM

2.1. Hardware Introduction

2.1.1. Module ESP32

In this project, they will need to use the esp32 module, specifically I chose esp32 wroom devkit v1. Picture below
ESP32-WROOM-32 is a powerful, generic Wi-Fi+BT+BLE MCU module that targets a wide variety of applications, ranging from low-power sensor networks to the most demanding tasks, such as voice encoding, music streaming and MP3 decoding.
At the core of this module is the ESP32-D0WDQ6 chip*. The chip embedded is designed to be scalable and adaptive. There are two CPU cores that can be individually controlled, and the CPU clock frequency is adjustable from 80 MHz to 240 MHz. The chip also has a low-power co-processor that can be used instead of the CPU to save power while performing tasks that do not require much computing power, such as monitoring of peripherals. ESP32 integrates a rich set of peripherals, ranging from capacitive touch sensors, Hall sensors, SD card interface, Ethernet, high-speed SPI, UART, I²S and I²C.

2.1.2. Module ESP8266

Espressif’s ESP8266EX delivers a highly integrated Wi-Fi SoC solution to meet users’ continuous demands for efficient power usage, compact design and reliable performance in the Internet of Things industry.

With the complete and self-contained Wi-Fi networking capabilities, ESP8266EX can perform either as a standalone application or as the slave to a host MCU. When ESP8266EX hosts the application, it promptly boots up from the flash. The integrated high speed cache helps to increase the system performance and optimize the system memory. Also, ESP8266EX can be applied to any microcontroller design as a Wi-Fi adapter through SPI/SDIO or UART interfaces.

With the complete and self-contained Wi-Fi networking capabilities, ESP8266EX can perform either as a standalone application or as the slave to a host MCU. When ESP8266EX hosts the application, it promptly boots up from the flash. The integrated high speed cache helps to increase the system performance and optimize the system memory. Also, ESP8266EX can be applied to any microcontroller design as a Wi-Fi adapter through SPI/SDIO or UART interfaces.

Besides the Wi-Fi functionalities, ESP8266EX also integrates an enhanced version of Tensilica’s L106 Diamond series 32-bit processor and on-chip SRAM. It can be interfaced with external sensors and other devices through the GPIOs. Software Development Kit (SDK) provides sample codes for various applications.

Espressif Systems’ Smart Connectivity Platform (ESCP) enables sophisticated features including:

  • Fast switch between sleep and wakeup mode for energy-efficient purpose;
  • Adaptive radio biasing for low-power operation
  • Advance signal processing
  • Spur cancellation and RF coexistence mechanisms for common cellular, Bluetooth, DDR, LVDS, LCD interference mitigation

Motion sensor

A motion sensor (or motion detector) is the linchpin of your security system because it detects when someone is in your home when they shouldn’t be. A motion sensor uses one or multiple technologies to detect movement in an area.

When a sensor detects motion, it sends a signal to your security system’s control panel, which connects to your monitoring center. This alerts you and the monitoring center to a potential threat in your home.

Types of motion sensors:

Passive infrared (PIR)

A passive infrared sensor detects body heat (infrared energy) by looking for changes in temperatures. This is the most-widely-used motion sensor in home security systems. When you arm your system, this activates the motion sensors to report possible threats.

A passive infrared sensor detects body heat (infrared energy) by looking for changes in temperatures. This is the most-widely-used motion sensor in home security systems. When you arm your system, this activates the motion sensors to report possible threats.

Microwave (MW)

This type of sensor sends out microwave pulses and measures the reflections off of moving objects.1 They cover a larger area than infrared sensors but are more expensive and vulnerable to electrical interference.

Dual technology motion sensors

Some motion sensors can combine multiple detection methods in an attempt to reduce false alarms. For example, it’s not uncommon for a dual technology sensor to combine a passive infrared (PIR) sensor with a microwave sensor.

Each sensor type operates in different areas of the spectrum (ranging from passive to active). Dual technology motion sensors are not as likely as other types to cause a false alarm, because both sensors need to trip in order to sound an alarm. However, this does not mean that they never cause false alarms.

In this tutorial, I will use PIR sensor (picture 6)

Specification for PIR Sensor:

+ Voltage: 5V – 20V
+ Power Consumption: 65mA
+ TTL output: 3.3V, 0V
+ Delay time: Adjustable (.3->5min)
+ Lock time: 0.2 sec
+ Trigger methods: L – disable repeat trigger, H enable repeat trigger
+ Sensing range: less than 120 degree, within 7 meters
+ Temperature: – 15 ~ +70
+ Dimension: 32*24 mm, distance between screw 28mm, M2, Lens dimension in diameter: 23mm

PIR Sensor Pinout

2.1.3.Module relay

The relay module is an electrically operated switch that allows you to turn on or off a circuit using voltage and/or current much higher than a microcontroller could handle. There is no connection between the low voltage circuit operated by the microcontroller and the high power circuit. The relay protects each circuit from each other.

Each channel in the module has three connections named NC, COM, and NO. Depending on the input signal trigger mode, the jumper cap can be placed at high level effective mode which ‘closes’ the normally open (NO) switch at high level input and at low level effective mode which operates the same but at low level input.

Relay Module Specification:

+ On-board EL817 photoelectric coupler with photoelectric isolating anti interference ability strong
+ On-board 5V, 10A / 250VAC, 10A / 30VDC relays
+ Relay long life can absorb 100000 times in a row
+ Module can be directly and MCU I/O link, with the output signal indicator
+ Module with diode current protection, short response time

Relay Module PIN Specifications

2.2. ESP32 Connectivity Diagram

ESP32 PIR Circuit Diagram

ESP32 PIR Sensor Actual circuit Diagram

ESP8266 Connectivity Diagram

ESP8266 PIR Motion Sensor Circuit Diagram

Source code:

Source Code ESP32:

#include <Arduino.h>
#define PIN_PIR       25
#define PIN_RELAY     26
void setup()
{
 Serial.begin(115200);
z                       pinMode(PIN_PIR,INPUT);  // set pin 7 input
                              pinMode(PIN_RELAY,OUTPUT); // set pin 2 output

  digitalWrite(PIN_RELAY,LOW); // turn off relay
}
void loop()
{
  if (digitalRead(PIN_PIR) == true)
                                 {

                        Serial.println(“have motion”);
                  digitalWrite(PIN_RELAY,HIGH);
                  delay(5000); // turn on light 5s
                digitalWrite(PIN_RELAY,LOW);
                                 } 

}

Source esp8266

#include <Arduino.h>
#define PIN_PIR       D2
#define PIN_RELAY     D5
void setup()
{
 Serial.begin(115200);
  pinMode(PIN_PIR,INPUT);  // set pin D2 input
                         pinMode(PIN_RELAY,OUTPUT); // set pin D5 output
  digitalWrite(PIN_RELAY,LOW); // turn off relay
}
void loop()
{
 if (digitalRead(PIN_PIR) == true)
                                 {

                 Serial.println(“have motion”);
               digitalWrite(PIN_RELAY,HIGH);
                        delay(5000); // turn on light 5s
                 digitalWrite(PIN_RELAY,LOW);
                                } 

}

ARDUINO – MOTION SENSOR

0

1. Introduction

Currently, with the continuous development of science and technology, all daily activities are automated, robots gradually take over many positions in our daily lives. In order to have the correct and efficient operation of automation devices, sensors are one of the key components. Motion sensors are one of them, which can help detect the movement of people or objects, thereby helping mechanical devices have the correct control signals.
In this article, we will show you how to connect and operate the PIR motion sensor with Arduino Uno R3 using visual studio code included with IO IDE platform. Through this tutorial, you will be able to apply motion sensors to your projects, making your products smarter.

2. SENSOR-MODULE/EXPANSION BOARD PINOUT DIAGRAM

2.1. Hardware Introduction

2.1.1. Arduino UNO R3

Arduino Uno is a microcontroller board based on the ATmega328P (datasheet). It has 14 digital input/output pins (of which 6 can be used as PWM outputs), 6 analog inputs, a 16 MHz ceramic resonator (CSTCE16M0V53-R0), a USB connection, a power jack, an ICSP header and a reset button. It contains everything needed to support the microcontroller; simply connect it to a computer with a USB cable or power it with a AC-to-DC adapter or battery to get started. You can tinker with your Uno without worrying too much about doing something wrong, worst case scenario you can replace the chip for a few dollars and start over again.
“Uno” means one in Italian and was chosen to mark the release of Arduino Software (IDE) 1.0. The Uno board and version 1.0 of Arduino Software (IDE) were the reference versions of Arduino, now evolved to newer releases. The Uno board is the first in a series of USB Arduino boards, and the reference model for the Arduino platform; for an extensive list of current, past or outdated boards see the Arduino index of boards.

Features

ATMega328P Processor

Memory

+ AVR CPU at up to 16 MHz
+ 32KB Flash
+ 2KB SRAM
+ 1KB EEPROM

Security

+ Power On Reset (POR)
+ Brown Out Detection (BOD)

+ Power On Reset (POR) + Brown Out Detection (BOD)

Peripherals

+ 2x 8-bit Timer/Counter with a dedicated period register and compare channels
+ 1x 16-bit Timer/Counter with a dedicated period register, input capture and compare channels
+ 1x USART with fractional baud rate generator and start-of-frame detection
+ 1x controller/peripheral Serial Peripheral Interface (SPI)
+ 1x Dual mode controller/peripheral I2C
+ 1x Analog Comparator (AC) with a scalable reference input
+ Watchdog Timer with separate on-chip oscillator
+ Six PWM channels
+ Interrupt and wake-up on pin change

Power

+ 2.7-5.5 volts

2.1.2. Motion sensor

A motion sensor (or motion detector) is the linchpin of your security system because it detects when someone is in your home when they shouldn’t be. A motion sensor uses one or multiple technologies to detect movement in an area.
When a sensor detects motion, it sends a signal to your security system’s control panel, which connects to your monitoring center. This alerts you and the monitoring center to a potential threat in your home.

Types of motion sensors:

Passive infrared (PIR)

A passive infrared sensor detects body heat (infrared energy) by looking for changes in temperatures. This is the most-widely-used motion sensor in home security systems. When you arm your system, this activates the motion sensors to report possible threats.
A passive infrared sensor detects body heat (infrared energy) by looking for changes in temperatures. This is the most-widely-used motion sensor in home security systems. When you arm your system, this activates the motion sensors to report possible threats.

Microwave (MW)

This type of sensor sends out microwave pulses and measures the reflections off of moving objects.1 They cover a larger area than infrared sensors but are more expensive and vulnerable to electrical interference.

Dual technology motion sensors

Some motion sensors can combine multiple detection methods in an attempt to reduce false alarms. For example, it’s not uncommon for a dual technology sensor to combine a passive infrared (PIR) sensor with a microwave sensor.

Each sensor type operates in different areas of the spectrum (ranging from passive to active). Dual technology motion sensors are not as likely as other types to cause a false alarm, because both sensors need to trip in order to sound an alarm. However, this does not mean that they never cause false alarms.
In this tutorial, I will use PIR sensor (picture 6)

Specification:

+ Voltage: 5V – 20V
+ Power Consumption: 65mA
+ TTL output: 3.3V, 0V
+ Delay time: Adjustable (.3->5min)
+ Lock time: 0.2 sec
+ Trigger methods: L – disable repeat trigger, H enable repeat trigger
+ Sensing range: less than 120 degree, within 7 meters
+ Temperature: – 15 ~ +70
+ Dimension: 32*24 mm, distance between screw 28mm, M2, Lens dimension in

diameter: 23mm

2.1.3. Module relay

The relay module is an electrically operated switch that allows you to turn on or off a circuit using voltage and/or current much higher than a microcontroller could handle. There is no connection between the low voltage circuit operated by the microcontroller and the high power circuit. The relay protects each circuit from each other.
The each channel in the module has three connections named NC, COM, and NO. Depending on the input signal trigger mode, the jumper cap can be placed at high level effective mode which ‘closes’ the normally open (NO) switch at high level input and at low level effective mode which operates the same but at low level input.

Specification:

+ On-board EL817 photoelectric coupler with photoelectric isolating antiinterference ability strong
+ On-board 5V, 10A / 250VAC, 10A / 30VDC relays
+ Relay long life can absorb 100000 times in a row
+ Module can be directly and MCU I/O link, with the output signal indicator
+ Module with diode current protection, short response time

2.2. How to connect

Source code:

#include <Arduino.h>
#define PIN_PIR       7
#define PIN_RELAY     2
void setup()
{
Serial.begin(115200);
pinMode(PIN_PIR,INPUT);  // set pin 7 input
pinMode(PIN_RELAY,OUTPUT); // set pin 2 output
digitalWrite(PIN_RELAY,LOW); // turn off relay
}
void loop()
{
if (digitalRead(PIN_PIR) == true)
{
Serial.println(“have motion”);
digitalWrite(PIN_RELAY,HIGH);
delay(5000); // turn on light 5s
digitalWrite(PIN_RELAY,LOW);
}
}