7

(avery) #1

Arduino programming: Stacks, classes, and scrolling displays


SCHOOL OF MAKING


adding a destructor, but a good programmer uses
the destructor to free up any allocated memory and
generally clean up after themselves.
The push function simply checks to make sure
the top isn’t yet at the maximum stack size value,
and enters the item value at the current top position
before incrementing top to the next array location.
We haven’t implemented pop because it’s not
needed – we’re simply overwriting previous values
in the array. Instead, we have peek to return the

item value at x. The tricky part is that because top
is always changing, x is an offset from the value of
top, which we modulo against the maximum stack
size, to make sure it’s both within range and loops
over when higher. Modulo is very useful for such a
simple operator!

DRAWING LINES
The next chunk of code instantiates three types for
the sensor, our new Stack class and for the screen,
before filling out the Arduino’s setup function. This

STACK OVERFLOW


A stack is a data structure, and that just means it holds
data in a specific way. The most common stack holds
data in the same way you create a deck of cards,
putting one card on top of the next and removing cards
from the top of the pile. In stack terminology, this is a
LIFO stack – the card that was last in is first out. FIFO
(first in, first out) is another common variant, and this
operates as a basic queue. Alan Turing even coined
the terms ‘bury’ and ‘unbury’ in 1946 to describe the
process of adding and removing data from a stack, but
we now use the terms ‘push’ and ‘pop’ for the same
thing. Additionally, ‘peek’ is often used when you want
to take a look at the top card, rather than remove it,
or examine another card in the pack. Just like in 1946,
however, stacks are ideal when you only have a limited
amount of memory.

The module itself combines both temperature and
humidity sensors, and the great thing about this
module is that it’s incredibly easy to use



Right
Libraries can be
downloaded and
installed manually,
as discussed last
month, but it’s much
easier to just use the
Arduino IDE

The term ‘stack
overflow’ actually
refers to when you
try to write to the
stack and the stack
is full. Fortunately, as
ours is fixed in size,
this won’t happen.

QUICK TIP


5
4
3
2
1

3
2
1

4
3
2
1

2
1 1

6
5
4
3
2

Pop
Pop
Pop
Pop
Pop

2

3

3

3

3

Push

Push

Push

Push

Push

1

2

3

4

5

1

2

3

4

1

2

3
1

2
1
Free download pdf