#include "main.h"
void I2C_Start(void);
void I2C_Stop(void);
void I2C_ACK(u8 ack);
u8 I2C_Send_Byte(u8 send_data);
u8 I2C_Receive_Byte(void);
//16Mhz 的时钟
void Calendar_Init(void)
{
SCL_OUT();
SDA_OUT();
}
void Calendar_Write(u8 addr, u8 calendar_data)
{
I2C_Start();
I2C_Send_Byte(0xa0);
I2C_Send_Byte(addr);
I2C_Send_Byte(calendar_data);
I2C_Stop();
}
u8 Calendar_Read(u8 addr)
{
u8 r_data;
I2C_Start();
I2C_Send_Byte(0xa0);
I2C_Send_Byte(addr);
I2C_Start();
I2C_Send_Byte(0xa1);
r_data = I2C_Receive_Byte();
I2C_ACK(1);
I2C_Stop();
return r_data;
}
void I2C_Start(void)
{
GPIOC->ODR |= 0x40; //SDA=1
GPIOD->ODR |= 0x08; //SCL=1
Delay_us(5);
GPIOC->ODR &= ~0x40; //SDA=0
Delay_us(5);
GPIOD->ODR &= ~0x08; //SCL=0
}
void I2C_Stop(void)
{
GPIOC->ODR &= ~0x40; //SDA=0
GPIOD->ODR |= 0x08; //SCL=1
Delay_us(5);
GPIOC->ODR |= 0x40; //SDA=1
Delay_us(5);
}
void I2C_ACK(u8 ack)
{
if(ack)
GPIOC->ODR |= 0x40; //SDA=1
else
GPIOC->ODR &= ~0x40; //SDA=0
GPIOD->ODR |= 0x08; //SCL=1
Delay_us(5);
GPIOD->ODR &= ~0x08; //SCL=0
Delay_us(5);
}
u8 I2C_Send_Byte(u8 send_data)
{
u8 i,ack;
for(i=0;i<8;i++)
{
GPIOD->ODR &= ~0x08; //SCL=0
Delay_us(5);
if(send_data & 0x80)
GPIOC->ODR |= 0x40; //SDA=1
else
GPIOC->ODR &= ~0x40; //SDA=0
send_data <<=1;
GPIOD->ODR |= 0x08; //SCL=1
Delay_us(5);
}
GPIOD->ODR &= ~0x08; //SCL=0
Delay_us(5);
SDA_IN();
GPIOD->ODR |= 0x08; //SCL=1
Delay_us(1);
ack = (GPIOC->IDR & 0x40)>>6;
Delay_us(5);
GPIOD->ODR &= ~0x08; //SCL=0
SDA_OUT();
Delay_us(5);
return ack;
}
u8 I2C_Receive_Byte(void)
{
u8 i,received_data;
SDA_IN();
for(i=0;i<8;i++)
{
received_data <<=1;
GPIOD->ODR |= 0x08; //SCL=1
nop();
nop();
if(GPIOC->IDR & 0x40)
received_data |= 1;
Delay_us(5);
GPIOD->ODR &= ~0x08; //SCL=0
Delay_us(5);
}
SDA_OUT();
return received_data;
}
|