Saturday, May 22, 2021

ESP8266 and ESP32 Sending messages to WhatsApp !!!

 For an index to all my stories click this text.

Have your ESP send messages to WhatsApp !!!

Please be aware that there is a small problem with the code in this story. The HTTPClient library has been changed. For an update on how to alter the program on this page look here : HTTPClient library update

As you know I have several ESP's running various IOT tasks in my home. Some are connected to my Domoticz home automation system and some are not. And what I want from some of these ESP's is to send me a message on my phone when something has happened. Something means somebody ringing my door, a door opening, a temperature rising too high etc.

I used to use IFTTT for that but since they limited their free service so much that it is not workable anymore I stopped using their service. Hey I am Dutch remember. I like things that are free.

So I was looking for an alternative to have my ESP's sending messages to my phone. Blynk certainly is an option and I already wrote some stories on that. And then I stumbled upon a great service that allows my ESP's sending messages to my WhatsApp account.

Whatsapp has a develloper program in which you can get access to their API's. That could be used. However this is only intended for corporations and not for private persons like me. Next to that there is a possibillity to have ESP's send messages to Whatsapp using Twillio. Twillio however is a paid service. And I am looking for a free service.

And out of the blue I found one. It is called CallMeBot. As this project demonstrates it works like a charm. There is only one small limitation. You are (at this moment) only allowed to send 25 messages to Whatsapp in 240 minutes. That is about one message per 10 minutes. For real life purposes that is enough. When intensively testing this might be a small problem.

CallMeBot

I presume that you already have installed WhatsApp on your phone, and are familiar with how it works. To send messages to WhatsApp from your ESP8266 or ESP32 you need to make use of a service called CallMeBot. And that is free !!! You can find their website here: https://www.callmebot.com/

CallMeBot uses a Bot which can be freely translated as a software robot. It operates as an intermediary between a microcontroller or computer or anything that can send a get-requests and WhatsApp. Sounds complicated but in reality it is not.

Activate the CallMeBot.

The first step is to add the Bot to your contacts list on your phone. Just do this the same way as you would do when adding a new person in your phone's contact list. You can give this contact any name you like. I gave mine, how surprising,  the name CallMeBot. Add the telephone number. You can find it at the CallMeBot webpage but I'll copy it here for you: +34 644 20 47 56

Edit: a reader pointed out to me that after I wrote this story CallMeBot had changed the telephone number in: +34 644 97 54 14

 
So please check the CallMeBot webpage for the actual phonenumber when you are reading this.
The reason why you need to do this is that this way the Bot will show up in your WhatsApp contacts.

So indeed now open WhatsApp and search in your contacts for CallMeBot or whatever name you chose.

Now you need to give the CallMeBot permission to send messages to you. This is done by sending the following message to the CallMeBot: I allow callmebot to send me messages. Please notice that in the message callmebot is spelled without capitals.



After a short while you will get a message back. This might take some time, depending on how busy the service is. When I activated the service it took almost 2 minutes before the Bot replied.

If you are wondering how I made this screenshot and how to copy/paste info from Whatsapp on my PC: Use the Whatsapp web version.

The reply consists actually of 2 messages. The first one is:

CallMeBot API Activated for +XXXXXXXXXXX
Your apikey is: YYYYYYY


The CallMeBot informs you that the Bot is activated for Phonenumber XXXXXXXXXXX which is your phonenumber, and that your API key is YYYYYYY.
Make sure to save the API key in a safe place. You will need it later on when we are going to send messages to Whatsapp.

You can now send messages using the API.
https://api.callmebot.com/whatsapp.php?phone=+XXXXXXXXXXXX&text=This+is+a+test&apikey=YYYYYY


This is the second message the CallMeBot sends. And this is a very important one as we are going to use the information in that message to build the ESP's software. Not only that we can use this for a first test.

First test

The great question off course always is: does it work. Well there is an easy way to test that.

Look at the second message CallMeBot send:

You can now send messages using the API.
https://api.callmebot.com/whatsapp.php?phone=+XXXXXXXXXXXX&text=This+is+a+test&apikey=YYYYYY


So, let us try that. Just paste this line in your browser and let's see what happens.



According to the webpage the message is send.



And yes there it is. The message was indeed send to the Callmebot contact in WhatsApp !!!! So this works. Next step is to get it working on the ESP.

Breadboard setup

As this is a test I am going to use a simple setup. I am going to attach a button to the ESP and thats all.



The button is attached with a pull-up resistor to D1 of the Wemos.

The ESP8266 program

I start with the complete listing and then get into the details.

// Simple trigger to send a message
// to Whatsapp 

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

const char* ssid = "YOUR-ROUTERS-NAME";
const char* password = "PASSWORD";

const int button = D1;
String tobesend;

void setup() 
  {
  pinMode(button, INPUT);
  
  Serial.begin(115200);
  delay(100);
    
  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");  
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());  
}

void loop() 
{
  if (digitalRead(button) == LOW)
    {
      Serial.print("connecting to ");
      Serial.println("whatsapp");


WiFiClient client;
HTTPClient http; //Declare an object of class HTTPClient //Specify request destination tobesend = "http://api.callmebot.com/whatsapp.php?"; tobesend = tobesend + "phone=+XXXXXXXXXXX"; tobesend = tobesend + "&text=The+button+on+the+ESP+was+pressed"; tobesend = tobesend + "&apikey=YYYYYY"; http.begin(client,tobesend); int httpCode = http.GET(); //Send the request if (httpCode > 0) { //Check the returning code String payload = http.getString(); //Get the request response payload Serial.println(payload); //Print the response payload } http.end(); //Close connection } }



As you can see it is just a normal program that starts the ESP8266Wifi library and the ESP8266HTTPClient library.

const char* ssid = "YOUR-ROUTERS-NAME";
const char* password = "PASSWORD";


Don't for get to put your routers credentials in here.

On the ESP8266 the button is attached to D1.
A string called tobesend is defined which will contain the URL that we are going to send to send a text to the CallMeBot.

In the setup nothing special either.
The button is defined as an INPUT, the serial port is opened and the wifi communication is started as we have done in many previous programs.

The loop is where the magic happens.

if (digitalRead(button) == LOW)

First we test if the button is pressed.

 HTTPClient http; //Declare an object of class HTTPClient

The HTTPClient library is activated and attached to http.

      tobesend = "http://api.callmebot.com/whatsapp.php?";
      tobesend = tobesend + "phone=+XXXXXXXXXXX";
      tobesend = tobesend + "&text=The+button+on+the+ESP+was+pressed";
      tobesend = tobesend + "&apikey=YYYYYY";

Remember from the beginning of this story that you can send messages to whatsapp by using the following line:
https://api.callmebot.com/whatsapp.php?phone=+XXXXXXXXXXXX&text=This+is+a+test&apikey=YYYYYY

Well here is the part where we build that line into the variable tobesend.
I splitted the line over multiple small lines to make it more useable in the program. Do not forget to alter the XXXXXXXX in your phone number and the YYYYYY in the apikey that was send to your whatsapp account.

I suppose you have noticed that the CallMeBot webpage showed that you need to use https (secure http). However the ESP is not up to that and luckily http works too !!!



As you can see it works flawless !!!!

The program is simple enough to alter to match your own needs. Attach a PIR to the ESP and have it send warnings when someone enters your room. Attach A Dallas DS18B20 and have the ESP send a warning when the temperature gets to high or to low. Use the filament sensor from this story: http://lucstechblog.blogspot.com/2020/05/filament-sensor-with-alarm-on-your-phone.html  and be warned if your 3D's printer filament is broken. There are hundreds of possibilities here.

Changing and expanding the message.

You can alter the text which has to be send in anything you like. There are however some rules for sending messages over http.

Spaces are not allowed. In our example we replaced the spaces with + which works just fine. You can also replace spaces with %20.

tobesend = tobesend + "&text=This%20is%20a%20test%0A";

This is how you would do that. The last part %0A is the newline character. This makes sure any text that follows is put on a new line.

Remember that you can only send text so any value that needs to be send to Whatsapp should be converted to a string.

temperature = 20;
tobesend = tobesend + String (temperature);


This is a valid way to convert a value to a String and add it to the text to be send.

ESP32

If you want to use the ESP32 to send messages to Whatsapp you need to make just small modifications to the program.

Just change:

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>


Into :

#include <WiFi.h>
#include <HTTPClient.h>


And use a different pin for attaching the button.

const int button = 34;

I normally use IO pin 34 for connecting a button but you can use any IO pin you like.

Concluding.

CallMeBot is a great way to send messages from your ESP's to your phone. WhatsApp notifies you when a message is received so you can get up to date info on anything that is important to you.

I am really happy that this works !!!
As I use Whatsapp a lot on my phone I it this is a most welcome addition.

Just be aware of the limitation of 25 messages per 240 minutes. That is a bit more as one message per 10 minutes. The limitation seems an obstruction when testing intensively but in real life projects it should not be a problem.

I am sure you find many ways to use this.

Till next time
Have fun.


Luc Volders






Friday, May 14, 2021

Android person counter

 For an index to all my stories click this text.

Due to the pandemic we are in, the company where I work is only allowed 50 people at the same time in our shop. Last time I showed you how to build a people counter using an ESP8266, some buttons and a TM1637 display. You can find that story here : http://lucstechblog.blogspot.com/2021/05/person-counter.html

That story I mentioned that I also build an Android App that did the same thing. Several people mailed me asking if they could get a copy, or where to download. Well the app is not in the play store. But at the end of this story there is a link where you can download it.

But I'll do better then that. I will show you ow it is build.

Mit's App Inventor

There are several ways to build an app for Android phones. One of the easiest ways is by using Mit's App Inventor. I have used App inventor for several projects on this weblog. Just look in the index page to find them : http://lucstechblog.blogspot.com/p/index-of-my-stories.html

App Inventor works with programming blocks, a system that is also used for (by example) programming BBC's Microbit and several other microcontrollers. It is originally derived from the programming language Scratch which you might know from the Raspberry Pi's.

App Inventor uses two screens to build an app. The first screen is where you design the app. Here you put buttons, text fields, picture fields etc etc on the screen. The second screen is where you do the programming and that is called the blocks screen.

Basically the first step is to put a button or text field etc on your screen. Then you give it a color, put an initial text in, decide upon text font, background color etc etc.
Next you move over to the blocks section and there add the program blocks that decide which action is performed when the button is clicked.

Sounds easy and it is.

App Inventor can be used to have your phone communicating with ESP8266's, ESP32's, your home automation system like Domoticz, or even with a Raspberry Pico using bluetooth. Give it a try. Look at my projects and use the blocks for your own purposes.

The Peoplecounter's blocks

The Peoplecounter app has 9 labels, 2 textboxes, 3 buttons and a picture on its screen.
When the app starts not all these fields are visible. Some have their visibility set to "false". They are not needed at the start of the app. 



The picture field is called canvas and is on the top left side of the screen. In my own version I have put the logo of our company in that field. You can do that by clicking on the canvas field and choosing a background image in the definition at the right side of the app designer. That logo will be build in, in the app when you make an APK from the blocks.

The first step is to fill in the number of customers that is maximally allowed in your shop. Press Ok and the initial fields vanish from the screen and the main fields appear.

Let's start with the complete blocks.



Let us examine the blocks in detail.



The app starts with initialising 3 variables. Teller (meaning counter) is used for registrating the number of people present at any time. Maxpersons is the maximum amount of persons allowed at the same time. totcust is the total number of customers that has visited the shop during that day.



This part of the app is run when the app is started, that is when the screen is initialised. The required fields are set visible. And the fields that are not required at the start have the visible parameter set to false.



In the initial screen you have to fill in the maximum number of people that is allowed at the same time in your shop. If you press the OK button this block is activated. The OK button is button3 in the app.
The initial fields will disappear and new fields and buttons will be shown.



Button1 is the button with 1+ as text. Pressing this button will add 1 person to the Teller variable and also 1 person to the totcust variable. So this adds 1 to the actual number of persons present and adds 1 to the total number of customers that were in the shop that day.



If the number of persons present (Teller) is larger as the number of persons that are allowed (maxpersons) then the text field is colored red as a warning. If the number of persons is within the allowed amount then the text fields background will be green.

The App

The app was tested on an old Alcatel C7 phone with (yes unbelievable) Android 4.2, My new (well relatively) Nokia 5 with Andoid 9 and on an Andoid emulator running Android 7. So you will not encounter problems when running it on your phone.

For testing purposes I often test apps first on the Android emulator before installing them on my phone. I use the LDplayer emulator which works fine on my windows machine. You can find a short revieuw on my weblog with this link: http://lucstechblog.blogspot.com/2021/03/ldplayer-android-emulator.html

 

I realise that the app's screen is not very fancy. As the source code is supplied at the end of this story you can alter it as much as you want and make it more visually attractive.

The app starts with questioning how many people are allowed at the same time in your shop. Fill the amount in, in the green field and then press ok. In this example I set the amount to 5 for testing purposes.



After pressing ok the screen changes and different fields are on display.

The +1 button adds 1 person. The -1 button subtracts one person. The amount of people present are shown in the green square at the top of the page.



Here the App has registrated that 4 people have entered the shop. This is also the total amount of people that visisted today as you can see in the blue line at the bottom of the screen.



The amount of people has increased to 6. As the maximum was set at 5 the field with the amount of people has changed color to red (danger).



Three people have left the shop. So the amount present is 3 but and the total amount that have visited today is still 6.



Another 2 people have entered the shop. So the total amount present is 5 and the total amount that have visisted the shop is at 8.

Why didn't my company choose for the App.

Well there is a small problem with using this app on your own phone. Suppose you are sitting at the door of the shop counting people. During lunch time it is someone else's turn to take your place. You are likely not willing to leave your pesonal phone in someone else's hands. He/she then has to use the same phone, or at least install the app on his own phone and take over the settings by pressing + and - several times.

Although my collegues have company phones they are reluctant to leave those phones in the hands of someone else. So that is why my company chose the ESP8266 peoplecounter version. Here is the link to that again: http://lucstechblog.blogspot.com/2021/05/person-counter.html

Get the sourcecode.

If you want to look at the sourcecode you have to get an account with MIT's App Inventor and then upload the AIA file to that account. You can find the AIA file here:
https://www.mediafire.com/file/00b0dv46tgcemhu/Peoplecounter_copy.aia/file

Get the App.

If you just want to play with the App you can download the APK file here:
https://www.mediafire.com/file/79mby3m72h68few/Peoplecounter_copy.apk/file

Download it and click on it and it will be installed on your phone.

That's it for now.
Have fun

Luc Volders














Friday, May 7, 2021

Person Counter part 2

For an index to all of my stories click this text

Last week I showed you my customer counter. I made it for the company where I work that has a webshop and a physical shop. Due to the pandemic we are only allowed 50 people max at the same time in our shop. So I designed a counter that manually keeps track of the number of people that are in the shop. You can re-read that story here http://lucstechblog.blogspot.com/2021/05/person-counter.html

The customer counter has a fixed number of 50 persons as maximum. And I wrote that I used an ESP8266 for this project as it has the ability to build a webpage that allows to set the maximum at a different number. That got me quite a lot of emails from people asking to publish the software for that.

Well I'll do better then that. This story gives you the software and I also designed a casing that can be 3D printed. You can find the design and STL files also in this story.

The Person Counter with webpage.

Here is the complete program.

// ======================================================
//            Customer counter program
// Webserver makes it possible to set the maximum
// number of customers
// Wemos D1 has 3 buttons attached to count customers
// intended for shop use during corona pandemic 
// when shops are allowed a maximum amount of customers
// By Luc Volders
// http://lucstechblog.blogspot.com/
// ======================================================

#include <TM1637Display.h>

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

#include <EEPROM.h>
#define EEPROM_SIZE 100

ESP8266WebServer server(80);

// Your routers credentials
const char* ssid = "YOUR-ROUTERS-NAME";
const char* password = "PASSWORD";


String textosend_string;


const int CLK = D6; //Set the CLK pin connection to the display
const int DIO = D5; //Set the DIO pin connection to the display

const int upbut = D1;
const int downbut  = D2;
const int totbut = D7;
 
int maxnum=0; 
int person = 0;
int total = 0;
 
TM1637Display display(CLK, DIO); //set up the 4-Digit Display.

// =========================================
// Here is the HTML page
// =========================================
String getPage()
  {
  String page = "<!DOCTYPE HTML>";
  page += "<html>";
  page += "<head>";
  page += "<meta name = \"viewport\" content = \"width = device-width, initial-scale = 1.0 maximum-scale = 2.5, user-scalable=1\">";
  page += "<title>Luc's Person Counter</title>";
  page += "<body style='background-color:powderblue;'>";
  page += "</head>";
  page += "<body>";
  page += "<h1 style='color:red'>Parameters for person counter</h1>";

  //Form to put the data in
  page += "<FORM action=\"/\" method=\"post\">";
  page += "Give the maximum amount of allowed customers<br>";
  page += "Number is now set at : ";
  page += maxnum;
  page += "<br><br>";
  page += "<input type=\"text\" name=\"textosend\" id=\"textosend\" value=\"Max number persons\">";
  page += "<br><br>";
  page += "<input type=\"submit\" value=\"Send to Person Counter\">";
  page += "</form>";
  page += "<br>";
  page += "<br>";
  page += "</script>";  
  page += "</body>";
  page += "</html>";
  return page;
  }


// ==================================================
// Handle for page not found
// ==================================================
void handleNotFound()
{
  server.send(200, "text/html", getPage());
}


// ==================================================
// Handle submit form
// ==================================================
void handleSubmit()
{
  //Text to show
  if (server.hasArg("textosend"))
      {
      textosend_string = server.arg("textosend");
      Serial.print("The received text is:             ");
      Serial.println(textosend_string);
      maxnum = textosend_string.toInt();
      EEPROM.write(0, maxnum); //the value to write in eeprom
      EEPROM.commit();
      }

  server.send(200, "text/html", getPage());       //Response to the HTTP request
}  


// ===================================================
// Handle root
// ===================================================
void handleRoot() 
{   
  if (server.args() ) 
    {
    handleSubmit();
    } 
  else 
    {
    server.send(200, "text/html", getPage());  
    }
}


// ===================================================
// Setup
// ===================================================
void setup()
{
  delay(1000);
  EEPROM.begin(EEPROM_SIZE);
  maxnum = EEPROM.read(0);
  if (maxnum == 0)
  {
     maxnum = 50;   
  }
  Serial.begin(115200);

  display.setBrightness(0x0a); //set the diplay to maximum brightness

  pinMode(D1, INPUT_PULLUP);
  pinMode(D2, INPUT_PULLUP);
  pinMode(D7, INPUT_PULLUP);

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid,password);
  
  for (int i=1; i<30; i++)
  {
  //while (WiFi.status() != WL_CONNECTED) 
  if (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  }


  if (WiFi.status() != WL_CONNECTED)
  {
  Serial.print("Setting soft-AP ... ");
  boolean result = WiFi.softAP("ESPsoftAP_01", "perscount");
  if(result == true)
  {
    Serial.println("Ready");
  }
  else
  {
    Serial.println("Failed!");
  }
  }
  
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
  server.on("/", handleRoot);
  server.onNotFound(handleNotFound);

  server.begin();
  delay(500);
}


// ===================================================
// Loop
// ===================================================
void loop()
{  
  server.handleClient(); 
  if (digitalRead(upbut) == 0)
 {
   person = person +1;
   total = total +1;
  if (person >maxnum)
     {
       display.showNumberDec(8888);
     }
   delay(500);
 }
 if (digitalRead(downbut) == 0)
 {
   person = person -1;
   if (person <0)
   {
     person = 0;
   }
    delay(500);
 }
 if (digitalRead(totbut) == 0)
 {
   display.showNumberDec(total);
   delay(3000);
 }
 display.showNumberDec(person);
}


Normally in all the stories in this weblog I give you an explanation on how the software works. But as there are a lot of tricks in it that are going to be discussed in future stories I will not get into the details here.

There are however two lines that you need to alter.

const char* ssid = "YOUR-ROUTERS-NAME";
const char* password = "PASSWORD";


In these lines fill in your own (or the shop's) routers name and password so the ESP8266 can connect to your network.

As stated I am not going into the details how the software works But I will show you how to use it.

How to use the Person Counter

First let me say that if you are going to use this on a fixed adress with a fixed maximum of people allowed at the same time you can just use the version discussed in the previous article.

At first start you do not need to access the webserver. The maximum number of persons is standard set at 50. The counter starts at 0. Pressing the green button adds a person. Pressing the red button subtracts a person and pressing the grey button shows the total amount of persons that visited the shop that day.

Removing the power resets the counter to 0.

If you need to alter the maximum number of people allowed in your shop you need to access the webserver.

As shown above you can set the credentials of your router in the software and if you do the person counter automatically connects to that router.
You can connect with your computer, phone or tablet to the person counter's IP adress. If you do not know the IP adress you can check your router to see what it is. In a arger company you could ask the IT manager. Another option is to connect the person counter with a USB cable to your Android phone and use an USB terminal program like USB Terminal Universal to be found in the Android Play Store.

If you do not set the credentials or move the person counter to a different location with different router credentials the person counter starts an access point.
In that case look in the wifi settings on your phone and connect to the ESP.
The Person Counter will be named Person Counter and the password is perscount.
The phone will tell you that the connection is made but that there is no internet available. That is OK.

Now point your browser to 192.168.4.1 this is the standard IP number for the ESP8266.

And there is the webpage.



The counter is when no alterations have been made set to 0. The program reads that number from its permanent storage and interprets that as being 50. I set this as the default value because this program was initially just meant for my work environment.



Now you can alter the text "Max number persons" in the number you want. Make sure you remove all of the text. Here I replaced it with 20 and then pressed the "Send to Person Counter" button. The webpage updates immediately and the number is stored in the permanent memory of the Wemos D1.

Next time you reboot the Wemos it automatically fetches the stored number (which now will be 20) and uses that in the program. So if the number exceeds 20 an alarm will be shown on the display being 8888.

For those that want to examine the program closer there are a few neat things in it.
- The webserver sends a form with a textfield with the post command
- There is permanent storage reserved in the Wemos memory with the EEPROM library
- Wifi tries to establish a connection to a known router and if that fails starts an accesspoint.
- The main program works wether you use the webserver or not.

Dont't worry. All these features will be discussed in later tutorials on this weblog.

Casing

In the previous story I showed the hardware schematic and showed that I put it on a stripboard for permanent use.

Off course I can not put a few stripboards on a persons desk and say: here you go, here is the person counter. It had to have a casing.



So I designed a casing in Tinkercad. 


To download them you need to create an account with Tinkercad. Don't hesitate, it's free !!



It took my Creality CR20 no less then 7 hours to print the casing !!!
Make sure you have enough filament on the spool. In your slicer set support everywhere. I used Prusa slicer for this as both the Creality slicer and Repetier did some weird things with the walls of the casing.

The small help parts are there to mount the stripboard in the casing and used as spacers. You could use some small strips of cardboard for that. Printing them took me just 7 minutes, so no big deal.



I started with re-enforcing the corners by adding some hot glue everywhere.



Next I glued the small boxes in the corners where the buttons are to come.



The stripboard with the buttons glued in place.



The small rectangular box was glued next to the display. It works as a spacer.



Then the display was glued into the casing.



And there we are.
As I was short of time I did not had the time to print a bottom and just glued a piece of cardboard at the bottom. I glued the USB cable to the cardboard and that's it. I was short of time because I needed it next day at my work.

As the dimensions are known when you download the model from Tinkercad you can easily print a bottom and back plate yourself.

Next day I took it to my work and it works as a charm !!!

Not only was this a fun project but it is also something real practical.

Till next time
have fun !!

Luc Volders










Saturday, May 1, 2021

Person Counter

 For an index to all my stories click this text.

I am as you might know in the Netherlands and until now we had a lockdown. At this moment the measures are a bit less stringent. I work at a company that sells all kinds of electrical equipment. We do that through our webshop and our physical shop. At first the shop has been closed. Then customers were allowed to visit on appointment. And now customers are free to visit the shop however a maximum of 50 customers at the same time is allowed.

At the entrance is a counter that is manned for collecting pre-ordered goods. The person behind that counter can keep track of the amount of customers. But that is a tedious task to do on paper. So I proposed to the board of directors to build an electronic person counter. And they agreed.

So last sunday I started working on the customer counter. I build two prototypes. The first is an hardware electronic one. The second is an app for android phones. I thought the app might be handy as all our employees are equipped with an Android phone. I managed to get both prototypes working within a few hours.

I present you here the hardware version.

Actually this is an easy project and could be made by anyone who read my book on the ESP32 as the mentioned parts (buttons and display) are all discussed in my book.

Person counter.

I wanted it to be as simple as possible so anyone can operate it.
There should be one button that must be pressed when a customer enters the building and another button that must be pressed when a customers leaves the building.
Next there should be a display that shows how many customers are present.

Well this is easy. For the display I used an TM1637 4 digit 8 segment display and further I needed two buttons. So this could easily be build with an ESP8266.

On monday I took the prototype with me and performed a test to see if it was functional. During the day it occurred to me that it would add some good information for our management if there was a total customer count. So at the end of the day we could see how many customers in total visited our shop that day.

Tuesday was kings-day (the birthday of our King) which is a national holliday but due to the pandemic no festivities were allowed so I had the time to add the third button and to write the additional code, which was in fact a matter of a few minutes. And I put the hardware on stripboard.

Wednesday was the first day we were officially open again so I performed another test with the final setup. And it performed really well.

Within 3 days from prototype to final setup !!

Breadboard prototype.



As you can see the breadboard setup is really simple. I used a Wemos D1 mini. The TM1637 display has its data line (DIO) attached to D5 and the Clock (CLK) line attached to D6.
The Add-1 button is attached to D1 and the Subtract-1 button to D2. The total-count button is attached to D7.
Normally I always use pull-up resistors but for simplicity I decided to use the internal PULLUP resistors of the Wemos D1.

The person count software

The TM1637 display needs a library. I used the TM1637Display library made by avishorp that is included in the Arduino's library manager. You can manually install it from the following link:
https://github.com/avishorp/TM1637

#include <TM1637Display.h>
 
const int CLK = D6; //Set the CLK pin connection to the display
const int DIO = D5; //Set the DIO pin connection to the display


const int upbut = D1;
const int downbut  = D2;
const int totbut = D7;
 
int person = 0;
int total = 0;
 
TM1637Display display(CLK, DIO); //set up the 4-Digit Display.
 
void setup()
{
 Serial.begin(9600);
 display.setBrightness(0x0a); //set the diplay to maximum brightness

 pinMode(D1, INPUT_PULLUP);
 pinMode(D2, INPUT_PULLUP);
 pinMode(D7, INPUT_PULLUP);
}
 
 
void loop()
{

 if (digitalRead(upbut) == 0)
 {
   person = person +1;
   total = total +1;
  if (person >50)
     {
       display.showNumberDec(8888);
     }
   delay(500);
 }

 if (digitalRead(downbut) == 0)
 {
   person = person -1;
   if (person <0)
   {
     person = 0;
   }
    delay(500);
 }

 if (digitalRead(totbut) == 0)
 {
   display.showNumberDec(total);
   delay(3000);
 }
 display.showNumberDec(person);
}



The program is straightforward. Nevertheless I will explain it here.

#include <TM1637Display.h>
 
const int CLK = D6; //Set the CLK pin connection to the display
const int DIO = D5; //Set the DIO pin connection to the display


The library is loaded and the CLK pin from the TM1637 is connected to D6 and the datapin to D5.

TM1637Display display(CLK, DIO);

The driver is started with a reference to the used pins.

void setup()
{
 Serial.begin(9600);
 display.setBrightness(0x0a); //set the diplay to maximum brightness

 pinMode(D1, INPUT_PULLUP);
 pinMode(D2, INPUT_PULLUP);
 pinMode(D7, INPUT_PULLUP);
}


The serial-port is initiated. Although this is not further used. I just added it for future expansion.
The TM1637 is set to maximum brightness and the pins for the buttons are defined as INPUT with the internal PULLUP resistors.

In the loop the magic happens.

 if (digitalRead(upbut) == 0)
 {
   person = person +1;
   total = total +1;
  if (person >50)
     {
       display.showNumberDec(8888);
     }
   delay(500);
 }


If the up button is pressed the person variable is increased AND the total variabele is increased. The person variable represents the number of persons present at that moment. The total variable contains the total amount of visitors.

If the person variable exceeds 50 the maxcimum number of people that are allowed is reached and the display shows 8888 as an error message.

 if (digitalRead(downbut) == 0)
 {
   person = person -1;
   if (person <0)
   {
     person = 0;
   }
    delay(500);
 }


If the downbutton is pressed the person variable is decreased. So one person less is present. Naturally a safety is build in so the counter can not get below 0.

 if (digitalRead(totbut) == 0)
 {
   display.showNumberDec(total);
   delay(3000);
 }
 display.showNumberDec(person);
}


If the Total button is pressed the display shows the total amount of people that has visisted the shop this day.

And that is all.

The person counter in real life.

Here is my breadboard setup.



When the grey button is pressed the display shows the total number of customers that has visited the show that day.
Pressing the green button ads one person to the person count and to the total.
Pressing the red button subtracts one person from the person count.



And here is the final version on stripboard.

Only one thing to do: design and print a case.

Why using an ESP8266.

An ESP8266 seems overkill for such a simple project. I could have used an Attiny85 as only 5 IO pins are used. However there are some considerations.
The ESP8266 has an USB port so the complete setup can be powered from a USB phone adapter. And the ESP8266 has Wifi !!!

Wifi can be used for future enhancements of the software.
There is a fixed limit of a maximum of 50 people in the software. I can build a webpage that allows me to alter this amount.
Look at my story about a time server: http://lucstechblog.blogspot.com/2020/02/time-is-of-essence.html
The software can be expanded  to measure how many customers are present every hour. This is valuable management information.
Another option is to measure which days are the busiest.

So enough possibilities for future expansions.
For now it works and that is the most important part.
We can see how many people are in the shop and that is important because if there are more as 50 people in the shop we risk a fine of several thousand euro's.

Till next time

Luc Volders