#include "TCA9539.h"
#include "Simulated_IIC_2_Master.h"

/*发送*/
void TCA9539_IIC_Send(uint8_t Address, uint8_t Register, uint8_t Function)
{
  uint8_t u8Ack;
  /*开始*/
  Simulated_IIC_2_Start();
  /*地址*/
  Simulated_IIC_2_Transmit_Data(Address);
  /*ACK*/
  u8Ack = Simulated_IIC_2_Receive_ACK();
  /*寄存器*/
  Simulated_IIC_2_Transmit_Data(Register);
  /*控制数据*/
  Simulated_IIC_2_Transmit_Data(Function);
  /*停止*/
  Simulated_IIC_2_Stop();
}
/*接收*/
void TCA9539_IIC_Receive(void)
{
  ;
}

uint16_t ADC_4=0;

uint8_t TCA9539_Init_Once = 0;
/*所有引脚设置为输出*/
void TCA9539_Init(void);
void TCA9539_Init(void)
{
  TCA9539_IIC_Send(0xEA, 0x06, 0);
  TCA9539_IIC_Send(0xEA, 0x07, 0);

  TCA9539_IIC_Send(0xE8, 0x06, 0);
  TCA9539_IIC_Send(0xE8, 0x07, 0);
}

uint8_t TCA9539_U7_Out_P0 = 0xFF;
uint8_t TCA9539_U7_Out_Keep_P0 = 0x00;

uint8_t TCA9539_U7_Out_P1 = 0xFF;
uint8_t TCA9539_U7_Out_Keep_P1 = 0x00;

uint8_t TCA9539_U9_Out_P0 = 0xFF;
uint8_t TCA9539_U9_Out_Keep_P0 = 0x00;

uint8_t TCA9539_U9_Out_P1 = 0xFF;
uint8_t TCA9539_U9_Out_Keep_P1 = 0x00;

void TCA9539_Control(void)
{
  if (TCA9539_Init_Once == 0)
  {
    TCA9539_Init_Once = 1;
    TCA9539_Init();
  }

  if (ADC_4 > 2000) /*U9:03/07拉低*/
  {
    TCA9539_U9_Out_P0 = 0x77;
  }

  // if (ADC_4 < 1800) /*U9:03/07恢复*/
  // {
  //   TCA9539_U9_Out_P0 = 0xFF;
  // }

  if (TCA9539_U7_Out_Keep_P0 != TCA9539_U7_Out_P0)
  {
    TCA9539_IIC_Send(0xEA, 0x02, TCA9539_U7_Out_P0);
    TCA9539_U7_Out_Keep_P0 = TCA9539_U7_Out_P0;
  }

  if (TCA9539_U7_Out_Keep_P1 != TCA9539_U7_Out_P1)
  {
    TCA9539_IIC_Send(0xEA, 0x02, TCA9539_U7_Out_P1);
    TCA9539_U7_Out_Keep_P1 = TCA9539_U7_Out_P1;
  }

  if (TCA9539_U9_Out_Keep_P0 != TCA9539_U9_Out_P0)
  {
    TCA9539_IIC_Send(0xE8, 0x02, TCA9539_U9_Out_P0);
    TCA9539_U9_Out_Keep_P0 = TCA9539_U9_Out_P0;
  }

  if (TCA9539_U9_Out_Keep_P1 != TCA9539_U9_Out_P1)
  {
    TCA9539_IIC_Send(0xE8, 0x02, TCA9539_U9_Out_P1);
    TCA9539_U9_Out_Keep_P1 = TCA9539_U9_Out_P1;
  }
}
