Build a People Counter for $30 Using an ESP8266 and NodeMCU

DZone 's Guide to

Build a People Counter for $30 Using an ESP8266 and NodeMCU

Want to get an idea of how many people are coming and going in an area? Build your own counter with minimal hardware, Ubidots Cloud, and the Arduino IDE.

· IoT Zone ·
Free Resource

A people counter is a device that used to measure the number of people traversing an entrance, hallway, street corner, etc. If you need to know how many people exist in a space, this is your simple solution. Mostly used in retail stores, shopping malls, and smart office buildings, this counting technology has provided insight to how shoppers/employers behave.

How is the people counter application applicable to you (other than just being really cool technology)? Imagine you're the owner of a shop; this counter would alert you to daily visitors, the walking paths taken when inside, where they stop, and how long they linger at in a place. Wouldn't you like to know what materials gain the most attention; possibly being able to reposition products geographically to increase awareness to benefit your customers' needs and your bottom line? 

In this guide, you will learn how to build your own home-made people counter. Also included are instructions for you newly collected data to be utilized via Ubidots, an application enablement platform. 

Materials required 

  • ESP8266 NodeMCU
  • PIR motion sensor
  • Female-female wires
  • Plastic protection case
  • MicroUSB Cable

Wiring and Casing 

As you can see, the motion sensor has three pins: V+, Ground, and a third for outputs signal ("1" = movement, and "0" static environment). First, plug the cables straight to the pins of your NodeMCU, follow the table and diagram below:

NodeMCU  -> PIR Sensor    -    NodeMCU  ->  LED

       GND     ->       GND         -        GND       ->  GND
         D6      ->        OUT        -           D4        ->  VCC
        3.3V    ->        VCC        -           - - -        -     - - -

Because the sensor is very sensitive to movement, I used the jumper switch behind it to set the lowest sensibility. I also painted over the lens corners to focus on one specific space instead of omnidirectional. (This was for my liking, but please explore and innovate as you see fit). The results of these few extra minutes of work were a friendly, contained device.

With the case and device pieced together, we now need to connect with Arduino IDE

To start, connect your NodeMCU to your computer's port using the micro USB

Note: If you do not already have the Arduino IDE, click here to download.

Open the Arduino IDE, then select Files -> Preferences.

Next, input the following URL into the Additional Board Manager URLs text box. You can add multiple URLs, separating them with commas if needed: 


Note: If you're a Mac user, please note that Arduino and File contain different drop down functions compared to Windows. Also, you will need to install the following driver to be able to upload your NodeMCU.

Open Boards Manager from Tools -> Board menu and install te ESP8266 platform. To simply find the correct device, search ESP8266 within the search bar. 

Select your NodeMCU 1.0 (ESP-12 Module) from the Tools > Board menu.

Additionally, we need to be able to communicate with the NodeMCU, and we also need to select the port com. 

Go to Tools > Port >  Select the appropriate PORT for your computer/device connection.

Also, to keep everything running fast and smooth, let's make sure the upload speed is optimized to 115200. 

Go to Tools > Upload Speed > 115200:

Next, we need to download the Ubidots MQTT ESP library from GitHub. To do this, open the MQTT ESP library here, then download the library by clicking the green button called "Clone or download" and select "Download ZIP".

Now move back to your Arduino IDE and click on Sketch -> Include Library -> Add .ZIP Library.

Select the ZIP file of ubidotsMQTTESP and then “Accept” or “Choose”.

If successful, you will receive a confirmation message in the Arduino IDE confirming your library.

Next, go to Sketch/Program -> Include Library -> Library Manager and install the PubSubClient library. To simply find the correct library, search PubSubClient within the search bar.  

Close the Arduino IDE and open it again. A restart is required. Please do not miss this step!!

Now it is time to start coding!

Copy the code below and paste it into the Arduino IDE.

Once you have copied the code, you will need to assign the parameters: Wi-Fi name and password, plus your individual, unique Ubidots TOKEN. If you don't know how to locate your Ubidots TOKEN, please reference this article below. 


 * Include Libraries
#include "UbidotsESPMQTT.h"
 * Define Constants
#define TOKEN "..." // Your Ubidots TOKEN
#define WIFINAME "..." //Your SSID
#define WIFIPASS "..." // Your Wifi Pass
#define MQTTCLIENTNAME "..." // Your MQTT Client Name, it must be unique so we recommend to choose a random ASCCI name
#define DEVICE "pir-sensor" // Assign the device label
#define VARIABLE "motion" // Assign the variable label
#define LED 2# define SENSOR D6uint8_t contador = 0;

unsigned long estado = 0;

 * Auxiliar Functions
void callback(char * topic, byte * payload, unsigned int length) {
    Serial.print("Message arrived [");
    Serial.print("] ");
    for (int i = 0; i < length; i++) {
        Serial.print((char) payload[i]);
 * Main Functions
void setup() {
    // put your setup code here, to run once:
    pinMode(SENSOR, INPUT);
    pinMode(LED, OUTPUT);
    client.wifiConnection(WIFINAME, WIFIPASS);
void loop() {
    // put your main code here, to run repeatedly:
    if (!client.connected()) {
        digitalWrite(LED, LOW);
        digitalWrite(LED, HIGH);
    } else {
        digitalWrite(LED, HIGH);
    uint8_t sensorValue = digitalRead(SENSOR);
    bool flag = false;

    if (sensorValue > 0) {
        for (uint8_t espera = 0; espera <= 4; espera++) {
            sensorValue = digitalRead(SENSOR);
            if (sensorValue == 1) {
            if (contador > 3) {
                flag = true;
    Serial.println("sending data");

    uint8_t value;
    if (flag) {
        value = 1;
        client.add(VARIABLE, value);
    } else {
        value = 0;
        if (estado == 10000) {
            client.add(VARIABLE, value);
            estado = 0;
    contador = 0;

Once you pasted the code and updated the Wi-Fi parameters, you must verify this within the Arduino IDE. To do this, in the top left corner of our Arduino IDE, you will see the icons below. Choose the checkmark icon to verify any code.

Image title

Once the code is verified, you will receive a "Done compiling" message in the Arduino IDE.

Next, you have to upload the code into your NodeMCU. To do this, choose the right-arrow icon beside the check mark icon. 

Image title

Once the code is uploaded, you will receive a "Done uploading" message in the Arduino IDE.

Now your sensor is sending the data to the Ubidots Cloud!

Status LED

Once your code is uploaded, the onboard LED will alert you to the device's connectivity.

  • LED on -> Ok, the device is connected and sending data.
  • LED blink (1 second) -> Trying to reconnect. Lost the connection. No access to the Internet.
  • LED off -> Device not connected.

Data Management in Ubidots 

If your device is correctly connected, you will see a new device created within the device section in your Ubidots application. The name of the device will be "sensor-pir". Also, inside the device, you will see the variable created called "motion."

If you desire to change your device and variable names to more friendly ones, please reference this article

Next, to count a number of people your device is detecting, we need to create a new derived variable to be able to manage the data and count a number of people detected. 

Click on "Add variable" and select "Rolling window":

Image title

Select the device called "pir-sensor" and the variable "motion", then compute the sum every time set as you desire (1 minute; 1 hour; 1 day) to get the number of people detected. Press Save and assign a name for the variable.

Image title

Once your variable is created, you will receive the number of people detected on that variable. Below is an illustration of the final result:

Image title


This project educates administrators and decision makers to a number of people passing through a particular space and how they operate. Please note that not every person will be detected due to limitations of the motion sensor. Line of sight is important for us humans, and machines struggle with this too. But we are working on it!

arduino ide ,esp8266 ,iot ,nodemcu ,tutorial

Published at DZone with permission of Maria Hernandez , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}