PIC單片機應(yīng)用專題三:I2C讀寫24C02
自從開始學(xué)習(xí)單片機起,就覺得I2C是個很有用的東西,它能大大節(jié)省我們的端口,現(xiàn)把軟件模擬的I2C程序?qū)懗鰜?既是給大家分享,也是為自己做一下備份.下面的程序是用I2C存儲24C02:
INCLUDE
;*************************定義變量************************
STATUS EQU 3H
PORTBEQU 6H
PORTCEQU 7H
EEPROM EQU 08H
ADDR EQU 09H
BUFINEQU 0AH
BUFOUT EQU 0BH
SLAVEEQU 0CH
TXBUFEQU 0DH
BIT EQU 0EH
DLY1 EQU 0FH
DLY2 EQU 10H
DI EQU 7
DO EQU 6
SDAEQU 7
SCLEQU 6
ACKF EQU 0
;**********************程序開始***************************
ORG7FFH
GOTO MAIN
ORG000H
;**********************啟動信號***************************************
BSTART
BSFPORTB,SDA
BSFPORTB,SCL
MOVLWB'00111111'
TRIS PORTB
NOP
NOP
NOP
NOP
NOP
NOP
BCFPORTB,SDA
NOP
NOP
NOP
NOP
NOP
BCFPORTB,SCL
NOP
NOP
RETLW0
;***********************停止信號********************************
BSTOP
BCFPORTB,SDA
MOVLWB'00111111'
TRIS PORTB
BCFPORTB,SDA
NOP
NOP
NOP
BSFPORTB,SCL
NOP
NOP
NOP
BSFPORTB,SDA
NOP
NOP
BCFPORTB,SCL
NOP
NOP
RETLW0
;**********************發(fā)送一個字節(jié)**************************
TX
MOVLWD'8'
MOVWFBIT
TXLP BCFEEPROM,DO
BTFSCTXBUF,7
BSFEEPROM,DO
CALL BITOUT
RLFTXBUF
DECFSZ BIT
GOTO TXLP
CALL BITIN
BTFSCEEPROM,DI
BSFPORTC,ACKF
RETLW0
;************************接收一個字節(jié)*****************************
RX
CLRF BUFIN
MOVLWD'8'
MOVWFBIT
BCFSTATUS,0
RXLP RLFBUFIN
BCFBUFIN,0
CALL BITIN
BTFSCEEPROM,DI
BSFBUFIN,0
DECFSZ BIT
GOTO RXLP
BSFEEPROM,DO
CALL BITOUT
RETLW0
;**********************發(fā)送********************************
BITOUT
MOVLW B'00111111'
trisPORTB
BTFSS EEPROM,DO
GOTOBITLOW
BSF PORTB,SDA
GOTOCLKOUT
BITLOW BCF PORTB,SDA
CLKOUT BSF PORTB,SCL
NOP
NOP
NOP
NOP
BCF PORTB,SCL
RETLW 0
;**********************接收****************************
BITIN
BSF EEPROM,DI
MOVLW B'10111111'
TRISPORTB
BSF PORTB,SCL
NOP
NOP
NOP
NOP
NOP
BTFSS PORTB,SDA
BCF EEPROM,DI
BCF PORTB,SCL
RETLW 0
;***********************主程序**********************
MAIN
MOVLWB'00000000'
TRIS PORTC
CLRF PORTC
WRITE ;寫存儲器
CLRF PORTC
MOVLWB'10100000'
MOVWFSLAVE
MOVLWB'10101010'
MOVWFBUFOUT
CLRF ADDR
LOOP0CALL BSTART
MOVF SLAVE,0
MOVWFTXBUF
CALL TX
MOVF ADDR,0
MOVWFTXBUF
CALL TX
MOVF BUFOUT,0
MOVWFTXBUF
CALL TX
CALL BSTOP
DELAY10MS
MOVLWD'13'
MOVLWDLY1
MOVLW0FFH
MOVWFDLY2
LP0DECFSZ DLY2
GOTO $-1
DECFSZ DLY1
GOTO $-5
READ ;讀存儲器
CLRF PORTC
MOVLWB'10100000'
MOVWFSLAVE
CLRF ADDR
LOOP1CALL BSTART
MOVF SLAVE,0
MOVWFTXBUF
CALL TX
MOVF ADDR,0
MOVWFTXBUF
CALL TX
CALL BSTART
MOVLWB'10100001'
MOVWFTXBUF
CALL TX
CALL RX
CALL BSTOP
NOP
NOP
NOP
NOP
NOP
NOP
MOVF BUFIN,0
MOVWFPORTC
LOOP2NOP
GOTO $-1
;************************
END