1.2.14. fejezet, TaskManagerIO: az eseményvezérelt programozás másként

Szükséges könyvtárak Arduino-hoz

Kapcsolódó hivatkozások

Minta program

#include <IoAbstraction.h>
 
int switchPin = 13;
int buttonPin = 12;
int switchState = LOW;
 
IoAbstractionRef ioDevice = ioUsingArduino();
 
char inChar;
bool serialAction() {
  while(Serial.available() > 0) {
    inChar = Serial.read();
    Serial.print(inChar);
  }
  return true;
}
 
void onButtonClick(uint8_t pin, bool heldDown) {
  Serial.print("Button clicked [hold:");
  Serial.print(heldDown);
  Serial.println("]");
}
 
void timerAction() {
  switchState = switchState == HIGH ? LOW : HIGH;
  ioDeviceDigitalWrite(ioDevice, switchPin, switchState);
}
 
void setup() {
  Serial.begin(9600);
  while(!Serial);
 
  ioDevicePinMode(ioDevice, switchPin, OUTPUT);
  ioDevicePinMode(ioDevice, buttonPin, INPUT);
  switches.init(ioDevice, SWITCHES_POLL_EVERYTHING, true);
  switches.addSwitch(buttonPin, onButtonClick, NO_REPEAT);
  taskManager.scheduleFixedRate(1, timerAction, TIME_SECONDS);
  Serial.println("Listeners started.");
}
 
void loop() {
    taskManager.runLoop();
}

SerialEventHandler

#include <TaskManagerIO.h>
 
class SerialEvent : public BaseEvent {
    private:
      Stream* _serial;
    public:
      SerialEvent(Stream* serial) {
        this->_serial = serial;
      }
    uint32_t timeOfNextCheck() override { 
      if (_serial->available()) markTriggeredAndNotify();
      return secondsToMicros(1);
    }
    void exec() override {
        char inChar;
        while(_serial->available()) {
          inChar = _serial->read();
          _serial->print(inChar);
        }
    }
};
 
void setup() {
  // put your setup code here, to run once:
  Serial.begin(19200);
  while (!Serial);
  SerialEvent* myEvent = new SerialEvent(&Serial);
  taskManager.registerEvent(myEvent);
}
 
void loop() {
  taskManager.runLoop();
}