... und die Klasse ist fertig
// https://forum.arduino.cc/index.php?topic=621568.0
class Sensor
{
private:
const byte pin;
bool last_state;
bool new_state;
const byte debounce; // max. 255ms, ansonsten auf unsigned int/long ändern
unsigned long last_ms;
public:
// Konstruktor
Sensor (byte p, unsigned long deb) :
// Initialisierungsliste
pin(p),
last_state(true),
new_state(true),
debounce(deb),
last_ms(0)
{}
// Methoden
void init()
{
pinMode(pin, INPUT_PULLUP);
}
void entflattern ()
{
unsigned long ms = millis();
bool state = digitalRead(pin); // pin einlesen
if (state != last_state) { // Hat sich Eingangspegel geändert?
last_ms = ms; // Wenn ja aktuelle Zeit
last_state = state; // und diesen Zustand merken
}
if (ms - last_ms >= debounce) { // Blieb letzter Zustand für x ms stabil ?
new_state = state; // Wenn ja aktuellen Zustand merken
}
}
bool get_state() { return new_state; }
};
Sensor sensoren[] = {
{2, 100}, // pin, Entprellzeit
{3, 90},
{4, 110},
{5, 80}
};
void setup()
{
Serial.begin(9600);
for (Sensor & s : sensoren)
{
s.init();
}
}
void loop()
{
for (Sensor &s : sensoren)
{
s.entflattern();
}
serieller_Monitor (500); // nur zum sichtbar machen
}
void serieller_Monitor (const unsigned int INTERVALL)
{
static unsigned long last_ms = 0;
unsigned long ms = millis();
if (ms - last_ms > INTERVALL)
{
last_ms = ms;
for (Sensor &s : sensoren)
{
Serial.print(s.get_state() );
Serial.print('\t');
}
Serial.println();
}
}