原创
I2C总线读写程序(已通过protus仿真)
2009-5-12 16:32
2623
3
4
分类:
软件与OS
STA:SETB SDA ;开始子程序
SETB SCL ; first high
NOP ; for 12MHz crystal
NOP
NOP
NOP
CLR SDA ; then low
NOP
NOP
NOP
NOP
CLR SCL
RET
STP: CLR SDA ;停止子程序
SETB SCL ; first high
NOP ; for 12MHz crystal
NOP
NOP
NOP
SETB SDA ; then high
NOP
NOP
NOP
NOP
RET
CACK: SETB SDA ; 检查应答信号子程序
SETB SCL ; let data valid of SDA
CLR F0 ; set flag
MOV C, SDA
JC CEND
SETB F0 ; non ACK
CEND: CLR SCL ; pulse end
RET
MACK: CLR SDA ; 发送应答子程序
SETB SCL ; pulse
NOP ; for 12MHz crystal
NOP
NOP
NOP
CLR SCL ; pulse end
RET
NOACK: SETB SDA ; 发送非应答子程序
SETB SCL ; pulse
NOP ; for 12MHz crystal
NOP
NOP
NOP
CLR SCL ; pulse end
RET
W8BIT: MOV R5, #08H ; 8位写子程序
WLP: RLC A
MOV SDA, C
SETB SCL ; pulse
NOP ; for 12MHz crystal
NOP
NOP
NOP
CLR SCL ; pulse end
CLR SDA
DJNZ R5, WLP
RET
R8BIT: MOV R5, #08H ; 8位读子程序
SETB SDA
CLR A
RLP: SETB SCL ; let data valid of SDA
MOV C, SDA
RLC A
CLR SCL ; pulse end
DJNZ R5, RLP
MOV @R0, A ; keep data in (R0)
RET
WNBYT: LCALL STA ; 写i2c总线子程序
MOV A, SLAW ; device addressing
LCALL W8BIT ; write byte
LCALL CACK ; check ACK
JNB F0,RETWRN ; no ACK, repeat !!!
MOV A, R1 ; eeprom address R1=00H,24C02的00H
LCALL W8BIT ; write byte
LCALL CACK ; check ACK
JNB F0, RETWRN ; no ACK, repeat
WRDA: MOV A, @R0 ; ram address R0=36H,片内的ram的36h
LCALL W8BIT ; write byte
LCALL CACK ; check ACK
JNB F0, WNBYT ; no ACK, repeat !!!
INC R0 ; RAM + 1,(auto EEPROM+1)
DJNZ R3, WRDA
RETWRN:LCALL STP ; stop bus
RET
RNBYT: LCALL STA ; 读i2c总线子程序
MOV A, SLAW ; device addressing (write)
LCALL W8BIT ; write byte
LCALL CACK ; check ACK of slaver
JB F0, REND ; no ACK, repeat !!!
MOV A, R1 ; eeprom address
LCALL W8BIT ; write byte
LCALL CACK ; check ACK of slaver
JB F0, REND ; no ACK, repeat !!!
LCALL STA ; start bus again
MOV A, SLAR ; device addressing (read)
LCALL W8BIT ; write byte
LCALL CACK ; check ACK of slaver
JB F0, RNBYT ; no ACK, repeat !!!
MOV R0,#36H
RDDA: LCALL R8BIT ; read byte
DJNZ R3, CYC
LCALL NOACK ; send non ACK
LJMP REND
CYC: LCALL MACK ; send ACK of master
INC R0 ; RAM + 1, (auto EEPROM +1)
LJMP RDDA
REND: LCALL STP ; stop bus
RET
用户222665 2009-5-14 20:04