TimerExample.pde 1.2 KB

12345678910111213141516171819202122232425
  1. // ---------------------------------------------------------------------------
  2. // While the NewPing library's primary goal is to interface with ultrasonic sensors, interfacing with
  3. // the Timer2 interrupt was a result of creating an interrupt-based ping method. Since these Timer2
  4. // interrupt methods were built, the library may as well provide the functionality to use these methods
  5. // in your sketches. This shows how simple it is (no ultrasonic sensor required). Keep in mind that
  6. // these methods use Timer2, as does NewPing's ping_timer method for using ultrasonic sensors. You
  7. // can't use ping_timer at the same time you're using timer_ms or timer_us as all use the same timer.
  8. // ---------------------------------------------------------------------------
  9. #include <NewPing.h>
  10. #define LED_PIN 13 // Pin with LED attached.
  11. void setup() {
  12. pinMode(LED_PIN, OUTPUT);
  13. NewPing::timer_ms(500, toggleLED); // Create a Timer2 interrupt that calls toggleLED in your sketch once every 500 milliseconds.
  14. }
  15. void loop() {
  16. // Do anything here, the Timer2 interrupt will take care of the flashing LED without your intervention.
  17. }
  18. void toggleLED() {
  19. digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // Toggle the LED.
  20. }