
// Autocreated code
//int Pin = 1;
//float Interval = 10;
//int SensorID = 1

void setup() {
  pinMode(TrigPin, INPUT_PULLUP);
  pinMode(LEDPin,   OUTPUT);
  // wait for push A0 button
  int val = digitalRead(TrigPin);
  while (val == HIGH) {
    val = digitalRead(TrigPin);
  }
  
  /** initialize 0xff **/
  for (int i = 0 ; i < 512 ; i++) {
    EEPROM.write(i, 0xff);
  }

  pinMode(TrigPin, OUTPUT);
  pinMode(EchoPin, INPUT);

  current = millis();
  prevREC = current;
  prevLED = current;
  Serial.begin(9600);
  
  firstFlag = true;

  // Convert sec to millis
  Interval = Interval * 1000.0;
  EEPROM.write(addr  , SensorID);
  EEPROM.write(addr+1, 0);
  EEPROM.write(addr+2, ((int)(Interval) >> 24) & 0x000000ff);
  EEPROM.write(addr+3, ((int)(Interval) >> 16) & 0x000000ff);
  EEPROM.write(addr+4, ((int)(Interval) >>  8) & 0x000000ff);
  EEPROM.write(addr+5, ((int)(Interval))       & 0x000000ff);
  addr += 6;
}

void loop() {
  current = millis();
  
  if ((current - prevREC > Interval) || firstFlag) {
    prevREC = current;
    int val;
    if (SensorID == ULTRASONIC) {
        val = measureUltrasonic(TrigPin, EchoPin);
    } else {
        val = analogRead(Pin);
    }
    byte vh = (val >> 8) & 0x00ff;
    byte vl = val & 0x00ff;
    EEPROM.write(addr, vh);
    EEPROM.write(addr+1, vl);
  
    addr = addr + 2;
    if (addr == 512) {
      addr = 510;
    }
    firstFlag = false;
    Serial.println(val);
  }

  if (current - prevLED > 1000) {
    prevLED = current;
    digitalWrite(LEDPin, state);
    state = !state;
  }

}

// ******************************************
// Processing Ultra sonic sensor
// ******************************************
int measureUltrasonic(byte pinTrig, byte pinEcho ){
  pinMode(pinTrig, OUTPUT);
  digitalWrite(pinTrig, LOW);
  delayMicroseconds(10);
  digitalWrite(pinTrig, HIGH);
  delayMicroseconds(110);
  digitalWrite(pinTrig, LOW);
  delayMicroseconds(10);
  pinMode(pinEcho, INPUT);
//  range = (pulseIn(pinEcho,HIGH, 30000) / 58.0); // (29us = 1cm) , (timeout > (8m / 344m/s) = 23.5ms )
//  return (int)(range * 10.0);

  return (int)(pulseIn(pinEcho,HIGH, 30000));
}


