ebook img

Raspberry Pi IoT In C, 2nd Edition PDF

411 Pages·2020·11.942 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 Raspberry Pi IoT In C, 2nd Edition

Raspberry Pi IoT In C 2nd Edition Harry Fairhead I/O Press I Programmer Library Copyright © 2020 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, Raspberry Pi IoT In C ISBN: 9781871962635 Second Edition First Printing, October 2020 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 is a registered trademark 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 This is the second edition of my book about IoT in C featuring the Raspberry Pi and things have changed a lot since the first edition. The Pi range has evolved and expanded over the time to provide both a low-cost, almost disposable, device, the Pi Zero and a desktop replacement, the Pi 4. What has stayed the same is the way that the Pi has enabled a full Linux system to be used for hardware-oriented IoT applications. Where in the past you might have opted for a microcontroller that didn’t run any sort of operating system, now even the simplest of IoT devices can be a full Linux server if the need arises. This is a different way to think about physical computing, but it brings many challenges and the biggest is speed. You could say that this is always an issue, but getting a hardware task complete can mean trimming timings to the microsecond. To do this means working close to the hardware and there is no language better for this than C. It may be an old language, but C is still at or close to number one in programming language rankings. It is worth learning and it isn’t difficult. The first problem any beginner at almost any programming project has to solve is what tools to use.. In the case of programming the Pi things are initially easy in that the GCC C compiler is installed as standard. When it comes to an editor or IDE to help you write programs, things become more difficult. Ideally you need a remote development system running on a desktop machine which will download, build and run the program on a remote Pi. The only IDE that does the job properly is NetBeans, but this is in a state of flux having moved from Oracle to Apache. This book still majors on NetBeans, but there is now an increasingly attractive alternative by way of Visual Studio Code. VS Code is slightly more difficult to set up, something that is covered in Appendix II, but works well once you are over that hurdle. I have also taken the opportunity to reorganize some of the material so that the more introductory topics come before the more advanced ones. So only after dealing with simple GPIO output, do we look at simple input. Input is generally harder to program than output because you aren’t in control of when things happen. The usual solution to this is to use events or interrupts. Linux doesn’t support user mode interrupts and to create something that behaves like an interrupt we need to look at the use of the new, character- mode, GPIO driver. In a later chapter the idea of using a finite state machine approach to input is described, which solves nearly all our problems without having to use interrupts. 3 Moving on to other forms of output, we explore Pulse Width Modulation (PWM) and what it can be used for – servos, music, LED control. The important topics of I2C, the serial port and the SPI bus are all covered in detail, including the new ports available on the Pi 4. A custom protocol is implemented to make use of the DHT22 temperature sensor and the very useful 1-wire bus is also implemented both as a custom protocol and using the serial port. As connecting with the web is key to the IoT, we look at how to use sockets to implement an HTML/2 client and server. Finally we consider how things work at the very lowest level via memory mapping to access registers and how to make the best of Linux in a real-time system, including the relatively new deadline scheduling. The main idea in this book is to work directly with the hardware. This approach frees you from dependence on the current Linux configuration and isolates you from the restrictions of the drivers. Perhaps more importantly, it ensures you understand what is going on and are in complete control. Similarly, on the hardware side, no HATs or other off-the-shelf expansion boards are used. Simple and direct electronics are often all that is needed and finding out how to do it means that you can understand how the expansion boards do their job. 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 my tireless editors Sue Gee and Kay Ewbank. I may know what a comma is for in C, but my understanding of its role in natural language is severely limited. Errors that remain, and I hope they are few, are mine. 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. You can also contact me at [email protected]. Harry Fairhead September, 2020 4 Table of Contents Preface 3 Chapter 1 Why Pi For IoT? 13 The Pi Versus The Microcontroller..................................................13 Which Pi?..........................................................................................14 No HATS Needed..............................................................................16 What To Expect.................................................................................17 User Mode – No Drivers....................................................................17 What Do You Need?..........................................................................18 Safety In Numbers.............................................................................20 Summary...........................................................................................21 Chapter 2 23 Getting Started Getting Started In C...........................................................................24 Local v Remote..................................................................................25 Installing NetBeans...........................................................................25 Your First C Pi Program.....................................................................28 Troubleshooting................................................................................33 Summary...........................................................................................34 Chapter 3 Getting Started With The GPIO 35 Setting Up the BCM 2835 Library With NetBeans...........................35 A First IoT Program...........................................................................38 Running Programs On NetBeans......................................................40 Pin Numbering..................................................................................41 GPIO Modes.......................................................................................43 Summary...........................................................................................45 Chapter 4 Simple Output 47 Output Mode.....................................................................................47 Multi Functions.................................................................................48 How Fast?...........................................................................................50 The Problem Of Clocks.....................................................................51 Including Pauses................................................................................53 Busy Wait...........................................................................................55 Automatic Busy Wait Calibration.....................................................57 Phased Pulses....................................................................................59 Can We Do Better?.............................................................................61 Summary...........................................................................................62 5 Chapter 5 Some Electronics 63 Electrical Drive Characteristics........................................................63 Driving An LED.................................................................................64 LED BJT Drive....................................................................................66 A BJT Example..................................................................................67 MOSFET Driver.................................................................................70 MOSFET LED....................................................................................71 Setting Drive Type.............................................................................72 Setting Output Mode.........................................................................74 Basic Input Circuit - The Switch......................................................74 Debounce...........................................................................................76 The Potential Divider........................................................................76 Summary...........................................................................................78 Chapter 6 Simple Input 79 GPIO Input.........................................................................................79 Basic Input Functions.......................................................................80 The Simple Button............................................................................80 Press Or Hold.....................................................................................83 How Fast Can We Measure?..............................................................84 The Finite State Machine..................................................................87 FSM Button........................................................................................89 FSM Hold Button...............................................................................91 FSM Ring Counter.............................................................................92 Summary...........................................................................................95 Chapter 7 GPIO The Linux Way 97 Why Integrate GPIO With Linux?.....................................................97 GPIO Character Device.....................................................................99 Raw GPIO Character Device In C - ioctl.........................................102 Getting Chip Info.............................................................................103 GPIO Output....................................................................................104 GPIO Input.......................................................................................107 Summary.........................................................................................109 6 Chapter 8 Advanced Input – Events, Threads, Interrupts 111 Events..............................................................................................111 Interrupts Considered Harmful?.....................................................112 Events And The BCM 2835 Library................................................113 Measuring Pulses With Events........................................................117 How Fast Are Events.......................................................................119 An Edgy Button...............................................................................120 Interrupts And The GPIO Character Driver...................................121 An Interrupt Function Using A Thread..........................................125 How Fast Is An Interrupt?...............................................................130 The Complete Program...................................................................131 Responding To Input.......................................................................134 Summary.........................................................................................135 GPIO Chapter 9 Pulse Width Modulation - Servos And More 137 Some Basic Pi PWM Facts...............................................................137 PWM Modes....................................................................................139 PWM Functions...............................................................................141 Selecting Clock Rate........................................................................142 Using PWM......................................................................................143 How Fast Can You Modulate?.........................................................145 Uses Of PWM – Digital To Analog..................................................146 Music...............................................................................................148 Controlling An LED.........................................................................149 Changing LED Brightness Linearly.................................................151 Controlling A Servo.........................................................................153 What Else Can You Use PWM For?.................................................157 Some Hardware Details...................................................................157 Summary.........................................................................................161 7 Chapter 10 Using The I2C Bus 163 I2C Hardware Basics.......................................................................164 The Pi I2C........................................................................................166 The I2C Functions...........................................................................168 Slow Read Protocols........................................................................173 A Real Device..................................................................................174 A First Program................................................................................175 The I2C Protocol In Action.............................................................177 Checksum Calculation....................................................................183 Complete Listing.............................................................................184 Summary.........................................................................................186 Chapter 11 The DHT22 Sensor Implementing A Custom Protocol 187 The DHT22......................................................................................187 The Electronics................................................................................190 The Software...................................................................................190 Complete Listing.............................................................................195 Summary.........................................................................................197 Chapter 12 Exploring 1-Wire Bus Basics 199 The Hardware..................................................................................199 Initialization....................................................................................200 Writing Bits......................................................................................203 A First Command - Writing Bytes...................................................204 Reading Bits.....................................................................................205 Summary.........................................................................................208 Chapter 13 Using iButtons 209 The Hardware..................................................................................210 Is There a Button?...........................................................................211 Read The Serial Number.................................................................211 Computing The CRC.......................................................................212 iButton Function..............................................................................215 Complete Program Listing...............................................................216 Summary.........................................................................................219 8 Chapter 14 DS18B20 Temperature Sensor 221 The Hardware..................................................................................221 Initialization....................................................................................223 Initiating Temperature Conversion.................................................224 Reading The Scratchpad.................................................................225 Getting The Temperature................................................................225 A Temperature Function.................................................................226 The Complete Program...................................................................227 Other Commands............................................................................230 Summary.........................................................................................233 Chapter 15 The Multidrop 1-Wire Bus 235 The Hardware..................................................................................235 The 1-Wire Search Algorithm.........................................................236 A Recursive Scan.............................................................................238 oneWireScan....................................................................................243 Scanning the Bus.............................................................................245 Error Checking.................................................................................247 How Many Devices?........................................................................248 Reading Specific Devices................................................................248 Alarm Scan......................................................................................252 Final Thoughts................................................................................252 Summary.........................................................................................253 Chapter 16 The Serial Port 255 Serial Protocol.................................................................................255 The UART Hardware.......................................................................259 Linux Device Names.......................................................................261 Getting Rid Of the Console.............................................................262 Opening the Serial Port...................................................................264 Raw Mode........................................................................................269 Sending Data...................................................................................271 Reading Data....................................................................................272 Polling For Data With Blocking.......................................................276 Polling For Data With Non-blocking...............................................278 Receiving A Big Block.....................................................................279 Blocking Versus Non-blocking........................................................280 Using A UART.................................................................................280 Summary.........................................................................................288 9 Chapter 17 Getting Started With The SPI Bus 289 SPI Bus Basics.................................................................................289 Pi SPI Interfaces..............................................................................290 How SPI0 Works..............................................................................292 The SPI Functions...........................................................................295 A Loopback Example......................................................................298 Problems..........................................................................................300 Summary.........................................................................................302 Chapter 18 A to D With The SPI Bus 303 The MCP3008..................................................................................303 Connecting To The Pi......................................................................305 Basic Configuration.........................................................................305 The Protocol....................................................................................306 Some Packaged Functions...............................................................309 How Fast..........................................................................................309 Summary.........................................................................................311 Chapter 19 Connecting With The Web - Sockets 313 Socket Basics...................................................................................313 Socket Functions.............................................................................314 A Web Client....................................................................................317 Connecting Using a URL.................................................................320 A Server...........................................................................................323 A Web Server?.................................................................................328 What About Security?.....................................................................330 Summary.........................................................................................331 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.