|
msp430g2533之iic(gpio模拟iic)
[复制链接]
#include
#include
#define SCL BIT6;
#define SDA BIT7;
#define uchar unsigned char
#define uint unsigned int
volatile int j;
void UART0_send_byte(unsigned char data)
{
for( j=10000;j>0;j--);
UCA0TXBUF=data;
}
void UART0_send_str(char *s)
{
while(*s != '\0')
{
UART0_send_byte(*s++);
}
}
void UART0()
{
DCOCTL = 0; // Select lowest DCOx and MODx settings
BCSCTL1 = CALBC1_1MHZ; // Set DCO
DCOCTL = CALDCO_1MHZ;
P1SEL |= BIT1 + BIT2 ; // P1.1 = RXD, P1.2=TXD
P1SEL2 |= BIT1 + BIT2 ; // P1.1 = RXD, P1.2=TXD
UCA0CTL1 |= UCSSEL_2; // SMCLK
UCA0BR0 = 104; // 1MHz 9600
UCA0BR1 = 0; // 1MHz 9600
UCA0MCTL = UCBRS0; // Modulation UCBRSx = 1
UCA0CTL1 &= ~UCSWRST; // **Initialize USCI state machine**
}
uchar R_word;
uchar ACK_Flag;
uchar read_buffer_iic[16] = {0};
uchar write_buffer_iic[16] = {0};
void delay(uint v)
{
while(v!=0)
v--;
}
void Start(void)
{
P1OUT &= ~SCL ;
P1OUT &= ~SDA ;
P1DIR &= ~SDA ;
P1DIR &= ~SCL ; delay(6);
P1DIR |= SDA ; delay(6);
P1DIR |= SCL ;
}
void Stop(void)
{
P1DIR |= SDA;
P1DIR &= ~SCL;
delay(6);
P1DIR &= ~SDA;
P1DIR |= SDA;
P1DIR |= SCL;
}
void Send_Byte(uchar Byte)
{
uint i;
for (i=0;i<8;i++)
{
if(Byte & 0x80)
{P1DIR &= ~SDA;}
else
{P1DIR |= SDA; }
P1DIR &= ~SCL ; delay(3) ;
Byte = Byte << 1;
P1DIR |= SCL ; delay(3) ;
}
}
void ACK(void)
{
P1DIR &= ~SDA;
P1DIR &= ~SCL;
ACK_Flag = 0;
delay(6);
if ((P1IN & BIT7))
ACK_Flag = 1;
P1DIR |= SCL;
delay(3);
}
void ACK_0(void)
{
P1DIR |= SCL;
P1DIR |= SDA;
delay(6);
P1DIR &= ~SCL;
P1DIR |= SCL;
delay(6);
}
void NOACK(void)
{
P1DIR &= ~SDA; delay(6);
P1DIR &= ~SCL; delay(6);
P1DIR |= SCL; delay(6);
P1DIR |= SDA;
}
void Receive_Byte(void)
{
uint j;
R_word = 0x00;
P1DIR &= ~SDA;
for(j=0;j<8;j++)
{
R_word = R_word << 1;
P1DIR &= ~SCL; delay(3);
if((P1IN & BIT7 ) == BIT7 )
R_word ++ ;
P1DIR |= SCL; delay(1);
}
}
void I2C_101_write(uchar W_addr,uchar dat)
{
Start();
delay(20);
Send_Byte(0x48); //write a byte :slave device
ACK();
Send_Byte(W_addr); // write a byte :e2prom address
ACK();
Send_Byte(dat);
ACK();
Stop();
delay(800);
}
void I2C_101_Read(uint R_addr,uchar n)
{
uchar i=0;
Start();
Send_Byte(0x90);
ACK();
Send_Byte(R_addr);
ACK();
Start();
Send_Byte(0x91);
ACK();
for(i=0;i
{
Receive_Byte();
ACK_0();
read_buffer_iic = R_word ;
}
Receive_Byte();
ACK_0(); //NOACK();
read_buffer_iic = R_word ;
Stop();
}
uint t;
void main(void)
{float t;
float tem;
char buf[10];
WDTCTL = WDTPW + WDTHOLD;
I2C_101_write(0x01,0x00) ;
UART0();
while(1)
{
I2C_101_Read(0,2) ;
t= read_buffer_iic[0]*100 + (uint)(read_buffer_iic[1]*0.0625*0.0625*100);
tem = t/100;
sprintf(buf," %8.4f\n",tem);
UART0_send_str(buf);
}
}
|
|