A sample implementation of Observer Pattern
This code was written using PlatformIO and vscode. Would you like This code to be compatible with the Arduino IDE?... tell me!
Implement Observer Design Pattern in a microcontroller.
Can we use design patterns in our code for microcontrollers? ... obviously yes (otherwise we would not be here).
OK, show me the code!
I said "code", not diagram!
#include ...
SensorReader sensorReader;
void setup()
{
...
sensorReader.attach(new LedIndicator());
sensorReader.attach(new LoggerToSerial());
sensorReader.attach(new MqttPublisher());
...
}
void loop()
{
sensorReader.work();
}
We define a class inheriting Subject with the type of notification argument
#define INTERVAL 2000
class SensorReader : public Subject<EventArgs>
{
public:
void work()
{
if (lastRead + INTERVAL < millis())
{
// Reading simulation
EventArgs args;
args.temperature = random(15, 35);
args.humidity = random(20, 80);
Subject::notify(args);
lastRead = millis();
}
}
private:
long lastRead = 0;
};
struct EventArgs
{
float temperature;
float humidity;
};
Yes, it's a struct but could be a class too
We define different classes inheriting Observer
class LoggerToSerial : public Observer<EventArgs>
{
public:
void notify(EventArgs args) override
{
Serial.print("Temperature: ");
Serial.print(args.temperature);
Serial.print(", Humidity: ");
Serial.println(args.humidity);
}
};
class LedIndicator : public Observer<EventArgs>
{
public:
void notify(EventArgs args) override
{
if (args.temperature > 30 || args.humidity > 50)
digitalWrite(LED_BUILTIN, LOW);
else
digitalWrite(LED_BUILTIN, HIGH);
}
};