Raspian missing menu bar [FIXED]

So Tyson and Tim have just got back from Malawi. We took out 5 Raspberry Pi computers for a new library that has been built in a school in Chigonere village.

One of the choices we made when designing the Pi set ups was to boot the OS from a USB stick rather than a partitioned SD card (see here for more on this).

Now on a couple of the Pi we had an issue during the week where the menu bar just vanished. With a bit of googling around (see this page for more) we figured out a solution:

$ sudo rm -r .config/lxpanel

$ startx

This deletes the existing user lxpanel config file and then restarts the x session, which then creates a fresh (and working) lxpanel config file. Job done!

Tim Greenwood

Tim currently works for Living Systems. His background is in psychology, and he has been working as a psychologist within education and the community for the last ten years. He recently gained a Masters of Arts in Management, Learning, and Leadership from Lancaster Business school focusing on the use of Action Research to promote curious and evolving ways of working with individuals, groups and organisations.

More Posts - Website

How to move your filesystem to a USB drive

(and why you might want to do this)

So you have a Raspberry Pi.

You know all about how it uses an SD card (or micro SD for RP B V2) BUT you have heard that SD cards can be a bit flakey when making lots of little read and writes…

SD cards work well in cameras where there are big writes and reads because this is what a camera wants to do, write new photos you have taken to the SD and load up the photos you have taken and want to admire.

Using SD cards on a Raspberry Pi is a little different. As you use your Raspberry Pi it will be making lots of lttle reads and writes all over the disk. Now this is what makes some IT super users (geeks?) a bit edgy. There is the possibility of the SD card failing, corrupting or generally just not performing very well. (one post I saw on the RP forums suggested that the major issue with corrupting SD cards might be to do with overclocking and some forum posts suggest this issue might be cleared up now e.g. see here)

Corrupting SD cards is not the only factor and for some speed is another reason to make the switch to USB for the filesystem (e.g. see here).

So one thing to bear in mind is that your Raspberry Pi will always have to do an initial boot from an SD card. (see here for more on this)

And then look for the root on the USB drive storing the file system (so all the reading and writing of files will happen on the USB drive rather than the SD card).

So if you’re interested in taking this project on, as we have done for our Malawi 2015 project; here is a good post detailing how to format your USB drive and copy the files from your existing OS stored on an SD card to the USB drive:

https://www.raspberrypi.org/forums/viewtopic.php?f=29&t=44177

Make sure you backup before you start this kind of advanced tinkering!

Malawi 2015:

We are taking out 5 Raspberry Pi setups to Malawi this August (more posts on this soon). Our plan is to set them up to boot from USB pen drives for the reasons mentioned above (speed and reliability) as we won’t be around to fix them if they go wrong. We also thought it would make things a lot easier if we could set up one Pi and USB drive, and then just clone the USB drives for the remaining Pi. This also means we can just send over new USB drives as needed. (Long term – it will be great to tap into local expertise or train up volounteers to take on some of these maintenance tasks.)

Tim Greenwood

Tim currently works for Living Systems. His background is in psychology, and he has been working as a psychologist within education and the community for the last ten years. He recently gained a Masters of Arts in Management, Learning, and Leadership from Lancaster Business school focusing on the use of Action Research to promote curious and evolving ways of working with individuals, groups and organisations.

More Posts - Website

Creating a Raspberry Pi Cat Detector

Have you ever wondered who is coming through your cat flap when you are not around?

Well I hadn’t, until I walked into my utility room one day and found a big fat grey moggy half in and half out of the cat flap looking up at me. This was not my cat. It was a tense moment as we both stared at each other. The offending moggy slowly backed up and stared at me defiantly from outside the cat flap.

This got me thinking about setting up a Raspberry Pi powered cat detector. I wanted to know if this cat was coming in regularly and helping itself to my cat’s food.

I sat down and planned out my basic design goals for my Raspberry-Pi-Cat-Detector (or RPi-CD for short):

1. Detect when a cat enters or exists the cat flap.

2. Take a photo of the cat

3. Email the photo to me

I like to use Python for scripting my projects mainly because it is easy, usually quite simple to understand and there is a lot of support on the internet when I need help (which is often!). There are also lots of modules (e.g. in this project I have used GPIO and picamera) that have been written by the Python community that let you do lots of really cool things with minimal coding.

Step 1. How to detect if something is moving through the cat flap

The first problem to solve was how to know if a cat is coming in through the cat flap. There are lots of ways of doing this. I chose to use a HC-SR501 PIR Infrared Motion Sensor Module (learn about them here) connected via my Raspberry Pi’s GPIO pins. This was mainly because they are cheap and fairly reliable which is presumably why they are used in many home security systems.

So how to connect the PIR to my Raspberry Pi?

All Raspberry Pi’s have what are called GPIO pins. They stick up out of the Pi board and look like this:

IMG_20150806_213529

I am using a Raspberry Pi Model B version 2. If you are using a different version (e.g. Raspberry Pi model B or B+) you might need to change which pins you are using. If you are new to GPIO check out this website: http://pi.gadgetoid.com/pinout

IMG_20150804_131053

PIR sensors can vary as to which order the pins are in. But they will all have 3. And they will be:

  • VCC (positive)
  • GND (negative)
  • OUT (signal – HIGH or LOW)

IMG_20150804_131509 IMG_20150804_131521

Your task is to connect up these 3 PIR pins to your Raspberry Pi via 3 GPIO pins. There are lots to chose from and a word of warning, if you get this bit wrong, you can fry your Raspberry Pi for good. Make sure you check and double check!

I am using physical pin numbers here and not BCM (see here for more on this).

VCC goes to GPIO pin 2

GND goes to GPIO pin 6

OUT goes to GPIO pin 11

I used a bread board as a way of making this easier, and as a way of connecting up an LED to use as a way of showing when a cat has been detected.

IMG_20150804_131131

Python has a module called GPIO (or RPi.GPIO see here) which will let me find out whether the PIR OUT pin, connected to GPIO pin 11 is HIGH or LOW. Sounds complicated right? But it really isn’t so bad when you have wired it all up, I promise.

When the PIR OUT is High (5v in this case), it means that the PIR has detected movement. LOW (0v) means it has not detected movement.

Using the GPIO module we can keep monitoring the status of the PIR OUT pin via the RPi.GPIO module and our Raspberry Pi GPIO pin 11.

The Python module RPi.GPIO is already isntalled if you have an up to date copy of NOOBS (for more on NOOBs see here).

Now we have a way of allowing our Raspberry Pi Cat Detector to be able to detect movement. But we are still blind!

Here is the code I used (cat_io.py):

GPIO.setmode(GPIO.BOARD)
# no warnings
GPIO.setwarnings(False)

# choose pins for reading PIR OUT and lighting up LED
PIR_PIN = 11
LED_PIN = 13

class PIR(object):

    def __init__(self):
        # set PIR_PIN as input - so we can read if HIGH or LOW
        GPIO.setup(PIR_PIN, GPIO.IN)

    def read(self):
        # tiny function to read PIR OUT on pin 11
        return GPIO.input(PIR_PIN)

class LED(object):

    def __init__(self):
        # set LED_PIN as output - so we can set as HIGH (on) or LOW (off)
        GPIO.setup(LED_PIN, GPIO.OUT)

    def on(self):
        # turn LED on
        GPIO.output(LED_PIN, 1)

    def off(self):
        # turn LED off
        GPIO.output(LED_PIN, 0)

    def blink(self, on_seconds, off_seconds, total_blinks):
        # blink LED
        for i in range(total_blinks):
            self.on()
            time.sleep(on_seconds)
            self.off()
            time.sleep(off_seconds)

Step 2. How to capture a photo of the detected cat

So to take a picture, whenever there was movement at the cat flap, I needed a camera. Luckily I had a Pi NOIR (see here) already. This is like a normal camera module but without an infrared filter. You can just use a normal pi camera, I was too cheap to buy another one and was willing to put up with pictures with no infrared filster (the main difference is the photos come out slightly more pinkish than normal).

The Python module picamera (see here) is a great way of taking pictures using Python. I was able to detect motion at the cat flap, now I could take a picture when I had detected that motion.

Here is the code I used (cat_camera.py):

import time
from datetime import datetime as dt
import picamera
from os import walk

class my_camera(object):

    def take_picture(self, save_location):
        '''
            when called, takes a picture and svaes jpg in specified 
            location
            WARNING - does not check if file already exists!
        '''
        with picamera.PiCamera() as camera:
            camera.resolution = (1024, 768)
            file_name = self.create_file_name()
            camera.capture(save_location + '/' + file_name)
            print 'taking picture'

    def create_file_name(self):

        return dt.now().strftime("%Y_%m_%d_%H_%M_%S") + ".jpg"

Step 3. How to send an email with the photos attached

The final hurdle was figuring out how to send an email with an attached photo, when I had detected and photographed a cat.

This turned out to be quite easy using modules that come as standard with Python. All I needed was a gmail account to use for this project and since gmail accounts are free, I just set up a new account.

Here is the code I used (cat_email.py):

import smtplib
from datetime import datetime as dt

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

from os import listdir

class send_mail(object):

    def send(self, file_location):
	''' who you want to send your cat detector emails to '''
        email_to = "this is where you put the to email address"
	''' and who they are from e.g. the new gmail account you just set up '''
        email_from = "this where you put the sender email address"

	# gmail smtp stuff
        smtp_server = 'smtp.gmail.com'
        smtp_port = 587
        smtp_user = email_from

	‘’’ enter your gmail password here - warning this is visible
	    to anyone who can open this file!!’’’
        
        smtp_pass = ‘youremailpasswordhere’

	# create message
        msg = MIMEMultipart('alternative')
        msg['To'] = email_to
        msg['From'] = email_from
        

        # get list of attachments i.e. all photos within subdirectory
	‘’’ I used a directory to store photos in and made it so that 
	photos taken within 10 seconds of each other were grouped into the
        same subdirectory
		’’’
        attachment_list = self.get_attachment_list(file_location)
        if len(attachment_list) > 0:
            count = 0
	    # here I make sure the max number of attached photos is 3
            while count < len(attachment_list) and count < 3:
                pic = attachment_list[count]
                file_name = file_location + '/' + pic
                image_data = open(file_name, 'rb').read()
                image = MIMEImage(image_data, name=pic)
                msg.attach(image)
                count += 1

        time_now = dt.now().strftime('%H:%M:%S')
        
	# create email subject
        msg['Subject'] = 'Cat Detector: cat detected (%s)' % time_now
	
	# email body
        body = '''Hi Tim,\nA cat has just been detected, see attched picture(s).
                \nBest,\nCatDetector
                '''

        body = MIMEText(body, 'plain')

        # attach body
        msg.attach(body)

	# try and send email
        try:   
            s = smtplib.SMTP(smtp_server, smtp_port)
            s.ehlo()
            s.starttls()
            s.login(smtp_user, smtp_pass)
            s.sendmail(email_from, email_to, msg.as_string())
            print 'email sent'
        except:
            print 'error sending mail'

    def get_attachment_list(self, file_location):
       # use listdir to return all files in directory
       return listdir(file_location)

Bringing it all together!

So if you have made it this far – well done!

The next thing I needed was a way to create and delete directories. And to reset the main folder with all the photos in. I added this to make sure the disk space was reclaimed each time I resey my pi. If you want to keep all your photos, you will need to tweak this code.

And yes be careful with this code. You have the power to delete things!

import os
import shutil

class cat_dirs(object):

    def __init__(self):
        # get file path of parent directory
        self.cat_parent_path = os.path.abspath('.') + '/'

    def create_dir(self, episode):
        
        try:
            ''' creates a directory within temp_pic directory '''
            directory = self.create_dir_name(episode)
            os.makedirs(directory)
            
        except:
            directory = None
            print 'error making directory'

        return directory

    def create_dir_name(self, episode):
        # create dir path/name from parent path and episode
        return self.cat_parent_path + 'temp_pic/' + episode
    
    def delete_dir(self, dir_name):
        ''' deletes a directory and contents within temp_pic directory '''
        directory = self.cat_parent_path + 'temp_pic/' + str(dir_name)
        try:
            shutil.rmtree(directory)
        except:
            print 'error deleteing directory'

    def reset(self):

        ''' delete temp_pic and recreate '''
        directory = self.cat_parent_path + 'temp_pic/'
        try:
            shutil.rmtree(directory)
            os.makedirs(directory)
            
        except:
            print 'error reseting directory'


The last part – writing a main loop to run all the code. (if you code a lot you will probably have guessed that as I wrote this code I created all the other classes shown above as I went along – but that is not so easy to follow in a blog article).

[editors note: this code is quite long and might take a bit of time to follow. You might find it just as easy to write your own main loop 😀 ]

#!/usr/bin/env python

import cat_camera
import cat_io
import cat_os
import cat_email
import time

class cat_detector(object):

    def __init__(self):
        '''instantiate cat classes:
        camera, PIR, LED, cat_dirs and send_mail'''
        self.cat_cam = cat_camera.my_camera()
        self.PIR = cat_io.PIR()
        self.LED = cat_io.LED()
        self.cat_dirs = cat_os.cat_dirs()
        self.send_email = cat_email.send_mail()

        #reset directory containing photos
        self.cat_dirs.reset()

    def get_status(self):
        return self.PIR.read()

    def main(self):
        # initiate variables
        cycle = 0
        detection = 0
        time_since_last_detection = 0
        episode = 0
        high_alert = False

        '''turn on LED to show script is running
        useful if running headless on boot (i.e. no monitor)'''
        self.LED.on()
        time.sleep(10)
        self.LED.off()
        
        #main loop
        while True:

            '''check if a cat is detected, if it is, add one to detection count
               and if start of episode, go into HIGH ALERT'''
            if self.get_status():

                high_alert = True

                ''' add one to detection because this is a new
                    cat detection '''
                detection += 1


                ''' if this is the first detection of an episode,
                    add one to episodes '''
                if detection == 1:
                    episode += 1
                    # first detection of new episode so create a new directory
                    if episode < 10:                                                   
                        folder_name = '0' + str(episode)                                          
                    else:                                                   
                        folder_name = str(episode)
                
                current_dir_name = self.cat_dirs.create_dir(folder_name)                 
                
                # take picture of detected cat                 
                self.LED.on()                 
                self.cat_cam.take_picture(current_dir_name)                 
                self.LED.off()                 

               '''because there has been a new detection,                    
                  reset time since last detectionto 0'''                 
               time_since_last_detection = 0                 
               
               # indicate detection with LED blinking                 
               self.LED.blink(0.05,0.05,25)             
          else:                 
              # else if there is no detection                                  
              if high_alert:                     
              ''' if high alert == true                         
                  check time since last detection,                         
                  if too long,                         
                  return alert status to normal '''                     
                  if time_since_last_detection > 9:
                        high_alert = False
                        time_since_last_detection = 0
                        detection = 0
                        self.LED.on() # shows user email is being sent
                        self.send_email.send(current_dir_name)
                        self.LED.off()
                    else:
                        # else add another second to time since last detection
                        time_since_last_detection += 1

            print '\n' *50 + '* ' * 30           
            print '''\nCycle: %s,
                        \nAlert Status: %s,
                        \nEpisode: %s,
                        \nDetection: %s
                        \nTime sinse last detection: %s''' % (cycle, high_alert, episode, detection,  
                                                                time_since_last_detection)       
            print '\n'
            cycle += 1
            time.sleep(1)
            

# run the cat detector!
RPiCD = cat_detector()
RPiCD.main()

 

Being really clever

Now by this point you can run the main loop and see if your cat detector is working. You might have used my code or written your own. But the clever bit is making this script run when you boot up your Raspberry Pi without connecting your monitor, mouse or keyboard. I used the LED in my main loop to show me that the script was running at the start (a long flash at the start) and then when my RPi CD was taking a photo or sending an email. This made life a lot easier than having to guess if everything was working ok.

A good guide for doing this is here:

http://blog.scphillips.com/posts/2013/07/getting-a-python-script-to-run-in-the-background-as-a-service-on-boot/

 

Did I capture the cat?

So did building this cat detector work? Did I find out if the big grey moggy was pilfering my cats food?

I detected my cat:

2015_07_30_16_30_09 2015_08_03_08_39_16 2015_08_03_08_39_21

and a few other things:

2015_07_30_15_56_00

Was this the invading cat coming in by stealth at night?

2015_07_31_03_22_43

 

So what is next for the cat detector?

Night time picture taking needs improving, as the above picture shows. How could this be done?

Options include:

a) using an infra-red LED to light up the picture without alerting the cat (my PiNOIR would be perfect for this as it has not infra red filter) and

b) experimenting with picamera and the exposure time (longer exposure would mean lighter picture but if the cat is moving fast, it could lead to blurred pictures)

[please note – the code given in this article may need reformating in IDLE or similar code editor because Python is sensitive to white space e.g. tabs, which can be dissrupted when posting code into wordpress. No responsibility can be taken by the author for attempts at recreating the RPi-Cat-Camera. The code is given for illustrative purposes only.]

Tim Greenwood

Tim currently works for Living Systems. His background is in psychology, and he has been working as a psychologist within education and the community for the last ten years. He recently gained a Masters of Arts in Management, Learning, and Leadership from Lancaster Business school focusing on the use of Action Research to promote curious and evolving ways of working with individuals, groups and organisations.

More Posts - Website

Experimenting with @PiNetDev

So what better way to spend a Saturday than hanging out with some fellow super geeks and loads of techy stuff?


Tim @tim_g_123

Tyson @tysondye

Aaron @aaronsaxtons


Our plan was simple, get 21 Raspberry Pi, and hook them up to PI Net.

So this was a proof of concept – nobody was going to be using the Raspberry Pis today, we just wanted to test out a few things:

1. How easy is it to install and set up Pi Net?IMG_20150509_105803

2. How would my (Tim) old laptop with a 10/100 ethernet connection handle serving up Raspian to 21 Pi?

3. How easy is it to add new users?

4. How easy is it to add additional software?

Step 1: setting up the hardware

IMG_20150509_114604IMG_20150509_114557

IMG_20150509_115826

 

 

 

IMG_20150509_114531HowMuchPi

IMG_20150509_131041

 

We connected my old laptop (running PiNet) to a network switch (don’t know what a switch is? Check this out). The switch was connected to a wireless network using a wireless bridge [thanks Lex!] (so the DHCP server on this network handled dishing out IP addresses to all the Pi and my old laptop running PiNet).

Step 2: preparing 21 micro SD cards

IMG_20150509_114522IMG_20150509_115241IMG_20150509_120342

 

 

 

 

a) The first thing to do was unbox all the micros sd cards and placing them in their adaptors

b) This step is optional – depending on whether PiNet has detected the correct IP address of the server you are using. In our case, we found out the IP address of my laptop on the network it was connected to (type ‘ifconfig’ into terminal) and updated the cmdline.txt file in the piBoot folder. You probably won’t need to do this if you set up PiNet on the same network you are going to be using it on. There is also a way of doing this from within PiNet itself.

b) Then each one was put into the SD card reader on my old laptop running Ubuntu 140.4 and PiNet (see here and here, for instructions on how to do this) … We found out that you need an up to date Ubuntu 14.04 install – maybe using Minimal CD (see here) or running “sudo apt-get update” and “sudo apt-get upgrade” (see here for more on this).

c) We then had to copy the contents of piBoot to the sd card (see here for detailed instructions)

Step 3: Powering on the beast!

IMG_20150509_131504

So it was at this point, we had to hope everything was set up correctly and just turn on the power to the Raspberry Pi. The SD card has a very small kernel which is able to look for PiNet . If it finds PiNet at the IP address we specified, it will then be served up a copy of a full Raspian image which it can then load and use as a fat client (PiNet uses fat clients, not thin clients to make the most of the Raspberry Pi hardware e.g. GPIO … see here for more on this).

How did it go?

IMG_20150509_120810

We wondered if we might have just recreated the Matrix… in fact it was better than that, we had a fully functional Raspberry Pi networked classroom.

So to test this out, we did a few things:

a) First we made a few user accounts and got surfing the net (using PiNet, creating new accounts is easy).

b) Then we had a go at installing software (Chromium-browser) using PiNet on the ubuntu laptop (running PiNet) and tested if it was then pushed out to all the Pi.

c) We didn’t quite get time to get Citrix Receiver working – keep an eye out for how we get on with this!

Check out this short video of the day!

(Special thanks go out to Andrew Mulholland for making PiNetDev freely available on github. A full guide to Pi Net can be found here: http://pinet.org.uk/articles/guides.html. We would love to make this article as correct and useful as it can be – if you spot anything, please leave some constructive feedback in the comments)

 

Tim Greenwood

Tim currently works for Living Systems. His background is in psychology, and he has been working as a psychologist within education and the community for the last ten years. He recently gained a Masters of Arts in Management, Learning, and Leadership from Lancaster Business school focusing on the use of Action Research to promote curious and evolving ways of working with individuals, groups and organisations.

More Posts - Website

Raspberry Pi Project – Hardware List

I’ve Got One… So Now What?

So you’ve taken the plunge and bought a Raspberry Pi (RPi), but what else do you need?  Or maybe you’re trying to see what you would need to get a Pi up and running before you actually buy one!  Well, I won’t go into the details of getting the Operating System (OS) or software on a Pi running as our friends at the Raspberry Pi organization have already done a great job with that, check here.

I’ve just recently had to finish a complete hardware list for twenty (20x) RPi setups for an educational institution and I wanted to share the specifics of what hardware we ordered and why that specific hardware.  There are also lots of ‘starter kits’ that you can buy that include a RPi, but rarely are they complete so hopefully this list fills in the missing parts.

I’ve broken it up into two sections: The Obvious and The Not-So-Obvious.  If you are really impatient you can just skip to the bottom to see the shopping list of all the hardware an associated links!

The Obvious

The Pi!

There are several different RPi models now, so be careful to know which ones you have!  All of the below will work for any of the RPi 2 ‘B’ model.  If you have a RPi 1 (A, A+, B, or B+), you’ll have to make some minor adjustments to the case and SD card accordingly, the rest of the items work for all the RPis.

A Monitor

Don’t think you must go a buy a brand new monitor; most modern TVs these days have/use HDMI so check yours before you go buy a new one.

If you do have to buy a new one, or you don’t want to share your TV with your RPi, then make sure you get a monitor or TV that takes HDMI natively.  This can be tricky with monitors, but for TVs it is straightforward.  On the back/side of the TV it will say ‘HDMI’ somewhere and it may have multiple HDMI ports.  

PC monitors most likely won’t take native HDMI so you’ll need to look for ‘DVI-D’ or ‘DVI-I’ as this can easily take a converted HDMI connection with a HDMI to DVI cable.  What you want to avoid is the ‘DVI-A’ connectors as those are analogue only and they won’t work with a RPi without a special powered converter as well.

Here is a Wikipedia link so you can read the difference if you are interested, but just use the pictures here to confirm what the monitor takes, and the HDMI-to-DVI cable provides (see below).

Keyboard and Mouse

This hopefully is ‘easy as pie’.  The most important part is just make sure they have USB connectors and not the old school PS/2 connections!

Not-So-Obvious

SD Card

The wonders of RPi can only be unlocked with an OS and software.  These are initially stored on ‘disc’ which is the form of a standard SD memory card.  For the RPi 2, you are looking for a microSD not the big brother like the RPi 1 models.  Here is the sizing guide taken from Wikipedia [….SD (blue), miniSD (green), microSD (red)]

SDHC is fine, class is not too important as better ‘class’ improves large reads/writes only and your RPi will be rarely being doing those as most of the time it will be doing small reads and writes.  There is a compatibility list found here if you are in doubt that your SD card will work.

HDMI Cable or HDMI to DVI-D cable

This one can be straight forward if you going to a native HDMI device, or tricky if you are going to a monitor with DVI connection.  Below is a picture of what you are looking for when you buy the HDMI-to DVI-D cable.

Micro USB and Power Plug

Your RPi will need power, that comes in the convenient form of a microUSB cable.  Simple to source, easily forgotten about.  And look for a screen/router/printer that may provide a powered USB connection so you may not have to power the power adapter to plug into the wall.

Here is a picture guide to the see which one is microUSB from Wikipedia:

Case and possible VESA mount

The RPi on it’s own from the manufacture is just bare bones circuitry!  If you were lucky your’s came with a case and if you were clever you purchased a case with it already.  Regardless, you want to get a case and protect that little guy!  There are a multitude of case options out there, and a lot of it comes down to taste (e.g. colour, images)

After you have a case, are you going to just let is dangle around like lost tourist!  What about getting a case that can be VESA mounted to back of the TV or monitor that you’ll be using for the RPi?  This way is is protected and out of the way for harmful coffee spills.

Now the Goods!

Now that you know all the hardware goods you need to buy, here is the shopping list with links to stores in the UK (where the educational institution is at) where you can buy the stuff!

 

Item Price
USB Mouse
£ 6.90
USB Keyboard
HDMI Cable £ 2.28
Pi Power Cable £ 1.07
Pi Power Plug £ 5.88
microSDHC Card 8GB £ 3.02
Pi Case £ 8.50
Raspberry Pi 2 – Model B £ 29.99
Monitor £ 68.63
Total £ 126.27

 

Now the Why

  • The RPi – at the time of writing this was the Raspberry Pi 2 – model B
  • Monitor – We went for a low cost, power efficient PC monitor over a TV.  Mainly because the TV costs were near double that of the monitor.   And since you need to buy a HDMI cable, the HDM-to-DVI for the monitor wasn’t more expensive.
  • Keyboard/Mouse – Easy choice, driven by price
  • SD Card – Again, just price driven but make sure you look at the compatibility list before you buy.
  • USB Power/Adapter – Driven by price and the length of cable you need.  You may have something lying around and if you’ve got spare USB plugs on the monitor or nearby printer/router you may not have to get the power adapter.
  • Case/Vesa mount – We chose not to get a vesa mount as we wanted the RPis on display for the class to see the circuitry to get a more ‘hands on’ feel.  That also drove the decision to get the clear case with access to the break-out pins.

 

Hopefully this helps with understand what is needed and an example project of what was actually purchased.  Now you just need to decide on your stuff!

Tyson Dye

I’m an IT architect for a leading UK hosting firm in Manchester, UK. But originally I’m from the Big Sky country of Montana, USA. And I’m passionate about IT training and bridging the gaps for anyone on the margins of life!

More Posts - Website

Follow Me:
TwitterLinkedInGoogle Plus

Porting SparkFun Inventor’s Kit to Raspberry Pi and Python using nanpy

Aim: having just figured out how to make an Arduino slave to the Raspberry Pi (see this post), it’s time to see what is possible using this set up. SparkFun have created (IMHO) a really nice set of circuits as part of their ‘Inventor’s Kit v3.2′. The aim for the next twelve posts is going to be to follow their circuits, porting the Arduino code to Python using the nanpy Python library.

Circuit 1: Blinking an LED – now we covered this in our first post looking at setting up the Arduino as slave (here).

Circuit 2: Potentiometer – this involves using a potentiometer to change the rate at which an LED blinks. A potentiometer is just a fancy name for a variable resistor. A resistor is very simply, something we use in electronics to control the current flowing through a circuit. The higher the resistance, the lower the current (see Ohm’s law for more on this relationship). We are now able to measure this using an analogue pin on the Arduino and make use of it within a Python programme running on our Pi!

IMG_20141221_193117.jpg [continue reading]

Tim Greenwood

Tim currently works for Living Systems. His background is in psychology, and he has been working as a psychologist within education and the community for the last ten years. He recently gained a Masters of Arts in Management, Learning, and Leadership from Lancaster Business school focusing on the use of Action Research to promote curious and evolving ways of working with individuals, groups and organisations.

More Posts - Website

Circuit 2: Potentiometer

Circuit 2: Potentiometer – this involves using a potentiometer to change the rate at which an LED blinks. A potentiometer is just a fancy name for a variable resistor. A resistor is very simply, something we use in electronics to control the current flowing through a circuit. The higher the resistance, the lower the current (see Ohm’s law for more on this relationship). We are now able to measure this using an analogue pin on the Arduino and make use of it within a Python programme running on our Pi!

It will be a good idea to read the SparkFun online guide to circuit #2 first – here.

Step 1: set up your Raspberry Pi and Arduino nanpy mashup (see here to find out how)

If you have used your Arduino using the Arduino IDE since you uploaded the special nanpy ‘firmware’ you will need to upload it again.

Step 2: write a cool Python script (or just use the code here)

''' import modules needed '''
from nanpy import Arduino
from nanpy import serial_manager
from time import sleep

''' create a serial connection '''
serial_manager.connect('/dev/ttyACM0')

''' Set analogue pin A0 to input mode '''
POT = 0 
Arduino.pinMode(POT, Arduino.INPUT)

''' Set digital pin 13 to output mode '''
LED = 13
Arduino.pinMode(LED, Arduino.OUTPUT)

''' decide if you want to print out delay each loop '''
printDelay = True

''' let people know the LED fun is about to start '''
print "starting"

''' while True basically means do this forever (or until someone presses control and c) '''
while True:
        # turn on LED
        Arduino.digitalWrite(LED, Arduino.HIGH)
        # wait (according to reading from potentiometer)	
        delay = Arduino.analogRead(POT)/1500.0
        if printDelay:
                # if printDelay == True, print out delay
                print 'delay: ' + str(delay)
                
        sleep(delay)
        # Turn off LED
        Arduino.digitalWrite(LED, Arduino.LOW)
        # wait (according to reading from potentiometer)
        sleep(delay)

Step 3: set up the circuit

See SparkFun documentation here.

Step 4: play with the potentiometer and watch to see your potentiometer blink at different rates

What happens if you change the number 1500.0 in our code?

What happens if we just use the reading from A0 without dividing it by a number at all?

Tim Greenwood

Tim currently works for Living Systems. His background is in psychology, and he has been working as a psychologist within education and the community for the last ten years. He recently gained a Masters of Arts in Management, Learning, and Leadership from Lancaster Business school focusing on the use of Action Research to promote curious and evolving ways of working with individuals, groups and organisations.

More Posts - Website

Experiment: use an arduino as a slave to your raspberry pi

IMG_20141219_180749.jpg

 

Why do this?

If you have got past the initial excitement of having a Raspberry pi, and tried getting into experimenting with inputs and outputs (i/o for short), you might have stumbled across the fact that the Raspberry Pi only has the ability to read digitally from it’s GPIO (general purpose input/output) pins.

IMG_20141219_175420.jpg

So if you have a variable resistor (potentiometer) or a light dependent resistor (or any other analogue sensor) – you won’t be able to measure anything but 1 or 0 (that is how digital works, you are either HIGH or LOW, as opposed to analogue which can be anything in between). Now there are some cool ways around this if you are into your electronics (see here or here). But there are a couple of good reasons for using an Arduino as ‘slave’ to read analogue inputs.

IMG_20141219_180655.jpg

Firstly, the Arduino is very reliable and safe – it has been designed for tinkering. You can make a few mistakes (within reason) when plugging in wires and choosing resistors. The Pi on the other hand is a big wus. Plug a 5v wire into one of its GPIO digital pins (designed for 3.3 volts) and you are likely to fry it! The other big reason to slave the Arduino – is that you can get the full power of Python (including libraries like PyBrain for Neural Networks) hooked up to the outside world through the Arduino’s analogue capabilities.

IMG_20141219_182802.jpg

Yes, using the Arduino IDE (integrated development environment aka a program that makes it easy to write Arduino software) is good and more than enough to keep anyone going even on very complex projects. But using BOTH the Pi and Arduino has it’s advantages IMHO. You get the power of the Pi and Python (think camera, image processing, audio etc) as well as the analogue, safe, reliability of the arduino. (some will be thinking it might be easier to just get a breadboard and a 10 bit ADC, and you might be right, but I would argue that, once set up, this is easier for those new to electronics).

[all experiments are conducted at your own risk]

 

Step 1: Install the Arduino IDE

Make sure you have an internet connection. Open up LXTerminal and type in:

$ sudo apt-get update

This updates the Raspberry Pi with an up to date list of software that is available.

Then type in the following:

$ sudo apt-get -y install arduino

This installs the Arduino IDE on your Pi using the program ‘apt-get’. The -y just means say yes to any questions during the installation.

You might be wondering why we have to install the Arduino IDE after all the fuss about using Python to connect with your Arduino. The reason is – we can use it to install Sketches/firmware on the Arduino, which is really handy for trouble shooting (more on this later).

 

Step 2: Install nanpy (a Python library) using setup tools 

nanpy will help us write the Python code which will help us set up the Arduino as slave to the Pi! AKA we will be able to read and write from the Arduino’s analogue pins.

$ wget http://bootstrap.pypa.io/ez_setup.py - O - | sudo python

(Make sure to use a capital O, not a zero, or you will get errors.)

 

Step 3: Install pyserial

nanpy needs to be able to talk with the Arduino using what is called a ‘serial connection’. To do this we need to install pyserial.

First download the pyserial tar.gz file using wget. 

$ wget http://pypi.python.org/packages/source/p/pyserial/pyserial-2.7.tar.gz

Now use tar to ‘unzip’ it:

$ tar zxf pyserial-2.7.tar.gz

(hint: if you press tab after starting to type ‘pyserial-2.7.tar.gz’ it will autocomplete the rest – which means no more typos! If you get nothing, try pressing tab twice)

Next move into the newly ‘unziped’ directory:

$ cd pyserial-2.7 (again tab works a treat here)

We can now use python to install the pyserial library:

~/pyserial-2.7 $ sudo python setup.py install

Step 4: Install nanpy 0.8

Move back to the home directory if you haven’t already:

~/ cd ~

Then download the nanpy 0.8 tar.gz:

$ wget https://pypi.python.org/packages/source/n/nanpy/nanpy-v0.8.tar.gz

Like we did in step 3, just go ahead and unzip it and install it.

$ tar zxf nanpy-v0.8.tar.gz

$ cd nanpy-0.8

~/nanpy-0.8 $ sudo python setup.py install

Step 5: This step is not entirely needed (see step 1) but is a good way to check everything is okay with the Pi → Arduino usb connection.

 Open the Arduino IDE from the Pi menu:

IMG_20141219_182856.jpg

Menu → Programming → Arduino IDE

Plug in the Arduino to a powered usb hub – not directly into your pi. This makes sure the Pi gets enough current to work properly.

Click Tools → Serial Port and select ‘/dev/ttyACM0’

This tells the Arduino IDE where to connect, in this case ‘/dev/ttyACM0’. 

Click open, which opens a menu. Chose 01. Basics → Blink

This opens a ‘sketch’ which will blink on and off the orange LED built onto the Arduino (pin 13).

Click upload to compile the sketch and load it onto your Arduino.

If everything is okay, you should see a blinking light on your Arduino?

 

Step 6: Upload a special firmware used to work with nanpy v0.8

Your Arduino will need you to load a special sketch on it (firmware) for it to work with nanpy. To do this, you will need to make it first.

Move from the nanpy-0.8 directory into the firmware directory using cd:

~/nanpy-0.8 $ cd firmware

Then type in the following:

~/nanpy-0.8/firmware $ export BOARD=uno

~/nanpy-0.8/firmware $ make

(you will get lots of output)

~/nanpy-0.8/firmware $ make upload

(you should see upload progress displayed)

 

Step 7: Run a simple python script to see if it is working 

Now to test out your first Python AND Arduino experiment!

First we will write a simple python script using the text editor nano.

$ nano blink.py

When nano opens, type in the following Python code:

''' import from nanpy and time modules '''
from nanpy import Arduino
from nanpy import serial_manager
from time import sleep

''' create a connection to the Arduino '''
serial_manager.connect('/dev/ttyACM0')

''' set pin 3 as an output '''
LED = 13
Arduino.pinMode(LED, Arduino.OUTPUT)

''' set the blink rate '''
delay = 1

print "starting"

''' while true aka start an infinite loop of led blinking '''
while True:
    Arduino.digitalWrite(LED, Arduino.HIGH)
    print delay
    sleep(delay)
    Arduino.digitalWrite(LED, Arduino.LOW)
    sleep(delay)

Press control and x to exit the file.

Type y to save changes.

Then type:

$ python blink.py

and watch the led on your Arduino blink. When you are ready, press control c to end the script.

 

Sources

Special thanks go to the following for inspiring and informing this post:

themagpi.com

Tony Goodhew and Raspberry Pi forum community

nanpy V0.8

Tim Greenwood

Tim currently works for Living Systems. His background is in psychology, and he has been working as a psychologist within education and the community for the last ten years. He recently gained a Masters of Arts in Management, Learning, and Leadership from Lancaster Business school focusing on the use of Action Research to promote curious and evolving ways of working with individuals, groups and organisations.

More Posts - Website