#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)
{
  /*U59:A0低，A1低*/
  SGM4591Q_IIC_Send(0xE8, 0x06, 0);/*P0组引脚为输出*/
  SGM4591Q_IIC_Send(0xE8, 0x07, 0);/*P1组引脚为输出*/
  SGM4591Q_IIC_Send(0xE8, 0x08, 0xFF);/*推挽输出*/
  SGM4591Q_IIC_Send(0xE8, 0x09, 0xFF);/*推挽输出*/

  /*U71:A0低，A1高*/
  SGM4591Q_IIC_Send(0xEC, 0x06, 0);/*P0组引脚为输出*/
  SGM4591Q_IIC_Send(0xEC, 0x07, 0);/*P1组引脚为输出*/
  SGM4591Q_IIC_Send(0xEC, 0x08, 0xFF);/*推挽输出*/
  SGM4591Q_IIC_Send(0xEC, 0x09, 0xFF);/*推挽输出*/

  /*U72:A0高，A1低*/
  SGM4591Q_IIC_Send(0xEA, 0x06, 0);/*P0组引脚为输出*/
  SGM4591Q_IIC_Send(0xEA, 0x07, 0);/*P1组引脚为输出*/
  SGM4591Q_IIC_Send(0xEA, 0x08, 0xFF);/*推挽输出*/
  SGM4591Q_IIC_Send(0xEA, 0x09, 0xFF);/*推挽输出*/
  
  /*U69:A0高，A1高*/
  SGM4591Q_IIC_Send(0xEE, 0x06, 0);/*P0组引脚为输出*/
  SGM4591Q_IIC_Send(0xEE, 0x07, 0);/*P1组引脚为输出*/
  SGM4591Q_IIC_Send(0xEE, 0x08, 0xFF);/*推挽输出*/
  SGM4591Q_IIC_Send(0xEE, 0x09, 0xFF);/*推挽输出*/
}

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 = 0;
uint8_t SGM4591Q_U9_Out_Keep_P0 = 0x00;

uint8_t SGM4591Q_U9_Out_P1 = 0;
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, 0x03, 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, 0x03, SGM4591Q_U9_Out_P1);
    SGM4591Q_U9_Out_Keep_P1 = SGM4591Q_U9_Out_P1;
  }
}
