Home Automation – SentryPi

Who left the garage door open?

We have a full house with a lot of activity and visitors.  There have been several times when the garage door is left open for extended periods of time.  While our Christmas decorations and paint supplies may not be a treasure most would be thieves would desire, it is still not the most comforting thing to think about leaving the garage open for all passerby to see.  I often thought it would be great to have a way to notify whoever is in the house that the garage is open.

Phase 1 – LED Indicator

I decided that my first step would be to design a way to detect “door open” by providing a simple indicator light.  I explored a few optical ways to do this (light beam, camera, reflectors) but quickly pivoted my approach when I found some unused microswitches.

I found a good place to detect “closed” on the main track.  I thought about piggybacking on the garage opener sensors but dismissed that as I didn’t want to risk an undesirable interaction with the opener and more importantly, I wanted to have the detection work even if power to the opener was interrupted.

This required that I build a bracket to mount the switch to and a ramp plate to compress the switch when the door was in the down position.

I used an aluminum sheet, cut with sheet metal snips,  bent and drilled holes to mount the microswitch and eventually attach it to the garage door track.  It took a few tries to get the right fit and right placement of the micro switch.

My first attempt destroyed the microswitch after a few uses.  The garage door track sled has a straight edge that collides with the microswitch roller. It created too much force on the small roller and eventually popped it loose.  To help with that, I added an aluminum ramp to the sled so that the microswitch roller would gently rise as the sled entered the “closed” position.

I decided to make the “door open” state be the closed circuit condition so that phase 1 of the project could start as a simple LED circuit indicator.

I attached the switch and drilled some pilot holes and mounted the bracket to the garage door track right above the sled when the door is in the closed position.

I added a 9V battery, a 470 ohm resister and a red LED to the circuit.  To complete this phase, I ran the wire from the garage to our entry hall and mounted an LED and housing above the HVAC controls.  Now we can all see the brilliant red LED glowing when the garage door is open.  That covers some of our use cases but I also want a more proactive notification.  Now on to phase 2…

Phase 2 – Raspberry Pi – Home Automation Sentry

Now that I have a working “door closed” sensor and indicator, I am ready to add the proactive home automation component, specifically the Raspberry Pi (RPI).  It just so happens that I have a spare RPI Model 3 that needed a project, and I wanted to experiment with AWS IoT services.

I used the RPI to detect the state of the switch. To do that, I will need to wire the circuit into the RPI’sGPIO headers.  I decided to use GPIO Pin 23 and the adjacent ground (GND) pin.

Here is the code that is used to detect the closed circuit (indicating an open door):

#!/usr/bin/python

##  
## Garage Door Sentry - RPI script to monitor door
##  

## load libraries
import RPi.GPIO as io 
import time 

print "Garage Door Sentry\n\n"

## set GPIO mode to BCM - allows us to use GPIO number instead of pin number
io.setmode(io.BCM)

## set GPIO pin to use

door_pin = 23
print "Sentry Activated - Watching: GPIO 23"

## use the built-in "pull-up" resistor
io.setup(door_pin, io.IN, pull_up_down=io.PUD_UP)  # activate input

## States for door: 0=closed, 1=open, 2=init
door=2
## infinite loop
while True:
    ## if switch is open
    if (io.input(door_pin)==True and door!=0):
        door=0 
        print "Door closed"
        # do some action
    ## if switch is closed 
    if (io.input(door_pin)==False and door!=1):
        door=1 
        print "Door open"
        # do some action
    time.sleep(1) # 1 second wait

The next step was to connect to AWS IoT to record this sensor data and send alert messages to my phone.

The following will help you set up your Raspbery Pi as a platform to install the SentryPi scripts.

Required:

  • Raspberry Pi – B+, 2 or 3
  • Wifi Dongle or Network Cable configured
  • SD card (Recommend: 16GB or larger)
  • AWS Account (IoT, DynamoDB)

Read the details on this GitHub Project: https://github.com/jasonacox/SentryPi

The project describes how I added these additional features:

  • Sentry Alert – Send a text message to contacts when an alert condition is reached.
  • Dashboard – Provide an automation dashboard for realtime status.
  • Other Sensor Data:
    • Temperature Sensors
    • Barometric Pressure Sensor
    • Humidity Sensor
    • Motion Sensor

To set up a web based dashboard, I decide to use static HTML, CSS and JS (jQuery, Chart.js and the AWS JavaScript SDK) so it can be hosted on a simple S3 bucket, a web server, or the RPi itself.  See here for the code. 
SentryPi Dashboard
SentryPi Dashboard - Garage Door Graph

Raspberry Pi – AirPiano

Wouldn’t it be cool if you could control your MIDI equipped digital piano from your iPhone?  Imagine a player piano capable of jukebox queuing up MIDI or Audio files and playing them in order.  That was my goal!  RPI to the rescue.

RaspiModelB

Required Ingredients:

  • Raspberry Pi – Model B, 512MB RAM, 16GB SD Card, Raspbian Linux, Apple 12W USB Power Adapter, USB WiFi Dongle
  • USB MIDI Digital Device (e.g. Yamaha Clavinova CLP-440 with USB MIDI port and RCA L+R Audio Inputs)
  • Software:  Apache HTTP Server, PHP, MySQL, (Nice to have:  Netatalk file server, Shairport AirPlay server)

Instructions:

My original thought was to turn the Yamaha speakers into a AirPlay device for our many iOS devices.  It’s nice to pipe in background tunes without having to hook up a device.  AirPlay is great way to do that but I didn’t want to spend $100+ to be able to do that.  The Raspberry Pi is more than capable of doing this. I found an extremely helpful blog post here:  http://www.raywenderlich.com/44918/raspberry-pi-airplay-tutorial

NOTE: Power is a big issue for the Raspberry Pi.  If you are using a WiFi dongle or any other USB device, I recommend making sure your power supply has enough kick to keep the RPI going.   I started out with a microUSB adapter that advertised 700mA but performance became very unstable, especially under load.  I switched to a 12W Apple adapter that I had handy and the problems disappeared.   The RPI FAQ recommends 1.2A (1200mA).

Setup for AirPiano – MIDI Control

The Project Code: https://github.com/jasonacox/raspberrypi

  • MySQL: Database ‘piano’ – see piano.sql file
  • Dequeue Service: Run the cron.sh script to have the RPI scan for new midi or wave files to play. Run it with:
bash -x cron.sh 0<&- 1>/dev/null 2>/dev/null &
  • Apache: Install apache http with mod_php and mysql support
  • Website Code: Install index.php, setup.php and the folder.png files into the document root of your webserver. Upload the MIDI (*.mid) and WAVE (*.wav) files to this location. Be sure to update $globalBase in setup.php to the folder where these files are located.

 

AirPlay via Raspberry Pi

Adam Burkepile has the best tutorial I’ve found on how to set up a RPI for AirPlay:

http://www.raywenderlich.com/44918/raspberry-pi-airplay-tutorial

Apple Share (AFP) Server via Raspberry Pi

The RPI is great for a tiny file server!  At the least, having it run an AFP server will allow quick drag and drop transfer from your Macs.  A Samba service for Windows shares is easy to set up as well.

sudo apt-get install netatalk

Yes, it is that easy.  Finder will now show your Raspberry Pi under “shared” along with any other local network shares:

Screen Shot 2013-12-27 at 11.22.08 PM

 

 

 

 

Simple LED Flasher using Transistors

Simple LED Flasher Project

I wanted to put together a simple two LED flasher circuit that would use the fewest parts and low power.  My first project of this type used the NE555 timer IC but besides the chip, it requires more power than what I would like to use.   Using a couple low-power NPN transistors, the circuit should be able to run for hours on a 9v battery.

The Circuit

I decided to use two 2N3904 transistors (a low power NPN transistor).  This design uses only 10 components but I added additional resistor to inline with the power source.  It could be removed and the other resistors adjusted to lower the power.

I used a free copy of LTSpice from Linear Technology to create the circuit (most SPICE packages do not have LED components for some reason) – you can download it here:  http://www.linear.com/designtools/software/ltspice.jsp

Which LED will light first?

The Breadboard

I assembled the circuit using a low cost breadboard I picked up at Fry’s Electronics.   Using a breadboard allowed me to play around with different components, especially the capacitors and resistors to tweak the flash rate and brightness.

Single LED Flasher

The simplest single LED Flasher circuit I have found uses a single transistor (NPN), 2 resistors and 1 capacitor.  This circuit uses the transistor as a Negistor using the NDR (negative differential resistance) effect.  The transitor will block current until the voltage threshold charging on C1 reach something close to 9v, at which point the voltage will become large enough to get the emitter-base junction to avelanche and drain the current through the LED.

Click here for the video:
http://jasonacox.com/images/IMG_2022.MOV

Reference

http://wild-bohemian.com/electronics/flasher.html

http://en.wikipedia.org/wiki/2N3904

http://www.linear.com/designtools/software/  (LTspice – Nice circuit design tool based on Spice)

http://jlnlabs.online.fr/cnr/negosc.htm

http://www.cappels.org/dproj/simplest_LED_flasher/Simplest_LED_Flasher_Circuit.html

To Engineer is Human

To Engineer is Human: The Role of Failure in Successful Design by Henry Petroski

This is a great book to remind us of the purpose of engineering and the dangers we face when designing technical bridges (and physical ones) across the unknown.

Petroski wrote this in the early 80’s and the examples and illustrations are sometimes dated but still practical. I found the section on computers, “From slide rule to computer” to be particularly interesting.  His case still hold true for the faster/newer techno-driven culture of the 21st century.

We have come to be a society that is so quick to change that we have lost the benefits of one of mankind’s greatest tools–experience.   – Henry Petroski

Engineering is very dependant upon feedback for improvement.  The goal of providing a design solution for the lowest cost will mean that materials, processes and other costly items will be minimized to achieve the most economical/efficient solution.  Unfortunately, there are things that we do not know about (the trite, “we don’t know about what we don’t know” phrase comes to mind) that can be or become significant issues in the design.  The Tacoma Narrows Bridge is a great example of this.

Engineering attempts to introduce “safety factors” into the design model to cover for the unknowns but this can often be inadequate, as was the case of the walkway collapse at the Kansas City Hyatt Regency Hotel.

Failures, while unfortunate and often deadly, should also be opportunities for improvement.  Petroski argues that it is important that details of failures be broadcast to provide corrective feedback to all engineers so that future designs will build on these learnings.

iWoz: Computer Geek to Cult Icon

This autobiography of Steve Wozniak is a delightful recount of the birth of the personal computer. 

Before cell phones that fit in the palm of your hand and slim laptops that fit snugly into briefcases, computers were like strange, alien vending machines. They had cryptic switches, punch cards and pages of encoded output. But in 1975, a young engineering wizard named Steve Wozniak had an idea: What if you combined computer circuitry with a regular typewriter keyboard and a video screen? The result was the first true personal computer, the Apple I, a widely affordable machine that anyone could understand and figure out how to use.

Wozniak’s life—before and after Apple—is a “home-brew” mix of brilliant discovery and adventure, as an engineer, a concert promoter, a fifth-grade teacher, a philanthropist, and an irrepressible prankster. From the invention of the first personal computer to the rise of Apple as an industry giant, iWoz presents a no-holds-barred, rollicking, firsthand account of the humanist inventor who ignited the computer revolution. 16 pages of illustrations.

Six Not-So-Easy Pieces: Einstein’s Relativity, Symmetry, And Space-Time

This sequel to Richard Feynamn’s Six Easy Pieces grabs six more additional lectures from his famous three-volume series, Lectures on Physics.  In this book, Feynman unfolds the complexity of Relativity, Symmetry and Space-Time.   As is typical for his style, he makes these very complex subjects approachable, but then drives deeper to reveal the mathematics behind the mysteries.   The narrative and related equations are definitely geared toward math and science students. 

As is his genius, Richard Feynman often unpacks complex concepts through the use of practical analogies.  His description of curved space in Chapter 6 was one of my favorite sections (p. 112). 

Curved Space

In order to understand this idea of curved space in two dimensions you really have to appreciate the limited point of view of the character who lives in such a space.  Suppose we imagine a bug with no eyes who lives on a plane, as show in Figure 6-1.  He can move only on the plane, and he has no way of knowing that there is any way to discover any “outside world.” (He hasn’t got your imagination.)  We are, of course, going to argue by analogy.  We live in a three-dimensional world, and we don’t have any imagination about going off our three-dimensional world in a new direction; so we have to think the thing out by analogy.  It is as though we were bugs living on a plane, and there was a space in another direction.  That’s way we will first work with the bug, remembering that he must live on his surface and can’t get out.

As another example of a bug living in two dimensions, let’s imagine one who lives on a sphere.  We imagine that he can walk around on the surface of the sphere, as in Figure 6-2, but that he can’t look “up,” or “down,” or “out.”

Now we want to consider still a third kind of creature.  He is also a bug like the others, and also lives on a plane, as our first bug did, but this time the plane is peculiar.  The temperature is different at different places.  Also, the bug and any rules he uses are all made of the same material which expands when it is heated.  Whenever he puts a ruler somewhere to measure something the ruler expands immediately to the proper length for the temperature at that place.  Whenever he puts any object–himself, a ruler, a triangle, or anything–the thing stretches itself because of the thermal expansion. 

Feynman uses this constructed analogy to explain how the bug would get different measurements in each of these “worlds.”  The bug is able to determine what type of world it lives in based on the measurements.  It is interesting to see through his example that the bug on the sphere experiences the same measurements as the bug on the temperature varying hotplate (both can measure a triangle with an angle-sum of 270 degrees where the bug in the plane would see a maximum sum of 180 degrees).  Scientist speculate on the “space” curvature of the universe by conducting experiments.  So far, it is inconclusive.

In this book, Feynman also covers a refresher course on Vectors (Ch. 1), discusses the Symmetry in Physical Laws (Ch. 2), does a detailed analysis of The Special Theory of Relativity (Ch. 3), Relativistic Energy and Momentum (Ch. 4), Space-Time (Ch. 5), and Curved Space (Ch. 6).

Realativity

The Special Theory of Realativity (p. 49) is a facinating approach to motion that for over 200 years was ruled by equations developed by Isaac Newton.   In Newton’s Second Law, 

which is the same as F=ma (where a is acceleration or the time derivative of velocity, dv/dt), the assumption is that mass (m) is a constant.  Einstein corrected this formula with his theory by saying that mass has the changing value,

where mo is the “rest mass” of a body when it is not moving and c is the speed of light (186,000 mi/s or 3×10^5 km/s).

Faster than the Speed of Light

Dr. João Magueijo presents a theory that allows for variable speed of light (VSL).   This is a rather controversial subject as it deals with a value in physics that has traditionally been constant (c, the value of the speed of light, 186,000 mps or 300,000 kps).  The speed of light is the underpinnings of Einstein’s theories of special relativity, as seen in the famous E=mc² equation.

The Book

While dealing very little with the science of theory itself, João does provide a very entertaining look at the often painful, slow and bureaucratic scientific process.  He spends considerable time presenting the histories and struggles of scientist like Einstein as well as his colleagues.  These narrative backdrops are used to provide contrast and similarities to his own scientific speculation.  These also provide the basis for the bipolar challanges against and support for VSL.

The Theory

João proposes that the speed of light is dependant upon energy or space-time.  He postulates that during the moment of creation, the high energy big bang of those intial moments could well increase the speed at which light travels by sixty orders of magnitude (that is 1 with 60 zeros).  This could explain the horizon problem of cosmology and propose an alternative to cosmic inflation.  This would reveal itself near black holes or cosmic strings.

The Scientist

Dr. João Magueijo received his doctorate from Cambridge, has been a faculty member at Princeton and Cambridge, and is currently a professor at Imperial College, London.   A lecture from João can be found here: http://forum.wgbh.org/wgbh/forum.php?lecture_id=3195

João writes, “we do not notice energy, but only variations in energy.”  He concludes the book by saying, “It’s difficult to sum up where VSL stands, as I finish this book… VSL is now an umbrella for many different theories.”

Links

VSL: http://en.wikipedia.org/wiki/Variable_speed_of_light
Speed of LIght: http://en.wikipedia.org/wiki/Speed_of_light

Robotics

The LEGO mindstorm robotics kit is a popular programmable controller that can allow kids and adults alike to enter the world of robotics.  I am currently playing with a few free software programs that my friend found that let you simulate virtual robots, including the mindstorm.

LEGO Mindstorm

LEGO Digital Designer – Just for fun, build something!

Microsoft Robotics Developer Studio – This allows you to model a virtual robot and world, complete with controls to maneuver your robo-friend.

Modeling Programs we are investigating to see if they can be used to construct virtual robots or the worlds they live in:  Wings3d, Silo3d, Blender3d

Mindstorm blog:
http://thenxtstep.blogspot.com/

 

Richard Feynman

Richard Feynman is Nobel prize winning physicist and famous communicator.  I put together a collection of YouTube Feynman videos: 

Transcript:

I have approximate answers and possible beliefs about different things, but I’m not too sure of anything. The many things I don’t know anything about, such as whether it means anything to ask why we’re here and what the question might mean, I might think about a little, but if I can’t figure it out, I go into something out. I don’t have to know an answer, and I don’t feel frightened by not knowing things. Being lost in the mysterious universe without having any purpose is the way it really is, as far as I can tell. Possibly, it doesn’t frighten.

I have a friend who’s an artist, and sometimes taking a view which I don’t agree with very well. He holds up a flower and says, “Look how beautiful it is,” and I’ll agree, but he says, “You see as I, as an artist, can see how beautiful this is, but you, as a scientist, take it all apart and it becomes a dull thing.” I think that he’s kind of nutty first of all. The beauty that he sees is available to other people and to me too, although I may not be as refined as he is. I can’t appreciate the beauty of the flower at the same time as I see much more about the flower than he sees. I can imagine the souls in there, the complicated actions inside, which also have a beauty. It’s not just beauty at this dimension of one centimeter; there’s also beauty at a smaller dimension. The inner structure, the processes, the fact that the colors and the flower are evolved in order to attract insects to pollinate it is interesting. It means the insects can see the color, which adds a question: is this aesthetic sense also exist in the lower forms? Why is it aesthetic? All kinds of interesting questions which science knowledge only adds to the excitement and mystery in the aura of a flower. It only adds to the excitement and mystery, but I don’t understand how it subtracts.