#include "Tlt_fdc2214_iic.h"
#include "stm32l4xx_hal.h"
#include "main.h"

extern TIM_HandleTypeDef htim15;

void TFDC2214_SDA_IN()
{
    GPIO_InitTypeDef GPIO_InitStruct = {0};

    GPIO_InitStruct.Pin = GPIO_PIN_7;
//	GPIO_InitStruct.Pin = GPIO_PIN_11;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
}

void TFDC2214_SDA_OUT()
{
    GPIO_InitTypeDef GPIO_InitStruct = {0};

    GPIO_InitStruct.Pin = GPIO_PIN_7;
//	GPIO_InitStruct.Pin = GPIO_PIN_11;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_OD;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
}

void Tdelay_us(uint32_t us)
{
	uint16_t start = __HAL_TIM_GET_COUNTER(&htim15);
  while((__HAL_TIM_GET_COUNTER(&htim15) - start) < us);
}

void TFDC2214_IIC_Start(void)
{
    TFDC2214_SDA_OUT();
    TSDA_HIGH();
    TSCL_HIGH();
    Tdelay_us(2);
    TSDA_LOW();
    Tdelay_us(2);
    TSCL_LOW();
    Tdelay_us(2);
}


void TFDC2214_IIC_Stop(void)
{
    TFDC2214_SDA_OUT();
    TSCL_LOW();
    Tdelay_us(2);
    TSDA_LOW();
    Tdelay_us(2);
    TSCL_HIGH();
    Tdelay_us(2);
    TSDA_HIGH();
    Tdelay_us(2);
}

uint8_t TFDC2214_IIC_Wait_Ack(void)
{
    uint8_t waitTime=0;
    TFDC2214_SDA_IN();
    TSDA_HIGH();
    Tdelay_us(2);
    TSCL_HIGH();
    Tdelay_us(2);
    while(TFDC2214_IIC_SDA_IN)
    {
        waitTime++;
        if(waitTime>250)
        {
            TFDC2214_IIC_Stop();
            return 1;
        }
    }
    TSCL_LOW();
    return 0;
}

void TFDC2214_IIC_Ack(void)
{
    TSCL_LOW();
    Tdelay_us(2);
    TFDC2214_SDA_OUT();
    TSDA_LOW();//发送0是ACK
    Tdelay_us(2);
    TSCL_HIGH();
    Tdelay_us(2);
    TSCL_LOW();
    Tdelay_us(2);
}

void TFDC2214_IIC_NAck(void)
{
    TSCL_LOW();
    Tdelay_us(2);
    TFDC2214_SDA_OUT();
    TSDA_HIGH();//发送1是nACK
    Tdelay_us(2);
    TSCL_HIGH();
    Tdelay_us(2);
    TSCL_LOW();
    Tdelay_us(2);
}

void TFDC2214_IIC_Send_Byte(uint8_t dat)
{
    uint8_t t;
    TFDC2214_SDA_OUT();
    TSCL_LOW();
    for(t=0; t<8; t++)
    {

        Tdelay_us(2);
        if(dat & 0x80)
            TSDA_HIGH();
        else
            TSDA_LOW();
        dat<<=1;
        TSCL_HIGH();
        Tdelay_us(2);
        TSCL_LOW();
        Tdelay_us(2);
    }
    //SCL_LOW();
}

uint8_t TFDC2214_IIC_Read_Byte(uint8_t ack)
{
    uint8_t i,receive=0;
    TSDA_HIGH();
    TFDC2214_SDA_IN();
    for(i=0; i<8; i++ )
    {
        receive<<=1;

        TSCL_LOW();
        Tdelay_us(2);
        TSCL_HIGH();
        Tdelay_us(2);
        if(TFDC2214_IIC_SDA_IN)receive++;//最低位置1
    }
    TSCL_LOW();
    if (!ack)
        TFDC2214_IIC_NAck();
    else
        TFDC2214_IIC_Ack();
    return receive;
}





