ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior...

48
ECE791/792 Final Paper Project Title: Smart Grid in the Home Project Team: Patrick O’Boyle & Amit Jain ECE Faculty Advisor: Allen Drake Date: May 23, 2013 Abstract: The Smart Grid in the Home is a power monitoring utility that reports information about power consumption on a web page. The results showed that the power usage statistics can be viewed from anywhere in the world, and is compatible with smart phones. Power statistics are stored on a secure MySQL database and reports the Watts and VARs measured from a standard 110V outlet.

Transcript of ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior...

Page 1: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE791/792 Final Paper

Project Title: Smart Grid in the Home

Project Team: Patrick O’Boyle & Amit Jain

ECE Faculty Advisor: Allen Drake

Date: May 23, 2013

Abstract:

The Smart Grid in the Home is a power monitoring utility that reports information about power

consumption on a web page. The results showed that the power usage statistics can be viewed from

anywhere in the world, and is compatible with smart phones. Power statistics are stored on a secure

MySQL database and reports the Watts and VARs measured from a standard 110V outlet.

Page 2: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 2

Page 3: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 3

Contents

Introduction ......................................................................................................................................5

Design ...............................................................................................................................................7

Implementation ............................................................................................................................... 10

Raspberry Pi ............................................................................................................................................ 13

Arduino UNO .......................................................................................................................................... 14

Web Development ........................................................................................................................... 15

Back End.................................................................................................................................................. 16

Front End ................................................................................................................................................ 18

Problems Faced ............................................................................................................................... 21

Budget ............................................................................................................................................. 22

Future Work .................................................................................................................................... 23

Performance .................................................................................................................................... 24

References ....................................................................................................................................... 25

Appendix A: HTML ........................................................................................................................... 26

Appendix B: Javascript ..................................................................................................................... 27

Appendix C: PHP Files ....................................................................................................................... 39

Appendix D: Python Files.................................................................................................................. 41

Appendix E: C++ ............................................................................................................................... 42

Appendix F: C ................................................................................................................................... 45

Appendix G: main.css Style Sheet ..................................................................................................... 48

Page 4: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 4

Figures Figure 1 - Smart Grid Operational Diagram ....................................................................................... 10

Figure 2 - Circuit Configuration of the ACS712 Hall-Effect Current Sensor ........................................... 11

Figure 3 - Circuit Configuration of the AC Voltage Transformer .......................................................... 11

Figure 4 - Circuit Configuration of the nRF24L01+ Wireless Module .................................................. 13

Figure 5 - Code Flowchart ................................................................................................................. 16

Figure 6 - Website Snapshot ............................................................................................................. 18

Page 5: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 5

Introduction

As the world moves toward being green and more conservative with energy usage, there is a

larger push for energy efficient homes and appliances. The home is where most electronic devices are

used and charged. People use appliances such as refrigerators, computers, air conditioners, televisions,

washing machines, and stoves which consume a lot of power without thinking much of it. These large

and small appliances can collectively guzzle a great amount of energy whether they are directly in use or

not. One of the only ways to determine how much energy is being used or wasted is by monitoring the

power readings on the house’s energy meter. The reading on these electrical energy meters is

synonymous with the total power used during a timeframe, given in kilowatt hours.

The power meters calculate how much electricity is used, and they are often located on the

outside of the house. It is in the interest of the power utility companies to calibrate the meters as

accurately as possible, because inaccurate calculations indicating lower energy usage result in a loss of

income. In addition, should the meters read inaccurate overages, refunds must be given to consumer.

The meter reading summarizes the overall power consumption from the utility company, but it does not

show how much power is being consumed at a more detailed level.

There are some devices that can be inserted between an outlet and load to show the load’s

energy consumption. The most popular is the Kill-A-Watt meter. This device is fairly large and bulky, and

it converts a two outlet socket into an individual socket with power monitoring. It is a simple solution to

view the power consumption of a single device. However, if one would want to view an entire home’s

power consumption, the Kill-A-Watt meter is not an economically sound solution, since the devices

range from $20-$50 per device.

Our Smart Grid in the Home is a system that allows for easy power monitoring of outlets with

the ability to control their power state. All of the power statistics are transmitted wirelessly between

Page 6: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 6

units to a central unit which uploads them to a database. This allows for easy scalability and data

storage management. The gathered statistics will then be displayed on a web page which also allows for

control of whether the outlet is active or not. By looking at the power consumption of an outlet, a user

can see if he or she has left an iron or a curling iron on, and shut it off remotely. This fire safety feature

is appealing to homeowners.

Power factor is an important part of the overall design, since the power factor needs to be

measured in order to find the Watts or VARs of a load. Watts are a measure of the power for a resistive

load, while VARs are a measure of the power for a reactive load. This means that you cannot make the

assumption that the voltage multiplied times the current is equal to the power, due to them both being

alternating sinusoids. If a computer was plugged into a similar device that only measured resistive

loads, the measured power from the outlet would be incorrect, since a computer contains reactive

elements such as capacitors and inductors.

Page 7: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 7

Design

The original design for the Smart Grid involved two different models of the sensor itself. The

first one was a user-friendly model to simply plug into the existing outlet. This device would have its

own case and would rest on the outside of an outlet, similar to the Kill-A-Watt meter. The second

design was an in-wall mount, where components were either placed into the outlet receptacle itself or

conversely in the wall in their own dedicated case. The second design was chosen for the prototype in

order to display all of the components used, as the first design was more difficult to implement since a

suitable case for the components to sit in would be needed. It was the original intention to use a 3D

printer to create a case for the components, but this was never realized in the final prototype.

The units measure power readings via hall-effect current sensors. These ICs take a power

source as an input, and output an alternating voltage proportional to the current flowing through the

source. A variety of chips exist with different current ratings, due to the nature of the analog to digital

converter (ADC). Since the ADC has a static resolution of 1024 bits, it means that there is a larger

increment in current values for higher amperage meters than lower ones. The higher amperage rated

current sensors have less precision, but are also able to accommodate a larger load. Chips with higher

current ratings have lower precision than those with lower ratings. It is possible to create several

models of the Smart Grid in order to accommodate higher power appliances. There exist higher rated

current sensors, of which are 5 Amp, 20 Amp, and 30 Amp.

In order to control the power state of the device plugged into the outlet, relay units were

implemented. There are two types of relays: electromechanical and solid state. Electromechanical

relays contain a solenoid capable of opening or closing a switch. When a current flows through the

solenoid coil, a magnetic field is induced to make the switch operate. Solid state relays allow for the

same control but with the relay composed of semiconductor materials instead of mechanical parts.

Page 8: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 8

Electromechanical relays were used in the prototype, but solid state should be explored since the

current sensors are susceptible to electromagnetic interference. The option of solid state relays may be

explored, as they offer less electromagnetic interference and kickback current due to bouncing when

states change.

A wireless mesh network operating at 2.4 GHz was originally designed to allow all the current

sensing devices to communicate with one another, but this idea was later abandoned since the range of

the wireless modules was increased by lowering the bandwidth between devices. The mesh network is

still a great idea, but involves a great amount of code to implement, since it involves a lot of chatter

between the Arduino devices. The 2.4 GHz spectrum was chosen because it is not licensed and allows

for free communication. The wireless modules chosen do not use the same protocol as 802.11b/g/n, so

the Arduinos do not have internet capability.

The base device of the system contains a wireless unit to communicate with the Arduino

microcontrollers. This is implemented with the Raspberry Pi, which is a device capable of operating linux

with general purpose I/O (GPIO) ports. A database-driven webserver is then hosted on the Raspberry Pi

to display the power measurements from the respective outlets. The webserver allows for the states of

the relays to be changed on each outlet, so that an end-user may turn outlets on or off from anywhere

in the world.

An Arduino microcontroller was be used to interface all the sensors and related components in

the slave devices. Analog to digital convertor pins on the Arduino were used to read the current value

of the sensor. This microcontroller was chosen because it is inexpensive, easy to use, has a large

support base, and offers many input and output pins with functions such as serial communication,

analog to digital converters, and pulse width modulation. The chips were powered internally from the

power from the wall.

Page 9: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 9

Equation 1: Phase Angle

Equation 1 shows the simple calculation of the phase angle based on the frequency (60Hz), and

the change in the time samples between measurements.

Equation 2: Power Factor

Equation 3: Reactive Factor

The power factor (eq. 1) and the reactive factor (eq. 2) are needed to calculate the Watts and

VARs being used in an outlet, where the subscripts ‘v’ and ‘i’ represent the voltage and current,

respectively. An additional statement may be added later in the code to show whether the power factor

is lagging or leading. When the power factor is lagging, it means that the load is inductive. When it is

leading, it means the load is capacitive. This can be useful information when determining what type of

load is attached to the device.

(

) Equation 4: Average Power

(

) Equation 5: Reactive Power

Equations 4 and 5 are the final values that are sent out from the C code. The subscript ‘m’ for

the voltage and current means that measurements are being made with peak-to-peak values. The

division by 2 is what puts everything in terms of the root-mean-square.

Page 10: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 10

Implementation

Figure 1 - Smart Grid Operational Diagram

A block diagram overview of the device can be seen in figure 1 above. The power entering the

circuit feeds to a relay that connects the circuit when the relay is activated by the microcontroller. The

current and voltage is then measured and sent to the ADC of the microcontroller within its 0 to +5V

window. The Arduino microcontroller then calculates values internally and sends the results to the

Raspberry Pi via the 2.4GHz wireless module.

Page 11: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 11

Figure 2 - Circuit Configuration of the ACS712 Hall-Effect Current Sensor

The current sensor module used in the design is the ACS712 rated for 5 Amps, and its circuit

diagram can be found in figure 2. This is mounted on a PCB with the required components for operation

and pin header pre-soldered, and was purchased from eBay. The instantaneous current is converted to

a voltage from -20 to +20 Volts which can be measured by the analog to digital function of the

microcontroller. There is an offset of ½Vcc so that both the positive and negative voltage swings can be

realized. Since Alternating Current (AC) is supplied to the outlets and the output is instantaneous, the

RMS value of this needs to be calculated.

Figure 3 - Circuit Configuration of the AC Voltage Transformer

Page 12: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 12

The RMS Watts cannot be calculated with the current measurement alone, which is why an AC

Voltage Transformer is included in the design. A simple resistor voltage dividing circuit is employed to

create a suitable window between 0 and 5 Volts using the VCC from the Arduino, as is shown in figure 3.

(

) Equation 6: Resistor Divider

It can be seen from Equation 6 how the voltage is stepped down from the transformer. The

transformer used was rated to step down to a 9V peak-to-peak sinusoid, but it was realized that this was

closer to 11.2V peak-to-peak. This meant that the resistor circuit needed to be altered so that the

voltage swing would be as close to 5V as possible. The capacitor C1 provides a suitable path to ground

for the AC signal from the transformer, and resistors R2 and R4 are presented to set a DC bias for the

signal going into the Arduino, since it is incapable of measuring negative voltage swings. The final

voltage swing achieved was close to 4.6V using the resistors from figure 3.

Relay modules were also purchased from eBay as it was the least expensive solution. Multiple

models were purchased including those with and without optocoupling. The purpose of the

optocoupler is to electrically isolate the connections controlling the relay and the connection being

controlled by the relay. The prototype currently uses a dual relay module without optocouplers, but this

was due to the isolated models not arriving soon enough via the mail. The boards receive a Vcc of +5V

and GND connection and control the relays via pins that can be driven directly from the microcontroller.

This is due to the fact that the boards already have a transistor to drive the electromechanical relay coil

with the proper current. Most of the relay modules purchased are only rated for 10A, so that must be

used in design consideration.

Page 13: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 13

Figure 4 - Circuit Configuration of the nRF24L01+ Wireless Module

The nRF24L01+ module was chosen for wireless communication, and the typical circuit diagram

is shown in figure 4, and was also available for a low cost from eBay. It contains an onboard antenna for

data communication on the PCB. When used in a low bandwidth application of 250 kbps, the unit has

an extended range of 100m (line of sight).

Raspberry Pi

The Raspberry Pi is a linux-based development computer the size of a credit card. It contains

GPIO ports and is capable of communicating with the Arduinos wirelessly as well as hosting nearly all the

code for the project. The operating system is debian linux and is hosted on an SD card. It is fitted with

an Ethernet port, two USB ports, HDMI, composite video, audio, and power input using a standard micro

USB port.

Page 14: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 14

Arduino UNO

An Arduino UNO microcontroller was originally chosen as the preferred chip to control all

peripherals. However, it was later decided that the Raspberry Pi would act as the master unit with the

webserver integrated. The Arduino line of microcontrollers offers an easy to use solution with a wide

variety of support. There are many built-in functions to make using features such as analog to digital

conversion simple to implement. It is an open source project so there are no licensing limitations with

the units. The UNO model was chosen specifically because it uses a through-hole DIP IC which is

socketed. This allows for the microcontroller to be easily replaced if a pin blows. A surface mount chip

is difficult to solder by hand, so the larger chip will be easier to put onto a prototyping board. By using

an external oscillator, the chip itself can be removed from the UNO development board when the design

is finalized.

Page 15: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 15

Web Development

MySQL is an open source database package which is easily installable on almost any operating

system. This is easily accepted by the debian platform installed on the Raspberry Pi. The database

contains the power usage statistics, including when it was taken and for which outlet, as well as the

current state of each relay. The same server hosting the database is used to host an Apache web server.

This web server is configured to gather the data from the MySQL database and display it in a graphical

format. The graphing is implemented using an open source package called Highcharts. This website

includes toggle control over the relay units in the outlet device, which then sends a message from the

base unit to the proper outlet and is implemented using PHP.

Page 16: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 16

Logical Code Flow

Figure 5 - Code Flowchart

Smart Grid in the Home uses many different programming languages to achieve the end result.

The reasons for this are compatibility and security. Measurements are taken using C, data is calculated

using C++, and Python is used to send and receive to and from the MySQL server. Data is then displayed

using Javascript, which sends and receives data to and from the MySQL server using PHP and is

embedded in HTML to create a webpage.

Back End

First, the Arduino UNO development board loads a C program to the ATmega IC. The C code on

this IC is what communicates with the relay, the AC voltage transformer, the hall-effect current sensor,

and the wireless communication device. There is a loop running which checks if the relay has a

matching value (one or zero) based on what is read from the wireless device. While it is checking the

relay state, it also sends the values for the voltage which is read in the analog to digital converter, as

well as for measurements from the current sensor. The most difficult portion of the code is how the

data is sent through the wireless modules.

The C code on the ATmega IC’s then sends/receives data to a C++ program stored on the

Raspberry Pi (Rpi). The Rpi also has a wireless module, which allows it to fully communicate with the

Page 17: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 17

ATmega chips. The C++ program will return the results for the Watts and VARs of a particular outlet and

send the result to a Python script. It was too difficult to include the header files for mysql commands in

the C++ itself, so a Python script was used as an effective alternative to send and receive data from the

database.

Two Python scripts are needed for the efficient transfer of data to and from the database. Since

too much overhead is created when including the code to connect to the database and check and add

values, a better thought was to connect to the database at the start of the C++ session. This connection

would them be maintained throughout the program, and a loop would be created thereafter to

manipulate the database. The C++ program will wait for all the values of the currents/voltages before

sending to the database, to create a synchronous send command to the database. There is also a

timeout, given that an outlet has been unplugged (otherwise it would never send any data), and this

command will also read the relay states from the database. If the value of the relay state has changed,

the C++ program will send a command to the C program on the ATmega chip to turn off the relay of the

selected outlet.

Page 18: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 18

Front End

Figure 6 - Website Snapshot

Highcharts is the Javascript charting library used to display the useful power readings on the

website. The script is embedded in the HTML web page, and each chart is added as a div element. A div

element is simply a container to hold objects from various coding languages in HTML. The HTML code

can be found in Appendix A. The Javascript code itself is long because each chart has its own options

and settings to manipulate, and can be found in Appendix B. It is difficult to run loops within Javascript

because web browsers such as Chrome and Firefox assume they use too much overhead and

immediately stop them from completing. For this reason, setInterval() was the function used to create a

dynamically updating chart. The function was embedded in a special “event” option within one of the

chart’s options, which essentially creates a more efficient loop that won’t consume too much memory in

the web browser. Every time the chart loops, a command referred to as an ajax call is initiated. An ajax

Page 19: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 19

call is able to encrypt a command to be sent to either a Python script or a PHP script, both of which

cannot be accessed directly from the web browser. This is to ensure no one has unauthorized access to

the MySQL database. The frontend could have just as easily been written in Python, but PHP was used

in order to give the team more experience with different types of scripting languages. These PHP files

are shown in Appendix C. There are several different ajax calls which are sent to the PHP file based on

what kind of data is to be retrieved for each chart. When a user connects to the website, an ajax call is

sent to retrieve all of the outlet power data from the database, as well as the relay state. Depending on

the command, the ajax function can retrieve any amount of information from the database and in this

case send it to Highcharts to be displayed on the website. Once that has been completed, the

setInterval function is initiated to loop and send an additional ajax call and retrieve the next value that

has been stored in the database. The values for the Watts, VARs, and power factor are then pushed to

the initial chart data and displayed dynamically. An example of a dynamically updating chart can be

seen on the Highcharts demo page located at http://www.highcharts.com/stock/demo/dynamic-

update.

Much like the Python scripts from the backend, there are also two PHP scripts. The first script,

named connect_to_mysql.php, is used to initiate and maintain a connection to the MySQL server, and

the second, named getpower.php, is initiated whenever the ajax call is started within the Javascript loop

in order to read or write values from or to the MySQL server. The second PHP script is a simple if/else

program which checks what kind of data was requested from the Javascript ajax call. For example, if the

ajax call was used from within the Javascript loop, the command would be getinstpower, which sends

the appropriate command to retrieve the most recent power reading from the server.

The MySQL server includes a unique function which adds a timestamp whenever a new set of

values are pushed onto the stack of columns, which is why the C++ program on the backend must be

Page 20: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 20

synchronous when writing to the MySQL server. If the data was asynchronously sent, then a new row

would have a timestamp, the Watt, and the VAR calculation for one outlet, but the other outlet values

would be zero. This would cause the chart to look similar to a triangle wave, which wouldn’t be easily

interpretable. Highcharts will accept only a Linux-standard timestamp, but the MySQL timestamp is in a

different format. For this reason, the timestamp string must be parsed and split into respective time

denominations (year, month, day, hour, etc.), and then put into the function Date.UTC() which

calculates the Linux-standard time stamp.

Highcharts is very particular about how data is stored, which was a difficult problem to

overcome. Highcharts also doesn’t have an internal debugger within the script since it is relatively new,

so any errors had to be solved methodically. Luckily, there is a very robust API which is easy to

understand. There are a variety of options available to change on the charts. The stockchart was

chosen for the project due to the range selection for any given time frame.

Relay buttons were used on the webpage to display the status and allow control of the relays in

real-time. A javascript function is tied to the button when pressed, which then makes an ajax call to the

php file. The php file then writes either a zero or one to the MySQL database, which is then read by the

C++ file. It allows for a record of on/off states for the relays, and can be modified easily to include dates

and times.

Page 21: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 21

Problems Faced

The prototype unit was successful in taking power readings and controlling the power state. In

testing, the power level output was sent serially to a computer. Initially, the device would reboot when

a serial communication channel was initiated, which was due to the Arduino UNO implementing

automatic reset for use with programming. There is a trace which can be cut to disable it, and solder

pads to reconnect it. When testing the current sensor, there was an associated offset. This means there

needed to be a calibration process. An offset value was hard coded to account for this, but it will not

always be the same. The unit has to be calibrated when plugged in without a load first, which yielded

the idea to add a calibrate button to the unit. The relay used in the device worked well but it was better

to use an opto isolated unit to prevent damage to the microcontroller during operation. The wireless

communication between the Raspberry Pi and the Arduinos was difficult to implement, but the API for

the wireless devices was useful in solving those related problems.

The front end was riddled with various debugging problems. This was mostly due to the lower

level of experience with writing high-level languages from an engineering perspective. Syntax errors

were most common while debugging large chunks of code, but there were also some problems parsing

different variable types as well. For example, all of the variables involved in the ajax calls had to be

decoded and parsed for their respective data types. The most difficult problem on the front end was the

debugging the PHP files. Any error in the PHP would report an internal server 500 error when viewed

from a web browser, which was not useful for debugging. To solve this, the PHP would have to be set to

return an error code to Javascript, which could then be viewed for debugging purposes.

Page 22: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 22

Budget

The budget for this project was very generous in lieu of what was planned. The original intent

was to purchase the parts for ten or more devices, but it was later realized that a demonstration of the

prototype only needed two or three. Each Arduino-controlled device contained a current sensor,

voltage transformer, relay module, wireless communication device, and ATmega integrated circuit. The

greatest cost was the voltage transformer, which was $35-40. The rest of the components were around

$15-20. The Raspberry Pi was surprisingly inexpensive, at $35; if the voltage transformer could be

eliminated, then the total cost of the project would be $40 for the Raspberry Pi, and $20-25 for each

additional Arduino-controlled device.

Page 23: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 23

Future Work

The Smart Grid in the Home has room for improvement. The AC voltage transformer was the

most expensive item in the project, and could be replaced by using a high voltage opto-isolator circuit

instead. It was not realized until later that this approach would have been less expensive, and more

accurate due to the hall-effect current sensor’s susceptibility to electromagnetic interference. The front

end could be improved with a number of options. More charts could be added to display different data,

such as the relay state over a period of time. A timer function could be implemented to control the

relays, or a software port to smart phone voice activation. It would also be very useful to allow the code

to ‘sense’ when an additional power-measuring device is added to the chain. As it stands now, if more

than two devices are added to the project, then the code and database would need to be manipulated

to accommodate the new devices.

Page 24: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 24

Performance

The device performed optimally, although there was no retail device for which to compare (such

as a Kill-A-Watt hour meter). When connected to a rotating fan, the power measured was 30.6 Watts.

When the fan was spinning, the power increased to 35.3 Watts, which was expected. The rating for the

fan was 40 Watts, so it was operating within the expected range. The reactive power measurements

were not realized due to problems with the code.

Page 25: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 25

References

"Function Reference." PHP:. N.p., n.d. Web. 23 May 2013.

"Highstock Options Reference." Highstock API Reference. N.p., n.d. Web. 23 May 2013.

"Highcharts Options Reference." Highcharts API Reference. N.p., n.d. Web. 23 May 2013.

"Learn to Create Websites." W3Schools Online Web Tutorials. N.p., n.d. Web. 23 May 2013.

Nilsson, James William., and Susan A. Riedel. Electric Circuits. Upper Saddle River, NJ: Pearson/Prentice

Hall, 2008. Print.

"Original MySQL API." PHP: Mysql. N.p., n.d. Web. 23 May 2013.

"The Python Standard Library." The Python Standard Library — Python V2.7.5 Documentation. N.p., n.d.

Web. 23 May 2013.

Page 26: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 26

Appendix A: HTML

<html lang="en" >

<head>

<style>

p.sans{font-family:"Arial", Helvetica, sans-serif;}

p {font-size: 40px;}

</style>

<p class="sans">Smart Grid in the Home</p>

<meta charset="utf-8" />

<meta name="author" content="Smart Grid" />

<title>Smart Grid in the Home</title>

<!-- add styles -->

<link href="css/main.css" rel="stylesheet" type="text/css" />

<!-- add scripts -->

<script src="js/jquery-1.9.1.js"></script>

<script src="js/highstock.js"></script>

<script src="js/highcharts-more.js"></script>

<script src="js/main.js"></script>

<script src="js/exporting.js"></script>

<div class="abs">

<div class="box"></div></div>

</head>

<body>

</br>

<div id="vumeter" class="gauge" style="width: 850px; margin: 0 auto">

</div></br>

<div id="varmeter" class="gauge" style="width: 850px; margin: 0 auto">

</div>

<div class="abs">

<div class="box">

</br>

<div id="total" class="chart" style="width: 850px; margin: 0 auto">

</div></br>

<div id="totalvar" class="chart" style="width: 850px; margin: 0 auto">

</div></br>

<div id="barchart" class="chart" style="width: 850px; margin: 0 auto">

</div>

</br>

<img id="relay1" src="http://192.168.2.133/power/css/off.png"; margin: 0 auto; width="100" height="100">&nbsp

&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp

<img id="relay2" src="http://192.168.2.133/power/css/off.png"; margin 0 auto; width="100" height="100"></br></br>

<button type="button"; class="relay1"; margin: 0 auto;>Relay: Outlet 1</button> &nbsp &nbsp &nbsp &nbsp &nbsp

&nbsp

<button type="button"; class="relay2"; margin: 0 auto;>Relay: Outlet 2</button>

</div>

</div>

</body>

</html>

Page 27: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 27

Appendix B: Javascript

// Once document is finished loading

$(document).ready(function() {

var pending1 = false;

$('.relay1').click(function relay1func(){

if (pending1){

return;

}

else {

pending1 = true;

$.ajax({

type: 'POST',

url: 'http://192.168.2.133/power/getpower.php',

//call the correct data function from the php file

data: "payload=getrelay1",

success: function(resp){

//make sure the returned data is a string

if (typeof(resp) == 'string'){

//decrypt the java-encoded string

resp = $.parseJSON(resp);

}

if (resp.length != 0){

var relay1 = resp;

if (relay1 == 1){

document.getElementById('relay1').src = "http://192.168.2.133/power/css/on.png";

}

else {

document.getElementById('relay1').src = "http://192.168.2.133/power/css/off.png";

}

}

}

});

pending1 = false;

}

});

pending2 = false;

$('.relay2').click(function relay2func(){

if (pending2){

return;

}

else {

pending2 = true;

$.ajax({

type: 'POST',

url: 'http://192.168.2.133/power/getpower.php',

data: "payload=getrelay2",

success: function(resp){

//make sure the returned data is a string

if (typeof(resp) == 'string'){

//decrypt the java-encoded string

resp = $.parseJSON(resp);

}

if (resp.length != 0){

var relay2 = resp;

if (relay2 == 1){

document.getElementById('relay2').src = "http://192.168.2.133/power/css/on.png";

}

else {

document.getElementById('relay2').src = "http://192.168.2.133/power/css/off.png";

}

}

}

});

pending2 = false;

}

});

// First chart initialized (VU meter)

var vu = new Highcharts.Chart({

chart: {

renderTo: 'vumeter',

type: 'gauge',

alignTicks: false,

borderColor: '#000000',

borderWidth: 2,

plotBorderColor: '#000000',

plotBorderWidth: 1,

plotBackgroundColor: {

linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },

stops: [

[0, '#70CF6A'],

[0.4, '#FFFFFF'],

[0.7, '#FFFFFF'],

Page 28: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 28

[1, '#70CF6A']

]

},

plotBackgroundImage: null,

height: 200,

},

credits: {

enabled: false

},

exporting: {

filename: 'Outlet_Inst_Watts',

scale: 4

},

legend: {

enabled: true,

align: 'right',

borderColor: 'black',

borderWidth: 2,

layout: 'vertical',

shadow: true,

verticalAlign: 'top',

y: 0

},

title: {

text: 'Real-Time Power Readings'

},

pane: [{

startAngle: -45,

endAngle: 45,

background: null,

center: ['18%', '145%'],

size: 270

}, {

startAngle: -45,

endAngle: 45,

background: null,

center: ['50%', '145%'],

size: 270

}, {

startAngle: -45,

endAngle: 45,

background: null,

center: ['82%', '145%'],

size: 270

}],

yAxis: [{

min: 0,

max: 500,

minorTickPosition: 'outside',

tickPosition: 'outside',

tickPixelInterval: 50,

labels: {

rotation: 'auto',

distance: 20

},

lineColor: '#000000',

tickColor: '#000000',

tickLength: 10,

minorTickLength: 7,

endOnTick: false,

plotBands: [{

from: 450,

to: 500,

color: '#C02316',

innerRadius: '100%',

outerRadius: '105%'

}],

pane: 0,

title: {

text: 'Power (RMS Watts)<br/><span style="font-size:10px">All Outlets</span>',

y: -40

}

}, {

min: 0,

max: 500,

minorTickPosition: 'outside',

tickPosition: 'outside',

tickPixelInterval: 50,

labels: {

rotation: 'auto',

distance: 20

},

lineColor: '#000000',

tickColor: '#000000',

tickLength: 10,

minorTickLength: 7,

endOnTick: false,

plotBands: [{

Page 29: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 29

from: 450,

to: 500,

color: '#C02316',

innerRadius: '100%',

outerRadius: '105%'

}],

pane: 1,

title: {

text: 'Power (RMS Watts)<br/><span style="font-size:10px">Outlet 1</span>',

y: -40

}

}, {

min: 0,

max: 500,

minorTickPosition: 'outside',

tickPosition: 'outside',

tickPixelInterval: 50,

labels: {

rotation: 'auto',

distance: 20

},

lineColor: '#000000',

tickColor: '#000000',

tickLength: 10,

minorTickLength: 7,

endOnTick: false,

plotBands: [{

from: 450,

to: 500,

color: '#C02316',

innerRadius: '100%',

outerRadius: '105%'

}],

pane: 2,

title: {

text: 'Power (RMS Watts)<br/><span style="font-size:10px">Outlet 2</span>',

y: -40

}

}],

plotOptions: {

gauge: {

dataLabels: {

enabled: true,

x: 0,

y: -120,

backgroundColor: {

linearGradient: {

x1: 0,

y1: 0,

x2: 0,

y2: 1

},

stops: [

[0, 'rgba(73, 222, 160, 0.7)'],

[1, 'rgba(255, 255, 255, 0.7)']

]

}

},

dial: {

radius: '100%'

},

pivot: {

borderColor: '#9E501C'

}

}

},

series: [{

data: [450],

yAxis: 0,

}, {

data: [150],

yAxis: 1,

}, {

data: [300],

yAxis: 2,

}],

tooltip: {

hideDelay: 0,

backgroundColor: {

linearGradient: {

x1: 0,

y1: 0,

x2: 0,

y2: 1

},

stops: [

[0, 'rgba(73, 222, 160, 0.7)'],

[1, 'rgba(255, 255, 255, 0.7)']

Page 30: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 30

]

},

borderColor: 'black',

borderWidth: 1,

positioner: function(){

return{x: 365, y: 50};

},

valueSuffix: ' Watts'

}

});

var vu2 = new Highcharts.Chart({

chart: {

renderTo: 'varmeter',

type: 'gauge',

alignTicks: false,

borderColor: '#000000',

borderWidth: 2,

plotBorderColor: '#000000',

plotBorderWidth: 1,

plotBackgroundColor: {

linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },

stops: [

[0, '#70CF6A'],

[0.4, '#FFFFFF'],

[0.7, '#FFFFFF'],

[1, '#70CF6A']

]

},

plotBackgroundImage: null,

height: 200,

},

credits: {

enabled: false

},

exporting: {

filename: 'Outlet_Inst_VAR',

scale: 4

},

legend: {

enabled: true,

align: 'right',

borderColor: 'black',

borderWidth: 2,

layout: 'vertical',

shadow: true,

verticalAlign: 'top',

y: 0

},

title: {

text: 'Real-Time Reactive Power Readings'

},

pane: [{

startAngle: -45,

endAngle: 45,

background: null,

center: ['18%', '145%'],

size: 270

}, {

startAngle: -45,

endAngle: 45,

background: null,

center: ['50%', '145%'],

size: 270

}, {

startAngle: -45,

endAngle: 45,

background: null,

center: ['82%', '145%'],

size: 270

}],

yAxis: [{

min: 0,

max: 500,

minorTickPosition: 'outside',

tickPosition: 'outside',

tickPixelInterval: 50,

labels: {

rotation: 'auto',

distance: 20

},

lineColor: '#000000',

tickColor: '#000000',

tickLength: 10,

minorTickLength: 7,

endOnTick: false,

plotBands: [{

from: 450,

Page 31: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 31

to: 500,

color: '#C02316',

innerRadius: '100%',

outerRadius: '105%'

}],

pane: 0,

title: {

text: 'Power (RMS VAR)<br/><span style="font-size:10px">All Outlets</span>',

y: -40

}

}, {

min: 0,

max: 500,

minorTickPosition: 'outside',

tickPosition: 'outside',

tickPixelInterval: 50,

labels: {

rotation: 'auto',

distance: 20

},

lineColor: '#000000',

tickColor: '#000000',

tickLength: 10,

minorTickLength: 7,

endOnTick: false,

plotBands: [{

from: 450,

to: 500,

color: '#C02316',

innerRadius: '100%',

outerRadius: '105%'

}],

pane: 1,

title: {

text: 'Power (RMS VAR)<br/><span style="font-size:10px">Outlet 1</span>',

y: -40

}

}, {

min: 0,

max: 500,

minorTickPosition: 'outside',

tickPosition: 'outside',

tickPixelInterval: 50,

labels: {

rotation: 'auto',

distance: 20

},

lineColor: '#000000',

tickColor: '#000000',

tickLength: 10,

minorTickLength: 7,

endOnTick: false,

plotBands: [{

from: 450,

to: 500,

color: '#C02316',

innerRadius: '100%',

outerRadius: '105%'

}],

pane: 2,

title: {

text: 'Power (RMS VAR)<br/><span style="font-size:10px">Outlet 2</span>',

y: -40

}

}],

plotOptions: {

gauge: {

dataLabels: {

enabled: true,

x: 0,

y: -120,

backgroundColor: {

linearGradient: {

x1: 0,

y1: 0,

x2: 0,

y2: 1

},

stops: [

[0, 'rgba(73, 222, 160, 0.7)'],

[1, 'rgba(255, 255, 255, 0.7)']

]

}

},

dial: {

radius: '100%'

},

pivot: {

Page 32: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 32

borderColor: '#9E501C'

}

}

},

series: [{

data: [450],

yAxis: 0,

}, {

data: [150],

yAxis: 1,

}, {

data: [300],

yAxis: 2,

}],

tooltip: {

hideDelay: 0,

backgroundColor: {

linearGradient: {

x1: 0,

y1: 0,

x2: 0,

y2: 1

},

stops: [

[0, 'rgba(73, 222, 160, 0.7)'],

[1, 'rgba(255, 255, 255, 0.7)']

]

},

borderColor: 'black',

borderWidth: 1,

positioner: function(){

return{x: 365, y: 50};

},

valueSuffix: ' VAR'

}

});

//render a chart to display the history of incoming power readings from outlets.

//this is a variable to hold the options that will be executed by the highcharts

//scripting library.

var Pchart = null;

var Qchart = null;

var barchart = null;

var Pchartoptions = {

chart: {

renderTo: 'total',

type: 'spline',

borderColor: '#000000',

borderWidth: 2,

plotBorderColor: '#000000',

plotBorderWidth: 1,

events: {

load: function() {

setInterval(loop, 2000);

}

}

},

credits: {

enabled: false

},

exporting: {

filename: 'Outlet Power (Watts)',

scale: 4

},

legend: {

enabled: true,

align: 'right',

borderColor: 'black',

borderWidth: 2,

layout: 'vertical',

shadow: true,

verticalAlign: 'top',

y: 55

},

navigator: {

adaptToUpdatedData: true,

baseSeries: 0,

yAxis: {

gridLineWidth: 1,

tickWidth: 1

}

},

plotOptions: {

allowPointSelect: true,

series: {

states: {

hover: {

enabled: true,

lineWidth: 5

Page 33: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 33

}

},

animation: {

duration: 2000

},

color: '#2B9468',

line: {

gapSize: 3

}

}

},

rangeSelector: {

buttons: [{

type: 'minute',

count: 1,

text: 'min'

}, {

type: 'minute',

count: 60,

text: 'hr'

}, {

type: 'day',

count: 1,

text: 'day'

}, {

type: 'month',

count: 1,

text: '1mo'

}, {

type: 'month',

count: 3,

text: '3mo'

}, {

type: 'year',

count: 1,

text: 'yr'

}],

inputEnabled: false,

selected: 2

},

series: [{

name: 'All Outlets',

type: 'spline',

color: '#F55225',

data: []

}, {

name: 'Outlet 1',

type: 'spline',

color: '#F525EE',

visible: false,

data: []

}, {

name: 'Outlet 2',

type: 'spline',

color: '#2567F5',

visible: false,

data: []

}],

title: {

text: 'Power Consumption History'

},

tooltip: {

hideDelay: 0,

backgroundColor: {

linearGradient: {

x1: 0,

y1: 0,

x2: 0,

y2: 1

},

stops: [

[0, 'rgba(73, 222, 160, 0.7)'],

[1, 'rgba(255, 255, 255, 0.7)']

]

},

borderColor: 'black',

borderWidth: 1,

crosshairs: {

dashStyle: 'dash'

},

valueSuffix: ' Watts'

},

xAxis: {

labels: {

step: 2

},

title: {

Page 34: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 34

text: 'Time'

}

},

yAxis: {

title: {

text: 'Power Reading (Watts)'

}

}

}

var Qchartoptions = {

chart: {

renderTo: 'totalvar',

type: 'spline',

borderColor: '#000000',

borderWidth: 2,

plotBorderColor: '#000000',

plotBorderWidth: 1

},

credits: {

enabled: false

},

exporting: {

filename: 'Outlet Power (Reactive)',

scale: 4

},

legend: {

enabled: true,

align: 'right',

borderColor: 'black',

borderWidth: 2,

layout: 'vertical',

shadow: true,

verticalAlign: 'top',

y: 55

},

navigator: {

adaptToUpdatedData: true,

baseSeries: 0,

yAxis: {

gridLineWidth: 1,

tickWidth: 1

}

},

plotOptions: {

allowPointSelect: true,

series: {

states: {

hover: {

enabled: true,

lineWidth: 5

}

},

animation: {

duration: 2000

},

color: '#2B9468',

line: {

gapSize: 3

}

}

},

rangeSelector: {

buttons: [{

type: 'minute',

count: 1,

text: 'min'

}, {

type: 'minute',

count: 60,

text: 'hr'

}, {

type: 'day',

count: 1,

text: 'day'

}, {

type: 'month',

count: 1,

text: '1mo'

}, {

type: 'month',

count: 3,

text: '3mo'

}, {

type: 'year',

count: 1,

text: 'yr'

}],

Page 35: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 35

inputEnabled: false,

selected: 2

},

series: [{

name: 'All Outlets',

type: 'spline',

color: '#2C1EC9',

data: []

}, {

name: 'Outlet 1',

type: 'spline',

color: '#3AC42D',

visible: false,

data: []

}, {

name: 'Outlet 2',

type: 'spline',

color: '#9C1727',

visible: false,

data: []

}],

title: {

text: 'Reactive Power Consumption History'

},

tooltip: {

hideDelay: 0,

backgroundColor: {

linearGradient: {

x1: 0,

y1: 0,

x2: 0,

y2: 1

},

stops: [

[0, 'rgba(73, 222, 160, 0.7)'],

[1, 'rgba(255, 255, 255, 0.7)']

]

},

borderColor: 'black',

borderWidth: 1,

crosshairs: {

dashStyle: 'dash'

},

valueSuffix: ' VAR'

},

xAxis: {

labels: {

step: 2

},

title: {

text: 'Time'

}

},

yAxis: {

title: {

text: 'Power Reading (VAR)'

}

}

};

var grouping = [[

'week', // unit name

[1] // allowed multiples

], [

'month',

[1, 2, 3, 4, 6]

]];

var baroptions = {

chart: {

renderTo: 'barchart',

borderColor: '#000000',

borderWidth: 2,

plotBorderColor: '#000000',

plotBorderWidth: 1,

type: 'column'

},

rangeSelector: {

buttons: [{

type: 'week',

count: 1,

text: 'wk'

}, {

type: 'month',

count: 1,

text: '1mo'

}, {

type: 'month',

count: 3,

text: '3mo'

Page 36: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 36

}, {

type: 'year',

count: 1,

text: 'yr'

}, {

type: 'ytd',

count: 1,

text: 'YTD'

}],

inputEnabled: false,

selected: 0

},

title: {

text: 'Power Usage per Day'

},

tooltip: {

hideDelay: 0,

backgroundColor: {

linearGradient: {

x1: 0,

y1: 0,

x2: 0,

y2: 1

},

stops: [

[0, 'rgba(73, 222, 160, 0.7)'],

[1, 'rgba(255, 255, 255, 0.7)']

]

},

borderColor: 'black',

borderWidth: 1,

},

xAxis: [{

title: {

text: 'Time'

}

}],

yAxis: [{

title: {

text: 'Power'

},

height: 200,

lineWidth: 2

}],

series: [{

name: 'Total Power (Watts)',

color: '#F55225',

dataGrouping: {

units: grouping

}

}, {

name: 'Outlet 1 Power (Watts)',

color: '#F525EE',

dataGrouping: {

units: grouping

}

}, {

name: 'Outlet 2 Power (Watts)',

color: '#2567F5',

dataGrouping: {

units: grouping

}

}, {

name: 'Total Reactive Power (VAR)',

color: '#2C1EC9',

dataGrouping: {

units: grouping

}

}, {

name: 'Outlet 1 Reactive Power (VAR)',

color: '#3AC42D',

dataGrouping: {

units: grouping

}

}, {

name: 'Outlet 2 Reactive Power (VAR)',

color: '#9C1727',

dataGrouping: {

units: grouping

}

}]

}

//Ajax call to fill the charts with initial data

$.ajax({

type: 'POST',

Page 37: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 37

url: 'http://192.168.2.133/power/getpower.php',

//call the correct data function from the php file

data: "payload=relayinit",

success: function(resp){

//make sure the returned data is a string

if (typeof(resp) == 'string'){

//decrypt the java-encoded string

resp = $.parseJSON(resp);

}

if (resp.length != 0){

var relay1 = parseInt(Number(resp['relay1']));

if (relay1 == 1){

document.getElementById('relay1').src = "http://192.168.2.133/power/css/on.png";

}

else {

document.getElementById('relay1').src = "http://192.168.2.133/power/css/off.png";

}

var relay2 = parseInt(Number(resp['relay2']));

if (relay2 == 1){

document.getElementById('relay2').src = "http://192.168.2.133/power/css/on.png";

}

else{

document.getElementById('relay2').src = "http://192.168.2.133/power/css/off.png";

}

}

}

});

$.ajax({

type: 'POST',

url: 'http://192.168.2.133/power/getpower.php',

//call the correct data function from the php file

data: "payload=getchartpower",

success: function(resp){

//make sure the returned data is a string

if (typeof(resp) == 'string'){

//decrypt the java-encoded string

resp = $.parseJSON(resp);

}

if(resp.length != 0){

var chartall_data = new Array();

var chart1_data = new Array();

var chart2_data = new Array();

var chartall_var = new Array();

var chart1_var = new Array();

var chart2_var = new Array();

var datetimemysql;

var temp = new Array();

var ymd = new Array();

var hms = new Array();

var datetime = new Array();

for(var i = 0; i < resp.length; i++){

//variable is stored as a string so need to convert to number, then calculate the float value

//to preserve decimal places, and then round it to two decimal places

var Pout1 = Math.round(parseFloat(Number(resp[i]['outlet1']))*10)/10;

var Pout2 = Math.round(parseFloat(Number(resp[i]['outlet2']))*10)/10;

var Qout1 = Math.round(parseFloat(Number(resp[i]['outlet1var']))*10)/10;

var Qout2 = Math.round(parseFloat(Number(resp[i]['outlet2var']))*10)/10;

chartall_data.push(Pout1+Pout2);

chart1_data.push(Pout1);

chart2_data.push(Pout2);

chartall_var.push(Qout1+Qout2);

chart1_var.push(Qout1);

chart2_var.push(Qout2);

//placeholder for the mysql-formatted date and time (yyyy-mm-dd hh:mm:ss)

datetimemysql = resp[i]['timestamp'];

//splits the string into two strings separated by the space, then splits those into three strings

each in two arrays

temp = String(datetimemysql).split(' ');

ymd = temp[0].split('-');

hms = temp[1].split(':');

ymd[0] = parseInt(Number(ymd[0]));

ymd[1] = parseInt(Number(ymd[1]));

ymd[2] = parseInt(Number(ymd[2]));

hms[0] = parseInt(Number(hms[0]));

hms[1] = parseInt(Number(hms[1]));

hms[2] = parseInt(Number(hms[2]));

//uses the arrays to push the correct date format (Date.UTC(yyyy, mm, dd, hh, mm, ss)), just the way

Highcharts likes it

datetime.push(Date.UTC(ymd[0],ymd[1],ymd[2],hms[0],hms[1],hms[2]));

}

var temparrayall = new Array();

var temparray1 = new Array();

var temparray2 = new Array();

var temparrayallvar = new Array();

var temparray1var = new Array();

var temparray2var = new Array();

var temparraybar = new Array();

//more code to put the data in a format highcharts will accept

Page 38: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 38

for(d = 0;d < datetime.length; d++){

temparrayall.push([datetime[d], chartall_data[d]]);

temparray1.push([datetime[d], chart1_data[d]]);

temparray2.push([datetime[d], chart2_data[d]]);

temparrayallvar.push([datetime[d], chartall_var[d]]);

temparray1var.push([datetime[d], chart1_var[d]]);

temparray2var.push([datetime[d], chart2_var[d]]);

}

//place the data in the chartoptions variable with all the other settings

Pchartoptions.series[0].data = temparrayall;

Pchartoptions.series[1].data = temparray1;

Pchartoptions.series[2].data = temparray2;

Qchartoptions.series[0].data = temparrayallvar;

Qchartoptions.series[1].data = temparray1var;

Qchartoptions.series[2].data = temparray2var;

baroptions.series[0].data = temparrayall;

baroptions.series[1].data = temparray1;

baroptions.series[2].data = temparray2;

baroptions.series[3].data = temparrayallvar;

baroptions.series[4].data = temparray1var;

baroptions.series[5].data = temparray2var;

//run highcharts and render everything

barchart = new Highcharts.StockChart(baroptions);

Qchart = new Highcharts.StockChart(Qchartoptions);

Pchart = new Highcharts.StockChart(Pchartoptions);

}

}

})//this function is not a loop, but is looped using setInterval in chartoptions.chart.events

var instance_ready = true;

function loop(){

if(instance_ready){

instance_ready = false;

//ajax call to associated php file

$.ajax({

type: 'POST',

url: 'http://192.168.2.133/power/getpower.php',

//call the correct data function from the php file

data: "payload=getinstpower",

success: function(resp){

//make sure the returned data is a string

if (typeof(resp) == 'string'){

//decrypt the java-encoded string

resp = $.parseJSON(resp);

}

if(resp.length != 0){

var data1 = Math.round(parseFloat(Number(resp['outlet1']))*100)/100;

var data2 = Math.round(parseFloat(Number(resp['outlet2']))*100)/100;

var data1var = Math.round(parseFloat(Number(resp['outlet1var']))*100)/100;

var data2var = Math.round(parseFloat(Number(resp['outlet2var']))*100)/100;

datetimemysqlnew = resp['timestamp'];

var dataall = data1 + data2;

var dataallvar = data1var + data2var;

var datetimemysqlnew;

var tempnew = new Array();

var ymdnew = new Array();

var hmsnew = new Array();

var datetimenew;

tempnew = String(datetimemysqlnew).split(' ');

ymdnew = tempnew[0].split('-');

hmsnew = tempnew[1].split(':');

ymdnew[0] = parseInt(Number(ymdnew[0]));

ymdnew[1] = parseInt(Number(ymdnew[1]));

ymdnew[2] = parseInt(Number(ymdnew[2]));

hmsnew[0] = parseInt(Number(hmsnew[0]));

hmsnew[1] = parseInt(Number(hmsnew[1]));

hmsnew[2] = parseInt(Number(hmsnew[2]));

datetimenew = (Date.UTC(ymdnew[0],ymdnew[1],ymdnew[2],hmsnew[0],hmsnew[1],hmsnew[2]));

//this command will replace the current data point with a new one

vu.series[0].data[0].update(dataall);

vu.series[1].data[0].update(data1);

vu.series[2].data[0].update(data2);

vu2.series[0].data[0].update(dataallvar);

vu2.series[1].data[0].update(data1var);

vu2.series[2].data[0].update(data2var);

//this will add a new data point to the current stack

Qchart.series[0].addPoint([datetimenew, dataallvar], true, false);

Qchart.series[1].addPoint([datetimenew, data1var], true, false);

Qchart.series[2].addPoint([datetimenew, data2var], true, false);

Pchart.series[0].addPoint([datetimenew, dataall], true, false);

Pchart.series[1].addPoint([datetimenew, data1], true, false);

Pchart.series[2].addPoint([datetimenew, data2], true, false);

}

instance_ready = true;

}

});

}

};

});

Page 39: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 39

Appendix C: PHP Files

connect_to_mysql.php:

<?php

Global $link;

$link = mysqli_connect('localhost', 'root', 'amit');

if (!$link){

die ('Could not connect to MYSQL');

}

Global $db_selected;

$db_selected = mysqli_select_db($link, 'power');

if (!$db_selected){

die ('Could not connect to database');

}

?>

getpower.php:

<?php

ini_set('display_errors', 'On');

error_reporting(E_ALL);

require 'connect_to_mysql.php';

$command_recieved = $_POST['payload'];

if ($command_recieved == 'getinstpower'){

$sqlCommand = "SELECT * FROM power ORDER BY timestamp DESC LIMIT 0,1";

$query = mysqli_query($link, $sqlCommand);

while($row = mysqli_fetch_array($query)){

$outlet1power = $row['outlet1'];

$outlet2power = $row['outlet2'];

$timestamp = $row['timestamp'];

$outlet1var = $row['outlet1var'];

$outlet2var = $row['outlet2var'];

}

$data_to_send = array('timestamp' => $timestamp, 'outlet1' => $outlet1power, 'outlet2' => $outlet2power,

'outlet1var' => $outlet1var, 'outlet2var' => $outlet2var);

echo json_encode($data_to_send);

}

else if($command_recieved == 'getchartpower'){

$sqlCommand = "SELECT * FROM power ORDER BY timestamp ASC";

$query = mysqli_query($link, $sqlCommand);

$data_to_send = array();

while($row = mysqli_fetch_array($query)){

$temp = array();

$temp = array('timestamp' => $row['timestamp'], 'outlet1' => $row['outlet1'], 'outlet2' => $row['outlet2'],

'outlet1var' => $row['outlet1var'], 'outlet2var' => $row['outlet2var']);

array_push($data_to_send, $temp);

}

echo json_encode($data_to_send);

}

else if($command_recieved == 'relayinit'){

$sqlCommand = "SELECT * FROM relays ORDER BY timestamp DESC LIMIT 0,1";

$query = mysqli_query($link, $sqlCommand);

while($row = mysqli_fetch_array($query)){

$relay1 = $row['relay1'];

$relay2 = $row['relay2'];

}

$data_to_send = array('relay1' => $relay1, 'relay2' => $relay2);

echo json_encode($data_to_send);

}

else if($command_recieved == 'getrelay1'){

$sqlCommand = "SELECT * FROM relays ORDER BY timestamp DESC LIMIT 0,1";

$query = mysqli_query($link, $sqlCommand);

while($row = mysqli_fetch_array($query)){

$relay1 = (int) preg_replace('/[^0-9]/', '', $row['relay1']);

$relay2 = $row['relay2'];

}

if ($relay1 == 0){

$sqlCommand = "INSERT INTO relays (relay1, relay2) VALUES (1, $relay2)";

$result = mysqli_query($link, $sqlCommand);

if ($result){

echo json_encode(1);

}

else {

echo "error </br>";

}

}

else if ($relay1 == 1){

$sqlCommand = "INSERT INTO relays (relay1, relay2) VALUES (0, $relay2)";

$result = mysqli_query($link, $sqlCommand);

if ($result){

echo json_encode(0);

}

Page 40: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 40

else {

echo "error";

}

}

}

else if($command_recieved == 'getrelay2'){

$sqlCommand = "SELECT * FROM relays ORDER BY timestamp DESC LIMIT 0,1";

$query = mysqli_query($link, $sqlCommand);

while($row = mysqli_fetch_array($query)){

$relay2 = (int) preg_replace('/[^0-9]/', '', $row['relay2']);

$relay1 = $row['relay1'];

}

if ($relay2 == 0){

$sqlCommand = "INSERT INTO relays (relay1, relay2) VALUES ($relay1, 1)";

$result = mysqli_query($link, $sqlCommand);

if ($result){

echo json_encode(1);

}

else {

echo "error </br>";

}

}

else if ($relay2 == 1){

$sqlCommand = "INSERT INTO relays (relay1, relay2) VALUES ($relay1, 0)";

$result = mysqli_query($link, $sqlCommand);

if ($result){

echo json_encode(0);

}

else {

echo "error";

}

}

}

else{

echo 'Unknown Command.';

}

?>

Page 41: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 41

Appendix D: Python Files

connect_to_mysql.py:

import MySQLdb;

mysql_options = {

‘user’: ’root’,

‘password’: ‘amit’,

‘host’: ‘localhost’,

‘database’: ‘power’,

‘raise_on_warnings’: True,

}

db = MySQLdb.connect(**mysql_options);

getpower.py:

import connect_to_mysql.py;

cur = db.curser();

def do_stuff(watts1, watts2, var1, var2)

sql1 = ”SELECT * FROM relays ORDER BY timestamp DESC LIMIT 0, 1”;

sql2 = ”INSERT INTO power(outlet1, outlet2, outlet1var, outlet2var) VALUES (“+watts1+”, “+watts2+”,”+ var1+”,”+

var2+”)”;

if command_received == “check_relays”:

cur.execute(sql1);

for row in cur.fetchall():

relay1 = str(‘relay1’);

relay2 = str(‘relay2’);

return relay1, relay2;

elif command_received == “insert_power”:

cur.execute(sql2);

else:

print “Invalid Command”;

Page 42: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 42

Appendix E: C++

/*

*

* Filename : rpi-hub.cpp

*

* This program makes the RPi as a hub listening to all six pipes from the remote

* sensor nodes ( usually Arduino or RPi ) and will return the packet back to the

* sensor on pipe0 so that the sender can calculate the round trip delays

* when the payload matches.

*

* Refer to RF24/examples/rpi_hub_arduino/ for the corresponding Arduino sketches

* to work with this code.

*

* CE is connected to GPIO25

* CSN is connected to GPIO8

*

* Refer to RPi docs for GPIO numbers

*

* Author : Stanley Seow

* e-mail : [email protected]

* date : 4th Apr 2013

*

*/

#include <cstdlib>

#include "../RF24.h"

#include <iostream>

#include <string>

#include <stdio.h>

#include <stdlib.h>

#include <sstream>

#include <typeinfo>

#include <vector>

#include <mysql/mysql.h> // I added include /usr/include/mysql/ to ld.so.conf which is why that works

using namespace std;

MYSQL *connection, mysql;

MYSQL_RES *result;

MYSQL_ROW row;

int query_state;

#define HOST "127.0.0.1" // you must keep the quotes on all four items,

#define USER "root" // the function "mysql_real_connect" is looking for a char datatype,

#define PASSWD "amit" // without the quotes they're just an int.

#define DB "power"

// mysql_init(&mysql);

// connection = mysql_real_connect(&mysql,HOST,USER,PASSWD,DB,0,0,0);

// Radio pipe addresses for the 2 nodes to communicate.

// First pipe is for writing, 2nd, 3rd, 4th, 5th & 6th is for reading...

// Pipe0 in bytes is "serv1" for mirf compatibility

const uint64_t pipes[6] = { 0x7365727631LL, 0xF0F0F0F0E1LL, 0xF0F0F0F0E2LL, 0xF0F0F0F0E3LL, 0xF0F0F0F0E4, 0xF0F0F0F0E5

};

// CE and CSN pins On header using GPIO numbering (not pin numbers)

RF24 radio("/dev/spidev0.0",8000000,25); // Setup for GPIO 25 CSN

void setup(void)

{

//

// Refer to RF24.h or nRF24L01 DS for settings

radio.begin();

radio.enableDynamicPayloads();

radio.setAutoAck(1);

radio.setRetries(15,15);

radio.setDataRate(RF24_250KBPS);

radio.setPALevel(RF24_PA_MAX);

radio.setChannel(76);

radio.setCRCLength(RF24_CRC_16);

// Open 6 pipes for readings ( 5 plus pipe0, also can be used for reading )

radio.openWritingPipe(pipes[0]);

// radio.openReadingPipe(1,pipes[1]);

// radio.openReadingPipe(2,pipes[2]);

// radio.openReadingPipe(3,pipes[3]);

Page 43: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 43

// radio.openReadingPipe(4,pipes[4]);

// radio.openReadingPipe(5,pipes[5]);

//

// Dump the configuration of the rf unit for debugging

//

// Start Listening

radio.startListening();

radio.printDetails();

printf("\n\rOutput below : \n\r");

usleep(1000);

}

void loop(void)

{

char receivePayload[32];

uint8_t pipe = 0;

radio.openReadingPipe(1,pipes[1]);

while ( radio.available( &pipe ) ) {

uint8_t len = radio.getDynamicPayloadSize();

radio.read( receivePayload, len );

printf(receivePayload);

//std::cout<<"a is of type: "<<typeid(receivePayload).name()<<std::endl; // Output 'a is of type int'

//printf(typeid(receivePayload));

stringstream ss;

string s;

ss << receivePayload;

ss >> s;

// char str[] = s;

char * pch;

pch = strtok (receivePayload,",");

while (pch != NULL)

{

printf ("%s\n",pch);

pch = strtok (NULL, ",");

}

//vector<char*> Split = ss.split_cstr(":CUT:");

//for(int i = 0;i<Split.size();i++)

// cout << Split[i] << endl;

// Display it on screen

//printf("Recv: size=%i payload=%s pipe=%i",len,receivePayload,pipe);

// Send back payload to sender

radio.stopListening();

// if pipe is 7, do not send it back

if ( pipe != 7 ) {

// Send back using the same pipe

// radio.openWritingPipe(pipes[pipe]);

radio.write(receivePayload,len);

receivePayload[len]=0;

printf("\t Send: size=%i payload=%s pipe:%i\n\r",len,receivePayload,pipe);

} else {

printf("\n\r");

}

// Enable start listening again

radio.startListening();

// Increase the pipe outside the while loop

pipe++;

// reset pipe to 0

if ( pipe > 5 ) pipe = 0;

}

Page 44: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 44

usleep(20);

}

int main(int argc, char** argv)

{

setup();

while(1)

loop();

return 0;

}

Page 45: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 45

Appendix F: C

/*

This program sends readings from four or more sensor readings and appends

2 bytes addr data pipes to the beginning of the payloads. The sender will send and

receive the payload on the same sender/receiver address.

The receiver is a RPi or UNO accepting 6 pipes and display received payload to the screen

The receiver will return the receive payload for sender to calculate the rtt

if the string compared matched to the lcd display

Max payload size is 32 bytes

Forked RF24 at github :-

https://github.com/stanleyseow/RF24

Date : 28/03/2013

Written by Stanley Seow

[email protected]

*/

#include <SPI.h>

#include "nRF24L01.h"

#include "RF24.h"

#include "printf.h"

#define RF_SETUP 0x17

// Make way for the SPI pins

// 10 -> LCD 4

// 7 -> LCD 6

// 3 -> LCD 11

// 4 -> LCD 12

// 5 -> LCD 13

// 6 -> LCD 14

// Set up nRF24L01 radio on SPI pin for CE, CSN

RF24 radio(9,10);

// For best performance, use P1-P5 for writing and Pipe0 for reading as per the hub setting

// Below is the settings from the hub/receiver listening to P0 to P5

//const uint64_t pipes[6] = { 0x7365727631LL, 0xF0F0F0F0E1LL, 0xF0F0F0F0E2LL, 0xF0F0F0F0E3LL, 0xF0F0F0F0E4LL,

0xF0F0F0F0E5LL };

// Example below using pipe5 for writing

const uint64_t pipes[2] = { 0xF0F0F0F0E2LL, 0x7365727631LL };

// const uint64_t pipes[2] = { 0xF0F0F0F0E2LL, 0xF0F0F0F0E2LL };

// const uint64_t pipes[2] = { 0xF0F0F0F0E3LL, 0xF0F0F0F0E3LL };

// const uint64_t pipes[2] = { 0xF0F0F0F0E4LL, 0xF0F0F0F0E4LL };

// const uint64_t pipes[2] = { 0xF0F0F0F0E5LL, 0xF0F0F0F0E5LL };

// Pipe0 is F0F0F0F0D2 ( same as reading pipe )

char receivePayload[32];

uint8_t counter=0;

void setup(void)

{

Serial.begin(57600);

printf_begin();

printf("Sending nodeID & 4 sensor data\n\r");

radio.begin();

// Enable this seems to work better

radio.enableDynamicPayloads();

radio.setDataRate(RF24_250KBPS);

radio.setPALevel(RF24_PA_MAX);

radio.setChannel(76);

radio.setRetries(15,15);

radio.openWritingPipe(pipes[0]);

radio.openReadingPipe(1,pipes[1]);

// Send only, ignore listening mode

//radio.startListening();

// Dump the configuration of the rf unit for debugging

radio.printDetails();

delay(1000);

Page 46: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 46

}

void loop(void)

{

uint8_t Data1,Data2 = 0;

char temp[5];

bool timeout=0;

// Get the last two Bytes as node-id

uint16_t nodeID = pipes[0] & 0xff;

// Use the last 2 pipes address as nodeID

// sprintf(nodeID,"%X",pipes[0]);

char outBuffer[32]=""; // Clear the outBuffer before every loop

unsigned long send_time, rtt = 0;

// Get readings from sensors, change codes below to read sensors

Data1 = sample();

if (Data1 < 19) { Data1 = 0; }

Data2 = 0;

if ( counter > 999 ) counter = 0;

// Append the hex nodeID to the beginning of the payload

sprintf(outBuffer,"%2X",nodeID);

strcat(outBuffer,",");

// Convert int to strings and append with zeros if number smaller than 3 digits

// 000 to 999

sprintf(temp,"%03d",Data1);

strcat(outBuffer,temp);

strcat(outBuffer,",");

sprintf(temp,"%03d",Data2);

strcat(outBuffer,temp);

strcat(outBuffer,",");

// Test for max payload size

//strcat(outBuffer,"012345678901");

// End string with 0

// strcat(outBuffer,0);

printf("outBuffer: %s len: %d\n\r",outBuffer, strlen(outBuffer));

send_time = millis();

// Stop listening and write to radio

radio.stopListening();

// Send to hub

if ( radio.write( outBuffer, strlen(outBuffer)) ) {

printf("Send successful\n\r");

}

else {

printf("Send failed\n\r");

}

radio.startListening();

delay(20);

while ( radio.available() && !timeout ) {

uint8_t len = radio.getDynamicPayloadSize();

radio.read( receivePayload, len);

receivePayload[len] = 0;

printf("inBuffer: %s\n\r",receivePayload);

// Compare receive payload with outBuffer

if ( ! strcmp(outBuffer, receivePayload) ) {

rtt = millis() - send_time;

printf("inBuffer --> rtt: %i \n\r",rtt);

// Turn on buzzer to Pin 2

Page 47: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 47

digitalWrite(2,HIGH);

}

// Check for timeout and exit the while loop

delay(10);

} // End while

delay(250);

digitalWrite(2,LOW); // Off the buzzer

}

float sample (void) {

float minval = 1023;

float maxval = 0;

float tempval = 0;

uint8_t power = 0;

// float time = millis();

for (int sample = 0; sample < 10000; sample++) {

tempval = analogRead(A0);

if ( minval > tempval ) { minval = tempval; }

if ( maxval < tempval ) { maxval = tempval; }

}

// time = millis() - time;

tempval = (((maxval - minval)/2.000)-4.500)*(5.000/1024.000)*(1000/185);

tempval = (tempval)/sqrt(2);

power = tempval * 120;

// Serial.println("powerVALUE: ");

Serial.println(power);

// Serial.println(" minVALUE: ");

// Serial.println(minval);

// Serial.println(" maxVALUE: ");

// Serial.println(maxval);

// Serial.println(" time: ");

// Serial.println(time);

if (power < 20 ) { power = 0; }

return power;

}

/*

Copyright (C) 2011 J. Coliz <[email protected]>

This program is free software; you can redistribute it and/or

modify it under the terms of the GNU General Public License

version 2 as published by the Free Software Foundation.

*/

/**

* @file printf.h

*

* Setup necessary to direct stdout to the Arduino Serial library, which

* enables 'printf'

*/

#ifndef __PRINTF_H__

#define __PRINTF_H__

#ifdef ARDUINO

int serial_putc( char c, FILE * )

{

Serial.write( c );

return c;

}

void printf_begin(void)

{

fdevopen( &serial_putc, 0 );

}

#else

#error This example is only for use on Arduino.

#endif // ARDUINO

#endif // __PRINTF_H__

Page 48: ECE791/792 Final Paper Project Title: Smart Grid in the Homeunh.edu/ece/Department/Senior Projects/ECE792_2013... · ECE 792: Senior Project Smart Grid in the Home Patrick O [oyle

ECE 792: Senior Project Smart Grid in the Home Patrick O’Boyle & Amit Jain

Page | 48

Appendix G: main.css Style Sheet

* {

margin: 0;

padding: 0;

}

header {

background-color:rgba(33, 33, 33, 0.9);

color:#ffffff;

display:block;

font: 14px/1.3 Arial,sans-serif;

height:50px;

position:fixed;

}

header h2{

font-size: 22px;

margin: 0px auto;

padding: 10px 0;

width: 80%;

text-align: center;

}

header a, a:visited {

text-decoration:none;

color:#fcfcfc;

}

.abs {

width: 100%;

position:absolute;

}

.box {

width: 220px;

margin: auto;

min-width:900px;

min-height:1500px;

background:#FFFFFF;

padding:0px;

}

body {

background:url("background.jpg") repeat scroll center transparent;

background-attachment: fixed;

text-align: center;

}

button {

background: none repeat scroll 0 0 #E3E3E3;

border: 1px solid #BBBBBB;

border-radius: 3px 3px 3px 3px;

box-shadow: 0 0 1px 1px #F6F6F6 inset;

color: #333333;

font: bold 12px;

margin: 0 5px;

padding: 8px 0 9px;

text-align: center;

text-shadow: 0 1px 0 #FFFFFF;

width: 150px;

}

button:hover {

background: none repeat scroll 0 0 #D9D9D9;

box-shadow: 0 0 1px 1px #EAEAEA inset;

color: #222222;

cursor: pointer;

}

button:active {

background: none repeat scroll 0 0 #D0D0D0;

box-shadow: 0 0 1px 1px #E3E3E3 inset;

color: #000000;

}