AC/DC current measurement using ACS712 sensor and NodeMCU ESP-12E micro-controller.


Getting Started

A glimpse of what you will read through this document to get you started on how to measure AC current by using an Allegro ACS712 Current Sensor and the NodeMCU ESP8266 ESP-12F module. Also, how this data could be uploaded to ThingSpeak analytic IoT platform.

The Current Sensor

This section highlights relevant features that need to be known for this tutorial related to the Allegro ACS712 Hall Effect-Based Linear Current Sensor.
  • Allegro ACS712 Hall Effect-Based Linear Current Sensor

Board

This section will describe, and highlight the main features of a common Development Board used for IoT projects and compatible with the Arduino IDE platform. 
  • NodeMCU ESP8266 ESP-12F module 

All together

A step-by-step process to set up your work environment using the ACS712A and NodeMCU ESP-12E module.

Programs

This part will walk you through a sequence of programs (sketch), starting from a baseline and eventually modifying until reaching a complete code, to update/flash your IoT Development Board using the Arduino IDE. 
  • analogRead
  • WiFi 
  • ThingSpeak

Before continuing… What You Need?

Hardware requirements to get you started on how to measure AC current.

Note: The cable cord in the picture was hand built, but it will work for the purpose of this tutorial.

  1. AC Power Extension Cable Cord Male/Female 10A/125V
  2. Allegro ACS712 5A Hall Effect-Based Linear Current Sensor
  3. ESP8266 NodeMCU LUA ESP-12E Internet WiFi Dev Kit
  4. Micro USB Cable 1ft.
  5. Breadboard
  6. Male to Female Breadboard Jumper Wires
  7. Wire Stripping Tool / Wire Cutter
  8. Multimeter
    Discloser: By click above links I may be eligible to earn profit to support this blog. 

The Current Sensor

Allegro ACS712 Hall Effect-Based Linear Current Sensor



Brief Description

ACS712 is a hall-effect linear current sensor IC manufactured by Allegro MicroSystems. It can be used for both AC and DC currents measurements. To operate it requires a 5V supply voltage and it will produce an analog voltage output proportional to the measurement current being sensed.

By “Hall-Effect”… What does it mean?

Generally speaking, is the effect of getting a measured output voltage as a result of an input current. 


Electrons from an electric current flow through a magnetic field plate. The magnetic field deflects the electrons in the conductor, i.e. causes the electrons to "push" to one side of the plate, creating a potential difference between the two sides. The difference in voltage from the side of the plate is the output of the sensor.

The Supply Voltage, VCC [V] = 5V


As mentioned earlier, to operate the sensor required a 5V power supply. This will be provided by the microcontroller as you will see later.

The Zero Current Output Voltage, VIOUT [V]= 2.5V

If the ASC712 is powered by 5V, AND there is no current across the input ( from Ip+ to Ip- ), the sensor output voltage, VIOUT, theoretically speaking will be Vcc x 0.5 = 2.5 V.

The Sensitivity [mV/A] value based on your ACS712 selection

There are three variants of ACS712 sensor based on the range of its current sensing. Depending on the variant, the output sensitivity also varies as shown below:


Note: For the purpose of this tutorial the model that it will be used is the ACS712ELCTR-05B-T; rated for a ± 5A readable current range with a sensitivity of 185 [mV/A] as highlighted above.  
A sensor's sensitivity indicates how much the sensor's output changes when the input quantity being measured changes. For instance, if the output voltage in a hall-effect sensor increases 1V when the input current increases by 1A, the sensitivity is 1 V/A. That is basically the slope of a linear equation.

Just to refresh. Here is a two-dimensional graph.

Where:

y = mx + b

describe the equation of the line.

y - is the output voltage
x - is the input current
m - is the slope we just mention
b - is known as the intercept

If the current input is zero (x = 0), the sensor output voltage, VIOUT, will be y = Vcc x 0.5 = 2.5 V.

In other words:

y = m(0) + 2.5 = 2.5

Therefore, the Voltage-Current relationship for the three models can be characterized by the three sensitivity indicator described in the table above, 185 mV/A, 100 mV/A and 0.66 mV/A. Also shown in the following three lines for the ±5A, ±20A and ±30A current range respectively:


Summary:
The Supply Voltage, VCC [V] = 5V .
The Zero Current Output Voltage, VIOUT [V]= 2.5V
The Sensitivity [mV/A]:
185 mV/A, 100 mV/A and 0.66 mV/A for the ±5A, ±20A and ±30A current range model type
respectively.

Board

ESP8266 ESP-12E NodeMCU Lua WiFi Development Board

Brief Description

NodeMCU is a Firmware distribution that uses the Lua scripting language on Expressif ESP8622 Wi-Fi microcontroller, as well as an open-source hardware development kit built around the ESP-12E WiFi module that itself includes the ESP8266 core processor. It has a CP2102 single chip USB to UART bridge IC for programming and debugging. And also, it can be powered via its micro USB port.



TECHNICAL SPECIFICATIONS
Microcontroller: ESP-8266 32-bit
Flash Memory: 4 MB
Clock Speed: 80 MHz
Operating Voltage: 3.3V
Digital I/O Pins: 11
Analog Input Pins: 1 (10-bit)
WiFi: Built-in 802.11 b/g/n
Version 1.0
Official Website: http://www.nodemcu.com/index_en.html

DOCUMENTATION
Schematic V3-340[PDF]
ESP8266EX Datasheet
CP210x Driver

The Analog Pin

The one feature relevant for this project is the Analog to Digital Converter (ADC) pin. Denoted as A0, TOUT or ADC0.

The output of the current sensor is an analog voltage, so to read it, in addition to a voltmeter, you can use a microcontroller like the NodeMCU ESP8266. It will read the analog output of the current sensor and converter to a digital value representation.

ADC Input Voltage Range

The ESP8266 ADC pin input voltage has a range from 0 to 1V, IF! using the bare WiFi Module.

However, most ESP8266 development boards, like the NodeMCU ESP8266, come with an internal voltage divider allowing the input range to go from 0 to 3.3V. This voltage divider can be found in the schematic of the NodeMCU ESP8266.

Reference: NodeMCU ESP8266 Dev Kit Schematic


ADC Resolution, 10-bit

The NodeMCU analog-to-digital converter is an embedded “10-bit precision SAR ADC”. This means, with an input voltage range from 1V to 3.3V and the giving 10-bit resolution ADC you can correlate the analog input values with a digital representation from 0 to 1024, as described below:


Now, remember that if there is no current through your ACS712 current sensor the analog output voltage will be 2.5V. The NodeMCU ADC will correlate the analog output voltage 2.5V with a 776.39 ADC value approximately. Reality vs expectation are two different things.

Summary:
Pinout Description: A0, ADC0 and/or TOUT.
Analog Input Voltage Range: 0 - 3.3V (If using the Dev. Board)
Resolution: 10-bit
Digital Output Value Range: 0 - 1024
 


All together

Diagram...







1.  AC power extension cord (Link)

Cut “one path” of the AC power extension cord with the wire cutter tool. It should resemble something similar to the one in the photo. I hope more professional!. Current is measured by creating a serial path through the sensor. Therefore:

a. Point A goes to Ip- terminal of the current sensor.
b. Point B goes to Ip+ terminal of the current sensor.

2. NodeMCU ESP-12E module and Current Sensor communication setup:

a. Connect NodeMCU A0 pin to Current Sensor VOUT pin: A0-->VOUT
b. Connect NodeMCU Vin pin to Current Sensor VCC pin: Vin-->VCC
c. Connect NodeMCU GND pin to Current Sensor GND pin: GND-->GND


3. Connect your NodeMCU ESP-12E to your computer using the micro USB cable.

STOP HERE. DO NOT CONNECT ANY LOAD.


Programs

Arduino Pre-requirements

Arduino IDE SW

If you've never used an Arduino before, you'll need to download the Arduino IDE. Check out this tutorial on installing Arduino to help on that subject.

Arduino core for ESP8266 WiFi chip

This step is very important because for Arduino IDE to recognize the NodeMCU ESP-12E module the “Arduino core for ESP8266 WiFi chip” needs to be installed. There are four methods to do so:
  1. Using Boards Manager
  2. Using git version
  3. Using PlatformIO
  4. Building with make
The suggested installation method for the latest git or master branch is by “Using git version”. Follow this video tutorial “Getting Started With NodeMCU Using Git Version of ESP8266 Core for Arduino”, and use the Arduino Core Documentation page as a reference guide to complete this step.

Drivers

If this is the first time you plug the NodeMCU ESP-12E module in, you may need to install drivers for it. Please, go to this link, CP2102 Drivers and download/install the drivers.

ThingSpeak Library 

Speaking of libraries, I will also go ahead and install the ThingSpeak library beforehand. You will need it at the end. Follow this tutorial → Link.

Arduino IDE Setup

If you meet all previous requirements let's now interact with the NodeMCU ESP-12E module:
  1. Connect the NodeMCU ESP-12E module to your computer using a micro USB cable.
  2. Open the Arduino IDE.
  3. From the top menu options select:
Tools > Board: > NodeMCU 1.0 (ESP-12E Module)

4. Next, verify if below IDE settings meet the exact same value parameters:
    Note: Port: “COM3” could be different.

analogRead

Now let's start from a baseline sketch and build on it until we get to our final code.

Without a Load

The first code will read the analog output voltage of the ACS712 current sensor without any load. Remember, if no current passes through the current sensor the analog output voltage of the ACS712 should be 2.5V  -- theoretically speaking. The NodeMCU ADC will correlate the analog output voltage 2.5V with an ADC value, which turns out to be approx. 776. Let's strive for that!

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/*
 * AnalogRead Sketch using ACS712 and NodeMCU ESP8266 ESP-12E module
 * by Alex Roman
 */
/*--------VARIABLES--------*/
/*--------NodeMCU--------*/
#define PIN A0

float resolution  = 3.3 / 1024;                   // Input Voltage Range is 1V to 3.3V
                                                  // ESP8266 ADC resolution is 10-bit. 2^10 = 1024
                                                    

void setup()
{
  Serial.begin(115200);                           // Initialize Serial communication
  pinMode(PIN, INPUT);                            // Set pin A0 as read. 
  
}
void loop() {
  
  Serial.print("analogRead = ");
  Serial.println(analogRead(PIN));                // Function to read from pin A0
  
  Serial.print("Voltage (when zero current) = ");   
  Serial.print(analogRead(PIN)* resolution, 3);   // ADC value multp. by resolution will give your the corresponding voltage value. 
  Serial.println(" V");        
  
  delay(1000); 
}

Output

  • analogRead = 754 avg. (at least that was the closest it got).
  • Voltage value 2.44V approx., almost 2.5V. I won't get mad!


The root mean square (RMS or rms) of a periodic waveform: Vrms/Irms

The r.m.s. value, also known as the effective value, is the amount of heat an ac current produces across a resistance compared with a steady current when passed through the same resistance at the same period of time. This is actually the value you see in a digital multimeter. And we are going to modify the first code to obtain the effective voltage and current values, i.e. Vrms and Irms.

Code 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
 * Vrms & Irms values from analogRead A0 using ACS712 and NodeMCU ESP8266 ESP-12E module
 * by Alex Roman
 */

/*--------VARIABLES--------*/
/*--------NodeMCU--------*/
#define PIN A0
float resolution  = 3.3 / 1024;                   // Input Voltage Range is 1V to 3.3V
                                                  // ESP8266 ADC resolution is 10-bit. 2^10 = 1024

uint32_t period = 1000000 / 60;                   // One period of a periodic waveform
uint32_t t_start = 0;                                 

// setup
float zero_ADC_Value = 0, zero_voltageValue = 0;   

// loop
float ADC = 0, Vrms = 0, Current = 0, Q = 0.0147;
float sensitivity = 0.185;                        // 185 mV/A, 100 mV/A and 0.66 mV/A for ±5A, ±20A and ±30A current range respectively. 

void setup()
{
  Serial.begin(115200);                           // Initialize Serial communication
  pinMode(PIN, INPUT);                            // Set pin A0 as read.  
  /*--------NodeMCU--------*/
  t_start = micros();                             
  uint32_t ADC_SUM = 0, n = 0;
  while(micros() - t_start < period) {            
    ADC_SUM += analogRead(PIN);                   // reading the analog value from pin A0. 
    n++;                                          // counter to be used for avg. 
  }
  zero_ADC_Value = (ADC_SUM / n);                 // The avg analog value when no current pass throught the ACS712 sensor.
  zero_voltageValue = zero_ADC_Value * resolution;    // The ACS712 output voltage value when no current pass trough the sensor (i = 0)

}
void loop() {
  
  /*----Vrms & Irms Calculation----*/
  t_start = micros();                             
  uint32_t ADC_Dif = 0, ADC_SUM = 0, m = 0;        
  while(micros() - t_start < period) {            // Defining one period of the waveform. US frequency(f) is 60Hz. Period = 1/f = 0.016 seg = 16,666 microsec
    ADC_Dif = zero_ADC_Value - analogRead(PIN);   // To start from 0V we need to subtracting our initial value when no current passes through the current sensor, (i.e. 750 or 2.5V).
    ADC_SUM += ADC_Dif * ADC_Dif;                 // SUM of the square
    m++;                                          // counter to be used for avg.
  }
  ADC = sqrt(ADC_SUM / m);                        // The root-mean-square ADC value. 
  Vrms = ADC * resolution ;                       // The root-mean-square analog voltage value.   
  Current = (Vrms  / sensitivity) - Q;        // The root-mean-square analog current value. Note: Q
  //------------------------------//
  
  Serial.print("analogRead = ");
  Serial.println(analogRead(PIN));
  
  Serial.print("Vrms = ");                        
  Serial.print(Vrms, 6);
  Serial.println(" V");        

  Serial.print("Irms = ");                       
  Serial.print(Current, 6);
  Serial.println(" A");
  Serial.print("\n");
  
  delay(1000); 
}

Output


  • There is no load connected

With a load

Connect to the AC Power Cord a load that you know or can find their specifications.
Example: A table lamp light bulb from my house have the following specs:
I will use it as a guidance. As I mentioned before, reality and expectation are two different things. Turn ON and compare your measurement with the spec.

Output

  • Theoretical: Irms 360mA
  • Measure: Irms 325mA avg.
  • Percent Error: 9.72%

Wifi

File Credentials

Open Notepad. Copy and paste the below information. Replace MySSID & MyPassword with your router or hotspot credentials. Save the file in the same exact location where your Arduino sketch is located with an “.h” extension. Example: secret.h

Copy & Paste

// Use this file to store all of the private credentials
// and connection details

#define SECRET_SSID "MySSID" // replace MySSID with your WiFi network name
#define SECRET_PASS "MyPassword" // replace MyPassword with your WiFi password


Location

Connection Completed!

Modify the code to add the WiFi section. You will be able to print, in the serial monitor of the Arduino IDE, “Connected, IP address: XYZ” if the NodeMCU module connects to your Wifi network.

Code


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
 * Vrms & Irms values from analogRead A0 using ACS712 and NodeMCU ESP8266 ESP-12E module. 
 * Plus WiFi connection to an access point.  
 * by Alex Roman
 */
 
/*--------LIBRARIES--------*/
#include <ESP8266WiFi.h>                            // Need to add the ESP8266WiFi.h library 
#include "secrets.h"                                // Also add the secrets.h file (The one saved in the same folder location as this scrip). 
/*--------VARIABLES--------*/
/*--------NodeMCU--------*/
#define PIN A0
float resolution  = 3.3 / 1024;                     // Input Voltage Range is 1V to 3.3V
                                                    // ESP8266 ADC resolution is 10-bit. 2^10 = 1024
uint32_t period = 1000000 / 60;                     // One period of a 60Hz periodic waveform 
uint32_t t_start = 0;

// setup
float zero_ADC_Value = 0;   

// loop
float ADC = 0, Vrms = 0, Current = 0, Q = 0.000;
float sensitivity = 0.185;                          // 185 mV/A, 100 mV/A and 0.66 mV/A for ±5A, ±20A and ±30A current range respectively. 

/*--------WiFi--------*/
char ssid[] = SECRET_SSID;                          // your network SSID (name) 
char pass[] = SECRET_PASS;                          // your network password
int keyIndex = 0;                                   // your network key Index number (needed only for WEP)
WiFiClient  client;                                 // Object


void setup()
{
  Serial.begin(115200);                             // Initialize Serial communication
  pinMode(PIN, INPUT);                              // Set pin A0 as read. 
  
  /*--------WiFi--------*/
  Serial.println();
  WiFi.begin(ssid, pass);                 // Initializes the WiFi library's network settings and provides the current status.
  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED)   // Return the connection status.
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
  
  //WiFi.mode(WIFI_OFF)
  wifi_set_sleep_type(NONE_SLEEP_T);
  /*--------NodeMCU--------*/
  t_start = micros();
  uint32_t ADC_SUM = 0, n = 0;
  while(micros() - t_start < period) {
    ADC_SUM += analogRead(PIN);
    n++;
  }
  zero_ADC_Value = ADC_SUM / n;                        // The avg analog value when no current pass throught the ACS712 sensor
    
}
void loop() {

   
  /*----Vrms & Irms Calculation----*/
  t_start = micros();                             
  uint32_t ADC_Dif = 0, ADC_SUM = 0, m = 0;        
  while(micros() - t_start < period) {            // Defining one period of the waveform. US frequency(f) is 60Hz. Period = 1/f = 0.016 seg = 16,666 microsec
    ADC_Dif = zero_ADC_Value - analogRead(PIN);   // To start from 0V we need to subtracting our initial value when no current passes through the current sensor, (i.e. 750 or 2.5V).
    ADC_SUM += ADC_Dif * ADC_Dif;                 // SUM of the square
    m++;                                          // counter to be used for avg.
  }
  ADC = sqrt(ADC_SUM / m);                        // The root-mean-square ADC value. 
  Vrms = ADC * resolution ;                       // The root-mean-square analog voltage value.   
  Current = (Vrms  / sensitivity) - Q;        // The root-mean-square analog current value. Note: Q
  //------------------------------//
  
  Serial.print("analogRead = ");
  Serial.println(analogRead(PIN));
  
  Serial.print("Vrms = ");                        
  Serial.print(Vrms, 6);
  Serial.println(" V");        

  Serial.print("Irms = ");                       
  Serial.print(Current, 6);
  Serial.println(" A");
  Serial.print("\n");
  
  delay(1000); 
}

Output



  • You are now connected to a network!



ThingSpeak

ThingSpeak Pre-requirements

  • Install ThingSpeak Communication Library for ArduinoLink
  • Create an Account: ThingSpeakLink (Is Free)
  • Create a Channel: Simple TutorialLink


  • Write down your channel number & API Key.


ThingSpeak Credentials

Remember the secrets document created for WiFi Credentials? Go ahead and edit it. Add the channel number & API Key to the document and save it (at the same exact location of your sketch). Example below:

Copy & Paste

// Use this file to store all of the private credentials
// and connection details

#define SECRET_SSID "MySSID" // replace MySSID with your WiFi network name
#define SECRET_PASS "MyPassword" // replace MyPassword with your WiFi password


#define SECRET_CH_ID 0000000 // replace 0000000 with your channel number
#define SECRET_WRITE_APIKEY "XYZ" // replace XYZ with your channel write API Key

Location

Send Data to ThingSpeak

Code


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/*
 * Vrms & Irms values from analogRead A0 using ACS712 and NodeMCU ESP8266 ESP-12E module. 
 * Plus WiFi connection to an access point. 
 * And ThingSpeak IoT platform Analysis access. 
 * by Alex Roman
 */
 
/*--------LIBRARIES--------*/
#include <ESP8266WiFi.h>                            // Need to add the ESP8266WiFi.h library 
#include "secrets.h"                                // Also add the secrets.h file (The one saved in the same folder location as this scrip). 
#include "ThingSpeak.h"
/*--------VARIABLES--------*/
/*--------NodeMCU--------*/
#define PIN A0
float resolution  = 3.3 / 1024;                     // Input Voltage Range is 1V to 3.3V
                                                    // ESP8266 ADC resolution is 10-bit. 2^10 = 1024
uint32_t period = 1000000 / 60;                     // One period of a 60Hz periodic waveform 
uint32_t t_start = 0;

// setup
float zero_ADC_Value = 0;   

// loop
int cnt = 0;
float ADC = 0, Vrms = 0, Current = 0, Q = 0.000, c = 0;
float sensitivity = 0.185;                          // 185 mV/A, 100 mV/A and 0.66 mV/A for ±5A, ±20A and ±30A current range respectively. 

/*--------WiFi--------*/
char ssid[] = SECRET_SSID;                          // your network SSID (name) 
char pass[] = SECRET_PASS;                          // your network password
int keyIndex = 0;                                   // your network key Index number (needed only for WEP)
WiFiClient  client;                                 // Object

/*--------ThingSpeak--------*/
unsigned long myChannelNumber = SECRET_CH_ID;       // your ThingSpeak Channel ID
const char * myWriteAPIKey = SECRET_WRITE_APIKEY;   // your ThingSpeak Channel API key

String myStatus = "";

void setup()
{
  Serial.begin(115200);                             // Initialize Serial communication
  pinMode(PIN, INPUT);                              // Set pin A0 as read. 
  /*--------WiFi--------*/
  Serial.println();
  WiFi.begin(ssid, pass);                 // Initializes the WiFi library's network settings and provides the current status.
  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED)   // Return the connection status.
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
  //WiFi.mode(WIFI_OFF)
  wifi_set_sleep_type(NONE_SLEEP_T);
  /*--------NodeMCU--------*/
  t_start = micros();
  uint32_t ADC_SUM = 0, n = 0;
  while(micros() - t_start < period) {
    ADC_SUM += analogRead(PIN);
    n++;
  }
  zero_ADC_Value = ADC_SUM / n;                      // The avg analog value when no current pass throught the ACS712 sensor
  /*--------ThingSpeak--------*/
  ThingSpeak.begin(client);                          // Initialize ThingSpeak 
    
}
void loop() {

   
  /*----Vrms & Irms Calculation----*/
  t_start = micros();                             
  uint32_t ADC_Dif = 0, ADC_SUM = 0, m = 0;        
  while(micros() - t_start < period) {            // Defining one period of the waveform. US frequency(f) is 60Hz. Period = 1/f = 0.016 seg = 16,666 microsec
    ADC_Dif = zero_ADC_Value - analogRead(PIN);   // To start from 0V we need to subtracting our initial value when no current passes through the current sensor, (i.e. 750 or 2.5V).
    ADC_SUM += ADC_Dif * ADC_Dif;                 // SUM of the square
    m++;                                          // counter to be used for avg.
  }
  ADC = sqrt(ADC_SUM / m);                        // The root-mean-square ADC value. 
  Vrms = ADC * resolution ;                       // The root-mean-square analog voltage value.   
  Current = (Vrms  / sensitivity) - Q;        // The root-mean-square analog current value. Note: Q
  //------------------------------//
  
  // Every 20 seconds avg. current will be uploaded to ThingSpeak.
  c += Current;
  cnt++;
  if (cnt == 20){
    c = c / cnt;
    ThingSpeak.setField(1, c);                    // Current
    ThingSpeak.setField(2, c*120);                // Voltage
     
    // write to the ThingSpeak channel
    int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
    if(x == 200){
      Serial.println("Channel update successful.");
    }
    else{
      Serial.println("Problem updating channel. HTTP error code " + String(x));
    }
    // figure out the status message
    if(c > 0.1){
      myStatus = String("Device is ON"); 
    }
    else if(c <= 0.1){
      myStatus = String("Device is OFF");
    }
    // set the status
    ThingSpeak.setStatus(myStatus);   
    c = 0;
    cnt = 0;
  } 
  
  delay(1000); 
}

Output


  • This is how it looks. ThingSpeak Channel will be updated every 15-20 seconds.
Everytime the channel is been updated you should see a confirmation message at the Serial Monitor

You have reached the END of this Tutorial. Hope it has been useful!!!


Comments

Unknown said…
Very detailed and impressive documentation. Really cool project!
The post you have shared here is really great as it contains some best knowledge which is very useful for me. Thanks for posting it. Keep it up. tag and test Melbourne
Such a helpful post you have shared here. I got some helpful knowledge from this post. Thanks for sharing such a post. Keep it up. microsonic ultrasonic sensors
Unknown said…
Hello, thank you for the nice explanation.

I would know why the voltage is very small and how we can set a real value of RMS voltage like 220V with an actual current of a lamp
Vishal Jha said…
Arduino: 1.8.14 Hourly Build 2021/03/09 09:33 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Disabled (new aborts on oom), Disabled, All SSL ciphers (most compatible), 32KB cache + 32KB IRAM (balanced), Use pgm_read macros for IRAM/PROGMEM, 4MB (FS:2MB OTA:~1019KB), 2, v2 Lower Memory, Disabled, None, Only Sketch, 115200"





















C:\Users\visha\Dropbox\PC\Documents\Arduino\demo\demo.ino: In function 'void setup()':

demo:67:3: error: 'ThingSpeak' was not declared in this scope

67 | ThingSpeak.begin(client); // Initialize ThingSpeak

| ^~~~~~~~~~

C:\Users\visha\Dropbox\PC\Documents\Arduino\demo\demo.ino: In function 'void loop()':

demo:91:5: error: 'ThingSpeak' was not declared in this scope

91 | ThingSpeak.setField(1, c); // Current

| ^~~~~~~~~~

exit status 1

'ThingSpeak' was not declared in this scope



This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.



Can anyone help me with this please its important
Anonymous said…
Can you please explain the same with DC load for measuring solar panel current?
Emman said…
this is a good project for us to go with, we'll use fluke 289 true rms multimeter
Arduino: 1.8.15 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Disabled (new aborts on oom), Disabled, All SSL ciphers (most compatible), 32KB cache + 32KB IRAM (balanced), Use pgm_read macros for IRAM/PROGMEM, 4MB (FS:2MB OTA:~1019KB), 2, v2 Lower Memory, Disabled, None, Only Sketch, 115200"

energy_meter_test:26:33: error: invalid conversion from 'const char*' to 'long unsigned int' [-fpermissive]

26 | unsigned long myChannelNumber = "1676492"; // your ThingSpeak Channel ID

| ^~~~~~~~~

| |

| const char*

exit status 1

invalid conversion from 'const char*' to 'long unsigned int' [-fpermissive]



This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.


how to solve this error
SamT said…
Goodness, What an Excellent post. I truly discovered this fluke 115 true rms multimeter.It is the thing that I was looking for. Thanks for this!
Hello, great blog post with amazing content that is very well explained!
I thank you for presenting this with everyone
Cable sizing calculator australia
Ganzo said…
What is Q represents in the code?