PIC单片机应用专题三:I2C读写24C02
扫描二维码
随时随地手机看文章
自从开始学习单片机起,就觉得I2C是个很有用的东西,它能大大节省我们的端口,现把软件模拟的I2C程序写出来,既是给大家分享,也是为自己做一下备份.下面的程序是用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
;**********************发送一个字节**************************
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
;************************接收一个字节*****************************
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
;**********************发送********************************
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