Understanding Arduino Interrupts Hardware, Pin Change & Timer Interrupts

Rek XIX
40 followers
1 Video View·Oct 31, 2022
Understanding Arduino Interrupts Hardware, Pin Change & Timer Interrupts
Today in the workshop we're using interrupts with the Arduino.
We'll learn about hardware, pin change, and timer interrupts, and we'll see how to use
them to improve our code.
Interrupts are a great feature, and they're easy to use once you know how.
So pardon the interruption, and welcome to the workshop.
Well hello and welcome to the workshop, and in today's video we are going to be working
with interrupts on the Arduino Uno.
Although everything we're doing today could also be applied to other Arduinos and other
microcontrollers because interrupts are a very important concept.
Now we've used interrupts before here in the Drobot Workshop.
Quite a few times we've used them within our code, and about four years ago I did a video
about using those little speed sensors that come with those robot car kits, and within
that video I gave a detailed explanation of how a hardware interrupt worked.
But that was four years ago, it was buried in another video, plus there are other types
of interrupts that the Arduino Uno is capable of, and we're going to discuss those today.
Now we're going to break with a bit of a tradition today, in most of my videos you'll notice
I start off by talking to you about the subject, and then we move into an animated explainer
that explains a bit more about the subject, and then we get into some experiments, etc.
Well we're not going to jump into the animated explainer right away today, we're going to
move right over to the workbench, and we're going to hook up an Arduino Uno to a couple
of components, we're going to write a sketch that doesn't use interrupts, and then we're
going to see how we can improve the performance of that sketch by using interrupts.
So let's head to the workbench, and hook up our Arduino.
Now here's how we're going to hook up our first demonstration, and it's very simple.
We'll use an Arduino Uno, and we'll also need a momentary contact normally open push button
switch.
We'll require an LED, you can use any color you want, and a dropping resistor for that
LED.
I used a 220 ohm resistor, but any value from 150 to about 470 ohms would probably work
just great.
Now we'll begin by connecting the digital output pin 13 of the Arduino to one side of
the dropping resistor, and we'll connect the other side of the dropping resistor to the
anode of the LED.
The cathode of the LED will be connected to one of the Arduino's grounds.
Digital pin 2 of the Arduino will be connected to one side of our push button switch, and
we'll connect the other side of the push button switch to ground.
And that's all there is for our wiring, now let's go and take a look at a bit of code
we can use with this.
Now the first sketch that we're going to run on our simple hookup is a very simple sketch
that just creates an LED toggle.
And the toggle will just allow us to press the push button to turn the LED on, and then
to press it again to turn it off.
It's a very easy sketch, and let's just take a look at it.
We'll start off by defining a couple of variables that represent both the pins that the LED
and the button are connected to, and then we define a boolean that represents the toggle
state.
So when it's false, the LED will be off, when it's true, the LED will be on.
Now we've got a function over here that we've defined, and I'm calling it checkSwitch, and
it just checks the status of the switch, and lights the LED accordingly.
So within checkSwitch, we do a digital read of the button pin.
And if it's low, we know that the switch has been pressed, because the switch is wired
so that when we press it, it's going to connect the ground to the input and drive it low.
So we know that it's pressed, we're going to put a little delay in there just to debounce
the switch, and that's just to present false triggering.
And then we're going to go and change the state of our toggle.
And so we just take the toggle state, and we invert it.
So if it's high, we make it low.
If it's low, we make it high.
And then we write that state over to the LED in order to represent our toggle state on
the LED.
Pretty simple.
Then we go into setup, we set up the pin mode for the LED as an output, and we'll set the
pin mode for the button pin.
And notice that we're using an input pull-up, and this prevented us from having to use an
external pull-up resistor.
We'll just use the internal 30k pull-ups that the Arduino has.
And the loop is very simple, because all we're doing is we're running our check switch function.
So we just continually run check switch, and check the status of the switch, and drive
the LED accordingly.
So let's load this up to our board and take a look at it working.
And so here's my basic toggle switch setup.
I've got everything up on a solid spread board over here, with my LED and of course my push
button switch.
And if I press the switch, I get the LED on.
And if I press it again, I get the LED off, which is of course the exact operation that
I was hoping for.
So it's a pretty simple sketch, and a pretty simple circuit.
And as it is right now, it seems to work.
So let's go and add something to our sketch, and see if it affects the operation of our
toggle.
So here's a slightly modified version of the last sketch, and I've only really added a
couple of things to it.
It starts off identically with the same LED and switch connections defined in a boolean
to represent the toggle state.
And we also use the same check switch function, it hasn't been modified at all.
In the setup, there's one small change, and I'm starting the serial monitor over here,
because I want to use that to monitor something.
And then in the loop, we start off with our check switch as we did before.
And here's the only change we've made, I've added the 5 second time delay.
So I'm going to print to my serial monitor when the delay starts, then I'm going to delay
for 5000 milliseconds, which is 5 seconds.
And then I'm going to print when the delay has been finished, and then we'll start the
loop and do everything over again.
So it's a pretty simple little modification.
But let's go and see if that affects the operation of our Arduino.
So we'll load that up and check it out.
So now we've got our code loaded up to the board, this is the code that's been modified
to have the delay at the end of the loop.
And we'll try our toggle switch again.
And it doesn't seem to be working very well.
I'm pressing the button, nothing is happening.
I look at my serial monitor, I'm in the midst of a delay it would appear.
And while I'm in that delay, it doesn't look like I can use my toggle switch.
No, it's very difficult to do.
Now there you go, sometimes you can get it to work if you happen to get it between the
point where the delay stops and the delay starts.
But otherwise, the toggle switch is pretty well non-functional.
And so now the circuit that we had working so well before doesn't really work at all.
And there must be a better way of doing this.
So as we've seen, adding a delay into the loop really messed up our circuit.
It barely works at all, and I think most of you can figure out why that is.
Now of course you wouldn't really be using a long delay for no specific reason in normal
code.
But there are things that will delay your code.
For example, if you've got a DHT22 temperature and humidity sensor and you're going to take
readings on that in the loop, well you've got to give that two seconds in between readings.
So there's a two second delay right over there.
You could also be doing something like driving a servo motor in which you have to wait a
finite amount of time for the motor to reach its position.
So there are a lot of reasons why your loop might delay the code.
Another thing about this code is if you think about it, it's really a bad way of checking
to see if a switch has been pressed.
I mean, this is kind of like the child who's in the backseat of the car during the long
distance road trip, who every two minutes is saying, are we there yet?
Are we there yet?
We're basically doing the same thing with our switch.
We just keep checking and saying, have you been pressed?
Have you been pressed?
And most of the time the answer is no.
There has to be a better way of doing something like this.
Hey, I just wanted to say that if you haven't subscribed to the YouTube channel yet, please
do so.
All you have to do is click on the red subscribe button below the video.
And after you do that, also hit the bell notification.
And as long as you've got notifications enabled on your YouTube, you'll get notified every
time I make a new video.
By the way, about 20% of my viewers have notifications enabled.
So if you're one of the 80% who doesn't, you might want to go and check your settings.
Okay, that was a bit uncalled for, but it actually served a point.
We were interrupted.
We are in the middle of having a conversation and we were interrupted by someone with a
completely different topic.
Now, in this particular case, the interruption was trivial and probably uncalled for, but
there are interruptions that can actually be very beneficial to you.
Someone interrupting you to say, excuse me, but your car is on fire.
Excuse me, but there's a piano about to fall on your head.
Those kinds of interruptions are the interruptions that you probably would appreciate and you
would stop doing whatever you're doing and go and deal with the situation.
While a microcontroller can do the same thing, we can interrupt the microcontroller and what
it will do is it'll take everything it's working on, it'll save it into registers, and then
it'll go and take care of our interrupt.
And that's exactly what we can modify our circuit to do in order to improve it so that
during the delay, we can still take responses from our switch.
So let's learn a little bit more about how hardware interrupts work with the Arduino.
In a typical Arduino sketch, we begin by declaring some variables, including the libraries we'll
need and perhaps defining a few functions.
In the setup routine, we set pin modes, we'll start devices, and if necessary, we'll run
any one-time code that needs to run at the beginning of our sketch.
After that, we enter the loop where we repeat our code indefinitely.
And within the loop, we run the commands in sequence.
If we look at the sketch that we just ran, you can see that we are running two main commands,
the checkswitch function, which we've defined externally, and the delay function.
We're also running a couple of serial prints as well.
Everything in our loop is run in sequence, so it starts off by running checkswitch.
While it's running checkswitch, that's the only thing that it's doing.
Our sketch then runs the delay, and while it's running the delay, that's the only thing
it's doing.
It's not paying attention to the checkswitch function, and of course, this is the problem
with our sketch that we've induced.
When it's running delay, it's not monitoring checkswitch, and any pushbutton activity then
is simply being ignored.
Once it finishes running delay, it'll go back and check the checkswitch, but it only does
that momentarily, which is why the operation of the switch is so intermittent and unreliable.
Now a better way to accomplish this would be to put checkswitch in its own function,
a function that was only called when a hardware interrupt was received.
In this scenario, the delay is still in the loop, and it runs continuously.
If however, an interrupt is received, everything in the loop is stopped and put aside, and
the program goes and runs the function that has been called by the interrupt.
After the running of the checkswitch function is complete, it goes back and runs the delay.
And this is a much better scenario, as it won't miss any presses of our pushbutton.
If we take another look at the flowchart for our program, you can see that we've added
another element, an ISR, or Interrupt Service Routine.
In some programming languages, this is called an interrupt handler.
In this scenario, the program runs as normal, with our declarations in the start, and our
setup routines, and then everything running in the loop repetitively.
However, if an interrupt is received, it breaks the operation from the loop, and goes and
runs the code in the ISR.
Once that's finished, it goes back and resumes where it left off in the loop.
An interrupt service routine is a function that is called whenever an interrupt is received.
When an interrupt is received, the program stops execution and runs the code in the ISR.
The execution in the loop will resume right after the interrupt service routine has finished.
Because it's interrupting the program, the ISR needs to be very fast.
There are several commands that can't be used in an interrupt service routine function,
such as delay, serial, and millis.
The interrupt service routine can call other functions, but they also need to be very fast.
The variables used in your ISR need to be defined globally, as you can't define variables
within an interrupt service routine.
You should also use the volatile declaration for those variables to prevent a compiler
error.
This can occur because the compiler may try to optimize your code, as it does not realize
that the values of these variables are being modified externally to your sketch.
Today we'll be experimenting with interrupts using the Arduino Uno, and this device has
two hardware interrupts.
Pin 2 is interrupt 0, or interrupt vector 0.
And pin 3 is interrupt vector 1.
Although the Uno only has two hardware interrupts, this is not true of all Arduino boards.
And here's a chart that shows you the number of interrupts for several different common
Arduino boards.
Within our sketch, we'll use the attach interrupt function in order to attach the interrupt
to the interrupt service routine function.
It has the following parameters.
The interrupt vector is the interrupt vector number that we wish to use.
Now, this is not the pin number, it is the internal number used for the interrupt.
We also need to define the name of the function that we're going to use as an interrupt service
routine.
The final parameter in attach interrupt is the mode parameter, and the mode parameter
determines how the interrupt is triggered.
Rising indicates that the interrupt is triggered when the input goes from low to high.
Falling is the opposite, and the interrupt is triggered when the input goes from high
to low.
Low simply means the interrupt is triggered when the input is low.
And change means the interrupt is triggered when it falls or rises.
The interrupt vector is of course a very important parameter in the attach interrupt function,
but it can be a confusing one as it doesn't match the pin number.
One way to determine the interrupt vector is to use the digital pin to interrupt function,
which accepts the pin number as a parameter and returns the interrupt vector number.
We can then modify the attach interrupt function to use the digital pin to interrupt function
within it as one of its parameters.
Using digital pin to interrupt is actually the preferred method of coding this.
The Arduino Due and Zero boards also have an additional high trigger mode that the other
boards don't have.
Interrupt vectors have a priority system, and only one interrupt service routine can
be run at a time.
If you receive multiple interrupts, they'll be executed in order of that priority.
And so now that we've learned more about hardware interrupts, let's go back to our sketch and
modify it to use them.
So here's a revised version of our sketch using interrupts to try to resolve the problem
we had with the time delay.
Now we're going to start off in a similar fashion by defining two constants to represent
the LED and the push button.
And we have our boolean that represents the toggle state, and I don't know if you've noticed
this word volatile in front of the boolean.
In the last two bits of code that was actually optional, it wouldn't have made much of a
difference.
But in this code, you absolutely need to use it.
And the reason you need to use this is because toggle state is not going to be modified during
the loop.
And it's quite possible that your compiler will look at it and say, well, we're not using
this variable.
Let's eliminate it.
And you don't want that to happen.
Now we've got our check switch function.
It's the same function we had before with one slight modification.
And the modification is that the small time delay I added for debouncing the switch has
been removed from it.
And the reason I did that is because I'm going to use check switch as my interrupt service
routine, as the function that is called whenever I receive an interrupt.
And delay is one of those functions that you can't use in an interrupt service routine.
But as it turns out, debouncing isn't that much of a problem, and I'll show you why in
a little bit.
Otherwise, check switch is identical to what it was before.
It just checks to see if the switch has been pressed.
And if it is, it toggles the toggle state variable and then drives the LED accordingly.
Now we go into setup, and there's a small difference here in setup.
We begin with the same pin mode commands we used before.
And we're also using the serial monitor.
And here's our difference.
This is where we attach the interrupt to an interrupt service routine.
And so we use attach interrupt.
And then in order to determine which interrupt, we're going to use the digital pin to interrupt
because that makes it so much easier because we can just specify the actual pin.
And we'll pass it the button pin.
Now the next parameter over here, which says check switch, is the function that we want
to call whenever we get an interrupt.
So check switch is the name of our function over here.
So this is our interrupt service routine.
And falling means that we want to trigger the interrupt on a falling pulse.
So on a time when the interrupt goes from high to low, that's when it's going to trigger.
And that's what's going to happen when we press our push button.
The push button has an internal pull up over here.
So it's always going to be high.
But when we press it, it's going to go low.
And that's going to trigger this interrupt.
Now if we go into the loop, you'll notice that the only thing we have in the loop is
our delay.
All of the functionality for triggering the LED and switching it has been done externally
by the interrupt and by this check switch function over here.
So all that's going to go on in our loop is a delay.
So let's load this up to the Arduino and see if it resolves our issue with the toggle during
delay.
So I've loaded the code with the interrupt up to the board and it's running right now.
And if you take a look at the serial monitor, you'll see that we're in a delay period, which
we pretty well are always going to be in because the only thing in our loop is the delay function.
And so now let's try pressing our switch.
And as you can see, we can toggle it on and we can toggle it off.
And it doesn't matter that the Arduino is running a delay at the moment.
The interrupt is interrupting that.
It's pushing everything of the delay aside.
It's servicing that and it's going back to run the delay.
And so this works very well.
So as you can see, an interrupt is a much better method of connecting a switch up to
an Arduino than just simply pulling it would be.
And this is one of the advantages of using hardware interrupts.
So as we've seen, a hardware interrupt was the solution to our dilemma about how to capture
the input from a push button when we have a long process like a delay running in our
loop.
And hardware interrupts can be very, very useful.
Now on the Arduino Uno, only two pins are hardware interrupt capable, and other models
of Arduinos have a different number of interrupt capable pins.
But you might want to use more than two pins on your Uno for interrupts, and there is a
way of doing that.
There is a way that you can use every I-O pin on the Arduino as an interrupt pin, and
that includes the analog pins as well.
And that method is called a pin change interrupt.
Now a pin change interrupt is not as versatile as a hardware interrupt, but it still can
be very useful.
So let's go and learn a little bit about pin change interrupts.
Every I-O pin on the Arduino Uno will support pin change interrupts.
The ATmega328 processor upon which the Uno is based has 24 pin change interrupt pins.
20 of those pins are available on the Arduino Uno.
Now as their name would apply, a pin change interrupt is activated on a change of state
only, so it's activated when the input goes low to high, or high to low.
The pins used with pin change interrupts are grouped into ports.
Now all of the pins on the same port will share a pin change interrupt.
On the Arduino Uno, pin change interrupts are divided into three ports.
Port B, Port C, and Port D.
By the way, you've probably noticed that on the Uno there's a gap between pins 7 and 8,
and the reason is this is the difference between Port D and Port B.
Port B is associated with pins 8 through 13.
These can also be designated with a port number, or a PCINT number.
The PCINT number is the one you're going to need in order to mask or unmask that specific pin.
Port C comprises of all the analog pins on the Arduino Uno.
Remember that the analog pins can also be used as digital I-O pins.
And Port D is comprised of 8 pins, from pin 0 to pin 7.
Note that Port D also contains the transmit and receive pins,
as well as the two hardware interrupt pins.
These can also be used as pin change interrupt pins.
The first step in using pin change interrupts is to enable or disable the port that you wish to work with.
This is done with the Pin Change Interrupt Control Register, or the PCICR.
Here is some sample code in which we wish to use Port B.
You'll notice we sent the binary number to the Pin Change Interrupt Control Register
that has a 1 in the bit 0 position, as 1 activates Port B.
After selecting the port you wish to use with the PCICR,
the next step is to enable or disable the pins on that port that you want to use for pin change interrupts.
You'll do this by modifying the pin change mask, and there are three masks, one for each of the ports.
We'll continue our code by using Pin D12, which is one of the pins in the Port B group.
In this case, we'll change Pin Change Mask 0,
and we'll send bit 4 high in order to activate Pin D12, and you can see that in this code.
The third step is to define the interrupt service routine.
The names of the interrupt service routines have already been predefined for you,
so you'll choose the interrupt service routine that corresponds to the port that you are using.
To continue our code, our interrupt service routine will be the ISR PCINT0 VECT,
as this is the one for Port B.
Another register that you should be aware of is the Pin Change Interrupt Flag Register, or the PCIFR.
This register is activated by any change within the pin group.
After activation, it must be reset by writing a 1 to the corresponding register,
and there is one register for each port.
You normally don't have to worry about doing this, however,
as it's automatically reset when the associated interrupt service routine has been triggered.
Pin change interrupts are useful, but there are some precautions you need to observe when using them.
Remember, pin change interrupts are only change.
You can't get a low, or you can't get a rising or a falling.
It is only a change, and so a push button being pressed will create two interrupts,
one when it goes down, and one when it comes back up.
Keep in mind that since we're using ports,
it's quite possible to have two or more pin change interrupts on the same port,
and you'll need to find a way of differentiating to determine which one caused the interrupt.
A common method of doing this is to use global values to store the previous port values.
When the interrupt is triggered,
you can compare the previous values to the current ones to determine which pin has changed.
You can also use a similar technique for detecting whether it is a high
or a low condition that has triggered the port.
So now let's go and work with pin change interrupts.
To demonstrate pin change interrupts,
we're going to add a couple of components to the Arduino Uno hookup that we already have.
Aside from the Arduino Uno, we'll now require two push buttons.
We'll also need two LEDs that can be the same color or two different colors.
And for each LED, we'll require a dropping resistor.
Again, I'm using 220 ohms, but that isn't a critical value.
We'll begin by connecting pin 11 to one side of a dropping resistor,
and the other side of that resistor will go to the LED's anode.
We'll attach the LED cathode to ground.
Pin 13 will also go to a dropping resistor, and then through to the anode of the other LED.
The cathode of that LED will also be tied to ground.
Pin 2 will go to one side of one of the push button switches.
The other side of that switch will be attached to ground,
and pin 7 will go to the remaining push button switch, whose other side is also grounded.
And this completes the wiring.
Now let's go and take a look at some code we can use for pin change interrupts.
Now the first sketch that we're going to run to experiment with pin change interrupts
is simply a sketch that shows you how you read one,
and we're only going to be using one of our LEDs and switches for this sketch.
We'll begin by defining that LED and switch, so we'll define the LED on pin 13
and the push button on pin 7.
And as we did in our previous sketches, we'll define a volatile boolean
called toggle state to indicate the input state.
Next we'll go into the setup, and it's the usual things.
We're going to set the LED up as an output, and set the switch up as an input
using the Arduino's internal 30k pull-up resistor.
Now we go and we set up our interrupt.
And we first modify the pin change interrupt control register, or PCICR.
And we need to tell it that we want to use the PCIe 2 bit, which is bit number 3.
So we write a 1 to bit number 3, and that tells us we want to use port D,
because our switch, as a matter of fact, both of our switches are on port D.
Next we have to modify the pin change mask for port D,
in order to tell it which of the inputs we actually want to use as interrupts.
And we're using pin D7, and that is bit number 7.
And so we take the PCMSK2, which is the mask for port D,
and we write bit 7 high and the rest of them low.
And that tells us we're going to respond the changes
only on this particular bit, which is pin D7.
Now we have no code running in the loop,
because everything is going to run in our interrupt service routine, which is over here.
Now the interrupt service routine name has already been predetermined,
because this is the ISR that's going to run whenever an interrupt occurs on port D.
Now in this particular case, we only have one interrupt capable on that port,
so we don't need to worry about determining which pin it came from.
We're simply going to invert our toggle state and do what we did before,
write that state to the LED.
Now remember though, that our interrupt is a change interrupt,
so we're going to get one when we press the button down,
and another one when we release it and the input goes back high.
So the operation might be a bit different.
At any rate, let's load it up to an Arduino and check it out.
And here's our first pin change interrupt demo.
Now of course I've got two switches and two LEDs wired up,
but right now I'm really only using one switch.
So this is the switch on D7, the red one, and this is the LED on pin D13.
And so when I press the switch, you'll see the LED come on.
When I release it, the LED goes off.
And that's actually the expected behavior, because remember,
a pin change interrupt operates, as its name would imply, on a change of state.
And so there's a change of state when I press the button down,
and bring it from high to low,
and then when I release the button, it goes from low to high,
because of the internal pull-up resistor.
So there are two changes of state involved here.
One for button down, one for button up.
So it really just operates like a push button that was wired in series with an LED.
Now because of the fact that you may get a little bit of bounce on this,
and you can't really debounce the circuit,
because commands like delay and millis can't be used within the interrupt service routine,
you may get the situation in which it operates in inverted mode.
You might get a couple of extra bounces here.
At least I found that out when I was experimenting.
And so it would stay on, and it would turn off when you pressed it down.
But for the most part, it's pretty reliable.
And see, there we go.
I've got it to that state now, where it's on now.
And when I press it down, it goes off.
So you will notice that.
And there are other ways of doing debouncing, including within hardware,
and that's something we'll examine another day.
But as a demonstration, this shows that we're able to activate pin D7,
which was not a hardware interrupt pin,
but use it as an interrupt pin with a pin change interrupt.
So now let's go and put all of the LEDs and switches to use in our next demonstration.
Our next pin change interrupt demonstration is going to use
both of the switches and both of the LEDs.
And of course, you'll recall that we have the switches wired to pins D2 and D7.
And D2 and D7 both happen to be on port number D.
So they're going to generate the same interrupt.
So the purpose of this sketch is to illustrate
how we would differentiate between the two inputs
to determine whether it came from D2 or D7.
Now we'll start off by defining the input and output connections
to the switches and LEDs.
And so that's over here.
And then we have a couple of volatile booleans that represent the input state.
So we've got one for D2 state and one for D7 state.
In the setup, we'll set the LEDs up as outputs
and the switches up as inputs using the internal pull-up resistor.
Then we'll go to the pin change interrupt control register
and we'll write to bit 3 to indicate that we want to monitor port D.
So this is what we've done here exactly as we did in the previous sketch.
Now we need to go to the pin change mask and enable both pins D2 and D7.
And that's done by enabling both bit number 2 and bit number 7 and setting them to 1.
So we've set bit number 2 to 1 and bit number 7 to a 1 over here on the mask.
Now, once again, in the loop, we have no code
because everything is running in the interrupt service routine, which is over here.
This is the one that is called whenever port D has an interrupt.
Now we need to determine whether that interrupt came from pin D2 or D7.
And in this design, I'm just looking for the interrupt going from high to low.
So a falling one.
I'm looking for a low condition on that pin as I'm using this as a true toggle.
And so I'm going to check out, first of all, button pin number 1,
which is on port D2 to find out if it's low.
And if it is low, I know this is the one that just got pressed.
I'm going to invert the state of my Boolean and I'm going to write that to the LED number 1.
And for D7, I do the exact same thing, except now I'm reading button pin number 2, which is D7.
And I'm going to use the D7 state Boolean and invert it
and write to the LED pin 2, which is the one on pin 13.
And so the operation should be that we should have a toggle
and each one independently controlled by a push button,
although their interrupts use the same port.
So let's load that to the Arduino and check it out.
So here's our two interrupts on the same port demonstration.
And I've got the yellow push button driving the yellow LED and the red one driving the red LED.
And it works pretty good.
I can press the yellow to toggle it on.
Press it again to toggle it off.
Do the same with the red.
Can have one on, toggle the other one and off.
It's pretty good.
Occasionally, I get caught up by the debouncing thing, but it's relatively stable.
And so this illustrates that despite the fact that both of these switches are connected to
pins that are on the same port, port D in this case,
we can still differentiate between the two different pin change interrupts
and respond to them accordingly.
One way to simplify your work with pin change interrupts is to use a library.
And there are a few libraries out there for pin change interrupts,
although many of them are old libraries that are no longer being supported.
There is one that you can get through the Arduino IDE.
However, go into tools and then go into your library manager.
And in the library manager, filter your search by pin change.
And if you scroll down to the bottom, you'll see one called pin change interrupt by Nico Hood.
And this is still a valid library.
So we're going to go and install it.
And it's been installed.
And let's go and take a look at one of the example sketches.
And here we are, pin change interrupt.
And there's one called pin change interrupt LED.
Let's open that one up and take a look at it.
Now there's a lot of explanation at the top over here.
It includes the library.
They define a input port, which in this case is going to be pin number seven.
So this is where you're going to connect the push button to ground.
We're going to set that input as an input with a pull up.
And we're going to use the built-in LED as an output.
So it's used pin 13 for the LED.
They've got a function they're going to call that I'll show you in a moment.
They're going to call it first inside the setup just to make sure it's functional.
It'll turn the LED on and off for a second.
And then this library uses a similar method to what we use with regular interrupts
to attach the pin change interrupt to a function,
which is going to be like the interrupt service routine.
So this bypasses the normal operation of pin change interrupts
and allows you to use your own function.
And here's the blink LED function itself.
It just basically turns the LED state around.
It does a digital write to the LED of whatever the opposite condition of the LED is.
And this is one way to switch the input of an LED.
I'll be showing you another way to do that in a little while as well.
And then on the loop again there's nothing to do
because everything is being done by the library and the pin change interrupt.
So let's go and load that up to our Arduino and check it out.
Now here's our pin change interrupt library demonstration.
And this functions identically to the first piece of demo code we did.
We've got pin D7, the red push button, hooked up and pin D13, the red LED.
And when I press down the push button, you can see that the LED comes on.
When I release it, it comes off because it is working again on a pin change interrupt.
So it's responding to both the change when it's down and the change when it's up again.
And it seems pretty stable.
In some ways it may even be a little more stable than the original demonstration.
I don't seem to have really much of an issue with debouncing this.
So this might be a route to go.
You might also find the library to be a little easier to work with
than working directly by putting binary numbers into a number of registers and masks.
But whatever way you choose to use it, I think you'll find that pin change
interrupts can open up a lot of possibilities
since they'll respond to every single pin on the Arduino Uno.
Now there's one other type of interrupt that you can use with an Arduino Uno,
and it's something called a timer interrupt.
As its name would imply, a timer interrupt is an interrupt that is generated after a
predetermined amount of time.
And this can be very useful in a lot of applications
if you have to take a reading of something periodically,
or if you need to produce an output periodically.
Now you've already used timer interrupts without even knowing it.
I'm sure you have if you've ever used the pulse width modulation,
if you've ever used the servo library,
if you've ever used the tone library while you've been using the Arduino's internal timers.
And because of that, you have to be careful when you're using timer interrupt
not to use a timer that's being used by another process.
So let's go and learn a little bit more about timer interrupts.
The ATmega328 chip that powers the Arduino Uno has three internal timers.
They're labeled timer 0, timer 1, and timer 2.
Timer 0 and timer 2 are 8-bit timers,
whereas timer 1 is a 16-bit timer.
The timers are driven by the Arduino's internal clock source,
and the Arduino Uno uses a 16 MHz clock oscillator.
Each cycle of the clock is considered to be a tick for the timer,
and is the minimum amount of time that the timer can time.
With a 16 MHz oscillator, each tick will be 62.5 ns long.
62.5 ns is a pretty short period of time,
so the chip also has an internal pre-scaler in order to divide the oscillator down
by some preset numbers.
Using the pre-scaler, we can divide our 16 MHz clock down to as low as 15.625 kHz,
which is a time period of 64 microseconds.
Each timer has its own set of bits to determine the pre-scaler value.
For timer 0, the CS02, CS01, and CS00 bits determine the value of the pre-scaler.
Note that it can also be set for no clock source,
which stops the timers, or for an external clock source.
Timer 1, the 16-bit timer, is handled the same way as timer 0,
except it uses the CS12, CS11, and CS10 bits instead.
Timer 2, which is another 8-bit timer, has a limited number of selections for the pre-scaler.
You can just simply set it for no clock source, or for four different pre-scaler values.
Note that you can't use an external clock source with timer 2.
An interrupt is generated when a timer reaches a specific value or count.
In compare match mode, that specific value can be stored in the compare match register.
Once the value has been matched, the timer will clear,
or set itself to 0 so that it can start over again.
It can also be operated in overflow mode,
where an interrupt is generated when the timer overflows its count.
The timer frequency can therefore be set by changing the value of both the pre-scaler
and the compare match register, and this is the formula for doing this.
Clock indicates the clock frequency, and notice the addition of the 1 at the end.
That is because the compare match register starts with a base of 0 and not 1.
Using this formula, we can determine the value that we need to get a 1Hz signal,
or 1 pulse per second, out of our timer.
In order to get the compare match register value,
we can turn the formula around as shown over here.
So as you can see, we arrive at a value of 15,624 if we want a 1Hz output,
and we are using a pre-scaler of 1024.
The names for the interrupt service routine functions have already been
predetermined for the timer interrupts,
and these are the names for both the compare match mode and the overflow mode.
Note that the small case x in both of these names would be replaced by the number of the timer,
so timer 0, timer 1, or timer 2.
So now that we know a little bit more about timer interrupts,
let's write some simple code to put them to use.
Now in this experiment, we're going to use timer 1
to drive an LED and to flash it on and off.
In other words, we're going to be doing the blink sketch.
And as we're going to be using the LED on pin 13,
there's no additional hookup required for this experiment
because the Arduino Uno has a built-in LED on pin 13.
If you still have the demo wired up that we used for hardware interrupts,
you can use this as well for our demonstration as it has an LED on pin 13.
So we'll start the code off by defining the connection for that LED on pin 13,
and then we also define another variable, an integer,
that's going to be the compare match register value,
which as you recall sets the output frequency of the timer along with the pre-scaler.
Now over here is our interrupt service routine,
and as I showed you earlier, the name has already been predetermined for us,
and since we're using comparison mode for timer 1,
this is the interrupt service routine that we'll be making use of.
Now we're going to preload our timer with the compare match value when this is called,
because when this is called, our timer has been triggered and is down to zero again.
So we're going to basically reset it to that value again every time we run this.
And then we're going to flip the value of the LED.
If it's on, we'll turn it off. If it's off, we'll turn it on.
And this is an interesting way of doing it.
We're doing a digital write to the LED pin,
and what we're writing to it is the inverse of the current state of the LED pin,
which is determined with a digital read.
So that's just another way of flipping the value of the LED,
and it has an advantage in that it's very fast,
and of course in an interrupt service routine, that is very important.
Now we'll go into this setup, and we'll set up our LED as an output,
and then we will disable all of the interrupts.
We don't want an interrupt to occur while we're running this setup.
We're going to initialize timer one,
and you do that by setting these two registers to a value of zero.
And then we're going to set the compareMatch a variable.
Now the compareMatch register value was determined by the formula
that it showed you in the explainer for the timers,
and so for a pre-scalar value of 256,
I came up with a compareMatch value of 31246,
and that will output a frequency of two hertz.
In other words, our LED is going to turn on and off
all within the period of a second.
That's going to be a period of a half a second on
and a half a second off over here.
And of course, you could change that by altering the value,
or if you wish, by changing the pre-scaler that you're going to use.
Now, so we set our timer compareMatch value to 31249,
the value that I determined,
and then we're going to preload it as we did earlier.
Then we'll set our pre-scaler up.
Now, you remember the pre-scaler for timer one
is determined by a number of different bits,
and in this case, bit CS12 needs to be set to a one,
so we're going to set that.
We don't need to set the zero bits
because they're automatically implied.
And now we're going to enable our timer for compareMode.
We could also have enabled it for overflowMode if we wanted to,
but this sets it into compareMode.
And then finally, we're going to re-establish all of the interrupts
now that everything is set up.
Now, if we go down into the loop, you'll notice there's absolutely nothing.
Everything here is being done by the timer
and by the interrupt service routine over here.
And so there's no code in the loop,
and yet we'll be able to make a blink sketch without any code in the loop.
So let's load this up to our Arduino and watch it in action.
And now here's our demonstration.
Fascinating as it might be, I'm using the same hookup
that I used for the hardware interrupt experiments.
So you'll note that I still have a push button on my Satellus breadboard,
although it's not being used in this circuit.
And we can plainly see that the LED is flashing right now.
And again, I think the interesting thing about this
is that there is no code in the loop.
The LED is just flashing because it's responding to a timer interrupt.
And if you have something that you need to do,
such as sample a sensor on a specific period of time,
the DHT22 sensor, for example, it needs a sample every two seconds.
A timer interrupt is an ideal way of accomplishing this.
So that concludes our look at interrupts.
I hope that you enjoyed it.
And more importantly, I hope that it's inspired you
to start using interrupts in your own code.
Now, if you need some more information about interrupts,
or if you want to grab the code that I used today,
just head over to the DroneBotWorkshop.com website,
where you will find an article that accompanies this video.
And there's a link right below the video to the article.
When you're on the website, if you haven't yet,
please sign up for my newsletter.
It's just a way of occasionally getting out to you
to let you know what's going on here in the workshop.
And of course, it's free.
All I need is your email address.
If you want to discuss interrupts and anything electronic,
well, the best place to go, of course, is on the DroneBotWorkshop forums.
And you can join the forum for free,
and talk to a bunch of like-minded individuals
who love to work with electronics.
And there's information about that below the video.
And finally, although it's been said earlier in the video,
if you haven't subscribed to the YouTube channel,
please do that.
I'd be honored to have you as my next subscriber.
And as I said before,
just go and click on the subscribe button that's below the video,
and also click on that bell notification.
And as long as you've got them enabled,
you'll be getting a notification every time that I make a new video.
So until we meet the next time,
please take good care of yourself,
and please stay safe out there.
And we will see you soon here in the DroneBotWorkshop.
Goodbye for now.
