|
我使用的是msp430f169。在SCL和SDA上加10K上拉电阻。
A2=A1=A0=0;
SCL = BIT4;
SDA = SDA;
本程序已经条是通过了。多谢在此过程中指教的各位。
#include "msp430x16x.h"
unsigned int adjg;
unsigned char ack,ctlbyte;
void ysh(unsigned long x)
{
while(x>0){x--;}
}
//写一个字节
void writebyte(unsigned char x)
{
unsigned char i;
for(i = 8;i>0;i--)//写字节
{
if(x>127)
{
DATAO |=BIT3;
ysh(50);
}
else
{
DATAO &=~BIT3;
ysh(50);
}
DATAO |=BIT4;
ysh(50);
DATAO &=~BIT4;
ysh(50);
x = x<<1;
}
DATAO &=~BIT3; //反馈
ysh(50);
DATAO |=BIT4;
ysh(50);
DATAO &=~BIT4;
ysh(50);
}
//读一个字节
uigned char readbyte(void)
{
unsigned char hc,i,x;
x = 0;
for(i = 7;i>0;i--) //读字节
{
x = x<<1;
DATAO |=BIT4;
ysh(50);
DATAO &=~BIT4;
ysh(50);
hc = DATAI;
hc = hc&0x08;
if(hc>0)
{
x = x|0x0001;
ysh(50);
}
}
P3DIR =0X1F;
ysh(50);
DATAO &=~BIT3; //反馈
ysh(50);
DATAO |=BIT4;
ysh(50);
DATAO &=~BIT4;
ysh(50);
return x;
}
//24c01地址写数据
void at24c01chshh(unsigned char add,unsigned char data)
{
unsigned char hc;
P3DIR = 0x1f;
ysh(50);
DATAO |= BIT3; //开始位
ysh(50);
DATAO |= BIT4;
ysh(50);
DATAO &=~BIT3;
ysh(50);
DATAO &=~BIT4;
ysh(50);
hc = 0xa0; //芯片地址发送
writebyte(hc);
_NOP();
hc = add; //存储地址发送
writebyte(hc);
_NOP();
hc = data; //数据发送
writebyte(hc);
_NOP();
DATAO |=BIT4; //停止位
ysh(50);
DATAO |=BIT3;
}
//从24c01任意地址读数据
unsigned int readat24c01(unsigned char add)
{
unsigned char x,hc;
P3DIR = 0x1f;
ysh(50);
DATAO |= BIT3; //开始位
ysh(50);
DATAO |= BIT4;
ysh(50);
DATAO &=~BIT3;
ysh(50);
DATAO &=~BIT4;
ysh(50);
hc = 0xa0; //芯片地质
writebyte(hc);
_NOP();
hc = add; //存储地址
writebyte(hc);
_NOP();
DATAO |= BIT3; //开始位
ysh(50);
DATAO |= BIT4;
ysh(50);
DATAO &=~BIT3;
ysh(50);
DATAO &=~BIT4;
ysh(50);
hc = 0xa1; //读命令
writebyte(hc);
_NOP();
P3DIR = 0X17;
ysh(50);
x = 0; //接收数据
x = readbyte();
_NOP();
DATAO |=BIT4; //停止位
ysh(50);
DATAO |=BIT3;
ysh(50);
return(x);
}
void main(void)
{
WDTCTL = WDTPW + WDTHOLD;
DCOCTL = 0X73;
BCSCTL1= 0X87; // 设置时钟频率4.00MHz
P3DIR = 0x0A;
while(1)
{
at24c01chshh(0x10,88); //在10h写数据88;
ysh(1000);
adjg = readat24c01(0x10); //读10h数据
_NOP();
}
}
|
|