132 lines
2.1 KiB
C
132 lines
2.1 KiB
C
/*
|
|
* iic.c
|
|
*
|
|
* Created on: Oct 24, 2021
|
|
* Author: wuwenfeng
|
|
*/
|
|
|
|
#include "iic.h"
|
|
#include "gpio.h"
|
|
#define iic_sda(x) HAL_GPIO_WritePin(iic_sda_GPIO_Port, iic_sda_Pin, x)
|
|
#define iic_scl(x) HAL_GPIO_WritePin(iic_scl_GPIO_Port, iic_scl_Pin, x)
|
|
#define read_iic_sda HAL_GPIO_ReadPin(iic_sda_GPIO_Port, iic_sda_Pin)
|
|
|
|
|
|
void iic_start()
|
|
{
|
|
iic_sda(1);
|
|
iic_scl(1);
|
|
iic_sda(0);
|
|
iic_scl(0);
|
|
}
|
|
|
|
void iic_stop()
|
|
{
|
|
iic_sda(0);
|
|
iic_scl(1);
|
|
iic_sda(1);
|
|
}
|
|
|
|
void iic_ack()
|
|
{
|
|
iic_scl(0);
|
|
iic_sda(0);
|
|
iic_scl(1);
|
|
iic_scl(0);
|
|
}
|
|
char iic_wait_ack()
|
|
{
|
|
int a=3000;
|
|
iic_scl(1);
|
|
iic_sda(1);
|
|
change_io_function(iic_sda_GPIO_Port, iic_sda_Pin,1);
|
|
// while(read_iic_sda)
|
|
// {
|
|
// a--;
|
|
// if(a==0)
|
|
// {
|
|
// iic_stop();
|
|
// return 1;
|
|
// }
|
|
// }
|
|
HAL_Delay(1);
|
|
change_io_function(iic_sda_GPIO_Port, iic_sda_Pin,0);
|
|
return 0;
|
|
}
|
|
|
|
void IIC_Write_Byte(unsigned char IIC_Byte)
|
|
{
|
|
iic_scl(0);
|
|
for(unsigned char i=0;i<8;i++)
|
|
{
|
|
if(IIC_Byte & 0x80)
|
|
{
|
|
iic_sda(1);
|
|
}else
|
|
{
|
|
iic_sda(0);
|
|
}
|
|
IIC_Byte<<=1;
|
|
iic_scl(1);
|
|
iic_scl(0);
|
|
}
|
|
}
|
|
|
|
unsigned char IIC_Read_Byte()
|
|
{
|
|
unsigned char k=0;
|
|
iic_scl(0);
|
|
iic_sda(1);
|
|
change_io_function(iic_sda_GPIO_Port, iic_sda_Pin,1);
|
|
for(unsigned char i=0; i<8; i++)
|
|
{
|
|
iic_scl(1);
|
|
k<<=1;
|
|
if(read_iic_sda==1)
|
|
{
|
|
k|=0x01;
|
|
}
|
|
|
|
iic_scl(0);
|
|
}
|
|
change_io_function(iic_sda_GPIO_Port, iic_sda_Pin,0);
|
|
return(k);
|
|
}
|
|
|
|
|
|
void IIC_SAND_DATE(unsigned char DEVICE_ADD,unsigned char IN_DEVICE_ADD,char *DATAS,uint16_t LONG)
|
|
{
|
|
iic_start();
|
|
IIC_Write_Byte(DEVICE_ADD);
|
|
if(iic_wait_ack()){return;}
|
|
IIC_Write_Byte(IN_DEVICE_ADD);
|
|
if(iic_wait_ack()){return;}
|
|
for(int a=0;a<LONG;a++)
|
|
{
|
|
IIC_Write_Byte(*DATAS);
|
|
DATAS++;
|
|
|
|
}
|
|
if(iic_wait_ack()){return;}
|
|
iic_stop();
|
|
}
|
|
|
|
void IIC_READ_DATE(unsigned char DEVICE_ADD,unsigned char IN_DEVICE_ADD,char *DATAS,uint16_t LONG)
|
|
{
|
|
iic_start();
|
|
IIC_Write_Byte(DEVICE_ADD);
|
|
if(iic_wait_ack()){return;}
|
|
IIC_Write_Byte(IN_DEVICE_ADD);
|
|
if(iic_wait_ack()){return;}
|
|
iic_start();
|
|
IIC_Write_Byte(DEVICE_ADD+1);
|
|
if(iic_wait_ack()){return;}
|
|
for(int a=0;a<LONG;a++)
|
|
{
|
|
*DATAS=IIC_Read_Byte();
|
|
DATAS++;
|
|
}
|
|
if(iic_wait_ack()){return;}
|
|
iic_stop();
|
|
}
|