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

Turn your Pi into a (local) Cloud Server!

Save and access docs and photos and music on your own local Pi Cloud* server! The best part: you can use it if, or when, the Internet goes down (or if you’re in a remote spot & want access to Wikipedia). Oh hey, and if your friend gets one and they live close (*ahem*80ft*ahem*), you can share stuff with them and make your own personal chat line!

That gets me thinking.. if enough folks built Pi Cloud servers, we could crowdsource the Internet! That would be an 11/10 on a scale of greatness. With the new models of the Raspberry Pi computer, it’s possible and not even expensive! (What! Tell me more!)

This tutorial will show you how to set up a short-range (~ 80 ft) WiFi Access Point and a personal web server (‘bringin it back to HTML bbies). You can set this up as a (closed) local network only (i.e. your own personal “cloud” backup device), or broadcast it to the rest of the world! (..if you do this be sure you know network security.)

That said, assuming you have a basic knowledge of the Pi, here’s the breakdown:

Read Time: ~ 40 min

Build Time: ~ 60 min (less if you are experienced w/ Linux)

Cost: ~ $35 (for the Pi 3)

If you are interested in using this to crowdsource a people’s Internet, share it w/ your friends & family & everyone you know (or build it for them!). If you build this project please mark that you’ve built it so we can get a sense of how many folks have the infrastructure we need to actually make a full-fledged people’s Internet. Lastly, follow me to stay updated (I am reaching out to some folks to try to get this to be a real thing, please feel free to contact me if you can help and/or take this on, it is open-source!).

 

New to Linux & Terminal Programming?

We’ll need to be able to access our Pi remotely (e.g. via SSH). If you’re like “wtf is that”, check out this introductory tutorial for a more thorough overview on how to set up the Raspberry Pi 3 and some quick Linux terminal programming.

This approach to the Pi Access Point* and web server** uses the Jessie Lite OS. If you follow this tutorial line-by-line, you will need this specific version of Linux.

Lastly, this tutorial is built off of the Adafruit Digital Free Library tutorial, so check that tutorial if you run into any issues (or leave a comment and myself or another helpful folk will attempt to answer your question 🙂 )

(Also, this might feel a bit long, so I’ve included various cute puppy photos throughout to keep you motivated :D)

*An Access Point is hardware device that allows a WiFi device (e.g. smartphone) to connect to a wired network (e.g. router).

**A web server is a computer that delivers a web page. When you go to your favorite websites, you type in “www.wikipedia.org” which takes you to the IP address for the web server and displays public information.

Warning: it is recommended to run your Pi as a local network only (i.e. do not connect the Pi to the broader World Wide Web) as the WPA2 password protocol may not be secure.

Materials

– Computer with Ethernet port & SD Card slot

– Raspberry Pi 3

– SD Card (8GB or larger, esp. if you want to use it for storage)

– MicroUSB to USB power cord

– Ethernet Cable

– RecommendedRaspberry Pi Case

Software Programs

1. PuTTY allows us to remotely log in to the Raspberry Pi using the Pi’s IP address, username, and password.

Download here: ​http://www.putty.org/

2. Etcher formats and writes the Raspbian (or other) Operating System (“OS”) to an SD card.

Download here:​ https://etcher.io/

3WinSCP allows for easy file transfer between your computer and the Raspberry Pi.

Download here (click on Installation Package): ​https://winscp.net/eng/download.php

4. Windows computers will need Bonjour print services for Windows (from Apple) to use the “raspberrypi.local” IP address.

Download here: ​https://support.apple.com/kb/dl999?locale=en_US

 

Quickstart

If you’ve worked with the Pi before and are comfortable w/ the Linux terminal and such, here’s a quick overview of this process:

1. Load Jessie Lite onto an SD card (8GB or more) and insert into the Pi.

Download the Jessie Lite OS here.

2. Remotely log in (e.g. SSH) and enter credentials.

3. Here’s a Github repository with all of the commands to turn your Pi into a web server 😀

Go through the Setup file and input the commands (in order). This process will install HostAPD (authentication), DHCP (IP management), iptables (firewall), and Apache (web server software).

4. Create a public web page or keep your files/data private/w/ friends & family.

A sample HTML web page adapted from the Adafruit Digital Free Library tutorial is included in the Github repository (ServerWebsiteHTML-Raw). You can also use the larger zip file to build off of 🙂

Warning: it is recommended to run your Pi as a local network only (i.e. do not connect the Pi to the broader World Wide Web) as the WPA2 password protocol may not be secure.

 

Set up the Raspberry Pi

1. Flash the SD card with Jessie Lite (​download Jessie Lite here). Enable SSH by adding a file named “SSH” in the SD card file contents (no extensions — remove the .txt if any added automatically). Insert into the Pi.

2. Plug in the Ethernet cable between your computer and the Pi, then plug the Pi power cable.

3. Create a network bridge between your computer and the Pi.

Go to Settings -> Network & Internet -> Change Adapter Settings. Select the Ethernet connection (should show an unknown connection or something similar). Hold the “CTRL” key, and then select the WiFi connection. Right click and choose “Bridge Connections.”

3. Open PuTTY, type “raspberrypi.local” for the hostname, and log into your Pi, woo!

If you are logging in for the first time, use the default username: pi and password: raspberry . Change your password using the command passwd .

4. Check that the Pi is connected to the Internet and update it.

Run this command to check if the Pi can connect to Google (it will print 5 lines saying it if received information from google.com):

ping -c 5 google.com

Run this command to update the Pi:

 sudo apt-get update
 sudo apt-get upgrade

Install Apache

Apache is our web server software! (It allows us to easily host information and files accessible via a web browser like Chrome, Firefox, Explorer, etc.).

Let’s install the Apache software and then change permissions to edit the HTML folder. Type and enter the following commands (in order):

sudo apt-get install apache2 -y
cd /var/www
sudo chown pi:pi /var/www/html
cd

Install Server Software!

1. Install HostAPD and DHCP software.

HostAPD is used to authenticate information sent and received from connected devices, and DHCP is a protocol used to provide quick, automatic, and central management for the distribution of IP addresses within a network.

To install both at once, type the following command and then press “y” to continue:

sudo apt-get install hostapd isc-dhcp-server

2. Install iptables for a firewall. (yayy for security!)

Run this command and type “y” (yes) to both of the config screens that pop up:

sudo apt-get install iptables-persistent

Edit the DHCP Configuration File

Let’s set up the DHCP communication protocol so we can send and receive information (pretty important if you’re thinking of building a connected network)! Go to the DHCP configuration file by typing the following:

sudo nano /etc/dhcp/dhcpd.conf

1. Add a comment (“#”) in front of the following lines (so it looks like the file in Photo 1):

option domain-name “example.org”;

option domain-name-servers ns1.example.org, ns2.example.org;

2. Remove the comment (“#”‘) from the “authoritative” line (Photo 1 also helpful here):

#If this DHCP server is the official DHCP server for the local network, the authoritative directive should be uncommented.

#authoritative;

3. Add this code to the very end of the file:

subnet 192.168.42.0 netmask 255.255.255.0 {    
    range 192.168.42.10 192.168.42.50;     
    option broadcast-address 192.168.42.255;
    option routers 192.168.42.1;
    default-lease-time 600;
    max-lease-time 7200;
    option domain-name “local”;
    option domain-name-servers 8.8.8.8, 8.8.4.4;
}

What is this doing?! To (very briefly) summarize, it sets up a range of IP addresses to assign to connected devices (from 192.168.42.10 to 192.168.42.50), just like your home router! It also tells the Pi how to communicate to other devices (its broadcast address, 192.168.42.255, and its own IP address, 192.168.42.1). It assigns an amount of time (in sec) to share this connection (lease time), and sets up domain name servers (like looking up a phone number in a directory).

4. Save and exit by pressing “Ctrl – X” and then “y” (and then the enter key).

Edit the Default DHCP Server File

Let’s edit the DHCP server file so that we can assign it to broadcast via WiFi! Go to the DHCP default server file by typing the following:

sudo nano /etc/default/isc-dhcp-server

1. Scroll down to the line that says INTERFACES=”” and change it to broadcast via wlan0 (that’s a zero, not an O):

INTERFACES=”wlan0”

2. Save and exit by pressing “Ctrl – X” and then “y” (you’ve probably figured this out key combo by now so I’ll stop mentioning it 🙂 ).

 

Set Up a Static IP Address

1. Let’s give our Pi a static (unchanging) IP address so that we can always find it, yay! Temporarily disable the wireless interface network:

sudo ifdown wlan0

2. Use the nano text editor program to edit the network interfaces file (which you probably figured out by reading the command (: )

sudo nano /etc/network/interfaces

3. Edit the file so that it looks exactly like the following, then exit & save (also check out the photo below):

auto lo
iface lo inet loopback
iface eth0 inet dhcp
allow-hotplug wlan0
iface wlan0 inet static
    address 192.168.42.1
    netmask 255.255.255.0
#iface wlan0 inet manual
#wpa-roam /etc/wpa-supplicant/wpa_supplicant.conf
#iface default inet dhcp

4. Assign a static IP:

sudo ifconfig wlan0 192.168.42.1

Configure the Access Point Details

1. Create a new configuration file named “hostapd”:

sudo nano /etc/hostapd/hostapd.conf

2. Write the following (exactly as-is) in this new configuration file (then exit & save) (see photo below):

interface=wlan0
ssid=HelloWorld #Name of your RPi WiFi connection
country_code=US #Unless you are elsewhere!
hw_mode=g
channel=6
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2 #This is the password protocol
wpa_passphrase=raspberry #Change the password!
wpa_key_mgmt=WPA-PSK
wpa_pairwise=CCMP
wpa_group_rekey=86400
ieee80211n=1
wme_enabled=1

3. Tell the HostAPD protocol where to find this new file.

Edit the default HostAPD file:

sudo nano /etc/default/hostapd

Find the line that says #DAEMON_CONF=””. Remove the comment and edit it so that it looks like this (see photo below):

DAEMON_CONF=”/etc/hostapd/hostapd.conf”

Edit the HostAPD initialization file:

sudo nano /etc/init.d/hostapd

Find the line that says DAEMON_CONF=. Edit it so that it to point to your new configuration file! Like this (Photo 3):

DAEMON_CONF=/etc/hostapd/hostapd.conf

Configure Network Address Translation (“NAT”)

This step allows for multiple clients (like all your friends!) to connect to the Pi’s WiFi at once (play all the games!!). It is a bit technical, so I’m gonna gloss over the deets (also not terribly familiar with this part), but it will get you through the process.

Note: you only need the iptables shenanigans if you want to connect your local access point to the greater World Wide Web.

1. First, we need to start IP forwarding every time the Pi turns on. Enter the following command to edit the sysctl* configuration file:

sudo nano /etc/sysctl.conf

— Scroll to the bottom and type this code on a new line, then exit & save:

net.ipv4.ip_forward=1

*btw that is an L in sysctl, not a 1, which I have messed up soooo many times -.-

2. Activate IP forwarding by typing:

sudo sh -c “echo 1 > /proc/sys/net/ipv4/ip_forward”

3. Create network translation between the Ethernet port eth0 and the WiFI port wlan0 by typing the following commands (w/ – signs and caps and such):

sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
sudo iptables -A FORWARD -i eth0 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT
sudo iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT

4. To ensure network translation happens when we reboot the Pi, run this:

sudo sh -c “iptables-save > /etc/iptables/rules.v4”

Test that Access Point!

1. Run hostapd with our configuration file manually with this command:

sudo /usr/sbin/hostapd /etc/hostapd/hostapd.conf

2. Check the WiFi list on your computer or smartphone and find your new access point SSID! If you didn’t change anything, it will be named “HelloWorld” with a password of “Raspberry”.

If you connect successfully, you will get some text on the Raspberry Pi screen. We won’t see much yet, but we are very close!

3. Cancel the test by typing “Ctrl+C” in the Raspberry Pi console.

You can check the status of the host AP server and the DHCP server with the following commands:

sudo service hostapd status
sudo service isc-dhcp-server status

 

Set up a Daemon!

A daemon is a program that starts automatically every time the Pi is powered on and runs in the background (not quite like the “His Dark Materials” series..).

1. Start the hostapd and dhcp programs:

sudo service hostapd start
sudo service isc-dhcp-server start

2. Run these next two commands to enable hostapd and dhcp to start automatically when the Pi turns on:

sudo update-rc.d hostapd enable 
sudo update-rc.d isc-dhcp-server enable

Almost there! Create an HTML Web Server!

1. Write an HTML page to host on your web server! Or download one I adapted from the Adafruit Digital Free Library 🙂

Here’s the zip file, and here’s the GitHub repository. Save and unzip the file.

2. Open WinSCP and enter the hostname: raspberrypi.local

3. Log in to the Pi (type the username and password).

4. On the Pi side of the screen (right side), go to the home directory.

Click the folder with the up arrow on it two times.

5.Go to the /var/www/html file.

Double-click on the folder labeled “var”, then the “www” folder”, and finally the “html” folder.

6. Delete the existing index.html file (or if you want to write your own you can just open and edit it).

7. Copy the web server files into the Pi html folder.

On the left side of the screen (your computer), go to the folder where you saved the files. Highlight and drag the contents (two folders and a file named “index.html”) into the Pi html folder. That’s it!

8. Open a browser and type “raspberrypi.local” in the navigation bar at the top. If it worked, you will see the web server page, what what!

Edit the HTML Pt. 1

Change up the HTML file to share the info and documents that you want!

1. Open the index.html file on the Pi.

2. Edit the headers and descriptors in the index.html file.

— Change the title of your web server by editing the text between the title parts:

<title> jenfoxbot's Local Web Server!</title><br>

— Change the heading of the webserver by editing the text between the h2 and center parts (line 51):

<h2> <center> 
jenfoxbot webserver
</center> </h2>

— Optional: Change the description of the webpage (line 55):

<pre><div><center>
<p>Depending on the position of the moon & stars*, 
this hotspot may or may not provide an Internet connection.</p>
<p> If there IS an Internet connection, check out <a href="http://www.foxbotindustries.com" style="font-size: 12.15px;">jenfoxbot's website</a> 
and learn about the other cool stuff she does! </p>
<p><i style="font-size: 12.15px;">*And by position of the moon & stars we mean the current whims of the builder, jenfoxbot :) </p> </i>
</center></div>

3. Optional: Delete existing documents, images, and videos and add your own!

Store PDFs in the “issues” folder and photos in the “images” folder. You can also create other folders to store different files.

Edit the HTML Pt. 2

1. Add your own documents!

— Decide what you want to include on your server and download PDFs of those docs. Also download images for each of the documents so you’ll have something fun to click on 😀

— Using WinSCP, add your documents to the appropriate folders.

— Edit the index.html or other appropriate html file (e.g. if you want to add or change a book in the helpful info page, edit the “helpfulinfo.html” file).  Display your documents and images by changing the file names and extensions and update the descriptions.

2. For folks new to code, you can add more documents by copying and pasting the existing code and changing the file names and extensions!

Here’s a helpful overview on HTML from the Khan Academy!

OMG Finally! We’re Done 🙂

Unplug the Ethernet cable, connect to your wireless access point, and then type in the IP address in the address bar of your favorite browser (192.168.42.1 if you followed this tutorial exactly).

If everything is working, you’ll see your web page (like the screenshots of mine above and below). Woohoo you just created a wireless access point!! (If it didn’t work, run through the setup again and double check that all the terminal code is exactly as shown, including spaces and such).

Explore your very own local Cloud website and decide how you want to use it from here!

What’s Next?

One option is to use it as a local wireless storage device. Plug in the Pi, connect to the WiFi access point you set up (this one is named “HelloWorld”), and store or withdraw files from it. You can access these files even if you are disconnected from the Internet. So you could save your favorite movie and still watch it when the power goes out 🙂 (er, assuming you have a charged laptop).

Add more documents (e.g. you can use it as backup storage), play around with the HTML code to make your site all fancy, and have fun!

Another option is to configure this as a public-facing web page and assign it a domain name so other people can access the files. This is particularly helpful if you are going somewhere without WiFi or cable Internet — you can take Wikipedia with you! (but maybe donate to them if you do that ’cause they are awesome). If you are comfortable with code, you can set this up to be an automatic backup server, a local wireless game server for you and your friends, etc. Get creative!

If you go this route, be sure you know a bit about network security as the WPA2 password protocol has recently been compromised (sad panda..).

Finally, as mentioned in the intro, you can use this Cloud server to kickstart a people’s Internet! Have a build day with your friends to create a bunch of Cloud servers so that you all can “talk” to each other! This approach isn’t necessarily the *best* (aka most efficient/effective) way to build a public Internet, but it’s a great starting point. Plus, the better we understand how these technologies work, the better we use them to solve serious problems and advocate for ourselves and our communities. 🙂

Intro to the (Headless) Raspberry Pi!

Finally! Use your Raspberry Pi without spending what feels like forever connecting external peripherals and dealing w/ a cable monstrosity: Configure your Pi to be headless! (not the scary kind tho) This is particularly helpful for folks teaching workshops with the Raspberry Pi, since it can be cumbersome (and expensive) to provide monitors, keyboards, and mice for every student.

I’m assuming that y’all know a bit about the Pi, so this tutorial will not cover what the Pi is or it’s awesome capabilities (I’m lookin’ at you, GPIO pins!). To learn more about what the Pi can do, check out some of my other tutorials (see the last section in this tutorial) or leave a comment.

What is covered in this tutorial: Enabling and using SSH, a general overview of the Linux terminal window, and how to connect to the Pi’s GUI (Graphical User Interface, aka the Desktop view) via SSH.

Read Time: 15 min

Build Time: ~20 min

Cost: Free! (assuming you already have an RPi and Ethernet cable)

Materials

Computer with Ethernet port & SD Card slot

– Raspberry Pi 3

– SD Card (8GB or larger)

– MicroUSB to USB power cord

– Ethernet Cable

– RecommendedRaspberry Pi Case & GPIO cable

Software

For this project, you’ll need the following (free!) software programs:

 

Configure the SD Card

1. Download your favorite flavor of Raspbian! You can get the most recent version here.

2. Insert your SD card and open Etcher.

3. Select the Raspbian zip file, the driver for your SD card, and click “format”.

4. Enable SSH access

Open the file contents for the SD card. Add a new text file titled “SSH”. If the computer adds a file extension (e.g. “.txt”), delete it and ignore any warnings.

5. Eject the SD card and insert it into your Pi.

 

Let’s Get Connected!

1. Plug in the Ethernet cable between the Raspberry Pi & your computer.

2. Plug in the USB power cable.

Check that the red power light turns on and that the Ethernet port lights (yellow & green) are on and/or blinking.

3. Connect the RPi to the World Wide Web (aka the Internet).

Go to Settings -> Network & Internet -> Change Adapter Options (aka Network Connections).

Click on the Ethernet connection, hold down “CTRL”, and then click on your WiFi connection.* Right-click in the window and select “Bridge Connections” — this will bridge the connection between the Ethernet port to your WiFi port.

*If you select the WiFi connection first, it will bridge the connection from the WiFi to the Ethernet, which would allow you to log into the Pi but not connect to the Internet.

4. Open PuTTY and log in to the Pi using the “raspberrypi.local” IP address.

Default username: pi

Default password: raspberry

5. Change the default password by typing passwd and following the prompts.

 

Navigating the Linux Terminal Window (Shell)

The terminal window is the control panel for the system.

It typically shows a command prompt, which gives us information but is not part of the commands to the system. Most commonly the command prompt displays the user’s login name and the current working directory (represented by a twiddle: ~ ).

Inputting Commands

Commands are written after the prompt and inputted by pressing the Enter key.

Commands can be issued as-is or followed by one or more options. Options usually have a dash in front of them, like the following:

ls -a

You can view the options for a specific command by typing the command name followed by “–help” (will cover this more later).

 

 

 

 

 

 

 

 

Linux Hot Keys!

There are a handful of special key combinations that make navigating the terminal window easier and faster. Here are a some of the most common ones:

  • Ctrl+A – Move cursor to beginning of command line
  • Ctrl+E – Move cursor to end of command line
  • Ctrl+C – End running program
  • Ctrl+D – Logout of current session
  • Ctrl+R – Search command history
  • Ctrl+Z – Suspend a program

 

  • Left and Right arrow keys – Move cursor one place to the left or right on command line
  • Up and Down arrow keys – Browse command history
  • Shift+PageUp and Shift+PageDown – Browse terminal buffer (to see text that is off screen)
  • Tab – Command or filename completion
  • Tab Tab – Shows file or command completion options

Practice using these every time you are in the terminal window and you’ll quickly become a Linux wizard!

Getting Help in the Terminal

1. Manual and Information Pages

The manual pages are an exhaustive resource for all of the available commands in the Linux terminal window. To read the manual pages on a particular command, type the following:

man command

This will pull up the manual pages for the particular command that you are searching. Here’s the manual pages for the apropos command:

In the manual, the first line contains the name of the command you are reading about and the ID of the section that contains the manual page.

After the first line is a synopsis, which is a short description of the command that includes technical notation of all the options and/or arguments. Options are a way of executing the command, and an argument is what you execute it on. Optional arguments are put between square brackets.

After the synopsis is a longer description of the command, followed by a more in-depth overview of the available options, information about combining options, other related commands, and other information pertaining to the command.

Some commands have multiple man pages, like the “passwd” command. To see all pages about a command, use the “-a” option:

man -a passwd

The info pages contain more recent information and can be easier to use. Here’s what the menu of the info pages looks like:

To view the info pages on a command (replacing “command” with the actual name of the command you want to research, like “apropos”), type the following:

info command

To navigate the info pages, use the arrow keys to browse through text, the Enter key to read about a particular keyword, “P” and “N” keys to go to the previous or next subject, and the space bar to move one page further. Use “Q” to quit.

2. whatis and apropos commands

The whatis command gives brief information about a command and lists the first section in the man pages that contains a relevant page (in parenthesis after the command name).

If you’re entirely unsure where to start, the apropos command is a good way to search for keywords. For example, if you want to know how to start a browser, you can type apropos browser, which will pull up a list of all browser-related programs, including web browsers, file and FTP browsers, etc.

Here’s the apropos search results for “text”, which displays commands and programs that contain the phrase “text”:

 

3. Using the –help option

Most commands also have the option –help, which gives a short explanation of the command and a list of available options. When in doubt, this is a great way to get some quick and useful information on using a particular command and its possible extensions.

To use the –help option, type –help after a particular command, like the following example (also shown in the photo above):

apropos --help

The output looks like this:

 

Enough of the Terminal Window! Where’s the friggin’ Desktop??

Alright alright.. Remote Desktop Connection is an easy way to use the desktop view, also known as “Graphical User Interface,” or GUI for short.

1. Install Remote Desktop Connection on your Pi:

sudo apt-get install xrdp

2. Install Remote Desktop Connection on your PC (is already installed on Windows OS).

3. Open Remote Desktop Connection and log in using the “raspberrypi.local” IP (or find your Pi’s IP using command ifconfig). Ignore warning (click “yes”).

4. Log in with the Pi’s username and password.

If you haven’t changed your password yet, do so now. (Yes, I know I already told ya to do so but it is worth repeating since someone could actually hack into your Pi if you don’t change the default password.)

Now you can use the Pi’s GUI and do almost* everything via your PC!

*Sadly, we can’t play Minecraft in this mode as it uses too much data to be transferred via SSH. Using a VNC viewer is one option around this if you really want to play Minecraft remotely.

What is SSH, anyway?

SSH stands for “Secure SHell” — it is a “cryptographic network protocol for operating network services securely over an unsecured network.” – Wikipedia

… Uh, what?

In other words, SSH is a secure way to connect between one computer and another, even if the network through which you are connected is not secure.

For example, if you are on a shared network and you use SSH to remotely log into another computer, other folks on the shared network can’t see what you’re doing through the remote connection (although Snowden did release documents that showed the NSA can sometimes decrypt SSH).

Common uses of SSH include remote log in, like if you want to connect to a computer that lives a mile underground without having to, you know, actually go down there. (I used to work for a super cool dark matter experiment called DRIFT and this is how we would access the computers that controlled the detector because the computers lived in a mine about 3 miles underground.. too far to travel to update software!).

Here’s the full Wikipedia page on SSH — it’s super cool so check it out!

More to Explore!

Go forth and explore! Practice using the terminal window until you get comfortable and familiar with the basic commands.

Program the GPIO pins to do cool stuff! Need some ideas? Check out these tutorials:

1. Making a Soil Moisture Sensor

2. Building an Irrigation Controller (can be paried w/ Soil Moisture Sensor)

3. Bark Back: Install an IoT Pet Monitor

4. Expand on your Smart Home & add a Motion Triggered Music Player

Need parts?

Take apart old & broken electronics! Electronic toys are a great place to get motors and speakers. If you want better motors, take apart power tools.

Ask friends or find a repair shop for extra parts and wire, save power cables from old electronics and use them as power supplies or harvest them for wires and/or connectors, save old headphones and use them for audio projects.

Best piece of advice: think before you toss 🙂



			

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!

Interactive Survey Game!

A survey questionnaire come to life! Use (nearly) any object to gather helpful data through an interactive, engaging, and fun multiple-choice survey.

This project uses the Makey Makey microcontroller in combination with a Raspberry Pi computer to read in participants’ survey choices and save the results in a text file.

Planning & Design!

This general design is easily customized to fit a different theme. The only crucial design requirement is to use materials that conduct electricity for the survey pieces, or wrap non-conductive materials in aluminum foil.

Suggestions:
Prototype, prototype, prototype! Build different versions and test them on family, friends, co-workers, or (ideally) your target audience. Observe how folks interact with your survey, then use that to make it better! And always remember to keep it simple 🙂

Materials

Makey Makey Kit
– Computer: Raspberry Pi

– One (1) ground piece, five (5) survey response pieces, one (1) submit piece, and two (2) yes/no pieces*

22 Gauge (stranded) Wire — five (5) 10 – 16″ strips and three (3) 6″ pieces (ends stripped)

– Container:

— Wood Box (12.5″ x 12.5″)
— Plexliglass.(“12 x 12”)
— Three (3) 2″ x 2″ wood panels

* Specific materials used in this design are detailed with the corresponding procedure, although customization is encouraged!

Tools

Safety goggles, woo!
Multimeter
— Optional: Soldering iron, solder& desoldering wick
— Ruler (or calipers)
Drill w/ both drill and driver bits
Flat wood file (to prevent splinters!)
Hot glue gun
— Epoxy (permanent)
– Pliers

Reprogram the Makey Makey

To reprogram the Makey Makey, you’ll need to have the Arduino IDE with Makey Makey drivers installed. Here’s a thorough tutorial on how to do this.


1. Plug Makey Makey into computer and open the Arduino IDE.

2. Open (or copy) Makey Makey source code:
Here’s the GitHub page for the Makey Makey.
Here’s a direct link to download the full program. This is a .zip file, so be sure to extract all the files.

3. Reprogram the “click” key into an “enter” key.
For a thorough overview of how to do this, check out this tutorial.

4. Change the following keys:
These two keys are mapped in the survey program, but can be left as-is or you can choose to switch other keys (e.g. the arrow keys). Just be sure to change the mapping in the program.

A. Change the “g” into an “n”.
B. Change “space” key into “y”.

Build the Survey Response Pieces!

Specific materials used in this design:

– Two (2) wood blocks, two (2) golf balls, and one (1) jar lid.
– Aluminum foil
Unistrut 1/2″ Channel Nut with Spring
– Ten (10) 1/2″ washers
– Plexiglass [or wood] (12″ x 12″)

Procedure:

1. Wrap each of the survey response pieces at least 2 – 3 times with foil, hot gluing each layer.

2. For unistrut spring pieces, hot glue (or epoxy) the top of the spring to the bottom of each survey response piece — be sure that the metal of the spring is touching the foil of the survey piece.

3. Attach the survey pieces to plexiglass.

Determine location of survey response pieces and mark with tape. Drill a hole at each point.

Place a washer on either side of the hold and screw bolt into unistrut spring about 3 turns.

4. Connect a wire to each of the unistrut spring pieces.

Wrap wire around base of bolt (between washer and plexiglass). Hand tighten the bolt to secure wire without squishing it

Build the Ground Piece!

Specific materials used in this design:
– Styrofoam ball
– Metal pipe
– Flange stand for pipe
– Aluminum foil
– Twelve (12) washers
– 4 wood screws
– Wood panel (2″ x 2″)

Procedure

1. Build a stand for the styrofoam ball — use conductive materials or wrap pieces in foil.

2. Wrap styrofoam ball in aluminum foil, leaving a “tail” of foil. Place ball on stand and push the foil tail against the inside of  Hot glue pieces together.

3. Cover the exposed end of the ground wire (24″) to the inside, or bottom, of base and adhere with tape or epoxy.

5. Add a layer of two (2) washers under base to avoid squishing the wire, then connect base to wood pane via screws or epoxy.

Build the Enter Key!

Specific materials used in this design:

– Clothespin
– Wood panel (2″ x 2″)
– One (1) wood screw + one (1) washer

The screw should be about 1/4″ longer than the wood thickness.

– Aluminum foil

Procedure:

1. Wrap one of the handles of the clothespin in foil.

2. Remove clothespin spring clamp, align other side of the clothespin on wood panel, and drill in a screw and washer.

Foil on the other side of the clothespin should make contact with the washer + screw when closed.

3. Reconnect spring clamp and other side (may need pliers). Epoxy bottom of clothespin to wood panel.

4. Use alligator clip or wrap wire around screw and secure with hot glue.

Make the Yes and No Keys! 

Specific materials used in this design:
– Two (2) plastic container lids
– Two (2) wood panels (2″ x 2″)
– Two (2) wood screws and washers

Each screw should be about 1/4″ longer than the wood thickness.

– Aluminum foil


Procedure

1. Cut circle out of container lids. Wrap in foil.

2. Align lids on wood panels and drill in a wood screw with washer on top — be sure the screw slightly pokes through the back of the wood panel.

3. Use alligator clip or wrap wire around screw and secure with hot glue. 

Connect Pieces to Makey Makey

1. Connect ground piece lead to Makey Makey ground pads.

2. Connect survey game pieces to the first five (5) Makey Makey back header pins on the left: “w”, “a”, “s”, “f”, and “d”.

3. Connect the no button to the last (6th) back header pin, “g”

4. Connect the yes button to the “space” pads.

5. Connect the submit piece to the “click” pads.



Load the Survey Program!

Using a Raspberry Pi computer means that all of the electronics can fit into the game box! Write up a program in Python to cycle through a series of survey questions and five possible choices that map to the survey response pieces.

Here’s my code:
GitHub page!
Python program only.

Final Touches & Case!

This case is designed to withstand high traffic, experimentation, and children — and to be easily (and cheaply) fixable and adjustable. Use this design or customize your own!

Materials:
12.5″ x 12.5″ wood box
1″ x 10 ” wood panel

Procedure:
1. Epoxy wood panel onto front of box.

2. Drill the submit, yes, and no keys into the wood panel.


Recommended to put the “submit” button on the far right (switched this after further testing and feedback).

 

3. Drill hole large enough to fit an HDMI port in the back panel of the box.

I used two 3/8″ bits and filed down the hole until the HDMI port fit.

4. Label the survey game pieces and the submit, yes, and no keys.

Test, & Install!

Connect the Raspberry Pi to a monitor, keyboard, and the Makey Makey. Test the program and double check all the keys. Once everything is up and running, remove the keyboard (and mouse if connected).

Load the python program, stand back, and let passersby have a blast participating in a survey!

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.