Electronics

ENERGY METER IOT – Open Electronics

 

Let’s interface our Energy Meter with Web to carry measurements to the ThingSpeak platform and see the ends in 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 techniques via the FT1346M board. We now have built-in it with the GSM board and its administration library to face the system to the exterior world. Now we need to present you how you can mix such {hardware} with an internet platform for IoT machine administration referred to as “ThingSpeak“. For the event, we have now 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 how you can combine the 2 libraries and create a web page on ThingSpeak to show the acquired knowledge.

Since we are going to use HTTP to hook up with the ThingSpeak platform, we are able to 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 knowledge out of your machine to the platform and think about the information acquired in real-time, presumably sending alerts via the Twitter and Twilio providers. 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 acquired. This enables designers to construct IoT techniques with out organising server providers or writing net software program.

Using 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 12 months (a mean of 8,200 per day).

Once you activate paid licenses you purchase Items akin 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 help you create a finite variety of Channels.

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

After this temporary introduction to the platform, we are able to transfer on to the outline of how you can create Channels with its associated fields.

Step one, for individuals who aren’t but an enabled person, is to register and to do that it’s essential to click on on “Signal Up” and comply with the steps indicated.

As soon as the registration is finished you possibly can proceed to the creation of a brand new Channel and to do that it’s essential to click on on the button “New Channel” as proven in Fig. 1, part circled in purple. A type will look like crammed 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 discipline); we determined to assign the title EnergyMeter;

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

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

– Subject 1 Voltage

– Subject 2  Present

– Subject 3  Energy Issue

– Subject 4  Lively Energy

– Subject 5  Reactive Energy

– Subject 6  Obvious Energy

4)    if you need, you possibly can insert the geo-localization knowledge, that’s Elevation, Latitude and Longitude; with these parameters, a geographic map can 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 aren’t used for this software.

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 title seems a closed padlock, indicating that the show is non-public; it’s doable to configure the Channel as public (the padlock opens) and due to this fact seen from outdoors. Once you publish the Channel, it may be seen by everybody or solely by approved customers.

Clicking on the newly created Channel opens a bit the place you possibly can:

  • 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 acquired for every of the “Fields” created within the “Personal View” part (the information displayed below this heading can be seen solely within the non-public part);
  • configure the show of the information acquired for every of the “Fields” created within the “Public View” part (the information displayed below this heading can be seen to anybody or to a restricted circle of chosen customers);
  • by clicking on the “API Keys” merchandise you might have entry to the learn/write keys related to the created Channel.

 

Fig. 3

 

The write secret is clearly completely different from the learn key; the previous, related to the URL handle of the connection to ThingSpeak, means that you can ship knowledge in string format to the fields beforehand created. For instance:

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

 

As you possibly can 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.

Beneath “Personal View” you possibly can configure which knowledge to show amongst these obtainable and how you can show them. Let’s see the instructions.

  • “Add Visualization permits associating a graph for every configured “Subject” among the many eight obtainable. If the command is clicked on, a range window is proposed from which to decide on the “Subject” whose knowledge is to be visualized (Fig. 4). On this case, solely “Subject 3” is out there, if you happen to click on on the chart after which on “Save” the corresponding chart can be created. Fig. 5 exhibits the newly created graph akin to “Subject 3”.

 

Fig. 4

Fig. 5

The chart clearly will be custom-made and to entry the configuration part it’s essential to click on on the pencil icon on the prime proper of the chart. On this manner the suitable configuration window known as, as proven in Fig. 6.

 

Fig. 6

 

On this window you possibly can configure:

  • Title is used to assign a label to the chart akin to “Subject 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”;
  • Shade means that you can set the hexadecimal worth and the colour of the graph;
  • Background is used to set hexadecimal worth and shade 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 implies that it’s robotically up to date each 15 seconds);

Days units what number of 24 hour intervals to attend earlier than together with the acquired 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 an information must be displayed amongst these acquired (optionally available);

Common units each what number of minutes the common worth of the acquired knowledge must be calculated and displayed;

Median units each what number of minutes the median of the acquired knowledge must be calculated and displayed;

Sum is used to set each what number of minutes the sum of the acquired knowledge 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; means that you can configure different strategies of displaying the acquired knowledge; 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 exhibits 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 get hold of the specified consequence together with:

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

Subject is used to set the related “Subject” from which to take the information to be visualized; right here we check with “Subject 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 count on 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 have now 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 shade;

– Numeric Show is used to set a numeric sort show (Fig. 8 exhibits 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 title to be assigned to the viewer (on this case, “Lively Energy”);

Subject is used to set the related “Subject” from which to take the information to be visualized (right here we check with “Subject 4”);

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

Items 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 acquired knowledge is above or under threshold (depends upon settings);

  • Export latest knowledge; permits to export the acquired knowledge 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 acquired knowledge;
  • MATLAB Visualization means that you can create MATLAB code to research and visualize the acquired knowledge.

 

Fig. 7

Fig. 8

 

Beneath the merchandise “Public View” we are able to configure, as already carried out for the non-public part, the visualization of the information acquired from the varied “Fields” with the distinction that these are seen to the surface. To make the information seen it’s essential to 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 is not going to dwell on it any additional.

Fig. 9, Fig. 10 and Fig.  11 present how we configured our “Channel” to show the information acquired 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 have now 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 lively energy acquisitions relative to a few days, so {that a} comparability will be made. The times may also be roughly, relying on the MATLAB code.

 

Fig. 11

 

To provide an thought, 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 need to graph (myFieldID) and the important thing to learn the information (readAPIKey). The “thingSpeakRead” operate 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 knowledge from
readChannelID = 870302;
% Lively Energy Subject ID
myFieldID = 4;
% Sooner or later 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 ‘’ under:
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 mentioned that, let’s go additional: to create the sketch that sends {the electrical} measurements to the “ThingSpeak” platform, it’s mandatory 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 reality if we take the libraries with out making any modifications 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 specifically with the information “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 can 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. Inside 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 have now to create a brand new operate inside which we have now 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 operate we have now the time variable administration code wanted by the MCP39F511 library that you just see in Itemizing 2. Relying on the chosen UART the suitable time variable can be used. Let’s go now to the GSM module administration library and specifically the information “Isr_GSM.h” and “Isr_GSM.cpp”. Within the first one we have now 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 operate pointer directed to the Flash handle the place the TIMER 1 interrupt dealing with operate of the MCP39F511 library is saved:

 

#ifdef ENABLE_EXT_TIMER1

    static void (* risky __Ext_Timer1_Vector)(void);

#endif

 

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

 

#ifdef ENABLE_EXT_TIMER1       

        void Ext_Timer1_Vector(void (*operate)(void));

#endif

 

That is additionally lively if the directive permits it.

The code current on this operate is:

 

#ifdef ENABLE_EXT_TIMER1 

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

    {     

        __Ext_Timer1_Vector = operate;

    }

#endif

 

and is used to load into the operate pointer the Flash handle of the operate to be referred to as.

Now we have now 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 mandatory code to name the specified operate:

 

ISR(TIMER1_OVF_vect) {

    TCNT1 = SLOWBASETIME;

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

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

#ifdef ENABLE_EXT_TIMER1

    if (__Ext_Timer1_Vector != NULL) {

        __Ext_Timer1_Vector();

    }

#endif   

}

 

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

 

Isr.Ext_Timer1_Vector(Isr_39F511.Timer1_Interrupt);

 

By calling this operate we made certain that throughout 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 extra enchancment because of the introduction of a sequence 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 have now 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 dimensions of the arrays, the extra SRAM reminiscence can be wanted. Subsequently, the dimensions for use should be chosen rigorously relying on the appliance to be applied (we are going to give a concrete instance after we discuss in regards to the sketch for sending knowledge to the “ThingSpeak” platform). The features for calculating the common worth are as described under.

  • uint16_t MCP39F511_RmsVoltageRawAverage(void) ® Calculates the common worth for the voltage measurement. The operate 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 operate 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 facility issue measure. The operate 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 operate uint16_t CalcAveragePowerFactor(void).
  • uint16_t MCP39F511_LineFrequencyRawAverage(void) ® Calculates the common worth with respect to the road frequency measurement. The operate 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 lively energy measurement. The operate 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 operate 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 operate 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, nevertheless the array they should work on modifications. Let’s analyze the operate 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 possibly can see, other than the native variables, we have now the do-while assemble that takes care of averaging over the values contained within the corresponding array.

The bigger the dimensions of the array, the longer it’ll take to calculate the common worth. The operate, 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) ® Hundreds the final learn worth of the RMS voltage into the “VoltageRmsRaw_Array” array;
  • void MCP39F511_UpdateLineFrequencyRawArray(void) ® Hundreds the final learn worth of the community frequency into the “LineFrequencyRaw_Array” array;
  • void MCP39F511_UpdatePowerFactorRawArray(void) ® Hundreds the final learn worth of the facility issue into the “PowerFactorRaw_Array” array;
  • void MCP39F511_UpdateRmsCurrentRawArray(void) ® Hundreds the final learn worth of the RMS present into the “CurrentRmsRaw_Array” array;
  • void MCP39F511_UpdateActivePowerRawArray(void) ® Hundreds the final learn worth of the lively energy into the “ActivePowerRaw_Array” array;
  • void MCP39F511_UpdateReactivePowerRawArray(void) ® Hundreds the final learn worth of the reactive energy into the “ReactivePowerRaw_Array” array;
  • void MCP39F511_UpdateApparentPowerRawArray(void) ® Hundreds 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 have now mentioned in earlier articles, we have now added the features essential to handle knowledge connections. Three new information named respectively “GprsCmd_GSM.cpp”, “TcpIpCmd_GSM.cpp”, “HttpCmd_GSM.cpp” and associated .h information have been created. The GSM SimCom modules are absolutely supported, the Quectel M95 is partially supported, and the Fibocom G510 isn’t supported.

When it’s mandatory to make use of AT instructions to handle knowledge connections, a preliminary GSM module initialization part just like the one already used and broadly defined for GSM connections (SMS and Voice) should be carried out. So the newest obtainable revision of our library can run:

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

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

  • AT+CGATT?  begins with a command that checks if the machine is related or to not the GPRS service and, in response to the consequence obtained, it’ll 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 consequence codes regarding the connection to the GPRS service;
  • AT+CSTT=”OWN OPERATOR ” ® units the APN (Entry Level Title) and, if mandatory, additionally sends Consumer 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 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 handle assigned to the PDP context, which is completely 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 acquired knowledge packet;
  • AT++CIPSRIP=1  units the GSM module to return, through “unsolicited consequence code”, the distant IP handle and port when an information packet is acquired;
  • 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 provider 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 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 possibly can see, it accommodates three unbiased 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 knowledge to ThingSpeak).

Under 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 through 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 knowledge. The third parameter signifies how a lot knowledge has been transmitted, and the final parameter signifies how a lot knowledge 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 knowledge to the ThingSpeak platform through the HTTP service: on the prime and on the backside, we have now 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 isn’t 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 concerning knowledge connection administration: there are constants strings that should be saved in EEPROM as already carried out for PIN codes, PUKs, and others. So there are directives to the compiler the place these constants are outlined and the utmost area they will occupy in EEPROM. Nevertheless, the writing in EEPROM of those string constants can solely be carried out via a particular sketch that we have now already mentioned on different events. The string constants that should 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 knowledge 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 knowledge 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 throughout the sketch initialization section and saved within the acceptable knowledge constructions 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 couple 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, notably 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 mandatory for the information connection, specifically, for our software, are strictly mandatory 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 telephone operator for the information connection, so you need 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 thing else will be left unchanged.

Having mentioned 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 information.

  • GSM_EnergyMeter_Thingspeak.ino  Primary 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 aren’t 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 usually we need to ship knowledge about electrical measurements to the platform “ThingSpeak.” Directive:

 

#outline TIMEOUT_THINGSPEAK_SEND_DATA

 

accepts as values 20, 30, 0 60, indicating that knowledge 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, specifically:

 

#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 dimensions of the array for use to common the values. Allowed values are 4, 8, 16, or 32.

Because the studying {of electrical} measurements happens each two seconds, it is suggested to have a buffer of size 8 for sending knowledge each 20 seconds, a buffer of size 16 for sending knowledge each 30 seconds, and a buffer of 32 if you happen to ship knowledge each 60 seconds. It’s not obligatory 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 typical of the learn values can be robotically disabled.  Fig. 12 exhibits a hypothetical measurement situation the place the blue hint is the time development 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 have now the time when knowledge 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 can 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 distributed (one pattern each two seconds).

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

 

Fig. 12

 

The idea turns into extra obvious by Fig. 13, the place knowledge is distributed 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 data since all the variability sampled between one sending and the following could be misplaced.

 

Fig. 13

 

Buffer helps remedy this drawback by conserving monitor 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. Word that sending a pattern each 20 seconds implies that 1,576,800 samples per 12 months can be despatched to the platform, simply over half of these obtainable with the free model. Should you as a substitute ship samples each 30 seconds, it will likely 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 throughout the printing on the serial monitor of {the electrical} measures and the strings that outline the sphere “discipline” for the values to be despatched to the platform.

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

  • retrieve the EEPROM addresses the place all GSM library administration constants, together with knowledge connections, are saved;
  • configure the enter and output I/O of the GSM protect;
  • configure the enter and output I/O of the Vitality Meter protect;
  • 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 are able to transfer on to the “void loop()” operate the place we discover:

 

ProcessStateMachineGsm();

ProcessHttpCmd();

 

The primary operate 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 also be managed when absolutely 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 operate is enabled, the respective arrays are loaded to calculate the common worth. When mandatory, the corresponding operate is then referred to as that performs the common worth calculation for every of the features for which it’s offered. For instance, the features wanted to calculate the common 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 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 possibly can see, the common worth calculation was carried out throughout the printing on the Serial Monitor.

Let’s now discuss in regards to the state machine for dealing with AT instructions for sending knowledge to the platform through the HTTP service. The operate gives a sequence of steps managed via a “switch-case” assemble. Every AT command is distributed at a fee of 1 second aside. So the operate first makes certain 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 akin 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 knowledge 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), via the HTTPACTION command, requires a GET to the chosen URL. Within the subsequent step (step 6), the command is distributed once more to test the standing of the service. If that is 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 can see the code simply described.

The composition of the command to ship knowledge to the chosen URL makes use of the “SetDataToHttpThingSpeak()” operate 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 knowledge to the platform, LED 6 (yellow) on the GSM protect is lit, whereas LED 9 (inexperienced) flashes to point that the code is operating easily.

Then again, on the EnergyMeter protect, LED 1 (purple) is lit throughout the studying section of {the electrical} measurements and LED 4 (inexperienced) throughout 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;
swap (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 mobile phone. We now 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 obtainable in your account.

Fig. 14 exhibits the configuration part the place you need to enter the channel ID and uncheck or go away the checkmark on the “Public” label (if the channel is non-public, uncheck it).

 

Fig. 14

 

Fig. 15 exhibits our channel with the corresponding electrical measurements: click on on “Accomplished” 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 knowledge visualization, permitting for extra in-depth evaluation (Fig. 19).

 

Fig. 15

Fig. 16

Fig. 17

Fig. 18

Fig. 19

 

CONCLUSIONS

We are able to take into account concluded each the dialogue of the sketch for sending knowledge 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

five − 2 =