Download def convertToNumber(data)

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Resistive opto-isolator wikipedia , lookup

Voltage optimisation wikipedia , lookup

Switched-mode power supply wikipedia , lookup

Buck converter wikipedia , lookup

Rechargeable battery wikipedia , lookup

Mains electricity wikipedia , lookup

Solar car racing wikipedia , lookup

Alternating current wikipedia , lookup

Rectiverter wikipedia , lookup

Immunity-aware programming wikipedia , lookup

Opto-isolator wikipedia , lookup

Solar micro-inverter wikipedia , lookup

Transcript
I.
Executive Summary
II.
Introduction
Background
Solar Cell Theory
The group was given the task to maximize the efficiency of a solar panel facility. This
would be achieved by increasing the amount of sunlight intensity into each solar panel. When
light hits a solar panel, the electrons in the doped solar cell, n-type doped and p-typed doped,
break away from their bonds and create an electric current. The electric current then is
transferred to the metal contacts within the panel to allow the energy created to be used outside
the panel.
Figure 1. Representation of Light Hitting Solar Cell
In all renewable energy, the efficiency output will never be 100%. Most solar panels
operate at only 11-15% efficiency when positioned in a stationary position. The low efficiency is
due to many different factors. Before the light ever hits the panel it loses more than 30% of
efficiency. This loss of energy is created by the scattering of molecules due to Earth’s
atmosphere, the scattering of molecules due to aerosols and dust particles, and absorption of the
molecules within the atmosphere and gasses in the air.
Even after the light intensity is weakened by over 30%, more losses can occur once the
light hits the solar panel. When the light comes in contact with the panel, the light is reflected off
the panel and the rest of the light is transmitted through the material. The energy within the
transmitted light can be absorbed by the solar cell if the energy is high enough. The energy
absorbed causes electrons to break from their respective bonds and the movement of the
electrons creates an electric field. Within the panel, the light that is absorbed can also be lost due
to recombination of electron-hole pairs.
The efficiency can be increased by changing the angle and orientation of the panels with
the sun. Maximum power is outputted by the panels when the array is 90 degrees relative to the
sun. Being exactly perpendicular to the sun all day gives the panel the maximum solar intensity
at every second of the day, no matter what the efficiency losses occur.
Overview of Solar Power
The current layout of the solar facility is stationary arrays. The stationary arrays are
placed in a position such that the maximum amount of energy is captured throughout the year.
The focus of the group was designing and building an effective way to capture the
maximum amount of light intensity. This is achieved by maximizing the solar panel’s
orientation to the sun during the year, particularly throughout the day. Improving panel
orientation will increase the amount of sunlight captured by the panel, which will in turn increase
solar energy production and increase the client’s profits.
World solar energy usage has grown substantially over the years. This growth is due to
the cost of installation decreasing drastically. When solar energy first came about, the cost of
installation and operation was far greater than its savings. With modern technology the cost has
reduced, therefore increasing the frequency of use. Not only is this good for the consumers, but
also plays a role in conserving earth’s non-renewable resources and cutting out pollution.
Over the last several weeks, the group has spent time working independently as well as
collectively. The work performed was researching alternatives in order to develop a final design
that will increase the overall efficiency of the solar facility. The tasks completed by the group are
as follows: developing constraints, brainstorming for alternative solutions, developing selection
criteria, narrowing the solutions to three preliminary designs, assigning the selection criteria a
weighted value, narrowing the preliminary designs down to one final design, and planning the
general direction the group is heading when entering Senior II the following semester.
Figure 1 below is the current solar facility that is being renovated by the group. The
panels are set in a stationary position on top of a single pole stand. The panels are facing 170
degrees south with a 60-degree azimuth angle. The panels are able to be adjusted manually by
removing the bolts that hold the bracket together and positioning them to the desired angle. A
change of 5 degrees per set position may be selected. With several arrays making up the solar
facility this process can be quite cumbersome. An automated system would free the time that
would be required to perform such a task. This time could be used for more constructive tasks
that need to be completed in the facility.
Figure 2. Solar Facility
Constraints
Constraints act as requirements on the system given as guide lines for the system to meet
in order for the system to operate almost flawlessly. Typically, the constraints are set by either a
governing operation or by whomever is requesting the design. As a result of the group
evaluating many different scenarios and the risks that could occur the group has come up with
the following constraints.
1. Human safety (high voltages),
2. The size of the solar facility,
3. Size of the array,
4. The landscape and geography of the location,
5. Weight of array,
6. Surrounding environment (wildlife and plant life safety),
7. Dirt and dust on panels,
8. Heat induced on the panels,
9. The weather affecting the system in different locations,
10. Reflection cannot affect motorist.
Research from Senior I
III.
Safety
Solar safety provides information to help develop safe work practices for typical solar panel
projects; it requires the ability to evaluate unique situations to actively create safe work practices.
solar panel and must resist harsh weather. A faulty setup can lead to the device falling from the
post and injuring passersby. The battery must also secure neatly and away from human
intervention. Tampering with the battery or microcontroller causes bodily damage and device
damage. The device design considers safety to other species as well. The design eliminates
exposed wiring or sharp edges that could damage animals interfering with the device. This
manual prescribes the following process to minimize workplace hazards:
1.
2.
3.
4.
Evaluate and identify hazards.
Eliminate or remove hazards.
Control hazards that cannot be eliminated.
Recover from accidents.
Photovoltaic Systems (PV) shell be permitted to supply a building or other structure in
addition to any other electricity supply systems. Identification and grouping. (PV) source circuits
and PV output circuits shall not be contained in the same raceway, cable tray, outlet box. PV
system conductors shell be identified and grouped as required.
The safety program is listed as the electrical safety in principles, controls, and procedures.
Electrical Safety Program (Principles)
1.
2.
3.
4.
5.
6.
Inspect the project equipment.
Maintain the electrical equipment’s insulation and enclosure integrity.
Plan every job and document first-time procedures
Anticipate unexpected events
Identify and minimize the hazard
Protect the employee from shock, burn, blast, and other hazards due to the working
environment
7. Use the right tools for the job
8. Assess people’s abilities
9. Audit these principles
Electrical Safety Program (Controls)
1. Every electrical conductor or circuit part is considered energized until proven others
2. No bare-hand contact is to be made with exposed energized electrical conductors or
circuit parts above 50 volts to ground. Unless the “bare-hand method” is properly used.
3. Deenergizing an electrical conductor or circuit part and making it safe to work on is in
itself a potentially hazardous task.
4. Use procedures as “tools” to identify the hazards and develop plans to eliminate the
hazard
5. Train employees to qualify them for working in an environment influenced by the
presence of electrical energy
6. Use logical approach to determine potential hazard of task
7. Identify and use precautions appropriate to the working environment
Electrical Safety Program (Procedures)
1. Purpose of task
2. Qualifications and number of employees to be involved
3. Hazardous nature and extent of task
4. Limits of approach
5. Safe work practices to be utilized
6. Personal protective equipment involved
7. Insulation materials and tools involved
8. Special precautionary techniques
9. Electrical diagrams
10. Equipment details
11. Sketches/pictures if unique features
12. Reference date
And here are some pictures that prove the group members were so careful and using the
safety tools.
IV.
Structural
For the fabrication and testing the group spent many hours not only constructing an array, but
also spent countless hours testing if what had been built was functional and would continue to
work for the duration of testing. In testing the group was also responsible for collecting data that
would determine if building a dual axis system was actually worth the expenses, meaning it
would increase the efficiency enough to save enough money to pay itself off and then last long
enough to make a substantial difference in money saved over its lifetime.
Fabrication
The fabrication of the array all started with the group buying the material and then
predetermining desired lengths of certain members. Once all the members had been sized the
next step was to begin cutting the material and putting it together. The first part of the array to
be built was the base so that the group would have something to hold the array while working on
it in the immediate future. Once the base had been completed the group began work on the
moving parts of the array. The north and south movement of the array was achieved by
mounting a single piece of tubing inside the main column and pinning it in place using a single
bolt but leaving it loose enough to still allow for rotation. The next main part was determining a
way to rotate the array about a horizontal axis or the east and west movement. At first the group
thought they could achieve this by building two hinges by binding two separate pieces of steel
into U shape and then putting together using rivets. The problem with this design was that the
rivets were too tight and would not allow the array to move freely enough. Luckily the group
was working in the shop one night and found a set of hinges design the same as the previous and
had a much more free range of motion and the group decided to use these hinges instead. On
top of the hinges the group place another piece of tubing in the same direction as north and south
movement piece, and then bolted two pieces of aluminum L running perpendicular to that
member. The solar panel was placed directly on top of these members. In order for the group to
achieve the necessary movement needed a 14 inch stroke actuator was attached to the main
column and the north and south member to rotate the array around the vertical axis. For the
horizontal rotation the group attached another piece of aluminum tubing coming off of the north
and south member at a 90° angle down and the attached an 18 inch stroke actuator to that
member. The actuator also attached to one of the L-shaped pieces that the solar panel that is
attached to. The final piece of the fabrication was to plug the actuators into the control box and
the then hook the control box to a battery.
V.
Data Recording
Once the array structure was complete, the next step was to record the output of the panel
for different orientations. One method to complete this task was using the already owned
Raspberry Pi. This device is a powerful microcontroller that meets the needs of the group. The Pi
is a mini computer with the ability to communicate with several sensor modules and connect
with a local network. In addition to utilizing the abilities of the Pi, the group thought it would be
best to have an additional tool to measure the output of the panel. After a bit of research, the
group found an energy multimeter with an LCD display. The two were used together to ensure
accurate data was received.
Wiring
Energy Meter
The first step the group took for recording the array output was connecting the three Emeters. These meters were used to monitor the panel output, the battery intake and output, and
the controller’s intake. Figure . below shows the E-meters installed under the lid of the battery
box.
Figure . Battery Box Lid
For the battery, the e-meter was connected in such a way that a positive current denotes
charging and a negative denotes discharging. The figure below shows the wiring diagram for
connecting the meters to the panel and battery. As can be seen in the image, these meters contain
what is called a shunt. The purpose of the shunt is to protect the meter from high currents. With
the shunt, the meter reads the voltage drop across it which will be in millivolts. Each millivolt
drop is directly equivalent to the amperage flowing through the system.
Figure . Panel and Battery E-meter
With such a low amperage going to the tracking controller, a meter with a shunt resistor
was unnecessary. This meter was simply wired in between the battery and the controller in the
configuration seen in the figure below.
Figure . Controller E-meter
Not only do these meters display the voltage and current, but also displays the output
power along with the accumulated power. Figure below shows an example output reading of
the E-meter. The panel and battery meters’ measure voltages between 6.5 and 100 volts, up to
100 amperes, up to 10 kilowatts, and up to 9999-kilowatt hours. The controller e-meter is very
similar except it can only measure up to 2 kilowatts, and has a limit of 20 amperes. Both sizes of
e-meters take 2 readings per second and have an accuracy of 1%.
Figure . Example Reading
Raspberry Pi
The second piece of equipment that the group used to collect data from the panel was the
Raspberry Pi. The group chose the Pi over other microcontrollers such as the Arduino, because
of the versatility that it supplies the user. The Raspberry Pi is basically a mini computer, not only
can it monitor several different inputs at once but it also interfaces well with the user. The code
can be written, compiled, and executed within the Pi, all that is needed is a monitor, keyboard,
and mouse. Additional features found on the Pi include; wired and wireless connection to the
internet, HDMI output, SD card with software, USB ports, touch screen display connect, and
camera connection. Having the ability to store all the code on the Pi and connect to the internet,
the user can easily download and update any library within the command terminal.
With the Pi, the group purchased a few different sensor modules to aid them in recording
daily data. The group used a light intensity sensor, a temperature sensor, and a power meter
sensor. Each of these three sensors was used to monitor daily variables to normalize the recorded
data.
The main sensor used by the group was the INA3221 breakout board which measures the
voltage and current at a point. Figure below shows the module and Figure . shows the wiring
diagram.
Figure . INA3221 Breakout Board
Figure . INA3221 Wiring Diagram
The INA3221 is a very useful module with the ability to take readings at three different
locations simultaneously. The downside to this sensor is the inability to read high current levels.
The board has an installed 0.1-ohm shunt resistor and can read up to 2 amperes safely. This only
means that the group was required to use a larger off board shunt resistor. The group elected to
use a 10A/75mv shunt. Before being able to use this shunt, the on board 0.1-ohm resistor trace
had to be cut. Figure below shows how to remove the onboard shunt and figure shows how to
connect the sensor to the load using both configurations. For this project, the group is required to
use the configuration shown at the bottom of the figure. Changes to the INA3221 code was also
required and will be elaborated upon in the next section.
Figure . INA3221 Shunt removal
Figure . INA3221 Shunt Setup
The next piece of monitoring equipment the group used was the DS18B20, an analog
temperature sensor manufactured by Sunfounder. As previously stated, temperature and
efficiency of a solar panel are proportional to one another. Knowing this, the group thought it
would be best to record the temperature throughout each day to normalize the data for each
configuration. Figure and figure below show the sensor and the wiring diagram to the
Raspberry Pi.
Figure . Temperature Sensor
Figure . DS18B20 Wiring Diagram
The final sensor the group used to aid them in their analysis was the BH1750FVI digital
light intensity sensor module. This sensor will take light intensity readings of the sun thought the
day similar to the temperature sensor, this will allow the group to compare daily readings. For
example, a day when the group performs dual axis tracking the sun may not be as powerful as a
day when the group does single axis tracking. They wanted to ensure the data was as accurate as
possible so nothing was misinterpreted. The applied module and wiring diagram can be seen in
the two figures below.
Figure . BH1750FVI Light Intensity Sensor
Figure . BH1750FVI Wiring Diagram
Maybe include figures here or in appendix once sensors are installed on panel
Code
The code used for this project can be found in Appendix . For this section, key areas in
the code will be addressed with changes that were required to meet the needs of the project. The
first change made to the code by the group was adjusting the INA3221 module configurations to
account for the off board shunt resistor. Figure below shows where this change had to be made.
Figure . INA3221 Module Code Configuration
The change was made in the INA3221 module code on line 163. Initially, this line of
code did not contain the 7.5, but with using the 10A/75mV off board shunt, the shunt voltage had
to be divided by 7.5. The shunt value 10A/75mV means that for every 7.5mV read by the sensor,
that is equivalent to 1A. So, if the voltage drop across the shunt was 15 mV, the current through
that shunt would be 2A.
The section of code seen below in the figure contains a couple of key section. Lines 33
through 42 contains code that asks the user how long they wish for the program to remain in the
while loop and how often they wish the program to take output readings. Line 38 calculates and
stores the runtime of the program in seconds and line 41 ask the user how often in seconds they
wish to take readings. Next, lines 45 through 48 open an Excel document and stores the variable
titles.
Figure . Prompt User
This section of code writes the data read by the sensor to a file. Lines 184 through 189
writes the data to the file and determines the order in which the data will be saved and line 200
closes the file. Line 197 and line 198 checks to see if the code has looped the number of times
determined by the user, and line 199 controls how long the code pauses before restarting the
loop. The final section of the code is lines 204, 205, and 206 which send a notification text
message and the excel sheets to the defined address. This section of code can be seen in the
figure below. The code for the notification text message and emails can be seen in the appendix.
Figure . Create and Send File
Figure below shows the main section of code for reading the temperature and light
intensity. This section of code creates an additional excel file to store the readings. Similar to the
INA3221 code lines 50 and 51 create an excel document, and lines 62 through 64 write the data
into the excel sheet. Lines 55 through 61 are used to determine the current temperature and
convert it to degrees Fahrenheit. Also, like before, lines 54, 66, and 67 control the while loop and
68 determines the pause before the next reading takes place. The code in its entirety can be found
in the appendix.
Figure . Light and Temperature
VI.
Controller Circuit
A microcontroller (MCU) is a small computer on a single integrated circuit containing a
processor core, memory, and programmable input/output peripherals. A microcontroller can
be considered a self-contained system with a processor, memory, and peripherals. It can also
be used as an embedded system. Therefore, the group chose DarkStar 2.0 because it is one of
the best controller in the market that will provide superior performance and contribute greatly
to the quality of our group project. This controller features dual axis remote controlled solar
tracker, remote sensor, and Bluetooth support with an integrated Android application that
gives unprecedented control over tracking parameters. This Android application can display
current status information including actuator position, photo-sensor values, manual control of
motors, and customization of all tracking parameters is also supported. In addition,
it can discriminately utilize pulse-feedback positioning on both primary and secondary axes.
This means that if pulses are detected during the start-up motor test, then the controller will
enable all of the features which require pulse-feedback for operation, such as stall protection
and customizable park position. Therefore, the controller is compatible with any dual-axis
mount based on an altitude-azimuth, equatorial, or Polar geometry. Also, it is compatible
with most linear actuators and slew drives that are equipped with direct current (DC) brushed
permanent magnet motors. Despite that, there are some restrictions for this controller such as
the maximum voltage is 40-volt DC as well 10 Ampere for the current, fuse protected and
reverse polarity protected.
VII.
Analysis
Results
Scaling
Alternative Design
Throughout this process, the students have analyzed multiple types of designs for
individual solar panels which can be scaled and used in the overall solar facility. The main
designs researched were the stationary solar panel, movement of a solar panel on a single-axis
system, movement of a solar panel on a dual-axis system, and a stationary panel angle against a
reflective panel. Each of these designs has its perks and faults.
Stationary Panel
The stationary panel system is in a fixed position that the panel is faced in a specific
direction and at a specific angle to create the maximum energy output. The direction of the panel
should face due south if the facility is in the northern hemisphere and the panel should face due
north if the facility is southern hemisphere. The panel is positioned this way, in order, that the
panel is perpendicular to the sun at mid-day. The angle of the panel is changed for the four
different seasons. The equations to calculate the angle of the panel for the different seasons can
be seen below.
Spring:
(𝐿𝑎𝑡𝑖𝑡𝑢𝑑𝑒 − 2.5)
(Equation 1)
Summer:
(𝐿𝑎𝑡𝑖𝑡𝑢𝑑𝑒 ∗ 0.9) − 23.5
(Equation 2)
Fall:
(𝐿𝑎𝑡𝑖𝑡𝑢𝑑𝑒 − 2.5)
(Equation 3)
Winter:
(𝐿𝑎𝑡𝑖𝑡𝑢𝑑𝑒 ∗ 0.9) + 29
(Equation 4)
For the analysis done by the students, the latitude of Jonesboro, Arkansas, is 35.84°. The
time of the analysis was done during the fall season. So the panel was faced due south and the
angle of the panel was positioned to be 33.34°.
(Will add analysis and pro/cons here)
Single-Axis Tracking System
The single-axis solar panel tracking system contains one linear actuator, a LED tracking
sensor, solar panel, structure, and a microcontroller. The panel would be faced due south and the
linear actuator would change the angle of the panel east to west so the panel would stay close to
perpendicular with the sun. This would give the panel more light intensity than the stationary
system, but it would still not be exactly perpendicular due to the fact the Earth tilts 23.5°
north/south when looking from the equator.
(Will add analysis and pro/cons here)
Dual-Axis Tracking System
The dual-axis solar tracking system contains two linear actuators, a LED tracking sensor,
solar panel, structure, and a microcontroller. The solar panel would have a park position when
there is no visible sun. The park position should face due south bu at the lowest angle possible
for the tracking system to be closest to the sun when it rises above the horizon. The linear
actuators would be placed in such a fashion to alter the angle of the north/south axis for different
times of the year and to alter the east/west axis throughout different periods of the day. The dualaxis system should cause the panel to be perpendicular, 90°, to the sun at all times of the day
which will create the maximum amount of light intensity at all periods of the day.
(Will add analysis and pro/cons here)
Stationary Reflective Mount
In this system, the panel would be mounted at a specific angle throughout the year. A
reflective panel would be positioned in front of the solar panel in order to increase the light
intensity throughout the entire day. The solar panel and the reflective panel would be positioned
and the side view would look like a ‘V’. The solar panel would be faced towards the west and the
reflective mirror would face west which would create the maximum amount of sunlight intensity
into the panel throughout the day.
(Will add researched analysis and pro/cons here)
Recommended Modification and Additions
VIII.
Conclusion
IX.
List of References
1. Early, Mark W., and Jeffrey S. Sergeant. "Article 690." NFPA 70 Nec. 2011 ed. N.p.:
n.p., n.d. 1108-1140. Print.
2. NFPA 70E: Standard for Electrical Safety Requirements for Employee Workplaces.
Quincy, MA: NFPA, 2004. Print.
3. "Solar Construction Safety"
http://www.coshnetwork.org/sites/default/files/OSEIA_Solar_Safety_12-06.pdf . Web.
4. "OSHA Solar Panel". Web.
5. "Arc Flash Safety" web. https://en.wikipedia.org/wiki/Arc_flash
6. "Bayite DC 6.5-100V 0-100A LCD Display Digital Current Voltage Power Energy Meter
Multimeter Ammeter Voltmeter with 100A Current Shunt." Amazon. N.p., n.d. Web. 13
Nov. 2016. <https://www.amazon.com/bayite-6-5-100V-Display-MultimeterVoltmeter/dp/B013PKYILS/ref=sr_1_5?m=A1T3LOAKNUUM9N&s=merchantitems&ie=UTF8&qid=1479094850&sr=1-5>.
7. "Grove/Pin Version of INA3221 3 Channel Current Measurement Breakout Board
– SwitchDoc Labs." SwitchDoc Labs. N.p., 26 Mar. 2016. Web. 13 Nov. 2016.
<http://www.switchdoc.com/2016/03/grove-version-ina3221-3-channel-currentmeasurement-breakout-board/>.
8. "THREE-CHANNEL CURRENT AND VOLTAGE I²C MONITOR." Notes on the
Raspberry Pi. N.p., n.d. Web. 13 Nov. 2016. <http://www.noveldevices.co.uk/rp-3channel-i2c-monitor>.
9. "REUK.co.uk." REUKcouk. N.p., n.d. Web. 13 Nov. 2016.
<http://www.reuk.co.uk/wordpress/raspberry-pi/ds18b20-temperature-sensor-withraspberry-pi/>.
10. "Lesson 23 Digital Temperature Sensor." Lesson 23 Digital Temperature Sensor. N.p.,
n.d. Web. 13 Nov. 2016. <https://www.sunfounder.com/learn/Sensor-Kit-v2-0-forArduino/lesson-23-digital-temperature-sensor-sensor-kit-v2-0-for-arduino.html>.
11. https://homecsp.com/store/index.php?id_cms=4&controller=cms
Appendix A
(Code)
--------------------------------------------------------------------------------------------------------------------INA3221 MODULE CODE
--------------------------------------------------------------------------------------------------------------------#!/usr/bin/env python
# SDL_Pi_INA3221.py Python Driver Code
# SwitchDoc Labs March 4, 2015
# V 1.2
#encoding: utf-8
from datetime import datetime
import smbus
# constants
#/*=========================================================================
#
I2C ADDRESS/BITS
#
----------------------------------------------------------------------*/
INA3221_ADDRESS =
(0x40)
# 1000000 (A0+A1=GND)
INA3221_READ
=
(0x01)
#/*=========================================================================*
/
#/*=========================================================================
#
CONFIG REGISTER (R/W)
#
----------------------------------------------------------------------*/
INA3221_REG_CONFIG
=
(0x00)
#
/*--------------------------------------------------------------------*/
INA3221_CONFIG_RESET
=
(0x8000) # Reset Bit
INA3221_CONFIG_ENABLE_CHAN1
INA3221_CONFIG_ENABLE_CHAN2
INA3221_CONFIG_ENABLE_CHAN3
(0x4000)
(0x2000)
(0x1000)
# Enable Channel 1
# Enable Channel 2
# Enable Channel 3
=
(0x0800)
# AVG Samples Bit 2 - See
=
(0x0400)
# AVG Samples Bit 1 - See
=
(0x0200)
# AVG Samples Bit 0 - See
INA3221_CONFIG_VBUS_CT2 =
time - See table 4 spec
INA3221_CONFIG_VBUS_CT1 =
time - See table 4 spec
INA3221_CONFIG_VBUS_CT0 =
time - See table 4 spec
(0x0100)
# VBUS bit 2 Conversion
(0x0080)
# VBUS bit 1 Conversion
(0x0040)
# VBUS bit 0 Conversion
INA3221_CONFIG_AVG2
table 3 spec
INA3221_CONFIG_AVG1
table 3 spec
INA3221_CONFIG_AVG0
table 3 spec
=
=
=
INA3221_CONFIG_VSH_CT2 =
time - See table 5 spec
INA3221_CONFIG_VSH_CT1 =
time - See table 5 spec
INA3221_CONFIG_VSH_CT0 =
time - See table 5 spec
(0x0020)
# Vshunt bit 2 Conversion
(0x0010)
# Vshunt bit 1 Conversion
(0x0008)
# Vshunt bit 0 Conversion
INA3221_CONFIG_MODE_2
See table 6 spec
INA3221_CONFIG_MODE_1
See table 6 spec
INA3221_CONFIG_MODE_0
See table 6 spec
=
(0x0004)
# Operating Mode bit 2 -
=
(0x0002)
# Operating Mode bit 1 -
=
(0x0001)
# Operating Mode bit 0 -
#/*=========================================================================*
/
#/*=========================================================================
#
SHUNT VOLTAGE REGISTER (R)
#
----------------------------------------------------------------------*/
INA3221_REG_SHUNTVOLTAGE_1
=
(0x01)
#/*=========================================================================*
/
#/*=========================================================================
#
BUS VOLTAGE REGISTER (R)
#
----------------------------------------------------------------------*/
INA3221_REG_BUSVOLTAGE_1
=
(0x02)
#/*=========================================================================*
/
SHUNT_RESISTOR_VALUE
Ohm
= (0.1)
# default shunt resistor value of 0.1
class SDL_Pi_INA3221():
###########################
# INA3221 Code
###########################
def __init__(self, twi=1, addr=INA3221_ADDRESS,
SHUNT_RESISTOR_VALUE ):
self._bus = smbus.SMBus(twi)
self._addr = addr
config = INA3221_CONFIG_ENABLE_CHAN1 |
INA3221_CONFIG_ENABLE_CHAN2 |
INA3221_CONFIG_ENABLE_CHAN3 |
INA3221_CONFIG_AVG1 |
\
INA3221_CONFIG_VBUS_CT2 |
INA3221_CONFIG_VSH_CT2 |
INA3221_CONFIG_MODE_2 |
\
INA3221_CONFIG_MODE_1 |
\
shunt_resistor =
\
\
\
\
\
INA3221_CONFIG_MODE_0
self._write_register_little_endian(INA3221_REG_CONFIG, config)
def _write(self, register, data):
#print "addr =0x%x register = 0x%x data = 0x%x " % (self._addr,
register, data)
self._bus.write_byte_data(self._addr, register, data)
def _read(self, data):
returndata = self._bus.read_byte_data(self._addr, data)
#print "addr = 0x%x data = 0x%x %i returndata = 0x%x " % (self._addr,
data, data, returndata)
return returndata
def _read_register_little_endian(self, register):
result = self._bus.read_word_data(self._addr,register) & 0xFFFF
lowbyte = (result & 0xFF00)>>8
highbyte = (result & 0x00FF) << 8
switchresult = lowbyte + highbyte
#print "Read 16 bit Word addr =0x%x register = 0x%x switchresult =
0x%x " % (self._addr, register, switchresult)
return switchresult
def _write_register_little_endian(self, register, data):
data = data & 0xFFFF
# reverse configure byte for little endian
lowbyte = data>>8
highbyte = (data & 0x00FF)<<8
switchdata = lowbyte + highbyte
self._bus.write_word_data(self._addr, register, switchdata)
#print "Write 16 bit Word addr =0x%x register = 0x%x data = 0x%x " %
(self._addr, register, data)
def _getBusVoltage_raw(self, channel):
#Gets the raw bus voltage (16-bit signed integer, so +-32767)
value =
self._read_register_little_endian(INA3221_REG_BUSVOLTAGE_1+(channel -1) *2)
if value > 32767:
value -= 65536
return value
def _getShuntVoltage_raw(self, channel):
#Gets the raw shunt voltage (16-bit signed integer, so +-32767)
value =
self._read_register_little_endian(INA3221_REG_SHUNTVOLTAGE_1+(channel -1) *2)
if value > 32767:
value -= 65536
return value
# public functions
def getBusVoltage_V(self, channel):
# Gets the Bus voltage in volts
value = self._getBusVoltage_raw(channel)
return value * 0.001
def getShuntVoltage_mV(self, channel):
# Gets the shunt voltage in mV (so +-168.3mV)
value = self._getShuntVoltage_raw(channel)
return value * 0.005
def getCurrent_A(self, channel):
#Gets the current value in A, considering the config settings and current
LSB
#Reads the current in Amps the 7.5 is due to the shunt being a 10A/75mA
or 1 amp per 7,5mV
valueDec = self.getShuntVoltage_mV(channel)/ 7.5
return valueDec;
--------------------------------------------------------------------------------------------------------------------INA3221 EMAIL CODE
--------------------------------------------------------------------------------------------------------------------#This program is used to email the recorded data to the user
#prompting for the user's email could be used
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
fromaddr = "[email protected]"
toaddr = "[email protected]"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Excel Sheet with Project Data"
body = "The following message contains an attachment with the array's daily
data."
msg.attach(MIMEText(body, 'plain'))
filename = "/home/pi/Desktop/Sr_Design/data_log.csv"
attachment = open("/home/pi/Desktop/Sr_Design/Power_data_log.csv", "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "**********")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
--------------------------------------------------------------------------------------------------------------------TEMPERATURE AND LIGHT INTENSITY CODE
--------------------------------------------------------------------------------------------------------------------#!/user/bin/python
import smbus
import os
import time
from time import sleep
from datetime import datetime
# Define some constants from the datasheet
DEVICE
= 0x23 # Default device I2C address
POWER_DOWN = 0x00 # No active state
POWER_ON
= 0x01 # Power on
RESET
= 0x07 # Reset data register value
# Start measurement at 4lx resolution. Time typically 16ms.
CONTINUOUS_LOW_RES_MODE = 0x13
# Start measurement at 1lx resolution. Time typically 120ms
CONTINUOUS_HIGH_RES_MODE_1 = 0x10
# Start measurement at 0.5lx resolution. Time typically 120ms
CONTINUOUS_HIGH_RES_MODE_2 = 0x11
# Start measurement at 1lx resolution. Time typically 120ms
# Device is automatically set to Power Down after measurement.
ONE_TIME_HIGH_RES_MODE_1 = 0x20
# Start measurement at 0.5lx resolution. Time typically 120ms
# Device is automatically set to Power Down after measurement.
ONE_TIME_HIGH_RES_MODE_2 = 0x21
# Start measurement at 1lx resolution. Time typically 120ms
# Device is automatically set to Power Down after measurement.
ONE_TIME_LOW_RES_MODE = 0x23
#bus = smbus.SMBus(0) # Rev 1 Pi uses 0
bus = smbus.SMBus(1) # Rev 2 Pi uses 1
def convertToNumber(data):
# Simple function to convert 2 bytes of data
# into a decimal number
return ((data[1] + (256 * data[0])) / 1.2)
def readLight(addr=DEVICE):
data = bus.read_i2c_block_data(addr,ONE_TIME_HIGH_RES_MODE_1)
return convertToNumber(data)
def main():
file = open("/home/pi/Desktop/Sr_Design/Light_data_log.csv","w")
i=0
if os.stat("/home/pi/Desktop/Sr_Design/Light_data_log.csv").st_size == 0:
file.write("Date,Time,Light Level (lx),Temp(F)\n")
while True:
i = i + 1
tempfile = open("/sys/bus/w1/devices/28-031590bc20ff/w1_slave")
#Opens sensor data
thetext = tempfile.read()
tempfile.close()
tempdata = thetext.split("\n")[1].split(" ")[9]
temperature = float(tempdata[2:])
#Records the data from the
DS18b20 teperature sensor
temperature = temperature / 1000
#keeps from going right three
places in the decimal
degreesFahrenheit = temperature *9/5+32
#Converts temp for degrees C
to Degrees F
file.write(str(time.strftime("%m-%d-%Y"))+
","+str(time.strftime("%H:%M:%S"))+
","+str(readLight())+ ","+str(degreesFahrenheit)+"\n" )
print i
if i == 20:
break
time.sleep(1) #Time between readings
if __name__=="__main__":
main()
--------------------------------------------------------------------------------------------------------------------TEMPERATURE AND LIGHT INTENSITY EMAIL CODE
--------------------------------------------------------------------------------------------------------------------#This program is used to email the recorded data to the user
#prompting for the user's email could be used
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
fromaddr = "[email protected]"
toaddr = "[email protected]"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Excel Sheet with Project Data"
body = "The following message contains an attachment with the array's daily
data."
msg.attach(MIMEText(body, 'plain'))
filename = "/home/pi/Desktop/Sr_Design/data_log.csv"
attachment = open("/home/pi/Desktop/Sr_Design/Light_data_log.csv", "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "*********")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
--------------------------------------------------------------------------------------------------------------------TEXT NOTIFICATION CODE
--------------------------------------------------------------------------------------------------------------------#This program sends the user a text notifying that the program is complete
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
fromaddr = "[email protected]"
toaddr = "[email protected]"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
body = "The sensor data has been collected and a table of the outputs has
been sent to your email"
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "***********")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
--------------------------------------------------------------------------------------------------------------------INA3221 MAIN CODE
--------------------------------------------------------------------------------------------------------------------# This program writes the Output readings of the array and temperature into
an Excel file
# The program is set to "a" for amending the file (line 10) Change to "w" to
Overwrite file with new Data
# This program can be edited to add additional sensor data to the file.
# This program also has the ability to notify the user via text message and
email when the program has finished its execution
import os
import sys
import time
import datetime
from time import sleep
from datetime import datetime
import random
import SDL_Pi_INA3221
ina3221 = SDL_Pi_INA3221.SDL_Pi_INA3221(addr=0x40)
# the three channels of the INA3221 named for SunAirPlus Solar Power
Controller channels (www.switchdoc.com)
PANEL_CHANNEL
= 1
BATTERY_CHANNEL
= 2
CONTROLLER_CHANNEL
= 3
#Creates a file where the data will be stored
file = open("/home/pi/Desktop/Sr_Design/Power_data_log.csv","w")
#Variables
i
=
num
=
by the user
time_elapsed
=
program has been running
run_time
=
loop
0
0
#Loop Counter
#Number of loops determined
0
#Keeps track of how long the
0
#Stores the duration of the
#This section prompts the user to enter the duration of the readings
print "How long do you wish the program to run? (hh:mm:ss)"
hours=input("Hours: ")
minutes=input("Minutes: ")
seconds=input("Seconds: ")
#3600 seconds in an hour 60 seconds in a minute, gives runtime in seconds
run_time = (hours * 3600) + (minutes * 60) + seconds
#Prompts the user to configure the frequency of readings in seconds
freq=input("Frequency of readings in seconds: ")
num = run_time/freq
#Number of loops the
program will execute
#Opens the file and creats the rows in the excel sheet
if os.stat("/home/pi/Desktop/Sr_Design/Power_data_log.csv").st_size == 0:
file.write("Date, Time, Panel Voltage (V), Panel Current (A), Panel Power
(W)," +
"Battery Voltage (V), Battery Current (A), Battery Power (W),"+
"Controller Voltage (V), Controller Current (A), Controller Power (W)\n")
#Records the start time of the loop
start_time = time.time()
#The loop will remain true until i is equal to num
while True:
#-----------------------------------------------------------------------------------------------------#
#Initiates the panel readings to zero to ensure no old data is still
stored for that variable
panel_shuntvoltage1 = 0
panel_busvoltage1
= 0
panel_current_A1
= 0
panel_loadvoltage1 = 0
panel_power
= 0
#For each reading an if statement is present to null any unwanted data
#Determines the Bus voaltage of the panel
if (ina3221.getBusVoltage_V(PANEL_CHANNEL) <= 0.999):
panel_busvoltage1 = 0
else:
panel_busvoltage1 = ina3221.getBusVoltage_V(PANEL_CHANNEL)
#Determines the Shunt Voltage of the panel
if ina3221.getShuntVoltage_mV(PANEL_CHANNEL) <= 0.999:
panel_shuntvoltage1 = 0
else:
panel_shuntvoltage1 = ina3221.getShuntVoltage_mV(PANEL_CHANNEL)
#Determines the Current of the panel
if ina3221.getCurrent_A(PANEL_CHANNEL) <= 0.0999:
panel_current_A1 = 0
else:
panel_current_A1 = ina3221.getCurrent_A(PANEL_CHANNEL)
#Calculates the Load Voltage of the panel by adding the bus and shunt
voltages
panel_loadvoltage1 = panel_busvoltage1 + (panel_shuntvoltage1 / 1000)
#Calculates the power supplied by the panel
panel_power = panel_loadvoltage1 * panel_current_A1
#This section is only needed for reviewing data in real time and will
only be seen on the PI display
print "Panel Bus Voltage: %3.4f V " % panel_busvoltage1
print "Panel Shunt Voltage : %3.4f mV " % panel_shuntvoltage1
print "Panel Load Voltage : %3.4f V" % panel_loadvoltage1
print "Panel Current : %3.4f A" % panel_current_A1
print "Panel Power : %3.4f W" % panel_power
print
#----------------------------------------------------------------------------------------------------#
#Initiates the battery readings to zero to ensure no old data is still
stored for that variable
battery_shuntvoltage2 = 0
battery_busvoltage2
= 0
battery_current_A2
= 0
battery_loadvoltage2 = 0
battery_power
= 0
#For each reading an if statement is present to null any invalid data
#Determines the Bus voaltage of the battery
if (ina3221.getBusVoltage_V(BATTERY_CHANNEL) <= 0.999):
battery_busvoltage2 = 0
else:
battery_busvoltage2 = ina3221.getBusVoltage_V(BATTERY_CHANNEL)
#Determines the Shunt Voltage of the battery
if ina3221.getShuntVoltage_mV(BATTERY_CHANNEL) <= 0.999:
battery_shuntvoltage2 = 0
else:
battery_shuntvoltage2 = ina3221.getShuntVoltage_mV(BATTERY_CHANNEL)
#Determines the Current of the battery
if ina3221.getCurrent_A(BATTERY_CHANNEL) <= 0.0999:
battery_current_A2 = 0
else:
battery_current_A2 = ina3221.getCurrent_A(BATTERY_CHANNEL)
#Calculates the Load Voltage of the battery by adding the bus and shunt
voltages
battery_loadvoltage2 = battery_busvoltage2 + (battery_shuntvoltage2 /
1000)
#Calculates the power supplied to the battery / if negative the battery
is supplying power)
battery_power = battery_loadvoltage2 * battery_current_A2
#This section is only needed for reviewing data in real time and will
only be seen on the PI display
print "Battery Bus Voltage : %3.4f V " % battery_busvoltage2
print "Battery Shunt Voltage : %3.4f mV " % battery_shuntvoltage2
print "Battery Load Voltage : %3.4f V" % battery_loadvoltage2
print "Battery Current : %3.4f A" % battery_current_A2
print "Battery Power :%3.4f W" % battery_power
print
#----------------------------------------------------------------------------------------------------#
#Initiates the controller readings to zero to ensure no old data is still
stored for that variable
controller_shuntvoltage3 = 0
controller_busvoltage3
= 0
controller_current_A3
= 0
controller_loadvoltage3 = 0
controller_power
= 0
#For each reading an if statement is present to null any invalid data
#Determines the Bus voaltage of the controller
if ina3221.getBusVoltage_V(CONTROLLER_CHANNEL) < 0.999:
controller_busvoltage3 = 0
else:
controller_busvoltage3 = ina3221.getBusVoltage_V(CONTROLLER_CHANNEL)
#Determines the Shunt Voltage of the controller
if ina3221.getShuntVoltage_mV(CONTROLLER_CHANNEL) < 0.999:
controller_shuntvoltage3 = 0
else:
controller_shuntvoltage3 =
ina3221.getShuntVoltage_mV(CONTROLLER_CHANNEL)
#Determines the Current of the controller
if ina3221.getCurrent_A(CONTROLLER_CHANNEL) < 0.00999:
controller_current_A3 = 0
else:
controller_current_A3 = ina3221.getCurrent_A(CONTROLLER_CHANNEL)
#Calculates the Load Voltage of the controller by adding the bus and
shunt voltages
controller_loadvoltage3 = controller_busvoltage3 +
(controller_shuntvoltage3 / 1000)
#Calculates the power supplied by the controller
controller_power = controller_loadvoltage3 * controller_current_A3
#This section is only needed for reviewing data in real time and will
only be seen on the PI display
print "Controller Bus Voltage : %3.4f V " % controller_busvoltage3
print "Controller Shunt Voltage : %3.4f mV " % controller_shuntvoltage3
print "Controller Load Voltage : %3.4f V" % controller_loadvoltage3
print "Controller Current : %3.4f A" % controller_current_A3
print "Controller Power :%3.4f W" % controller_power
print
#----------------------------------------------------------------------------------------------------#
#This section writes all the data to the excel file. The voltage, current
and power of each along with
# the date, time, and temperature of the reading
file.write(str(time.strftime("%m-%d-%Y")) + ", " +
str(time.strftime("%H:%M:%S")) +
", " + str(panel_loadvoltage1) + ", "+str(panel_current_A1) +
", " + str(panel_power) +
", " + str(battery_loadvoltage2) + ",
"+str(battery_current_A2) + ", " + str(battery_power) +
", " + str(controller_loadvoltage3) + ",
"+str(controller_current_A3) + ", " + str(controller_power) +
"\n")
file.flush()
#This is also for Pi display to runtime, amount of readings left to take,
and time remaining
print "Time elapsed :%3.4f S" % time_elapsed
print "Number of readings left to take: " + str(num - i)
print "Time Remaining: " + str( run_time - time_elapsed) + "Seconds\n"
#When the counting variable reaches the desired number of readings the
program breaks the loop and closes the file
if i == num:
break
time.sleep(freq)
file.close()
#This calls the program that emails the Data in an attached file
#The two programs need to be located in the same folder
os.system("python Power_Data_to_email.py")
os.system("python Light_Data_to_email.py")
os.system("python NotificationText.py")