7

(avery) #1
FORGE

void push(int item) {
if (top == MAXSTACK)
top = 0;
ourList[top++] = item;
}
int peek(int x) {
return ourList[(top + x) % MAXSTACK];
}
};
This stack is a list of data that we can keep pushing
data to, and peeking at data in. It will always hold the
most recent 128 datapoints pushed into the stack.
Our stack is implemented within a class. We
discussed classes in the previous tutorial when we
used one to access the DHT11, but in the above code
we’re creating our own. Classes, a little like stacks,
are a huge subject that can even dictate the design of
an entire programming language, but they’re basically
just a way of co-locating data with the functions that
use the data. In our case, that means the data is the
value for each temperature reading, and the functions
add and read values from the stack. If the data and
functions are solely for the use of the class, they’re
defined beneath a ‘private’ specifier, and won’t be
accessible outside the class – this helps hide the
complexity and avoids erroneous access from outside
the class. Conversely, for data and functions intended
to be accessed by you, the programmer, we use
the ‘public’ specifier. In our above class, the push


and peek functions are all public, as we’ll be using
these to create and view our stack. The array
that holds the temperature readings,
ourList, is private, as too is an
integer that holds the
current top array
position of
the stack.
There are
three functions
that are members
of this class. The
first is special because
it takes the name of the
class itself – Stack(). This
is the constructor, and like
setup() in an Arduino project,
it runs automatically when a
class is instantiated. We use this
instantiation to set the internal values
to zero, including every element of the
array. This safeguards against wayward
values being left over in memory or a
previous execution. Although we’ve not used
it here, the opposite function to the constructor
is the destructor, written as ~Stack() in a class
definition, and this function is run when a class is
deleted. As our code only quits when the Arduino is
reset or powered off, we’re saving space and not

If you experience
display problems,
you may need to
use an external 5 V
power source for the
screen, connecting
the common ground
to the Arduino.

QUICK TIP


Above
SSD1306-compatible
screens are cheap
and readily available,
and can even be
found in different
colours and in
multiple colour
configurations
Left
The OLED display
and temperature
sensor in situ on
the breadboard
Free download pdf