Arduino Projects

How To Build IoT Tamper-Proof Energy Meter Using Arduino & WiFi

watch the video

In this project tutorial, we will design, construct, and program an IoT tamper-proof energy meter using Arduino and WiFi LAN dashboard. This project’s research aims to design and model an energy meter with a Wi-Fi-based anti-theft/tamper mode that precisely measures the power consumed, detects tampering activity, and notifies the authorized personnel through SMS or Email.

Components Needed For Tamper-Proof Energy Meter Project

ComponentsQuantity
PZEM Module with Current Transformer1
NodeMCU board1
2004 LCD module1
Dc switch1
I2C LCD module1
Single Channel Relay Module1
5V power supply1
Veroboard, wire and PCB sockets1
6×6 casing1
AC Socket1
2.5mm Wire3 yards

The Materials needed for this project design is detailed in the table above.

Tamper-Proof Energy Meter: The Circuit Diagram

Circuit diagram for IoT tamper-proof energy meter

The Single phase energy module PZEM as shown in the picture above is connected with having its current transformer running through the Live wire of the Public Utility Input. This current transformer is responsible for sensing the amount of current consumes by the Load.

The PZEM module is programmed via serial communication protocol. This connection is  made to read the load voltage, open voltage, power factor once the MCU is connected to the module. To program this module, the connection is made as shown above. We used the Arduino IDE to program the energy module.

Programming The Project Design

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>
//include a library to h elp communicate with the LCD via I2C
#include <LiquidCrystal_I2C.h>
//include a library for the PZEM module. note that it depends on UART in this case we sed a software serial to define other pins as UART
#include <PZEM004Tv30.h>
#include <Wire.h>
#include "RTClib.h"

RTC_DS3231 rtc;

//create and instance of the LiquidCrystal, this name will be use as a class to call all the functions of the lcd library
LiquidCrystal_I2C lcd(0x27, 20, 4);
//create an instance of the PZEM004Tv30 library, this name will be used to call the functions available in the pzem library.
//the pins of the UART is also declared
PZEM004Tv30 pzem(D3, D4); // (RX, TX) OF THE SOFTWARE-SERIAL

const char* ap_ssid = "MOYIN";
const char* ap_password = "a1b2c3d4e5";
const char* ssid = "Moyin";
const char* password = "password";
const char* host = "maker.ifttt.com";
const char* apiKey = "bBoafo8uqrZq72TzdrU0ye";

const int tamper_slot = 1;
const int quota_slot = 100;
const int tamper_button = D5;
const int relay = D6;
bool tamper_flag;
bool buttonState;
bool email_Logic = false;
float quota;
int On = LOW;
int Off = HIGH;


//create global variables to hold the values of parameters to be read from the module later in the program
// we declare these variables as float because they will hold floating poin numbers, that is numbers with decimal points
float voltage;
float current;
float power;
float energy;
float frequency;
float pf;
double energy_unit;

ESP8266WebServer server(80);

//Check if header is present and correct
bool is_authenticated() {
  Serial.println("Enter is_authenticated");
  if (server.hasHeader("Cookie")) {
    Serial.print("Found cookie: ");
    String cookie = server.header("Cookie");
    Serial.println(cookie);
    if (cookie.indexOf("ESPSESSIONID=1") != -1) {
      Serial.println("Authentication Successful");
      return true;
    }
  }
  Serial.println("Authentication Failed");
  return false;
}

//login page, also called for disconnect
void handleLogin() {
  String msg;
  if (server.hasHeader("Cookie")) {
    Serial.print("Found cookie: ");
    String cookie = server.header("Cookie");
    Serial.println(cookie);
  }
  if (server.hasArg("DISCONNECT")) {
    Serial.println("Disconnection");
    server.sendHeader("Location", "/login");
    server.sendHeader("Cache-Control", "no-cache");
    server.sendHeader("Set-Cookie", "ESPSESSIONID=0");
    server.send(301);
    return;
  }
  if (server.hasArg("USERNAME") && server.hasArg("PASSWORD")) {
    if (server.arg("USERNAME") == "smartech" &&  server.arg("PASSWORD") == "1234") {
      server.sendHeader("Location", "/");
      server.sendHeader("Cache-Control", "no-cache");
      server.sendHeader("Set-Cookie", "ESPSESSIONID=1");
      server.send(301);
      Serial.println("Log in Successful");
      return;
    }
    msg = "Wrong username/password! try again.";
    Serial.println("Log in Failed");
  }
  String Home_Page = "<!DOCTYPE html>";
  Home_Page += "<html> <head> <meta name='viewport' content='width=device-width, initial-scale=1'>";
  Home_Page += "<style> body {font-family: Arial, Helvetica, sans-serif;} input[type=text], input[type=password] { width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; box-sizing: border-box; }";
  Home_Page += "button { background-color: #04AA6D; color: white; padding: 14px 20px; margin: 8px 0; border: none; cursor: pointer; width: 100%; }";
  Home_Page += "button:hover { opacity: 0.8; } .cancelbtn { width: auto; padding: 10px 18px; background-color: #f44336; }";
  Home_Page += ".imgcontainer { text-align: center; margin: 24px 0 12px 0; position: relative; }";
  Home_Page += "img.avatar { width: 40%; border-radius: 50% }";
  Home_Page += ".container { padding: 16px; }";
  Home_Page += "span.psw { float: right; padding-top: 16px; }";
  Home_Page += ".modal { display: none; position: fixed; z-index: 1; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgb(0,0,0); / background-color: rgba(0,0,0,0.4); padding-top: 60px }";
  Home_Page += ".modal-content { background-color: #fefefe; margin: 5% auto 15% auto; border: 1px solid #888; width: 80%; }";
  Home_Page += ".close { position: absolute; right: 25px; top: 0; color: #000; font-size: 35px; font-weight: bold;}";
  Home_Page += ".close:hover, .close:focus { color: red; cursor: pointer; }";
  Home_Page += ".animate { -webkit-animation: animatezoom 0.6s; animation: animatezoom 0.6s }";
  Home_Page += "@-webkit-keyframes animatezoom { from {-webkit-transform: scale(0)} to {-webkit-transform: scale(1)} }";
  Home_Page += "@keyframes animatezoom { from {transform: scale(0)} to {transform: scale(1)} }";
  Home_Page += "@media screen and (max-width: 300px) { span.psw { display: block; float: none; } .cancelbtn { width: 100%; } } </style> </head> <body>";
  Home_Page += "<h2>Tamper-proof Energy Meter</h2>";
  Home_Page += "<h4>Click button below to access device settings.</h4>";
  Home_Page += "<button >

Explanation of the Source Code

The source code written above also contains HTML, CSS and a little bit of Javascript functions. The whole source code aims at promoting the WiFi LAN based dashboard where the user and admin can monitor the project remotely.

The picture diagram above shows the Bare minimum source code (also called sketch) on the Arduino Software IDE. It illustrates only two functions: the setup() function and the loop() function. This program code is used to reset every module to it has nothing running inside previously. Hence we applied this also here. The setup() function runs any program which is within it once and proceeds to the function while the loop function runs any command or syntax placed within it repeatedly. The setup() function was used as shown below to set the baudrate (communication speed) between the personal computer (PC) and the microcontroller.

The program code began with calling the vital libraries (important pieces of code needed in the program). These libraries are the Softwareserial library and the PZEM library. The former tells the complier that we are using the software serial method for communication with the PZEM module rather than the hardware. This means that we are defining our own pins for the serial communication pins; namely, the Receiver and Transmitter pins (this is shown in code line 24 and 25 respectively). We called the PZEM library to make used of its function syntax. Which is shown how it is passed to serial communication in code line 29 and 30. As mentioned above, the serial communication is set to 115200 baudrate in the function setup() at code line 24.

The function begins with printing the hexadecimal address of the PZEM module and the AC voltage read by the sensor in floating variable. Other AC power parameter was also read by the sensor. These were current, power, energy, frequency and power factor (PF). This is shown in code line 42 through 48. We used an if condition to check when there was error reading any of the parameters.  This was to be displayed on the Serial monitor.  However if there wasn’t any error in reading any of the above parameters, the parameters read would be displayed using the else statement condition shown in code line 66 through 71.

Interfacing and Programming LCD

The 2004 LCD was interfaced to the design as shown in the figure above; using the Intra-Intra Circuit (I2C). This is very possible using I2C LCD module. It allowed us to communicate to the LCD module using 2-wire method rather than the 4-wire data or 8-wire data method. This 2-wire method are the Serial Data (SDA) and the Serial Clock (SCL) wire.

This allowed us to use the I2C backlight() function to turn on the LED of the LCD module and print a display of welcome message. And cleared the LCD screen after 3 seconds of displaying the message. The loop() displays the parameters on the LCD module. This si shown in code line 89 through 110. The syntax makes use of cursor position in its lcd.setCursor() function. This means that the LCD was segmented into rows and columns. The first row was row 0. And since it was a 20×4 LCD module, the last row was row 3. The print() function prints string data type or character to where the cursor is placed.

Results

When powered the LCD displays the name of the user and a welcome message. and it will also display the project name and energy parameters that are metered.

Interfacing Tamper-Proof Mechanism

The system was needed detect theft by noticing when a user has tampered with it by opening the casing. To get this done, we used a pushbutton which we placed at the top of the case cover as shown in the diagram below.

The program code for the schematic above is written thus:

const int tamper_slot = 1;
const int quota_slot = 100;
const int tamper_button = D5;
const int relay = D6;
bool tamper_flag;
bool buttonState;
bool email_Logic = false;
float quota;
int On = LOW;
int Off = HIGH;

The program allowed us to detect intrusion as one would open the meter when it is powered. As the system was meant to be placed on High tension distribution pole. The opening would mean that the user would want to bypass the legal output channel to avoid paying for bills.

However, this mechanism of theft demanded we attached a 3.3V LiPo battery to keep the system on even when there is no Utility supply. This battery is recharged when the Utility supply returns. The downside to this method is that if the Utility supply is not restored for a long period of time, the battery dies of overuse and undercharged state.

To solve this problem, we had to think of way to use an RTC (real time clock) module. This was able to keep the time and wait for a system mode of No Power.  Each RTC chip comes with an external battery that allows it to keep time even when the design it is connected to goes offline. This external battery was removed and the and the RTC was powered directly by the utility supply via the power supply. When the device is being tampered with, the pushbutton would go into tamper mode and the RTC would record the power interruption.

The IoT dashboard for Tamper-proof energy meter

Here is the WiFI dashboard of the project displayed on a mobile port. The source code above has web development script of HTML that renders the code to produce such and interface as shown here. It also has inline CSS and a little bit of JS code. Once the user connects to the LAN WiFi, he or she can go to the IP address and see these web results.

And this is the admin dashboard. For the admin, he can log in and with his secured login details and do some admin functions. like reset the meter and if the user has tampered with the meter, and it is locked, he could swipe the tampered mode and restart the meter.

Conclusion

So far we have designed and constructed an IoT tamper-proof energy meter. For us to send these values to the cloud, we will add the Cayenne libraries and export the measured and metered energy parameters to Cayenne mydevices designed dashboard. See this project on how to do that. The Cayenne dashboard will also allow us to set notifications or alerts in the form of email or SMS depending on the factors we set for. Leave us a comment about what you think about the project design.

Read More

smartechlabs

Recent Posts

Flipping the Script: The Benefits of Reverse Learning

Introduction Education is an ever-evolving field, constantly adapting to new discoveries, technologies, and methodologies. One…

1 hour ago

Weird History Wonders: 5 Bizarre Events That Defy Explanation

Introduction History is full of strange and inexplicable events that challenge our understanding of the…

1 hour ago

Setting the Record Straight: Historians’ Biggest Mistakes

Introduction History is a fascinating tapestry of events, people, and stories that have shaped our…

4 hours ago

Read Raw Deal, A Novel by Gill Valle

Raw Deal by Gill Valle takes readers on a gripping journey into the gritty and…

6 hours ago

Read Jack the Ripper, A Novel by Rick Geary

Rick Geary’s Jack the Ripper is not just a graphic novel, but a profound exploration…

7 hours ago

Read Foreign Faction, A Novel by A. James Kolar

The tragic murder of six-year-old beauty queen JonBenét Ramsey in 1996 is one of the…

8 hours ago

This website uses cookies.