20 easy raspberry pi projects toys, tools, gadgets, and more

244 121 0
20 easy raspberry pi projects  toys, tools, gadgets, and more

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

20 EASY RASPBERRY PI® PROJECTS TOYS, TOOLS, GADGETS, AND MORE! BY RUI SANTOS AND SARA SANTOS SAN FRANCISCO 20 EASY RASPBERRY PIđ PROJECTS Copyright â 2018 by Rui Santos and Sara Santos All rights reserved No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher ISBN-10: 1-59327-843-8 ISBN-13: 978-1-59327-843-4 Publisher: William Pollock Production Editor: Laurel Chun Cover Design: Mimi Heft Interior Design: Beth Middleworth Developmental Editor: Liz Chadwick Technical Reviewer: Les Pounder Copyeditor: Rachel Monaghan Compositors: Meg Sneeringer and Laurel Chun Proofreader: James Fraleigh Cover artwork: “Electronic Circuit Board” by Creativity103 (licensed under CC BY 2.0) Circuit diagrams made using Fritzing (http://fritzing.org/) The following photographs are reproduced with permission: Figure 0-2 © Jud Froelich (courtesy of SeeMoreProject) and Figure 13-2 © Naturebytes For information on distribution, translations, or bulk sales, please contact No Starch Press, Inc directly: No Starch Press, Inc 245 8th Street, San Francisco, CA 94103 phone: 1.415.863.9900; info@nostarch.com www.nostarch.com Library of Congress Cataloging-in-Publication Data: Names: Santos, Rui (Writer on electronics), author | Santos, Sara, author | Raspberry Pi Foundation Title: 20 easy Raspberry Pi projects : toys, tools, gadgets, and more! / Rui Santos and Sara Santos Description: San Francisco : No Starch Press, Inc., [2018] Identifiers: LCCN 2017046491 (print) | LCCN 2017059387 (ebook) | ISBN 9781593278717 (epub) | ISBN 1593278713 (epub) | ISBN 9781593278434 (pbk.) | ISBN 1593278438 (pbk.) | ISBN 9781593278717 (ebook) | ISBN 1593278713 (ebook) Subjects: LCSH: Raspberry Pi (Computer) Programming Popular works | Computer programming Popular works Classification: LCC QA76.8.R15 (ebook) | LCC QA76.8.R15 S26 2018 (print) | DDC 005.1 dc23 LC record available at https://lccn.loc.gov/2017046491 No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc Raspberry Pi is a trademark of the Raspberry Pi Foundation Other product and company names mentioned herein may be the trademarks of their respective owners Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark The information in this book is distributed on an “As Is” basis, without warranty While every precaution has been taken in the preparation of this work, neither the authors nor No Starch Press, Inc shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it For the amazing people who have made this book possible (besides us) Contents Acknowledgments Introduction Primer LEDS Project 1: Blinking an LED Project 2: Pushbutton LED Flashlight Project 3: LED Dimmer Switch Project 4: A Graphical user Interface for a Multicolor LED Project 5: Rainbow Light Strip Displays Project 6: An LCD Reminder Project 7: Mini Weather Forecaster Project 8: Pong with a Sense HAT Sensors Project 9: All-in-One Weather Sensor Station Project 10: Intruder Alarm with Email Notifications Project 11: Gas and Smoke Alarm Project 12: Temperature and Humidity Data Logger Cameras Project 13: Burglar Detector with Photo Capture Project 14: Home Surveillance Camera Web Applications Project 15: Building your First Website Project 16: Connecting your Electronics to the Web Project 17: Internet of Things Control Center with Node-RED Games and Toys Project 18: Digital Drum Set Project 19: Make a Game in Scratch: Hungry Monkey Project 20: Wi-Fi Remote-Controlled Robot Raspberry Pi GPIO Pin Guide Decoding Resistor Values Contents in Detail Acknowledgments Introduction Who Is This Book For? About This Book What Do You Need for This Book? Organization of This Book Primer Getting Started with the Raspberry Pi Uses for the Raspberry Pi Differentiating Between Boards Getting to Know the Raspberry Pi and its Accessories Project Component List Uploading the Operating System Downloading Noobs Formatting a MicroSD Card on Windows or macOS Formatting a MicroSD Card on Linux Loading Raspbian onto the MicroSD Card Setting Up Your Raspberry Pi as a Desktop Computer Connecting Your Raspberry Pi Booting Up Your Pi for the First Time Desktop Tour Shutting Down, Rebooting, and Logging Off Getting Started with Python Python Integrated Development Environment Basic Python Instructions The Python Editor Your First Python Program Making a Simple Calculator LEDS Project 1: Blinking an LED Introducing the GPIO Pins Introducing LEDS Finding the Right Resistor Wiring the Circuit Writing the Script Entering the Script Running the Script Taking It Further Project 2: Pushbutton LED Flashlight Introducing Switches and Buttons Wiring the Circuit Writing the Script Taking It Further Project 3: LED Dimmer Switch Introducing Potentiometers Reading Analog Signals with Raspberry Pi Analog-to-Digital Converters Pulse-Width Modulation Wiring the Circuit Writing the Script Entering the Script Running the Script Taking It Further Project 4: A Graphical user Interface for a Multicolor LED Introducing RGB LEDs Wiring the Circuit Writing the Script Controlling the Intensity and Closing the Window Designing the User Interface with Tkinter Running the Script Taking It Further Project 5: Rainbow Light Strip Introducing the WS2812B Addressable RGB LED Strip Introducing the Logic Level Converter Wiring the Circuit Writing the Script Installing the WS281X Library Enabling SPI Communication Entering the Script Running the Script Taking It Further Displays Project 6: An LCD Reminder Introducing the Liquid Crystal Display Soldering the Headers The LCD Module Pinout Wiring Your Circuit Writing the Script Installing the Python Library for a Character LCD Displaying a Character Message Adding Other Functionality Scrolling a Reminder Message Running the Script Taking It Further Project 7: Mini Weather Forecaster Introducing the OLED Display Using the OpenWeatherMap API Understanding JSON Syntax Making an API Request Wiring the Circuit Writing the Script Installing the Library for the OLED Display Enabling I2C Communication Entering the Script Running the Script Taking It Further Project 8: Pong with a Sense HAT Introducing Pong Introducing the Raspberry Pi Sense HAT Mounting the Board Using the Sense HAT Emulator Working with Sense HAT Functions and Controls Controlling the LED Matrix Reading Data from the Joystick Writing the Script Entering the Script Running the Script Taking It Further Sensors Project 9: All-in-One Weather Sensor Station The Sense HAT as a Weather Station The Temperature Sensor The Humidity Sensor The Barometric Pressure Sensor Reading Temperature, Humidity, and Pressure Building a User Interface for Your Readings Writing the Script Creating the User Interface Automatically Updating the Readings Running the Script Taking It Further Project 10: Intruder Alarm with Email Notifications Introducing the PIR Motion Sensor Sending an Email with Python Finding Your SMTP Server Details The Email-Sending Script Running the Email-Sending Script Wiring the Circuit Writing the Script Taking It Further Project 11: Gas and Smoke Alarm Introducing the MQ-2 Gas and Smoke Sensor Introducing the Piezo Buzzer Wiring the Circuit Writing the Script Setting the Threshold Value Running the Script Taking It Further Project 12: Temperature and Humidity Data Logger Introducing the DHT22 Sensor Wiring the Circuit Writing the Script Installing the DHT22 Library Entering the Script Creating, Writing, and Closing txt Files Running the Script Taking It Further Cameras Project 13: Burglar Detector with Photo Capture Introducing the Raspberry Pi Camera Module V2 Building the Burglar Detector Enabling the Camera Connecting the Camera Wiring the Circuit Writing the Script Entering the Script Running the Script Taking It Further Project 14: Home Surveillance Camera Recording Video to a File Writing the Script Entering the Script Running the Script Taking It Further Web Applications Project 15: Building Your First Website Setting Up the Project Files Setting Up an HTML Web Page Setting Up the Basic Content Adding the Title, Headings, and Paragraphs Seeing Your Web Page Adding Links, Images, and Buttons Styling Your Page with CSS Embedding a Style Sheet Styling Your HTML Content Styling the Header Styling the title Class Styling the Headings, Paragraphs, and Links Styling the Button Taking It Further Project 16: Connecting Your Electronics to the Web Introducing Web Servers Introducing the Relay Module Relay Pinout Relay Usage Project Overview Wiring the Circuit Preparing Your Pi to Run a Web Server Installing Flask Organizing Your Files Writing the Scripts Creating the Web Server Writing the HTML File Writing the CSS File Launching Your Web Server Taking It Further power source while creating the Node-RED application; once it’s ready, you should change to the portable power source You’ll find the Pi’s IP address using Angry IP Scanner software Download it onto your regular desktop or laptop computer for free from http://angryip.org/download/, and then follow the prompts to install it Once the installation is complete, open Angry IP Scanner and click the Start button Wait a few seconds until it shows the available IP addresses Your Pi IP address should have raspberrypi.lan as a hostname, so jot down the corresponding IP address Figure 20-4 highlights our Raspberry Pi IP address, which is 192.168.1.122 FIGURE 20-4: Finding the Raspberry Pi IP address with the Angry IP Scanner software Creating the Node-RED Flow NOTE For an introduction to Node-RED, see Project 17 On your regular computer, making sure it’s on the same network as your Pi, open a web browser tab and go to http://:1880, replacing with the Raspberry Pi IP address you noted earlier In our case, we navigated to http://192.168.1.122:1880 Your Raspberry Pi NodeRED web server should open In the top-right corner of the window, select the dashboard tab and, inside the Layout tab, create a tab called Robot Next, create two groups inside that Robot tab, called Main and Poweroff The Main group is where you’ll organize the buttons that control the robot, and the Poweroff group is where you’ll add the button to remotely turn off your Raspberry Pi Once you’ve completed these tabs and groups, your layout should look like Figure 20-5 FIGURE 20-5: Node-RED application dashboard layout Add five buttons, a function, six rpi gpio output nodes, and an exec node to the flow Wire the nodes and edit their names to match the ones in Figure 20-6 FIGURE 20-6: Node-RED application nodes Edit the function’s properties so that it has six outputs, assigning all of the nodes’ properties as shown in Table 20-1 TABLE 20-1: Properties assigned to each node NODE PROPERTIES Group: Main [Robot] Size: auto Forward Icon: fa-arrow-up Label: Forward Payload: forward Left Group: Main [Robot] Size: auto Icon: fa-arrow-left Label: Left Payload: left Right Group: Main [Robot] Size: auto Icon: fa-arrow-right Label: Right Payload: right Group: Main [Robot] Size: auto Reverse Icon: fa-arrow-down Label: Reverse Payload: reverse Stop f Group: Main [Robot] Size: auto Icon: fa-hand-paper-o Label: Stop Payload: stop Function: enter the code in Listing 20-1 Outputs: Enable M1 GPIO: GPIO5 – 29 Type: Digital output + M1 GPIO: GPIO27 – 13 Type: Digital output – M1 GPIO: 18 – GPIO24 Type: Digital output Enable M2 GPIO: GPIO17 – 11 Type: Digital output + M2 GPIO: GPIO6 – 31 Type: Digital output – M2 GPIO: GPIO22 – 15 Type: Digital output Group: Poweroff [Robot] Size: auto Poweroff Icon: fa-power-off Label: Poweroff Background: red Command: /usr/bin/sudo + Append: not checked exec poweroff Name: Poweroff Figure 20-7 shows how the exec node is set up FIGURE 20-7: exec node properties All nodes should be in the Main group, except the Poweroff button, which should be part of the Poweroff group Entering the Script Insert the JavaScript code in Listing 20-1 (also available https://www.nostarch.com/RaspberryPiProject/) into the function node: LISTING 20-1: The remote-controlled robot script ➊ var msg1 = { payload: }; var msg2 = { payload: }; var msg3 = { payload: }; var msg4 = { payload: }; var msg5 = { payload: }; var msg6 = { payload: }; ➋ if (msg.payload === "forward") { msg1.payload = 1; msg2.payload = 1; msg4.payload = 1; msg5.payload = 1; } else if (msg.payload === "left") { for download from msg1.payload = 1; msg2.payload = 1; } else if (msg.payload === "right") { msg4.payload = 1; msg5.payload = 1; } else if (msg.payload === "reverse") { msg1.payload = 1; msg3.payload = 1; msg4.payload = 1; msg6.payload = 1; } ➌ return [msg1, msg2, msg3, msg4, msg5, msg6]; This function sends messages to the connected rpi gpio output nodes in the order they’re connected to the function node This means that msg1 is sent to the Enable M1 node, msg2 to + M1, msg3 to – M1, and so on (see Figure 20-6) First you initialize all the payload message variable values to ➊ Then the series of if and else if statements checks which button was pressed ➋, depending on the payload received by the function, and sets the message values according to the action the robot should take For example, if you press the Forward button, the payload received by the function node is forward, so the condition at ➋ is met and the code changes the msg1, msg2, msg4, and msg5 payload values to 1, while msg3 and msg6 remain Then, the function node sends the msg.payload values to the corresponding nodes ➌ For the robot to go forward, the payloads would need to be: Enable M1: + M1: – M2: Enable M2: + M2: – M2: Here, both motors are enabled and moving in the same direction—forward The following table shows the messages the function should send to each node for each action ACTION ENABLE M1 + M1 – M1 ENABLE M2 + M2 – M2 Forward 1 1 Left 1 0 0 Right 0 1 Reverse 1 1 Stop 0 0 0 When the Stop button is clicked, none of the conditions set in the code is met, and the function sends the values initialized at the start ➊ Outside the function node, when the Poweroff button is clicked, the exec node executes the poweroff command to turn off the Pi Remember that you’ve filled the exec command property with /usr/bin/sudo/poweroff—see Table 20-1 Once everything is in place, click the Deploy button at the top-right corner to save the changes and run the flow Running the Application Now your Node-RED application is ready Go to http://:1880/ui (replacing with your own) to see your application dashboard It should look something like Figure 208 Test the controls to see if the wheels are moving in the right direction, and don’t forget that you need to insert the four AA batteries into the battery holder in order to power the motors If one or both motors are spinning in the wrong direction, switch the black and red wires on the MotoZero for that motor terminal, or change the payload messages to match the required directions FIGURE 20-8: Node-RED application to remotely control the robot POWERING UP THE ROBOT Now that the application is ready, click the Poweroff button to shut down the Pi Then wait a few seconds for it to shut down Change the Pi’s power source from the wall socket to the power bank Wait a few minutes for the Pi to power up and autostart Node-RED On a smartphone or other device that’s on the same network as your Pi, open a new browser tab and go to http://:1880/ui Then click on the buttons to remotely control your robot Congratulations—you now have a Wi-Fi-controlled robot! TAKING IT FURTHER There’s a lot of room for upgrades on your robot Here are some ideas for upgrades that will need both hardware and software changes You’ll need to experiment a bit with Node-RED to get these working: Get a robot chassis with four wheels and control four motors instead of two Add LEDs and buzzers to the robot to make it more interactive Add sensors, like an ultrasonic sensor, so the robot can avoid obstacles by itself Raspberry Pi GPIO Pin Guide This guide is a GPIO pin reference for all available Raspberry Pi boards to date Use the tables to check for the pin’s location, name, and function The following table shows the GPIOs for the Raspberry Pi Model B, Raspberry Pi Model B, Raspberry Pi Model A+, Raspberry Pi Model B+, Raspberry Pi Zero, and Raspberry Pi Zero W FUNCTION NAME NAME FUNCTION DC power 3.3 V 5V DC power SDA1, I2C GPIO 5V DC power SCL1, I2C GPIO GND GPIO_GCLK GPIO GPIO 14 TXD0 GND 10 GPIO 15 RXD0 GPIO_GEN0 GPIO 17 11 12 GPIO 18 GPIO_GEN1 GPIO_GEN2 GPIO 27 13 14 GND GPIO_GEN3 GPIO 22 15 16 GPIO 23 GPIO_GEN4 DC power 3.3 V 17 18 GPIO 24 GPIO_GEN5 SPI_MOSI GPIO 10 19 20 GND SPI_MISO GPIO 21 22 GPIO 25 GPIO_GEN6 SPI_CLK GPIO 11 23 24 GPIO SPI_CE0_N GND 25 26 GPIO SPI_CE1_N DNC 27 28 DNC I2C ID EEPROM GPIO 29 30 GND GPIO 31 32 GPIO 12 GPIO 13 33 34 GND GPIO 19 35 36 GPIO 16 GPIO 26 37 38 GPIO 20 GND 39 40 GPIO 21 I2C ID EEPROM NUMBER NUMBER Raspberry Pi Model A and Raspberry Pi Model B Rev have the same pinout but have only the first 26 pins The Raspberry Pi Model B Rev was the very first Raspberry Pi board released and has a different pinout from all the other boards These boards aren’t available anymore, but just in case you have one, here’s the pinout FUNCTION NAME NUMBER NUMBER NAME FUNCTION DC power 3.3 V 5V DC power SDA0, I2C GPIO 5V DC power SCL0, I2C GPIO GND GPIO_GCLK GPIO GPIO 14 TXD0 GND 10 GPIO 15 RXD0 GPIO_GEN0 GPIO 17 11 12 GPIO 18 GPIO_GEN1 GPIO_GEN2 GPIO 21 13 14 GPIO_GEN3 GPIO 22 15 16 GPIO 23 GPIO_GEN4 GPIO 24 GPIO_GEN5 GND DC power 3.3 V 17 18 SPI_MOSI GPIO 10 19 20 SPI_MISO GPIO 21 22 GPIO 25 GPIO_GEN6 SPI_CLK GPIO 11 23 24 GPIO SPI_CE0_N GND 25 26 GPIO SPI_CE1_N GND Decoding Resistor Values This quick guide shows you how to identify different resistors A resistor is a passive electrical component that creates resistance to the electrical flow, limiting the amount of current reaching a certain part of the circuit In this book, you use resistors mainly to limit the amount of current reaching LEDs Use this resistor color chart to help you calculate a resistor’s resistance value from the bands on its body COLOR FIRST BAND SECOND BAND THIRD BAND MULTIPLIER TOLERANCE Black 0 1Ω Brown 1 10 Ω +/–1% Red 2 100 Ω +/–2% Orange 3 KΩ Yellow 4 10 KΩ Green 5 100 KΩ +/–0.5% Blue 6 MΩ +/–0.25% Violet 7 10 MΩ +/–0.10% Gray 8 White 9 +/–0.05% Gold 0.1 Ω +/–5% Silver 0.01 Ω +/–10% Resistors usually have four bands The first two digits represent the first two digits of the value The third is a multiplier representing the number of zeros after the first two digits The fourth is the tolerance of the resistance For example, let’s calculate the resistance of the resistor in Figure B-1 Figure B-1: A four-band resistor The first band is green (5) = The second band is blue (6) = The third band is yellow (4) = 0000 (indicates the number of zeros) The fourth band is gold, so the tolerance is +/– percent The resistance value is therefore 56 × 10,000 (10 kΩ), which results in 560 kΩ The tolerance is percent, which means the resistance value may be between 560 kΩ ± 5%, so between 532 kΩ and 588 kΩ You don’t need to worry too much about the tolerance unless you’re using really sensitive components For this book, resistors with percent tolerance are fine to use UPDATES Visit https://www.nostarch.com/RaspberryPiProject/ for updates, errata, and other information More no-nonsense books from NO STARCH PRESS ARDUINO PROJECT HANDBOOK, VOL 25 Practical Projects to Get You Started by MARK GEDDES JUNE 2016, 272 pp., $24.95 ISBN 978-1-59327-690-4 full color THE ARDUINO INVENTOR’S GUIDE Learn Electronics by Making 10 Awesome Projects by BRIAN HUANG and DEREK RUNBERG JUNE 2017, 336 pp., $29.95 ISBN 978-1-59327-652-2 full color ARDUINO WORKSHOP A Hands-On Introduction with 65 Projects by JOHN BOXALL MAY 2013, 392 pp., $29.95 ISBN 978-1-59327-448-1 THE MAKER’S GUIDE TO THE ZOMBIE APOCALYPSE Defend your Base with Simple Circuits, Arduino, and Raspberry Pi by SIMON MONK OCTOBER 2015, 296 pp., $24.95 ISBN 978-1-59327-667-6 ARDUINO PLAYGROUND Geeky Projects for the Experienced Maker by WARREN ANDREWS MARCH 2017, 344 pp., $29.95 ISBN 978-1-59327-744-4 LED PROJECT HANDBOOK Edited by JOHN BAICHTAL SPRING 2018, 280 pp., $24.95 ISBN 978-1-59327-825-0 full color PHONE: 1.800.420.7240 OR 1.415.863.9900 EMAIL: sales@nostarch.com WEB: www.nostarch.com .. .20 EASY RASPBERRY PI PROJECTS TOYS, TOOLS, GADGETS, AND MORE! BY RUI SANTOS AND SARA SANTOS SAN FRANCISCO 20 EASY RASPBERRY PI PROJECTS Copyright â 201 8 by Rui Santos and Sara Santos... author | Raspberry Pi Foundation Title: 20 easy Raspberry Pi projects : toys, tools, gadgets, and more! / Rui Santos and Sara Santos Description: San Francisco : No Starch Press, Inc., [201 8] Identifiers:... Raspberry Pi and Its Accessories Let’s take a closer look at a Raspberry Pi board Figure 0-4 shows an annotated Raspberry Pi Model B board FIGURE 0-4: The Raspberry Pi Model B The Raspberry Pi

Ngày đăng: 04/03/2019, 10:05

Từ khóa liên quan

Mục lục

  • Title Page

  • Copyright Page

  • Dedication

  • Contents

  • Contents in Detail

  • Acknowledgments

  • Introduction

  • Primer

  • LEDS

    • Project 1: Blinking an LED

    • Project 2: Pushbutton LED Flashlight

    • Project 3: LED Dimmer Switch

    • Project 4: A Graphical user Interface for a Multicolor LED

    • Project 5: Rainbow Light Strip

    • Displays

      • Project 6: An LCD Reminder

      • Project 7: Mini Weather Forecaster

      • Project 8: Pong with a Sense HAT

      • Sensors

        • Project 9: All-in-One Weather Sensor Station

        • Project 10: Intruder Alarm with Email Notifications

        • Project 11: Gas and Smoke Alarm

        • Project 12: Temperature and Humidity Data Logger

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan