本帖最后由 一路向北lm 于 2018-1-29 17:05 编辑
1.AT24C02 iic
#include <stc15f2k60s2.h>
#include "intrins.h"
sbit scl = P2^0;
sbit sda = P2^1;
void Snop() //@11.0592MHz
{
unsigned char i;
_nop_();
i = 11;
while (--i);
}
void i2c_start(void)
{
sda = 1;
scl = 1;
Snop();
sda = 0;
Snop();
scl = 0;
}
void i2c_stop(void)
{
sda = 0;
scl = 1;
Snop();
sda = 1;
Snop();
}
void i2c_sendbyte(unsigned char byt)
{
unsigned char i;
//
EA = 0;
for(i=0; i<8; i++){
scl = 0;
Snop();
if(byt & 0x80){
sda = 1;
}
else{
sda = 0;
}
Snop();
scl = 1;
byt <<= 1;
Snop();
}
EA = 1;
//
scl = 0;
}
unsigned char i2c_waitack(void)
{
unsigned char ackbit;
scl = 1;
Snop();
ackbit = sda; //while(sda); //wait ack
scl = 0;
Snop();
return ackbit;
}
unsigned char i2c_receivebyte(void)
{
unsigned char da;
unsigned char i;
//
EA = 0;
for(i=0;i<8;i++){
scl = 1;
Snop();
da <<= 1;
if(sda)
da |= 0x01;
scl = 0;
Snop();
}
EA = 1;
//
return da;
}
void i2c_sendack(unsigned char ackbit)
{
scl = 0;
sda = ackbit; //0:发送应答信号;1:发送非应答信号
scl = 1;
Snop();
scl = 0;
Snop();
}
void delay1ms(unsigned char t)
{
unsigned char i;
while(t--){
for(i=0; i<112; i++);
}
}
void iic_write(unsigned char add,unsigned char dat)
{
i2c_start();
i2c_sendbyte(0xa0);
i2c_waitack();
i2c_sendbyte(add);
i2c_waitack();
i2c_sendbyte(dat);
i2c_waitack();
i2c_stop();
delay1ms(30);
}
unsigned char iic_read(unsigned char add)
{
unsigned char da;
i2c_start();
i2c_sendbyte(0xa0);
i2c_waitack();
i2c_sendbyte(add);
i2c_waitack();
i2c_start();
i2c_sendbyte(0xa1);
i2c_waitack();
da = i2c_receivebyte();
i2c_sendack(1);
i2c_stop();
return da;
}
#ifndef _I2C_H_
#define _I2C_H_
void delay1ms(unsigned char t);
void iic_write(unsigned char add,unsigned char dat);
unsigned char iic_read(unsigned char add);
#endif
|