have been very curious about how the Arduino timer is working, recently checked the atmega328p chip data, has now been atmega328p Timer1 timer as a description, control output matching pin D9 output level.
The Arduino timer is available in normal mode, CTC mode, Fast PWM mode, and phase-adjustable PWM mode. This article uses the CTC mode, which is when the registerTCNT1 is equal to OCR1A/OCR1B (that is, match),oc1a/oc 1 Baccording to the value of com1x[1:0] The corresponding change (set, clear 0 or reverse). At the same time TCNT1 cleared,TCNT1 restarts the count from 0x00, and matches when the count result is equal to the value in the next OCR1A/OCR1B register. When a match occurs, the matching comparison flag ocf1x, or ocf1x=1, can be applied to match the comparison interrupt. This article uses the OC1A (Arduino Pro mini's D9 pin) pin as the output and compares the match-level inversion.
Arduino Timer Setup steps: 1 Set the timer initial value, determine the timing time, 2, set timer matching mode, 2, set the Prescaler mode, and timing time. Here is the relevant code.
1 /*******************************************************************************2 ***3 *project CODE: Timed Output *4 *create DATE:2014/11/27 *5 *created by:hgxh *6 *function: OC1A output pin level changes every 1s * after timing time7 *modify DATE:2014/11/27 *8 *document: *9 *others:cpu = 16MHZ *Ten ********************************************************************************* One **/ A voidSetup () { -DDRB = (1 << 1);//The oc1a is set to output mode and the OC1A pin is the PB1 pin, which is the Arduino Pro Moni D9 pin -Ocr1a =15624;//Timer Initial value period 0.5Hz Ocr1a = 16000000/(2*1024*0.5)-1 = 15624 theTccr1a = (0<<COM1A1) | (1<<COM1A0) | (0<<WGM11) | (0<<WGM10);//OC1A Output level alternating conversion, CTC mode -TCCR1B = (0<<WGM13) | (1<<WGM12) | (1<<CS12) | (0<<CS11) | (1<<CS10);//1024, Cs[12:10] determines the crossover mode is 1, 8, 64, 256, 1024 several - - } + voidLoop () - { + A if((TIFR1 &0x01) ==1)//ocf1a position 1 after output comparator a matches atOcr1a =15624;//Timer Initial value -}
The Arduino timer function