ATmega48PA/88PA/168PA/328P
Assembly Code Example
C Example
Comments
ldi r16,
(1<<TWINT)|(1<<TWSTA)|
TWCR = (1<<TWINT)|(1<<TWSTA)|
(1<<TWEN)
1
2
Send START condition
(1<<TWEN)
out TWCR, r16
wait1:
while (!(TWCR & (1<<TWINT)))
Wait for TWINT Flag set. This
indicates that the START
condition has been transmitted
in
r16,TWCR
;
sbrs r16,TWINT
rjmp wait1
in
r16,TWSR
if ((TWSR & 0xF8) != START)
Check value of TWI Status
Register. Mask prescaler bits. If
status different from START go to
ERROR
andi r16, 0xF8
cpi r16, START
brne ERROR
ERROR();
3
4
5
ldi r16, SLA_W
out TWDR, r16
TWDR = SLA_W;
Load SLA_W into TWDR
Register. Clear TWINT bit in
TWCR to start transmission of
address
TWCR = (1<<TWINT) |
(1<<TWEN);
ldi r16, (1<<TWINT) |
(1<<TWEN)
out TWCR, r16
wait2:
while (!(TWCR & (1<<TWINT)))
Wait for TWINT Flag set. This
indicates that the SLA+W has
been transmitted, and
in
r16,TWCR
;
sbrs r16,TWINT
rjmp wait2
ACK/NACK has been received.
in
r16,TWSR
if ((TWSR & 0xF8) !=
MT_SLA_ACK)
Check value of TWI Status
Register. Mask prescaler bits. If
status different from
andi r16, 0xF8
cpi r16, MT_SLA_ACK
brne ERROR
ERROR();
MT_SLA_ACK go to ERROR
ldi r16, DATA
out TWDR, r16
TWDR = DATA;
TWCR = (1<<TWINT) |
(1<<TWEN);
Load DATA into TWDR Register.
Clear TWINT bit in TWCR to
start transmission of data
ldi r16, (1<<TWINT) |
(1<<TWEN)
out TWCR, r16
wait3:
while (!(TWCR & (1<<TWINT)))
Wait for TWINT Flag set. This
indicates that the DATA has been
transmitted, and ACK/NACK has
been received.
in
r16,TWCR
;
6
7
sbrs r16,TWINT
rjmp wait3
in
r16,TWSR
if ((TWSR & 0xF8) !=
MT_DATA_ACK)
Check value of TWI Status
Register. Mask prescaler bits. If
status different from
andi r16, 0xF8
cpi r16, MT_DATA_ACK
brne ERROR
ERROR();
MT_DATA_ACK go to ERROR
ldi r16,
(1<<TWINT)|(1<<TWEN)|
TWCR = (1<<TWINT)|(1<<TWEN)|
(1<<TWSTO);
Transmit STOP condition
(1<<TWSTO)
out TWCR, r16
226
8161D–AVR–10/09