100% found this document useful (2 votes)
34 views

Get Arduino Interrupts Norman Dunbar free all chapters

Dunbar

Uploaded by

olowunaserls
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
34 views

Get Arduino Interrupts Norman Dunbar free all chapters

Dunbar

Uploaded by

olowunaserls
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Download the Full Version of ebook for Fast Typing at ebookmass.

com

Arduino Interrupts Norman Dunbar

https://ebookmass.com/product/arduino-interrupts-norman-
dunbar/

OR CLICK BUTTON

DOWNLOAD NOW

Download More ebook Instantly Today - Get Yours Now at ebookmass.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

King Of The Hill: Norman Mailer On The Fight Of The


Century Norman Mailer

https://ebookmass.com/product/king-of-the-hill-norman-mailer-on-the-
fight-of-the-century-norman-mailer/

ebookmass.com

Prelude for Lost Souls Helene Dunbar

https://ebookmass.com/product/prelude-for-lost-souls-helene-dunbar-2/

ebookmass.com

Prelude for Lost Souls Helene Dunbar

https://ebookmass.com/product/prelude-for-lost-souls-helene-dunbar/

ebookmass.com

Oxford Practice Grammar - Basic Norman Coe

https://ebookmass.com/product/oxford-practice-grammar-basic-norman-
coe/

ebookmass.com
The Promise of Lost Things Helene Dunbar

https://ebookmass.com/product/the-promise-of-lost-things-helene-
dunbar/

ebookmass.com

We Are Lost And Found Helene Dunbar

https://ebookmass.com/product/we-are-lost-and-found-helene-dunbar/

ebookmass.com

We Are Lost and Found Helene Dunbar

https://ebookmass.com/product/we-are-lost-and-found-helene-dunbar-2/

ebookmass.com

We Are Lost And Found Helene Dunbar

https://ebookmass.com/product/we-are-lost-and-found-helene-dunbar-3/

ebookmass.com

We Are Lost and Found Helene Dunbar

https://ebookmass.com/product/we-are-lost-and-found-helene-dunbar-4/

ebookmass.com
Maker Innovations Series

Jump start your path to discovery with the Apress Maker Innovations
series! From the basics of electricity and components through to the
most advanced options in robotics and Machine Learning, you'll forge a
path to building ingenious hardware and controlling it with cutting-edge
software. All while gaining new skills and experience with common
toolsets you can take to new projects or even into a whole new career.
The Apress Maker Innovations series offers projects-based learning,
while keeping theory and best processes front and center. So you get
hands-on experience while also learning the terms of the trade and how
entrepreneurs, inventors, and engineers think through creating and
executing hardware projects. You can learn to design circuits, program
AI, create IoT systems for your home or even city, and so much more!
Whether you're a beginning hobbyist or a seasoned entrepreneur
working out of your basement or garage, you'll scale up your skillset to
become a hardware design and engineering pro. And often using low-
cost and open-source software such as the Raspberry Pi, Arduino, PIC
microcontroller, and Robot Operating System (ROS). Programmers and
software engineers have great opportunities to learn, too, as many
projects and control environments are based in popular languages and
operating systems, such as Python and Linux.
If you want to build a robot, set up a smart home, tackle assembling a
weather-ready meteorology system, or create a brand-new circuit using
breadboards and circuit design software, this series has all that and
more! Written by creative and seasoned Makers, every book in the series
tackles both tested and leading-edge approaches and technologies for
bringing your visions and projects to life.
More information about this series at https://link.springer.com/
bookseries/17311.
Norman Dunbar

Arduino Interrupts
Harness the Power of Interrupts in Your Arduino
and ATmega328 Code
Norman Dunbar
Rawdon, West Yorkshire, UK

ISSN 2948-2542 e-ISSN 2948-2550


Maker Innovations Series
ISBN 978-1-4842-9713-1 e-ISBN 978-1-4842-9714-8
https://doi.org/10.1007/978-1-4842-9714-8

© Norman Dunbar 2024

This work is subject to copyright. All rights are solely and exclusively
licensed by the Publisher, whether the whole or part of the material is
concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in
any other physical way, and transmission or information storage and
retrieval, electronic adaptation, computer software, or by similar or
dissimilar methodology now known or hereafter developed.

The use of general descriptive names, registered names, trademarks,


service marks, etc. in this publication does not imply, even in the
absence of a specific statement, that such names are exempt from the
relevant protective laws and regulations and therefore free for general
use.

The publisher, the authors, and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.

This Apress imprint is published by the registered company APress


Media, LLC, part of Springer Nature.
The registered company address is: 1 New York Plaza, New York, NY
10004, U.S.A.
Writing books is not an easy task, especially if you have other
commitments, like family, work, a dog, and suchlike. I would like to thank
my wife Alison for allowing me some spare time to get my thoughts down
on paper (or PDF) and also to everyone involved in the Arduino universe,
be that hardware, software, or even just a LATEX file to get Arduino IDE
code formatting styles available in a LYX document.1
Preface
Interrupts seem to be a bone of contention with some makers, but they
are actually quite simple (famous last words?) and have the bonus effect
of allowing almost instantaneous response to certain events happening,
which a polling application might miss, depending on what else it was
doing at the time.
Much of the Arduino code you see in books or on pages on the
Internet seem to avoid interrupts, which tends to give the impression
that they are somehow difficult. This could not be further from the
truth!
Interrupts actually help make your code simpler as you only have to
code the normal chain of events in your main loop and then write small,
very small for best results, functions to handle one interrupt event each.
For example, consider a small Arduino robot which wanders around its
environment and has a pair of switches attached to it to detect obstacles
– similar to the antennae on some insects.
The main code in the loop() function should concentrate on
driving the robot, most likely in a forward direction but based on a
variable which tells it which way to drive. Interrupts would be used to
detect when the collision switches had been “pressed” (by hitting
something) and update the variables used in the loop() to change
direction and turn away from the detected obstacle.
This book will hopefully make Arduino (ATmega328P) interrupts a
lot less “difficult” and easier to use in your own code.

1 Code and Listings


Inline code, within the text, will be formatted as typewriter text, like
this.
Code segments and listings in the rest of the book will be shown as
follows:
Listing 1 Example code listing

Hopefully, you will note that the code formatting is in the same style as
the code in the Arduino IDE environment.
This is thanks to arduinoLanguage.tex, a small LATE X file,
which is available from my GitHub repository.2 Of course, this was not all
my own work; I forked the original repository owned by “Trihedral.”3 I
am extremely grateful to “Trihedral” for making the code available as it
saved me no end of work, not least trying to figure out the color codes! I
have slightly amended my version to highlight the ATmega328P’s
register and bit names in addition to the Arduino Language highlighting.
If the code in Listing 1 is not highlighted as it would normally appear
in the Arduino IDE, then I humbly apologize; the production processes
in converting my PDF files into a proper book appear to have
overwritten the Arduino style with their own in-house style. C’est la vie.

You are permitted to reuse the code listed in this book as you see fit
– it’s here to help you, so use it! And if you want to credit me, then
feel free to do so as well – but it’s not mandatory.
The code repository for this book is located at https://​github.​com/​
Apress/​arduino-interrupts.

2 Arduino and AVR Code


Some of the examples in this book are obviously written for the Arduino
IDE – those examples will need to be compiled within the IDE or using
the new Arduino-cli utility4 of course!
The non-Arduino examples will be found in folders named
“PlatformIO.”5 This is another development system for Arduino and AVR
projects, and I thoroughly recommend it. The project files, included in
this book’s code repository, will mainly be configured for either my
Arduino Duemilanove or my Arduino Uno boards and may need to be
slightly edited to suit your particular Arduino board. It will not be
necessary for you to create a new project and then copy my files from
the src, lib, and/or include directories into your project’s similarly
named directories as all you need to do is edit the supplied
platformio.ini file in each project to suit your board.
If you only have the Arduino IDE and you wish to try out the
PlatformIO (plain AVR C++ in other words) versions of the sketches in
the examples, then you can easily do this if you start a new sketch in the
Arduino IDE and copy the code from the PlatformIO source file(s) into it,
replacing all the standard code that the IDE creates for you.
When you compile the code, it will still compile all the Arduino files
that it would normally do, but it will not link them into the finished
binary (hex) file. You will get the same sized executable ready for
uploading as you would get with the PlatformIO system installed.
What you will not get is any of the Arduino Language features such
as millis(), delay(), setup(), loop(), and so on, and there’s
none of the nice hand-holding that you get from the Arduino Language –
you are firmly in control now! (Have fun!)
Oh yes, for the sake of keeping things simple, most, if not all, of the
example sketches and code just flash an LED. Everyone knows how to do
this, don’t they? LEDs are a fairly simple method of showing how
something works without needed masses and masses of sometimes
impenetrable code. Out there in the real world, things are a bit more
involved than just blinky lights – but hopefully, I’ll have explained things
in a good enough way for you to go off and make your own, interrupt-
driven, projects. Good luck and have fun!

3 Admonitions
If I want to draw your attention to something or emphasize some fact
from the main body of the text, I will use a note, as follows:

Note
This is a note that I want to bring to your attention.

If there is something that you really need to be aware of, you will see
this:

Warning
This is some text that I want to bring to your attention. It may help
prevent your Arduino from releasing the magic blue smoke that
makes it work, or it may explain the reason why your code fails to do
what was expected.

And finally, if I have a useful tip or helpful hint, I will do this:

Tip
Never run with scissors!
Terminology
Terms like “master” and “slave” are deemed to be no longer acceptable,
and many organizations have been amending their documentation to
replace those terms with other, more acceptable ones.
In the data sheet for the ATmega328P,6 the existing “master” and
“slave” terms are still in place. In this book, I will avoid those terms,
unless I am directly quoting from the data sheet or using the name of a
register or bit within a register.
I will be replacing “slave” with “sensor” or “peripheral” and “master”
with “controller” as appropriate and as is currently the new standard.
Introduction
This book is intended to be a guide, for beginners and moderately
experienced Arduino makers, into the slightly scary world of Arduino
Interrupts. Actually, it’s not actually the Arduino, it’s the Arduino’s
microcontroller, the ATmega328P. However, I’ll be using one or two of
my Arduino boards as test beds throughout.
Interrupts do not feature much7 in the Arduino Language, but are an
integral part of the AVR hardware itself. They are what allows your
sketch, or application code, to apparently do two things at once.
Consider, for example, that your laser cutter has a powerful and
exceedingly destructive laser beam. You would like the beam to cut off
immediately when you hit the Big Red PANIC! Switch – it’s no good to
you, or anyone else, if the beam carries on until the end of the
programmed cut and then checks to see if the switch has been pressed.
That switch is almost 100% certain to be attached to an interrupt,
and that interrupt will “fire” as soon as the switch is hit, cutting off the
beam immediately.
There are times when polling a sensor is acceptable, but in doing so,
you waste the microcontroller’s time and resources when it should be
left to get on with whatever the main task is, and only process the sensor
input when the sensor has some to offer.
Do you sit in your lounge at home regularly checking the front door
to see if someone is there? Or do you wait for the doorbell to chime,
interrupting whatever you are doing at the time? That’s the difference
between polling and interrupts in a nutshell.
The main body of code continues as programmed, doing what it does
best, and without checking the “front door” all the time. When the
“doorbell” chimes, the program is interrupted, saves its place in the
code, goes off to see who is at the door, and then comes back to continue
from where it left off. There’s no specific place that it can be interrupted;
it can happen at any place in the code, and it will be handled correctly –
if programmed to do so.
In the forthcoming chapters, I will explain the vast majority of the
interrupts8 available on the microcontroller used in the Arduino Uno,
Nano, and my favorite, the Duemilanove, the Atmel (now Microchip)
ATmega328P. In each case, where relevant, I will explain what the
interrupt is for; how it works; how, or if, it can be used in an Arduino
sketch; and how it can be used in plain AVR C++ code. In addition, if I
feel like showing off, I will show it in AVR Assembly Language. All the
demonstration code will be available for download from the book’s
GitHub account.
Where appropriate, each demonstration will be accompanied by a
Fritzing9 project in which only the breadboard layout is of any relevance.
For those readers without a Fritzing installation (and why not?), there
will be a PNG image, exported from the project, to show the breadboard
layout.
Any source code or other supplementary material referenced by the
author in this book is available to readers on GitHub (github.​com/​
Apress). For more detailed information, please visit https://​www.​
apress.​com/​gp/​services/​source-code.
Acknowledgments
I would like to thank everyone at Apress and Springer who were
involved in the production of this book. Some names that spring to mind
are Miriam Haidara, my Commissioning Editor, who thought this would
be a good book; Sowmya Thodur who has had to suffer keeping me
organized and on the straight and narrow; Jessica Vakili who has had the
misfortune to have to work with me on two books now; James Markham,
my Development Editor; and especially to all the unsung heroes behind
the scenes who converted my files into something you can hold in your
hand and read in the bath!
Open source has played a big part in this book too. The book was
written using the LyX editor (www.​lyx.​org/​).
Graphics for various circuit schematics and breadboard layouts are
courtesy of the Fritzing tool for circuit design (https://​fritzing.​org/​).
Arduino code highlighting is facilitated by the Arduino Latex Listing
project run by “Trihedral” on GitHub (https://​github.​com/​trihedral/​
ArduinoLatexList​ing/​).
Code for the book was developed using both the Arduino IDE
versions 1.8.6 and 2.1.0 (www.​arduino.​cc/​) and PlatformIO, my
preferred development system (https://​platformio.​org/​).
Finally, I must thank my Technical Reviewer, Farzin Asadi, who
kindly read and commented on my code and pointed out a, thankfully,
small number of errors and improvements.
Discovering Diverse Content Through
Random Scribd Documents
Irene was knitting a pretty blue scarf. One morning she laid it on
the couch while she went to talk to a little friend. Suddenly she heard
a noise. Scamper, scamper! Pitter, patter!
When she came in the twins were playing with her ball of blue
wool. And part of the scarf was unraveled and wound around Puff’s
neck.
After she unwound the wool, she locked them both in the cellar.
She thought that would be a dreadful punishment! But they had a
GRAND TIME! They chased a little mouse that had left his home in
the wall because he didn’t think! Fluff caught him in the coal bin.
When Irene brought them upstairs, Fluff was as black as Puff.
They had to have another bath!

“Dear!” sighed Irene, “Twins are such trouble!”


The very next day, when she was writing a letter to her grandma,
Puff jumped on her lap and spilled the ink! And while she was
fetching a cloth to wipe it up, Fluff tumbled the waste-paper basket
all over the floor!

That day she locked them in the kitchen. But they got into more
trouble than ever. They smelled fish!
When Irene came to the kitchen, the big fish mother had bought
for dinner was falling from the table! And Puff and Fluff were having
the worst fight.
“You are bad kitties!” she cried, and she whipped them! Then she
put them out of the house and shut the door, although her heart hurt
frightfully. “I must train them!” she said.
Fluff looked at Puff. Puff looked at Fluff. “Meow! Meow!” Fluff said,
“We have been turned from our home.” “Meow! Meow!” answered
Puff, “we must go back to the farm!”
When Irene looked for them at dinner-time they were gone! She
looked everywhere! But the twins were not to be found. She called
them until her throat ached. “Here Puff! Here Fluff!” But no kitties
came running.
Then she was very sad. “Dear! Dear!” she said, “They have run
away because I punished them!”
Then Daddy came home, “Oh, Daddy!” Irene cried, “my TWINS
have RUN AWAY! We must go and find them!” So right after dinner
Daddy got out the big car. Soon they were way, way out in the
country. The sun was going down behind the hills. “Oh!” sobbed
Irene, “I am afraid they are lost.”
Suddenly Daddy stopped the car with a jerk. He had almost run
over the TWIN KITTIES! Irene jumped out and picked them up. Soon
Puff and Fluff were on their way back home. They were very happy
to be cuddled in Irene’s arms.
She held them very close. “Dear Kitties,” she said, “you must take
your punishments bravely. If I did not correct your faults when you
are kittens, you would grow up into BAD CATS!”
Fluff and Puff rolled up into two little balls. They were so happy
that they had such a nice, kind mistress, who trained them so well,
and yet forgave them so readily, that they purred louder than the
engine.
When they reached home Irene laid them tenderly on the pretty
couch. Then she went up to bed. Fluff and Puff did not go to sleep at
once. They lay awake planning to show their gratitude to their nice,
kind little girl mother.
“Meow!” said Fluff, “she took us in when no one else would look at
us, and gave us a home!”

“Mew!” answered Puff. “And she has taught us how to act in a


pretty home like this. We were not well trained when we came here.”
“P-r-r-r-r-r!” continued Fluff in a bit softer tone. “If she hadn’t loved
us a lot she would never have searched for us.”
“And we’d be back in the cold, cold barn!” purred Puff, cuddling
down in the warm cushion.
“From now on we must be very, very good!” said Fluff, sleepily.
“We—must—be—very—very—good!” purred Puff softly. Then his
head fell over on Fluff’s back. They were both fast asleep.
Transcriber’s Notes:
Missing or obscured punctuation was silently
corrected.
Typographical errors were silently corrected.
Inconsistent spelling and hyphenation were
made consistent only when a predominant form
was found in this book.
*** END OF THE PROJECT GUTENBERG EBOOK MY TWIN
KITTIES ***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright
in these works, so the Foundation (and you!) can copy and
distribute it in the United States without permission and without
paying copyright royalties. Special rules, set forth in the General
Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the


free distribution of electronic works, by using or distributing this
work (or any other work associated in any way with the phrase
“Project Gutenberg”), you agree to comply with all the terms of
the Full Project Gutenberg™ License available with this file or
online at www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works

1.A. By reading or using any part of this Project Gutenberg™


electronic work, you indicate that you have read, understand,
agree to and accept all the terms of this license and intellectual
property (trademark/copyright) agreement. If you do not agree to
abide by all the terms of this agreement, you must cease using
and return or destroy all copies of Project Gutenberg™
electronic works in your possession. If you paid a fee for
obtaining a copy of or access to a Project Gutenberg™
electronic work and you do not agree to be bound by the terms
of this agreement, you may obtain a refund from the person or
entity to whom you paid the fee as set forth in paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only


be used on or associated in any way with an electronic work by
people who agree to be bound by the terms of this agreement.
There are a few things that you can do with most Project
Gutenberg™ electronic works even without complying with the
full terms of this agreement. See paragraph 1.C below. There
are a lot of things you can do with Project Gutenberg™
electronic works if you follow the terms of this agreement and
help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project
Gutenberg™ works in compliance with the terms of this
agreement for keeping the Project Gutenberg™ name
associated with the work. You can easily comply with the terms
of this agreement by keeping this work in the same format with
its attached full Project Gutenberg™ License when you share it
without charge with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.

1.E. Unless you have removed all references to Project


Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project
Gutenberg™ work (any work on which the phrase “Project
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookmass.com

You might also like