From: vl_garistov Date: Tue, 17 Nov 2020 22:52:30 +0000 (+0200) Subject: Added timer example with extrenal interrupt for enable/disable X-Git-Url: https://kolegite.com/gitweb/?a=commitdiff_plain;h=444416a69af93530f0af08a6f5c040f1b1fb8293;p=vmks.git Added timer example with extrenal interrupt for enable/disable --- diff --git a/Examples/Timer_1Hz_with_external_enable/Timer_1Hz with external enable.png b/Examples/Timer_1Hz_with_external_enable/Timer_1Hz with external enable.png new file mode 100644 index 0000000..fc72730 Binary files /dev/null and b/Examples/Timer_1Hz_with_external_enable/Timer_1Hz with external enable.png differ diff --git a/Examples/Timer_1Hz_with_external_enable/Timer_1Hz_with_external_enable.ino b/Examples/Timer_1Hz_with_external_enable/Timer_1Hz_with_external_enable.ino new file mode 100644 index 0000000..895f612 --- /dev/null +++ b/Examples/Timer_1Hz_with_external_enable/Timer_1Hz_with_external_enable.ino @@ -0,0 +1,60 @@ +#define BTN_PIN 2 + +void button_pressed_ISR(void); + +volatile uint8_t timer_en = 0; + +void setup() +{ + // Stop reception of interrupts + noInterrupts(); //cli(); + + pinMode(BTN_PIN, INPUT_PULLUP); + attachInterrupt(digitalPinToInterrupt(BTN_PIN), button_pressed_ISR, FALLING); + + // Set PB1 to be an output (Pin9 Arduino UNO) + DDRB |= (1 << PB1); + + // Clear Timer/Counter Control Registers + TCCR1A = 0; + TCCR1B = 0; + TIMSK1 = 0; + + // Set non-inverting mode - Table 15-3 (page 108) + TCCR1A |= (1 << COM1A1); + + // Set Fast-PWM Mode (Mode 14) - Table 15-5 (page 109) + TCCR1A |= (1 << WGM11); + TCCR1B |= (1 << WGM12); + TCCR1B |= (1 << WGM13); + + // Clear Timer 1 Counter + TCNT1 = 0; + + // Set PWM frequency/top value - Output PWM 10kHz + ICR1 = 15625; + OCR1A = 10000; + + // Enable interrupts + interrupts(); +} + +void loop() +{} + +void button_pressed_ISR(void) +{ + if (timer_en) + { + timer_en = 0; + // Disable the timer by selecting "none" as the clock source + TCCR1B &= ~((1 << CS11) | (1 << CS12) | (1 << CS10)); + } + else + { + timer_en = 1; + // Enable the timer + TCCR1B |= (1 << CS12) | (1 << CS10); + TCCR1B &= ~(1 << CS11); + } +}