Golang and Arduino

Small arduino and golang programs

arduino blink without delay new way


typedef void (*myFunction)() ;

class RepeatEvery {
  private:
    unsigned long currentMillis = millis();
    unsigned long prevMillis = currentMillis;
    bool prevCanRun = false;
    unsigned long lwait;
    myFunction lf;
  public:
    RepeatEvery(myFunction f, unsigned long wait) {
      lwait = wait;
      lf = f;
    }

    void handle() {
      bool r = true;
      handle(r);
    }

    void handle(bool& canRun, bool reset = true) {
      currentMillis = millis();
      if (prevCanRun != canRun) {
        prevCanRun = canRun;
        if (reset == true)
          prevMillis = currentMillis;
        else
          prevMillis = currentMillis - lwait - 1;
      }
      if (currentMillis - prevMillis >= lwait && prevCanRun == true ) {
        prevMillis = currentMillis;
        lf();
      }
    }
};

bool runOnce = true;
bool canRun = true;

// function which depends on external variable
// blink LED_BUILTIN sveral times
RepeatEvery fn([] {
  Serial.println("Blink Blink");
  digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
}, 1000);

// function which turns on or of function named "fn"
// disables blinking after 5s and sets LED_BUILDIN to LOW
RepeatEvery repeatAlways([] {
  runOnce = false; // stop repeatAlways
  canRun = false; // stop fn
  digitalWrite(LED_BUILTIN, LOW);
  Serial.println("disable blinking");
}, 5000);

void setup() {

  Serial.begin(9600);
  while (!Serial);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  repeatAlways.handle(runOnce);
  fn.handle(canRun, true);
}

July 8, 2021