7

(avery) #1

Arduino programming: Stacks, classes, and scrolling displays


SCHOOL OF MAKING


we want to include the two new library header files
alongside dht.h for the sensor:
#include <dht.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>

Beneath these lines, we’re going to use three
#define statements to bake-in system-wide values
that save us from changing the actual code to
accommodate hardware differences:
#define DHT11_PIN 2
#define SCREENADR 0x3C
#define MAXSTACK 128

The first line sets the pin connected to the
temperature and humidity sensor, the same as in the
previous tutorial. The second line is the I^2 C address
of the screen. The screen and the Arduino talk to
each other using the I^2 C protocol, and because
you can connect multiple devices over I^2 C, each is
differentiated with an address. Ours is 0x3C. This
should be included in your screen documentation,
or even burnt into the PCB, but you can also run
a script to probe any connected I^2 C devices and
return the address of each device if you need to
(hsmag.cc/kigPeT).
The third statement in the above code is a
precursor to a new and important concept we’re
going to introduce in this tutorial, and that’s

something called a ‘stack’. We’re going to use a
simplified stack to hold 128 separate temperature
measurements, so that we can draw a histogram
of changes in temperature over time. You might
wonder why we don’t use a simple array to hold
these values, but this is because we want the
histogram to scroll in real time as temperatures are
added. If we were to simply update the values in an
array sequentially, the histogram would draw itself
across the screen, left to right, and then simply
reset to the left border of the screen again, as you
see in many such implementations. But a stack
allows us to have a sliding window of values that
follow a leading edge, effectively creating a scrolling
histogram of temperature data. This all sounds
more complicated than the actual code, so let’s take
a look:
class Stack
{
private:
int ourList[MAXSTACK];
int top;
public:
Stack() {
top = 0;
for (int i = 0; i <= MAXSTACK; i++)
ourList[i] = 0;
}

Using the text
function requires
a foreground
and background
colour. Without a
background colour,
when the text
updates it will look
corrupted, but it’s
because old text
pixels are still there in
the background.

QUICK TIP


Right
The display we’re
using is less than an
inch across, which
is ideal for tiny IoT
installations and self-
contained devices
Free download pdf