arduino button with pull up

Make button respond immediately without delay in arduino

Sometimes in our arduino project we need a button that repon immediately. When the button pressed the arduino respon directly without delay even there are delay in the sketch. Yes, we will make the button respon immediately and ignore the delay when the button pressed!

So how we do that?

If you are new in arduino, or microcontroller programming maybe you not yet familiar with interrupt. So our key now is interrupt. Just like the word interrupt. This means that you will interrupt the arduino, make arduino do what you what to do immediately and leave what its job for a while.

You can wire your arduino and button like below:

arduino button with pull up
arduino button pull up

If you don’t want to use resistor. You can read how to make button without resistor here. Make sure you are connect button to pin 2 or pin 3, because another pin in arduino UNO will not work for interrupt. How about another arduino board? You can refer to table below.

 

Board Digital Pins Usable For Interrupts
Uno, Nano, Mini, other 328-based 2, 3
Mega, Mega2560, MegaADK 2, 3, 18, 19, 20, 21
Micro, Leonardo, other 32u4-based 0, 1, 2, 3, 7
Zero all digital pins, except 4
MKR1000 Rev.1 0, 1, 4, 5, 6, 7, 8, 9, A1, A2
Due all digital pins
101 all digital pins

 

You can read more about interrupt here.

OK, Let’s get our hand dirty!

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(interruptPin, INPUT);
  attachInterrupt(digitalPinToInterrupt(interruptPin), glow, FALLING);  //attach interrupt on pin 2, then call function glow when interrupt happen and interrupt happen when input on pin 2 FALLING (transition from HIGH to LOW);
}

void loop() {
  glow();
  delay(5000);
}

void glow() {
  digitalWrite(ledPin, HIGH);
}

 

You can change FALLING to RISING if you want interrupt to happen when input goes from LOW to HIGH. Or you can use CHANGE instead and make interrupt happen when input is changing, means like you use RISING and FALLING at the same time.

Leave a Reply

Your email address will not be published. Required fields are marked *