/*
WFH Sensor spi democode @ arduino_uno
*/

const int sclk = 10;//pin1
const int sen = 6;//pin3
const int sdi = 11;//pin7,mosi
const int sdo = 12;//pin8,miso,read data

uint8_t RawData[5];
long reading = 0;
float press = 0;//kPa
float temp = 0;//degree Celsius
float fDat;

/*
 ** One byte data read by SPI
*/
uint8_t SPI_Read_OneByte(void)
{
  uint8_t i;
  uint8_t temp = 0;
  for (i = 0; i < 8; i++)
  {
    temp <<= 1;
    digitalWrite(sclk, HIGH);
    if (digitalRead(sdo) == HIGH) 
      temp |= 0x01;
    else
      temp &= ~0x01;
    digitalWrite(sclk, LOW);
  }
  return temp;
}

/*
** One byte data written by SPI
*/
void SPI_Write_OneByte(uint8_t u8_writedata)
{
  uint8_t i;
  for (i = 0; i < 8; i++)
  {
    if (u8_writedata & 0x80) 
    {
      digitalWrite(sdi, HIGH); 
    }
    else
    {
      digitalWrite(sdi, LOW);
    }
    digitalWrite(sclk, HIGH); 
    u8_writedata <<= 1; 
    digitalWrite(sclk, LOW); 
  }
}

/*
** Send conversion command to read data
*/
uint8_t* GetSensorData()
{
  uint8_t buf[5];
  uint8_t error = 0;
  
  memset(RawData, 0, sizeof(uint8_t) * 5);

  //Get CalTempData
  WFSensor_WriteReg(0x30, 0x08);
  delay(10);
  RawData[3] = WFSensor_ReadReg(0x09);
  RawData[4] = WFSensor_ReadReg(0x0A);  
 
  //Get CalPressData
  WFSensor_WriteReg(0x30, 0x09);
  delay(10); 
  RawData[0] = WFSensor_ReadReg(0x06);
  RawData[1] = WFSensor_ReadReg(0x07);
  RawData[2] = WFSensor_ReadReg(0x08);

  return RawData;
}

/*
** Send command values to registers
*/
void  WFSensor_WriteReg(uint8_t addr, uint8_t value)
{
  digitalWrite(sen, LOW);
  SPI_Write_OneByte(0x00);
  SPI_Write_OneByte(addr);
  SPI_Write_OneByte(value);
  digitalWrite(sen, HIGH);
}

/*
** Read value from register
*/
uint8_t  WFSensor_ReadReg(uint8_t  addr)
{
  uint8_t value;
  digitalWrite(sen, LOW);
  SPI_Write_OneByte(0x80);
  SPI_Write_OneByte(addr);
  value = SPI_Read_OneByte();
  digitalWrite(sen, HIGH);
  return value;
}


void idleStatus()
{
  digitalWrite(sen, HIGH);
  pinMode(sclk, INPUT);
 // pinMode(sen, INPUT);
 // pinMode(sdo, INPUT);
  pinMode(sdi, INPUT);
  delay(1);
}

void workStatus()
{
  pinMode(sclk, OUTPUT);
  pinMode(sen, OUTPUT);
  pinMode(sdo, INPUT);
  pinMode(sdi, OUTPUT);
  delay(1);
}

void setup() {
  workStatus();
  digitalWrite(sen, HIGH);

  //active: 4-wire SPI
  WFSensor_WriteReg(0x00, 0x01);
  delay(1);
}

void loop() {
  
  uint8_t* p1 = GetSensorData();
  reading = p1[0];
  reading = reading << 8;
  reading |= p1[1];
  reading = reading << 8;
  reading |= p1[2];
  if (reading >= 8388608) {
    fDat = (int32_t)(reading - 16777216) / 8388608.0f;
  } else {
    fDat = reading / 8388608.0f;
  }
  //output_press
  press = fDat * 250 + 25;//WF100D_200KPA_S6
  
  //output_temp
  temp = -1.2+p1[3]+p1[4]*0.004;
  if(p1[3] >= 0x80) temp -= 256;
  delay(500);
}
