Project Pi Diary | Malawi 2015

Day 1 | Monday 24th August 2015

Today we went to Chigonere village and participated in an impromptu meeting with a number of key local authorities including the DC (District Councellor, one of 27 in Malawi), who then speaks directly to the government, and the MP. This was the DC’s first visit to the new Kasupe Primary School complex and his timing was perfect as it meant that he also got a chance to see the new Raspberry Pi suite being set up.

After the meeting had finished, those present moved through to the newly built library where we unpacked and set up some of the Pi-s for them to see. Gift, who runs an Internet Cafe in Monkey Bay, the nearest access to computers which is 15km away, was also able to help us unbox and set up the Raspberry Pi.

As Tyson introduced people to the Raspberry Pi technology, some showed signs of being mesmerized. Tyson was doing a great job as front man while those present waited for the inverter to be setup to provide AC power from the DC solar panels. Without the solar panel, inverter and batteries to supply the juice, the Pi were not that interesting.

Tyson then invited anyone to ask questions. The Village Group Headman (VGH), a level above the Village Headman, (VH) (we soon recognized how many people had official roles around here), naturally responded, ‘How can we have questions when weve never seen a computer before?’

The power supply was promptly sorted. Tyson then presented a whirlwind tour of the OS (the Raspberry Pi we had brought were set up to use an operating system called Raspian) and various applications useful for the school’s curriculum. Again, many of those present seemed fascinated by the complete novelty of what Tyson was demonstrating. The room was strangely quiet and people grouped closely together listening and watching. When it came to the Minecraft demo (a free piece of software that ships with Raspian made by Mojang), it was time for the expert… Toby, Tim’s 9 year old son. People there were unfamiliar with seeing a child so confident on a computer and they’d certainly not previously even seen a Minecraft game. It was great that Solomon, one of Kasupe’s project managers in Malawi asked for a round of applause for Toby’s help. Perhaps it opened their eyes to the fact that you didn’t need to be UK computer expert (potentially how Tyson had been introduced at that point) to be good with computers?

Day 2 | Tuesday 25th August 2015

Day 2 was all about the teachers. We led 2x three hour sessions with them, which someone commented is longer than their school day. We focused on some of the basics of how to logon and logoff, reboot if the Raspberry Pi freeze up, and shutdown at the end of the day.  We showed them how to hold the mouse and where to find applications to run once they’ve logged on.

A basic question among the teachers was how to create documents, we showed them how to open LibreOffice Writer and type their name and their head teacher’s name. This went down well, with a lot of focused effort and participation; it was as if somehow seeing their name as a creation on the computer screen was significant; they had created something and this really got many of them visibly excited! (we noticed smiles, pointing at the screen, bringing others over to see and teaching/supporting others to be able to achieve the same results)

Tyson reflected that for those who have grown up with computers these may seem extremely basic tasks that would take anyone at UKFast only a few moments to complete: logging on, using the mouse to control the graphical user interface and so on. This process took us the whole of the first three hour session. We recognized how we had forgotten that learning these fundamental IT skills really is like learning a new language.

Many of the Teachers were fast learners. While at the start, many did not know how to find particular right keyboard keys, by the end of the session, many had become very accomplished. It was amazing to think many of those present were multilingual and learning and typing in a second language. Tim recognized how some teachers spontaneously began teaching others the skills they had mastered and commented ‘it’s amazing how you just forget what it was like before you learnt to interact with computer GUIs, like just knowing that to make a window bigger you drag the bottom corner, or to scroll down a list of font sizes, you hold and click the bar at the left and drag it down. It all just becomes second nature. None of it is that complicated, but if you don’t know, you don’t know. It’s exciting and humbling that these teachers could see the potential for the Pi in their classrooms and so wanted to learn how to become ICT literate themselves, going back to basics, and being open to new things!’  

Having about 20 teachers and only 5x Raspberry Pi computers, it took more time than we might have expected to swap around and let everyone take their turn.  Another time factor was that although the computers were being donated tothe Kasupe Primary School Center, the session was open to all teachers in the three village area overseen by the GVH. This meant that we had teachers from the local ‘community day secondary school’ and another primary school. This turn out was considered extraordinary for development projects, especially as it was an unpaid event. We were encouraged that the teachers were motivated to give up their entire day. This raised an interesting question about intrinsic andextrinsic motivators. Clearly, the opportunity to use the computers and learning the basic IT skills was reward enough at this point. The recognition dawned on us that the teachers were  imagining how the computers could fit in with their teaching methods.

One of the highlights of the day for us was after the second session. Tyson got to talking with Majawa, who teaches maths. He wanted to know how the Raspberry Pi could help him in the classroom. Firstly, Majawa had found logging on to the Pi fairly challenging. He said that when youre typing the password, you only see dots appearing, not the letters you’re typing. This means if you make a typing error (which youre likely to do when first learning to type) you don’t find out until you’ve finished typing and hit enter. Secondly, if you hold down a key for more than a second or so, the letter starts to repeeeeeaaaattttt itself. Again, this seems second nature to a person who has clocked 100s of hours on a computer but can really throw you when you’re new. But we observed how Majawa is a very patient and persistent teacher and not easily defeated.

At the end of the session, Majawa was delighted when Tyson told him about Mathmatica (a hugely powerful maths application that costs lots of money for university students, but is free on the Pi). Tyson offered to show Majawa a few basic uses of the application. In a short space of time Majawa, his teaching assistant, and two of his colleagues were looking over Tyson’s shoulder, eager to see how they might grasp how to teach Math[?s] with the benefit of the computer.

Tyson commented ‘After stumbling around we started building algebra equations. And the next thing I know they were working out the equations on paper behind me as they wanted to double check the computer was correct. It was of course, but they were well impressed with that setup and we started talking about how they could use it in their classes. That led us to the end of afternoon session and Majawa and I both left with silly smile stuck on our faces.’

It was significant that the Head Teacher of the local secondary school became enthusiastic and got involved. He quickly appreciated the potential of the Raspberry Pi for increasing educational opportunities in his school and the area.

Day 3 | Wednesday 26th August 2015

Today we worked with primary aged students. It was great to show them around the OS, how to use the keyboard and the mouse, how to open applications, and all sorts.

We focused on showing them LibreOffice Writer and Sheets for document / office skills, Scratch for programming (which they really struggled with because it requires a high level of computer navigation skills around the user interface), and Minecraft for mouse and keyboard skills (they loved it but didn’t really get it as it was so foreign to them). It was a very short opportunity but we enjoyed working on the primary target of the project.

And today was very rewarding as the district council official connected with what we are doing. He has announced that he is to bring the national TV station crew out to the village to film what is going on here. So tune in to TV Malawi later. (We’ll do our best to to get a copy of the recording)

Day 4 | Thursday 27th August 2015

Thursday was again very stimulating. We participated in a huge meeting to discuss how to connect the school as it is currently, the Raspberry Pi computers, their use in the community, and expanding the school to include additional years (so start teaching secondary students).

It was headed by the Territorial Authority (TA), seated in the red chair in the picture, who is the highest tribal authority in Malawi. The TA oversees dozens of villages and over 200,000 people.  The man speaking in the picture is one of their MPs. He was making pledges to expand the school and was enthusiastic about how much of a gift the Raspberry Pi computers are to the students and the whole community.

That meeting took all morning and into the afternoon. Beforehand we showed more students the basic use of the computers and afterwards opened it up for training the teachers on anything in which they were interested: LibreOffice Writer training, LibreOffice Sheet training, typing, and Mathematica or Python.

Day 5 | Friday 28th August 2015

Friday was our last day at the village.

We held another teacher training period from 1pm to 3pm, open to all teachers from the three villages in this area.  In the morning we held a more intensive training session for Witness, Richard and Rebecca, the three individuals we selected to be leaders of the project after we had returned to the UK. (See attached picture, from the right to left; Tyson, Witness, Richard, Rebecca, and Tim).

Our plan is that Project Pi will communicate with theses three via email and WhatsApp to assist and offer further training remotely, while these three will take the project and the training further with the teachers and then the students.

In the morning session we showed them how to use the 3G wifi device we brought, and how to top up the Malawian SIM with credit for Internet access. We also showed them how to troubleshoot the Raspberry Pi computers if they break and how to fix them (i.e. if the SD card gets corrupted or the eCloud USB stick fails).

Tyson commented ‘It was really cool to be able to hand this over and see the sense of pride the three had about taking ownership in the project. Now, it’s time to see what happens next, where the village and the Kasupe project will take this! Now the real adventure begins!’

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

Get involved with our Raspberry Pi Project August 2015

This August, Tim Greenwood, co-director of Living Systems, will be travelling out to Monkey bay, Malawi, to help set up an internet cafe with Tyson Dye of UKFast.

timIMG_20150509_114557

This is the second project the two have delivered as part of their Project Pi. Last year Tim flew out to Johanesburg to set up ten Raspberry Pi computers at the Khaya Centre in Lehae. See more about that here http://www.ukfast.co.uk/press-releases/hosting-firm-sponsors-south-africa-tech-project-.html and here http://projectpi.org.uk/khaya-centre-mount-olive-2014/.

And a short video documenting the trip here:

This year’s project is going to see the duo heading out to the Kasupe Project, Monkey Bay, Malawi (http://www.kasupe.org.uk/).  Tim made a connection with Davy, Kasupe’s co-founder, back in 2005 and when Davy heard about the project in South Africa he reached out to see if a similar venture might be possible for Kasupe.

This August will be about installing 5 Raspberry Pi computers for the primary school which Kaspue has started in a rural village near Monkey Bay, Malawi. This will immediately open up the internet to children for researching assignments, connecting with others socially using social media and learning about basic ICT skills as well as e-safety. There will also be a chance for members of the community to get online for a small fee.

Charging for use of the internet is nothing new, the web cafe concept has been around for a long time. However, this will be a good way of creating a small revenue stream for the new centre which will be re-invested back into the project. This will pay for any breakges, 3G data bills and might even lead to the creation of a part-time job managing the project. These goals are ambitious and will need to be tested for their practical merit in the field.

Tim’s interest in this project is from a leadership/action research perspective which specialises in organisational learning within complex and dynamic environments.

Tyson commented that his is ‘understanding how IT in general can be deployed in developing countries to make a positive and lasting impact on communities.’

Watch this space for updates!

Support us here: https://mydonate.bt.com/fundraisers/projectpi

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

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