I want to have a project where a switch connected to pin 2 of arduino and the other lead of switch to 5v. whenever the switch is pressed the serial monitor should display the number for which the switch is pressed.
here is the code that i used:
int val;
volatile int count = 0;
volatile int pulse = 2;
void setup()
{
Serial.begin(9600)
}
void loop()
{
attachinterrupt(0, counter, RISING);
}
void counter()
{
val = digitalRead(pulse);
count = count + 1;
Serial.print(count);
}
thats the code..
but after opening serial monitor and pressing the nothing happens. Somebody Please help me to sort out this problem.
Moderator edit: </mark> <mark>[code]</mark> <mark>
MarkT:
Things that you cannot use in an interrupt routine because they deadlock the Arduino:
delay()
Serial
( there may be others in other libraries - anything that waits for other
interrupts, basically )
Things that don't work in an interrupt routine:
millis()
( there may be others in other libraries )
Things that aren't a good idea in an interrupt routine:
anything time-consuming, anything that can be done in loop() without
difficulty.
Millis() is often used in ISRs as long as you realize that it doesn't increment while inside the ISR, however it's still good as a 'time stamp' to tell a sketch when the interrupt triggered and use that value for say a debounce function.
Its often a good idea to check what a function w.r.t. interrupts before
calling it from an ISR, which is usually simple to do - look at its source code,
which you should have and should become familiar with as/when needed...
ChirantanKansara9:
I want to have a project where a switch connected to pin 2 of arduino and the other lead of switch to 5v. whenever the switch is pressed the serial monitor should display the number for which the switch is pressed.
You don't need interrupts to detect button presses, and unless you're doing this specifically because you want to play with interrupts, you'd be better off without them. The state change detection example sketch shows how to detect button presses including debouncing the input. It would only need a very simple change to increment a counter and print it out each time a button press is detected.