blynkkk / blynk-sketch-generator

This repository is for generating Blynk sketches.
https://examples.blynk.cc
MIT License
25 stars 25 forks source link

Button Interrupt example has far too much in the void loop() #84

Closed Peterkn2001 closed 1 year ago

Peterkn2001 commented 5 years ago

Can we please change the existing Button Interrupt example. It has far too much unnecessary stuff happening in the void loop() that really ought to be handled directly in the void checkPin() function (which is called by the interrupt handler). This encourages new users to think that this approach is acceptable.

Revised code (minus the preamble, board specific libraries and credential definitions) is below:

WidgetLED led1(V1);

// We make this variable volatile, as it is used in interrupt context
volatile int  pinValue   = 0;

void checkPin()
{
  // Invert state, since button is "Active LOW"
  pinValue = !digitalRead(2);

  // Process the value
  if (pinValue) {
    led1.on();
  } else {
    led1.off();
  }
}

void setup()
{
  // Debug console
  Serial.begin(9600);

  Blynk.begin(auth, ssid, pass);
  // You can also specify server:
  //Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80);
  //Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);

  // Make pin 2 HIGH by default
  pinMode(2, INPUT_PULLUP);
  // Attach INT to our handler
  attachInterrupt(digitalPinToInterrupt(2), checkPin, CHANGE);
}

void loop()
{
  Blynk.run();
}
vshymanskyy commented 1 year ago

No, calling led1.on(); and led1.off(); in the interrupt context is not allowed (in many systems, at least).