When reading back a software assigned pin value, a nop instruction must be inserted as indicated in Figure 9-4. The out
instruction sets the “SYNC LATCH” signal at the positive edge of the clock. In this case, the delay tpd through the
synchronizer is 1 system clock period.
Figure 9-4. Synchronization when Reading a Software Assigned Pin Value
SYSTEM CLK
r16
INSTRUCTIONS
SYNC LATCH
PINxn
0xFF
out PORTx, r16
nop
in r17, PINx
r17
0x00
0xFF
tpd
The following code example shows how to set port B pins 0 and 1 high, 2 and 3 low, and define the port pins from 4 to 7 as
input with pull-ups assigned to port pins 6 and 7. The resulting pin values are read back again, but as previously discussed,
a nop instruction is included to be able to read back the value recently assigned to some of the pins.
Assembly Code Example(1)
...
; Define pull-ups and set outputs high
; Define directions for port pins
ldi
ldi
out
out
r16, (1<<PB7)|(1<<PB6)|(1<<PB1)|(1<<PB0)
r17, (1<<DDB3)|(1<<DDB2)|(1<<DDB1)|(1<<DDB0)
PORTB, r16
DDRB, r17
; Insert nop for synchronization
nop
; Read port pins
in
r16, PINB
...
C Code Example
unsigned char i;
...
/* Define pull-ups and set outputs high */
/* Define directions for port pins */
PORTB = (1<<PB7)|(1<<PB6)|(1<<PB1)|(1<<PB0);
DDRB = (1<<DDB3)|(1<<DDB2)|(1<<DDB1)|(1<<DDB0);
/* Insert nop for synchronization*/
_NOP();
/* Read port pins */
i = PINB;
...
Note:
1. For the assembly program, two temporary registers are used to minimize the time from pull-ups are set on pins
0, 1, 6, and 7, until the direction bits are correctly set, defining bit 2 and 3 as low and redefining bits 0 and 1 as
strong high drivers.
54
ATmega16/32/64/M1/C1 [DATASHEET]
7647O–AVR–01/15