Pages: [1]   Go Down
Author Topic: Arduino Analog Interrupt  (Read 1360 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 15
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I am trying to implement an interrupt on digital pin 2 that will record values from analog Pins, however when value on digital pin 2 changes from "1" to "0" the Serial output stops and nothing seems to get recorded (Penny, Dime, Quarter, Nickel) so I cant tell if anything is actually happening. Is there something wrong with my approach?

Code:
int dime = 0;
int penny = 0;
int nickel = 0;
int quarter = 0;

int analogPin0 = 0;
int analogPin1 = 1;
int analogPin2 = 2;
int analogPin3 = 3;


void setup()
{
  Serial.begin(9600);
  pinMode(2, INPUT);
}

void loop()
{
  attachInterrupt(0, analog, CHANGE);
}

void analog()
{
  while(digitalRead(2) == LOW)
  {
    Serial.println(digitalRead(2));
    dime = analogRead(analogPin0);
    penny = analogRead(analogPin1);
    nickel = analogRead(analogPin2);
    quarter = analogRead(analogPin3);
    
    Serial.println(dime);
    Serial.println(penny);
    Serial.println(nickel);
    Serial.println(quarter);
    
    if(dime > 20)
    {
      Serial.println("Dime");
      delay(10000);
    }
    
    if(penny > 20)
    {
      Serial.println("Penny");
      delay(10000);
    }
    
    if(nickel > 20)
    {
      Serial.println("Nickel");
      delay(10000);
    }
    
    if(quarter > 20)
    {
      Serial.println("Quarter");
      delay(10000);
    }
      
    delay(5);
  }
  detachInterrupt(0);
}


Logged

0
Offline Offline
Faraday Member
**
Karma: 7
Posts: 2526
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Using delay() inside an ISR is very much bad.  Specifically it relies on interrupts, which IIRC are disabled while inside an ISR.  ISRs need to be fast fast fast, in and out, to keep from causing problems elsewhere.

Use the ISR to set a global flag, then check that flag's presence inside loop().

-j
Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 15
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thanks, kg4wsv I think i got it working now  smiley
Logged

Pages: [1]   Go Up
Jump to: