#include "Type.h"
#include "IIC.h"
#include "Delay.h"
void I2C_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructer;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructer.GPIO_Pin=GPIO_Pin_2 | GPIO_Pin_3; //6--SCL 7--SDA
GPIO_InitStructer.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructer.GPIO_Mode=GPIO_Mode_Out_PP; GPIO_Init(GPIOA, &GPIO_InitStructer);
}
void SDA_OUT(void)
{
GPIO_InitTypeDef GPIO_InitStructer;
GPIO_InitStructer.GPIO_Pin= GPIO_Pin_2;
GPIO_InitStructer.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructer.GPIO_Mode=GPIO_Mode_Out_PP;
GPIO_Init(GPIOA, &GPIO_InitStructer);
}
void SDA_IN(void)
{
GPIO_InitTypeDef GPIO_InitStructer;
GPIO_InitStructer.GPIO_Pin= GPIO_Pin_2;
GPIO_InitStructer.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructer.GPIO_Mode=GPIO_Mode_IPU;
GPIO_Init(GPIOA, &GPIO_InitStructer);
}
void SDA_Set()
{
GPIOA->ODR |= GPIO_Pin_2;
}
void SDA_Reset()
{
GPIOA->ODR &= (u16)(~GPIO_Pin_2);
}
uint8 SDA_Get()
{
if(GPIOA->IDR&GPIO_Pin_2)
return 0x01;
else
return 0x00;
}
void SCL_Set()
{
GPIOA->ODR |= GPIO_Pin_3;
}
void SCL_Reset()
{
GPIOA->ODR &= (u16)(~GPIO_Pin_3);
}
void I2C_Start(void)
{
SDA_OUT();
SDA_Set();//SDA H
Delay_us();
SCL_Set();//SCL H
Delay_us();
SDA_Reset();//SDA L
Delay_us();
SCL_Reset();//SCL L
Delay_us();
} void I2C_Stop(void)
{
SDA_OUT();
SDA_Reset();//SDA L
Delay_us();
SCL_Set();//SCL H
Delay_us();
SDA_Set();//SDA H
Delay_us();
}
u8 I2C_Wait_Ask(void)
{
int count=;
SDA_IN();
SCL_Set();
Delay_us();
while(SDA_Get())
{
count++;
if(count>)
{
I2C_Stop();
return ;
}
Delay_us();
}
SCL_Reset();
Delay_us();
return ;
}
void I2C_WriteByte(u8 data)
{
u8 i;
SDA_OUT();
for(i=;i<;i++)
{
if(data & 0x80) //MSB,???????????
SDA_Set();
else
SDA_Reset();
Delay_us();
SCL_Set();
Delay_us();
SCL_Reset();
Delay_us();
data<<=;
}
}
u8 I2C_ReadByte(void)
{
u8 data,i;
data = ;
SDA_IN();
for(i=;i<;i++)
{
data<<=;
SCL_Set();
Delay_us();
if(SDA_Get())
data|=0x01;
SCL_Reset();
Delay_us();
}
return data;
}
#define WD_DEVICE_ADDR 0xA6 //ALT ½ÓµØΪA6 ½ÓµçԴΪ3A
#define RD_DEVICE_ADDR 0xA7 //?????IIC???????,??ALT ADDRESS????????
void I2C_WriteData(uint8 addr, uint8 data)
{
I2C_Start();
I2C_WriteByte(WD_DEVICE_ADDR);//OLED??
if(I2C_Wait_Ask()==)
return ;
I2C_WriteByte(addr);//?????
if(I2C_Wait_Ask()==)
return ;
I2C_WriteByte(data);
I2C_Wait_Ask();
I2C_Stop();
}
uint8 I2C_ReadData(uint8 addr)
{
uint8 temp;
I2C_Start();
I2C_WriteByte(WD_DEVICE_ADDR);//OLED??
if(I2C_Wait_Ask()==)
return ;
I2C_WriteByte(addr);//?????
if(I2C_Wait_Ask()==)
return ; I2C_Start();
I2C_WriteByte(RD_DEVICE_ADDR);//OLED??
if(I2C_Wait_Ask()==)
return ;
temp = I2C_ReadByte();//?????
I2C_Stop();
return temp;
}
#ifndef __IIC_H__
#define __IIC_H__
#include "Type.h"
#include "stm32f10x.h" void I2C_Init(void);
void I2C_WriteData(uint8 addr, uint8 data);
uint8 I2C_ReadData(uint8 addr); #endif