Arduino Playground is read-only starting December 31st, 2018. For more info please look at this Forum Post

PinChangeInt Example

This code counts the number of times pin 15 (aka Analog 1) changes state and prints the count when it recives a p on the serial port.

  1. /*
  2. Copyright 2011 Lex.V.Talionis at gmail
  3. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
  4. */
  5. #include <PinChangeInt.h>
  6. #include <PinChangeIntConfig.h>
  7.  
  8. #define PIN 15  // the pin we are interested in
  9. volatile byte burp=0;    // a counter to see how many times the pin has changed
  10. byte cmd=0;     // a place to put our serial data
  11.  
  12. void setup() {
  13.   Serial.begin(9600);
  14.   Serial.print("PinChangeInt test on pin ");
  15.   Serial.print(PIN);
  16.   Serial.println();
  17.   pinMode(PIN, INPUT);     //set the pin to input
  18.   digitalWrite(PIN, HIGH); //use the internal pullup resistor
  19.   PCintPort::attachInterrupt(PIN, burpcount,RISING); // attach a PinChange Interrupt to our pin on the rising edge
  20. // (RISING, FALLING and CHANGE all work with this library)
  21. // and execute the function burpcount when that pin changes
  22.   }
  23.  
  24. void loop() {
  25.   cmd=Serial.read();  
  26.   if (cmd=='p')
  27.   {
  28.     Serial.print("burpcount:\t");
  29.     Serial.println(burp, DEC);
  30.   }
  31.   cmd=0;
  32. }
  33.  
  34. void burpcount()
  35. {
  36.   burp++;
  37. }