Electronics Product Rating

ENERGY METER IOT – Open Electronics

 

Let’s interface our Energy Meter with Web to deliver measurements to the ThingSpeak platform and see the leads to handy graphs.

 

A couple of posts in the past, we launched the MCP39F511 built-in circuit, able to performing electrical measurements in single-phase electrical methods by way of the FT1346M board. We’ve got 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 find out how to mix such {hardware} with an online platform for IoT system administration known as “ThingSpeak“. For the event, we’ve got 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 find out how 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 knowledge from digital units recognized as IOT (Web of Issues). It’s then doable to ship information out of your system to the platform and look at the information obtained in real-time, probably sending alerts by way of the Twitter and Twilio providers. As well as, the platform offers 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 methods with out organising server providers or writing internet software program.

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

If you activate paid licenses you purchase Items comparable to 33 million messages that may be processed and saved in a single 12 months or in different phrases about 90,000 messages per day.

As well as, the Items let 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 transient introduction to the platform, we will transfer on to the outline of find out how to create Channels with its associated fields.

Step one, for many who usually are not but an enabled person, is to register and to do that you should click on on “Signal Up” and comply with the steps indicated.

As soon as the registration is finished you may proceed to the creation of a brand new Channel and to do that you should click on on the button “New Channel” as proven in Fig. 1, part circled in purple. A type will seem like stuffed in with a number of fields, as proven in Fig. 2, the steps to comply with 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’ve got inserted as description “MCP39F511 Vitality Meter”;

3)    for every Channel you may activate eight totally different fields, every of those represents a measurement to be saved and processed; we’ve got activated six fields out of eight; particularly, we’ve got 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)    in order for you, you may insert the geo-localization information, that’s Elevation, Latitude and Longitude; with these parameters, a geographic map shall 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 usually are not used for this utility.

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

 

Fig. 2

 

Now, below “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 non-public; it’s doable to configure the Channel as public (the padlock opens) and subsequently seen from outdoors. If 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/non-public by clicking on the “Sharing” merchandise;
  • configure the show of the information obtained for every of the “Fields” created within the “Non-public View” part (the information displayed below this heading shall be seen solely within the non-public part);
  • configure the show of the information obtained for every of the “Fields” created within the “Public View” part (the information displayed below this heading shall be seen to anybody or to a restricted circle of chosen customers);
  • by clicking on the “API Keys” merchandise you may 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 handle of the connection to ThingSpeak, permits you to ship information in string format to the fields beforehand created. For instance:

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

 

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

Below “Non-public View” you may configure which information to show amongst these accessible and find out how to show them. Let’s see the instructions.

  • “Add Visualization permits associating a graph for every configured “Area” among the many eight accessible. If the command is clicked on, a variety 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 on the market, for those who click on on the chart after which on “Save” the corresponding chart shall be created. Fig. 5 reveals the newly created graph comparable to “Area 3”.

 

Fig. 4

Fig. 5

The chart clearly might be personalized and to entry the configuration part you should click on on the pencil icon on the prime proper of the chart. On this method the suitable configuration window is named, as proven in Fig. 6.

 

Fig. 6

 

On this window you may configure:

  • Title is used to assign a label to the chart comparable 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”;
  • Colour permits you to set the hexadecimal worth and the colour of the graph;
  • Background is used to set hexadecimal worth and coloration 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 robotically 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 (elective);

Common units each what number of minutes the common 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;

Knowledge Min is used to set the minimal anticipated worth;

Knowledge 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 variety 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 have to be stuffed in to be able to receive the specified end result 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 consult with “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;

Items 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’ve got 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 distinct coloration;

– Numeric Show is used to set a numeric sort show (Fig. 8 reveals the configuration used for the energetic 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 consult with “Area 4”);

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

Items of measurement (watts “W”);

Knowledge 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 have to 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 (relies on settings);

  • Export latest 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 research and visualize the obtained information.

 

Fig. 7

Fig. 8

 

Below the merchandise “Public View” we will configure, as already completed for the non-public part, the visualization of the information obtained from the varied “Fields” with the distinction that these are seen to the surface. To make the information seen you should name up the “Sharing” part and comply with the directions. The configuration of the general public part is similar to the non-public 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 through graph and pointer indicator. Identical for Lively, Reactive and Obvious energy measurements with the distinction that for these we’ve got 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 through MATLAB (3-Day Lively Energy Comparability) that correlates energetic energy acquisitions relative to 3 days, so {that a} comparability might be made. The times will also be kind of, relying on the MATLAB code.

 

Fig. 11

 

To offer 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 determine the feedback. Three variables have been declared that determine 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 short legend.

Itemizing 1

% Channel ID to learn information from
readChannelID = 870302;
% Lively Energy Area ID
myFieldID = 4;
% In the future date vary
oneDay = [datetime(‘yesterday’) datetime(‘today’)];
% Channel Learn API Key
% In case your channel is non-public, then enter the learn API key between the ‘’ beneath:
readAPIKey = ‘LU2P9AT2EOTD79Q8’;
% Learn Lively Energy Knowledge
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 begin with to combine and harmonize the 2 libraries GSM and MCP39F511 in order that they will 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.

In truth if we take the libraries with out making any modifications and embrace 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 shall be ignored, vice versa will probably be included within the library.

So when the MCP39F511 library is for use alone in a sketch it have to be uncommented, whereas whether it is for use along with the GSM library it have to 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’ve got to create a brand new perform inside which we’ve got to place the code used within the administration of the interrupt vector of TIMER 1:

 

static unstable void Isr_MCP39F511::Timer1_Interrupt(void)

 

Contained in the perform we’ve got 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 shall 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’ve got 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 handle the place the TIMER 1 interrupt dealing with perform of the MCP39F511 library is saved:

 

#ifdef ENABLE_EXT_TIMER1

    static void (* unstable __Ext_Timer1_Vector)(void);

#endif

 

The perform pointer is barely thought-about if the directive to the compiler ENABLE_EXT_TIMER1 is uncommented and subsequently energetic. The perform pointer is energetic on the time when the directive to the compiler ENABLE_EXT_TIMER1 is energetic (i.e. not commented out). That stated we should create a perform, to be known as through the initialization of the sketch, which assigns to the pointer described earlier than the beginning handle 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 energetic if the directive permits it.

The code current on this perform is:

 

#ifdef ENABLE_EXT_TIMER1 

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

    {     

        __Ext_Timer1_Vector = perform;

    }

#endif

 

and is used to load into the perform pointer the Flash handle of the perform to be known as.

Now we’ve got the handle 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’ve got concluded the modifications to the 2 libraries. Now contained in the sketch, through 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 through 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 modifications talked about above has been affected by an additional enchancment because of the introduction of a collection of features for the calculation of the common worth on some electrical measurements. Through the directive to the compiler:

 

#outline ENABLE_AVERAGE_CALC

allow/disable the features for calculating the common worth and relative administration arrays. Along with the above directive, we’ve got launched one other one for outlining the scale that the arrays wanted to calculate the common worth will need to 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 shall be wanted. Subsequently, the scale for use have to be chosen rigorously relying on the appliance to be applied (we are going to give a concrete instance once we discuss in regards to the sketch for sending information to the “ThingSpeak” platform). The features for calculating the common worth are as described beneath.

  • uint16_t MCP39F511_RmsVoltageRawAverage(void) ® Calculates the common 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 common worth concerning 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 common 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 desires the auxiliary perform uint16_t CalcAveragePowerFactor(void).
  • uint16_t MCP39F511_LineFrequencyRawAverage(void) ® Calculates the common 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 common worth with respect to the energetic 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 common 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 common 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 comparable, nonetheless the array they must work on modifications. 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’ve got 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 would take to calculate the common 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 energetic 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’ve got mentioned in earlier articles, we’ve got 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 just like the one already used and extensively defined for GSM connections (SMS and Voice) have to be carried out. So the newest accessible revision of our library can run:

  • Fundamental initialization of the GSM module for SMS and voice administration;
  • Initialization to GPRS (Common Packet Radio Service);
  • Knowledge 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 system is related or to not the GPRS service and, in line with the end result obtained, it would execute or not the following command;
  • AT+CGATT=1  hooks the GSM module to the GPRS;
  • AT+CIPMUX=0  allows a Single IP Connection;
  • AT+CGEREP=1  allows the GSM to ship, through serial interface, the unsolicited end result codes regarding the connection to the GPRS service;
  • AT+CSTT=”OWN OPERATOR ” ® units the APN (Entry Level Title) and, if needed, additionally sends Person Title and Password;
  • AT+CIICR  prompts the information connection to the GPRS service;
  • AT+CIFSR  command to show the native IP handle assigned by the GPRS service;
  • AT+CGDCONT=1, “IP”, “OWN OPERATOR”  used to outline the PDP context (“Packet Knowledge Protocol”); the PDP context used is “IP”;
  • AT+CGATC=1,1  prompts the PDP context;
  • AT+CGPADDR=1  command used to show the IP handle assigned to the PDP context, which is totally different from the IP handle assigned by the GPRS service;
  • AT+CIPHEAD=1  used to configure the GSM module to return the IP handle of the sender on the head of the obtained information packet;
  • AT++CIPSRIP=1  units the GSM module to return, through “unsolicited end result code”, the distant IP handle 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 handle (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 have to be set to at least one:

 

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

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

As an alternative, the dealing with code within the sketch to make sure the right 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 traditional 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 offers a collection of different instructions for managing the information connection through HTTP service (utilized in our instance sketch).

  • AT+HTTPINIT ® used for initializing the HTTP service, have to 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 components, 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 have to be executed because the final command.

 

The next is the sequence of the AT instructions used to ship information to the ThingSpeak platform through the HTTP service: on the prime and on the backside, we’ve got 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 shipped 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 concerning information connection administration: there are constants strings that have to be saved in EEPROM as already completed for PIN codes, PUKs, and others. So there are directives to the compiler the place these constants are outlined and the utmost house they will occupy in EEPROM. Nonetheless, the writing in EEPROM of those string constants can solely be completed by way of a particular sketch that we’ve got already mentioned on different events. The string constants that have to be saved in EEPROM are:

  • APN telephone operator;
  • Username and Password for APN (they aren’t at all times used however have been outlined anyway in case of want);
  • PDP context;
  • distant server IP handle 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 through the sketch initialization section and saved within the applicable information buildings in order that they’re at all times 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 a number of 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 subsequently, the directive is energetic:

 

#outline ARDUINO_MEGA2560_REV3

 

whereas the opposite is clearly commented. At all times 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 have to 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 supplied by your telephone operator for the information connection, so it’s a must to insert the APN supplied 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 must configure the PIN and PUK code string. All the things else might be left unchanged.

Having stated that, you’ll must 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  Important 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. At the moment, the digital inputs of the 2 buttons P1 and P2 of the GSM_EnergyMete R.1.0 board usually are 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 prime, 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 allows the calculation of the common 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’s endorsed 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 for those who ship information each 60 seconds. It’s not necessary to calculate the common 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 common of the learn values shall be robotically disabled.  Fig. 12 reveals a hypothetical measurement situation 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 common worth calculated with a buffer of size 8. In purple, we’ve got the time when information are despatched to ThingSpeak (each 20 s). There are two doable situations: the primary one sees the calculation of the common worth disabled, then each 20 seconds, the final instantaneous worth measured shall be despatched to the platform. Doing so will trigger you to lose all samples between one submission and the following.

The second situation entails calculating the common worth, so each 20 seconds, the common worth calculated on eight samples is shipped (one pattern each two seconds).

There isn’t any lack of info as a result of intermediate samples between one submission and the following are at all times thought-about.

 

Fig. 12

 

The idea turns into extra obvious by taking a look at Fig. 13, the place information is shipped each 30 seconds and each 60 seconds, respectively. Within the prime 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 because of the longer buffer. Identical 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 could be poor in info since all the variability sampled between one sending and the following could be misplaced.

 

Fig. 13

 

Buffer helps clear up this downside by holding 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. Observe that sending a pattern each 20 seconds signifies that 1,576,800 samples per 12 months shall be despatched to the platform, simply over half of these accessible with the free model. In the event you as an alternative ship samples each 30 seconds, will probably be 1,051,200 samples in a 12 months. Lastly, at 60-second intervals, the platform will obtain 525,600 samples per 12 months.

Let’s proceed with the sketch evaluation; on the prime of the file, we discover the string constants used each through 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 take care of:

  • 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 Vitality Meter defend;
  • configure ISR Timer 1 library Vitality 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 Vitality 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.

Through the studying of {the electrical} measurements, if the perform is enabled, the respective arrays are loaded to calculate the common worth. When needed, the corresponding perform is then known as that performs the common worth calculation for every of the features for which it’s supplied. For instance, the features wanted to calculate the common worth are known 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, so that they have to be transformed to the right worth to show relying on what number of decimal locations are supplied. For instance, the next is used to print the common 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 common worth calculation was completed through the printing on the Serial Monitor.

Let’s now discuss in regards to the state machine for dealing with AT instructions for sending information to the platform through the HTTP service. The perform offers a collection of steps managed by way of a “switch-case” assemble. Every AT command is shipped at a fee of 1 second aside. So the perform first makes positive that there are not 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 comparable to the present standing.

The sequence entails 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 way of the HTTPACTION command, requires a GET to the chosen URL. Within the subsequent step (step 6), the command is shipped once more to verify the standing of the service. If so, we confirm that the ACTION command is profitable, and solely then will we begin to shut the HTTP service with the termination command. In Itemizing 4, you will 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 operating easily.

Then again, on the EnergyMeter defend, LED 1 (purple) is lit through the studying section of {the electrical} measurements and LED 4 (inexperienced) through 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 let you view the graphs on ThingSpeak for the chosen ID and its studying API key in your cellular phone. We’ve got tried, on the Android platform, “ThingView Free” (there may be additionally a paid model that’s richer in options known as “ThingView Full,” which prices about 2 €) and, as soon as put in, permits us to configure the channel to view amongst these accessible 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 non-public, uncheck it).

 

Fig. 14

 

Fig. 15 reveals our channel with the corresponding electrical measurements: click on on “Executed” 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 extra 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 will think about concluded each the dialogue of the sketch for sending information to the ThingSpeak platform and the modifications made to the libraries for managing GSM modules and the built-in MCP39F511.

 

FROM OPENSTORE

Energy meter module

Universal GSM Shield

VOLTAGE MEASUREMENT TRANSFORMER

CURRENT MEASUREMENT TRANSFORMER

 

Leave a Comment

eighteen − nine =