Project Pi take five Raspberry Pi Computers to Kasupe Primary School in Malawi

This August, a team from Manchester, England, took out five Raspberry Pi computers to a small village school in Chigonere, near Monkey Bay, Malawi. The aim of the project was to set up the Raspberry Pi computers in a newly built primary school library, enabling pupils, teachers and community members from the school and neighbouring villages learn basic IT skills as well as getting online and connected. [see bottom of post for a short video]

Left to right: Tim, Rebecca, Richard, Witness, and Tyson.

Project Pi was co-founded by Tim Greenwood and Tyson Dye in 2014. Their aim was simple, leveraging the power of the Raspberry Pi to help teach and inspire IT literacy with anyone who was interested.

They cut their teeth in 2014 with a trip to the Khaya Centre in Johannesburg. Tyson, chief architect for Project Pi, was able to draw upon his years of experience as a solutions architect for a large IT company in Manchester and design a Raspberry Pi set up which would not only be cost effective but also durable. This meant, among other things, choosing the right combination of monitor, keyboard, mice and networking gear within budget and quality spec. No mean feat. In total they took out ten computers, kindly sponsored by Tyson’s firm, UKFast.

The duo also selected a number of open source applications they thought would inspire learning and creativity (Scratch, Minecraft-Pi and Libreoffice). Tim, a psychologist with a background in education and learning, was then able to support members of the Khaya Centre in setting up the Raspberry Pi, learning about the core features and software available as well as learning how to design and run sessions in a hands on and exciting way.

Mandla (left) and team at the Khaya Centre, Lehae, Johannesburg, 2014
Tim and Valencia (Khaya Centre Lead)

Soon after arriving back in the UK, September 2014, Tim was approached by an old friend Davy Chilakalaka, co-founder, with his wife Sally, of the Charity Kasupe. Davy had connected with Tim on LinkedIn and when catching up on Tim’s news, his heart skipped a beat when he heard about the project which Tim and Tyson had just completed in Johannesburg. Davy wanted to know if Project Pi would like to bring the power of the Pi out to his home village in Malawi; where he was just starting to project manage the building of a new set of school buildings. There would be a new library which Davy knew would be just perfect for a Raspberry Pi computer suite.

Children playing at Chigonere Primary School, Malawi
Davy and Sally Chilakalaka, co-founders of Kasupe Charity

In case you are wondering what a Raspberry Pi computer is, it is a small (credit card sized) computer which is capable of running OS like Linux or Android. Raspberry Pi are cheap (under £30 at the time of writing, see here). And they are very good for projects which need a reliable and easy to fix computer. They are perfect for children and those new to computing to learn and tinker without fear of breaking either the software or hardware. In fact this was what inspired their creation by the Raspberry Pi Foundation (see here).

The new Raspberry Pi 2 Model B which we used this year in Malawi
Tyson experimenting with a Raspberry Pi 2

Davy was born in Chigonere, Malawi and came to England to study in 2000. His work at Kasupe has allowed a ‘bridge’ to form between Chigonere and the UK. Davy himself has one foot in both cultures, providing him with a unique standpoint to facilitate development projects in Malawi. He understands firsthand the impact of high quality education as well as a love of his home country Malawi, and old stomping ground, Chigonere village.

Tyson and Tim had learnt a lot from Johannesburg and with the prospect of a second project in Malawi they put their thinking caps on, reaching out to a number of other projects using Raspberry Pi within projects in the UK and abroad. One such conversation, with Dr Maximilian Bock (madanyu.org), had alerted them to the need to support Teachers in becoming confident with using the Pi within the classroom. In short, if you want to avoid Pi gathering dust on classroom shelves, you need to capture hearts and minds. This created a particular line of inquiry for the project: How do we work with teachers in such a way that they will feel confident and inspired to incorporate Raspberry Pi within their curriculums and classrooms?

Elise, Tyson and Toby ready to check in at Manchester Airport.
Tim taking a selfie at Nairobi Airport.

This August, Tyson and his wife Elise (a talented musician) and Tim and his 9 year old son Toby (a talented Minecrafter) set off for Malawi with 5 Raspberry Pi computers. And like the Johansberg project, UKFast kindly provided the five Raspberry Pi kits we took out.

A brief diary of their adventures can be found [here].

During their stay, they worked hard to set up a working Raspberry Pi computer suite; train and build relationship with teachers from Kasupe Primary school as well as other local primary and secondary schools; get to know and partner with Kasupe’s Malawi side project team; and other key stakeholders within the community e.g. village, village group and district authorities who are key players with regard to authorising any projects within their territories. We were even lucky enough to have a visit from Malawi TV!

Toby and Tyson with the Headteacher of a local primary school.
Moses (Teacher at Kasupe Primary School) helping a colleague learn to use Libreoffice Write application.

By the end of the week we had Teachers asking when we were coming back, a moment which really made us feel that we had made some lasting connections. Tyson was particularly blown away by some of the progress made by attendees on the educational software we had installed (e.g. touch typing). For many people coming to use the Pi, this was their first time using a computer, which meant learning a whole new language. Just imagine the amount of things you take for granted when using a computer, from where to click to maximise a window, how to scroll down a list of font sizes, where to put your fingers when touch typing, how to log on to the computer when you can’t see what letters you have typed into the password field. And hats off to people learning all this in a second language!

Teachers from a number of local schools experimenting with Libreoffice Write.
The Deputy Head teacher of a local Primary school being supported in using Libreoffice Write by two colleagues.

After coming back from Malawi Tim reflected that: “So far Tyson and I/Project Pi have taken on two very different projects and I have been excited by what we have been able to do with a relatively small budget. I just love the fact that computers are really great teachers in themselves – you either get them to do the thing you had in mind – or you don’t. And they’re always ready for you to come back and have another go!”

As part of the project, there was also opportunity for some cultural exchange and Elise was able to facilitate some singing workshops with local musicians. Elise reflected that she was ‘amazed to discover the local choir sang in tune without any instruments to aid rehearsal or training and in up to eight parts – and they didn’t seem to think it was anything special!’  During her workshop she noticed the group were excited to learn they could make a more dynamic sound by simply using their voices in different ways while singing – with no fancy instruments needed.  Elise commented that  ‘It was incredible to me to observe the similarities between singers in Chigonere and in the UK, even down to their perceived improvement needs.’

Elise working with a talented
local choir from Chigonere Village.

Update: Mid September 2015

So where next? We left having installed the Raspberry Pi; having worked hard with local teachers on looking at what the Pi can do; and having gained a lot of interest in the project from a wide range of stakeholders (from local authorities to interested citizens). But one of the key outcomes for Project Pi, has been leaving with an open communication channel to the small team we left in charge: Witness, Rebecca and Richard. WhatsApp has proven to be a great tool for sharing updates, asking questions (both ways) and sharing pictures.

We have been able to start charging a small fee (50 MKW, which is about 0.6 GBP) for accessing the internet and basic computer training. All the funds raised are being reinvested back into the project to cover key running costs, such as 3G data charges to connect the wireless router to the internet.

Check out the project video:

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

Project Pi | Downloads

  1. September 2015 | Project Pi Malawi 2015 Press Release PDF | [link]
  2. September 2015 | Project Pi Malawi 2015 Diary PDF | [link]

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

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

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

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

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