#include "SGM4591Q.h"
#include "Simulated_IIC_2_Master.h"

/*发送*/
void SGM4591Q_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 SGM4591Q_IIC_Receive(void)
{
  ;
}

uint16_t ADC_4=0;

uint8_t SGM4591Q_Init_Once = 0;
/*所有引脚设置为输出*/
void SGM4591Q_Init(void);
void SGM4591Q_Init(void)
{
  SGM4591Q_IIC_Send(0xEA, 0x06, 0);
  SGM4591Q_IIC_Send(0xEA, 0x07, 0);

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

uint8_t SGM4591Q_U7_Out_P0 = 0xFF;
uint8_t SGM4591Q_U7_Out_Keep_P0 = 0x00;

uint8_t SGM4591Q_U7_Out_P1 = 0xFF;
uint8_t SGM4591Q_U7_Out_Keep_P1 = 0x00;

uint8_t SGM4591Q_U9_Out_P0 = 0xFF;
uint8_t SGM4591Q_U9_Out_Keep_P0 = 0x00;

uint8_t SGM4591Q_U9_Out_P1 = 0xFF;
uint8_t SGM4591Q_U9_Out_Keep_P1 = 0x00;

void SGM4591Q_Control(void)
{
  if (SGM4591Q_Init_Once == 0)
  {
    SGM4591Q_Init_Once = 1;
    SGM4591Q_Init();
  }

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

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

  if (SGM4591Q_U7_Out_Keep_P0 != SGM4591Q_U7_Out_P0)
  {
    SGM4591Q_IIC_Send(0xEA, 0x02, SGM4591Q_U7_Out_P0);
    SGM4591Q_U7_Out_Keep_P0 = SGM4591Q_U7_Out_P0;
  }

  if (SGM4591Q_U7_Out_Keep_P1 != SGM4591Q_U7_Out_P1)
  {
    SGM4591Q_IIC_Send(0xEA, 0x02, SGM4591Q_U7_Out_P1);
    SGM4591Q_U7_Out_Keep_P1 = SGM4591Q_U7_Out_P1;
  }

  if (SGM4591Q_U9_Out_Keep_P0 != SGM4591Q_U9_Out_P0)
  {
    SGM4591Q_IIC_Send(0xE8, 0x02, SGM4591Q_U9_Out_P0);
    SGM4591Q_U9_Out_Keep_P0 = SGM4591Q_U9_Out_P0;
  }

  if (SGM4591Q_U9_Out_Keep_P1 != SGM4591Q_U9_Out_P1)
  {
    SGM4591Q_IIC_Send(0xE8, 0x02, SGM4591Q_U9_Out_P1);
    SGM4591Q_U9_Out_Keep_P1 = SGM4591Q_U9_Out_P1;
  }
}
