#include <MSP430G2553.h>
#define SDA_1 P1OUT |= BIT7
#define SDA_0 P1OUT &=~ BIT7
#define SCL_1 P1OUT |= BIT6
#define SCL_0 P1OUT &=~ BIT6
#define SDA_out P1OUT |= BIT7
#define SDA_in P1OUT &=~ BIT7
unsigned char Readword[12];
void init_clk(void)
{
unsigned char j;
do
{
IFG1 &=~ OFIFG;
for( j=10 ; j>0 ; j--)
{
_NOP();
}
}
while((IFG1&OFIFG)!=0);
P1DIR |= BIT6+BIT7;
P3DIR |= BIT5;
P3OUT &=~ BIT5;
}
void Delay(void) //Delay
{
unsigned char t;
for(t=0;t<15;t++)
_NOP();
}
void Long_Delay(void) //Delay
{
unsigned char t;
for(t=0;t<200;t++)
_NOP();
}
void Start(void) //Start
{
SDA_out;
SCL_1;
_NOP();
SDA_1;
Delay();
SDA_0;
Delay();
SCL_0;
Delay();
}
void Stop(void) //Stop
{
SDA_0;
Delay();
SCL_1;
Delay();
SDA_1;
Delay();
}
void ACK(void) //ACK
{
SDA_0;
SCL_0;
Delay();
SCL_1;
Delay();
SCL_0;
Delay();
SDA_1;
Delay();
}
void NACK(void) // NOT ACK
{
SDA_1;
Delay();
SCL_1;
Delay();
SCL_0;
Delay();
SDA_0;
Delay();
}
void Write1(void) //Write a bit : 1
{
SDA_1;
Delay();
SCL_1;
Delay();
SCL_0;
Delay();
}
void Write0(void) //Write a bit : 0
{
SDA_0;
Delay();
SCL_1;
Delay();
SCL_0;
Delay();
}
void Writebyte(unsigned char Wchar) //写一个字Wchar
{
unsigned char i;
for(i=0;i<8;i++)
{
if(Wchar&0x80) Write1();
else Write0();
Wchar<<=1;
}
SDA_1;
Delay();
}
unsigned char CheckACK(void) //receive ACK
{
unsigned char flag;
//SDA_1;
Delay();
SCL_1;
Delay();
SDA_in;
_NOP();_NOP();
flag = P1IN&BIT7 ; //read SDA
SCL_0;
Delay();
SDA_out;
if(flag) return 0;
else return 1;
}
unsigned char Readbyte(void)
{
unsigned char rchar=0 ,i,flag;
SCL_0;
Delay();
for(i=0;i<8;i++)
{
SDA_in;
Delay();
SCL_1;
Delay();
flag=P1IN&BIT7;
rchar<<=1;
if(flag) rchar |= 0x01;
_NOP();
// SDA_out;
// Delay();
SCL_0;
Delay();
}
SCL_0;
Delay();
return rchar;
}
void WriteNbyte(unsigned char address,unsigned char dataaddr,unsigned char *buff,unsigned char n)
{
unsigned char i;
Start();
Writebyte(address); //find eeprom
if(!CheckACK())
{Stop();return ;}
Writebyte(dataaddr); //find unit address
if(!CheckACK())
{Stop();return ;}
for(i=0;i<n;i++)
{
Writebyte(buff);
if(!CheckACK())
{Stop();return ;}
}
Stop();
Delay();
}
void ReadNbyte(unsigned char address,unsigned char dataaddr,unsigned int n)
{
unsigned char i;
Start();
Writebyte(address); //find eeprom
if(!CheckACK())
{Stop();return ;}
Writebyte(dataaddr); //find unit address
if(!CheckACK())
{Stop();return ;}
Start();
Writebyte(0xaf); //read
if(!CheckACK())
{Stop();return ;}
for(i=0;i<n;i++)
{
Readword=Readbyte();
ACK();
}
Stop();
Delay();
}
void main(void)
{
unsigned char write[9],i;
for(i=0; i<8; i++){
write =49+i;
}
WDTCTL = WDTPW + WDTHOLD;
init_clk();
// P1SEL = 0xc0; P1.6,7= SCL&SDA
while(1)
{
//write
WriteNbyte(0xae,0x00,write,2);
Long_Delay();
//read
ReadNbyte(0xae,0x00,2);
Long_Delay();
Long_Delay();
}
}
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
一周热门 更多>