Wednesday, March 2, 2016

Solar Powered Remote Temperature Sensor

The scientific method allows us to examine the universe and its natural phenomena. Through collection and analysis of data, we discover historical trends to make predictions about future events. One such phenomenon that greatly impacts our daily, and long-term, lives is temperature. This tutorial shows you how to build your own remote temperature sensor that automatically uploads data to the web service. This is a perfect, hands-on project for teaching, or learning, the difference between daily temperature fluctuations and average temperature over time, a particularly crucial distinction when discussing climate change.

This system uses the ​Particle Photon as the control device, a handy lil' microcontroller that easily connects to WiFi. The Photon reads in temperature data from the SparkFun TMP102 digital temperature sensor, then uploads the data to a web server for remote data acquisition and, if desired, subsequent analysis and plotting.

Recommended Reading

The goal of this tutorial is to give you enough information to get your remote temperature sensor up and running as quickly as possible, regardless of your background and experience with the components used in this project. As such, this tutorial provides only a brief mention of the underlying hardware and software elements. Check out the guides below for more in-depth information, including the I2C communication protocol used by the TMP102 sensor and the Phant library used by the web service.

Hardware Guides

- Guide to setting up the Particle Photon
- Hookup Guide for Photon Battery Shield
- Tutorial to hooking up the TMP102 for Arduino
- Datasheet for the TMP102
- Datasheets are your friend! It is highly recommended to review this datasheet, at the very least to get more familiar with datasheets.

Software Guides

- The TMP102 temperature sensor uses I2C (Inter-Integrated Circuit) communication protocols. If you are new to this, here is a handy overview of I2C protocols.
- This tutorial uses the web server to host the temperature data stream.
- Here's a guide on pushing data to the host.
- Here's a tutorial on using HTTP to log data.



- Particle Photon microcontroller
- SparkFun Photon Battery Shield
- TMP102 Digital Temperature Sensor
- 2.5 W Solar panel
- Polymer Lithium Ion Battery - 6 Ah
If you live in a sunnier climate than Seattle, you can use a lower capacity battery (e.g. 2000 mAh battery).
- Be careful with the JST connectors, and avoid pulling the wires, particularly when removing them. Check out [this tutorial for an easy way to remove them.
- Six (6) Header pins
- Surface Mount DC Barrel Jack
- Four (4) Male-to-Female Breadboard Jumper Wires (or use 22-gauge insulated wire)
- Breadboard (and/or PCB board)

Casing and Installation

- For electronics: Project box or waterproof tupperwear
There are tons of options for cases, just be sure it is durable, waterproof, and not made of metal (will block the WiFi signal).

- Stand for solar panel (e.g. metal post, garden sign, plant holder, etc.)
While a stand is somewhat optional, it allows you to point the panel towards the sun and adjust it throughout the year to obtain maximum incident solar radiation. Check out your local thriftstore for inexpensive items to use as a stand. Be sure the stand + attached panel will withstand the elements (including wind). Alternatively, you can attach the solar panel directly to the temperature sensor case.


- Soldering Iron
- Wire Strippers
- Multimeter
- Epoxy, or other electrically insulating adhesive
- Velcro (to adhere solar panel to stand)
- Drill or waterproofing electrical tape (for getting solar panel cable into case)

 Build It! Pt. 1

1. Set up the Particle Photon.
Go to the Photon set up page and follow the instructions to set up your Photon for WiFi. The Photon LED will slowly pulse (aka breathe) light blue when it is successfully connected to WiFi. Run through a practice program to check that the Photon is working as expected.
We also need the Integrated Development Environment ("IDE") to program the Photon. Visit this site to guide you through this process.

2. Locate your specific Photon "Device ID" and the "Access Token". Store in a convenient, and secure, location.
The Device ID is found by going to the "Devices" tab in the Particle Build IDE. Your Access Token is found in the "Settings" tab.

3. Solder header pins to the SparkFun temperature sensor (TMP102).

4. Solder the DC barrel jack onto the bottom of the Photon Battery Shield. 

Build It! Pt. 2

1. Plug the Photon into the Photon Battery Shield.
Be sure that the rounded edges of the Photon line up with the rounded lines on the battery shield. Connect the battery and solar panel to the respective connectors. Check that the Photon powers on and connects to WiFi.

2. Connect the TMP102 temperature sensor to Photon battery shield pins with the breadboard jumper wires (or stranded 22 gauge insulated wire).

The green wire corresponds to the SDA pins, yellow wire to the SCL pins.

This project only needs four (4) of the six (6) pins on the TMP102: VCC, GND, SDA and SCL. If you want to connect multiple temperature sensors using the I2C lines, you can use the ADDR0 pin to changes the device address for each sensor (See the I2C communication tutorial for help with this.
Connect TMP102 VCC pin to the Photon 3.3V source and GND to a Photon GND pin. Connect the TMP102 SDA pin to the Photon D0 pin and the SCL pin to the Photon D1 pin.

You can keep the final system on a broadboard or transfer it to a PCB board.

Program It! Pt. 1: Read in the TMP102 Temperature Sensor

The program provided in Program It! Pt. 3 is designed to function nearly as-is, with only a few minor changes necessary to get the system up and running. Unless you want to add more sensors, or use different sensors, you do not need to change the program code to read in the TMP102 temperature data. That said, if you are new to electronics, or I2C communication, it is still helpful to understand the basics of how the TMP102 sends data, particularly when debugging.

Quick Overview of TMP102 Datasheet
The TMP102 temperature sensor uses I2C communication, a two-wire serial interface.The two lines are SDA (Data) and SCL (Clock). The corresponding Photon pins are D0 (SDA) and D1 (SCL). The program below uses the default address of 72 (code variable `TEMP102_ADDRESS`) for the TMP102 sensor.

The TMP102 sensor outputs two bytes in binary (code variable `BYTES_TO_READ`). The first byte is the most significant byte (MSB), and the second byte is the least significant byte (LSB). The first 12 bits (out of 16) are used to indicate temperature, where one LSB is 0.0625 °C. The program is commented where these operations occur.

Review the TMP102 data sheet for more information.

Program It! Pt. 2: Set up a Data Host

This system uses the web service to log the TMP102 temperature data. You can remotely access the temperature data using the public URL generated when you create your data stream. To use the program provided in the next section, follow the procedure below to set up a data stream on the server.

1. Create a data stream on the service.

2. Fill in your desired title and description.

3. For the fields section, input "temp" and "unit". It is imperative to use these exact field names (all lower case) or the data will not upload unless you change the respective field names in the program.

4. Save the data stream. This will redirect you to the stream's key page. Copy all of this information and store in a secure location.

A quick overview of the keys:

Public Key – This is a long hash that is used to identify your stream and provide a unique URL. This key is publicly visible, meaning that anyone who visits your stream’s URL will be able to see this hash.

Private Key – The private key is necessary to post data to the stream. Only you should know this key.

Delete Key – This key deletes the stream, so normally you’ll want to avoid this key. Only use this key if you need to fix the field names or if you truly want to delete the data stream.

Fields – In our program, our fields are "temp", which corresponds to the temperature reading in degrees Celsius, and "unit", to let us know that our reading is in degrees Celsius. These fields set specific values and create a new log of data.

5. The timestamp generated is given in the UTC (Universal Time Coordinate) timezone. The easiest way to handle this timezone is to convert it to your local timezone once you've downloaded the data.

6. To monitor the Photon output, use the Particle driver downloaded as described in the "Connecting Your Device" Photon tutorial .
To view the particle serial monitor, in the command prompt type `particle serial monitor`. This is extremely helpful for debugging and checking to be sure the Photon is posting data to your host. The program provided in the next section includes print statements that indicate the status of the data acquisition and upload process to help facilitate the setup process.



Program It! Pt. 3: System Code

Here's the GitHub page for the program code (and here's the raw text of the code for folks who are new to GitHub).

What you need to change in the program:
1. Copy and paste your data stream public key to the array called `publicKey[]`.
Edit the following program code:
`const char publicKey[] = "INSERT_PUBLIC_KEY_HERE";`

2.Copy and paste your data stream private key to the array called `privateKey[]`.
Edit the following program code:
`const char privateKey[] = "INSERT_PRIVATE_KEY_HERE";`
What you may want to change in the program:
1. The posting rate (code variable `postingRate`) sets how often the temperature data is uploaded to the data stream. The current post rate is ~ 20s (20000 ms).
You can set a different value in line 23 of the program, reproduced below. The maximum post rate allowed by the host is about one data point every 10 seconds (100 posts every 15 minutes).
    `const unsigned long postingRate = 20000; //post rate to (time in milliseconds)`
2. The temperature unit (currently in °C).
To upload data in °F, multiply `temp` (line 47) by 1.8 and add 32, as shown below.
    `int temp = (((( MSB << 8) | LSB) >> 4) * 0.0625)*1.8 + 32;`
Be sure to update the output unit from "C" to "F" in line 51:
`postToPhant(temp, 'F');`

3. If you are comfortable with code, feel free to change anything else you want!

Test & Encase!

1. Plug battery and solar panel into Photon battery shield.
Check that the Photon successfully powers on, connects to WiFi (the Photon LED will be breathing light blue), and sends temperature data to your data stream (accessible via the public URL).

2. Coat electrical connections in epoxy or other (ideally waterproof) adhesive.
Please note that epoxy is very permanent. If you intend to modify the project or use the components for another project in the future, use an adhesive method that is removable, like hot glue.

3. Place electronics in project case.
Determine where the solar panel cable will enter the case. Use waterproofing electrical tape to seal area around solar panel cable or a drill hole in the case for the solar panel cable (coat exterior in waterproofing tape or epoxy). If you place the temperature sensor inside the case, ensure that there is sufficient air ventilation to avoid turning the project case into a sauna.

Be sure that the wires are not stretched or bent much as this will cause breakage over time.

4. Seal any remaining holes or other air gaps with waterproofing electrical tape or epoxy.
If you are sealing the project case lid, it is highly recommended to use a removable sealant like the waterproofing electrical tape to access the electronics in the future.

5. Connect solar panel to stand.
The stand in this example is a towel rack found at a local thrift store. This was perfect for my needs because 1) it was very inexpensive and 2) the rings are adjustable, which allows me to change the orientation of the solar panel to point it towards the maximum incident solar radiation (aka sunlight) depending on where it is installed outdoors and the current season (since the sun's path changes depending on the seasons).

There are tons of options for a stand! Peruse your garage/basement/attic/cupboards/closets or check out the outdoor section of a local thrift store or hardware store. Look for objects that can withstand nature's elements, will maintain ridigity, and can support the solar panel weight.


1. Once the case and stand are complete, connect the battery and solar panel to the Photon battery shield.
Check that the Photon is adequately powered, connected to WiFi (pulsing light blue), and is uploading data to your data stream.

The battery recommended in this tutorial has a capacity of 6Ah (Amp-hours), which means it can provide 6A for 1 hour. The Photon microcontroller average power consumption is between 80 - 100 mA. Assuming maximum current draw of 0.1A, this means that the battery can power the system for ~60 hours (2.5 days) without any charge from the solar panel. This is ideal/necessary for cloudy locations (like Seattle where this project was designed and built) or for remote sites that are difficult to access on a daily basis.

If you use a different battery, calculate the total number of hours the battery can power the Photon, without being charged by the solar panel. Do this by dividing the battery capacity (given in Amp-hours) by the Photon max. current draw (0.1A). Since the sun hides behind the other side of the planet at night, be sure that your battery can provide power for at least 10-12 hours.

2. Install the system within reach of the WiFi signal for which it is configured -- the Photon will flash green if it is not connected to WiFi.
If using a clear case, be sure to place the temperature sensor in a shady location, avoiding direct sunlight, as incident solar radiation will increase the temperature measurement. To avoid this greenhouse effect, use or paint a black container.

3. Place the solar panel in the sunniest spot available at your chosen location.
Determine the optimum solar angle for your panel, and point the solar panel in that direction. You'll want to change this angle over the course of the year as the sun angle changes (higher in the summer, lower in the winter, also highly dependent on location). Here's a great online calculator to help you determine the optimal solar angle in your particular city.

Data Acquisition and Analysis

The service allows you to download your data in a few different formats, so pick the format that is easiest for you to handle. Most common data analysis programs, including Excel, R, and Python, can handle CSV (Comma Separated Values) files.

Below is one method to plot your data using a program written for the R platform, a free statistical software environment.

1. Download your data in CSV file format (button is located a the top of the data stream).

2. In the R workspace, run the program below to generate a plot and basic analysis of your data.
Here's a link to a sample program that reads in the CSV file and plots the temperature in Celsius and Fahrenheit degree scales, as well as a brief summary output of the data.

Education Extension

Building this remote temperature sensor teaches practical, hands-on skills in hardware and software engineering. Beyond direct project-based learning, there are tons of ways to extend this project for classroom and other citizen science activities. Here are a few ways to use this system to teach fundamental scientific concepts.

What is Temperature?
This system measures temperature at a very specific, and known, location, which allows us to combine our direct observations with experimental data. Create your own experiment to change the temperature reading by changing the outside environment, keeping everything else the same.

For example, move the temperature sensor into direct sunlight, and gather data over a specific time interval, then move the temperature sensor back into the shade for the same amount of time. Analyze how the temperature reading changes and compare it to your own observations of outside temperature. Experiment with different ways to change the temperature reading. Be creative*, and see what tests your students think up!
*Avoid water contact unless you've thoroughly coated the electrical connections in epoxy or other waterproof adhesive.

Heat Capacity: Comparison of Temperature and Heat
Build the temperature sensor case to be air-tight, then use different material types and/or sizes of enclosures to analyze the difference between temperature and heat. Different materials have different heat capacities or the amount of heat needed to raise the material's temperature by one degree. In other words, materials absorb and retain heat at varying rates. This helps us understand that heat is a form of energy, while temperature is a measure of that energy.

For each case, place sensor in direct sunlight and leave overnight. Determine how quickly the temperature sensor reading increases and decreases. A high heat capacity material will slowly increase and decrease in temperature, whereas a low heat capacity material will quickly heat up and cool off. Create plots of the temperature changes for various cases to determine what types of materials, and what sizes, retain heat the most. Find patterns between different material types and use those patterns to determine why certain materials have higher heat capacities.

Analysis of Data Trends: Long-Term vs. Short-Term
The difference between daily temperature and average temperature is a crucial concept in understanding climate change. It also provides a real-world application of the difference between long- and short-term trends. Fortunately, the service makes this analysis simple and straightforward, the hardest part is waiting! It is also suggested to have a back-up battery if you live in a cloudy climate (like Seattle).

For this science lesson, gather data for a minimum of two (2) to three (3) months, ideally through a seasonal change. Download the data and find the average (mean) temperature by day, week, and month. Select a few 24-hour periods to plot temperature, and compare daily fluctuations with your calculated averages. See if you can use the temperature data to pinpoint the changing seasons!

1 comment:

  1. This comment has been removed by a blog administrator.


Creative Commons License
This work by Jennifer Fox is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License