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);
}

arduino blink without delay when button is pressed


// led pin 
const int ledPin1 = 13;
// button pin const int buttonPin1 = 2;
// blinking delay const int interval1 = 500; bool ledState1; bool canBlink1; unsigned long previousMillis1; void setup() { pinMode(ledPin1, OUTPUT); // set led pin to output pinMode(2, INPUT_PULLUP); // button pin set to INPUT with internal PULLUP(default state will be HIGH) } void loop() { unsigned long currentMillis = millis(); bool buttonState1 = digitalRead(buttonPin1); if (buttonState1 == LOW) { while (digitalRead(buttonPin1) == LOW); if (digitalRead(buttonPin1) == HIGH) { canBlink1 = !canBlink1; digitalWrite(ledPin1, LOW); } } if (currentMillis - previousMillis1 >= interval1 && canBlink1) { previousMillis1 = currentMillis; ledState1 = !ledState1; digitalWrite(ledPin1, ledState1); } }