Raspberry Pi Mechatronics Projects HOTSHOT 1849696225 %7BE56CA9D0%7D %5BYamanoor %26 Yamanoor 2015 01 26%5D {E56CA9D0} [Yamanoor & 26]
User Manual: 1849696225 %7BE56CA9D0%7D Raspberry Pi Mechatronics Projects Hotshot %5BYamanoor %26 Yamanoor 2015-01-26%5D
Open the PDF directly: View PDF .
Page Count: 606
Download | |
Open PDF In Browser | View PDF |
Raspberry Pi Mechatronics Projects HOTSHOT Table of Contents Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers www.PacktPub.com Support files, eBooks, discount offers, and more Why subscribe? Free access for Packt account holders Preface What this book covers What you need for this book Who this book is for Conventions Mission briefing Why is it awesome? Your Hotshot objectives Mission checklist Task 1 Prepare for lift off Engage thrusters Objective complete – mini debriefing Classified intel Reader feedback Customer support Downloading the example code Downloading the color images of this book Errata Piracy Questions 1. Hello World A quick introduction to the Raspberry Pi Features of a Raspberry Pi Where can I buy a Raspberry Pi? Requirements to get started with the Raspberry Pi Operating systems on the Raspberry Pi Getting started with Raspbian Downloading Raspbian Flashing image on to the SD card Windows Linux A command-line interface-based approach Identifying the SD card mount point Unmount the SD card Flash the SD card GUI-based approach Setting up the Raspberry Pi Mission briefing Why is it awesome? Your Hotshot objectives Mission checklist Hunting and gathering Engage thrusters Objective complete – mini debriefing Setting up the GPIO Engage thrusters Installing GPIO libraries Objective complete – mini debriefing GPIO programming using Python Engage thrusters An alternative to quick2wire – RPi.GPIO Objective complete – mini debriefing Electrical output of our program Engage thrusters Objective complete – mini debriefing Introduction to the Pi Crust – a prototyping platform for the Raspberry Pi Mission accomplished Hotshot challenge 2. A Raspberry WebIDE Example Mission briefing Why is it awesome? Your Hotshot objectives Mission checklist Installation, features, and usage of the Occidentalis operating system from Adafruit Prepare for lift off Engage thrusters Objective complete – mini debriefing Setup of a remote login into the Raspberry Pi Prepare for lift off Engage thrusters Objective complete – mini debriefing Installation of the Raspberry Pi WebIDE Engage thrusters Objective complete – mini debriefing Python development on the WebIDE Prepare for lift off Quick introduction to the I2C interface Configuring the I2C interface on the Raspberry Pi Engage thrusters Objective complete – mini debriefing Test and debugging examples using the WebIDE Prepare for lift off Engage thrusters Objective complete – mini debriefing Mission accomplished Hotshot challenge 3. The Arduino Raspberry Pi Interface Mission briefing Why is it awesome? Where can you buy an Arduino? Your Hotshot objectives Mission checklist Installing the Arduino IDE Prepare for lift off Engage thrusters Objective complete – mini debriefing Programming the Arduino using the Raspberry Pi Prepare for lift off Engage thrusters Objective complete – mini debriefing Raspberry Pi AlaMode Prepare for lift off Engage thrusters Objective complete – mini debriefing The Weasley weather clock Prepare for lift off Engage thrusters Objective complete – mini debriefing Controlling the stepper using the Arduino Prepare for lift off Engage thrusters Counterclockwise rotation of the stepper motor Objective complete – mini debriefing Controlling the RGB LED Strip using the Arduino Prepare for lift off Engage thrusters Objective complete – mini debriefing I2C Communication using the Arduino (optional) Prepare for lift off Engage thrusters The 7-Segment display 8x8 LED matrix BlinkM Proximity sensor Objective complete – mini debriefing Serial port communication with the Raspberry Pi Engage thrusters Python program for the Weasley clock Arduino acknowledgement to control signal Control flow for the weather clock Temperature data Control of the RGB LED strip Control of stepper via serial port Programming the weather forecast position 8x8 matrix control BlinkM control Objective complete – mini debriefing Mission accomplished Hotshot challenge 4. Christmas Light Sequencer Mission briefing Why is it awesome? Your objectives Mission checklist Interface the devices to the Raspberry Pi Prepare for lift off Engage thrusters Connecting multiple appliances to the Raspberry Pi Objective complete – mini debriefing Setting up the digitally addressable RGB matrix Prepare for lift off Where can I buy them? Engage thrusters How does it work? Lighting up the RGB LED strip An Arduino-based control Objective complete – mini debriefing Interface of an audio device Prepare for lift off Engage thrusters Objective complete – mini debriefing Installing the web server Prepare for lift off Engage thrusters Objective complete – mission debriefing Interfacing the web server Prepare for lift off Engage thrusters Objective complete – mini debriefing Mission accomplished References 5. Internet of Things Example – An E-mail Alert Water Fountain Mission briefing Why is it awesome? Your objectives Mission checklist Prepare for lift off Engage thrusters Objective complete – mini debriefing Installation of the Flask framework Prepare for lift off Engage thrusters Objective complete – mini debriefing Controlling RGB LEDs from a web page Prepare for lift off Engage thrusters Objective complete – mini debriefing Setup of the e-mail alerts in the fountain Prepare for lift off Engage thrusters Objective complete – mini debriefing Mission accomplished Hotshot challenge 6. Raspberry Pi as a Personal Assistant Mission briefing Why is it awesome? Your objectives Mission checklist Setting up the e-mail feed parser Prepare for lift off Engage thrusters Setting up the parser for reminders and events Prepare for lift off Engage thrusters Designing an enclosure design for the personal assistant Prepare for lift off Engage thrusters Setting up the assembly for the dish monitor Prepare for lift off Engage thrusters Objective complete – mini debriefing Setting up sensors for the key alert system Prepare for lift off Engage thrusters Objective complete – mini debriefing Mission accomplished Hotshot challenges References 7. Raspberry Pi-based Line Following Robot Mission briefing Why is it awesome? Your Hotshot objectives Mission checklist Assembly of the Pi Plate for the line following robot Prepare for lift off Engage thrusters Objective complete – mini debriefing Sensor selection, interface, and data interpretation Engage thrusters Light Dependent Resistors Infrared emitter/detector Machine-vision-based line following robot Sensor selection Objective complete – mission debriefing Implementation of line following logic based on sensor data Prepare for lift off Engage thrusters Objective complete – mini debriefing Testing the motor driver circuit Prepare for lift off Engage thrusters Objective complete – mini debriefing Preparation of the line following course Prepare for lift off Engage thrusters Use electrical tape and build a track Designing the chassis for the line following robot Prepare for lift off Engage thrusters Objective complete – mini debriefing A step-by-step assembly of the robot Prepare for lift off Engage thrusters Objective complete – mini debriefing Mission accomplished Hotshot challenge References 8. Connect Four Desktop Game using Raspberry Pi Mission briefing Why is it awesome? Your objectives Mission checklist Hello world example with the pygame Prepare for lift off Engage thrusters Playing sounds using the pygame module Building menus using the pygame module Objective complete – mini debriefing Getting started with the Connect Four game (UI and sound effects) Prepare for lift off Engage Thrusters Adding a menu for the game Adding sounds to the game Objective complete – mission debriefing Interfacing game inputs using the PiFace module Prepare for lift off Engage thrusters Objective complete – mini debriefing A brief description of the Connect Four Game AI Prepare for lift off Engage thrusters Main game loop Objective complete – mini debriefing Marquee design and control (optional) Prepare for lift off Engage thrusters Objective complete – mini debriefing Setup of the switches using a cardboard box Prepare for lift off Engage thrusters Objective complete – mini debriefing Mission accomplished Hotshot challenge References 9. The Raspberry Pi-enabled Pet/Wildlife Monitor Mission briefing Why is it awesome? Your objectives Mission checklist Installing and testing the python-twisted framework Prepare for lift off Engage thrusters Objective complete – mini debriefing Setting up and testing Spark Core to interact with appliances Prepare for lift off Engage Thrusters Objective complete – mini debriefing Installing and testing the Google Coder project on the Raspberry Pi Prepare for lift off Engage thrusters Objective complete – objective complete A brief overview of a bird feeder that triggers a camera Prepare for lift off Engage thrusters Objective complete – mini debriefing Alternatives and project ideas to consider Mission accomplished Hotshot challenge 10. Raspberry Pi Personal Health Monitor Mission briefing Why is it awesome? Your Hotshot objectives Mission checklist Setting up a web server to record health parameters Prepare for lift off Engage thrusters Objective complete – mini debriefing A simple exercise tool using the Raspberry Pi Prepare for lift off Engage thrusters A mini project idea Objective complete – mini debriefing Setting up an e-mail feed parser to refill a prescription as well as remind the user about an upcoming doctor’s appointment Engage thrusters Setting up a reminder for doctor’s appointments Objective complete – mini debriefing A simple tool that reminds a person to take his/her pills Prepare for lift off Engage thrusters Other project ideas Objective complete – mini debriefing Mission accomplished Hotshot challenge 11. Home Automation using Raspberry Pi Mission briefing Why is it awesome? Your objectives Mission checklist A simple example that controls limited indoor and outdoor lighting in the evening Prepare for lift off Software prerequisites Engage thrusters Objective complete – mini debriefing Alternative solutions and some project ideas to consider A customary web server example Prepare for lift off Engage thrusters Objective complete – mini debriefing Turning on a lawn sprinkler only when there is no rain forecast! Prepare for lift off Engage thrusters Objective complete – mini debriefing Gaining remote access to your Raspberry Pi to control appliances Some project ideas to consider Mission accomplished 12. Using a Raspberry Pi for Science and Education Mission briefing Why is it awesome? Your Hotshot objectives Improving your vocabulary using the Raspberry Pi Prepare for lift off Engage thrusters Objective complete – mini debriefing Raspberry Pi and Khan Academy Some ideas to consider Building a science fair exhibit using the Raspberry Pi Prepare for lift off Engage thrusters Objective complete – mini debriefing Some simple educational experiments using the Raspberry Pi Hotshot challenge 13. Tips and Tricks Mission briefing Why is it awesome? Your objectives Mission checklist Setting up Raspberry Pi as a development platform #1 – Simple trick for Python development via remote login #2 Web development using Google Coder #3 Adafruit Occidentalis #4 Java Development using the Raspberry Pi #5 The Thingbox project Remotely logging in the Raspberry Pi from anywhere on the Internet Problems that might be encountered while using Raspberry Pi SD card corruption Power issues Devices powered by USB Cool add-on hardware sources developed for the Raspberry Pi platform The Raspberry Pi model B versus B+, model A versus A+ Project ideas that can be implemented over a weekend Useful resources for the Raspberry Pi Raspberry Pi Foundation’s forums: Raspberry Pi Stack Exchange: Element 14’s Raspberry Pi community: Mission accomplished Index Raspberry Pi Mechatronics Projects HOTSHOT Raspberry Pi Mechatronics Projects HOTSHOT Copyright © 2015 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: February 2015 Production reference: 1190215 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-84969-622-7 www.packtpub.com Credits Authors Sai Yamanoor Srihari Yamanoor Reviewers Guy Scheffer Sreedhar Vaddi Cheuk Yu Commissioning Editor Usha Iyer Acquisition Editors Usha Iyer Rebecca Pedley Sam Wood Content Development Editor Susmita Sabot Technical Editor Parag Topre Copy Editor Janbal Dharmaraj Project Coordinator Milton D’souza Proofreaders Simran Bhogal Maria Gould Ameesha Green Paul Hindle Indexer Hemangini Bari Graphics Sheetal Aute Disha Haria Production Coordinators Aparna Bhagat Manu Joseph Cover Work Aparna Bhagat About the Authors Sai Yamanoor is a mechatronics engineer working for a private start-up school in the San Francisco Bay Area where he builds devices that help students achieve their full potential. He completed his degree in mechanical engineering at Carnegie Mellon University, Pittsburgh, PA, and his undergraduate work in mechatronics at Sri Krishna College of Engineering and Technology, Coimbatore, India. His interests, deeply rooted in DIY and open software and hardware cultures, include developing gadgets and apps that improve quality of life, Internet of Things, crowdfunding, education, and new technologies. In his spare time, he plays with various devices and architectures such as Raspberry Pi, Arduino, Galileo, Android devices, and others. Sai shares his adventures with mechatronics at the aptly named “Mechatronics Craze” blog at http://mechatronicscraze.wordpress.com/. I want to thank my parents for encouraging me in all my endeavors and for making me what I am today. I am grateful to my brother who has helped shape my career all these years. I look forward to working with Srihari on similar projects in the future. I sincerely thank Mr. S. Balaji Raghavendra who has been a great source of inspiration to me while pursuing my undergraduate degree. I am also thankful to Susmita Sabot and the entire support team at Packt Publishing who were patient and understood the circumstances during difficult times. Srihari Yamanoor is a nature photographer and mechanical engineer with experience working in medical device design and CAD/CAM. He completed his master’s in science as well as a degree in engineering from Stanford University. His work and interests in medical devices include women’s health, cancer, orthopedics, and cardiovascular diseases, as well as newer areas such as digital health and electronic health records. He has several thousands of hours of CAD experience behind him and is also certified among other things as a SolidWorks expert, simulation professional, and a SolidWorks instructor. His interests range from engineering and education to social entrepreneurship, animal welfare, and crowdfunding. I would like to thank my parents, Narasimhan and Yasoda Venakatakrishnan, for their steadfast support in my education and efforts throughout the years, culminating in projects such as this book. Over the course of the years, many friends have helped both Sai and me grow in many ways. For this reason, I would like to say a big word of thanks, in no particular order, to Rika Catherine Hirachi, Anna Liu Jao, Shirupa Gupta, Patrick Nguyen, Vishnu Prasad Ramachandran, Andrew Eib, Christopher Ma, and Karthik Palaniappan. I am sure I am missing some names, and for this, I apologize in advance. I would also like to thank my gracious mentors, Dr. Kevin Waldron, Dr. James Stubbs, Russell Sampson, Mukund Patel, and as I fondly call him, Cyril “Master”, all of whom have given me advice and shown me the way. I would like to especially thank my first cat, Squeaky, and the felines Bob, Saxon, and Fishbone, that have followed me, for inspiring me and pushing me to stay on track and keep an eye on the big picture. About the Reviewers Sreedhar Vaddi has 4 years of experience in big data, 4 years in cloud computing, and 15 years in Java. His experience includes work in the fields of big data security, biomedical/healthcare, mobile security, financial services (wholesale, mortgage, investment, and brokerage), the Web (marketplace, crowdsourcing, and advertising), news and entertainment, property and casualty insurance, software product development, and scientific research. He has hands-on experience as an architect working on enterprise mobile applications, Hadoop, SaaS, PaaS, IaaS, the cloud, rich enterprise applications, n-tier enterprise systems, Enterprise Application Integration (EAI) in web-enabling legacy systems, IBM Mainframe and SAP, and SOA web services with Java2 and JEE. He has also worked in all phases of SDLC, namely designing, developing, performance testing, and implementing Web-2.0, Web-UI, server-side, middleware, and mobile applications. He has also worked with Big 5 Consulting and Fortune 100 companies. He has led teams of sizes varying from 2 to 80 across the globe in different time zones, cultures, and dialects. He is an administrator of JEE containers (Geronimo, WebSphere, Weblogic, JBoss, and Tomcat) and CDH. He is also a technical consultant at a stealth mode start-up in animal care in the clinical trials industry. He is a diligent worker and quick learner with excellent problem solving, presentation, and mentoring skills. Cheuk Yu is pursuing a bachelor’s degree in electrical engineering at the University of California, Los Angeles (UCLA), with an emphasis on circuit and signal processing. He worked on multiple embedded systems projects using various microcontrollers such as Arduino, Teensy, and Raspberry Pi. As a student researcher for the ELFIN CubeSat Mission at UCLA, he also has hands-on experience working on printed circuit boards, including designing and testing avionics and ground support equipment boards. Besides work and study, he is also an amateur radio operator and astronomer. www.PacktPub.com Support files, eBooks, discount offers, and more For support files and downloads related to your book, please visit www.PacktPub.com. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us atfor more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. https://www2.packtpub.com/books/subscription/packtlib Do you need instant solutions to your IT questions? PacktLib is Packt’s online digital book library. Here, you can search, access, and read Packt’s entire library of books. Why subscribe? Fully searchable across every book published by Packt Copy and paste, print, and bookmark content On demand and accessible via a web browser Free access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access. Preface The Raspberry Pi is a quaint example of technological innovations that come by once every two or three decades and set off a revolution that touches every aspect of human life from scientific exploration to entertainment to education. What is exciting this time around is that there are several such innovations happening simultaneously. They might sound like, and are in a way, buzzwords, but they are in fact real, and are changing our lives in so many ways, so few of which we are consciously aware of. We are speaking of innovations in entrepreneurship, such as crowdsourcing or the emergence of DIY with an almost cult-like following to innovations in technology that are current, such as 3D printing and Internet of Everything, and innovations that are impending such as 4D printing, smart manufacturing, and much more. The Raspberry Pi has already found several uses as evidenced by hundreds of websites, project examples, and crowdsourcing campaigns. People have used the Pi to build robots, teach programming, restore old gaming consoles, stream videos, collect data, and do many other things. The Pi itself has gone through design iterations and continues to spur competing systems. People have taken advantage of this and have hooked up the Pi to many different ecosystems, expanding its ubiquity and utility. The purpose of this book is to help those who are excited about the Raspberry Pi and have project ideas in mind, or would simply like to get their hands dirty and practice implementing projects so that they can then use that knowledge for other endeavors. We tried to take a practical approach, introducing the Pi in the first couple of project that you can skip if you are familiar with the Raspberry Pi and have used it before. We then discuss projects of increasing complexity. We have also attempted to diversify the projects to demonstrate various uses for the Pi throughout the book. What this book covers Project 1, Hello World, will introduce the Raspberry Pi and remind you of things that you should know as you proceed through the book. We will set up the Raspberry Pi and blink an LED. Project 2, A Raspberry WebIDE Example, will take you through Python development using a browser. We will use the Adafruit WebIDE and lead you through the development process using Adafruit products as props for the examples. Project 3, The Arduino Raspberry Pi Interface, is inspired by the Harry Potter series, and in an effort to show our love for this series, we have created a clock similar to the innovative and endearing Weasley clock using the Raspberry Pi and an Arduino. This project, of course, allows the clock to report back weather conditions. Project 4, Christmas Light Sequencer, discusses holidays as the best time for DIY projects, and if you are ever starved of ideas, holidays are the best time to cook up ideas. We picked a Christmas-themed project to demonstrate controlling appliances connected to a local network using Raspberry Pi. Project 5, Internet of Things Example – An E-mail Alert Water Fountain, follows the theme of the previous project. We will show you how to control a decorative fountain such that anytime you receive a new e-mail, your fountain’s light will flash an alert (this can also be switched to receive Twitter alerts). Project 6, Raspberry Pi as a Personal Assistant, will show you how you can use the Pi as your personal assistant, reminding you of chores, setting alarms, and doing everything at your command. Project 7, Raspberry Pi-based Line Following Robot, will take you through the simplest of all robots, the line following bot, with Raspberry Pi at the helm. This project will show you the way for this and other complex robotics projects you wish to implement. Project 8, Connect Four Desktop Game using Raspberry Pi, follows the instant-classic theme for the Raspberry Pi, which includes games. All manners of gaming applications, including the revival of archaic games to new ones and mods, are being created using the Raspberry Pi. We will implement the game using a push button interface. Project 9, The Raspberry Pi-enabled Pet/Wildlife Monitor, will walk you through a fun example of a bird feeder monitor that allows you to trigger a photo capture each time the bird approaches the feeder. You can think of extending this to other pets, or say, the feral cats in your colony. Project 10, Raspberry Pi Personal Health Monitor, is a project where we set up a simple web server to record our personal health parameters, build a simple tool to remind ourselves to remain physically active, and remind ourselves to refill a prescription via email alerts. Project 11, Home Automation using Raspberry Pi, is a project where we will show you how to control appliances using a twisted network where the appliance is connected to a platform such as an Arduino. The Raspberry Pi acts as a server that controls all such nodes in the network. Project 12, Using a Raspberry Pi for Science and Education, is a project packed with examples, including a vocabulary learning tool, a web host for Khan Academy, and a windmill generator science exhibit. Have fun learning and teaching! Project 13, Tips and Tricks, is a project packed with tips and tricks that will help you use the Raspberry Pi! You can also get the videos, tips and tricks, and many more things related to the projects at http://diywithpi.com/. What you need for this book To get started, you will need the Raspberry Pi, a monitor, a keyboard, a power source, and preferably, a laptop or personal computer running on any OS—Windows, Linux, or Apple. Other hardware and software recommendations are made in the individual projects, and you are welcome to replace them with what you see fit. A working knowledge of Python is preferred, but not required. Who this book is for This book is primarily aimed at hobbyists and do-it-yourself enthusiasts as well as those looking to implement specific projects using low cost hardware and software centered around the Raspberry Pi. Basic exposure to electronics, programming, and Internet usage is assumed. We have tried to take a pragmatic approach, implementing the projects and showing how you can do this on your own. Conventions In this book, you will find several headings appearing frequently. To give clear instructions of how to complete a procedure or task, we use: Mission briefing This section explains what you will build, with a screenshot of the completed project. Why is it awesome? This section explains why the project is cool, unique, exciting, and interesting. It describes what advantage the project will give you. Your Hotshot objectives This section explains the eight major tasks required to complete your project. Task 1 Task 2 Task 3 Task 4 Task 5 Task 6 Task 7 Task 8 Mission checklist This section explains any pre-requisites for the project, such as resources or libraries that need to be downloaded, and so on. Task 1 This section explains the task that you will perform. Prepare for lift off This section explains any preliminary work that you may need to do before beginning work on the task. Engage thrusters This section lists the steps required in order to complete the task. Objective complete – mini debriefing This section explains how the steps performed in the previous section allows us to complete the task. This section is mandatory. Classified intel This section provides some extra information relevant to the task. You will also find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning. Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: “We will go through the important features of the pygame module, which is necessary to build our arcade game, including playing sounds and controlling the menu.” A block of code is set as follows: GPIO.output(25, True) while 1: GPIO.output(25,False) sleep(1) GPIO.output(25,True) sleep(1) Any command-line input or output is written as follows: # cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample /etc/asterisk/cdr_mysql.conf New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: “clicking the Next button moves you to the next screen”. Note Warnings or important notes appear in a box like this. Tip Tips and tricks appear like this. Reader feedback Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply send an e-mail to , and mention the book title via the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors. Customer support Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase. Downloading the example code You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. Downloading the color images of this book We also provide you a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from http://www.packtpub.com/sites/default/files/downloads/6227OT_ColoredImages.pdf. Errata Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submiterrata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support. Piracy Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at with a link to the suspected pirated material. We appreciate your help in protecting our authors, and our ability to bring you valuable content. Questions You can contact us at if you are having a problem with any aspect of the book, and we will do our best to address it. Chapter 1. Hello World It is a Hotshot custom to begin learning anything new with a Hello World example. Since we will be doing really cool things in this book, we will say “Hello World” in a unique fashion. In this project, we will use the Raspberry Pi to cause an LED light to blink. This project is directed towards those who are relatively new to the Raspberry Pi environment as a warm-up exercise. Feel free to skip ahead if you have already done this with your Pi, though we suggest you look through and make sure you haven’t missed anything. A quick introduction to the Raspberry Pi If we search for the term Raspberry Pi over the web or open the Raspberry Pi Foundation’s webpage, we will find that the Raspberry Pi is a computer that is the size of a credit card. Parts of a Raspberry Pi Features of a Raspberry Pi The Raspberry Pi Foundation (http://www.raspberrypi.org/) initially released the Raspberry Pi model B. This was followed by the Raspberry Pi model A. In 2014, the Raspberry Pi foundation released variants B+ and A+. The Raspberry Pi models A and A+ (costing 25 USD and 20 USD respectively) do not come with an Ethernet port, a USB port and 256 MB RAM. The model A+ replaced model A while the model B+ replaced model B. The model B (price: 35 USD) came with an Ethernet port, 2 USB ports, and 512 MB RAM; model B+, which supersedes model B, comes with 40 pin GPIO header as opposed to 26 in the earlier models, and has 4 USB ports and a micro SD card slot instead of the SD slot. Per the Raspberry Pi Foundation website, model B+ (as well as model A+) consumes lower power, has better audio and a better form factor, which we certainly concur with. The model A+ also comes with a 40 pin GPIO header and a micro SD card slot. The models A+ and B+ have nine more GPIO pins than their predecessors. Note The Raspberry Pi 2 was released after we finished writing the book. Please refer to the book’s site to find out more about getting started with model 2. The objective of this book is to build cool projects using the Raspberry Pi. We will discuss the components of Raspberry Pi from this perspective. If you are interested in finding out more about the Raspberry Pi, the Raspberry Pi Foundation’s webpage has published the technical specifications of all the components. First, we will discuss the components available on the Raspberry Pi and the use of these components in our projects. The components of the Raspberry Pi include: 2 USB ports (1 USB port available in model A) Ethernet port (available only in models B and B+) RCA output HDMI output Audio output Low level peripherals, which include: GPIO (General Purpose Input Output) UART/Serial Port (Universal Asynchronous Receiver Transmitter) I2C (two wire interface) SPI (Serial Peripheral Interface) Where can I buy a Raspberry Pi? Element14 and RS Components are the most common distributors of the Raspberry Pi in the United States. The Raspberry Pi model A was roughly priced at 25 USD, while its successor model A+ was priced at 20 USD. The model B was priced at 35 USD and the model B+ is priced at 40 USD. There are also an ever increasing number of local distributors such as Adafruit and Fry’s Electronics in the US that sell the Raspberry Pi for a margin. Please check the Raspberry Pi Foundation website and other sources for more vendors. Requirements to get started with the Raspberry Pi In this section, we will discuss the items required to get started with the Raspberry Pi. We will need all the same things that are required to use a computer/laptop. They are: Display Keyboard Mouse Wi-Fi Adapter / Ethernet cable Note It is possible to use the Raspberry Pi via remote login using a secure shell. This might seem difficult to those who are new to the Linux environment. The setup of the Raspberry Pi for remote login is explained in Project 13, Tips and Tricks. The Raspberry Pi eLinux wiki (http://elinux.org/RPi_Hub) has listed peripherals that have been tested and confirmed to have worked on the Raspberry Pi. You have the freedom to choose peripherals according to your choice. Display: The Raspberry Pi is provided with an HDMI output and an RCA output. It is possible to connect a monitor that has an HDMI input. It is also possible to connect monitors that have a DVI input with an HDMI to the DVI cable. Power supply: Since the Raspberry Pi consumes 700 mA for its operation, it is recommended that the reader uses powered USB hubs to use devices such as Wi-Fi adapters as opposed to plugging in devices such as the Wi-Fi adapters directly to the USB port of the Raspberry Pi to avoid the device resetting itself. Operating systems on the Raspberry Pi The Raspberry Pi foundation recommends the following operating systems on the Raspberry Pi. They are: Raspbian Arch Linux ARM RISC OS You are welcome to choose any operating system of your choice. For beginners, we strongly recommend the Raspbian OS for projects. The Raspbian is equipped with tools to get started easily. The Raspberry Pi’s firmware is implemented such that the operating system is loaded from an SD card. Getting started with Raspbian In this section, we will download an image from the Raspberry Pi Foundation’s webpage to a computer, flash an SD card with the image, and set up the operating system on the Raspberry Pi. We will also try to write and execute our first example. Downloading Raspbian The latest Raspbian image is hosted on the Raspberry Pi Foundation’s webpage (http://www.raspberrypi.org/downloads/). The latest image at the time of writing this book was Raspbian wheezy. We need to download the image and extract it to the folder of our choice. Raspbian wheezy on the Raspberry Pi Foundation’s website Flashing image on to the SD card We will discuss flashing the SD card with the Raspbian image on both Windows and Linux machines. Windows Extract the files to a location of your choice. The Win32DiskImager tool is required to prepare the SD card with the Raspbian image. Tip A standard Raspbian image is about 1.8 GB big. It is strongly recommended that you use an SD card that is at least of 4 GB big. The Win32DiskImager tool We can flash the SD card in three simple steps (as shown in the preceding screenshot): 1. 2. 3. 4. Select the SD card that needs to be flashed. Select the Raspbian image location. Click on Write. Click on Yes to confirm. Confirm overwriting the SD card 5. It can take a while before the write cycle is completed. Linux There are two identical methods to flash an SD card on a Linux machine. The two approaches include: A GUI-based approach A command-line interface-based approach A command-line interface-based approach The SD card can be flashed in three simple steps using a command-line interface. These steps are as follows: 1. Identify the SD card mount point. 2. Unmount the SD card. 3. Flash the SD card. Identifying the SD card mount point As soon as we insert the SD card into a USB card reader or an SD card slot found on a laptop, we need to open a terminal on our Linux machine. We need to identify our device’s mount point on the machine using the following command: df –h The devices enumerated on the machine will be listed as shown in the following screenshot: Storage devices identified by the operating system Unmount the SD card In the previous example, the /dev/sdb5 path is the storage device of interest. There may be more than one storage device that might be connected to a machine. We need to make sure that we have identified the right device. Once we have identified the device, it has to be unmounted using the following command: umount /dev/sdb Flash the SD card Now, we will flash our SD card using the following command: dd bs=4M if=~/2012-09-18-wheezy-raspbian.img of=/dev/sdb The if= argument points to the location of the image and of= refers to the SD card mount point. The write operation takes a while to complete and it is ready for use on the Raspberry Pi upon completion. GUI-based approach On a Debian Linux-based operating system, there is a package called usb-imagewriter. The ImageWriter package performs the same operations required to flash an SD card. A USB ImageWriter on Ubuntu Setting up the Raspberry Pi Now that the image is flashed, let’s get started with setting up the Raspberry Pi for the first time. We will have to insert the SD card slot found on the other side of the Raspberry Pi. A flashed SD card in the slot When the keyboard and the mouse are connected, we can get started by powering up the Raspberry Pi! Once the Raspberry Pi is powered up, the operating system boots up to Raspi-config. The raspi-config is the tool used to set up desktop options, keyboard settings, storage settings, and so on. The Raspi-config screen is shown in the following screenshot: The Raspi-config screen In this section, we will discuss each feature of the raspi-config tool: info: As the name suggests, this section gives the general information about the tool. expand_rootfs: While the SD card is flashed with the operating system image, the SD card is partitioned just about the size of the image. This command aids to expand the partition so that the remaining space can be used for file storage. overscan: This is an option used when the Raspberry Pi is connected to the television. configure_keyboard: This option is used to configure the change_type option of the keyboard. change_pass: The default password is raspberry, and if necessary, this option lets you switch to a stronger password. change_locale: The option lets you change the language preferences. change_timezone: We can set our current time zone using this option. memory_split: This option lets us split the memory between the ARM processor’s CPU and the graphics processor. overclock: The default clock speed is 700 MHz. This option lets you set the clock speed to 1 GHz. This might vary for Raspberry Pi 2. ssh: This option enables the secure shell server. This is required to remotely log in the Raspberry Pi and control devices remotely. It is enabled by default on Raspbian. boot_behaviour: This option enables you to boot directly into the desktop. Tip It is important that you enable this option on as the default option boots into a normal text-based console. update: If the Raspberry Pi is connected to the Internet using an Ethernet raspi-config tool downloads any package that might be available. cable, the Once we complete the setup process by selecting Finish, the Raspberry Pi reboots and expands the filesystem if necessary. Mission briefing In this project, we will set up the GPIO (General Purpose Input Output) peripheral on the Raspberry Pi and write our first program to cause an LED to blink. At the end, we will repeat the same steps with a Raspberry Pi add-on board called PiCrust. This will allow you to get your feet wet and ensure you have all the right tools going forward, and should you need to, troubleshoot any problems you might identify. Why is it awesome? Think of saying “Hello World” as both a nod to programming tradition and a dry run to ensure you are well equipped! Your Hotshot objectives The objectives for this mission are quite simple, and yet take us all several milestones further! Here are the objectives of the Hello World mission: Collect all the necessary tools Set up the GPIO peripheral Introduce ourselves to the Raspberry Pi environment Turn a light emitting diode (LED) on and off with a 1 second delay Mission checklist Go over the previous sections, and make sure you have all the tools. Download the GPIO libraries, and ensure you can log in to the Raspberry Pi remotely, and you are all set! Note There are two different ways to use a Raspberry Pi. They are: Connecting a monitor to the HDMI port or the RCA jack and a keyboard to the USB port of the Raspberry Pi. Remotely logging into the Raspberry Pi from the reader’s workstation. If you are a beginner, it is best to use the first method while the second method can be used if you are familiar with the Linux operating system and remote login capabilities. Once we complete the setup process by selecting Finish, the Raspberry Pi reboots and expands the file system if necessary. Hunting and gathering As stated before, you will need to make sure you have all the tools. So, go ahead, hunt and gather away. Grab at least one of each of the following and more than one of each, if you, like us, are prone to accidents: A laptop to download the Raspberry Pi image and set up everything Raspberry Pi—Model B/B+ (preferred), a keyboard, and a mouse for the Raspberry Pi (optional) SD card with 4GB memory (SD card preparation was explained earlier in this project) USB Power Adapter (Rated 1.0 A) and Micro USB power cable Ethernet cable Wi-Fi adapter—(optional) refer to the eLinux wiki for Raspberry Pi for verified peripherals Breadboard Jumper wires Discrete Resistor Values A work bench (or a clean working surface—hopefully you have one) Good thoughts and a can-do attitude Lots of coffee, tea, or a safe beverage of your choice Engage thrusters You will need all of the tools listed in the previous section to get through this project. Take your time and make sure you have everything handy! Objective complete – mini debriefing Do you have all the tools? Ready to go? Then on to the next task! Setting up the GPIO We need to enable the GPIO peripherals in our Raspbian installation to get started. In order to download the required tools and set things in motion, the Raspberry Pi needs to be connected to the Internet. The GPIO pin is a pin that is available from the Raspberry Pi’s processor that enables interfacing input and output devices to the Raspberry Pi. In this section, we will talk about setting up the GPIO for interfacing an output device. There is a 26-pin interface (40 in Model B+) available on the Raspberry Pi and about 17 of those 26 pins are GPIO pins (26 of them in Model B+) while the others are miscellaneous pins such as power. The pins are driven by a 3.3 V rail and each GPIO pin is rated for about 17 mA and the total current draw not exceeding 50 mA. Engage thrusters We also need to know the GPIO peripherals available to conduct our experiment. The following figure shows the GPIO maps of the Raspberry Pi Rev 1 and Rev 2: GPIO map for Models A, B, and B+. (Image published with permission from Raspi.tv) The letter P1 shown in the following image corresponds to P1-1 of the GPIO map. P1-1 corresponds to the first pin on the left in the front row, while P1-2 corresponds to the first pin on the left in the back row. The Raspberry Pi GPIO peripheral In this book, we will be mostly using Python programming language. Python is a very simple and easy language to learn. We may wander off to other programming languages from time to time, but we will mostly stick to Python. With this in mind, let’s get started. Installing GPIO libraries There are a lot of libraries available to access the GPIO peripheral. The easiest to install and use is the quick2wire python API. The API is used to control the GPIO peripherals and I2C devices connected to the Raspberry Pi. Note There are different libraries such as the RPi.GPIO, Pi4J, and so on. We are using the quick2wire API in this example as a beginner might find it easy to use. You are welcome to use other libraries of your choice. The quick2wire-gpio-admin tool enables controlling the GPIO pins without root access. One disadvantage of using the quick2wire module is that it provides access only to GPIO pins 0 through 7. The terminal can be located in the left corner of the desktop and has been highlighted in the following screenshot: A Command-line terminal on the Raspbian desktop 1. The quick2wire library installation is based on a post on the quick2wire website (http://quick2wire.com/articles/how-to-add-quick2wire-as-a-raspbian-software- source/). In order to install the quick2wire-python library, the repository needs to be added to /etc/apt/sources.list. In the command line, the repository is added by using the nano text editor: sudo nano /etc/apt/sources.list The following lines need to be added to the file: # Quick2Wire Software deb http://dist.quick2wire.com/raspbian wheezy main deb-src http://dist.quick2wire.com/raspbian wheezy main The file can be saved by typing CTRL+X. The file can also be saved by pressing Y key while exiting the editor. Alternatively, the lines can be added using a graphical text editor such as, leafpad and saving it: sudo leafpad /etc/apt/sources.list 2. In order to ensure that the packages are downloaded from the quick2wire repository, we need to authenticate the packages using a key available from quick2wire: wget https://raw.githubusercontent.com/quick2wire/quick2wire-softwareusers/master/software@quick2wire.com.gpg.key sudo apt-key add software@quick2wire.com.gpg.key 3. The cache is updated and the latest software packages can be downloaded as follows: sudo apt-get update sudo apt-get upgrade 4. The quick2wire tool is installed as follows: sudo apt-get install quick2wire-gpio-admin sudo apt-get install quick2wire-python3-api Objective complete – mini debriefing Now, wasn’t that easy? Let’s get more familiar with the GPIO input/output operations. GPIO programming using Python In this section, we will ensure that the library is correctly installed and add the user to the group. This will enable the user to use the GPIO pins without having root privileges. This will be followed by the section on getting started with GPIO control programming in Python. Engage thrusters In order to get started with programming in the Raspberry Pi, we will launch Python IDLE3 from the desktop. Launching IDLE3 from the desktop 1. Now, we have to get started with programming the LED blinking example in IDLE3. 2. This LED blinking sample code is as follows: from time import sleep from quick2wire.gpio import pins, Out with pins.pin(7, direction=Out) as out_pin: while True: out_pin.value = 1 sleep(1) out_pin.value = 0 sleep(1) out_pin.unexport() 3. We will import the sleep class from the time module in the first line. This is required to introduce a 1-second delay between turning the LED on and off every other second: from time import sleep 4. We also need the pin class from the quick2wire GPIO library: from quick2wire.gpio import Pin 5. We need to set the output pin that we will be using in the example: LED_output = Pin(8, Pin.Out) 6. We can set the pin to the logical high (3.3 V) as follows: LED_output=1 7. We will set the pin to the logical low (0 V) as follows: LED_output=0 8. We will execute the same thing using an infinite while loop: while True: LED_output=1 sleep(1) LED_output=0 sleep(1) 9. This will make the LED blink with a 1-second delay. We should also note the indent on the blink sequence. The blink sequence has a different indent compared to the while loop. Hence, the code that is at a different indent is executed infinitely. 10. When the program is interrupted (by pressing CTRL + C on the keyboard), we need to unexport the pins at exit: out_pin.unexport() An alternative to quick2wire – RPi.GPIO 1. Another alternative is to use RPi.GPIO (https://pypi.python.org/pypi/RPi.GPIO). It comes as a standard package along with the Raspbian Wheezy OS. Let’s perform a quick review of the code: import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BCM) GPIO.setup(8,GPIO.OUT) GPIO.output(8,GPIO.LOW) while True: GPIO.output(8,GPIO.HIGH) sleep(1) GPIO.output(8,GPIO.LOW) sleep(1) GPIO.cleanup() 2. After importing the required modules, we get started with setting up the pin numbering mode. There are two types of pin numbering modes, namely: The BCM Pin numbering mode: The pin numbers are based upon the pin numbers of the BCM chip. The Board numbering mode: The pin numbers are based upon the pin numbers of the Raspberry Pi GPIO header. In this example, we will set the BCM numbering mode and set pin 8 as the output: GPIO.setmode(GPIO.BCM) GPIO.setup(8,GPIO.OUT) 3. We can set the pin to logical high (3.3 V) as follows: GPIO.output(8,GPIO.HIGH) 4. We can set the pin to logical low (3.3 V) as follows: GPIO.output(8,GPIO.LOW) 5. Now, the LED can be made to blink with a 1 second delay: while True: GPIO.output(8,GPIO.HIGH) sleep(1) GPIO.output(8,GPIO.LOW) sleep(1) 6. When the program is interrupted by typing CTRL + C, we have to clean up and release any occupied GPIO resources: GPIO.cleanup() Objective complete – mini debriefing In this section, we finished writing a program to make an LED blink. In the next section, we will put a circuit together that makes an LED blink. Electrical output of our program In the previous section, we wrote a program to make an LED blink. Let’s look at the electrical connection to observe the output of our program. We will connect a resistor between the GPIO pin and the anode of the LED. We will connect the cathode to the ground pin of the Raspberry Pi. Engage thrusters We will connect the LED and the resistor to the GPIO pin and the ground pin, as shown in this image: LED blinking circuit Note If we are not careful with the handling of the Raspberry Pi GPIO pins, it may either temporarily reset the Raspberry Pi or sometimes even permanently damage the GPIO pin. There are several tutorials in basic electronics available over the Web. It is important that you familiarize yourself with the basics of electronics. Once we connect the circuit as shown in the preceding image, we will be able to execute the program and conclude our experiment. We can execute the program by running the module, as shown in the following screenshot: Executing the Python example Objective complete – mini debriefing That’s it! We have wet our feet by saying Hello World by blinking an LED! On our way to bigger and better things, let’s stop and examine the Pi Crust for a moment. Introduction to the Pi Crust – a prototyping platform for the Raspberry Pi Now that our Hello World example is done, we will leave you with one more thing. Throughout this book, we will review some add-on hardware to access the GPIO peripherals on the Raspberry Pi. In this project, we will discuss the Pi Crust board for the Raspberry Pi. The Pi Crust board was designed by Joe Walnes. It is a board that is stackable on the Raspberry Pi and eliminates the need for a breadboard to prototype circuits. A Pi Crust board The Pi Crust is an open source add-on hardware and costs approximately $14 to build one ourselves. The design can be downloaded free of cost from http://picru.st. So, it is up to you to decide whether you want to simply buy one, build one, or as we are prone to encourage, improve upon it and open source it for others to benefit! The main advantage behind Pi Crust is that it is aids prototyping. It allows easy access to the I2C interface, SPI interface, UART port, and the GPIO pins. The following figure shows BlinkM—an I2C-driven RGB LED mounted on top of the Pi Crust. Pi Crust stacked on top of the Raspberry Pi Mission accomplished Now that you have traveled this far with us, how do you feel? Do you need a break, or more coffee? Before you do either, let’s review. In this project, we got started with the LED blinking example using the Raspberry Pi. We discussed the setup of GPIO peripherals and using them in an experiment. You are welcome to continue experiments with the GPIO peripherals with projects such as LED sequencing, three bit counter, and so on. In the forthcoming projects, we will look into I2C communication, SPI communication, and UART communication (serial port). Hotshot challenge Well done; you have taught your Pi to say “Hello World”! However, we are sure you can do more, much more. Have you watched the movie Close Encounters of the Third Kind? Well, if not, you should. However, this is not a challenge in itself. In the movie, the human beings attempt at communication with what they believe is aliens by building a pattern of lights that are set to music. Can you make a pattern of LEDs repeat that or something similar? Chapter 2. A Raspberry WebIDE Example In this project, we will learn how to develop projects using the WebIDE from Adafruit Industries. We will flash an SD card with the Raspbian OS, install the Occidentalis tool (https://learn.adafruit.com/adafruit-raspberry-pi-educational-linux-distro/occidentalis-v0dot-3), set up the web-based development tool, and test the setup using an example. Note Occidentalis was initially available as a Raspbian OS image by Adafruit Industries. It comprised of the toolset that enabled to get started with project development using the Raspberry Pi. The OS image was deprecated and released after we finished writing the book. We have taken our best effort to update the book. Please refer to this book’s website for more information. Mission briefing In this project, we will discuss installing a tool, Occidentalis, and a WebIDE that enables programming in the Python language on the Raspberry Pi. We will also discuss one example from the Adafruit repository and another example of driving an RGB LED. The following table lists the bill of materials used in this project. These are just examples, and alternative products that have a similar specification may also be used. Item Estimated Cost Raspberry Pi Model B 35 USD Adafruit Cobbler (https://www.adafruit.com/product/914) 7 USD Adafruit 7-segment LED Backpack (https://www.adafruit.com/product/879) 10 USD Blinkm (https://www.sparkfun.com/products/8579) 13 USD Why is it awesome? The Adafruit WebIDE in combination with the Occidentalis operating system enables development in the Python language on a Raspberry Pi using just a web browser. It also enables access to sample projects developed by Adafruit via Bitbucket, a source control tool. (If you are not familiar with source control tools such as Bitbucket, Git, and so on, the examples in this project are a great way to get started!) The Adafruit WebIDE is a tool developed for hobbyists and comes with examples for techniques such as pulse-width modulation (used in lighting system control) and I2C communication, and also provides examples for controlling products from Adafruit. Note The Adafruit WebIDE is now a beta release and it may not work successfully across different platforms. The Adafruit learning system has indicated that this development tool was directed towards advanced hobbyists. We have taken our best efforts to explain it as simply as possible. Pulse-width modulation is a technique used widely in motor control, lighting systems, and so on. It is a technique where the average voltage applied to a device is varied by changing the width of the pulse. There are several tutorials on pulse-width modulation (https://learn.sparkfun.com/tutorials/pulse-width-modulation) available all over the Web. I2C communication (https://learn.sparkfun.com/tutorials/i2c) is a form of serial communication interface used to connect multiple slave devices (usually sensors) with a master device (Raspberry Pi or a microcontroller) through a common interface. Your Hotshot objectives In this project, we will discuss the following features: Bootstrapping your Raspberry Pi by installing Occidentalis Setup of remote login into the Raspberry Pi Installation of the Raspberry Pi WebIDE Python development on the WebIDE Test and debugging examples using the WebIDE Note This project should not be considered as an attempt to promote Adafruit Industries or their products developed for their platform. This project merely demonstrates simplification of development on the Raspberry Pi using a tool from Adafruit Industries. Mission checklist In order to get started, the first step is to install the Occidentalis distro, which is a derivative of the Raspbian operating system. The things required to get started are as follows: A 4 GB SD card flashed with the Raspbian OS An Occidentalis image. An Ethernet cable Installation, features, and usage of the Occidentalis operating system from Adafruit The first step is installing Occidentalis on the Raspberry Pi. Prepare for lift off The first step is the installation of the Adafruit-Pi-Finder tool. The tool can be downloaded from https://github.com/adafruit/Adafruit-Pi-Finder/releases/latest. It is available for Windows, Linux, and Mac platforms. Engage thrusters 1. You can find detailed instructions on installing the Occidentalis tool at https://github.com/adafruit/Adafruit-Pi-Finder. 2. Alternatively, a step-by-step instruction is also available on this book’s website. We cannot include them here since changes were made to Occidentalis installation process after we finished writing this book. Objective complete – mini debriefing Once the installation is complete, we have to ensure that the Raspberry Pi as well as the development machine are connected to the network via the Ethernet port or a USB Wi-Fi dongle. Setup of a remote login into the Raspberry Pi In this section, we will remotely log in to the Raspberry Pi using a secure shell. Since the Raspberry Pi comes with sshd enabled, it is possible to log in remotely using the local name, raspberrypi.local (During the bootstrapping process, the avahi-daemon tool is installed and hence, it is possible to remotely log in to the Raspberry Pi using the local name, raspberrypi.local). Alternatively, on a Windows machine, you can use a tool such as Advanced IP Scanner (http://www.advanced-ip-scanner.com/) to find the IP address of the Raspberry Pi. A snapshot of this tool is shown later in this project. Note If you are using a Windows machine, the Bonjour Print Services drivers have to be installed to remotely log in using the local name, raspberrypi.local. The Bonjour Print Services drivers are available from http://support.apple.com/kb/DL999. Prepare for lift off The IP address of the Raspberry Pi can be identified using tools such as Advanced IP Scanner, as shown in the following screenshot: A list of devices and IP addresses connected to a network similar to the Raspberry Pi Engage thrusters 1. Once we know the IP address, we use an SSH client such as PuTTY on Windows or a command-line terminal on a Linux or a Mac machine to remotely log in to the machine (in this case, we show this on a Windows machine). 2. On a Windows machine, we either use the IP address of the Raspberry Pi or its local name (raspberrypi.local) and log in to the Raspberry Pi, as shown in the following screenshot: 3. Once we enter the IP address / local name in the PuTTy window, we log in as follows: login as: pi @ 's password: raspberry Alternatively, we can also log in using the IP address of the Raspberry Pi instead of the local name, raspberrypi.local. Objective complete – mini debriefing If the username and password are entered correctly, we should be able to remotely log in to the Raspberry Pi to install the web server. Installation of the Raspberry Pi WebIDE We will get started by using a remote login client such as PuTTY to remotely log in to the Raspberry Pi and install the Adafruit WebIDE. In order to get started with examples from the Adafruit repository, we need a Bitbucket account, and Adafruit provides detailed instructions for this at http://learn.adafruit.com/webide/getting-started. Engage thrusters 1. Once we have logged in, the Adafruit learning system’s website recommends executing the following to install the web server: curl https://raw.githubusercontent.com/adafruit/AdafruitWebIDE/master/scripts/install.sh | sudo sh 2. It should take about five minutes to finish the installation. If the installation was successful, we should be able to see the message marked in the following screenshot: Successful completion of the Adafruit WebIDE installation 3. Assuming the installation was successful, we should be able to launch the Adafruit WebIDE using http://raspberrypi.local. Adafruit WebIDE launched for the first time 4. In order to make use of the examples from Adafruit Industries, we need to create a Bitbucket account (it is possible to create one with a Google account) and integrate the WebIDE with the Bitbucket account. The instructions for this are provided on the web page, as shown in the preceding screenshot. Objective complete – mini debriefing If the installation was successful, after completion of the registration, we are done with this task. Let’s move on and learn to code using the WebIDE! Python development on the WebIDE In this section, we will use a 7-segment LED backpack and the Adafruit Cobbler along with a 26-pin ribbon cable. We will test an example from the Adafruit repository (https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code). In this project, the new add-on hardware that we will discuss is the Adafruit Cobbler. The Cobbler is a small board that aids prototyping circuits on a breadboard. The Adafruit Cobbler costs about 7 USD while the ribbon cable costs about 3 USD and the 7-segment backpack costs about 10 USD. Note The earlier mentioned products are merely examples to demonstrate the Adafruit WebIDE. There are alternative prototyping platforms and products available for a higher or lower price. The Cobbler mounted on a breadboard Prepare for lift off In order to get started with the prototyping, the 26-pin ribbon cable is used to connect the GPIO interface to the Cobbler, as shown in the following image. We have to ensure that pin 1 of the GPIO header matches pin 1 of the Adafruit Cobbler. (The Cobbler comes with a shrouded header, and hence it is foolproof. However, pin 1 of the Raspberry Pi needs to be matched correctly.) Quick introduction to the I2C interface The I2C interface was invented by Phillips Semiconductors. It is a form of serial communication interface used to connect multiple slave devices (usually sensors) with a master device (Raspberry Pi or a microcontroller) through a common interface. Each device has a unique address that is used by the master to read or write data. There are plenty of resources available to familiarize ourselves with the I2C interface. We will move on to the next stage of configuring the interface. Configuring the I2C interface on the Raspberry Pi In the Occidentalis distribution, the I2C drivers are installed and enabled by default. Hence, we can get started by connecting the Adafruit 7-segment backpack to the Adafruit Cobbler, as shown in the following image. (Connections between the Cobbler and the 7segment backpack are Clock pin, SCL (C)-SCL(B) Data Pin - SDA(C) -SDA(B), 3V3(C) to +(B) GND(C) to -(B), where C is the Cobbler and B is the backpack): 7-segment backpack connections on a breadboard Now that we have connected the Raspberry Pi, the Adafruit Cobbler, and the 7-segment backpack, let’s get started with the detection of the backpack on the Raspberry Pi’s I2C interface and program an example. Before we get started with the example, we need to determine the I2C bus to which the device is connected by using the following command: sudo i2cdetect –y 0 The command outputs a table that contains the list of devices for that particular bus. Since there are no devices connected to bus 0, we scan for devices on bus 1. In this experiment, we are testing the Adafruit 7-segment backpack. In the figure that follows, the 7-segment backpack is connected to bus 1 and the device address is 0x70. Refer to the following screenshot: The i2cdetect output We should change the bus address in the code to drive the 7-segment backpack. Line 11 in the Adafruit_I2C.py file needs to be changed in the code according to the bus to which the device is connected. Hence, line 11 should be: def __init__(self, address, bus=smbus.SMBus(1), debug=False): Engage thrusters 1. The 7-segment backpack is a device controlled via an I2C port. Any I2C device has four pins, namely clock, data, power supply, and ground. The I2C device needs to be connected to the Cobbler, as shown in the earlier screenshot. 2. There are several examples available from Adafruit in the WebIDE. Let’s locate the ex_7segment_clock.py example (in the IDE, it is located at Adafruit_RaspberryPi-Python-Code | ex_7segment_clock.py). This is a simple example to display the current time on the 7-segment backpack: The ex_7segment_clock.py file location in the WebIDE 3. Let’s do a quick review of the program. We get started by importing the datetime and Adafruit_7Segment modules: The segment variable is initialized as an instance of an I2C device at the address 0x70. We enter an infinite loop and get the current time using the datetime module: now = datetime.datetime.now() hour = now.hour minute = now.minute second = now.second Since the 7-segment LED backpack consists of four digits, we write the current time at each position as follows along with a colon: # Set hours segment.writeDigit(0, segment.writeDigit(1, # Set minutes segment.writeDigit(3, segment.writeDigit(4, int(hour / 10)) hour % 10) # Tens # Ones int(minute / 10)) minute % 10) # Tens # Ones # Toggle colon segment.setColon(second % 2) # Wait one second # Toggle colon at 1Hz This exercise is repeated with a one second interval. 4. The program is executed by clicking on Run found in the IDE. If our connections were right, we should be able to see the current time on the 7-segment display (shown in the following figure). Objective complete – mini debriefing We were able to test an Adafruit product using their WebIDE in this section. A 7-segment backpack connected to the Cobbler Test and debugging examples using the WebIDE In this example, we will connect the BlinkM to the Raspberry Pi. A BlinkM is an RGB LED that can be connected to your Raspberry Pi via the I2C interface. It is possible to execute light scripts using the port. The connections to the BlinkM are similar to that of the 7-segment backpack. BlinkM connected to the Cobbler Note It is important to pay attention while connecting devices to the GPIO header of the Raspberry Pi. If there are devices that draw a lot of current from the GPIO pins, it may reset the Pi or permanently damage it in the event of a short circuit. It is assumed that you are familiar with basic electronics and capable of handling such devices. Prepare for lift off Similar to the previous experiment, we need to determine the bus to which the device is connected using the i2cdetect command. As shown in the following screenshot, the device is connected to bus 1 and the device address is 0x09: Blinkm connected to bus 1 Engage thrusters 1. The BlinkM datasheet (thingm.com/fileadmin/thingm/downloads/BlinkM_datasheet.pdf) provides step-bystep information to execute the light scripts. 2. A list of scripts available on the BlinkM is shown in the following screenshot: A list of scripts available on the BlinkM 3. Let’s see the code to execute a light script (for example, script number 6) on the BlinkM using the Adafruit WebIDE interface. In order to execute a script forever, the datasheet mentions that the following characters should be written at the I2C device address in the following sequence: 'p',