Auto-Mapping

// Soil Moisture Sensor Pin
int soilMoisturePin = A0;
// Calibration Variables
int moistureMinValue;
int moistureMaxValue;

void setup() {
  // Initialize serial communication
  Serial.begin(9600);
}

void loop() {
  // Prompt user to calibrate the sensor
  Serial.println("Calibrating Soil Moisture Sensor");
  Serial.println("Please follow the instructions.");

  // Calibrate minimum moisture value
  Serial.println("Place the sensor in dry soil.");
  Serial.println("Press Enter when ready to calibrate minimum value, or enter 'X' to exit.");
  while (true) {
    if (Serial.available()) {
      char input = Serial.read();
      if (input == '\n') {
        moistureMinValue = analogRead(soilMoisturePin);
        Serial.print("Minimum Moisture Value: ");
        Serial.println(moistureMinValue);
        break;
      } else if (input == 'X' || input == 'x') {
        Serial.println("Exiting calibration process.");
        while (true) {
          if (Serial.available()) {
            char input = Serial.read();
            if (input == '\n') {
              break;
            }
          }
        }
        break; // Exit the calibration loop
      }
    }
  }

  if (moistureMinValue != 0) {
    // Calibrate maximum moisture value
    Serial.println("Place the sensor in moist soil.");
    Serial.println("Press Enter when ready to calibrate maximum value, or enter 'X' to exit.");
    while (true) {
      if (Serial.available()) {
        char input = Serial.read();
        if (input == '\n') {
          moistureMaxValue = analogRead(soilMoisturePin);
          Serial.print("Maximum Moisture Value: ");
          Serial.println(moistureMaxValue);
          break;
        } else if (input == 'X' || input == 'x') {
          Serial.println("Exiting calibration process.");
          while (true) {
            if (Serial.available()) {
              char input = Serial.read();
              if (input == '\n') {
                break;
              }
            }
          }
          break; // Exit the calibration loop
        }
      }
    }
  }

  if (moistureMaxValue != 0) {
    // Perform mapping and display calibrated values
    while (true) {
      int mappedValue = map(analogRead(soilMoisturePin), moistureMinValue, moistureMaxValue, 0, 100);
      Serial.print("Moisture Level: ");
      Serial.print(mappedValue);
      Serial.println("%");
      delay(1000);
    }
  }
}

Last updated