Using Arduino for Citizen Science!

Science allows us to ask our most pressing questions and explore all sorts of curiosities. With some thought, hard work, and patience, we can use our explorations to build a better understanding and appreciation of the complex and beautiful world around us.

This tutorial will teach you how to use an Arduino (uno) microcontroller, how to use different types of sensors, and how to gather and visualize data. Along the way, we’ll build three projects: a tilt switch, a temperature and humidity sensor, and a light sensor!

Difficulty Level: Beginner

Read Time: 20 min

Build Time: Depends on your project! (Projects in this tutorial take about 15 – 20 min)

Pssst, What’s the Difference Between Citizen Science and “official Science”?

The biggest difference is that citizen science is, as I love to say, “hand wavy”, which means that there are lots of errors and uncertainties and no rigorous process to identify them. Because of this, conclusions reached through citizen science are much less accurate than science-science and should not be relied upon to make serious/life-altering/life-threatening claims or decisions.*

That being said, citizen science is a great way to build a fundamental understanding of all sorts of fascinating scientific phenomenon and is good enough for most day-to-day applications.

*If you are doing citizen science and you discover something potentially dangerous (e.g. high lead levels in water), inform your educator (if applicable) and contact the relevant authorities and professionals for assistance.

What Is Arduino??

Arduino is a microcontroller board and Integrated Development Environment (“IDE”), which is a fancy way of saying “coding program”. For beginners, I highly recommend Arduino Uno boards because they are super robust, reliable, and powerful.

Arduino boards are a good choice for citizen science projects because they have lots of input pins to read in both Analog and Digital sensors (we’ll get more into this later).

Of course, you can use other microcontrollers for citizen science depending on your (or your students’) needs, abilities, and comfort level. Here is an overview of microcontrollers to help ya decide what is best for you!

To flash, or program, an Arduino board, plug it in via USB, then:

1. Select the type of Arduino you’re using under Tools -> Boards.

 

2. Select the port (aka where it’s connected to your computer).

 

3. Click the Upload button and check that it finishes uploading.

Tools & Materials

If you’re just getting started, getting a kit is a quick & easy way to get a bunch of parts at once. The kit I’m using in this tutorial is the Elegoo Arduino Starter Kit.*

Tools

  • Arduino Uno
  • USB A to B cable (aka printer cable)
  • Jumper Wires
    • 3 male-to-male
    • 3 male-to-female
  • Breadboard
    • Optional but recommended to make your life easier and more fun 🙂

Materials

For the projects covered in this tutorial, you’ll need these parts from the Elegoo Arduino Starter Kit:

  • Tilt Switch
  • DTH11 Temperature and Humidity Sensor
  • LED
  • 100 Ohm Resistor

*Full disclosure: I purchase these same kits for workshops, but the kit used in this tutorial was donated by the lovely folks at Elegoo.

What Kinds of Sensors Can We Use?

When designing a science experiment, we typically start with a question: How much CO2 do plants absorb in a day? What is the impact force of a jump? What is consciousness??

Based on our question, we can then identify what we want to measure and do some research to figure out what sensor we can use to gather data (although it miiight be a bit tricky to gather data for that last question!).

When working with electronics, there are two main types of sensor data signals: Digital and Analog. In the photo, the first two rows of parts are all digital sensors, while the top two rows are analog.

There are many different types of digital sensors, and some are more challenging to work with than others. When doing research for your citizen science project, always check how the sensor puts out data (srsly tho) and make sure you can find an (Arduino) library for that specific sensor.

In the three projects covered in this tutorial we’ll use two types of digital sensors and one analog sensor. Let’s get a-learnin!

Digital Sensors!

Part 1: the Easy Ones

Most sensors you’ll use output a Digital Signal, which is a signal that is either on or off.* We use binary numbers to represent these two states: an On signal is given by a 1, or True, while Off is 0, or False. If we were to draw a picture of what a binary signal looks like, it would be a square wave like the one in the photo below!

There are some digital sensors, like switches, that are super easy and straightforward to measure because either the button is pushed and we get a signal (1), or it is not pushed and we have no signal (0). The sensors pictured in the bottom row of the first photo are all simple on/off types. The sensors on the top row are a bit more complex and are covered after our first project.

The first two projects in this tutorial will teach you how to use both types! Onward to build our first project!!

*On means an electrical signal in the form of electric current and voltage. Off means no electrical signal!

Project 1: Tilt Switch Digital Sensor

For this first project, let’s use a tilt switch, that black cylindrical sensor with two legs!
Step 1: Insert one leg of the tilt switch into Arduino Digital Pin 13, and the other leg into the GND pin right next to pin 13. Orientation doesn’t matter.

Step 2: Write a sketch that reads in and prints out the status of Digital Pin 13.

Or you can just use mine!

If you’re just getting started in coding, read through the comments to better understand how the sketch works and try changing some things to see what happens! It’s OK to break things, that’s a great way to learn! You can always re-download the file and start over 🙂

Step 3: To see your live data, click on the Serial Monitor button.

.. aaaand that’s it! You can now use the tilt switch to measure orientation! Set it up to call out your kitty when it knocks something over, or use it to keep track of how tree branches move during storms! .. & there are probably other applications in between those two extremes.

Digital Sensors!

Part 2: PWM and Serial Communication

There are many ways to create more complex digital signals! One method is called Pulse Width Modulation (“PWM”), which is a fancy way of saying a signal that is on for a certain amount of time and off for a certain amount of time. Servo motors (which can be used to measure position) and ultrasonic sensors are examples of sensors that use PWM signals.

There are also sensors that use serial communication to send data one bit, or binary digit, at a time. These sensors require some familiarity with reading datasheets and can be pretty tricky if you’re just getting started. Fortunately, common serial sensors will have code libraries* and sample programs to pull from so you can still cobble together something functional. More details on serial communication protocols is beyond the scope of this tutorial, but here is a great resource on serial communication from SparkFun to learn more!

For this sample project, let’s use the temperature and humidity sensor (DHT11)! This is a lil’ blue square with holes and 3 pins.

First we’ll need a couple of special libraries for the DHT11 sensor: the DHT11 library and the Adafruit Unified Sensor library.
To install these libraries (and most other Arduino libraries):

Step 1: Open up the Arduino library manager by going to Sketch -> Libraries -> manage Library

Step 2: Install and activate the DHT library by searching for “DHT” and then clicking Install for the “DHT Arduino Library” .

Step 3: Install and activate the Adafruit Unified Sensor library by searching for “Adafruit Unified Sensor” and clicking install.

Step 4: Insert the DHT library into your open sketch by going to Sketch -> Libraries, and clicking on the “DHT Arduino Library.  This will insert a couple of new lines at the top of your sketch, which means our library is now active and ready to use!

*Just like your fav local library, code libraries are a wealth of knowledge and other folks’ hard work that we can use to make our lives easier, yay!

Project 2: Temp and Humidity Digital Serial Sensor

 

Grab 3 male-to-female jumper wires from the Elegoo Arduino Starter Kit and we’re ready to go!

Step 1: With the header pins facing you, connect the rightmost header pin on the DHT11 to an Arduino ground (“GND”) pin.

 

Step 2: Connect the middle header pin to Arduino 5V output pin.

 

Step 3: Connect the leftmost header pin to Arduino Digital Pin 2.

Step 4: Finally, read the DHT library and try your hand at writing a sketch! Oooor you can use mine or the DHT test example sketch within Arduino -> Examples!

When you’ve got it up and running, go forth and measure the temperature and humidity of all the things! .. Like an animal’s breath, a greenhouse, or your favorite climbing spot at different times of the year to find the *perfect* sending temp.

Analog Sensors!

After the difficult dive into digital sensors, analog sensors can seem like a breeze! Analog signals are a continuous signal, like the photo below.

Most of the physical world exists in analog (e.g. temperature, age, pressure, etc.), but since computers are digital*, most sensors will output a digital signal. Some microcontrollers, like Arduino boards, can also read in analog signals**.

For most analog sensors, we give the sensor power, then read in the analog signal using the Analog Input pins. For this test, we’ll use an even simpler setup to measure the voltage across an LED when we shine a light on it.

*Computers use digital signals to store and transmit info. This is because digital signals are easier to detect and are more reliable, since all we’ve got to worry about is getting a signal or not versus having to worry about the quality/accuracy of the signal.

** To read in an analog signal on a digital device, we must use an Analog-to-Digital, or ADC, converter, which approximates the analog signal by comparing the input to a known voltage on the device, then counting how long it takes to reach the input voltage. For more info, this is a helpful site.

Project 3: LED As a Light Sensor!

Grab an LED (any color except white), a 100 Ohm resistor, and 2 jumper cables. Oh, and a breadboard!

Step 1: Insert the LED into the breadboard with the longer leg on the right side.

Step 2: Connect a jumper wire from Arduino Analog Pin A0 and the longer LED leg.

Step 3: Connect the resistor between the shorter LED leg and the breadboard negative power rail (next to the blue line).

Step 4: Connect the Arduino GND pin to the negative power rail on the breadboard.

Step 5: Write a sketch that reads in Analog Pin A0 and prints to the Serial Monitor!

Here is a sample code to get ya started.

Visualizing Data: Arduino IDE!

The Arduino IDE comes with built-in tools to visualize data. We’ve already explored the basics of the Serial Monitor which allows us to print sensor values. If you want to save and analyze your data, copy the output directly from the Serial Monitor and paste into a text editor, spreadsheet, or other data analysis tool.

The second tool we can use to see our data in the Arduino program is the Serial Plotter, a visual version (aka graph) of the Serial Monitor. To use the Serial Plotter, go to Tools –> Serial Plotter. The graph below is the output of the LED as a light sensor from Project 3!*

The plot will auto-scale and as long as you’re using Serial.println() for your sensors, it will also print all of your sensors in different colors. Hooray! That’s it!

*If you look at the end, there is a super interesting wave pattern which is likely due to the Alternating Current (“AC”) in our overhead lights!

Visualizing Data: Excel!

For more serious data analysis, there’s a super cool (and free!) add-in for Excel called Data Streamer*, which you can download here.

This add-in reads from the serial port, so we can use the exact same coding technique of printing data to serial to get data directly into Excel.. heck yes!!

How to use the Data Streamer Add-In:

1. Once you’ve installed it (or if you have O365), click on the Data Streamer tab (far right) in Excel.

2. Plug in your Arduino and click “Connect Device”, then select the Arduino from the drop-down menu.

3. Click “Start Data” to start data collection! You’ll see three new sheets open up: “Data In”, “Data Out”, and “Settings”.

Live data is printed in the Data In sheet.  Each row corresponds to a sensor reading, with the newest value printed in the last row.

By default we only get 15 rows of data, but you can change this by going to “Settings”. We can gather up to 500 rows (limit is due to Excel bandwidth — there’s a lot happening in the background!).

 

4. Add a Plot of your data! Do some data analysis!
Scatter plots show you how the sensor readings change over time, which is the same thing we saw in the Arduino Serial Plotter.

To add a Scatter Plot:

Go to Insert -> Charts -> Scatter. When the plot pops up, right click on it and choose “Select Data”, then Add. We want our data displayed on the y-axis, with “time”** on the x-axis.

To do this, click the arrow next to the y-axis, go to the Data In sheet, and select all of the incoming sensor data.

We can also do calculations and comparisons in Excel! To write a formula, click on an empty cell and type an equals sign (“=”), then the calculation you want to do. There are lots of built-in commands like average, maximum, and minimum.

To use a command, type the equals sign, the command name, and an open parenthesis, then select the data you’re analyzing and close the parentheses.

5. To send more than one column of data (AKA more than one sensor), print the values on the same line separated by a comma, with a final blank new line, like this:

Serial.print(sensorReading1); 
Serial.print(","); 
Serial.print(sensorReading2); 
Serial.print(","); 
Serial.println();

*Full disclosure: Although this tutorial is not affiliated, I do work w/ the Microsoft Hacking STEM team which developed this add-in.

**If you want the actual time to be on the x-axis, select the timestamp in Column A on the Data In sheet for the x-axis values in your Scatter Plot. Either way, we’ll see our data as it changes over time.

Go Forth and Measure All the Things!!

Alright folks, that’s all! Time to go outward and upward! Use this as a foundation to start exploring sensors, Arduino coding, and data analysis to tackle your questions, curiosities, and fav mysteries in this big, beautiful world.

Remember: there are lots of folks out there to help you along the way, so please leave a comment if you have a question!

Need some more ideas? Here’s how to make a wearable state change switch, a solar-powered remote temperature sensor, and an Internet-connected industrial scale!

Like this tutorial and want to see more? Support our projects on Patreon! 😀

Raspberry Pi Impact Force Monitor

How much impact can the human body handle? Whether it’s football, rock climbing, or a bicycle accident, knowing when to seek immediate medical attention after a collision is incredibly important, especially if there are no obvious signs of trauma. This tutorial will teach you how to build your very own impact force monitor!

 

Read Time: ~15 min

Build Time: ~60-90 min

This open-source project uses a Raspberry Pi Zero W and an LIS331 accelerometer to monitor and alert the user of potentially dangerous G-forces. Of course, feel free to modify and adapt the system to suit your various citizen science needs.

Note: Build fun stuff with the Impact Force Monitor! However, please don’t use it as a substitute for professional medical advice and diagnosis. If you feel that you have taken a serious fall, please visit a qualified and licensed professional for proper treatment.

Suggested Reading

To keep this tutorial short n’ sweet (er, well, as much as possible), I’m assuming you’re starting with a functional Pi Zero W. Need some help? No problem! Here’s a full setup tutorial.

We’ll also be connecting to the Pi remotely (aka wirelessly). For a more thorough overview on this process check out this tutorial.

**Stuck or want to learn more? Here are some handy resources:**

1. Excellent “Getting Started” guide for the Pi.

2. Full hookup guide for the LIS331 accelerometer breakout board.

3. More about accelerometers!

4. Overview of the Raspberry Pi GPIO pins.

5. Using the SPI and I2C Serial buses on the Pi.

6. LIS331 Datasheet

Materials

 

Tools

  • Soldering Iron & accessories
  • Epoxy (or other permanent, non-conductive liquid adhesive)
  • Probably also scissors 🙂

But wait! What is Impact Force?

Fortunately the term “impact force” is pretty straightforward: the amount of force in an impact. Like most things though, measuring it requires a more precise definition. The equation for impact force is:

F = KE/d

where F is the impact force, KE is the kinetic energy (energy of motion), and d is the impact distance, or how much the object crunches. There are two key takeaways from this equation:

1. Impact force is directly proportional to the kinetic energy, meaning that the impact force increases if the kinetic energy increases.

2. Impact force is inversely proportional to impact distance, meaning that the impact force decreases if the impact distance increases. (This is why we have airbags: to increase the distance of our impact.)

Force is typically measured in Newtons (N), but impact force may be discussed in terms of a “G-Force”, a number expressed as a multiple of g, or earth’s gravitational acceleration (9.8 m/s^2). When we use units of G-force, we are measuring an objects acceleration relative to free fall towards the earth.

Technically speaking, g is an acceleration, not a force, but it is useful when talking about collisions because acceleration* is what damages the human body.

For this project, we’ll use G-force units to determine if an impact is potentially dangerous and deserving of medical attention. Research has found that g-forces above 9G can be fatal to most humans (without special training), and 4-6G can be dangerous if sustained for more than a few seconds.

Knowing this, we can program our impact force monitor to alert us if our accelerometer measures a G-force above either of these thresholds. Hooray, science!

For more information, read about impact force and g-force on Wikipedia!

Acceleration is a change in speed and/or direction.

Configure the Pi Zero W

Gather your Raspberry Pi Zero and peripherals to configure the Pi to be headless!

  • Connect the Pi to a monitor and associated peripherals (keyboard, mouse), plug in the power supply, and log in.
  • Update software to keep your Pi speedy & secure. Open the terminal window and type these commands:
    • Type and enter:
sudo apt-get update
  • Type and enter:
sudo apt-get upgrade
  • Reset:
sudo shutdown -r now

Enable WiFi & I2C

  • Click the WiFi icon on the upper right corner of the desktop and connect to your WiFi network.
  • In the terminal type this command to bring up the Pi’s Software Configuration Tool:
sudo raspi-config
  • Select “Interfacing Options”, then “SSH”, and choose “Yes” at the bottom to enable.

  • Go back to “Interfacing Options”, then “I2C”, and select “Yes” to enable.
  • In the terminal, install remote desktop connection software:
sudo apt-get install xrdp

  • Type ‘Y’ (yes) on your keyboard to both prompts.
  • Find the Pi’s IP address by hovering over the WiFi connection (you might also want to write it down).

  • Change the Pi’s password with the passwd command.

Restart the Pi and Log in Remotely

We can now ditch the HDMI and peripherals, woohoo!

  • Setup a remote desktop connection.
    • On a PC, open Remote Desktop Connection (or PuTTY if you’re comfy with that).
    • For Mac/Linux, you can install this program or use a VNC program.
  • Enter the IP for the Pi and click “Connect” (Ignore warnings about unknown device).
  • Log in to the Pi using your credentials and away we go!

Build It! Electronics

Here’s the electrical schematic for this project:

Note: The LIS331 breakout board in the schematic is an older version — use the pin labels for guidance

And here’s the pinout for the Pi Zero:

Connect the Accelerometer to the Pi’s GPIO

  • Solder and carefully remove any flux residue on the accelerometer and Pi GPIO’s header pins.

  • Then connect jumper wires between the LIS331 breakout board and Pi between the following pins:

LIS331 Breakout Board                     Raspberry Pi GPIO Pin

GND                                                 GPIO 9 (GND)

VCC                                                  GPIO 1 (3.3V)

SDA                                                   GPIO 3 (SDA)

SCL                                                   GPIO 5 (SCL)

  • To make it easier to connect the sensor to the Pi Zero, a custom adapter was made by using a female header and jumper wires. Heat shrink was added after testing the connections.

Add an Alert LED!

  • Solder a current limiting resistor to the negative LED leg (shorter leg) and add shrink wrap (or electrical tape) for insulation.

  • Use two jumper cables or header pins to connect the positive LED leg to GPIO26 and the resistor to GND (header positions 37 and 39, respectively).

Completed Electronics Setup

Connect the battery pack to the Pi’s input power to complete the setup!

Program It!

The Python code for this project is open-source! Here’s a link to the GitHub repository.

For Folks New to Programming:

  • Read through the program code and comments. Things that are easy to modify are in the “User Parameters” section at the top.

For Folks More Comfortable w/ the Technical ‘Deets:

  • This program initializes the LIS331 accelerometer with default settings, including normal power mode and 50Hz data rate. Read through the LIS331 datasheet and modify initialization settings as desired.

All:

  • The maximum acceleration scale used in this project is 24G, because impact force gets big real quick!
  • It is recommended to comment out the acceleration print statements in the main function when you are ready for full deployment.

Before you run the program, double check that the accelerometer address is 0x19. Open the terminal window and install some helpful tools with this command:

sudo apt-get install -y i2c-tools

Then run the i2cdetect program:

i2cdetect -y 1

You’ll see a table of I2C addresses displayed as shown in the image above. Assuming this is the only I2C device connected, the number you see (in this case: 19) is the accelerometer address! If you see a different number, take note and change in the program (variable addr).

Quick Overview of Program

The program reads the x, y, and z acceleration, calculates a g-force, and then saves the data in two files (in the same folder as the program code) as appropriate:

  • AllSensorData.txt – gives a timestamp followed by the g-force in the x, y, and z axes.
  • AlertData.txt – same as above but only for readings that are above our safety thresholds (absolute threshold of 9G or 4G for more than 3 seconds).

G-forces above our safety thresholds will also turn on our alert LED and keep it on until we restart the program. Stop the program by typing “CTRL+c” (keyboard interrupt) in the command terminal.

Here’s what both data files look like:

Test the System!

Open the terminal window, navigate to the folder where you saved the program code using the cd command.

cd path/to/folder

Run the program using root privileges:

sudo python NameOfFile.py

Check that the acceleration values in the x, y, and z-direction are printing to the terminal window, are reasonable, and turn on the LED light if the g-force is above our thresholds.

  • To test, rotate the accelerometer so that the each axes point towards the earth and check that the measured values are either 1 or -1 (corresponds to acceleration due to gravity).
  • Shake the accelerometer to make sure the readings increase (sign indicates direction of axis, we’re most interested in the magnitude of the reading).

Secure Electrical Connections & Install It!

Once everything is working correctly, let’s make sure the impact force monitor can actually withstand impact!

  • Use heat shrink tube and/or coat the electrical connections for the accelerometer and LED in epoxy.
  • For super durable, permanent installations, consider coating the whole shebang in epoxy: the Pi Zero, the LED, and the accelerometer (but NOT the Pi cable connectors or the SD card).
    • Warning! You can still access the Pi and do all the computer stuff, but a full coat of epoxy will prevent the use of the GPIO pins for future projects. Alternatively, you can make or purchase a custom case for the Pi Zero, although check for durability.

Secure to a helmet, your person, or a mode of transportation like your skateboard, bicycle, or cat*!

Fully test that the Pi is securely fastened or the GPIO pins may become loose causing the program to crash.

*Note: I originally meant to type “car”, but figured an impact force monitor for a cat might also yield some interesting data (with kitty’s consent, of course).

Embedding the Circuit in a Helmet

Theres a few methods of embedding the circuit into a helmet. Here’s my approach to a helmet installation:

  • If you have not already, connect battery to Pi (with battery off). Secure the accelerometer to the back of the Pi with nonconductive insulation in between (like bubble wrap or thin packing foam).

  • Measure the dimensions of the Pi Zero, accelerometer, LED, and battery connector combination. Add 10% on either side.

  • Draw a cutout for the project on one side of the helmet, with the battery connector facing towards the top of the helmet. Cut out the padding in the helmet leaving a few millimeters (~ 1/8 in.).

  • Place the sensor, Pi, and LED in the cutout. Cut pieces of the excess helmet padding or use packaging foam to insulate, protect, and hold the electronics in place.

  • Measure the battery’s dimensions, add 10%, and follow the same cutout for the battery. Insert the battery into the pocket.

  • Repeat the insulation technique for the battery on the other side of the helmet.

  • Hold the helmet padding in place with tape (your head will keep it all in place when you are wearing it).

Deploy!

Power up the battery pack!

Now you can remotely log into the Pi through SSH or remote desktop and run the program via the terminal. Once the program is running, it starts recording data.

When you disconnect from your home WiFi, the SSH connection will break, but the program should still log data. Consider connecting the Pi to your smartphone hotspot WiFi, or just log back in and grab the data when you get home.

To access the data, remotely log into the Pi and read the text files. The current program will always append data to the existing files – if you want to delete data (like from testing), delete the text file (via the desktop or use the rm command in the terminal) or create a new file name in the program code (in User Parameters).

If the LED is on, restarting the program will turn it off.

Now go forth, have fun in life, and check on the data every so often if you happen to bump into something. Hopefully, it’s a small bump but at least you’ll know!

Adding More Features

Looking for improvements to the impact force monitor? It is outside the scope of the tutorial but try looking at the list below for ideas!

Do some analysis on your g-force data in Python!

The Pi Zero has Bluetooth and WiFi capabilities – write an App to send the accelerometer data to your smartphone! To get you started, here’s a tutorial for a Pi Twitter Monitor.

Add in other sensors, like a temperature sensor or a microphone*!

Happy Building!

*Note: To hear the whooshing sounds associated with your acceleration! 😀

Renewable Energy Technology: What is it and How to Use it!

Now more than ever, folks like you and me have to step up and take a stand to protect and preserve our environment (and, quite honestly, our species). One great way to do that is to incorporate renewable energy technology into projects that use electricity.

Even if the environmental aspect isn’t enough to get you on board, you should still use renewable energy tech because the simple truth is that eventually we will run out of coal and natural gas. Besides, renewable energy tech is cleaner and more cost-effective in the long term, AND it means that you rely less on external sources for electricity — super handy in case there’s a severe storm or a solar flare that temporarily knocks out your local power grid.

First of all, what is renewable energy technology? Basically, it encompasses any technology that generates (electrical) energy from effectively renewable sources. For example, from our perspective, the sun is essentially an infinite power source since it will be around long after we are gone and produces more energy than we could possibly hope to consume in our lifetime.

Coal and natural gas are NOT renewable because they are finite, meaning that there is only so much of it available for us to use. Once we’ve used it up, we’re pretty much sh** out of luck, as the saying goes.

Now that I’ve convinced you it’s a good idea to use renewable energy technology, what are your options and how do you actually go about incorporating them into your projects?? Well my friend, read on to find out! This is by no means an exhaustive list, but it does cover the most common and easily accessible types of renewable energy tech.

Also, this guide assumes you have a basic knowledge of electronics, so please ask if there is a term or concept that you’re unsure about and I’ll be happy to expand or provide you with more thorough resources. Happy building!!

Photovoltaic Panels (aka Solar Panels)

Solar panels are awesome! I put these first because they are one of the most common and, in my opinion, the easiest to incorporate into all kinds of different electronic projects.

How Solar Panels Work

Solar panels convert incident radiation (aka sunlight) into usable electrical energy via the photoelectric effect. Basically, a photon (light carrier particle) knocks into an electron and transfers its energy to the electron. By making solar panels out of special materials called semi-conductors, one with extra electrons and one with missing electrons (aka “holes”), the free electrons are attracted towards the positively charged material (and repelled by the negatively charged material). When an external load is connected across the solar panel, it creates an effective current.

Since the current output depends on the amount of sunlight hitting the panel, the highest power output occurs when the panel is in full, direct sunlight (and is free of dust and debris).

How to Use a Solar Panel

  1. First, solar panels output Direct Current (“DC”), which is ideal for computer/microcontroller projects. For household applications, you’ll need an inverter to convert the DC voltage into AC.
  2. Second, since we’ll only get energy generation during the day, we’ll (most likely) need to use a rechargeable battery to store the energy for use at all hours of the day and night. Calculate the battery capacity that you’ll need by multiplying the electric current consumption of your project by the number of hours it will be on and consuming power without any external charge. For example, if my project consumes 0.20 mA of current and I want it to be able to provide power all night (~ 12 hours), I’ll need a battery with a minimum capacity of: 0.20mA * 12 hours = 0.0024 Ah (2.4 mAh). Also, the battery voltage needs to be lower than the solar panel voltage for current to flow from the panel into the battery.
  3. Third, use a diode for trickle charging or a charge controller for higher power applications to protect the solar panel from backwards current flow.
  4. Finally, to choose the right sized panel, figure out how much power your project consumes (P = I * V) and pick a panel within a reasonable range. For example, the power consumption of a 5V, 0.50mA microcontroller is 0.0025 W, so a panel between 1W and ~ 7W would be more than sufficient. For larger power panels, be sure you have sufficient circuit protection to avoid blowing out your microcontroller or other electronic device(s).

For more information, here is a helpful guide.

Wind & Water Turbines

Wind and water turbines use pretty much the same mechanism to generate electrical energy, so I lumped ’em together. Of course, depending on what medium you’re using, you’ll want a different turbine size and shape.

How Turbines Work

Turbines are a mechanical device that rotate when an external fluid passes through the blades of the turbine, whether it’s water or wind (whoa what air is a fluid?! yes, yes it is :D). The turbine is connected to a drive shaft that spins an electric generator to produce electrical energy. 

How to Use Turbines

  1. Turbines are location dependent, so first you’ll want to figure out if it’s feasible: Do you have a stream, waterfall, or other moving water source nearby? Does the location of your project get steady wind?
  2. Turbines also output DC current, so you’ll need an inverter for household appliances.
  3. As with solar panels, you will likely want a rechargeable battery to store the power for use anytime during the day or night, regardless of weather conditions. Calculate your needed battery capacity using the same method as for solar panels.
  4. Use a diode for low-power projects and a charge controller for larger projects to protect the energy generator from backwards current flow.
  5. Determine the power output for your turbine by calculating the power consumption of your project in the same way that’s outlined for the solar panel.

There are tons of DIY wind turbine projects on the interwebs, including on Instructables! Find one that fits your project needs and try building your own!! 😀

Here’s a link to more information on wind turbines!

 

Thermoelectric Generator

Thermoelectric generators (“TEGs”) are super cool, but generally have a very low power output. That said, they are not weather dependent, don’t have any moving parts (aka are essentially maintenance free), and are very reliable. Thermoelectric generators can be super handy for small projects like charging smartphones or powering LEDs.

How Thermoelectric Generators Work

Ok, so these things are somewhat complicated — basically, special materials with high electrical conductivity and low thermal conductivity can generate an electric current when there is a temperature gradient (aka a temperature difference between one side and the other). So if you heat one side of the thermoelectric generator and cool the other side, a current will flow. It also works the other way around — if you apply a current to the generator leads, it will cause one side to heat up and the other side to cool down.

A super simple thermoelectric generator is shown in the photo above: a junction of two different metals (copper and iron) is heated to produce a current output between one end of the copper wire and the head of the nail. It’s too little current to be of much practical use, but it’s a great educational project!

How to Use Thermoelectric Generators

  1. Another DC electrical energy generator! Get at those inverters for AC power applications.
  2. Since these are super low power, I’d suggest a rechargeable battery just like with solar panels and turbines, and maybe even an amplifier like a transistor.
  3. Since these will likely stay low power, you shouldn’t need a diode to protect the TEG, but be sure to have adequate circuit protection for your particular electronic load.
  4. You can purchase TEGs that have specific power outputs, typically for camping purposes, or you can rig up your own using peltier junctions. Consider connecting a few in series to get a higher energy output.

Here’s a great overview on how TEGs work, check it out and be inspired!

 

Other Types of Renewable (& Clean) Energy Technology

Ok, so that’s it! We’ve covered 3 of the primary renewable (and clean) energy technologies! There are TONS more out there but they are either 1) super involved, 2) super expensive or 3) both. Here are two of the more common ones to give you a sense of what is possible in the wonderful world of renewable energy technology!

Geothermal Power Plants

Geothermal power plants use hot water deep in the earth to run a steam turbine. This requires ridiculously deep wells (~ 1km) to pump up the hot water, run it through a heat exchanger (or directly through a steam turbine if you’re lucky enough to be close to a water source that hot), and then push the water back into the earth or let it seep back down naturally.

These are super cool because there are no negative consequences of energy generation — no pollution is generated (only steam!), no water is lost, and it the water will heat back up naturally over time.

Nuclear Power Plants

These are a bit controversial due to the radioactive waste byproducts of nuclear fission, but nuclear power plants do in fact generate renewable, clean energy. As long as the waste is properly stored and there are safeguards in place to prevent meltdowns, nuclear power plants are relatively safe and well understood.

Currently, nuclear power plants use the process of fission, which involves breaking up an unstable atom (e.g. uranium) to get out high energy electromagnetic radiation (aka light). That energy is usually converted into heat and used to run a steam turbine.

Ideally, we’ll figure out fusion somewhere in the near future, which is the process of fusing two simple atoms together (usually two isotopes of hydrogen). Nuclear fusion generates electromagnetic energy and inert particles like helium. This is what stars do! Except they are much, much more efficient as they are insanely hot and high pressure.

Fusion does NOT produce any radioactive waste, so it would be a perfect solution to our energy crisis. Now to just figure out how to get a net positive energy output….

For more info on fusion, check out this awesome article by the folks at Industrial Quick Search Directory.

Go Forth & Build!

Now you know what renewable energy technology is and, generally speaking, how to incorporate it into your personal projects. It’s also a great way to charge your gadgets while out and about, make your projects portable, and have a backup power source in the event of a power outage.

Please feel free to ask any and all questions! My goal with this is to empower you to feel confident in using some sort of renewable energy tech in your everyday life, whether you purchase it or build your own.

Remember, it’s ok (and encouraged) to start small and simple! Use a solar panel to power a small motor, use a wind turbine on your bike helmet to power a bike light, or use a thermoelectric generator to light up some LEDs while camping!

If this tutorial inspires you, I’d love to see any projects you made, share ’em in the comments below!!

Make Custom (& Inexpensive) Circuit Blocks!

Create, build, and play with your very own LEGO-inspired circuit blocks! Explore the basics of electricity and circuits, discover how sensors work and use ’em to design your own experiments, and incorporate upcycled materials to improve on your materials-sourcing & MacGuyver-ing skills! That old gum wrapper? Make it into a resistor or a switch!

But seriously, this is a super fun (and inexpensive) project/toy/game to teach electronics to kids (and adults!) of all ages and experience levels. The total cost of this project is under $30 and it takes about 2 hours to design and build.

 

Ok.. so where do we start?

First we need a base, the circuit block itself. This design uses breadboards* as the circuit block bases. I chose mini color breadboards so that each color denotes a specific type of electronic component (see next section). These are super cheap, typically less than $1 per board. Follow my design or create your own!

For each breadboard/component, we also need at least two or more breadboard wires (or 22 or 24 stranded wire), so for 20 breadboards with a single component we need 40 or more breadboard wires.

*Breadboards are non-edible, inexpensive prototyping boards for electronics projects. See photo above for a quick illustration of how breadboards work, or check out this tutorial.

 

Gather Electronic Components!

If you happen to have an assortment of electronic components around, gather them up and go through them to find the most choice pieces — we want components with only two leads, like simple motors, fans, LEDs, resistors, capacitors, etc. Check out websites like SparkFun or Amazon and search for electronic components.

Hey, wait, where can I get this stuff for free??

Dig up that box of broken electronics in your garage and see what you can find inside the electronics!

The best sources for components are electronic toys that move and/or make noise, speakers, telephones, and other medium-sized electronics.You’ll need wire cutters and pliers to remove the pieces, be sure to keep the legs intact so they can easily connect to the breadboard.

Avoid smartphones, tablets and laptops since the circuit components are suuuuper small and difficult to attach to a breadboard (unless that’s what you’re going for, then extract away!). For safety reasons, avoid appliances (e.g. microwaves, televisions, refrigerators, etc.), and do not use capacitors that are larger than a child’s thumb.

 

Build the Circuit Blocks!

The breadboard assortment I got included red, blue, white, green and black, mini breadboards. I broke up the colors into the following categories and components:

 

Red boards (power devices): One 1 W solar panel, one 9V battery clip, one 2 AA battery box, and two coin cell cases.

 

 

 

Blue boards (simple active): one motor w/ propeller, six LEDs of different colors (three per board), and one transistor (the transistor is pretty tricky — I’d recommend replacing this with another motor).

 

 

 

Green boards (sensors): one photoresistor, one buzzer/piezoelectric sensor, one peltier junction, and one capacitive sensor (this didn’t end up working, so replace it with a pressure sensor or other cool, two-lead sensor).

 

 

 

White boards (simple passive): six resistors of varying values (three per board), two (small electrolytic) capacitors of different values, and one potentiometer.

 

 

 

 

Black boards (electromechanical): Two pushbutton switches of different sizes/types (one per board), two toggle switches (single board), and one cooling fan.

 

 

 

To build each circuit block:
Connect each component to the first rows of each breadboard (be sure they aren’t shorted — should be on either side of the breadboard), and hot glue the wires into place. Remember to label which side is positive and which side is negative! Another fun option is to make labels for each component.

 

Plug & Play!

You’re ready to start building circuits and teaching other people the basics of electronics! Start simple, then add in more components to explore their function and see how they affect your circuit.

Here’s an example progression exploring different ways to light up an LED:

1. Use a coin cell to light up an LED.

Exploration questions: Does orientation matter? Where do the wires need to connect to the breadboard?

2. Use the solar panel to light up an LED. Move the panel into the shade (or cover it with your hand), and see how the LED brightness changes.

Exploration questions: How does the brightness of the LED change when you cover the solar panel? Why does this happen?

3. Use a coin cell and potentiometer to adjust the brightness of an LED.

Exploration questions: What do you notice? Does it matter how we connect the potentiometer?

4. Use a coin cell and a photoresistor to adjust the brightness of an LED.

Exploration questions: What do you notice?. Does it matter how we connect the photoresistor? How could we use the photoresistor in an experiment?

Build your own sequences to teach folks about specific circuit components or sensors, or use them as a fun & educational free-time project!

IoT Pet Monitor!

Keep an eye (er, ear) on your beloved bbies while you are away! This project monitors the volume of sound in your home and if your pet gets too anxious and starts barking or making other loud noises, soothe their sad lil’ soul by turning on music or your own (pre-recorded) voice!

This tutorial will show how to build this project using a Raspberry Pi computer to monitor sound in your home (via the Cloud) to see if and when your pet is upset.

Along with the Pi (and speakers), we’ll use the SparkFun MEMS microphone breakout board to measure volume levels and trigger the audio player. Data is uploaded to the CloudMQTT service using the MQTT communication protocol.

Total Read Time: 8 min.

Total Build Time: 60 min. (less if you are experienced)

Suggested Reading

To build this project, you’ll need a fully configured, WiFi-connected Raspberry Pi 3 computer with ​Raspbian OS. It’s also helpful to know some ​Python programming as well as the following things: (1) how to use and control the Raspberry Pi GPIO pins; (2) MQTT communication; and (3) analog sensors. If any of this is unfamiliar, or if you’re just curious (be curious!), check out the tutorials below!

Raspberry Pi 3

  1. ​Raspberry Pi 3 Starter Kit Hookup Guide
  2. ​Raspberry Pi GPIO
  3. ​SPI Communication with the Raspberry Pi

MQTT Communication Protocol

MQTT (Message Query Telemetry Transport) is a popular IoT communication protocol. We’ll use the Paho Client Python library and an MQTT service called ​CloudMQTT. Here’s more about MQTT and how to use it:

  1. Exploring Communication Protocols for IoT
  2. Getting Started with CloudMQTT
  3. ​Overview of Eclipse Paho MQTT Python client library

MEMS Microphone Breakout Board

The MEMS microphone is an analog microphone, so we’ll need an Analog-to-Digital converter (“ADC”) to read in the analog signal with the Raspberry Pi digital GPIO pins.

  1. Getting started with the SparkFun MEMS Microphone Breakout Board
  2. ​MEMS Microphone Datasheet
  3. MCP3002 ADC Datasheet

 

Materials

Raspberry Pi 3 Model B

We’ll also need the following peripherals: ​Raspberry Pi 3 Case​SD Card (minimum 8 GB); ​Raspberry Pi 3 GPIO cable; ​MicroUSB power cable; HDMI cable and ​HDMI-compatible monitor; USB keyboard; USB mouse; speakers with 1/8″ headphone port.

​SparkFun MEMS Mic Breakout Board

​MCP3002 (Analog-to-Digital Converter)

​Breadboard & ​M-to-M Breadboard Jumper Wires

 

Configure the Raspberry Pi

Step 1: Check & Install Updates
Checking for and installing updates is always a good way to start. Run the following commands in the terminal window:

    sudo apt-get update
    sudo apt-get upgrade
    sudo reboot

Step 2: Set up SPI Interface for MEMS Microphone + MCP3002

To use the SPI (Serial Port Interface) to read in the MEMS Microphone via the MCP3002, we’ll need the Python Dev Package:

    sudo apt-get install python-dev

We’ll also need the SPI Interface (may want to create a subfolder to save this in):

    git clone git://github.com/doceme/py-spidev
    sudo python setup.py install

Here’s the SPI-Dev Documentation if you run into any issues.

Step 3: Playing Sounds with OMXPlayer

The OMXPlayer is an audio and video player pre-loaded on Raspbian OS. It works with most sound file types, including: .wav, .mp3, and .m4a. This is what we’ll use to play back sounds when Fido gets too loud. The Python library to control the OMXPlayer is included in Raspbian (woo!).

To test the OMXPlayer from the terminal, type the following:

    omxplayer /home/.../SongFilePath/SongFileName.mp3

If that doesn’t work, try forcing it over the local audio-out device:

    omxplayer -o local /home/.../SongFilePath/SongFileName.mp3

Step 4: Configure CloudMQTT Server

Now we set up an MQTT server! To do this using CloudMQTT, do the following:

  1. Set up a CloudMQTT account (the “Cute Cat” plan is free).
  2. Create a new MyCloud instance.
  3. In the Console, create a new ACL rule.
  4. You can monitor published messages in the “Websocket” UI.

 

Finally, install the MQTT Paho Client Python library:

    pip install paho-mqtt


Build it! Hardware

Here’s a pinout for the Raspberry Pi 3:

1. Insert MCP3002 pins into breadboard. Here’s a pinout for this board:

The MCP3002 uses 4 SPI pins for communication: Serial Clock (“SCL”), Master Input Slave Output (“MISO”), Master Output Slave Input (“MOSI”), and Chip Select (“CS”). These pins correspond to Raspberry Pi GPIO pin 11 (SCLK), GPIO pin 9 (MISO), GPIO Pin 10 (MOSI), and GPIO Pin 8 (CE0).

Make the following connections with MCP3002 pins:

  • ​Connect Pin 1 to Raspberry Pi GPIO Pin 8 (CE0)
  • Connect Pin 2 to the analog output of the MEMS Microphone breakout board
  • Connect Pin 4 to GND
  • Connect Pin 5 to Raspberry Pi GPIO Pin 10 (MOSI)
  • Connect Pin 6 to Raspberry Pi GPIO pin 9 (MISO)
  • Connect Pin 7 to Raspberry Pi GPIO Pin 11 (SCLK)
  • Connect Pin 8 to Raspberry Pi 3.3V out

2. Solder wires to the MEMS Microphone breakout board. Connect to MCP3002 and Raspberry Pi.

  • ​Connect Vcc to Raspberry Pi 3.3V.
  • Connect GND to Raspberry Pi GND
  • Connect AUD to MCP3002 Pin 2

3. Plug in all the cables for the Raspberry Pi and turn everything on.

 

Build it! Software

Our goal with the Bark Back is twofold: trigger a playback sound when the dog barks, and send the data to a server where we can check it.

Here’s the ​open-source Python program for this project. Feel free to (and please do) adjust and modify the code

To get the program up and running, you need to fill in two things:

songList: Write in the file path and file name for each of the songs you want to play.

creds: Input your CloudMQTT information in this dictionary.

Step 1: Read in the SparkFun MEMS Microphone breakout board.

Read in the ADC value (between 0 and 1023) from the MEMS Microphone breakout board (via the MCP3002) using the SPI library and calculate the signal peak-to-peak amplitude.

Map the signal peak-to-peak amplitude to a Volume Unit. The current code maps the ADC range between 0 and 700 (based on quick experimentation) to a Volume Unit between 0 and 10. To adjust the sensitivity of the microphone, adjust the ADC input range.

For a thorough overview of the MEMS mic, ​check out this tutorial.

Step 2: Trigger audio player.

First we’ll need songs to play! You can quickly record sounds in GarageBand (or on your smartphone) and send ’em to the Raspberry Pi. In Python, use the subprocess library to call the omxplayer.

In the code, input the file path of the songs you want to play back in the *songList* variable (line 26). The current volume threshold is set to 7 in the main function.

Step 3: Send data to CloudMQTT Server

Use the ​Paho Client Python library to communicate with the CloudMQTT servers. To broadly summarize: Set up a Client server; define communication protocols; connect with our credentials (aka creds); and subscribe and publish our data. Most of this is done in the main function (lines 129 – 149, and lines 169 – 174).

To check on received data, go to the “Websocket UI” tab in the CloudMQTT console.

 

Test & Install & Enjoy!

Run the BarkBack.py program in Terminal or in the Python IDE (you can also use SSH to run the program after you’ve already left).

Check that you are getting volume levels in your Websocket UI tab.

Test the system by triggering the mic (clap, yell, bark, etc.) to be sure that the speakers play through all of the sounds.

Once everything is up and running, it’s recommended to solder the components to a PCB (Printed Circuit Board) if you intend to install the system for more than just a few days.

 

Project Extensions

1. Add in an RPi camera module to include video.
2. We’re already connected to the IoT, so why not throw in some more sensors! For example, you could monitor hazardous gases (perhaps methane?).
4. Prefer a reward over barking back? Create an automatic treat dispenser to reward your pet for being quiet for a few hours. Here’s a candy-dispensing tutorial for inspiration and to help get you started.
5. Share your findings and adaptations in the comments below!

Happy building!

IoT Industrial Scale!

finalscale2-v2

 

What does a baby elephant weigh?* How much impact force does a jump have?? How can you tell if a rain barrel is full without looking inside??? Answer all these questions and more by building your very own Internet of Things (“IoT”) industrial scale using the SparkFun OpenScale board!

This project is intended for folks with a lil’ bit of background using Arduino or other microcontrollers. But, whether this is your first or 137th project, check out the links in the Suggested Reading section below (and throughout the tutorial) or leave a comment if you have any questions!

Read time: ~ 15 min.

Build time: Approx. 2 – 3 hours

*To weigh a baby elephant, you might need to be a zookeeper or otherwise have an elephant friend.. but you could always weigh Fido and/or kitty!

For all you visual learners, check out a video of the project below:

 

Materials!


To follow along and build your own scale, all the parts used are listed below.

Electronics

To make the system wireless:

All these parts can be found in the wish list here.

Scale and Casing

  • Terminal blocks (5)
  • Three (3) M3 screws per load cell (total of 12)
  • One (1) project case (to protect the electronics)
  • One (1) base board, and one (1) top board (for the scale platform)
    • My base board was ~ 16″ x 16″ and my top board was ~ 12″ x 14″.
    • Both boards should be sturdy and not flex or dent.
  • Wood slats to frame the sides of the top board to hold it in place.
  • Four (4) feet for base

 

But wait! There’s some background reading..


First of all, how do we measure weight??
Strain gauges!

Also called load sensors, strain gauges measure electrical resistance changes in response (and proportional) to, well, strain! Strain is how much an object deforms under an applied force, or pressure (force per area). Check out this super awesome tutorial for more info on how strain gauges work.

Usually what you’ll find in a bathroom scale is a load cell, which combines four strain gauges in a wheatstone bridge. This project uses four disc compression load cells rated at 200 kg.

Here’s some additional background material to learn more about the components and tools used in this project:

  1. Serial Terminal Basics
  2. OpenScale Applications and Hookup Guide
  3. Getting Started with Load Cells
  4. Photon Development Guide

As usual, don’t forget to read the Datasheet for the Load Cells and any other components you with to use in your project.

Build the Electronics! Pt. 1


industrialscale-schematicv2

Connect the Load Cells!

Load cells have four signal wires:

  • Red: Excitation+ (E+) or VCC
  • Black: Excitation- (E-) or ground
  • White: Output+ (O+), Signal+ (S+)+ or Amplifier+ (A+)
  • Green (or blue): Output- (O-), Signal- (S-), or Amplifier (A-)

They also have bare (or yellow) grounding wires to block outside (electromagnetic) noise.

Connect all five load cell wires in parallel to the OpenScale terminal blocks with the corresponding labels. You might need to switch the green and white load cell wires – check this by adding weight to the load cells. If the weight is decreasing, switch the wire orientation.

The OpenScale terminal blocks are a bit cramped with four load cells, so I used the terminal blocks pictured above. If you have a case for the electronics, remember to put the connectors INSIDE the case before connecting them to the load cells (not speaking from experience or anything..).

 

Build the Electronics! Pt. 2


Connect the OpenScale to a data logger!

In addition to printing, reading, and gathering data from the Arduino serial monitor (see “Reading Load Cells!”), we can add a Photon microcontroller to connect to WiFi and upload the measurements to the Internet!

Connect the OpenScale “Serial Out” ground (“GND”) port to the Photon GND, and the OpenScale “TX” port to the Photon “RX” port. If your data logger needs power, connect the OpenScale 5V port to the data logger Vin port. That’s it!

 

Build the Base & Case!


1. Plan out, measure, and mark location of load cells.

Load cells should be at least 1″ in from the top platform board sides and installed equidistant and on the same plane (aka same height) with each other.

Each load cell needs three M3 type screws, which requires fairly precise measurements. I opted for a quick & easy solution: make a plastic stencil that marks the load cell outline and the location of the screw holes. The plastic I used was cut from a discarded strawberry container (yay, free and upcycled!).

2. Drill holes for load cell screws and attach load cells to base board.

3. Attach feet to base.

4. Secure the scale platform.

Place platform on top of the load cells. Attach wood slats to sides of base with wood glue and/or screws to secure the platform in place laterally, but not vertically. AKA, be sure that there is no resistance to the board pushing downward.

Add brackets on opposite sides for a more secure hold.

5. Place electronics into project box container (or tupperware) and drill holes for cables.

6. Admire your handiwork!

 

Connect the OpenScale!


One of the awesome features of the OpenScale program is that it outputs data to the Arduino IDE serial monitor (9600bps). All we need to do is plug in our OpenScale via USB, select the appropriate board (Arduino Uno) and port, and you can read the load cell data directly from the Arduino Serial Monitor. More info on how to do this here.

Enter ‘x’ to bring up the OpenScale settings menu. Entering ‘x’ again leaves the menu and the OpenScale will start printing data!

arduinoserialmonitor-fullmenu2_labeled

We also need to remove the serial trigger from the OpenScale. Do this by going to the menu, inputting ’t’, and turning the serial trigger to OFF.

You can change various other settings on the OpenScale using the serial monitor, including units (lbs/kg), print rate, decimal places, etc. You can adjust, or peruse, the entire OpenScale program by downloading it from GitHub!

Note: If you are connected to another microcontroller, the OpenScale does not send data when in the menu mode.

 

Tare & Calibrate the OpenScale


Tare!

We’ll need to tare the OpenScale each time it is powered up. To tare the scale, remove all weights from the scale and open the OpenScale settings menu. Input ‘1’ in the OpenScale menu, wait for it to finish taring, then exit the menu and check that the output is close to zero (+/- 5 lbs). If the reading is still off, taring again should fix the problem – if not, check that the load cell grounding wires are properly connected to ground.

Calibrate!

We also need to calibrate the OpenScale to get accurate measurements. It’s also recommended to re-calibrate the system every few weeks (or days) to avoid creep (slow change in reading over time).

To calibrate the scale:

  1. Remove all weights (except the platform).
  2. Open the OpenScale menu and select ‘2’ to open the calibration setting.
  3. Place a (known) weight on the scale and adjust the calibration factor using ‘+’ and ‘-’ until the scale reads out the calibration weight within a reasonable margin in error.*

Also, the load cell output varies with temperature (‘cause heat causes expansion), so we need to keep the system at a constant temperature (or use different calibration factors at different temperatures.

*My experimental uncertainty was about +/- 5 lbs.

 

Program the Photon!


Write a program for the Photon that will read in the serial output data from the OpenScale and push it to the IoT platform of your choice. Or you can use/modify my code 🙂

Here’s the GitHub repository for the IoT scale.

This program reads data from the OpenScale and pushes it to ThingSpeak (also prints it to the Photon serial monitor). ThingSpeak is super easy (and free!) to set up, the only downside is that it only allows data to be posted every 15s.

What you need to do to make the program work for your setup:

programcode-whattochange_labeled

  1. Include your WiFi SSID (network name) and your WiFi password in lines 53 & 54, and lines 69 & 70.
  2. Set up a ThingSpeak channel!  thingspeak-channelsetup
    1. Name the channel and write a brief description.
    2. Include at least one field name. If you want to push more data, like temperature or a timestamp, include those corresponding fields.
    3. Save the channel!
  3. Copy the “Channel ID” number and the “Write API Key” and input them into lines 84 & 85.thingspeak-apikeys_labeled

Read through the comments in the program code for more information on how the program works.

 

Test & Refine!


Prototype complete! Have your favorite human or animal stand (or awkwardly lay..) on the scale to check that it works as expected.

Check thoroughly to see if there is anything that needs to be fixed, secured, and/or improved. During my build process I noticed that a lot of the wood I was using to test would get dented by the load cells, resulting in inaccurate readings.

 

Lessons Learned & Next Steps!


My initial goal for this IoT scale was to gather data on the forces due to jumping (specifically in parkour). Alas, the OpenScale is intended for constant loads and the fastest print rate is 505 ms, which is too slow to get accurate readings on impact force.

Fortunately, we can still use the scale to gather general data and use this design as a foundation for future versions. Some quick and well-timed preliminary testing by a professional jumper (~165 lbs) resulted in the readings plotted below:

data-jumptest3

It shows a single jump, where the landing corresponds to the highest reading (~ 230 lbs), and the point just before that (~ 135 lbs) is when his feet were in the air. (The weight decrease + little blip after the the peak is when he was stepping off the scale.)

In addition to an updated program to print data faster, I’ll need waaay more data and a consistent, controlled procedure to determine any kind of reasonable relationship between impact force, jump height, and weight. Also, the top platform was a bit dented after these tests, so I’ll need a sturdier wood, or metal, scale platform.

Overall, this was a cool proof-of-concept and an informative preliminary test! Plus, there are tons of other practical uses for this simple Internet-connected scale!

 

Education Extension & Beyond!


Beyond being a great hands-on project for computer science, engineering, and electronics courses, this is a handy experimentation tool for physics classrooms! Use it to illustrate the difference between weight and mass, demonstrate how acceleration relates to force, or use the on-board temperature sensor to estimate the mathematical relationship between thermal expansion and load cell output.

Other Applications:

  • Use the system to measure the weight of a rain barrel and notify you when it is full.
  • Make a bathroom scale that keeps track of your weight (or your animal’s weight).
  • Monitor the weight of your Halloween candy to be sure that no one is sneaking some from under your nose.

Happy Building!

Hazardous Gas Monitor

Build a portable gas monitor to check for dangerous levels of hazardous gases in your home, community, or on the go and prevent your friends from lighting a cigarette during  a gasoline fight.*

This tutorial shows you how to build a web-connected “canary” monitor for three hazardous gases: Liquid Propane Gas (“LPG”), Methane (aka natural gas), and Carbon Monoxide (“CO”) . Using the Particle Photon microcontroller, the sensor readings are converted into parts-per-million (“PPM”) and uploaded to the data.sparkfun.com web service.

*Please note that this is solely a movie reference — gasoline fights should probably be avoided in real life.


Helpful Background Info!


1. How to set up the Particle Photon.

2. Pushing data to the data.sparkfun.com web server.

3. New to relays? Check out this a handy reference.

4. Here’s a helpful overview on the N-Channel MOSFET.

5. For powering the Photon, here’s a thorough guide on the Photon Battery Shield.

6. Highly recommended to peruse the datasheets for the three gas sensors.


Choosing a Battery!


The gas sensors used in this project require a fair amount of current, about 0.17 A each at 5V. To make the system portable, we’ll need a high capacity battery. One easy, and affordable, option is to use four (rechargeable) AA batteries in series. These batteries will last about 4 hours.

Another option is to use a lithium ion battery (“LIB”). LIBs have a higher capacity than AAs, but typically run at a lower voltage. If you go with this option, you may need to include a correction factor when you calculate the sensor value or boost the battery voltage with a transistor or other component.

The photo above shows a table with the approximate lifetime of a few different battery options.

If all of this sounds confusing, here’s a more thorough tutorial.


Materials!


Here’s a Wish List that includes all the necessary components for this project!

Microcontroller and Accessory Components

Particle Photon microcontroller

SparkFun Photon Battery Shield

– One 2000 mAh Polymer Lithium Ion Battery

Surface Mount DC Barrel Jack

Barrel jack to USB power supply cable

One (1) Lamp Switch

– Optional: Male-to-Female JST connector cable

Gas Sensor Circuit

One (1) Project Case

– One (1) 4 AA battery case

– Four (4) AA Rechargeable Batteries

One (1) Toggle Switch (SPST switch)

Piezo Buzzer

Three (3) Red LEDs

– Three (3) 10 kΩ resistors

One (1) PCB

22 Gauge stranded wire

– Optional: Electrical connectors (3-5)

LPG (MQ6) Gas Sensor

MQ6 LPG Gas Sensor

Gas Sensor Breakout Board

– One (1) 4.7 kΩ resistor

– One (1) 5V Voltage Regulator

Methane (MQ4) Gas Sensor

MQ4 Methane Gas Sensor

Gas Sensor Breakout Board

– One (1) 4.7 kΩ resistor

– One (1) 5V Voltage Regulator

Carbon Monoxide (MQ7) Gas Sensor

MQ7 CO Gas Sensor

Gas Sensor Breakout Board

– One (1) 4.7 kΩ resistor

– One (1) 5V Voltage Regulator

– One (1) 5V SPDT Relay

– One (1) N-Channel MOSFET

– One (1) 10 kΩ potentiometer

– One (1) 10 kΩ resistor


Tools!


– Soldering Iron

– Wire cutters/strippers

– Drill

– Screwdriver

– Epoxy (or hot glue)


Build it! Electronics


1. Solder gas sensor breakout boards to gas sensors. Orientation doesn’t matter, just be sure that the silkscreen (aka labels) are facing down so that you can read them (had to learn that one the hard way..). Solder wires to the gas sensor breakout board.

2. Solder three voltage regulators to the PCB board. For each regulator, connect positive battery output to the regulator input, and connect middle voltage regulator pin to ground.

3. Connect the LPG (MQ6) and Methane (MQ4) sensors.

For each sensor:

  1. Connect H1 and A1 to the output of one of the voltage regulators (recommended to use an electrical connector).
  2. Connect GND to ground.
  3. Connect B1 to Photon analog pin (LPG goes to A0, Methane to A1)
  4. Connect a 4.7 kΩ resistor from B1 to ground.

4. Connect the CO (MQ7) gas sensor.

*Aside: The MQ7 sensor requires cycling the heater voltage (H1) between 1.5V (for 90s) and 5V (for 60s). One way to do this is to use a relay triggered by the Photon (with the aid of a MOSFET and potentiometer) — when the relay is not powered, the voltage across H1 is 5V, and when the relay is powered the voltage across H1 is ~ 1.5V.

  1. Connect GND to ground.
  2. Connect B1 to Photon analog pin (A2). Connect 4.7 kΩ resistor from B1 to ground.
  3. Connect A1 to third voltage regulator output (5V source).
  4. Connect Photon 3.3V pin to positive relay input.
  5. Connect Photon Digital Pin D7 to left MOSFET pin, and a 10 kΩ resistor to ground.
  6. Connect middle MOSFET pin to relay ground pin. Connect right MOSFET pin to ground.
  7. Connect relay Normally Open (“NO”) pin to H1, and the Normally Closed (“NC”) pin to middle potentiometer pin.
  8. Connect right potentiometer pin to ground, and left pin to H1.
  9. Adjust potentiometer resistance until it changes the relay output to ~ 1.5V when the relay receives power.

5. Connect an LED and 10 kΩ resistor to each of the Photon digital pins D0, D1, and D2. Connect buzzer to Photon digital pin D4.


6. Connect toggle switch between battery pack and PCB board power. Recommended to include an electrical connector for the battery pack to make it easier to switch out batteries.


7. Connect lamp switch between LIB and Photon battery shield — recommended to use an extra JST cable for this to keep the LIB battery cable in tact (and make it easier to install the lamp switch).

8. Label wires!


Build a Case!


1. Drill hole for toggle switch on case lid.

2. Drill 3 holes in the case lid for the LED lights to shine through, and 3 holes for the gas sensors to have air contact. Adhere components on the inside of the lid.

3. Drill hole in the side of the case for barrel jack USB cord to connect to the Photon Battery Shield.

4. Drill two small holes on the side of the case for the lamp switch cable. Adhere lamp switch to side of case.

5. Label the LEDs with its corresponding gas sensor on the outside of the case.

6. Check electrical connections and, if everything is good to go, coat electrical connections in epoxy or hot glue.


Calculate Gas Sensor PPM!


Each of the gas sensors outputs an analog value from 0 to 4095. To convert this value into voltage, use the following equation:

Sensor Voltage = AnalogReading * 3.3V / 4095

Once you have the sensor voltage, you can convert that into a parts per million (“PPM”) reading using the sensitivity calibration curve on page 5 of the gas sensor datasheets. To do this, recreate the sensitivity curve by picking data points from the graph or using a graphical analysis software like Engauge Digitizer .

Plot PPM on the y-axis and V_RL on the x-axis, where V_RL is the sensor voltage. There is a lot of room for error with this method, but it will give us enough accuracy to identify dangerous levels of hazardous gases. Estimated error bars are around 20 PPM for the LPG and Methane sensors, and about 5 PPM for the CO sensor.

Next, find an approximate equation for the PPM vs. V_RL curve. I used an exponential fit (e.g. y = e^x) and got the following equations:

LPG sensor: PPM = 26.572*e^(1.2894*V_RL)

Methane sensor: PPM = 10.938*e(1.7742*V_RL)

CO sensor: PPM = 3.027*e^(1.0698*V_RL)


Program it!


First, set up a data stream on the [data.sparkfun.com service](http://data.sparkfun.com). Next, write a program to read in the analog value of each gas sensor, convert it to PPM, and check it against known safe thresholds. Based on OSHA safety standards, the thresholds for the three gases are as follows:

  • LPG: 1,000 PPM
  • Methane: 1,000 PPM
  • CO: 50 PPM

If you want to get up and running quickly, or are new to programming, feel free to use my code! Use it as-is or modify to suit your particular needs.

Here’s the GitHub page!

Here’s the raw program code.

Change the following in the code:

1. Copy and paste your data stream public key to the array called `publicKey[]`.

`const char publicKey[] = “INSERT_PUBLIC_KEY_HERE”;`

2.Copy and paste your data stream private key to the array called `privateKey[]`.

const char privateKey[] = “INSERT_PRIVATE_KEY_HERE”;

To monitor the Photon output, use the Particle driver downloaded as described in the [“Connecting Your Device” Photon tutorial](https://docs.particle.io/guide/getting-started/connect/photon/). Once this is installed, in the command prompt, type `particle serial monitor`. This is super helpful for debugging and checking that the Photon is posting data to the web.


Be a Citizen Scientist!


Now we get to test and employ our gas monitor! Turn the batteries for the gas sensors on using the toggle switch, wait about 3 – 5 minutes, then turn the Photon on with the lamp switch (the gas sensor heater coils take some time to heat up). Check that the Photon is connected to WiFi (on-board LED will slowly pulse light blue) and is uploading data to the server. Also check that the gas sensor readings increase when in proximity to hazardous gases — one easy, and safe, way is to hold a lighter and/or a match close to the sensors.

Once up and running, use the sensor to monitor for dangerous gas leaks around your home, school, workplace, neighborhood, etc. You can install the sensor in one location permanently, or use it to check gas levels in different locations (e.g. SoCal..).

Educator Extension!

This project is a perfect excuse for a hands-on chemistry lesson! Use the monitor to learn the fundamentals of various gases — what kinds of gases are in our environment, how are different gases produced, and what makes some of them hazardous or dangerous.

Study the local environment and use a lil’ math to record and plot LPG, Methane, and CO in specific locations over time to see how the levels change. Use the data to help determine what causes changes in the gas levels and where/when gas concentrations are the highest.

 


More to Explore!


Monitor hazardous gas concentrations around your neighborhood or city and use the results to identify problem areas and improve public safety.

Use Bluetooth, or your smartphone WiFi, to connect to the Photon and upload data to the web wherever you are!

Include other sensors, gaseous or otherwise , to create a more comprehensive environmental monitoring system.

Faraday Cage Phone Pouch

This Faraday Cage phone pouch blocks all radio signals coming in or out of your cellphone. Material costs are about $10, it takes ~ 30 minutes to build, and it can fit in your pocket!

The purpose of this pouch is to prevent access to your phone and its data (e.g. location) if and when you so choose. Before placing in the pouch, be sure to put your phone in airplane mode as the phone will drain its battery trying to find a signal.

Materials

  • Conductive fabric
    Sized to fit your phone + a top flap. For an iPhone w/ a (giant) case, I needed about 7.5″ x 3.5″.
  • Thread (regular, any color)
  • Button (any type)
    Alternatively, you can use velcro, a safety pin, or any other means to hold down the top flap.

Tools

  • Scissors
  • Ruler
  • Needle or Sewing Machine (preferred)
  • Safety pins (optional but helpful)

Build it! Pt. 1

  1. Measure the width, height, and depth of your phone (+ case, if you have one).
  2. Add 1″ to your phone width measurement and 2″ to your phone height measurement. Cut conductive fabric into a rectangle of that size.
    For example, the iPhone 5 is 4.87″ tall, 2.31″ wide and 0.30″ thick. Thus, you want a rectangle that is at least 6.5″ tall and 3.5″ wide.To double check your measurements, mark where you plan to cut the conductive fabric w/ a pen or pencil. then wrap the fabric around your phone. Be sure that you can fold down the top of the conductive fabric.
    Helpful tip: It’s always better to leave extra room. Measure twice, cut once, and so forth.
  3. Place phone on one side of the conductive fabric and fold the fabric over the phone. Safety pin sides together.Leave an inch or two above the phone so the top can be folded over like an envelope.

Build it! Pt. 2

  1. fw4y1vmi5p7kgsn-largeSew bottom + sides of conductive fabric together using small hand stitches or a sewing machine.
  2. Turn pouch inside-out to hide stitching.
  3. Place phone inside pouch, fold top down and mark where the button will go.
  4. Sew button on & cut a small slit in the top flap to attach.Remove excess fabric as necessary, but be sure that the conductive fabric completely encases the phone when the top flap is folded down.

img_0260

Done!

Place phone inside the Faraday Cage pouch whenever you want to cut off all radio signals coming in and out of your phone.

For another awesome version of the same concept, check out my friend’s scarf project here.

Curious as to how this works? Awesome! In super simple terms, a Faraday Cage “traps” radio waves in the wires that make up the cage. In this design, the conductive fabric threads are the metal wires that form the Faraday Cage. Due to the small mesh size (aka wires are super close together), this design will block any electromagnetic radiation with a wavelength larger than visible light. 🙂

Here’s a good overview on what a Faraday Cage is and how you can build a different version.

And here’s the Wikipedia blurb on Faraday Cages, an excellent source if you want to learn more!

Raspberry Pi Irrigation Controller

F7PVGADHZV3TCB3.LARGEGardening improves health and quality of life, connecting us to our local environment. Plus, you can eat organic fruits and veggies at very little cost. Alas, remembering to water can sometimes take a backseat to our busy lives. Fortunately, home automation is easier than ever with inexpensive and accessible microcontrollers like the Raspberry Pi 2 Model B and Arduino.

This tutorial details the construction process for a remotely controlled solenoid irrigation valve. In other words, a home computer controls the water flow of an outdoor hose spigot, or bib. The materials cost is about $30-40, excluding the Raspberry Pi (RPi). Cheaper parts can be found with patience and creativity.

The design is intended as a simple introduction to building a complete, personalized home irrigation system. It is also intended to encourage simple DIY solutions to everyday problems. Make modifications and upgrades to suit your needs, resources, and skill level. To conserve water, include drip irrigation and a soil moisture sensor.

Note: This project involves high voltage which requires extreme caution. Always check power connections before touching exposed wires.

Materials

FA20S0WI0LCOO0B.LARGE

Raspberry Pi, GPIO Cable, GPIO cable adapter + breadboard

This tutorial assumes the RPi has all GPIO libraries. To install outdoors, the RPi also needs a WiFi adapter and to be accessible by SSH or other remote login.

Solenoid Irrigation Valve
This tutorial uses a 24 VAC solenoid for a 3/4″ hose spigot.
Some background: there are two main types of solenoids: AC or DC.

  • An AC solenoid valve turns water on when voltage is applied, and turns it off when the power is off. The drawback is that it uses AC voltage, requiring an adapter to convert the wall voltage, 120 VAC, into the 24 VAC voltage needed to trigger the valve. Outdoor Installation likely requires an extension cord.
  • A DC solenoid valve allows for a battery powered system. It can easily be modified to be wireless and powered by renewable energy using a medium solar panel (~10 W). However, most DC irrigation valves are latching solenoids and require switching the valve lead polarity to turn water on and off.

I chose an AC valve for the first prototype because I already had a few parts.. and adequate rechargeable batteries can be expensive.

— Solid State Relay
The Solid State Relay, or relay, is the intermediary switch between the RPi and the solenoid valve. This tutorial uses a Crouzet Model OAC5-315; its input is 3 – 8 VDC and its output is between 24 – 120 VAC at 1A.

N3904 Transistor

4.7 kOhm Resistor

PCB Board
Sized to fit the relay, GPIO pins, transistor and resistor.

AC Power Adapter (120 VAC to 24 VAC)
Use an extension cord and/or longer leads to install outdoors.

— 22-gauge stranded wire (insulated), min. 10 feet

— Waterproof container
I used a leftover project box wrapped with waterproof tape. Cheap/free containers are easy to find; Talenti ice cream containers are an example, and also happen to contain delicious ice cream. With small containers, be sure exposed AC connections are completely covered in epoxy to protect the RPi.

— Optional: Waterproof connectors, waterproofing tape/lots of duct tape

FQ7ILN7I0LCOO0E.LARGETools

Soldering iron, solder, solder sucker

Wire strippers

Epoxy
Check that it is safe for outdoor use. Marine-grade epoxy may be best for long-term outdoor installation.

— Screwdriver

— Optional (but highly recommended): Multimeter

— Depending on your system container, a drill might also be useful.

Build It!

FE74HWMI0LCOO0F.LARGEHardware Intro: Solenoid Setup

  1. Add wire leads to the AC power adapter (if there are none); use at least 3-4 ft of wire.
    This AC power adapter has screw-type connectors. Recommended to coat these in epoxy.
  2. Verify that the solenoid works by connecting the leads to the power adapter.
    The valve makes a “clicking” sound when it is turned on.
    For thorough testing, repeat with the valve connected to the hose spigot.
  3. F5HUWP0I0LCOO0H.LARGEOptional: Extend solenoid valve leads using the waterproof connectors.
    Twist wires together inside the connectors, check the connection (aka continuity), then epoxy the openings.


    Remember, never touch exposed wires when power is on. Always double-check power connections.

Hardware Pt. 1

F55BJ37I0PYY1SJ.LARGE

If the schematic makes sense, skip the next three hardware steps (Hardware Pts 1 – 3).

FH4GQX8I0LCOSVB.LARGEPay attention to the layout of the PCB pads and use them to make connections simpler and more direct. Plan where components are connected prior to soldering. It may be easier to solder components in a different order.
1. Solder the relay to the PCB board.
The labels on the relay tell you the function of each pin. Here’s the datasheet for further reference.
1.a. Solder a wire lead to each relay pin, leaving 6 in. or more for the AC leads. 

F788JF3I0PZ2MGQ.LARGE2. Solder the RPi GPIO pin 18, 3.3 VDC pin, and ground pin to PCB board pads.

3. Solder the transistor to the PCB board, keeping each of the legs electrically insulated.

4. Solder one end of the resistor to the middle transistor leg (base pin) and the other end to GPIO pin 18.
Any other available GPIO pin works as long as you change the code to correspond to your chosen pin.
For best results, use one 4.7 kOhm resistor and connect as shown in the photo to the left.

FP5I646I0PZ2ONK.LARGEHardware Pt. 2 

  1. Connect the RPi ground pin to transistor pin 1, or emitter pin.
    Connect from the flat side of the transistor with a wire, the PCB pads, or a combination. For stranded wire, it helps to twist the ends before pushing them through the PCB holes.
  2. Connect transistor pin 3, or collector pin, to the negative DC relay pin.
  3. Connect the RPi 3.3 VDC pin to the positive DC relay pin. 


Hardware Pt. 3

  1. FESTW3ZI0PZ38JX.LARGEConnect one valve lead to one AC power source lead.
    Twist wires together and coat in solder. AC current alternates directions, so either lead will work for both the valve and AC power source.FHUMWX2I0PZ38IE.LARGE
  2. Connect the remaining valve lead to one of the relay AC output pins.
  3. Connect the remaining AC power source lead to the other relay AC output pin.
  4. Check all electrical connections with a multimeter.
    If available, check continuity. Otherwise, plug in the AC power source and check that there is ~ 24 VAC across the relay AC pins.
    A friendly reminder: Never touch exposed AC connections when the power source is plugged in.
  5. Coat all exposed AC connections in epoxy, including the relay AC pins.
    For safety purposes and to adhere connections.

Software

The software program turns the valve on and off by applying a voltage across the DC terminals of the relay.

1. With that basic principle in mind, here’s a simple code to get you started:

#Import the necessary libraries
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM) 
#Setup pin 18 as an output
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT) 
#This function turns the valve on and off in 10 sec. intervals. 
def valve_OnOff(Pin):
    while True:
        GPIO.output(18, GPIO.HIGH)
        print("GPIO HIGH (on), valve should be off") 
        time.sleep(10) #waiting time in seconds
        GPIO.output(18, GPIO.LOW)
        print("GPIO LOW (off), valve should be on")
        time.sleep(10)
valve_OnOff(18)
GPIO.cleanup()

F6I6KS9I0PZ38QU.LARGE2. Run the code in the terminal window of the RPi using the following:

sudo python FileName.py

3. Run the program before connecting the AC power source.
Use a multimeter to check that the voltage across the DC relay pins fluctuates from ~ 0VDC to ~ 3.3 VDC in ten second intervals.

4. Plug in the AC power source and run the program again. Listen for the solenoid to click on and off.

Waterproofing

  1. Double and triple-check all your connections with a multimeter.
  2. FRLCNBBI0PYXZIF.LARGECoat remaining exposed connections in epoxy
    Give yourself a way to remove the RPi + GPIO cable from the rest of the circuit so the RPi can be used for future projects (if so desired).
  3. Place the RPi and PCB board components in a waterproof container.
    Find a way to seal the external power cables. The first prototype uses waterproof tape to cushion wires and seal the box. Drilling holes in the box and sealing with epoxy is another quick and easy option.. get creative!
  4. Optional: To organize loose wires, twist insulated wires around each other, use zip ties or innovate another method.

Test & Improve!

That’s it! Rewrite the program to water your garden as needed. The easiest way is to keep the program as a timer. Change the program to increase the watering time to suit your plant needs and the wait time to >12 hours (>43,200 s).

ValveFinalPhoto2

ValveFinalPhoto

This system was originally designed to be controlled by a RPi-powered soil moisture sensor. To combine the two projects, copy the valve function into the soil moisture sensor program. Update the valve function to turn on if the soil moisture reading is below a certain threshold. Follow the hardware setup as outlined in the soil moisture sensor tutorial. Connect components to the existing PCB board if there is enough space, otherwise get another PCB board for the soil moisture sensing circuit.

Now that you understand the fundamentals, customize and upgrade the system to suit your own needs! Possible extensions include monitoring and/or controlling the system with your phone, or using renewable energy technology for power (e.g. photovoltaics + battery).

Raspberry Pi Soil Moisture Sensor

Conserving freshwater is one of those seemingly constant struggles, especially with a human population exceeding seven billion. In the United States, between 80 – 90 % of freshwater is consumed by agriculture, making it the perfect industry to implement more efficient ways of using water! Installing a soil moisture sensor is one way to optimize irrigation systems and reduce water consumption. Soil moisture sensors measure the amount of water in the soil so that your plants get water only when needed.

The following tutorial is a simple capacitive soil moisture sensor that uses a co-planar capacitor from the Zero Characters Left blog. The sensing circuit can be constructed for less than $25.00 w/ little or no prior experience in hardware or software prototyping. Experiment with and modify the system to create a version that suits your own needs!

Also, you can power this entire system using a portable solar USB charger.. 🙂

Materials

IMG_4855

— Raspberry Pi Microcontroller

  • This tutorial is based on a fully set-up Raspberry Pi, including GPIO libraries + GPIO cable w/ breadboard connector.I also recommend setting it up for wireless + SSH

1 MegaOhm resistor

  • This resistance was the best for my system, but a different resistor value might work better for your own setup. Experiment w/ different value resistors and see what happens!

— Co-Planar Capacitor (here)

— Solid core or stranded 22-gauge wire

  • Recommended to get stranded wire b/c conducts better & is less likely to break.

— Breadboard, breadboard wires + GPIO breadboard converter

  • This is the bare minimum needed to built the system. I recommend that you use better/more permanent connections once you have tested the system and made sure that it all works as expected.

Tools

IMG_4854

— Soldering iron, solder & solder-sucker (or solder wick)

  • A soldering iron is (almost) essential for this project, especially for attaching wire leads to the co-planar capacitor. You can purchase a soldering iron, solder and solder wick (removes solder) for ~ $20-30, or find a local makerspace/hackerspace that will let you come in and use an on-site soldering iron.

— Wire Strippers
— Epoxy
— Optional (but highly recommended): Multimeter (for testing and debugging!)

Operational Principles

  1. Soil is made up of four main components: organic matter, sand, silt, and clay. Between these are air gaps that can be filled with water. Here’s a diagram of different soil water contents:soilsaturation
  2. Water conducts electricity better than air. This information allows for tons of different types of soil moisture sensors. This design uses a capacitive sensor: the capacitance of the sensor changes based on the amount of water in the soil.

Sensor & Circuit Design

An RC circuit provides a quick & simple way to measure changes in the sensor capacitance due to changes in soil water content.
A little bit of jargon: “RC” stands for Resistor Capacitor. An RC circuit generates a time-varying current depending on the initial voltage, the initial current, and the circuit resistance and circuit capacitance. AKA: the output of the RC circuit depends on how much power you put into it and on the resistors and capacitors in the circuit.. which makes sense as that’s all there is in the circuit!RN_TimeConstant
Every RC circuit has an associated time constant, which is the time it takes the capacitor to reach ~ 63% of its maximum charge.  The time constant equals the total circuit resistance times the circuit capacitance:  τ = R * C
The graph on the right shows how the voltage across the capacitor changes over time.

The time constant is used to measure changes in the sensor capacitance. As the capacitance changes, so does the time constant. The equation above tells us that the time constant is directly proportional to capacitance, i.e. the time constant increases as the capacitance increases, and vice versa.

In this system, the co-planar capacitor is the soil moisture sensor (or SMS). Theoretically, when the sensor is in air or dry soil, the time constant is small b/c the capacitance is low. In water or saturated/wet soil, the time constant is larger b/c the capacitance is higher.

Here’s the circuit schematic:

SMS_SchematicV2

If you want to boost or lower the signal, change the value of the resistor to increase/decrease the magnitude of the sensor output.An Odd Observation: When the sensor was in dryish/damp soil and not registering, touching the resistor leads caused the sensor to output a reasonable signal. It also was sensitive to changes in light. These phenomena could be due to finicky connections & exposed wires; RC circuits tend to be sensitive to changes.

Build It!

Hardware:

  1. IMG_4838Solder wire leads onto the soil moisture sensor pads. Test connection w/ multimeter. If the sensor is electrically connected, coat in epoxy & let dry before continuing.
    If you’re using stranded wire + a breadboard, you’ll need to find a way to connect the stranded wire to the breadboard (b/c trying to shove it into the breadboard holes will make you want to pull your hair out). I stripped two breadboard wires and soldered them to the sensor leads. My connections were stil a bit finicky. Try different methods and see what works best. Use available materials and keep it simple!
    For the remaining hardware steps, reference the schematic and the picture below.IMG_4835
  2. Connect the RPi GPIO pins to the breadboard. Connect the 3.3 V output pin to the “+” column along the side of the breadboard.
  3. Connect the GPIO ground pin to the “-” column.
  4. Connect one resistor end to the 3.3 V output (any of the holes in the “+” column). Connect the other end to any of the breadboard rows. Orientation of the resistor leads doesn’t matter.
  5. Connect GPIO pin 14 to the same breadboard row as the resistor. You can use a different GPIO pin, but remember to change it in the software program.
  6. Connect one of the soil moisture sensor leads to the same breadboard row as the resistor + probe. Connect the other lead to ground (any of the holes along the “-” column). It doesn’t matter which lead goes where.
    Here’s a photo of the breadboard setup (3.3 V connection is hidden by GPIO cable):
    IMG_4862

    Software:

  7. Write a code to measure the capacitance of the sensor! Use the fact that the time constant changes depending on the medium in which the sensor is installed (capacitance is much larger in water than in air).
    Or you can just use mine 🙂
    Keep in mind that is a basic program and doesn’t include a GUI. All commands are run on the Pi’s terminal window (LXTerminal). The program prints the raw time constant, which is correlated to soil water content, a time stamp. If the reading is too low, the program also prints a reminder to water the plants. It also stores the raw data in a text file. To end the program, use “Ctrl + Z” or “Ctrl + C”.
    Modify and improve the program based on your own skills/needs. Remember to change the watering threshold based on your own experimental discoveries!
  8. Test the code and determine your ideal threshold.
    a) Test the sensor in water and air first; this provides the upper and lower bounds on the sensor output. If you find that the sensor is not reading in either of these mediums, change the value of the resistor until you get a reasonable signal. Be sure to record the reading for at least 5 – 10 minutes. It is helpful to plot the results in a program like Excel or R.
    b) Place the sensor in a cup of dry soil. Add a small amount of water and measure changes in sensor output over time (wait at least 5 – 10 minutes).
    c) If you are not getting a reading in either medium, try checking the electrical connections on the sensor.
  9. Fix the program as necessary.
    Your signal will likely be different than mine due to minor differences in your sensor and general setup. Use your findings from 8.a) & b) to find an approximate value at which your soil is too dry.
  10. Run the program & use it to maintain consistent watering of your beloved plants! 😀

Optional extension of the project: Making it survive outdoors!

IMG_1201Coat everything (except the sensor) in epoxy! .. Ok, so maybe not. Although, honestly it might work if you’re careful. Otherwise, you’ll want to scrap the breadboard for a PCB board + more 22-gauge wire. Molex connectors or something similar are a handy feature for the sensor.

Build process:

  • Solder the resistor & the sensor leads to the PCB board.
    • Your PCB may have copper lines connecting various pads; use this pattern on the PCB board to your advantage!
    • If your PCB board does not have any pads connected, an easy way to connect components is to run wires along the bottom.
  • Test the system w/ a multimeter or by running the code to be sure that it works as expected.
  • NOW coat it all in epoxy!
  • (Gently) shove the sensor circuit + RPI system into a waterproof container. My mom collects Talenti ice cream containers and they are super awesome for projects like this. Plus it’s a great excuse to eat a container of ice cream 🙂

If you run into any problems or you’re struggling with a particular step, please leave a comment & we can troubleshoot together! And we can help save the world by reducing our personal water consumption, yay!