Arduino and Raspberrypi collaboration for motion detection


The above video will show the final assembled part of the motion detector.
I will try to have additional videos on how to setup each device from the scratch.

Below you will find the code that is used in the arduino part.

The basic part would be
– The arduino will detect the motion
– It will hit the API inside the raspberry pi
– The raspberry pi will log the motion being detected into the database.

After this, any other system can make the use of the data that has been logged into the database.

<pre>

/*
 Web client
 
 This sketch connects to a raspberry pi RoR websever
 using an Arduino Wiznet Ethernet shield. 
 
 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13
 Modified for motion by Kaleb Woldearegay
 created 18 Dec 2009
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe, based on work by Adrian McEwen
 
 */

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
byte ip[] = {192,168,2,4}; //shield's ip
byte geteway[] = {192,168,0,1};
// Set the static IP address to use if the DHCP fails to assign
IPAddress server(192,168,2,9); //pi's ip

// Initialize the Ethernet client library
// with the IP address and port of the server 
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

//sensor and LED
int calibrationTime = 30; 

//the time when the sensor outputs a low impulse
long unsigned int lowIn; 

//the amount of milliseconds the sensor has to be low 
//before we assume all motion has stopped
long unsigned int pause = 5000; 

boolean lockLow = true;
boolean takeLowTime; 

int pirPin = 7; //the digital pin connected to the PIR sensor's output
int ledPin = 13;

//end sensor and LED


void setup() {
 // Open serial communications and wait for port to open:
 Serial.begin(9600);
 while (!Serial) {
 ; // wait for serial port to connect. Needed for Leonardo only
 }
 
 //sensor and LED
 pinMode(pirPin, INPUT);
 pinMode(ledPin, OUTPUT);
 digitalWrite(pirPin, LOW);
 //give the sensor some time to calibrate
 Serial.print("calibrating sensor ");
 for(int i = 0; i < calibrationTime; i++){
 Serial.print(".");
 delay(1000);
 }
 Serial.println(" done");
 Serial.println("SENSOR ACTIVE");
 delay(50);
 
 // start the Ethernet connection:
 if (Ethernet.begin(mac) == 0) {
 Serial.println("Failed to configure Ethernet using DHCP");
 // no point in carrying on, so do nothing forevermore:
 // try to congifure using IP address instead of DHCP:
 Ethernet.begin(mac, ip);
 }
 
 // give the Ethernet shield a second to initialize:
 delay(1000);
}

void loop()
{ 
 //sensor and LED stuff
 if(digitalRead(pirPin) == HIGH){
 digitalWrite(ledPin, HIGH); //the led visualizes the sensors output pin state
 if(lockLow){ 
 //makes sure we wait for a transition to LOW before any further output is made:
 lockLow = false; 
 Serial.println("---");
 Serial.print("motion detected at ");
 Serial.print(millis()/1000);
 Serial.println(" sec"); 
 delay(50);
 } 
 takeLowTime = true;
 }

 if(digitalRead(pirPin) == LOW){ 
 digitalWrite(ledPin, LOW); //the led visualizes the sensors output pin state

 if(takeLowTime){
 lowIn = millis(); //save the time of the transition from high to LOW
 takeLowTime = false; //make sure this is only done at the start of a LOW phase
 }
 //if the sensor is low for more than the given pause, 
 //we assume that no more motion is going to happen
 if(!lockLow && millis() - lowIn > pause){ 
 //makes sure this block of code is only executed again after 
 //a new motion sequence has been detected
 lockLow = true; 
 Serial.print("motion ended at "); //output
 Serial.print((millis() - pause)/1000);
 Serial.println(" sec");
 delay(50);
 //Serial.println("connecting...");
 // if you get a connection, report back via serial:
 if (client.connect(server, 3000)) {
 Serial.println("connected");
 // Make a HTTP request:
 client.println("GET /increment");
 client.println("Connection: close");
 client.println();
 client.stop();
 } 
 else {
 // kf you didn't get a connection to the server:
 Serial.println("connection failed");
 client.stop();
 }
 }
 }
}


</pre>

pidora running out of space on SD card on raspberry

I was having a lot of problem using the debian version of raspberrypi. The problem was lots of dependencies when I was trying to install some packages.
So, I respectfully ditched raspbian and moved to the fedora flavor – pidora

I flashed the OS on it without any problem but I had a problem again when I try to load packages – this time, I am running out space.

Problem

Trying to install git gave me this error

Error downloading packages:
  1:perl-Error-0.17021-1.fc20.noarch: Insufficient space in download directory /var/cache/yum/arm/20/pidora/packages
    * free   0 
    * needed 31 k
  perl-Git-1.9.3-1.fc20.noarch: Insufficient space in download directory /var/cache/yum/arm/20/pidora-updates/packages
    * free   0 
    * needed 53 k
  perl-TermReadKey-2.30-20.fc20.armv6hl: Insufficient space in download directory /var/cache/yum/arm/20/pidora/packages
    * free   0 
    * needed 28 k
  git-1.9.3-1.fc20.armv6hl: Insufficient space in download directory /var/cache/yum/arm/20/pidora-updates/packages
    * free   0 
    * needed 4.2 M

Diagnosis

I was trying to communicate with the raspberrypi headless. And I noticed that the there are only two partitions being used allocated a little more than 2GB from all my 16GB secure disk.

df -h

Gave me the output of

Filesystem      Size  Used Avail Use% Mounted on
/dev/root       1.9G  1.8G     0 100% /
devtmpfs        218M     0  218M   0% /dev
tmpfs           218M     0  218M   0% /dev/shm
tmpfs           218M  280K  218M   1% /run
tmpfs           218M     0  218M   0% /sys/fs/cgroup
tmpfs           218M  4.0K  218M   1% /tmp
/dev/mmcblk0p1   50M   23M   28M  45% /boot

As you can see the root is allocated only 2G and it is used of course.

Then I tried to see the partitions

fdisk -l

And that listed

Disk /dev/mmcblk0: 14.5 GiB, 15548284928 bytes, 30367744 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: **********

Device         Boot     Start       End  Blocks  Id System
/dev/mmcblk0p1 *         2048    104447   51200   c W95 FAT32 (LBA)
/dev/mmcblk0p2         104448   4233960 2064756+ 83 Linux

If you notice closely, the used partitions start with number 1. And on the top you will see there is another partition with the number 0. That is being unused.

Goal

To extend the partition size of the root using the unused space from /dev/mmcblk0

Process

This can be done in two different processes.
1. Take out the SD card put it in your other computer where you have partitioning software, like on ubuntu you can use gparted which is graphical and easy to use or on mac with disk utility
2. Use the old school fdisk and parted tools for partition
I am old school :)

fdisk /dev/mmcblk0

Hit p for printing the partition information:

Disk /dev/mmcblk0: 14.5 GiB, 15548284928 bytes, 30367744 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: **********

Device         Boot     Start       End  Blocks  Id System
/dev/mmcblk0p1 *         2048    104447   51200   c W95 FAT32 (LBA)
/dev/mmcblk0p2         104448   4233960 2064756+ 83 Linux

This will be the information we would be matching against later after the partition is done
Then use the parted tool

parted /dev/mmcblk0

This will provide

GNU Parted 3.1
Using /dev/mmcblk0
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) unit chs                                                         
(parted) print                                                            
Model: SD SA16G (sd/mmc)
Disk /dev/mmcblk0: 1890,77,42
Sector size (logical/physical): 512B/512B
BIOS cylinder,head,sector geometry: 1890,255,63.  Each cylinder is 8225kB.
Partition Table: msdos
Disk Flags: 

Number  Start     End         Type     File system  Flags
 1      0,32,32   6,127,56    primary  fat16        boot, lba
 2      6,127,57  263,140,45  primary  ext4

Look the Disk /dev/mmcblk0: 1890,77,42 information. The ending point for the disk is at cylinder 1890 while partition two is at 263, the head is at 77 while that of partition 2 is at 140 and 42 vs 45 for the sector. Well, as you can see the limit is higher and we want to use the maximum that is using the Disk ending..

Now delete the partition

(parted) rm 2

Ignore the notice and press i

Now if you type ‘print’ you will see the listing without the partition 2

(parted) print                                                            
Model: SD SA16G (sd/mmc)
Disk /dev/mmcblk0: 1890,77,42
Sector size (logical/physical): 512B/512B
BIOS cylinder,head,sector geometry: 1890,255,63.  Each cylinder is 8225kB.
Partition Table: msdos
Disk Flags: 

Number  Start    End       Type     File system  Flags
 1      0,32,32  6,127,56  primary  fat16        boot, lba

Now the fun part Making the partition with larger size

(parted) mkpart primary 6,27,57 1890,77,42

This will allocate the space starting from the first partition to the end of the disk

hit print again

Model: SD SA16G (sd/mmc)
Disk /dev/mmcblk0: 1890,77,42
Sector size (logical/physical): 512B/512B
BIOS cylinder,head,sector geometry: 1890,255,63.  Each cylinder is 8225kB.
Partition Table: msdos
Disk Flags: 

Number  Start     End         Type     File system  Flags
 1      0,32,32   6,127,56    primary  fat16        boot, lba
 2      6,127,57  1890,77,42  primary  ext4

You can see the end information of partition 2 is we instructed it

Then reboot your raspberry

sudo reboot

Then ssh again

ssh root@[raspberrypi.ip.address.here]

Finally do the resizing for partition 2

resize2fs /dev/mmcblk0p2

Then check your bank

df -h

This has listed

Filesystem      Size  Used Avail Use% Mounted on
/dev/root        15G  1.8G   12G  14% /
devtmpfs        218M     0  218M   0% /dev
tmpfs           218M     0  218M   0% /dev/shm
tmpfs           218M  280K  218M   1% /run
tmpfs           218M     0  218M   0% /sys/fs/cgroup
tmpfs           218M  4.0K  218M   1% /tmp
/dev/mmcblk0p1   50M   23M   28M  45% /boot

As you can see the available size of /dev/root has bumped to 12G!

ENjOY the pi!

Problem with MergeList /var/lib/dpkg/status raspberrypi

Having this problem after flashing the OS on your SD card?
It looks the latest wheezy is having this problem. I didn’t have this problem before. Any way the simplest fix I have so far is clearing the status file and running the update again

i@raspberrypi ~ $ sudo rm /var/lib/dpkg/status
pi@raspberrypi ~ $ sudo touch /var/lib/dpkg/status
pi@raspberrypi ~ $ sudo apt-get update

The first command is to remove the corrupted status file
The second would create a blank file with name status, just the reverse of the first command
Last, update to fill up the status..

That is it..

Browser shows the same image after the update

If there is an image change on the same file name, say logo.png or front.jpeg, the change won’t happen right away unless you force refresh it on browser to clear the cache.
The problem with this one is when you have dynamic updates and your users couldn’t see the change right away b/c of the cache.

The simple fix for this would be appending version at the end of the file name. Like your original html would look like:

img height="200" src="/path/to/image/file.ext" 

Then appending the version at the end

img height="200" src="/path/to/image/file.ext?v=someVersionGoesHere" 

For any backend it would be easy to append the versioning when the image is presented. It could be random number or unix timestamp would work in this case too..

If you are generating the images from javascript, say based on the json response, you can do

var version = new Date()->getTime(); //get the unix timestamp
var path = "/path/to/image/file.ext?v="+version;

$('#image_id').attr('src', path);

Shall do the trick. I used jQuery her but, it is not limited to it..

Select an element with multiple classes jQuery

CSS Classes, as we know are the main drivers in the UI. Since we have only one id per element, our arena or tweak on that area is almost limited.
But classes are possible to be deployed multiple times per element and we can apply independent actions per classes..
Now, when you have two classes assigned and you want to single out that element having two classes in jQuery you would do

$('.class1.class2')

Without any space in between.
Common usage would be with javascript where you would take and put classes based on actions.

Yup!

Failed to Retrieve Share List from Server when connecting unix

I was getting the Failed to Retrieve Share List from Server when I was trying to move files from my mac to mint 13 pc.

I am trying using the existing samba protocol.

Here is how I fixed it.
I just added the ip address of the mac on my hosts file

sudo vi /etc/hosts

this will bring the hosts file. Then add the ip address and the host name of the computer you are trying to communicate.

Say the ip address of the computer you are trying to connect is 192.168.2.5

192.168.2.5 hostname

Then reboot your *nix

sudo reboot

Wi-fi connected but no internet mac troubleshooting

It is a bit frustrating when you want to send and email or watch a trailer on youtube or whatever it is and you can’t connect. it looks we can’t live without it anymore :)
Here are steps that would help you to figure out what has went wrong when you are in such scenarios. We will start from the obvious ones..

1. Are you on the right wi-fi? Yea it looks obvious but mac being smart and remembering wi-fi spots you might be on the wrong one.. so give it a check

2. Is that only your mac that is not connected to the internet? Check your other gadgets have internet from the wi-fi you are trying to connect. If others can’t make it then the concern would be changed to the source.

3. Restart your router. Usually, most routers have reset button. Reset it, unplug the power and let it be like that for a couple of minutes and check again.

4. Click on the apple icon on the top left, and click System Preferences. Then select network. On the left you would see your Wi-Fi being listed. Click on it and on the right window, turn wi-fi off and click again to make it on. Then select the network from the drop down list. This one would be usually used for when you see the exclamation point on the Wi-Fi icon

5. Try the wireless diagnostics. You can access, click on the Wi-Fi icon on the right top cornet while holding the option button. It will be listed on the bottom of the list. Follow the wizard and see if that helps the problem.

6. See if you IP is accessible from other machines. If you have another computer, it could be windows or linux use the ping command to check if your ip-address is accessible and valid. On windows, open the command prompt and write ping ip.address.here. You can get the ip address of your mac from System preference->network then click on the Wi-Fi. You will see it on the right pane. Say your ip address is 192.168.2.3

ping 192.168.2.3

7. If the step number is shows you the ip-address has the problem, change the range of ip-addresses from your router to force a distribution of new ip-addresses to your devices. Please google how to assign the ip-range on your router using your router brand. The default we accessible router configuration would be http://192.168.0.1. try that on your browser or check what it is from the manual and update accordingly..

Good luck!

Installing Imagick on mac for php 54

Here is a step by step installation for imagick on mac

brew install ghostscript
brew install ImageMagic –with-ghostscript
sudo pecl install imagick

if you don’t have pecl
cd /usr/local
culr -0 http://pear.php.net/go-pear.phar
sudo php -d detect_unicode=0 go-pear.phar
add extension=imagick.so to php.ini

restart webserver