Datasheet

Example 20-3. Assembly Code Example
(1)
TIM16_ReadTCNT1:
; Save global interrupt flag
in r18,SREG
; Disable interrupts
cli
; Read TCNT1 into r17:r16
in r16,TCNT1L
in r17,TCNT1H
; Restore global interrupt flag
out SREG,r18
ret
The assembly code example returns the TCNT1 value in the r17:r16 register pair.
Example 20-4. C Code Example
(1)
unsigned int TIM16_ReadTCNT1( void )
{
unsigned char sreg;
unsigned int i;
/* Save global interrupt flag */
sreg = SREG;
/* Disable interrupts */
_CLI();
/* Read TCNT1 into i */
i = TCNT1;
/* Restore global interrupt flag */
SREG = sreg;
return i;
}
Note: 
1. The example code assumes that the part specific header file is included. For I/O registers located in
extended I/O map, IN, OUT, SBIS, SBIC, CBI, and SBI instructions must be replaced with
instructions that allow access to extended I/O. Typically LDS and STS combined with SBRS, SBRC,
SBR, and CBR.
Atomic Write
The following code examples show how to do an atomic write of the TCNT1 register contents. Writing any
of the OCR1A/B or ICR1 registers can be done using the same principle.
Example 20-5. Assembly Code Example
(1)
TIM16_WriteTCNT1:
; Save global interrupt flag
in r18,SREG
; Disable interrupts
cli
; Set TCNT1 to r17:r16
out TCNT1H,r17
out TCNT1L,r16
; Restore global interrupt flag
out SREG,r18
ret
The assembly code example requires that the r17:r16 register pair contains the value to
be written to TCNT1.
Example 20-6. C Code Example
(1)
void TIM16_WriteTCNT1( unsigned int i )
{
ATmega48PA/88PA/168PA
16-bit Timer/Counter1 (TC1) with PWM
© 2018 Microchip Technology Inc.
Datasheet Complete
DS40002011A-page 165