ENERGY METER IOT – Open Electronics

 

Let’s interface our Power Meter with Web to deliver measurements to the ThingSpeak platform and see the ends in handy graphs.

 

A number of posts in the past, we launched the MCP39F511 built-in circuit, able to performing electrical measurements in single-phase electrical programs by the FT1346M board. Now we have built-in it with the GSM board and its administration library to face the system to the exterior world. Now we wish to present you methods to mix such {hardware} with an online platform for IoT gadget administration referred to as “ThingSpeak“. For the event, we now have written a particular sketch that makes use of the GSM library with built-in AT instructions for managing HTTP connections and the administration library of the built-in MCP39F511; in these pages, we are going to clarify methods to combine the 2 libraries and create a web page on ThingSpeak to show the acquired information.

Since we are going to use HTTP to hook up with the ThingSpeak platform, we will solely use SIMCOM GSM modules: within the sketch we used SIM800C.

 

THINGSPEAK INTRODUCTION

ThingSpeak is a platform that gives a service for aggregating, visualizing, and analyzing a stream of information from digital units recognized as IOT (Web of Issues). It’s then doable to ship information out of your gadget to the platform and examine the information obtained in real-time, probably sending alerts by the Twitter and Twilio companies. As well as, the platform gives MATLAB Analytics, with which you’ll write and execute MATLAB code to course of, analyze and visualize the information obtained. This permits designers to construct IoT programs with out establishing server companies or writing net software program.

The usage of ThingSpeak is freed from cost for the event of small initiatives for non-commercial use, e.g. sending lower than 3 million messages to the platform per yr (a median of 8,200 per day).

Whenever you activate paid licenses you purchase Models equivalent to 33 million messages that may be processed and saved in a single yr or in different phrases about 90,000 messages per day.

As well as, the Models help you create a finite variety of Channels.

For our utility, we used the Free model, which is greater than sufficient to create a demo.

After this temporary introduction to the platform, we will transfer on to the outline of methods to create Channels with its associated fields.

Step one, for individuals who should not but an enabled consumer, is to register and to do that you have to click on on “Signal Up” and observe the steps indicated.

As soon as the registration is completed you may proceed to the creation of a brand new Channel and to do that you have to click on on the button “New Channel” as proven in Fig. 1, part circled in purple. A kind will seem like crammed in with a number of fields, as proven in Fig. 2, the steps to observe are as follows:

1)    give a reputation to the brand new Channel (Title subject); we determined to assign the identify EnergyMeter;

2)    insert an outline of the brand new Channel to be created (Description subject); on this case we now have inserted as description “MCP39F511 Power Meter”;

3)    for every Channel you may activate eight totally different fields, every of those represents a measurement to be saved and processed; we now have activated six fields out of eight; particularly, we now have the next:

– Area 1 Voltage

– Area 2  Present

– Area 3  Energy Issue

– Area 4  Lively Energy

– Area 5  Reactive Energy

– Area 6  Obvious Energy

4)    if you need, you may insert the geo-localization information, that’s Elevation, Latitude and Longitude; with these parameters, a geographic map might be visualized indicating the place of the realized measurement system.

 

Fig. 1

 

The Metadata, Tags, Hyperlink to Exterior Web site and Hyperlink to GitHub entries should not used for this utility.

As soon as all these initializations are accomplished, click on on the “Save Channel” button.

 

Fig. 2

 

Now, underneath “My Channels” the newly created channel will seem (Fig. 3): to the left of its identify seems a closed padlock, indicating that the show is personal; it’s doable to configure the Channel as public (the padlock opens) and due to this fact seen from outdoors. Whenever you publish the Channel, it may be seen by everybody or solely by approved customers.

Clicking on the newly created Channel opens a piece the place you may:

  • modify the configuration parameters of the newly created Channel by clicking on the “Channel Settings” merchandise;
  • make the created Channel public/personal by clicking on the “Sharing” merchandise;
  • configure the show of the information obtained for every of the “Fields” created within the “Personal View” part (the information displayed underneath this heading might be seen solely within the personal part);
  • configure the show of the information obtained for every of the “Fields” created within the “Public View” part (the information displayed underneath this heading might be seen to anybody or to a restricted circle of chosen customers);
  • by clicking on the “API Keys” merchandise you could have entry to the learn/write keys related to the created Channel.

 

Fig. 3

 

The write secret’s clearly totally different from the learn key; the previous, related to the URL tackle of the connection to ThingSpeak, permits you to ship information in string format to the fields beforehand created. For instance:

https://api.thingspeak.com/replace?api_key=89QC6FHH0AU5536Z&field1=233

 

As you may see, within the string there’s the writing key assigned to our Channel and on the finish of the important thing there are the fields to which the information should be despatched; within the instance, there’s solely “field1” which is assigned the worth 233.

Underneath “Personal View” you may configure which information to show amongst these out there and methods to show them. Let’s see the instructions.

  • “Add Visualization permits associating a graph for every configured “Area” among the many eight out there. If the command is clicked on, a range window is proposed from which to decide on the “Area” whose information is to be visualized (Fig. 4). On this case, solely “Area 3” is out there, in case you click on on the chart after which on “Save” the corresponding chart might be created. Fig. 5 reveals the newly created graph equivalent to “Area 3”.

 

Fig. 4

Fig. 5

The chart clearly will be custom-made and to entry the configuration part you have to click on on the pencil icon on the high proper of the chart. On this method the suitable configuration window known as, as proven in Fig. 6.

 

Fig. 6

 

On this window you may configure:

  • Title is used to assign a label to the chart equivalent to “Area 3”: “Energy Issue”;
  • X-Axis is used to assign a label to the X-axis: “Time”;
  • Y-Axis is used to assign a label to the Y-axis: “PF”;
  • Coloration permits you to set the hexadecimal worth and the colour of the graph;
  • Background is used to set hexadecimal worth and colour of the graph background;

Kind units the chart sort: Line, Bar, Column, Spline and Step;

Dynamic? is used to set if the chart must be dynamic or not (dynamic signifies that it’s routinely up to date each 15 seconds);

Days units what number of 24 hour durations to attend earlier than together with the obtained worth within the feeds;

Outcomes units the variety of samples to be displayed within the graph;

Timescale is used to set each what number of minutes a knowledge must be displayed amongst these obtained (non-obligatory);

Common units each what number of minutes the typical worth of the obtained information must be calculated and displayed;

Median units each what number of minutes the median of the obtained information must be calculated and displayed;

Sum is used to set each what number of minutes the sum of the obtained information must be calculated and displayed;

Information Min is used to set the minimal anticipated worth;

Information Max is used to set the utmost anticipated worth;

Y-Axis-Min units the minimal worth to be displayed on the Y-axis;

Y-Axis Max is used to set the utmost worth to be displayed on the Y-axis;

  • Add Widgets; permits you to configure different strategies of displaying the obtained information; clicking on this command a range window seems from which you’ll select:

Gauge is used to set a graphical tachometer-like show (Fig. 7 reveals the configuration used for the show of the mains voltage); there are a number of fields that should be crammed in with a purpose to receive the specified consequence together with:

Title units the identify to be assigned to the viewer (on this case “Voltage”);

Area is used to set the related “Area” from which to take the information to be visualized; right here we seek advice from “Area 1”;

Min is used to set the minimal worth; the anticipated minimal worth is 0 V;

Max is used to set the utmost worth; we anticipate 350 V as the utmost worth;

Models is used to set the unit of measure (on this case volt “V”);

Tick Interval is used to set the delta for displaying numbers on the tachometer. On this case, we now have set steps of 25 models in order that the values are readable with out overlapping;

Replace Interval units how lengthy it takes to refresh the worth to be displayed (set to fifteen seconds);

Vary is used to setting separate show sections on the tachometer; right here the center part is between 180 V and 250 V (regular worth) and the 2 outer sections are between 0 V and 180 V (mains voltage too low) and between 250 V and 350 V (mains voltage too excessive) have a unique colour;

– Numeric Show is used to set a numeric sort show (Fig. 8 reveals the configuration used for the lively energy show); right here too there are a number of fields to set:

Title is used to set the identify to be assigned to the viewer (on this case, “Lively Energy”);

Area is used to set the related “Area” from which to take the information to be visualized (right here we seek advice from “Area 4”);

Replace Interval is used to set how typically the worth to be visualized should be refreshed (15 seconds are set);

Models of measurement (watts “W”);

Information Kind is used to set whether or not the worth to be visualized is an integer sort or with decimals; within the latter case it should be written what number of decimals are desired (on this case three);

Lamp Indicator is used to set an alarm and is sort of a normally-off LED that lights up if the obtained information is above or beneath threshold (is dependent upon settings);

  • Export current information; permits to export the obtained information in JSON, XML and CSVM so it’s doable to export all “Fields” in a single file utilizing the choices of line one “EnergyMeter Channel Feed” or every channel individually utilizing the next strains;
  • MATLAB Evaluation; permits us to create MATLAB code for the evaluation of the obtained information;
  • MATLAB Visualization permits you to create MATLAB code to investigate and visualize the obtained information.

 

Fig. 7

Fig. 8

 

Underneath the merchandise “Public View” we will configure, as already accomplished for the personal part, the visualization of the information obtained from the assorted “Fields” with the distinction that these are seen to the skin. To make the information seen you have to name up the “Sharing” part and observe the directions. The configuration of the general public part is similar to the personal one, so we won’t dwell on it any additional.

Fig. 9, Fig. 10 and Fig.  11 present how we configured our “Channel” to show the information obtained from the MCP39F511 built-in. Within the instance we needed to show Voltage, Present and Energy Issue measurements each by way of graph and pointer indicator. Similar for Lively, Reactive and Obvious energy measurements with the distinction that for these we now have additionally used the numerical show. The geographic location seems on the backside of the measures.

 

Fig. 9

Fig. 10

 

As famous in Fig. 11 we launched a graph generated by way of MATLAB (3-Day Lively Energy Comparability) that correlates lively energy acquisitions relative to a few days, so {that a} comparability will be made. The times will also be roughly, relying on the MATLAB code.

 

Fig. 11

 

To provide an concept, in Itemizing 1 we report the MATLAB code used to generate the graph: the strains of code that start with “%” and are coloured inexperienced establish the feedback. Three variables have been declared that establish ID of the channel used (readChannelID), the sphere you wish to graph (myFieldID) and the important thing to learn the information (readAPIKey). The “thingSpeakRead” perform takes care of studying the information of the chosen channel on the requested day and the “plot” attracts the graph. On the backside we discover strings related to the chart title, X – Y axis labels and a quick legend.

Itemizing 1

% Channel ID to learn information from
readChannelID = 870302;
% Lively Energy Area ID
myFieldID = 4;
% At some point date vary
oneDay = [datetime(‘yesterday’) datetime(‘today’)];
% Channel Learn API Key
% In case your channel is personal, then enter the learn API key between the ‘’ beneath:
readAPIKey = ‘LU2P9AT2EOTD79Q8’;
% Learn Lively Energy Information
ActivePower_Day_1 = thingSpeakRead(readChannelID,’Fields’,myFieldID, ...
‘dateRange’, oneDay, ‘ReadKey’,readAPIKey);
ActivePower_Day_2 = thingSpeakRead(readChannelID,’Fields’,myFieldID, ...
‘dateRange’,oneDay-days(1),’ReadKey’,readAPIKey);
ActivePower_Day_3 = thingSpeakRead(readChannelID,’Fields’,myFieldID, ...
‘dateRange’, oneDay-days(2),’ReadKey’,readAPIKey);
% Create array of durations
myTimes1 = minutes(1:size(ActivePower_Day_1));
myTimes2 = minutes(1:size(ActivePower_Day_2));
myTimes3 = minutes(1:size(ActivePower_Day_3));
% Visualize the information
plot(myTimes1,ActivePower_Day_1, myTimes2,ActivePower_Day_2, myTimes3, ActivePower_Day_3);
legend({‘Day1’,’Day2’,’Day3’});
xlabel(‘Minutes’);
ylabel(‘Lively Energy W’);
title(‘3-Day Lively Energy Comparability’);

 

 

INTEGRATE GSM LIBRARY GSM AND MCP39F511

Having stated that, let’s go additional: to create the sketch that sends {the electrical} measurements to the “ThingSpeak” platform, it’s needed to start with to combine and harmonize the 2 libraries GSM and MCP39F511 in order that they’ll work collectively with out producing conflicts with the interrupt vectors inherent to the administration of TIMER 1, utilized by each to generate the time base used for the administration of all time variables used within the libraries.

Actually if we take the libraries with out making any adjustments and embody them in a sketch we are going to get the next error from the C compiler:

 

(.textual content+0x0): a number of definition of `__vector_20′.

 

Thus, it’s essential to implement distinctive dealing with of the interrupt vector of TIMER 1.

Let’s begin with the MCP39F511 library and particularly with the recordsdata “Isr_MCP39F511.h” and “Isr_MCP39F511.cpp”. Within the file “Isr_MCP39F511.h” we create a directive to the compiler named:

 

#outline ENABLE_ISR_TIMER1

 

which permits to allow/disable the code sections inherent to the TIMER 1 interrupt administration. In different phrases, if the directive is commented out the TIMER 1 interrupt dealing with code might be ignored, vice versa it will likely be included within the library.

So when the MCP39F511 library is for use alone in a sketch it should be uncommented, whereas whether it is for use along with the GSM library it should be commented. Throughout the file “Isr_MCP39F511.cpp” the features affected by this directive are:

 

void Isr_MCP39F511::EnableLibInterrupt(void)

void Isr_MCP39F511::EnableTimerInterrupt(void)

ISR(TIMER1_OVF_vect)

Along with the directive simply launched we now have to create a brand new perform inside which we now have to place the code used within the administration of the interrupt vector of TIMER 1:

 

static risky void Isr_MCP39F511::Timer1_Interrupt(void)

 

Contained in the perform we now have the time variable administration code wanted by the MCP39F511 library that you just see in Itemizing 2. Relying on the chosen UART the correct time variable might be used. Let’s go now to the GSM module administration library and particularly the recordsdata “Isr_GSM.h” and “Isr_GSM.cpp”. Within the first one we now have to introduce a directive to the compiler:

 

#outline ENABLE_EXT_TIMER1

 

which permits us to allow/disable the code for managing the exterior TIMER 1 interrupt, that’s the a part of code created from scratch within the MCP39F511 library. Then we create a perform pointer directed to the Flash tackle the place the TIMER 1 interrupt dealing with perform of the MCP39F511 library is saved:

 

#ifdef ENABLE_EXT_TIMER1

    static void (* risky __Ext_Timer1_Vector)(void);

#endif

 

The perform pointer is just thought of if the directive to the compiler ENABLE_EXT_TIMER1 is uncommented and due to this fact lively. The perform pointer is lively on the time when the directive to the compiler ENABLE_EXT_TIMER1 is lively (i.e. not commented out). That stated we should create a perform, to be referred to as in the course of the initialization of the sketch, which assigns to the pointer described earlier than the beginning tackle in FLASH the place is saved the administration perform of the interrupt TIMER 1 within the administration library of the MCP39F511:

 

#ifdef ENABLE_EXT_TIMER1       

        void Ext_Timer1_Vector(void (*perform)(void));

#endif

 

That is additionally lively if the directive permits it.

The code current on this perform is:

 

#ifdef ENABLE_EXT_TIMER1 

    void Isr_GSM::Ext_Timer1_Vector(void (* risky perform)(void))

    {     

        __Ext_Timer1_Vector = perform;

    }

#endif

 

and is used to load into the perform pointer the Flash tackle of the perform to be referred to as.

Now we now have the tackle to level to and we simply have so as to add contained in the administration of TIMER 1 interrupt within the GSM library the required code to name the specified perform:

 

ISR(TIMER1_OVF_vect) {

    TCNT1 = SLOWBASETIME;

    .........................................

    .........................................

#ifdef ENABLE_EXT_TIMER1

    if (__Ext_Timer1_Vector != NULL) {

        __Ext_Timer1_Vector();

    }

#endif   

}

 

With this we now have concluded the modifications to the 2 libraries. Now contained in the sketch, in the course of the initialization section (void setup()), we have to insert in the correct place the next line of code:

 

Isr.Ext_Timer1_Vector(Isr_39F511.Timer1_Interrupt);

 

By calling this perform we made positive that in the course of the administration of TIMER 1 by the GSM library the time variables of the MCP39F511 library are additionally managed.

The administration library of the built-in MCP39F511 along with the adjustments talked about above has been affected by an extra enchancment as a result of introduction of a sequence of features for the calculation of the typical worth on some electrical measurements. Through the directive to the compiler:

 

#outline ENABLE_AVERAGE_CALC

allow/disable the features for calculating the typical worth and relative administration arrays. Along with the above directive, we now have launched one other one for outlining the size that the arrays wanted to calculate the typical worth should have:

 

#outline AVERAGE_ARRAY_SIZE 4

 

The allowed values for this directive to the compiler are 4, 8, 16, and 32. The bigger the scale of the arrays, the extra SRAM reminiscence might be wanted. Due to this fact, the scale for use should be chosen rigorously relying on the applying to be carried out (we are going to give a concrete instance after we speak concerning the sketch for sending information to the “ThingSpeak” platform). The features for calculating the typical worth are as described beneath.

  • uint16_t MCP39F511_RmsVoltageRawAverage(void) ® Calculates the typical worth for the voltage measurement. The perform works on the RAW values learn by the MCP39F511 and returns a 16-bit unsigned integer worth.
  • uint32_t MCP39F511_RmsCurrentRawAverage(void) ® Calculates the typical worth relating to the present measurement. The perform works on the RAW values learn by the MCP39F511 and returns a 32-bit unsigned integer worth.
  • uint16_t MCP39F511_PowerFactorRawAverage(void)® Calculates the typical worth with respect to the ability issue measure. The perform works on the RAW values learn by the MCP39F511 and returns a 16bit unsigned integer worth. The calculated worth should then be transformed between the allowed values -1 and +1 and wishes the auxiliary perform uint16_t CalcAveragePowerFactor(void).
  • uint16_t MCP39F511_LineFrequencyRawAverage(void) ® Calculates the typical worth with respect to the road frequency measurement. The perform works on the RAW values learn by the MCP39F511 and returns a 16-bit unsigned integer worth.
  • uint32_t MCP39F511_ActivePowerRawAverage(void) ® Calculates the typical worth with respect to the lively energy measurement. The perform works on the RAW values learn by the MCP39F511 and returns a 32-bit unsigned integer worth.
  • uint32_t MCP39F511_ReactivePowerRawAverage(void) ® Calculates the typical worth with respect to the reactive energy measurement. The perform works on the RAW values learn by the MCP39F511 and returns a 32-bit unsigned integer worth.
  • uint32_t MCP39F511_ApparentPowerRawAverage(void) ® Calculates the typical worth with respect to the obvious energy measurement. The perform works on the RAW values learn by the MCP39F511 and returns a 32-bit unsigned integer worth.

Itemizing 2

//===========================================
// Timeout 8 bit
if (Isr_39F511.ZcdTimeOut > 0) { Isr_39F511.ZcdTimeOut--; }
//===========================================
//===========================================
// Timeout 16 bit
#if outlined(HARDWARE_UART1_39F511) || outlined(SOFTWARE_UART1_39F511)
if (Isr_39F511.Uart1_TimeOut > 0) { Isr_39F511.Uart1_TimeOut--; } // TimeOut for {hardware}/software program
serial COM 1
#endif
#if outlined(HARDWARE_UART2_39F511) || outlined(SOFTWARE_UART2_39F511)
if (Isr_39F511.Uart2_TimeOut > 0) { Isr_39F511.Uart2_TimeOut--; } // TimeOut for {hardware}/software program
serial COM 2
#endif
#if outlined(HARDWARE_UART3_39F511) || outlined(SOFTWARE_UART3_39F511)
if (Isr_39F511.Uart3_TimeOut > 0) { Isr_39F511.Uart3_TimeOut--; } // TimeOut for {hardware}/software program
serial COM 3
#endif
//===========================================

 

 

The features for calculating the imply worth are related, nonetheless the array they should work on adjustments. Let’s analyze the perform for calculating the the grid voltage common worth:

 

uint16_t Cmd_MCP39F511::MCP39F511_RmsVoltageRawAverage(void) {

    uint8_t Index = 0;

    uint32_t AverageTemp = 0;          

    do {

        AverageTemp += VoltageRmsRaw_Array[Index++];

    } whereas (Index < AVERAGE_ARRAY_SIZE);   

    return((uint16_t)(AverageTemp / AVERAGE_ARRAY_SIZE));

 }

 

As you may see, aside from the native variables, we now have the do-while assemble that takes care of averaging over the values contained within the corresponding array.

The bigger the scale of the array, the longer it should take to calculate the typical worth. The perform, on this case, returns a 16-bit unsigned integer worth.

The next features are used to load the values into the respective arrays:

  • void MCP39F511_UpdateRmsVoltageRawArray(void) ® Masses the final learn worth of the RMS voltage into the “VoltageRmsRaw_Array” array;
  • void MCP39F511_UpdateLineFrequencyRawArray(void) ® Masses the final learn worth of the community frequency into the “LineFrequencyRaw_Array” array;
  • void MCP39F511_UpdatePowerFactorRawArray(void) ® Masses the final learn worth of the ability issue into the “PowerFactorRaw_Array” array;
  • void MCP39F511_UpdateRmsCurrentRawArray(void) ® Masses the final learn worth of the RMS present into the “CurrentRmsRaw_Array” array;
  • void MCP39F511_UpdateActivePowerRawArray(void) ® Masses the final learn worth of the lively energy into the “ActivePowerRaw_Array” array;
  • void MCP39F511_UpdateReactivePowerRawArray(void) ® Masses the final learn worth of the reactive energy into the “ReactivePowerRaw_Array” array;
  • void MCP39F511_UpdateApparentPowerRawArray(void) ® Masses the final learn worth of the obvious energy into the “ApparentPowerRaw_Array” array.

 

The precise sequence of use of the uncovered features, assuming we’re engaged on the RMS voltage, is:

Cmd_39F511.MCP39F511_ReadRmsVoltageRaw();

Cmd_39F511.MCP39F511_UpdateRmsVoltageRawArray();

Cmd_39F511.MCP39F511_RmsVoltageRawAverage();

 

GPRS, TCPIP, and HTTP LIBRARY FUNCTIONS

Within the GSM library, which we now have mentioned in earlier articles, we now have added the features essential to handle information connections. Three new recordsdata named respectively “GprsCmd_GSM.cpp”, “TcpIpCmd_GSM.cpp”, “HttpCmd_GSM.cpp” and associated .h recordsdata have been created. The GSM SimCom modules are totally supported, the Quectel M95 is partially supported, and the Fibocom G510 will not be supported.

When it’s needed to make use of AT instructions to handle information connections, a preliminary GSM module initialization part much like the one already used and extensively defined for GSM connections (SMS and Voice) should be carried out. So the most recent out there revision of our library can run:

  • Primary initialization of the GSM module for SMS and voice administration;
  • Initialization to GPRS (Common Packet Radio Service);
  • Information connection initialization for functions that use the HTTP service with GET/POST.

So the extra initialization sequence for information connections is as follows:

  • AT+CGATT?  begins with a command that checks if the gadget is related or to not the GPRS service and, in line with the consequence obtained, it should execute or not the following command;
  • AT+CGATT=1  hooks the GSM module to the GPRS;
  • AT+CIPMUX=0  permits a Single IP Connection;
  • AT+CGEREP=1  permits the GSM to ship, by way of serial interface, the unsolicited consequence codes regarding the connection to the GPRS service;
  • AT+CSTT=”OWN OPERATOR ” ® units the APN (Entry Level Title) and, if needed, additionally sends Consumer Title and Password;
  • AT+CIICR  prompts the information connection to the GPRS service;
  • AT+CIFSR  command to show the native IP tackle assigned by the GPRS service;
  • AT+CGDCONT=1, “IP”, “OWN OPERATOR”  used to outline the PDP context (“Packet Information Protocol”); the PDP context used is “IP”;
  • AT+CGATC=1,1  prompts the PDP context;
  • AT+CGPADDR=1  command used to show the IP tackle assigned to the PDP context, which is totally different from the IP tackle assigned by the GPRS service;
  • AT+CIPHEAD=1  used to configure the GSM module to return the IP tackle of the sender on the head of the obtained information packet;
  • AT++CIPSRIP=1  units the GSM module to return, by way of “unsolicited consequence code”, the distant IP tackle and port when a knowledge packet is obtained;
  • AT+SAPBR=3,1, “CONTYPE”, “GPRS ”  configures the information connection sort for functions with IP;
  • AT+SAPBR=3,1, “APN”, “OWN OPERATOR ”  used to configure personal operator APN for IP-based functions;
  • AT+SAPBR=1,1  prompts the service for IP-based functions;
  • AT+SAPBR=2,1  request assigned IP tackle (the returned IP is the same as the one assigned by the GPRS service).

 

To allow initialization of the GPRS and HTTP part, the next flags should be set to 1:

 

Gprs.GprsFlag.Bit.EnableGprsFunctions = 1; // Allow GPRS features

Http.HttpFlag.Bit.EnableHttpFunctions = 1; // Allow HTTP features

As a substitute, the dealing with code within the sketch to make sure the proper initialization sequence is:

 

Gsm.ExecuteUartState();

if (Gsm.GsmFlag.Bit.GsmInitInProgress == 1) {

    Gsm.InitGsmSendCmd();

    Gsm.InitGsmWaitAnswer();

} else if (Gsm.GsmFlag.Bit.GprsInitInProgress == 1) {

    Gprs.InitGprsSendCmd();

    Gprs.InitGprsWaitAnswer();

} else if (Gsm.GsmFlag.Bit.HttpInitInProgress == 1) {

    Http.InitHttpSendCmd();

    Http.InitHttpWaitAnswer(); 

} else { 

Gsm.UartContinuouslyRead();

Gsm.ProcessUnsolicitedCode();

Gsm.GsmAnswerStateProcess();

…............

…............

}

 

 

As you may see, it accommodates three impartial initialization sections: the primary one is the basic one for voice and SMS functions, the second takes care of the initialization of the GPRS service, and eventually the initialization for HTTP functions (used to ship information to ThingSpeak).

Beneath is the whole sequence of AT instructions despatched to initialize the information connection:

 

AT+CGATT?<CR><LF>

<CR><LF>

+CGATT: 1<CR><LF>

<CR><LF>

OK<CR><LF>

AT+CIPMUX=0<CR><LF>

<CR><LF>

OK<CR><LF>

AT+CGEREP=1<CR><LF>

<CR><LF>

OK<CR><LF>

AT+CSTT=”iliad”<CR><LF>

<CR><LF>

OK<CR><LF>

AT+CIICR<CR><LF>

<CR><LF>

OK<CR><LF>

AT+CIFSR<CR><LF>

<CR><LF>

10.145.242.241<CR><LF>

AT+CGDCONT=1,”IP”,”iliad”<CR><LF>

<CR><LF>

OK<CR><LF>

AT+CGACT=1,1<CR><LF>

<CR><LF>

+CGEV: ME PDN ACT 1<CR><LF>

<CR><LF>

OK<CR><LF>

AT+CGPADDR=1<CR><LF>

<CR><LF>

+CGPADDR: 1,”10.65.240.242”<CR><LF>

<CR><LF>

OK<CR><LF>

AT+CIPHEAD=1<CR><LF>

<CR><LF>

OK<CR><LF>

AT+CIPSRIP=1<CR><LF>

<CR><LF>

OK<CR><LF>

AT+SAPBR=3,1,”CONTYPE”,”GPRS”<CR><LF>

<CR><LF>

OK<CR><LF>

AT+SAPBR=3,1,”APN”,”iliad”<CR><LF>

<CR><LF>

OK<CR><LF>

AT+SAPBR=1,1<CR><LF>

<CR><LF>

OK<CR><LF>

AT+SAPBR=2,1<CR><LF>

<CR><LF>

+SAPBR: 1,1,”10.145.242.241”<CR><LF>

<CR><LF>

OK<CR><LF>

 

Along with the AT instructions simply described, the library gives a sequence of different instructions for managing the information connection by way of HTTP service (utilized in our instance sketch).

  • AT+HTTPINIT ® used for initializing the HTTP service, should be executed first.
  • AT+HTTPSTATUS? ® reads the standing of the HTTP service; it receives as response 4 parameters: <mode>, <standing>, <end> and <stay>. The primary parameter signifies whether or not a “GET”, “POST,” or “HEAD” command is in progress. The second parameter signifies the standing of the service, i.e., “0” ready, “1” receiving, or “2” transmitting information. The third parameter signifies how a lot information has been transmitted, and the final parameter signifies how a lot information nonetheless must be despatched or transmitted.
  • AT+HTTPPARA ® used to set the parameters of the HTTP service. The command is split into two distinct elements, the primary half units the parameter for the HTTP service (AT+HTTPPARA=”CID”,1), whereas the second half units the connection URL with the information to be despatched to ThingSpeak” (AT+HTTPPARA=”URL”, “http://api.thingspeak.com/replace.json?………”).
  • AT+HTTPACTION=0 ® used to set whether or not a “GET” (0), “POST” (1), “HEAD” (2) or “DELETE” (3) must be carried out. (2) or a “DELETE” (3).
  • AT+HTTPTERM ® terminates the HTTP service and should be executed because the final command.

 

The next is the sequence of the AT instructions used to ship information to the ThingSpeak platform by way of the HTTP service: on the high and on the backside, we now have the command for initializing the HTTP service and the command for terminating the service, respectively. After that, the HTTPSTATUS command is used to confirm that the service will not be busy, and if free, the information is distributed to the platform utilizing the HTTPPARA command (two instructions executed in sequence). The HTTPACTION command follows this for performing the “GET” command to the chosen URL (Itemizing 3).

One final consideration relating to information connection administration: there are constants strings that should be saved in EEPROM as already accomplished for PIN codes, PUKs, and others. So there are directives to the compiler the place these constants are outlined and the utmost house they’ll occupy in EEPROM. Nonetheless, the writing in EEPROM of those string constants can solely be accomplished by a particular sketch that we now have already mentioned on different events. The string constants that should be saved in EEPROM are:

  • APN cellphone operator;
  • Username and Password for APN (they don’t seem to be all the time used however have been outlined anyway in case of want);
  • PDP context;
  • distant server IP tackle for TCP/IP information connection; a most of three IP addresses are allowed if a number of connections are used (AT+CIPMUX=1);
  • Distant server area for TCP/IP information connection (a most of three domains are allowed in case of a number of connections);
  • connection port to the distant server (as much as three ports are allowed in case of a number of connections);
  • URL for the HTTP service;
  • IP Proxy;
  • Proxy Port.

 

The beginning addresses in EEPROM for every of those strings are retrieved by code in the course of the sketch initialization section and saved within the acceptable information constructions in order that they’re all the time accessible.

Itemizing 3

AT+HTTPINIT<CR><LF>
<CR><LF>
OK<CR><LF>
AT+HTTPSTATUS?<CR><LF>
<CR><LF>
+HTTPSTATUS: GET,0,0,0<CR><LF>
<CR><LF>
OK<CR><LF>
AT+HTTPPARA=”CID”,1<CR><LF>
<CR><LF>
OK<CR><LF>
AT+HTTPPARA=”URL”,”http://api.thingspeak.com/replace.json? api_key=89QC6FHH0AU9636Z&field1=230.44&field2=
00.000&field3=0.998&field4=-00000.00&field5=-00000.00&field6=00000.00”<CR><LF>
<CR><LF>
OK<CR><LF>
AT+HTTPACTION=0<CR><LF>
<CR><LF>
OK<CR><LF>
<CR><LF>
+HTTPACTION: 0,200,278<CR><LF>
AT+HTTPSTATUS?<CR><LF>
<CR><LF>
+HTTPSTATUS: GET,0,0,0<CR><LF>
<CR><LF>
OK<CR><LF>
AT+HTTPTERM<CR><LF>
<CR><LF>
OK<CR><LF>

 

 

THE SKETCH

Earlier than beginning the outline of the Arduino firmware, let’s spend just a few phrases on programming the EEPROM reminiscence with all of the string constants. The definition of the Arduino board used is contained within the GSM library, significantly within the “Io_GSM.h” file. In our case, we’re utilizing Arduino Mega 2560, and due to this fact, the directive is lively:

 

#outline ARDUINO_MEGA2560_REV3

 

whereas the opposite is clearly commented. All the time within the file “Io_GSM.h” have been enabled the directives for the administration of state machines for AT instructions for GPRS, TCP/IP, and HTTP.

 

#outline ENABLE_ANSWER_GPRS_AT_CMD_STATE

#outline ENABLE_ANSWER_TCP_IP_AT_CMD_STATE

#outline ENABLE_ANSWER_HTTP_AT_CMD_STATE

 

and associated states:

 

#outline ANSWER_GPRS_AT_CMD_STATE 5

#outline ANSWER_TCP_IP_AT_CMD_STATE 6

#outline ANSWER_HTTP_AT_CMD_STATE 7

 

Within the sketch of writing to EEPROM should be outlined the string constants needed for the information connection, particularly, for our utility, are strictly needed solely the next:

 

const char FLASH_APN[] PROGMEM = “”iliad””

const char FLASH_HTTP_URL[] PROGMEM = “”http://api.thingspeak.com/replace.json?api_key=89QC6FHH0AU9636Z””

 

The primary one signifies the APN offered by your cellphone operator for the information connection, so it’s a must to insert the APN offered by your operator, whereas the second is the URL wanted for the information connection to the “ThingSpeak” platform regarding your channel. If used, additionally, you will should configure the PIN and PUK code string. Every part else will be left unchanged.

Having stated that, you’ll should program the Arduino Mega with the code within the sketch.

Let’s analyze our sketch, which is split into 5 separate recordsdata.

  • GSM_EnergyMeter_Thingspeak.ino  Foremost file with all variable declarations, declaration of I/O probably usable by the sketch, directives to the compiler of the string constants utilized by the serial monitor, definition of the state machines used in addition to the 2 features “void setup()” and “void loop().”
  • DigitalInput.ino  accommodates the administration of the digital enter I/O. Presently, the digital inputs of the 2 buttons P1 and P2 of the GSM_EnergyMete R.1.0 board should not used on this model of the sketch.
  • DigitalOutput.ino  accommodates the administration of the digital output I/O. The output I/O of the GSM_EnergyMete R.1.0 board are the buzzer, the 2 relays, and the 4 LEDs.
    We want solely LEDs 1 and 4.
  • Measures.ino  accommodates the code wanted to handle the state machine that reads the information of {the electrical} measurements made by the MCP39F511 and the relative code for printing on the serial monitor.
  • Timersint.ino ® accommodates the administration of the interrupt vector for TIMER 5. Time base 2 ms.

 

Let’s analyze first the file GSM_EnergyMeter_Thingspeak.ino the place on the high, we discover the directive to the compiler that signifies how typically we wish to ship information about electrical measurements to the platform “ThingSpeak.” Directive:

 

#outline TIMEOUT_THINGSPEAK_SEND_DATA

 

accepts as values 20, 30, 0 60, indicating that information must be despatched each 20, 30, and 60 seconds, respectively. The directives ought to accompany this directive to the compiler within the MCP39F511 administration library, particularly:

 

#outline ENABLE_AVERAGE_CALC

#outline AVERAGE_ARRAY_SIZE 4

 

The primary permits the calculation of the typical worth over {the electrical} measurements taken, whereas the second defines the scale of the array for use to common the values. Allowed values are 4, 8, 16, or 32.

For the reason that studying {of electrical} measurements happens each two seconds, it is strongly recommended to have a buffer of size 8 for sending information each 20 seconds, a buffer of size 16 for sending information each 30 seconds, and a buffer of 32 in case you ship information each 60 seconds. It’s not necessary to calculate the typical worth to be despatched to the platform; if you wish to ship the instantaneous worth with out averaging, it’s essential to touch upon the above directive. The typical of the learn values might be routinely disabled.  Fig. 12 reveals a hypothetical measurement state of affairs the place the blue hint is the time pattern of the mains voltage learn each 2 seconds (a pattern each two seconds). The purple sign is the typical worth calculated with a buffer of size 8. In purple, we now have the time when information are despatched to ThingSpeak (each 20 s). There are two doable eventualities: the primary one sees the calculation of the typical worth disabled, then each 20 seconds, the final instantaneous worth measured might be despatched to the platform. Doing so will trigger you to lose all samples between one submission and the following.

The second state of affairs includes calculating the typical worth, so each 20 seconds, the typical worth calculated on eight samples is distributed (one pattern each two seconds).

There is no such thing as a lack of info as a result of intermediate samples between one submission and the following are all the time thought of.

 

Fig. 12

 

The idea turns into extra obvious by taking a look at Fig. 13, the place information is distributed each 30 seconds and each 60 seconds, respectively. Within the high graph, the imply worth is calculated utilizing a buffer of size 16, the sign in yellow; as proven in Fig. 12, the sign is slower in monitoring the unique sampled sign as a result of longer buffer. Similar for the underside graph, the place the buffer is 32 lengthy; on this case, it’s extra evident that if averaging was disabled, sending the instantaneous worth learn each 60 seconds can be poor in info since all the range sampled between one sending and the following can be misplaced.

 

Fig. 13

 

Buffer helps resolve this drawback by conserving observe of previous samples.

The draw back is that the longer the buffer, the extra SRAM is required to carry the samples wanted to carry out the averaging; it additionally requires an extended computation time. Be aware that sending a pattern each 20 seconds signifies that 1,576,800 samples per yr might be despatched to the platform, simply over half of these out there with the free model. If you happen to as a substitute ship samples each 30 seconds, it will likely be 1,051,200 samples in a yr. Lastly, at 60-second intervals, the platform will obtain 525,600 samples per yr.

Let’s proceed with the sketch evaluation; on the high of the file, we discover the string constants used each in the course of the printing on the serial monitor of {the electrical} measures and the strings that outline the sphere “subject” for the values to be despatched to the platform.

Let’s analyze the perform “void setup()” that initializes the sketch, which should cope with:

  • retrieve the EEPROM addresses the place all GSM library administration constants, together with information connections, are saved;
  • configure the enter and output I/O of the GSM defend;
  • configure the enter and output I/O of the Power Meter defend;
  • configure ISR Timer 1 library Power Meter administration from GSM library;
  • configure the UART for the serial monitor;
  • configure the UART for communication with the GSM module;
  • allow the GSM library interrupt;
  • allow the Power Meter library interrupt;
  • begin the initialization of the GSM module;
  • print the sketch revision on the serial monitor.

At this level the initialization is full and we will transfer on to the “void loop()” perform the place we discover:

 

ProcessStateMachineGsm();

ProcessHttpCmd();

 

The primary perform accommodates the code wanted to handle the GSM module, the three initialization steps, and the state machine administration features to ship the AT instructions required by the HTTP service towards the ThingSpeak platform. The state machine for studying electrical measurements can be managed when totally operational, which begins the studying sequence each two seconds. On this case, the relative printing of the learn values on the serial monitor is as soon as each 5 seconds.

In the course of the studying of {the electrical} measurements, if the perform is enabled, the respective arrays are loaded to calculate the typical worth. When needed, the corresponding perform is then referred to as that performs the typical worth calculation for every of the features for which it’s offered. For instance, the features wanted to calculate the typical worth are referred to as earlier than printing the learn common worth on the serial monitor or earlier than sending the information to ThingSpeak. The values contained within the arrays are of sort RAW, in order that they should be transformed to the proper worth to show relying on what number of decimal locations are offered. For instance, the next is used to print the typical worth of the RMS voltage:

 

Serial.println((float)(Cmd_39F511.MCP39F511_RmsVoltageRawAverage())/(pow(10, VOLTAGE_DEC)));

 

The fixed VOLTAGE_DEC is the same as two as a result of the RMS voltage measurements have solely two decimal locations; as you may see, the typical worth calculation was accomplished in the course of the printing on the Serial Monitor.

Let’s now speak concerning the state machine for dealing with AT instructions for sending information to the platform by way of the HTTP service. The perform gives a sequence of steps managed by a “switch-case” assemble. Every AT command is distributed at a price of 1 second aside. So the perform first makes positive that there aren’t any pending processes by checking the standing of some flags. If the time variable “Isr.TimeOutWait” is zero, it proceeds with sending the AT command equivalent to the present standing.

The sequence includes initializing the HTTP service (step 1) adopted by a service standing request (step 2). If the service is free, you begin sending information utilizing the HTTPPARA command divided into two steps (steps 3 and 4). In step 4, you ship the information to the chosen URL (saved in EEPROM) and queue the information to be despatched to the platform. The subsequent step (step 5), by the HTTPACTION command, requires a GET to the chosen URL. Within the subsequent step (step 6), the command is distributed once more to examine the standing of the service. If that is so, we confirm that the ACTION command is profitable, and solely then can we begin to shut the HTTP service with the termination command. In Itemizing 4, you’ll discover the code simply described.

The composition of the command to ship information to the chosen URL makes use of the “SetDataToHttpThingSpeak()” perform to load a particular array of the GSM library “Http.UrlParameters”.

Setting the “Http.HttpFlag.Bit.AddHttpParameters” flag to “1” tells the library that it should queue the string within the “Http.UrlParameters” array to the AT command.

Whereas sending information to the platform, LED 6 (yellow) on the GSM defend is lit, whereas LED 9 (inexperienced) flashes to point that the code is working easily.

Then again, on the EnergyMeter defend, LED 1 (purple) is lit in the course of the studying section of {the electrical} measurements and LED 4 (inexperienced) in the course of the printing section on the serial monitor of the identical.

Itemizing 4

void ProcessHttpCmd(void) {
if ((Gsm.GsmFlag.Bit.GsmSendCmdInProgress == 0) && (Gsm.GsmFlag.Bit.GsmInitInProgress == 0) &&
(Gsm.GsmFlag.Bit.GprsInitInProgress == 0) && (Gsm.GsmFlag.Bit.HttpInitInProgress == 0)) {
if (Isr.TimeOutWait == 0) {
Isr.TimeOutWait = T_1SEC;
change (LocalStateSendCmd)
{
case CMD_AT_HTTP_INIT:
Http.SetCmd_AT_HTTP_INIT();
LocalStateSendCmd = CMD_ATQ_HTTP_STATUS_1;
break;
case CMD_ATQ_HTTP_STATUS_1:
Http.SetCmd_AT_HTTP_STATUS();
LocalStateSendCmd = CMD_AT_HTTP_PARA_STEP_1;
break;
case CMD_AT_HTTP_PARA_STEP_1:
if (Http.HttpFlag.Bit.HttpStatus > 0) {
Http.SetCmd_AT_HTTP_STATUS();
break;
}
Io.LedOn(PIN_LED6);
Http.SetCmd_AT_HTTP_PARA(HTTP_PARAM_CID_CODE);
LocalStateSendCmd = CMD_AT_HTTP_PARA_STEP_2;
break;
case CMD_AT_HTTP_PARA_STEP_2:
Http.HttpFlag.Bit.AddHttpParameters = 1;
SetDataToHttpThingSpeak();
Http.SetCmd_AT_HTTP_PARA(HTTP_PARAM_URL_CODE);
LocalStateSendCmd = CMD_AT_HTTP_ACTION;
break;
case CMD_AT_HTTP_ACTION:
Http.SetCmd_AT_HTTP_ACTION(HTTP_ACTION_METHOD_GET);
LocalStateSendCmd = CMD_ATQ_HTTP_STATUS_2;
break;
case CMD_ATQ_HTTP_STATUS_2:
TimeOutHttpAction = T_5SEC;
Http.SetCmd_AT_HTTP_STATUS();
LocalStateSendCmd = CMD_AT_HTTP_TERM;
break;
case CMD_AT_HTTP_TERM:
if (Http.HttpFlag.Bit.HttpStatus > 0) {
Http.SetCmd_AT_HTTP_STATUS();
break;
}
if (Http.HttpFlag.Bit.HttpStatusCode != 200) {
if (TimeOutHttpAction > 0) {
break;
}
}
Http.SetCmd_AT_HTTP_TERM();
LocalStateSendCmd = CMD_AT_HTTP_INIT;
#if TIMEOUT_THINGSPEAK_SEND_DATA == 20
Isr.TimeOutWait = T_12SEC;
#elif TIMEOUT_THINGSPEAK_SEND_DATA == 30
Isr.TimeOutWait = T_22SEC;
#elif TIMEOUT_THINGSPEAK_SEND_DATA == 60
Isr.TimeOutWait = T_52SEC;
#else
Isr.TimeOutWait = T_22SEC;
#endif
Io.LedOff(PIN_LED6);
break;
case CMD_AT_NOTHING:
Io.LedOff(PIN_LED6);
break;
default:
break;
}
}
}
}

 

 

CURIOSITIES

Some smartphones APPs help you view the graphs on ThingSpeak for the chosen ID and its studying API key in your cellular phone. Now we have tried, on the Android platform, “ThingView Free” (there’s additionally a paid model that’s richer in options referred to as “ThingView Full,” which prices about 2 €) and, as soon as put in, permits us to configure the channel to view amongst these out there in your account.

Fig. 14 reveals the configuration part the place it’s a must to enter the channel ID and uncheck or depart the checkmark on the “Public” label (if the channel is personal, uncheck it).

 

Fig. 14

 

Fig. 15 reveals our channel with the corresponding electrical measurements: click on on “Carried out” to substantiate the information and get the reference to the channel with the measures (Fig. 16); choosing the channel will show solely the graphs set within the channel as proven in Fig. 17 and Fig.  18. With the paid model, you get further and superior options for information visualization, permitting for extra in-depth evaluation (Fig. 19).

 

Fig. 15

Fig. 16

Fig. 17

Fig. 18

Fig. 19

 

CONCLUSIONS

We are able to contemplate concluded each the dialogue of the sketch for sending information to the ThingSpeak platform and the adjustments made to the libraries for managing GSM modules and the built-in MCP39F511.

 

FROM OPENSTORE

Power meter module

Common GSM Protect

VOLTAGE MEASUREMENT TRANSFORMER

CURRENT MEASUREMENT TRANSFORMER

 

Leave a Comment