P4.7---SDA
P4.6---SCL
#include "msp430x44x.h"
#define SCL 0X40;
#define SDA 0X80;
#define Ram_addr 0x250;
int R_word;
int Ack_Flag;
void Delay(int m)
{
while(m-- > 0);
}
void Start(void)
{
P4OUT = 0;
P4DIR &= ~SCL;
P4DIR &= ~SDA;//SET HIGH LEVEL
P4DIR |= SDA;
P4DIR |= SCL;
}
void Stop(void)
{
P4DIR |= SDA;
P4DIR &= ~SCL;
P4DIR &= ~SDA;
P4DIR |= SCL;
}
void Send_Byte(char Byte)
{
int i;
for (i=0;i<8;i++)
{
if(Byte & 0x80)
{
P4DIR &= ~SDA;
}
else
{
P4DIR |= SDA;
}
P4DIR &= ~SCL;
Delay(50);
P4DIR |= SCL;
Byte = Byte << 1;
}
}
void Ack(void)
{
P4DIR &= ~SDA;
P4DIR &= ~SCL;
Ack_Flag = 0;
Delay(10);
if ((P4IN & 0x80))
{
Ack_Flag = 1;
}
P4DIR |= SCL;
Delay(10);
}
void NOAck(void)
{
P4DIR &= ~SDA;
Delay(10);
P4DIR &= ~SCL;
Delay(10);
P4DIR |= SCL;
Delay(10);
P4DIR |= SDA;
}
void Receive_Byte(void)
{
int j;
R_word = 0x00;
P4DIR &= ~SDA;
for(j=0;j<8;j++)
{
P4DIR &= ~SCL;
if(P4IN & 0x80)
{
R_word |= 0x01;
}
else
{
R_word &= 0xFE;
}
//Delay(50);
P4DIR |= SCL;
R_word = R_word << 1;
}
R_word = R_word >>1;
}
void I2C_Write(int W_addr,int word)
{
while (1)
{
Start();
Delay(20);
Send_Byte(0xA0);//write a byte :slave device
Ack();
if (Ack_Flag)
continue;
Send_Byte(W_addr);// write a byte :e2prom address
Ack();
if(Ack_Flag)
continue;
Send_Byte(word);
Ack();
if(!(Ack_Flag))
break;
}
Stop();
}
void I2C_Random_Read(int R_addr)
{
int *paddr;
paddr = (int*)Ram_addr;
while(1)
{
Start();
Send_Byte(0xA0);
Ack();
if(Ack_Flag)
continue;
Send_Byte(R_addr);
Ack();
if(Ack_Flag)
continue;
Start();
Send_Byte(0xA1);
Ack();
if(!Ack_Flag)
break;
}
Receive_Byte();
*paddr = R_word;
NOAck();
Stop();
}
void main(void)
{
P4DIR = 0XFF;
WDTCTL = WDTHOLD+WDTPW;
while(1)
{
I2C_Write(0x2A,0x10);
Delay(500);
I2C_Random_Read(0x2A);
}
} |