Sunday, July 13, 2014

The R2D2 Project - The vision


I have always wanted to build a robot like  R2D2 (who hasn't right?) , so I recently purchased a used Hasbro Interactive R2D2 like this one. I did not expect it to work and I got pretty much what I expected. It powers on and responds to the "Hey R2" command but that is about it. I am going to change most of the electronics in it anyway so I wasn't too concerned.

Time to take it apart!  There are already quite a few comprehensive documents and videos on how to disassemble the R2D2 online so I am not going into the details here.

R2 uses 4 AA batteries for the 2 PCB boards inside and 4 DD for running the 3 motors (2 for the legs and one for the rotating dome). The power board looks like this.


















Main control board (left). After the dis-assembly (right).





















Here is what I intend to do. Note that this is all in-flight, so the plans are subject to change.

Hardware:
1) Re-use the 4 AA for motor control.
2) Re-use the speaker and potentially the multiple mics
3) Re-use the LEDs for the dome
4) Add an Intel Galileo as the main brain for the robot
5) USB webcam w/ audio
6) PIR sensors/Ultra-sonic range finder

Software:
1) Yocto (Intel IOT Devkit Version)
2) Speech recognition via Google speech to text API
3) OpenCV for object recognition
4) Motion (If you have read my other posts, you know that I love using this)

Monday, February 10, 2014

Raspberry Pi Home Security + Automation - Phase 3

In Phase 1 and 2 of my previous posts in this series, I showed the basic setup of a Home security  +  automation system. No home security system is complete without a siren/alarm so this posts addresses that.

I was looking for a way to trigger the alarm and wanted it to be completely isolated from the Pi GPIO to avoid false triggers.  I also wanted to avoid using more GPIO for this project so I decided to a 433Mhz wireless siren similar to the one on Ebay here

If you open up the wireless strobe siren you will find this:


There is a small switch on the PCB to switch the circuit on/off. A white wire goes from the board to the piezo siren. For initial testing, I would recommend disconnecting the siren so that you can verify that your system works correctly without the really loud (90 dB) siren.

A 433MHz transmitter accompanies the strobe/siren to trigger it. I wanted to decode the code sent by this to allow me to trigger the siren myself. So I hooked it up to a 12V battery below and pressed the test button (see picture below).


The receiver already connected to the Pi (as shown in Phase 1) will help you find the code for your siren module. (use RFSniffer provided on the ninjablocks website to do this)

Here is a  short video showing the system in action.

Note - 
  • The 433 MHz door/window sensor  shown here is actually one that is normally connected to my  door/window and is not the one provided for triggering the siren. 
  • I have removed the waits in the code to trigger the siren immediately for the purpose of this video. You would normally have a delay to allow system disarm by an authorized individual


video

Thursday, January 16, 2014

Raspberry Pi - Controlling 433 MHz remote outlets

In my previous post here, I tried to use a cheap 433 MHz transmitter to replicate the 433 MHz remote functionality but landed up hacking the remote to send the codes instead. The main issue I was facing there was that the code was not being recognized by the RF outlets.

I was finally able to resolve that issue so I just need one GPIO pin to control all my RF remote outlets now!

Troubleshooting my original issue:

I am using this receiver and transmitter - 433MHz Tx-Rx pair (set of 2)








I was using the RCSwitch library ported over to the Raspberry Pi from here
http://ninjablocks.com/blogs/how-to/7506204-adding-433-to-your-raspberry-pi

As mentioned in my previous post, I first tried using the Audacity route but I could not decode the data correctly.

Since I had an Arduino lying around as well, I downloaded the RCSwitch library for the Arduino and tried the advanced receiver demo.

The output for one switch of my remote looked like this:
Protocol: 1
Decimal: 1398209
binary: 000101010101010111000001
PulseLength: 207

I noticed that the pulse length was 207 which is different from the default length in the code. I quickly changed the pulse length in the send demo sketch on the Arduino and was able to get the RF outlet to switch on!

So I went back to my Raspberry Pi and modified the send.cpp code to look like this:
int main(int argc, char *argv[]) {
    /*
     output PIN is hardcoded for testing purposes
     see https://projects.drogon.net/raspberry-pi/wiringpi/pins/
     for pin mapping of the raspberry pi GPIO connector
     */
    int PIN = 0;
    unsigned long code = atoi(argv[1]);

    if (wiringPiSetup () == -1) return 1;
        printf("sending code[%d]\n", code);
        RCSwitch mySwitch = RCSwitch();
        mySwitch.enableTransmit(PIN);
        mySwitch.setPulseLength(207);
        mySwitch.send(code,24);
        return 0;
}

Note: I have removed the header files for a cleaner code look below. Please include them in your actual code if you want to use the code below.



I have the transmitter data pin connected to the Pi pin 11 (GPIO 17). I re-ran make in the dir and sent the previously decoded code:
sudo ./send 1398209

And it works! Good riddance to the multiple GPIO pins to replicate the remote functionality +  the remote is free for use independently now.


Monday, January 6, 2014

Arduino Yun - Introduction + Controlling GPIO via a web server

My Arduino Yun arrived over the weekend and I was surprised by how small it was compared to my Pi or Galileo. It is roughly the size of a credit card (see below).



Some of the things I really like about this:

  • Built in Wifi, micro SD card reader and  Linux OS (Linino)
  • Small form factor - ideal for applications that I am interested in like robotics and home automation
  • Easy Wifi setup in any new location
  • Ability to program sketches over Wifi and use the console terminal wirelessly to see events happening in the sketches.

This is a great guide to get started: http://arduino.cc/en/Guide/ArduinoYun. I used it to setup WiFi and allow open REST API access.

My first goal was to set up a USB webcam and install motion on my Yun. I achieved this by using the package management to install the necessary driver and packages
opkg install kmod-video-uvc motion

I plugged in my webcam via a USB hub and I was happy to see that it showed up after using dmesg and lsusb.

I started up motion and was able to see that it streams to a Firefox browser seamlessly. Goal #1 accomplished.

Next, I wanted to use a web browser to control GPIO to enable my next project which is a web controlled robot. So I wrote a simple sketch that uses browser buttons to turn the on board LED on and off. The sketch can be downloaded  here.

To get this to work I had to do one step that was not clearly documented anywhere. I had to manually create a soft link in my /www/ folder for sd:
ln -s /mnt/sda1 /www/sd

Another key thing to note here, is that your sketch folder needs to have a www sub folder with the index.html and zepto.min.js file in it. When your sketch is uploaded via WiFi, the contents of the www folder and automatically copied to /www/sd/<sketchname> folder

The REST calls to /arduino are made from the index.html file. To undestand what the REST API is, I would encourage you to read up on it in the getting started URL mentioned above.

If you view the source of the html, you will see this:


<script type="text/javascript">

    function ledon()
   {
       $('#content').load('/arduino/ledon');
   }
   function ledoff()
  {
      $('#content').load('/arduino/ledoff');
  }

</script>


It basically passes the ledon/ledoff commands to the Arduino once the buttons are pressed. The sketch simply looks for this and manipulates the GPIO:


if (command == "ledon") {
       digitalWrite(13, HIGH);
 }

else if (command == "ledoff") {
       digitalWrite(13, LOW);
}

After you have uploaded the sketch over to your Yun, you can use any browser to go to http://your_yun_name.local/sd/webled

You should see these buttons which will allow you to control the on board LED.


Hope this helps others who are trying to attempt something similar.

Monday, December 23, 2013

Raspberry Pi Home Security + Automation - Phase 2

Update: I was able to get the RF outlets to work using a cheap transmitter from Ebay. So the below method is just here for documentation purposes.Check out my post here

I added more functionality to my system described in my earlier post here. As part of phase 2, I added internet controlled outlet/switch control via the Pi. This is an easy way to convert an RF outlet switch to a web controlled one.

I picked up a remote + 3 RF outlet switches  (433Mhz) from Ebay which are manufactured by DB-Tech.

Remote control outlet switch socket









There is a single button to toggle the outlet on/off. My initial intent was to use a RF receiver to decode the code sent by the remote and replicate it. I tried several methods including the ones outlined here to use your PC soundcard + Audacity to decode your waveforms, but my attempts were unsuccessful.

So I opened up the remote and it looks like this: (ignore the wires - that is something I added, as you will see later in the post)



It uses 3 simple buttons and a PT2262 Encoder. It comes with 12V battery to power it. The datasheet of the encoder can be found here. I noticed that the supply voltage is rated at 4-15V and I tried to power the circuit via the Raspberry Pi GPIO. I was pleased to discover that it works for voltages slightly below 4 as well!

So I soldered  3 wires to the switches by tracing the pins that would be normally be connected to the +ve of the 12 V supply.  The other end of the wires are driven by 3 Pi GPIO. I used a crocodile clip to connect the Pi GND line to the -ve supply of the circuit (normally connected to the battery -ve).




This solution does not scale too well with the number of outlets, so I have to find something better eventually.

The next steps are pretty straightforward and involve adding new macros to the existing webiopi interface (from phase 1) to control those GPIO. I found that a delay of 0.5 sec between driving a high and low provides enough time for an outlet to be switched on/off.

I also have cron jobs that run python scripts to power these outlets on/off at different times automatically. This can be really useful for repetitive tasks like switching on/off a light every night or turning on an electric kettle every morning.

The end result is an internet controlled home automation system that lets you power on/off different electrical devices.

Here is the updated web server interface:


Just in time for Christmas, here is a short video showing how I turn on my Christmas Tree lights using the interface on a phone.

video







Thursday, November 21, 2013

Raspberry Pi Home Security System - Phase 1


I wanted to make an inexpensive home security and automation system with the following goals:
  • Home security system controlled by the internet or a 4x3 keypad
  • Use 433MHz Door/window sensors to trigger an alarm
  • Use 433MHz wireless switches to control home lighting
  • Actions on alarm trigger - Siren and send out an email/tweet
  • Future enhancements -  Laser trip wires!
Update 1: I added 2 webcams to the system and any motion now triggers an alarm as well.
Update 2: Check out phase 2 of the project here, which adds internet controlled outlet switches.
Update 3: Check out phase 3 of the project here, which adds a wireless siren + a demo video of the system.
Update 4: I swapped the 433Mhz receiver for a much better one based on reader Kris's feedback. Updated original post below.
Update 5: The information from all the phases of this project have been consolidated and written up as an instructable here: http://www.instructables.com/id/DIY-Home-Security-Automation-using-a-Raspberry-Pi/

System Overview:



For Phase 1 - I plan on enabling the home security functionality. Phase 2 will be the home automation (wireless light control etc.) and additional security features like webcam motion detection and potentially laser trip wires.

Hardware:

I picked up an inexpensive set of 433MHz transmitter-receiver modules ($2.77) and 433Mhz  door/window sensors ($12.99) from Ebay (links below)



433MHz Tx-Rx pair (set of 2)








I am now using a 433MHz receiver ($5.99) suggested by Kris (Thanks!) which is much better than the one originally recommended.  Link for that item is here:

Updated module - 433MHz super heterodyne receiver

433MHz Door/Window Sensors (set of 4)











For the input interface I picked up a 4x3 membrane keypad available on the Adafruit website ($3.95)












I have 2 webcams that I use for this project:

  1. An inexpensive USB webcam connected to the Pi directly
  2. A Tenvis JPT3815W IP Webcam connected to my home internet.


Software:

433 MHz RF communication on Pi:
I found this article on using 433MHz Tx-Rx modules with the raspberry pi. Follow the instructions here to install the 433Utils package.
http://ninjablocks.com/blogs/how-to/7506204-adding-433-to-your-raspberry-pi

A couple of points to note here:
  1. The outputs of the receiver are 5V TTL and I wasn't so pleased connecting them directly to 3.3 V tolerant Pi inputs.So I used a simple voltage divider circuit (220 ohm/440 ohm) to drop the voltage to something around 3.3 V. 
  2. The receiver from Ebay does not come with an antenna. This threw me off initially because I wasn't receiving any code unless my transmitter was few inches away from the receiver. The recommended length for an antenna for this module is a 172mm long one (1/4 wavelength).
  3. I modified RFSniffer.cpp to write to a file, if the code matched my specific transmitters.
 
  if (value == 0) {
          printf("Unknown encoding");
        } 
  else {

          printf("Received %i\n", mySwitch.getReceivedValue() );
          if (mySwitch.getReceivedValue() == enter your transmitter code here ) {
                  system("sudo echo -n 1 > trigger.txt");
          }
       }

       Run a "make" in the RPi_utils directory to create an updated executable.

You will need to install WebIOPi for the web interface. 

You will also need motion to detect movement using any webcam. Check out my previous post here to see how to set this up. 

Python code for rest of the software can be found on github:
https://github.com/tkmaker/RaspberryPiHomeAlarm

A shout out to Chris Crumpacker for enabling the 4x3 keypad code on the Pi. Thanks!

You can modify the passcode to arm/disarm the system from the keypad via keypad.py

You need to modify intruder_mail.sh with your email settings. You can also customize your email subject/message in this script.

Code overview:

There are 2 main scripts of importance -
  1. control.py - Calls keypad.py and alarm.py. Arms/Disarms the system based on web/keypad interface.
  2. alarm.py - Monitors the system status and if armed, checks for triggers before sounding an alarm.





Setup:

I have the RF receiver hooked up to my Pi (rev B) with data input on GPIO 21.

The 4x3 membrane keypad is connected as follows:
  • Pin 7 on the keypad is ROW 0- GPIO 18
  • Pin 6 on the keypad is ROW 1- GPIO 23
  • Pin 5 on the keypad is ROW 2- GPIO 24
  • Pin 4 on the keypad is ROW 3- GPIO 25
  • Pin 3 on the keypad is COL 0 - GPIO 4
  • Pin 2 on the keypad is COL 1 - GPIO 17 22
  • Pin 1 on the keypad is COL 2 - GPIO 22 10
Update: I had to change the GPIO being used here since GPIO 17 will be used by the RF transmitter (see post for phase 3) to send a code to the RF siren.

Green LED is on GPIO 7

The 2 webcams are monitored as 2 different threads via the motion software. You can check out this post here to see how to set that up.

I have modified /etc/motion/motion.conf to write to trigger.txt on motion detection.

# Command to be executed when a motion frame is detected (default: none)
on_motion_detected sudo echo -n 1 > /home/pi/trush_workdir/scripts/homealarm/trigger.txt

I also have it set up to upload images and videos to my Google drive (see my previous post for details)

Start control.py as a webiopi process:
 
sudo python control.py -m webiopi -d 8085
You can use any port of choice above. I used 8085.
You should see an interface like this once you go to your Pi IP address:8085

If you pull the website up on a touchscreen phone connected to your home internet, you can press the arm/disarm buttons to activate/de-active the system. The rest of the buttons are not enabled yet.
You can also enter the passcode (default 123) on your keypad to arm/disarm your system.
To test out the system -
  1. Arm it via the web interface or keypad - The terminal should show the status here
  2. Trigger a fake intrusion via the door sensor - Look for the alarm triggered message. The LED will blink 20 times and an email will be sent out 
  3. Disarm and arm again
  4. Trigger a fake intrusion by moving in front of the webcam - Look for the alarm triggered message. The LED will blink 20 times and an email will be sent out 
For now, the alarm action doesn't include a siren - I plan to add this as part of phase 2 as well. 
Please feel free to leave your questions and comments Any suggestions to improve or enhance the system are welcome.

Tuesday, November 12, 2013

Raspberry Pi Motion Detector


One of my first projects with a Raspberry Pi was a  motion detector for a home security application. The goal was to  alert me via an email when there was any movement detected by a webcam and also upload pictures and videos to a Google drive account. The webcam  could also be controlled remotely to view my home when I was away as well.

This post should help if you want to attempt something similar.

First off, you will need:

A webcam -  For this project I used an inexpensive Silicon Motion USB webcam which I borrowed from a friend you had it lying around. 

WiFi  - I used the popular Edimax EW-7811Un 150 Mbps Wireless 802.11bgn USB Adapter

Motion Detect Software:

Motion - An open source motion detection software

sudo apt-get install motion     

Main file of importance here is:  /etc/motion/motion.conf
Lines to modify
daemon on -> change this to  off
webcam_localhost on -> change this to  off
control_localhost on  -> change this to  off
Some useful parameters:
TCP/IP Port for remote webcam control:
control_port 8080
TCP/IP Port for remove webcam stream:
webcam_port 8081
Picture size:
width 320
height 240
Threshold for detecting motion. The threshold is the number of changed pixels counted after noise filtering, masking, despeckle, and labelling. Change this based on your personal needs.
threshold 1500

Actions to perform based on motion detect:
on_picture_save <script>
on_motion_detected <script>
on_movie_end <script>

You can customize what action you want to take based on several triggers. In my case, I used a google drive uploader script written by Peter Nichols(Thanks!).  You can copy the python code from the post here

You will need python and gdata (google data) Linux packages to get this to work.

Usage: Change the action line in the motion.conf above to this:
on_picture_save sudo python <script name> -u <google username> -p <google passwd> -l <google drive folder> -f  %f -m jpg
on_movie_end sudo python  <script name> -u <google username> -p <google passwd> -l <google drive folder> -f  %f -m mp4


You are all set!

Start the motion software in setup mode:
sudo motion -s

While running, you can see the pixel change value, noise value etc per frame. You can change the threshold value in the motion.conf file based on your specific needs. 

Test out the motion detection to see if everything works as expected.

Remote control/monitoring of the Webcam

 You can connect to your Raspberry Pi IP address with port 8080 i.e. (<my raspberry Pi IP>:8080) to control and change different parameters of your motion.conf file remotely. I will let you play around with that

You can also monitor your webcam feed via the streaming port (8081). This is useful if you want to see what is going on in your home after a motion detect alarm.

If you want to connect to your raspberry pi and motion software from a remote location, you have to setup port forwarding via your home router firewall settings. You can usually see what devices are connected to your router (via IP address) and enable certain ports for those devices (eg 8080,8081). Be careful here, since you are now opening this up to the outside world! Motion allows you for password enabled access as well (see motion.conf file) which I would highly recommend.

Please leave your comments or questions below and I will be happy to respond to them.