micro:bit magic wand (Beginner)

 

While it is a bit tricky for us non-magical humans to levitate objects with our minds, words, or wands, we can use technology to do (basically) the same things!

This project uses two micro:bits, a few small electronic parts, and some everyday objects from around the house to create our very own magical wand.

I went for the Wingardium Leviosa spell, but you can most certainly adapt this project to cast other spells 🙂

Difficulty: Beginner+ (a lil’ bit of experience w/ coding and circuits is helpful)

Read Time: 10 min

Build Time: ~ 2 hrs

Cost: ~ $35

Materials

  • Wand!
    • You can purchase custom wands or make your own! Find a suitable stick and add some flair (or leave it bare!), or get creative and make one out of things you can find around the house!
  • Feather (for floating!)
  • Glove (for hiding the micro:bit wand controller)
  • Aluminum can
  • Small piece of cardboard (~ 2″ x 2″/5cm x 5cm)

What are we doing??

One of my favorite scenes from the first Harry Potter book was when, after all of the other students are struggling, Hermoine makes a feather float with the spell Wingardium Leviosa. This simple spell captures the essence of why we love magic: that literally at the flick of our wrist and a few choice words, we can instantly make surprising (and impressive) things happen.

Although we don’t have exactly that kind of magic, we do have technology that sometimes seems miraculous. So that sort of counts!

By now you’ve probably guessed: To mimic my fav scene, I wanted to levitate a feather. For that, we can use the power of wind! For this beginner-friendly tutorial, I chose to use a small 5V DC motor with fan blades made from an aluminum can. You can imitate my design or, better yet, create your own!

This tutorial will show you how to do the following:

1. Write a simple block-based code for a micro:bit wand controller

2. Build a circuit to control a small, 5V DC motor

3. Write a simple block-based code for a magical receiver that is triggered with a radio signal (aka bluetooth)

4. Build a setup to make our tech really look like magic!

 

Code it: Wand Controller!

Let’s start with our magic wand!

Since this is a beginner-friendly project, we are using block-based coding on the Make Code website. If you have more experience w/ coding you can also program the micro:bit using micropython or C++ in your fav coding environment (e.g. Idle, Visual Studio Code, etc.).

Alright, let’s get blockin’!

Step 1: In the On Start block, set the Radio Group number. 

Pick a number you love and will remember, since we’ll also need this for the receiver.

Step 2: Decide how you want your wand to trigger action.

The micro:bit has an accelerometer which measures changes in acceleration in our three spatial dimensions: up/down, left/right, and forwards/backwards.

Quick solution: Use the “on shake” block! (Code 1, above photo)

More complex, gesture-based solution: Explore how the accelerometer works and observe the output as you make gestures (open the Arduino IDE Serial Monitor to see the output, if you need help with this check out this tutorial). Use your observations to set triggers. (Code 2 in the above photo)

The example in Code 2 is my attempt at a Wingardium Leviosa gesture: swish-and-flick! (down and left) Use it as-is or as a starting point for your own fav magical gesture!

Helpful Tips:

(1) Since microcontrollers process information super quickly, the pause block gives us time to finish the first part of the gesture before the micro:bit checks for the second part.

(2) I added axes labels on the micro:bit so I could more easily figure out how to get the right motion for Wingardium Leviosa spell — definitely recommend this!

Step 3: Use the gesture to send a radio number.

The “radio send number” block is found in the “radio” block set. Any (rational, real, non-infinite) number will work!

Step 4: Download and save the code onto the micro:bit!

The micro:bit power lights will flash as this is happening, when they are done flashing the code is finished uploading.

Build it: Magical Receiver!

Grab your second micro:bit, your breadboard, and all the fun electronic parts and pieces!

Step 1: Insert your MOSFET transistor into the breadboard.

Recommended to have the black part of the transistor facing you so that pin references in these instructions are accurate 🙂

Step 2: Grab one of your pin-ended alligator clips and connect it from micro:bit pin P0 to an open row in the breadboard.

Step 3: Connect your resistor between the micro:bit P0 wire and the MOSFET Gate pin (leftmost pin).

Step 4: Connect a pin-ended alligator clip between micro:bit GND pin and the MOSFET source pin (rightmost pin).

Step 5: Using your two remaining pin-ended alligator clips, connect the motor leads to two open rows in the breadboard.

Step 6: Connect your jumper wire from one of the motor wires to the MOSFET drain pin (middle pin).

Step 7: Connect your diode across the motor terminals so that the negative side (w/ the stripe) connects to the remaining motor wire (yellow wire in photo).

Step 8: Connect the negative (black) battery lead to the MOSFET source pin (same row as micro:bit GND).

Step 9: Connect the positive (red) battery lead to the remaining motor wire (yellow wire).

Code it: Magical Receiver!

Step 1: Set Radio Group to be the same as for the Wand Controller.

Step 2: Pull out a “on radio received” block and set it to “receivedNumber”.

Step 3: Drag a repeat block into the “on radio received” block and switch it to repeat 2 – 3 times.

Step 4: (Optional but recommended) Show an icon on the micro:bit to let you know if it received the string.

This is super duper helpful for debugging.

Step 5: Turn on Digital Pin 0! (aka “digital write pin P0” to 1)

This block is found under the “Pins” block under the Advanced tab.

Step 6: Pause for a few seconds.

I chose 4 seconds, you can keep this or adjust as desired.

Step 7: Turn off Digital Pin 0 (“digital write pin P0” to 0) and the micro:bit display.

Step 8 (Optional but recommended): Add a back-up trigger using micro:bit button A for testing and debugging purposes 🙂

Voila! Download the code onto your Magical Receiver micro:bit and we’re ready for the magical prop!

Let’s make wind!

Let’s make a wind generator!! AKA a fan 🙂 Turn on a hot glue gun and grab your scissors, permanent marker, aluminum can, and some cardboard.

Step 1: Carefully cut out a rectangle of aluminum from an empty can and a small circle of cardboard about 1/2″ (1 cm) in diameter.

 

Step 2: Print out the paper fan template above at 50% to scale. Cut out one of the fan blades and trace it five (5) times onto the aluminum foil.

Step 3: Carefully cut out the aluminum fan blades and glue onto the cardboard circle at equal intervals.

Step 4: Glue the motor mount onto a piece of cardboard (I also added “legs’ made of wooden dowels to make it easier to connect the alligator clips).

Other options:

  • Use the motor drive shaft to spin objects or make some gears/levers to move things in different directions
  • If you connect micro:bit to speakers, it can also play sounds!
  • Start with something simple and play around to find something that makes you feel magical.

Test all the things!

And now, for our favorite part: testing!! Power up your micro:bits (and connect the battery) and move your wand controller (or use the quick button trigger) to test that our magical receiver moves the motor.

When you are done testing, coat the magical receiver connections in hot glue to hold them in place. If you want an ultra-permanent solution, use epoxy (waterproof is a nice bonus feature). Be careful to avoid getting glue (and especially epoxy) on your micro:bits so that you can still use them for future projects!

Note: When you first power everything up, the motor may start spinning without a signal. Trigger the wand controller and it should stop, then behave as expected.

Not working as expected?

Debugging is an almost inevitable part of building things, so congratulations! You are officially a maker! Here are some debugging tips:

1. Power is the most common issue for makers of all experience levels. Double check that the battery is properly connected and both the micro:bit power lights are on (those little yellow lights by the microUSB port).

2. Motor not moving? Be sure none of the wires or other objects are in the way.

3. Motor pulling the feather towards it rather than away? Swap the orientation of the motor leads. This will cause the motor to spin in the opposite direction and thus the air will be pushed in the opposite direction.

Make all the magic!

We’re basically wizards now! Use gloves to hide and hold the micro:bit wand controller and battery pack. Hide your magical receiver in a fantastical container to really impress all the people. I snagged a hollow book stack, cut a hole in the top, and glued my motor with the fan inside.

That’s it! Practice your spell and impress your friends with your new-found powers.

Questions, comments, creations? Leave a comment! Happy making, you magical beings!

DIY Custom Light Performance

The motivation for this project was to create a controller that allows users to “play” light like it is an instrument with gesture control, custom visuals, and brightness/speed dials.

Considering how pricey consumer light controllers can be (often $100 bucks or more- not including the lights!) we decided to make a cheaper, more customizable solution! One aspect of this project that we were particularly excited about was the low barrier to entry. Most users pick up the controller in 2-3 songs, unlike other light toys (gloving, poi, ect) that require a much larger practice investment.

Here is our approach, you are welcome to use as-is or modify the project for all of your wild and wonderful needs!

Build Time: 2-3 hours 

Estimated Cost: $80 of materials

Project Materials

Case/Mounting Board (I used a wood box from a craft store)
Seeed Grove Sound Sensor v1.6 (Optional- Not used in this version)
Addressable LED Strips (2-3)
Rotary Potentiometer (2)
Digilent Pmod KYPD
Ultrasonic Rangefinder
Arduino UNO

Project Tools

Dremel
Soldering Iron
Hot glue gun

Build Overview

Design Considerations

One of the challenges with a project like this is the number of buttons it needs. Even in my more conservative designs, I wanted to have around 8 buttons to manage the different visual sequences, color palettes, and other mode selection. Wiring up that many buttons can be tedious and adds more points of failure. Additionally, the Arduino Uno board has a limited number of digital inputs. Luckily, the Pmod KYPD solves both of these issues!

The Pmod KYPD’s small form-factor allows it to fit neatly onto any baseboard without taking up too much space. I am using a free wood sample I got from my local hardware store as my mounting panel.

Electrical Schematic

Build Process

1. Start by connecting the Pmod KYPD to the Arduino Uno digital pins as shown in the above Fritzing diagram.

2. Next, wire in your potentiometers to Analog Pins A5 (brightness) and A4 (speed).

3. Attach the LED Strips to Ground and 5V, then wire both signal pins into Digital Pin 11.

4. Wire up the sound sensor to power and ground, and the white wire to A1 and yellow wire to A0.

If you do not have the connecting cable as a reference, the yellow wire is the outside one, and more documentation on the sensor is here. For the Ping sensor/Ultrasonic rangefinder Trig is on Digital Pin 13 and Echo is on Digital Pin 12 (in addition to power and ground of course).

5. The PmodBTN is wired to Analog Pin 0-4, along with ground and power.

Code

1. Download the 2.0_Code.

2. Activate the  FastLED and Keypad library (both found in the Arduino IDE library manager).

Keypad is not listed first when you search for it, you will have to scroll down until you find the one by Mark Stanley and Alexander Brevig.

3. Copy and paste the code into the Arduino IDE and click upload. Now it is time to play around with the board!

Note: Buttons 3 and 4 are attached to the ping sensor so try putting your hand over the sensor when you activate those visualizers.

Read through the code and our comments to see where you can make changes or add in new features. Have fun and feel free to expand this project to add more visualizers, sensors, ect!

More information

We updated the code and added more functionality, download LEDController_2 if you want the additional features. This code also requires the FastLED and KeypadUpload libraries.

In the new code the visualizers are:

  1. Flow
  2. Waterfall
  3. DoubleBounce
  4. Hand Bounce
  5. Levels
  6. Center Levels
  7. Blob
  8. AmbientSpots
  9. Segments
  10. Pulse

The numbers correspond to the visualizers and the letter to color palettes.

For the PmodBTN module, the effects are the following:

  • Top Right: Strobe
  • Bottom Right: Bounce Out (Double Bounce Single Sequence)
  • Bottom Left: Pause
  • Top Left: Not Set

Effects are temporary animation sequences that interrupt the current visualizer. They perform a single loop, then the current animation resumes. The one exception is the pause button, which requires you to unpause or skip out of it using a different effect.

Mechanical Design:

For our final version, we took a hollow wooden box from a local craft store and placed/traced out each component on the box. Then we dremeled a hole under the spot for the wires and set the Arduino inside the box. Finally, we mounted each piece with hot glue (after running the wires) and clipped the box shut with the metal clasp that came on it.

That’s it! Please let us know if you have any questions or issues and definitely share your creations with us!

Happy making!

Using Arduino for Citizen Science!

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

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

Difficulty Level: Beginner

Read Time: 20 min

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

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

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

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

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

What Is Arduino??

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

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

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

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

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

 

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

 

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

Tools & Materials

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

Tools

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

Materials

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

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

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

What Kinds of Sensors Can We Use?

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

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

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

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

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

Digital Sensors!

Part 1: the Easy Ones

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

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

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

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

Project 1: Tilt Switch Digital Sensor

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

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

Or you can just use mine!

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

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

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

Digital Sensors!

Part 2: PWM and Serial Communication

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

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

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

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

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

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

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

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

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

Project 2: Temp and Humidity Digital Serial Sensor

 

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

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

 

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

 

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

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

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

Analog Sensors!

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

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

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

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

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

Project 3: LED As a Light Sensor!

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

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

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

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

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

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

Here is a sample code to get ya started.

Visualizing Data: Arduino IDE!

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

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

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

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

Visualizing Data: Excel!

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

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

How to use the Data Streamer Add-In:

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

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

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

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

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

 

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

To add a Scatter Plot:

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

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

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

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

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

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

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

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

Go Forth and Measure All the Things!!

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

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

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

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

Raspberry Pi Impact Force Monitor

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

 

Read Time: ~15 min

Build Time: ~60-90 min

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

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

Suggested Reading

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

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

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

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

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

3. More about accelerometers!

4. Overview of the Raspberry Pi GPIO pins.

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

6. LIS331 Datasheet

Materials

 

Tools

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

But wait! What is Impact Force?

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

F = KE/d

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

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

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

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

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

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

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

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

Acceleration is a change in speed and/or direction.

Configure the Pi Zero W

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

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

Enable WiFi & I2C

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

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

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

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

Restart the Pi and Log in Remotely

We can now ditch the HDMI and peripherals, woohoo!

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

Build It! Electronics

Here’s the electrical schematic for this project:

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

And here’s the pinout for the Pi Zero:

Connect the Accelerometer to the Pi’s GPIO

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

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

LIS331 Breakout Board                     Raspberry Pi GPIO Pin

GND                                                 GPIO 9 (GND)

VCC                                                  GPIO 1 (3.3V)

SDA                                                   GPIO 3 (SDA)

SCL                                                   GPIO 5 (SCL)

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

Add an Alert LED!

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

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

Completed Electronics Setup

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

Program It!

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

For Folks New to Programming:

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

For Folks More Comfortable w/ the Technical ‘Deets:

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

All:

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

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

sudo apt-get install -y i2c-tools

Then run the i2cdetect program:

i2cdetect -y 1

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

Quick Overview of Program

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

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

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

Here’s what both data files look like:

Test the System!

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

cd path/to/folder

Run the program using root privileges:

sudo python NameOfFile.py

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

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

Secure Electrical Connections & Install It!

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

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

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

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

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

Embedding the Circuit in a Helmet

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

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

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

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

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

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

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

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

Deploy!

Power up the battery pack!

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

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

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

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

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

Adding More Features

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

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

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

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

Happy Building!

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

Make a Minecraft Gesture Controller!

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

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

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

Read time: 20 min

Build Time: ~ 2 hours

Cost: ~$30

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

Materials

Tools

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

 

Build the Glove Controller!

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

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

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

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

3. Attach CPX to the glove with velcro squares.

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

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

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

Plan out your controller!

 

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

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

1. Determine (crucial) game controls.

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

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

Movement:

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

Actions:

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

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

Here is my design thought process:

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

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

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

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

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

Let’s get programming: Set up the CPX!

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

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

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

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

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

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

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

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

 

Add all the libraries!

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

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

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

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

 

Writing the Controller Code

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

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

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

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

  • LIS3DH accelerometer

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

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

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

2. Configure and initialize the libraries.

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

3. Write short functions for each of the controls.

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

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

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

Debugging: Seeing what’s up the CPX program

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

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

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

1. Download PuTTY* here.

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

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

3. Open PuTTY and select “Serial”.

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

5. Click Connect! 

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

 

Test & Improve

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

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

Test 1:

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

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

Test 2:

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

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

 

Have all the fun!!

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

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

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

<3, jenfoxbot

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 🙂



			

Micro:Bit Puppet “Text Message” System

Intro

Nearly all of our wireless communication is done using radio waves*, including phone calls, text messages, and WiFi. With its built-in radio transmitters and receivers, the Micro:Bit microcontroller makes it super easy to build all sorts of projects with radio communication.

This particular project is a simple & quick way to send text messages between two Micro:Bit** microcontrollers – the sender writes a (short) message that is transmitted via radio to the receiving Micro:Bit, which shakes a lil’ puppet using a servo motor, and then displays the message on the Micro:Bit LED screen. Each Micro:Bit can be both a sender and receiver.

It’s sort of like a two-person Twitter.. if the tweet notified you via dancing cardboard robot puppet!

*Radio waves are long-wavelength light waves. Check out the electromagnetic spectrum here!

**A huge THANK YOU to Adafruit for donating the Micro:Bit microcontrollers used in this project for educational purposes! yayy thank you for supporting this educational endeavor!! 😀

Materials & Tools

Electronics

Puppet (or other Message Alert System) Materials

Tools

  • Hot Glue Gun
  • Scissors and/or utility knife (e.g. exacto knife)
  • Pencil
  • Ruler or other straightedge

Build the Incoming Message Alert Puppet!

Step 1: Build a cardboard puppet like the one shown in the photo or create your own! Use the paper fasteners to make joints.

Step 2: Build a mounting system to attach the puppet to the servo with skewers and cardboard.

I used a magnet to attach the puppet to the servo mounting system because magnets are awesome, but you can also use glue, tape, velcro, or a variety of other adhesives!

Step 3: Build a stand for the puppet.

  • On an approx. 6 in. x 12 in. cardboard sheet, measure, mark, and cut a hole for the servo body so that the arms of the servo rest against the front of the cardboard sheet.
  • Cut two triangles out of cardboard and glue them on the back of the stand so that the stand, well, stands upright!
  • Cut a hole for the Micro:Bit wires to thread through and add two pushpins on the front to hold the Micro:Bit.

 

 

 

 

 

 

 

Code the Two Micro:Bits!

To start, choose one Micro:Bit to be the sender and the other Micro:Bit to be the receiver. Once both are working as expected, add in the code for both roles.

Use the Make Code Micro:Bit website to program each Micro:Bit. As this is intended as a beginner project, the whole system can be built using the block-based programming language, although adaptations are encouraged and appreciated!

If there is more than one pair of Micro:Bits in the room (i.e. in a classroom setting), remember to set different radio group numbers for each pair.

The sender sends a (short) text based on user inputs over radio, like the example above. Pretty simple!

The receiver moves the servo when an incoming text is received, then scrolls the message text on the LED screen, like in the example below.

Press the reset button to stop sending/receiving the incoming message.

 

Connect the Servo!

Connect the servo red wire to the Micro:Bit 3V power pin, the servo black wire to Micro:Bit ground pin, and the servo white (or yellow) wire to the Micro:Bit input pin P0.

Send all the Messages!

Program both Micro:Bits to be both a sender and a receiver so you can communicate back and forth. Then switch power from the laptop to the battery pack and test out your wireless communication system! When the sender sends a message, the puppet will notify you to check the LED screen so that you can see the incoming message.

How far of a range can you get? Test it out!

There are tons of other extensions to this introductory project, here are some possibilities:

  • Add more message options by adding more inputs or changing how those inputs are read;
  • Instead of a table-top alert system, build a wearable alert system;
  • Send voice messages and/or other sounds.

Happy building!

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!

Make a Sneaky Wearable ‘State Change Switch’!

 

Secretly change settings for your wearable outfits or use this button as a secret prank trigger! Here’s a quick & easy tutorial on how to build and program a “state change switch.” AKA a button that cycles through different settings. It’s super easy and has tons of practical applications!

Read Time: ~ 5 min
Build Time: ~ 30 min
Cost: Super cheap (>$5)

Materials!

materials1-sm

— Glove (just one.. but you should probably wear two to avoid giving away the secret)

— Three (3) stranded wire segments (24/26 gauge), approx. 3 ft

Wires should be long enough to reach from your palm to wherever you want to hide the electronics. I hid mine in a belt pouch, but you could also opt for a pocket, backpack, etc.

— One (1) 10kOhm resistor

— One (1) pushbutton (aka momentary switch)

— One (1) 1″ x 1″ piece of thin wood

Those free wood swatches at hardware stores are perfect!

— Microcontroller

I used the SparkFun EL Sequencer b/c I was using this switch to select different settings for my Hallowen EL Wire costume. Check out the tutorial to learn how to build your own version of this costume, or you can use this state change switch with any ol’ microcontroller for your own awesome project!

 

Build it!

schematic_bb

buttonbase1-sm

1. Drill holes in a small piece of wood for the button feet.

resistor1-sm

2. Solder a wire to one of the button legs, and a resistor to the other button leg on the same side. Solder a black wire to the resistor.

3. On the other side of the button, solder a wire to the leg across from the resistor.

4. Test electrical connections, then coat all solder joints in hot glue.

buttonbase-bottom2-sm

5. Connect the black wire to the microcontroller ground, and the wire on the same side to the microcontroller voltage output (Vcc).

6. Connect the wire on the other side to a microcontroller digital (or analog) input pin (see schematic above), and then onward to programming!

buttonbase-solder-sm

 

Program it!

code-screenshot

Most folks that program state change switches use the modular, or mod, operator* to tell different settings apart. It’s not perfect, but for how little code is involved it’s a good way to cycle through different settings and get back to our original state.

Here’s a quick sketch that will allow you switch between three different settings by pushing the button. As is, it’s written to switch between three different digital output settings. In other words, if you have a motor connected to your microcontroller, the button will switch the motor from constantly on, to pulsing (i.e. repeatedly on/off), to constantly off, then back to constantly on.

*The mod operator (usually “%”) divides the number by the value after the operator and gives you the remainder. For example, if you see: 10%2, it means 10 / 2 = 5, which equals 0, since there is no remainder. Another example is 10%3, which equals 1, since 10 / 3 = 3.33, and 0.33 is one out of three. Here’s more info on this or feel free to leave a comment if you have any questions!

 

Finish & Test!

Connect the button wire leads to your microcontroller inputs, run the full program and test to see that it works as expected. If it’s all good, put the glove on and push the state change switch and watch as your costume/insertotherawesomeprojecthere changes through different settings!

Now go forth and show off your project around town!