ebook img

Programming the Raspberry Pi Pico/W in MicroPython, Second Edition PDF

360 Pages·2022·11.509 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Programming the Raspberry Pi Pico/W in MicroPython, Second Edition

Programming the Raspberry Pi Pico/W in MicroPython Second Edition Harry Fairhead & Mike James I/O Press I Programmer Library Copyright © 2022 IO Press All rights reserved. This book or any portion thereof may not be reproduced or used in any manner whatsoever without the express written permission of the publisher except for the use of brief quotations in a book review. Harry Fairhead & Mike James, Programming the Raspberry Pi Pico in MicroPython 2nd Edition ISBN Paperback: 9781871962802 ISBN Hardback: 9781871962062 First Printing, 2022 Revision 0 Published by IO Press www.iopress.info In association with I Programmer www.i-programmer.info and with I o T Programmer www.iot-programmer.com The publisher recognizes and respects all marks used by companies and manufacturers as a means to distinguish their products. All brand names and product names mentioned in this book are trade marks or service marks of their respective companies and our omission of trade marks is not an attempt to infringe on the property of others. In particular we acknowledge that Raspberry Pi and Pico are registered trademarks of the Raspberry Pi Foundation. For updates, errata, links to resources and the source code for the programs in this book, visit its dedicated page on the IO Press website: iopress.info. 2 Preface The Raspberry Pi Pico is a remarkable microcontroller. Based on the RP2040 processor chip, designed by Raspberry Pi specially for this small form factor it was originally launched in 2020. It experienced something of a relaunch in 2022 with the release of the Pico W, a version of that has Wi-Fi capability, overcoming the limitation that the original Pico lacked network connectivity. It was the advent of the Pico W that prompted this Second Edition. You can think of as the Pico W as a super-set of the original – everything you can do with an original Pico you can do with a Pico W, but not vice versa. The differences between the two are set out in Chapter 1 and two new chapters are dedicated to how to make use of the additional features of the Pico W and in particular how to create a web client and a web server. In the rest of the book references to “the Pico” encompass both variants unless there is a need to make a distinction. The MicroPython language is a good choice for programming the Pico. It isn’t the fastest way, but in most cases it is fast enough to interface with the Pico’s hardware and its big advantage is that it is easy to use. As a high-level language, MicroPython is based on Python 3 and is fully object-oriented. This means that you can create classes to encapsulate hardware and make your code easier to use and understand. It is also easier to implement complex algorithms and so make your data processing easier. In general, you can take an existing Python 3 program and simply run it under MicroPython, usually with no changes. If there are any changes then they are generally minor. Another good thing about MicroPython on the Pico is that it is very easy to get started. After a simple installation procedure you have a working MicroPython machine which you can program almost at once using the Thonny IDE. Despite Thonny being a really useful IDE we also show how to use VS Code because it has more extensive syntax checking and input prompting. Both IDEs are easy to get started with and easy to use so the choice between them is up to you. The Pico has so many resources that a comprehensive account would fill a book twice this size. In order to make things fit in the space available we have concentrated on things that are accessible from MicroPython and that are basic to getting started. We have avoided “advanced” topics which generally lead the beginner into deep water far too quickly. However, this edition covers of use of the second core, uasyncio and asynchronous programming in general. 3 Another “advanced” topic that is covered is the use of the PIO (Programmable I/O) because it is one of the key advantages of using the Pico, allowing you to delegate interaction with external hardware to a peripheral. Using this facility you can avoid any problems that you might have with MicroPython’s lack of speed as you can write a PIO program which runs at the full speed of the Pico. The PIO isn’t the solution to every problem, but although challenging it is very useful and a lot of fun. You will find out about the PIO in a dedicated chapter and then use it to implement a “driver” for the DHT22 and the 1-Wire bus. This book doesn’t teach you Python or MicroPython in the sense of basic programming, but a knowledge of how to program in almost any language is all you really need. All examples are written in a very simple style that avoids the use of some features of Python that are very “neat” but tend to obscure the meaning of the code from a beginner. You can easily refactor any of the examples into classes that suit your particular purpose and programming style. This is not a projects book, although there isn’t much left for you to do to round out the embryonic projects that are used as examples. Instead it is about understanding concepts and the acquisition of skills. The hope is that by the end of the book you will know how to tackle your own projects and get them safely to completion without wasting time in trial and error. Thanks to our tireless editors Sue Gee and Kay Ewbank. Programming is the art of great precision, but English doesn’t come with a built-in linter. Errors that remain, and we hope they are few, are ours. For the source code for the programs in this book, together with any updates or errata, links to resources including recommendations for obtaining electronic components, visit its dedicated page on the IO Press website: iopress.info. You can also contact us at [email protected] or [email protected] Harry Fairhead Mike James December, 2022 4 Table of Contents Chapter 1 The Raspberry Pi Pico – Before We Begin 13 The Pico And Its Family..................................................................14 What To Expect................................................................................16 What Do You Need?.........................................................................16 Community......................................................................................18 Summary.........................................................................................19 Chapter 2 Getting Started 21 Installing MicroPython....................................................................21 Hello World Using Thonny.............................................................23 Hello World VS Code......................................................................25 Summary.........................................................................................28 Chapter 3 Getting Started With The GPIO 29 Pico Pins..........................................................................................29 Basic GPIO Functions......................................................................31 Blinky...............................................................................................32 Which Hardware?............................................................................34 Summary.........................................................................................36 Chapter 4 Simple Output 37 Basic GPIO Functions......................................................................37 How Fast?.........................................................................................38 Including Pauses..............................................................................40 Fixed Time Delay.............................................................................41 Phased Pulses..................................................................................42 Setting Multiple GPIO Lines...........................................................43 Summary.........................................................................................45 5 Chapter 5 Some Electronics 47 Electrical Drive Characteristics.......................................................47 Driving An LED...............................................................................48 LED BJT Drive..................................................................................50 A BJT Example................................................................................51 MOSFET Driver...............................................................................54 MOSFET LED..................................................................................55 Setting Drive Type...........................................................................56 Setting Output Mode.......................................................................58 Basic Input Circuit - The Switch....................................................58 Debounce.........................................................................................60 The Potential Divider......................................................................60 Summary.........................................................................................62 Chapter 6 Simple Input 63 GPIO Input.......................................................................................63 Basic Input Functions......................................................................64 The Simple Button..........................................................................64 Press Or Hold...................................................................................67 How Fast Can We Measure?............................................................68 The Finite State Machine................................................................70 FSM Button......................................................................................72 FSM Hold Button.............................................................................73 FSM Ring Counter...........................................................................74 Summary.........................................................................................77 Chapter 7 Advanced Input – Events and Interrupts 79 Events...............................................................................................79 Interrupts Considered Harmful?.....................................................80 Hardware Events.............................................................................81 An Edgy Button...............................................................................83 Measuring Pulses With Events........................................................85 Interrupts.........................................................................................86 How Fast Is An Interrupt?...............................................................88 Race Conditions and Starvation.....................................................90 Responding To Input.......................................................................91 Summary.........................................................................................92 6 Chapter 8 Pulse Width Modulation 93 Some Basic Pico PWM Facts...........................................................93 Pico PWM........................................................................................95 Changing The Duty Cycle...............................................................98 Duty Cycle Resolution.....................................................................99 Uses Of PWM – Digital To Analog................................................100 Frequency Modulation..................................................................102 Controlling An LED.......................................................................103 What Else Can You Use PWM For?...............................................106 Summary.......................................................................................107 Chapter 9 Controlling Motors And Servos 109 DC Motor.......................................................................................109 Brushed Motors.............................................................................110 Unidirectional Brushed Motor......................................................112 Unidirectional PWM Motor Controller........................................114 Bidirectional Brushed Motor........................................................116 Bidirectional Motor Software........................................................120 Using A Single Full H-Bridge As Two Half H-Bridges.................121 Controlling a Servo........................................................................121 Brushless DC Motors.....................................................................125 Stepper Motors..............................................................................127 Stepper Motor Driver....................................................................130 Stepper Motor Rotation – Using Timers.......................................134 Summary.......................................................................................138 Chapter 10 Getting Started With The SPI Bus 139 SPI Bus Basics...............................................................................139 Pico SPI Interfaces.........................................................................142 The SPI Functions.........................................................................143 Using the Data Transfer Functions...............................................144 A Loopback Example.....................................................................146 Using The CS Line.........................................................................147 The BME280 Humidity, Pressure and Temperature Sensor........149 Problems........................................................................................153 Summary.......................................................................................154 7 Chapter 11 A-To-D And The SPI Bus 155 Pico ADC........................................................................................155 The MCP3008 SPI ADC.................................................................157 Connecting To The Pico................................................................159 Basic Configuration.......................................................................160 The Protocol..................................................................................160 SPI ADC Class...............................................................................163 How Fast?.......................................................................................164 Summary.......................................................................................165 Chapter 12 Using The I2C Bus 167 I2C Hardware Basics.....................................................................167 The Pico I2C..................................................................................169 The I2C Functions.........................................................................170 Slow Read Protocols......................................................................175 A Real Device.................................................................................175 A First Program..............................................................................176 The I2C Protocol In Action...........................................................178 Reading The Raw Temperature Data............................................179 Processing The Data......................................................................180 Reading Humidity.........................................................................181 Checksum Calculation..................................................................182 Complete Listing...........................................................................183 Summary.......................................................................................185 Chapter 13 Using The PIO 187 PIO Basic Concepts.......................................................................188 State Machines And GPIO............................................................189 PIO Blinky......................................................................................190 Clock Division And Timing..........................................................192 Writing Loops................................................................................194 Data To The PIO............................................................................195 Output To GPIO.............................................................................197 Side Effects....................................................................................200 Input...............................................................................................203 Edges..............................................................................................205 Advanced PIO................................................................................207 Summary.......................................................................................209 8 Chapter 14 The DHT22 Sensor Implementing A Custom Protocol 211 The DHT22....................................................................................211 The Electronics..............................................................................214 The DHT Driver.............................................................................214 The Protocol..................................................................................215 DHT22 Using the PIO – Counting................................................219 DHT22 Using the PIO – Sampling................................................224 Complete Listing...........................................................................226 Summary.......................................................................................228 Chapter 15 The 1-Wire Bus And The DS1820 229 The Hardware................................................................................229 Initialization..................................................................................230 Using The Driver...........................................................................232 Writing Bits....................................................................................232 Writing With The Driver...............................................................234 A First Command - Writing Bytes.................................................235 Writing Bytes With the Driver.......................................................236 Reading Bits...................................................................................237 Reading Using The Driver.............................................................238 Working With 1-Wire Devices.......................................................239 Computing The CRC.....................................................................239 The DS18B20 Hardware................................................................241 The DS18B20 Driver.....................................................................243 Initialization..................................................................................244 Initiating Temperature Conversion...............................................245 Reading the Scratchpad................................................................246 Getting The Temperature..............................................................246 A Temperature Class.....................................................................247 The Complete Program..................................................................248 Driver Version................................................................................250 A PIO DS18B20 Program...............................................................251 Complete Program.........................................................................257 Other Commands..........................................................................259 Summary.......................................................................................262 9 Chapter 16 The Serial Port 263 Serial Protocol...............................................................................263 UART Hardware............................................................................265 Setting Up the UART.....................................................................266 Data Transfer.................................................................................267 Serial Polling..................................................................................269 Timeouts........................................................................................270 Polling On Write............................................................................271 Reading and Writing Characters and Strings...............................273 Summary.......................................................................................274 Chapter 17 Using The Pico W - WiFi 275 The Pico W...................................................................................275 The WLAN Class...........................................................................276 A Practical Connect.......................................................................277 WiFi Scan.......................................................................................280 A Simple HTTP Client..................................................................280 Request Methods...........................................................................281 A Custom Server...........................................................................282 The urequests Module..................................................................284 A Temperature Sensor Client........................................................286 Sockets...........................................................................................289 A Socket Web Client......................................................................293 SSL Socket Based HTTPS Client..................................................294 Socket Server.................................................................................296 A Socket Temperature Server.......................................................297 An SSL HTTPS Server..................................................................301 Non-Blocking Sockets...................................................................306 The Connection Queue.................................................................307 Summary.......................................................................................309 10

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.