Golang and Arduino

Small arduino and golang programs

arduino debounce any pin function

P.S. all buttons should be connected to ground without any resistors.


bool debounce(const int pin) {
  static unsigned long ldt = 0;
  static unsigned long dbdelay = 50;

  static bool lbs = HIGH;
  static bool bs = LOW;

  const bool input = digitalRead(pin);

  if (input != lbs) {
    ldt = millis();
  }

  if (millis() - ldt > dbdelay) {
    if (input != bs) {
      bs = input;
      if (input == LOW) {
        return true;
      }
    }
  }
  lbs = input;
  return false;
}

const uint8_t inputPins[] { 8 } ; // just add more pins like { 8, 2, 3, 4 };

void setup() {
  Serial.begin(9600);

  // set input pins to INPUT_PULLUP mode
  for (uint8_t i; i < sizeof(inputPins) / sizeof(inputPins[[0]); i++) {
  pinMode(inputPins[i], INPUT_PULLUP);
  }
}

void loop() {
  // check if button on pin 8 is connected to ground (pressed)
  if (debounce(8)) {
    Serial.println("hello");
  }
}

July 5, 2021