You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Arduino的电机自动启停系统开发及代码逻辑调试求助

Fixing Your Automatic Soil Moisture Control Logic

Let's work through why your auto mode isn't updating sensor values or switching the motor correctly, then fix the code step by step.

What's Wrong with the Current Code

Your existing auto-mode block has two critical flaws that break the intended behavior:

  1. It runs only once: Right after setting auto_flag = 1, you execute one sensor check, then immediately set auto_flag = 0—so the auto mode stops before it can monitor changes over time.
  2. Duplicate sensor reads: You call readSoil() twice (once in the if condition, once in the print statement), which might give inconsistent readings if moisture shifts between calls.
  3. No persistent loop: Auto mode needs to keep running in a loop, checking the sensor repeatedly, until you send an "Auto off" command to disable it.

Corrected Code Implementation

First, ensure auto_flag is a global variable (so it's accessible to both your SMS command handler and the main loop). Here's the revised logic:

// Global variables (outside any function)
bool auto_flag = false;
const int Maxdryness = /* Insert your threshold value here */;
// Add your pin definitions below (example)
const int motorPin1 = 2;
const int motorPin2 = 3;
const int wetSoil = 4;
const int drySoil = 5;
const int soilSensorPin = A0;

void setup() {
  Serial.begin(9600);
  // Initialize pins
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  pinMode(wetSoil, OUTPUT);
  pinMode(drySoil, OUTPUT);
  // Set initial states
  digitalWrite(motorPin1, LOW);
  digitalWrite(motorPin2, LOW);
  digitalWrite(wetSoil, HIGH);
  digitalWrite(drySoil, LOW);
}

void loop() {
  // Handle incoming SMS commands (adjust this to match your SMS library logic)
  if (hasNewSMS()) {
    String command = getReceivedSMS();
    if (command.equalsIgnoreCase("Auto on")) {
      auto_flag = true;
      send_message("System is now automatic");
    } else if (command.equalsIgnoreCase("Auto off")) {
      auto_flag = false;
      send_message("System is now manual");
      // Clean up motor/LED state when exiting auto mode
      digitalWrite(motorPin1, LOW);
      digitalWrite(motorPin2, LOW);
      digitalWrite(wetSoil, HIGH);
      digitalWrite(drySoil, LOW);
    } else if (command.equalsIgnoreCase("Motor on")) {
      auto_flag = false; // Disable auto mode for manual control
      digitalWrite(motorPin1, HIGH);
      digitalWrite(motorPin2, LOW);
      send_message("Motor turned on manually");
    } else if (command.equalsIgnoreCase("Motor off")) {
      auto_flag = false;
      digitalWrite(motorPin1, LOW);
      digitalWrite(motorPin2, LOW);
      send_message("Motor turned off manually");
    }
  }

  // Auto mode logic: runs continuously while auto_flag is true
  if (auto_flag) {
    // Read sensor once and store the value to avoid inconsistent readings
    int sensorValue = readSoil();
    
    Serial.print("Soil Moisture = ");
    Serial.println(sensorValue);

    // Check moisture threshold and adjust motor/LEDs
    if (sensorValue >= Maxdryness) {
      Serial.println("Soil is good.");
      digitalWrite(wetSoil, HIGH);
      digitalWrite(drySoil, LOW);
      digitalWrite(motorPin1, LOW);
      digitalWrite(motorPin2, LOW);
    } else {
      Serial.println("Low Soil Moisture detected.");
      digitalWrite(wetSoil, LOW);
      digitalWrite(drySoil, HIGH);
      digitalWrite(motorPin1, HIGH);
      digitalWrite(motorPin2, LOW);
    }

    delay(1000); // Adjust delay for desired check frequency (1 second here)
  }

  // Add any other background tasks or manual mode logic here
}

// Your existing sensor reading function (adjust to match your hardware)
int readSoil() {
  return analogRead(soilSensorPin); // Example for analog soil sensor
}

Key Fixes Explained

  • Persistent auto mode: The auto logic runs in the main loop() and keeps checking the sensor as long as auto_flag is true. It only stops when you send an "Auto off" command.
  • Single sensor read: We store the sensor value in a variable once per loop iteration, so the condition check and print statement use the exact same reading.
  • Clear mode separation: Manual commands (Motor on/off) automatically disable auto mode to prevent conflicts, and exiting auto mode resets the motor/LEDs to a safe state.
  • Real-time updates: Every loop iteration refreshes the sensor value and adjusts the motor based on current moisture, so it reacts immediately when the soil switches between wet and dry.

Additional Tips

  • Add sensor debouncing: If your readings are noisy, average 3-5 consecutive reads to avoid false motor triggers.
  • Use non-blocking delays: Replace delay() with millis() if you need the system to handle incoming SMS more responsively (no more missed commands during delays).
  • Verify Maxdryness: Double-check that your threshold matches your sensor's behavior (most analog soil sensors return higher values for drier soil).

内容的提问来源于stack exchange,提问作者Cynthia Aranda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:41:11