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! 😀

Make a Minecraft Gesture Controller!

Move your body to play Minecraft! What!! Yes. Check the video for a demo 🙂

This tutorial will show you how to make your very own gesture game controller for Minecraft (or your other fav. computer game). Move your hand(s) to walk/run/jump, look around, and attack* all the things!

Let’s get started! Grab yourself a Circuit Playground Expresssnag my program code, and get shakin’ to play Minecraft in (srsly) the most fun way ever! 😀

Read time: 20 min

Build Time: ~ 2 hours

Cost: ~$30

*It is a biiiiit tricky to attack moving things (like monsters), so be careful in survival mode! Or use this to challenge your skills 🙂

Materials

Tools

  • Sewing Needle
  • Scissors
  • and a lil’ patience.. 🙂

 

Build the Glove Controller!

You can make the gesture controller without the glove, but the glove controller makes it easier to play, keeps the CPX in the same orientation (very important), and means you can use your fingers as added controls!

1. Cut rectangles of conductive fabric for the finger pads (~ 0.5 in. x 1 in.).

2. Use regular thread to sew the conductive fabric pads onto each of the glove fingers.

Suggested to use a highlighter or other pen to avoid sewing the two sides of the glove together (learn from my mistakes bbies).

3. Attach CPX to the glove with velcro squares.

4. Use an alligator clip or insulated wire to connect the CPX ground (“GND”) to the thumb pad.

5. Stitch conductive thread from the CPX capacitive touch pads (A1, A2, A3 & A4) to each of the four fingers.

6. If you have a multimeter, check continuity between the CPX pins and the conductive thread pads.

Plan out your controller!

 

First! What do we need to do to control Minecraft (or another awesome game)?

This is a super helpful & fun lesson in Design Thinking, but you can skip this if you want to just use my controls. You can always come back here later if you want to make changes later 😀

1. Determine (crucial) game controls.

Note: Start simple! Figure out the most important controls for the game and start there. You can always add more later.

Here are the controls that I wanted to use while playing Minecraft.. in creative mode 🙂 (you can use the same ones or customize your own controller!):

Movement:

  • Walk forward: W key
  • Run: Ctrl + W
  • Jump: Space bar
  • Look Left & Right: Mouse rotate
  • Walk backward: S key

Actions:

  • Attack: Mouse Left Click
  • Place Block/Push/Open: Mouse Right Click
  • Inventory: E key
  • Escape: ESC key

2. Decide how you want to use gestures and/or the finger pads to trigger these controls. Recommended to sketch out your plan.

Here is my design thought process:

I’ve always wanted to feel like I was actually *in* a game, so I went the “cheap VR” route and used gestures to control basic movements. For walking, I went the “let’s move my arms like I’m walking” route, which easily transitioned into running and jumping by increasing the speed of motion.

To make it easy to place a block or exchange items, I decided to use an “awkward handshake” motion.

Turning was a bit of a challenge, but my goal was to be able to look around by moving my hands in the direction I wanted to look.

Attack became the pointer finger pad, inventory the middle finger pad (which I ended up removing), Escape the ring finger pad, and the pinky finger pad to let me to walk backwards.

Again, you can keep these same controls or design your own 😀

Let’s get programming: Set up the CPX!

1. If you’re using Windows, download the Adafruit Windows Drivers here.

2. Download & save the latest CPX Circuit Python UF2 file.

3. Plug in the CPX with a USB cable (make sure it has data transfer capabilities).

4. Double-click the reset button on the CPX.

The LEDs should turn green. If they are red, it means something is wrong with data transfer to the CPX — check the USB cable, try another USB port on your computer, or try the trusty “unplug and plug back in” method.

5. On your computer, you will see a new disk drive called “CPLAYBOOT”.

6. Drag the CPX Circuit Python UF2 file onto the disk drive.

7. The “CPLAYBOOT” drive will disappear and be replaced with “CIRCUITPY”.

 

Add all the libraries!

Libraries let us access all sorts of special functions for the CPX without having to do a ton of programming.. hooray for open-source! This install will download most of the standard Circuit Python libraries* so peruse them at your leisure to learn about more cool things you can do!

1. Download and save the Adafruit Circuit Python Library Bundle Release from here.

2. Unzip the folder, open the first folder, and copy the “lib” folder onto the “CIRCUITPY” drive.

*It is unlikely that you’ll run out of space since the CPX comes with at least 2MB of Flash storage. But, if you do end up needing more space, you can revisit the libraries and remove the ones you don’t need. If you mess ’em up, just copy and paste the lib folder again.

 

Writing the Controller Code

The CPX has an on-board compiler, which means you can program it in (pretty much) any language you want! I opted for MicroPython, a version of Python for microcontrollers, ’cause Python is awesome.

Read this step if you want to understand how the program works (definitely suggested) or if you want to modify the code.

Here’s the GitHub repository that has the full code.Download it, drag it to your CPX, and rename the file “Code.py” (here’s the raw code if you want to just copy & paste).

1. To do the things I mentioned in the last step in MicroPython, we need the following libraries:

  • LIS3DH accelerometer

    • This allows us to use motion to trigger various things.
  • Human Interface Device (“HID”) keyboard

    • This library allows us to control the keyboard!
  • HID mouse

    • This library means we can control the mouse!
  • CPX capacitive touch
    • This library lets us use the capacitive touch feature on the CPX, hooray!
  • A couple of other libraries to make our lives easier: timebusio, and board.

2. Configure and initialize the libraries.

Assign variables for the keyboard, mouse, and accelerometer objects. Select a range for the accelerometer.

3. Write short functions for each of the controls.

The motion controls can be tricky. Do some initial testing with the accelerometer by printing the values in a serial monitor (in the source code, go to the __main__ function and uncomment the two debugging lines). This will help you to determine thresholds for walking, running and jumping, looking left and right, and placing objects.

The touch pad triggers are much easier as you are only looking for a capacitive trigger (True/False).

Remember to release all of the keyboard and mouse keys at the end of each function!

Debugging: Seeing what’s up the CPX program

If you’re familiar with Arduino, you’re probably familiar with the Serial Monitor. The CPX has the same feature with a slightly different access point depending on what program you are using.

If you are using Mu it’s super easy: the serial console is built in and will automatically detect your board, yay!.

If you are using Idle or another program, follow these steps:

1. Download PuTTY* here.

2. Go to Windows Device Manager and check the serial port number for the CPX (e.g. COM18) — see Photo below.

If there are multiple serial ports listed, unplug the CPX and plug it back in to see which one disappears then reappears.

3. Open PuTTY and select “Serial”.

4. Enter the serial port number (e.g. COM18) under “Serial line” and the baud rate of 115200 under “Speed”.

5. Click Connect! 

*PuTTY is a free and open-source SSH and telnet connection program.

 

Test & Improve

Load the program onto the CPX by dragging and dropping the python file onto the CIRCUITPY drive, then rename the file as “Code.py”

Like pretty much every project, this one will likely be a little wonky when you first get it running. If the touch pads are acting strange, reset the CPX (this recalibrates the capacitive input pins).

Test 1:

– Open up the serial monitor with PuTTY and run the program (CTRL + D)

– Test each of the movement controls (you’ll see the mouse moving on the screen and make sure the program doesn’t crash as well as the touch pads (which should display relevant text on the serial monitor).

Test 2:

Deploy in Minecraft creative mode! Test the movement and action controls to see if anything breaks or doesn’t work as expected (plz keep in mind that this is a prototype)

Update the program based on your testing. Remember, it’s OK if it’s not perfect, there’s always time to make it better!

 

Have all the fun!!

You’re ready to run through Minecraft!! Just be wary of monsters, it might be a bit tricky to protect yourself..

Supplementing your gesture controller with a keyboard is a good idea if you want play for reals 🙂

Please like and/or leave a comment if you enjoyed the tutorial! And of course, let me know if you have any comments or questions!
Happy Building!

<3, jenfoxbot

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!

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!

Blinking Light(s) with the Raspberry Pi!

Welcome to the wonderful world of controlling physical objects with software! This tutorial is a complete beginners introduction to the Raspberry Pi computer, covering the basic features and functions to help you bring your ideas to life!

IMG_4140

Blinking a light using the Raspberry Pi’s General Purpose Input and Output (“GPIO”) pins is the hardware equivalent of a “Hello World” software program.

  1. First, gather the following materials:
    Breadboard (or wires/alligator clips)
    Two (2) Breadboard wires (Male-to-female are ideal)
    One (1) (or more!) LED (Light Emitting Diode)
    One (1) 330 Ohm resistor
    And the rest of the normal stuff to set up the RPi (SD card, power cord, keyboard + mouse (or just keyboard), HDMI cable and monitor.)
  2. Wire up the breadboard!IMG_4146
    Pick a GPIO pin. Attach the female end of one breadboard wire to the GPIO pin, and the male end
    Connect the other breadboard wire from ground on the RPi (third down on exterior side) to negative slot on the breadboard.
    Connect the resistor from the positive series of holes to an open row on the breadboard (I picked row 10).Connect the long side of the LED to the same row the resistor is in. Connect the short side to the negative slot.
    Make sure nothing explodes (just kidding that probably won’t happen 🙂 )
  3. Write a quick Python program.
    The program switches the GPIO pin between on and off, turning the LED on/off as it switches. Save the program somewhere easy, like the Desktop.
    Here’s my code if you need some assistance:

    import RPi.GPIO as gpio
    import time

    #SEtup pin 18 as an output
    gpio.setmode(gpio.BCM)
    gpio.setup(18, gpio.OUT),/span>

    #define data to be the value of pin 18
    #data = GPIO.IN0(18)

    #Make an LED flash on and off
    while True:
    gpio.output(18, gpio.HIGH)
    print(‘Light is on.’) #Optional printout of status
    time.sleep(1) #changing the number increases/decreases length of signal
    #print(data)
    gpio.output(18, gpio.LOW)
    print(‘Light is off.’) #Optional printout of status
    time.sleep(1)
    #print(data)

  4. Run the program!

IMG_4144In the terminal window, go to the folder where you saved your program. The command cd + the directory name (ex. /home/pi/Desktop) will take you there.
Run the program by typing sudo python “ProgramTitle”.py
As long as everything is connected and the program does what you think it does, the LED will flash.
That’s it! Super simple, and it means that this little RPi computer just controlled a physical object wooooo!!!
Optional fun:
– Change the timing of the blink.
– Connect a couple more LEDs the same way you connected the first (these will be in parallel with each other).
– Connect additional GPIO pins to more LEDs and change the timing (remember to also add in the appropriate code).

Helpful info:

www.atariarchives.org
www.atariarchives.org


As shown in the photo to the right, breadboards usually have columns for positive and negative (red and black, respectively) that are connected electrically all the way down the board.  Each row contains 5 holes that are also connected.

The resistor needs to go in between the LED and the power source to limit the amount of current, or electricity, flowing through the LED. The LED would be brighter w/out the resistor, but it will probably burn up super quick.

Happy building!

IMG_4150

Setting up a Raspberry Pi to Control Physical Objects, Pt. 2

What cool things can you do with the Raspberry Pi?

Source: http://www.aoakley.com
Source: http://www.aoakley.com

Welcome back to exploring the Raspberry Pi! There are tons of awesome things you can do with the Raspberry Pi — (pretty much) everything that you would do on a normal computer, like word processing, surfing the internet, streaming videos, etc.

You can write programs on it using the Idle software (Python language), Scratch, or Linux. This might seem mundane, but keep in mind that you bought this lil’ computer for only $30 dollars (+shipping and handling). If you have kids, this is a fantastic option for a first computer! The RPi naturally teaches and encourages hardware and software programming. Plus, you won’t mind as much when the kids spill apple juice all over it (or if you’re like me and still spill apple juice on computers, this is a great option for a backup computer..).

 

You can print this GPIO Leaf and stick in on the board!
You can print this GPIO Leaf and stick in on the board!

GPIO Pins!
By far the coolest way to use the Pi is to interface w/ the real world using the GPIO pins (that row of 26 pins adjacent to the RCA video port, or the yellow port). The GPIO pins have different functions as shown in the photo below: 17 of the 26 total pins are actual GPIO pins, while the rest are either ground, a power source (5 VDC or 3.3 VDC) or labeled “DNC” for “Do Not Connect”/”N/C” for “Not Connected” (connecting to these pins may short the Pi, so it is recommended to avoid these).

GPIO pins can be used as an input or an output. As an input, the pin can distinguish between two values: HIGH*  and LOW. As an output, you can send an ON, or HIGH signal (3.3 VDC), or an OFF, or LOW signal (0 VDC). These pins can be used for tons of physical tasks, like turning on/off lights (Christmas light choreography, anyone??), controlling motors, reading sensors, and honestly pretty much anything you can conceive, as long as you build a proper circuit.

Some of the GPIO pins also have more specific functions, such as SDA (data line), SCL (clock), etc.; if you’re reading this as a beginner don’t worry about these just yet. When you find a project you’re excited about you’ll naturally learn these functions as necessary.
*High input threshold is a signal of ~ 1.8 VDC, although it can vary between 0.8 – 2.0 VDC. This means that any signal coming in to your GPIO pin that is above 0.8 VDC may be read as “HIGH” by the RPi.

Advanced users will be happy to know that you can modify many of the GPIO characteristics from software (this link also has the robust GPIO electrical specifications).

For absolute beginners, here are some helpful things to know about the GPIO pins:
ac-dc-voltageGPIO pins operate on Direct Current (DC) voltage. Unless you want to see smoke come out of the RPi, do NOT input Alternating Current (AC) signals, like the one that comes out of the wall.
Be very careful about what you connect to the GPIO pins. You will not be able to control a motor directly from a GPIO pin; in this instance, the GPIO pin functions as a switch, rather than the actual power for the motor. Here’s a great tutorial on how to control a small motor.

Looking for more inspiration? Here’s a general list of 25 cool things to do w/ your RPi! You can also Google “Raspberry Pi projects” or browse the Instructables website for RPi projects.

The next post will cover a simple circuit you can build and control w/ the RPi.

Setting up a Raspberry Pi to Control Physical Objects, Pt. 1

RaspberryPiLogosmallThere are a slew of relatively simple systems to control physical objects w/ software. The most popular options are Arduino, the Raspberry Pi, and BeagleBoard. I’m an avid Raspberry Pi advocate, so let’s start with that!

The RPi is a simple & inexpensive computer that has general purpose input and output (GPIO) pins that interface w/ the real world.

(This tutorial assumes you are a beginner, but some technical jargon is included. Please feel free to comment if a term or phrase is not clear.)

What is a Raspberry Pi?RaspiModelB-1024x902

The Raspberry Pi is a credit-cared sized computer created by the Raspberry Pi Foundation, an educational charity based in the UK. It is designed to promote programming, computing, and interfacing with the physical world. It can control pretty much anything you are capable of conceiving.

There are two versions of the Pi:

  • Model A is cheaper w/ fewer features; 256 MB of RAM, one USB port and no Ethernet port.
  • Model B is more expensive, but has 512 MB of RAM, two USB ports, and a 100mb Ethernet port.

Where to purchase:

You can buy a Raspberry Pi from a variety of distributors. Model B from Adafruit is $40 (+ shipping & handling).

Other supplies:

RaspPiStarterKitThe Pi is literally just a computer. You’ll need a few additional supplies to set it up and use it (unless you’re a wizard). Think of it like a puzzle: collect the remaining pieces to customize an inexpensive interactive computer! To make the process easier, here’s a list of parts w/ explanations (you probably already have some):

  1. Power Cord
    The Pi runs on a micro-USB power supply, similar to many phone chargers. More specifically, the Pi needs 5 VDC and at least 700 mA. The Pi Foundation recommends a power supply that can provide 1200 mA. You can get one for less than $10, best values ~ $5, if you’re crafty you can find cheaper (or free). Here’s a google search for some that meet the best specs. Take note of where the power cord plugs into: wall socket, USB, etc.
  2. SD Card
    The Pi needs an SD card for physical memory storage (it doesn’t have a built-in hard drive or solid state drive). For ~ $6, you can buy an SD card with a pre-installed operating system and necessary software from the Pi Foundation’s Swag store here.
    With slightly more effort, you can buy any generic SD card and download the software here. This is fairly easy with a Mac system; if you chose to go down this route, here’s a great tutorial.
  3. Monitor & Display cable: HDMI/DVI cable or RCA composite video lead.
    Most modern monitors and TVs have HDMI ports for video (you can connect your RPi to your TV, woo!!). If you don’t already have one lying around, HDMI cables are found at RadioShack, Best Buy, Amazon, Ebay, etc. You can also get a HDMI converter cable for monitors or TVs w/ different ports. Older monitors are easy to find for free; many places of business, colleges/universities, and friends are happy to part with old monitors, or you can check out e-waste recycling bins.
  4. USB Keyboard & mouse (easiest way to set up).
    Any keyboard and mouse w/ a USB connection will work w/ the Pi.

Optional Supplies:

  1. Raspberry-Pi-Geek-Cases-1Ethernet Cable  (easiest way to connect to the Internet for Model B).

    Usually blue and lying around in some pile of cords you know are important. You can also buy them at places like Radio Shack, Best Buy, Amazon, etc.
  2. USB WiFi chip.
    Getting a USB WiFi “dongle” (yes, that is actually what it is called..) will allow you to connect to the Internet w/out an Ethernet cable. This requires some fairly involved setup, but it is completely doable for a RPi user of any experience level. Here are two methods:
    –Using wicd-curses,
    –Using GUI application
  3. Audio Lead (if not using HDMI)
    To get sound w/out an HDMI cable, you’ll need a standard 3.5mm jack to connect to speakers or headphones.
  4. Case
    The Raspberry Pi is designed to be a bare-bones computer to reduce cost as much as possible. However, cases are helpful protection from inevitable accidents and improve the mechanical connection of cables. There are TONS of awesome cases made specifically for the Raspberry Pi, although feel free to get creative and make your own!

Basic Setup:

raspberry_pi_iphone

  1. Insert SD card. Plug the RPi into a monitor & connect the keyboard and mouse via USB. An Ethernet cord is also recommended as it makes installing software on the RPi much easier.
  2. Plug the power cord into the RPi. Make sure you see a light turn on. (Yes, I honestly needed to include this step because this is an all too frequent problem for me.)
    Always do this after everything else is plugged in.
  3. If everything has been connected properly, you will see a start-up window. Every operating system (OS) will be different, but initial setup is simple and manageable.
    If you have a pre-loaded RPi-specific OS, or you have Raspbian or Adafruit’s OS, here’s a super straightforward tutorial on how to fully configure the RPi.Changing a few basic settings will definitely make life easier. From personal experience, if you have an SD card larger than 2 MB it’s useful to initially expand root partition to use the full SD capacity. If you want to avoid a command line window, you can specify Desktop launch whenever you power up the RPi.The default username is “pi” and the password is “raspberry”.Note: Since every OS is different, if your Pi doesn’t launch into the startup window, if you are still on the terminal window type “startx” into the command line. If that doesn’t work, leave a comment and we can troubleshoot together!
  4. Essentially that’s it! Once you’re at the desktop, you can use the Pi much like any other computer! Some basic programs: Midori is a simple Internet browser, Leafpad is a word processing program, Idle is a Python programming environment, and Scratch is kid-friendly programming language.

I will add more on how to set up the wireless, or other topics as requested.