程序功能:将数据存入24c08,然后用led显示存入的数据
*/
#define uchar unsigned char
#define uint unsigned int
#define SCL_H P1OUT |= BIT2 //高低电平宏定义
#define SCL_L P1OUT &= ~BIT2
#define SDA_H P1OUT |= BIT3
#define SDA_L P1OUT &= ~BIT3
#define SCL_OUT P1DIR |= BIT2 //将P1.2口(SCL)设为输出状态
#define SDA_OUT P1DIR |= BIT3 //将P1.3口(SDA)设为输出状态
#define SDA_IN P1DIR &= ~BIT3 //将P1.3口设为输入状态,判断SDA高低电平
#define SDA_T (P1IN & BIT3) //用于数据线(SDA)的检测
void delay(uchar n) //短暂延时函数,用于电平延时
{
uchar i,j;
for(i=n;i>0;i--)
for(j=0;j<5;j++);
}
void io_init() //用于显示
{
P2DIR = 0XFF; //用于led显示
}
void iic_init() //iic总线初始化
{
SCL_OUT; //将P1.2口(SCL)设为输出状态
SDA_OUT;
delay(1);
SCL_H;
delay(1);
SDA_H;
delay(1);
}
void start()
{
SDA_OUT;
delay(1);
SCL_H;
delay(1);
SDA_H;
delay(1);
SDA_L;
delay(1);
}
void stop()
{
SDA_OUT;
delay(1);
SCL_H;
delay(1);
SDA_L;
delay(1);
SDA_H;
delay(1);
}
void respon() //可能有问题 ,简化了应答机制
{
uchar i=0;
SDA_IN; //输入,用于读数据
SCL_H; //高电平时
delay(1);
while((SDA_T==1)&&(i<252)) //等待应答,即SDA拉低0
{
i++;
}
}
void writebyte(uchar data) //从最高位开始传送
{
uchar i;
SDA_OUT;
for(i=0; i<8; i++)
{
SCL_L;
delay(1);
if((data&0x80)==0x80)
SDA_H;
else
SDA_L;
delay(1);
SCL_H;
delay(1);
data = data << 1; //data左移7次即可,第8次没给sda
}
}
uchar readbyte() //从最高位开始读
{
uchar i,temp=0;
SDA_IN; //输入,用于读数据
delay(1);
for(i=0; i<8; i++)
{
SCL_L; //允许数据变化
delay(1);
SCL_H; //停止数据变化
delay(1);
temp = (temp<<1)|SDA_T;
delay(1);
}
return temp;
}
void write_24c08(uchar add,uchar data)
{
start();
writebyte(0xa0); //单字节写入
respon();
writebyte(add);
respon();
writebyte(data);
respon();
stop();
}
uchar read_24c08(uchar add)
{
uchar data;
start();
writebyte(0xa0); //单字节写入
respon();
writebyte(add);
respon();
start();
writebyte(0xa1); //单字节读
respon();
data = readbyte();
stop();
return data;
}
void main(void)
{
uchar data; //用于存放读出的数据
WDTCTL = WDTPW + WDTHOLD;
io_init();
iic_init();
write_24c08(8,0x55); //随便写入一个数据
data = read_24c08(8);
P2OUT = data; //用led显示
while(1);
} |