#include <Wire.h>
#include "gw_grayscale_sensor.h"

// SDA : A4
// SCL : A5

#define GW_GRAY_ADDR GW_GRAY_ADDR_DEF // 使用默认地址

void setup() {
  // 初始化I2C
  Wire.begin();

  // 初始化串口
  Serial.begin(115200);
}

void loop() {
  uint8_t sensor_4, sensor_5;
  uint8_t ping_rep = 0;
  uint8_t sensor_arr[8];

  // 循环 直到PING成功
  while (ping_rep != GW_GRAY_PING_OK) {
    Wire.beginTransmission(GW_GRAY_ADDR);
    Wire.write(GW_GRAY_PING);
    Wire.endTransmission();

    Wire.requestFrom(GW_GRAY_ADDR, 1);
    ping_rep = Wire.read();
    delay(10);
  }

  /* ping 成功 */

  /* ----------------------读取探头们的GrayB 滞回比较器参数--------------------- */
  Wire.beginTransmission(GW_GRAY_ADDR);
  Wire.write(GW_GRAY_CALIBRATION_BLACK); //白色为GW_GRAY_CALIBRATION_WHITE
  Wire.endTransmission();

  Wire.requestFrom(GW_GRAY_ADDR, 8);
  for (int i = 0; i < 8; ++i) {
    sensor_arr[i] = Wire.read();
  }
  // 由此 sensor_arr[0:7] 存放着 探头1-8的校准数据

  for (int i = 0; i < 8; ++i) {
    Serial.print(sensor_arr[i]);
    Serial.print(" ");
  }
  Serial.println();

  /* ----------------------如何更新传感器校准数据:------------------- */

  // 假设数据如下(仅供参考)
  for (int i = 0; i < 8; ++i) {
    sensor_arr[i] = 0x66; //sensor_arr = {0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66};
  }

  /* 更新探头校准数据 */
  Wire.beginTransmission(GW_GRAY_ADDR);
  // 写入命令
  Wire.write(GW_GRAY_CALIBRATION_BLACK);

  // 写入8个探头的8个数据
  for (int i = 0; i < 8; ++i) {
    Wire.write(sensor_arr[i]);
  }
  Wire.endTransmission();
  // 设置探头1-8的校准值完毕


  /* 用户操作 */
  while (1) {

  }
}