Skip to content
Alex Krieg edited this page May 25, 2018 · 6 revisions

Default

Imagine that you have a button that is supposed to trigger a certain activity.
How would you solve this problem?

const byte buttonPin = 3;

void myTriggerFunction();
void setup()
{
  pinMode(buttonPin,INPUT);
}
void loop()
{
  if(digitalRead(buttonPin) == true)
  {
    myTriggerFunction();
  }
}
void myTriggerFunction()
{
  //Button pressed
}

This code could be a solution. If you want to query different events now, such as rising or falling edge or button pressed or not,
so the code could by quickly very large and that only with a button.

Is not it much easier if you don't have to worry about reading the button? I think so, and so some libraries of mine offer you the ability to add a function to an event.


How events work

To use an event, you need a function that can be triggered.
Mostly such functions will not accept or return any parameters.

So you have to define a function that you can pass to the object.
The object stores the address (pointer) of the function.
The function is triggered when the .Update(); function is called.
But only if a function has been deposited and the event has occurred.


Make an event

An example of an event looks like this:

#include "button.h"

const byte buttonPin = 3;
Button myButton(buttonPin);

void myTriggerFunction();
void setup()
{
  myButton.OnPressedEdge(myTriggerFunction);
}
void loop()
{
  myButton.update();
}
void myTriggerFunction()
{
  //Button pressed
}

This is a clear code.

Special events

Some events allow the defined function to accept parameters.
e.g. In library B57164 (temperature sensor).
There, an event can be triggered when the temperature exceeds or falls below a certain level.
When such an event is triggered, the temperature is simultaneously passed to the function.

#include "B57164.h"

const byte sensorPin = A0;
const float triggerTemperature = 50;
Temperature myTempSensor(sensorPin );

void temperatureTooHigh(float temp);
void setup()
{
  myTempSensor.onHigherThan(triggerTemperature ,temperatureTooHigh);
}
void loop()
{
  myTempSensor.update();
}
void temperatureTooHigh(float temp)
{
  Serial.print("Temperature too high: ");
  Serial.println(temp);
}

Advantages

Simpler programming. Structure and task distribution through the functions. Clear code.

Disadvantages

Assigned to the .Update() function. Delays in the code should be avoided. Use the Timer library instead of the delays.

Clone this wiki locally