Simulate an ESP32 Watering Controller

Build a safe ESP32 watering controller simulation with Claude Code and Wokwi.

Introduction

30 Second Summary

Automatic watering sounds simple until damp soil sits right on the line between water and wait. Testing that decision with real equipment can turn a small mistake into a flooded pot.

In this project, you will build a safe ESP32 plant-watering simulation with Claude Code and Wokwi. Its blue valve indicator makes every control decision visible in a structured event log.

What You'll Build

Your demo responds as the virtual soil knob moves, lights the blue valve LED when watering is needed, stops unsafe watering, then sleeps until the next timer wake.

By the end of this project, you'll have:

  • A responsive virtual moisture gauge that converts raw ADC readings into a visible 0 to 100 percent scale.
  • A blue valve indicator with hysteresis that stays on through the threshold gap before stopping at the wet target or the 8-second safety limit.
  • A repeatable deep-sleep cycle that records wake sources, moisture events, warnings, and awake time in the Serial Monitor.
  • Secret Mission: estimate the awake duty cycle to compare a quick wet sensing cycle with a dry 8-second watering cycle.

Are there any prerequisites?

No embedded systems experience or physical hardware is required. You need eligible paid Claude Code access plus a Wokwi account on the €0 Community plan.

Before We Start

This project starts with a safe browser-only ESP32 simulation so you can test watering decisions before combining electricity with water. You will focus on preventing endless watering and unstable valve switching.

Set Up Claude Code and Wokwi

Setup confusion can hide the embedded-systems lesson behind account problems or terminal problems. This step gives every later change a known place to run.

You will prepare Claude Code for local file generation. You will also save a public Wokwi Community project that runs your first ESP32 sketch.

In this step, get ready to:
  • Install Claude Code with verified terminal access.
  • Create the local project folder with an authenticated Claude Code session.
  • Run a public Wokwi ESP32 project with an always-visible Serial Monitor.
Choose access and install Claude Code

Claude Code requires an eligible paid subscription or a Console account. The free Claude plan does not include Claude Code.

Which Claude access should you use?

  • Use an existing Pro, Max, Ultra, Team, Enterprise, or Console account if you already have one.
  • Choose Claude Pro for the lowest fixed-price individual option in this project.
  • Claude Pro costs $20 USD when billed monthly.
  • The annual Claude Pro subscription costs $200 USD when billed upfront.
  • Use a Console account if you prefer pay-as-you-go API billing.

Billing choices can feel risky before the project has even started. A subscription stays predictable when you avoid switching Claude Code to API usage.

  • Choose the eligible Claude account you want to use.
  • Decline API credits if you are using a subscription.
  • Avoid authenticating with ANTHROPIC_API_KEY.

First, check whether Claude Code is already available. This separates a working installation from a machine that still needs the native installer.

  • Press Cmd+Space on macOS or the Windows key on Windows to open system search.
  • Type Terminal on macOS or Windows PowerShell on Windows. Press Enter.
  • Check for Claude Code by running this command:
claude --version

What does this check do?

The command asks the installed Claude Code program for its version. A version number proves that your current shell can find the program.

Choose the tab that matches what your terminal shows.

✔️ I see a version number

Good progress. Claude Code is installed and available from your terminal.

ⓧ Command not found

Your machine needs the native Claude Code installer. Choose your operating system below.

macOS

  • Install Claude Code by running this command in Terminal:
curl -fsSL https://claude.ai/install.sh | bash
What does this installer do?

This command downloads the official Claude Code native installer. The installer makes the claude command available to your shell.

  • Close the current Terminal window.
  • Press Cmd+Space to open Spotlight.
  • Type Terminal. Press Enter.
  • Verify the fresh Terminal session by running this command:
claude --version
Why use a fresh Terminal?

A fresh Terminal loads the command path added by the installer. You should now see a Claude Code version number.

Windows

The native Windows installer works in Windows PowerShell without administrator access.

  • Install Claude Code by running this command in Windows PowerShell:
irm https://claude.ai/install.ps1 | iex
What does this installer do?

This command downloads the official Claude Code native installer through PowerShell. The installer makes the claude command available to your shell.

  • Close the current Windows PowerShell window.
  • Press the Windows key to open Start.
  • Type Windows PowerShell. Press Enter.
  • Verify the fresh PowerShell session by running this command:
claude --version
Why use a fresh PowerShell session?

A fresh PowerShell session loads the command path added by the installer. You should now see a Claude Code version number.

Once the fresh shell prints a version number, the native installation is ready.

Still missing the Claude command?

Run the installer again in the same shell type shown above. Close every terminal window before opening another fresh session.

Check the official Claude Code setup guide for operating-system requirements.

Help me troubleshoot my Claude Code installation.

Create the local project and authenticate

Claude Code works inside the folder where you launch it. Creating a dedicated folder keeps its generated Wokwi files together.

A fresh shell also confirms that the installer remains available after the original session closes. Choose your operating system below.

macOS

  • Press Cmd+Space to open Spotlight.
  • Type Terminal. Press Enter.
  • Create the plant-watering-simulator folder in Documents by running these commands:
mkdir -p ~/Documents/plant-watering-simulator
cd ~/Documents/plant-watering-simulator

What do these commands do?

  • The first command creates plant-watering-simulator inside your Documents folder.
  • The second command moves your Terminal session into that folder.

Starting Claude Code may open a browser authentication flow. Use the eligible account you chose earlier.

  • Start Claude Code from the project folder by running this command:
claude

What does this command do?

The command opens an interactive Claude Code session inside plant-watering-simulator. Files created during this session stay in that folder.

  • Complete the browser authentication with your chosen eligible account.
  • Return to Terminal after the browser confirms authentication.

You should see the interactive Claude Code prompt ready for your first request.

Windows

  • Press the Windows key to open Start.
  • Type Windows PowerShell. Press Enter.
  • Create the plant-watering-simulator folder in Documents by running these commands:
New-Item -ItemType Directory -Force -Path "$HOME\Documents\plant-watering-simulator"
Set-Location -Path "$HOME\Documents\plant-watering-simulator"

What do these commands do?

  • The first command creates plant-watering-simulator inside your Documents folder.
  • The second command moves your PowerShell session into that folder.

Starting Claude Code may open a browser authentication flow. Use the eligible account you chose earlier.

  • Start Claude Code from the project folder by running this command:
claude

What does this command do?

The command opens an interactive Claude Code session inside plant-watering-simulator. Files created during this session stay in that folder.

  • Complete the browser authentication with your chosen eligible account.
  • Return to Windows PowerShell after the browser confirms authentication.

You should see the interactive Claude Code prompt ready for your first request.

Authentication did not complete?

Confirm that you selected an eligible paid subscription or Console account. Avoid supplying an API key when you intend to use subscription access.

Help me troubleshoot Claude Code authentication.

Build the Wokwi starter simulation

Wokwi Community costs €0 per month. Its free projects are public, so keep credentials and private data out of every project file.

The new ESP32 project gives you browser editors for sketch.ino and diagram.json. Claude Code creates the local versions that you copy into those editors.

  • Visit the new Wokwi ESP32 project page in Safari on macOS or Microsoft Edge on Windows.
  • Sign in or register with Google or GitHub.
  • Keep your account on the €0 Community plan.
  • Return to the new ESP32 project page after authentication.

You should see a new ESP32-DevKitC V4 project with sketch.ino and diagram.json available as project tabs.

Claude Code may request permission to create both local files after you submit the next prompt.

  • Switch back to the Claude Code session from earlier.
  • Generate the two Wokwi project files by pasting this prompt:
Create two files for a Wokwi ESP32-DevKitC V4 project. In sketch.ino, start Serial at 115200 and print exactly CLAUDE_WOKWI_READY once from setup. Keep loop empty. In diagram.json, use the board-esp32-devkit-c-v4 part and an always-visible Serial Monitor. Do not add libraries.

What does this prompt create?

  • The prompt creates sketch.ino with one startup message.
  • The prompt creates diagram.json with an ESP32-DevKitC V4 board.
  • The diagram connects the board to an always-visible Serial Monitor.
  • The empty dependencies object keeps external libraries out of the project.
  • Approve the creation of sketch.ino if Claude Code requests permission.
  • Approve the creation of diagram.json if Claude Code requests permission.
  • Wait for Claude Code to confirm that both files exist.

Claude did not create both files?

Confirm that the Claude Code session started inside plant-watering-simulator. Submit the exact prompt again if only one file was created.

Help me create the two Wokwi files.

Use the following reference to keep the local files and Wokwi editors aligned exactly.

  • Select the sketch.ino tab in Wokwi.
  • Replace its entire contents with this code:
void setup() {
  Serial.begin(115200);
  Serial.println("CLAUDE_WOKWI_READY");
}

void loop() {
}

What does this sketch do?

  • The setup() function runs when the simulated ESP32 starts.
  • Serial communication starts at 115200 baud.
  • The startup code prints CLAUDE_WOKWI_READY once.
  • The empty loop() function prevents repeated messages.
  • Confirm that the Wokwi editor contains one CLAUDE_WOKWI_READY line.
  • Select the diagram.json tab in Wokwi.
  • Replace its entire contents with this configuration:
{
  "version": 1,
  "author": "NextWork learner",
  "editor": "wokwi",
  "parts": [
    {
      "type": "board-esp32-devkit-c-v4",
      "id": "esp",
      "top": 0,
      "left": 0,
      "attrs": {}
    }
  ],
  "connections": [
    [ "esp:TX", "$serialMonitor:RX", "", [] ],
    [ "esp:RX", "$serialMonitor:TX", "", [] ]
  ],
  "serialMonitor": {
    "display": "always",
    "newline": "lf"
  },
  "dependencies": {}
}

What does this diagram define?

  • The parts array adds one ESP32-DevKitC V4 board.
  • The serial connections carry messages between the simulated board and the Serial Monitor.
  • The display setting keeps the Serial Monitor visible when the simulation starts.
  • The dependencies object remains empty because this starter sketch needs no external libraries.

✔️ Awesome, I've got everything!

Both Wokwi file tabs now match the local project files. You are ready to run the simulation.

ⓧ I'd like to double check the full code

Compare each Wokwi tab with the complete file below.

void setup() {
  Serial.begin(115200);
  Serial.println("CLAUDE_WOKWI_READY");
}

void loop() {
}

What should match in the sketch?

Your full sketch.ino should contain one setup function and one empty loop function. The startup message must match the reference character for character.

{
  "version": 1,
  "author": "NextWork learner",
  "editor": "wokwi",
  "parts": [
    {
      "type": "board-esp32-devkit-c-v4",
      "id": "esp",
      "top": 0,
      "left": 0,
      "attrs": {}
    }
  ],
  "connections": [
    [ "esp:TX", "$serialMonitor:RX", "", [] ],
    [ "esp:RX", "$serialMonitor:TX", "", [] ]
  ],
  "serialMonitor": {
    "display": "always",
    "newline": "lf"
  },
  "dependencies": {}
}

What should match in the diagram?

Your full diagram.json should contain one board and two serial connections. Its Serial Monitor configuration should use the exact values shown above.

Before you start the simulation, do you expect the readiness message to appear once or repeat continuously?

  • Start the simulation using the run control in the Wokwi toolbar.

The always-visible Serial Monitor should print CLAUDE_WOKWI_READY once. The message stays on screen because loop() has no repeated work.

That is your first working ESP32 simulation. Claude Code generated the project files that Wokwi can now run in the browser.

Readiness message missing?

Check that sketch.ino contains the exact startup message. Confirm that diagram.json keeps the Serial Monitor display set to always.

Stop the simulation after correcting either file. Start it again to rerun setup().

Help me troubleshoot my Wokwi readiness message.

Your local AI workflow and browser simulator are ready. Next, you will turn a virtual input into a moisture gauge.

Turn the Soil Knob Into a Moisture Gauge

Your Wokwi project already proves that the ESP32 can run code in the simulator. Its raw ADC reading still gives a plant owner no useful sense of whether the soil is dry or wet.

This step turns that electrical reading into a moisture percentage from 0% to 100%. You will also add an inactive valve indicator that becomes useful in the next step.

In this step, get ready to:
  • Use Claude Code to update the local circuit and firmware files.
  • Copy the revised files into Wokwi.
  • Sweep the potentiometer to verify the moisture calibration.
Ask Claude Code to build the gauge

Prompt-driven coding lets Claude Code turn a precise hardware behavior into matching firmware and circuit files. The calibration endpoints tell it how to translate voltage into plant-friendly moisture values.

Claude Code may pause for permission before editing. Its request should name only sketch.ino and diagram.json.

  • Return to the Claude Code session inside your plant-watering-simulator folder.
  • Send the complete project request by pasting this prompt:
Update the Wokwi project into a moisture gauge. Add a wokwi-potentiometer with initial value 700. Connect VCC to ESP32 3V3, GND to an ESP32 GND pin, and SIG to GPIO34. Add a blue wokwi-led labeled Water valve in series with a 220 ohm wokwi-resistor from GPIO15 to GND. In sketch.ino, use analogRead on GPIO34, treat raw 4095 as 0 percent dry and raw 0 as 100 percent wet, constrain the result to 0 through 100, print Moisture: followed by the percentage every 500 milliseconds, and keep GPIO15 LOW. Use only Arduino-ESP32 built-in APIs.

What is Claude Code changing?

  • The potentiometer supplies a changing analog signal to GPIO34.
  • The readMoisturePercent() function maps the calibrated raw range to a constrained percentage.
  • The blue valve LED connects to GPIO15 through a 220 ohm resistor.
  • The LOW output keeps the simulated valve off during this sensing-only step.
  • Approve the file edits if Claude Code requests permission.
  • Confirm Claude Code reports that both project files were updated.

Good progress. Your local project now contains the virtual sensor circuit and its moisture conversion logic.

Claude Code did not update both files?

Check that the Claude Code session is inside the existing plant-watering-simulator folder. Ask it to apply the requested changes directly to both existing files if it only returns a description.

Compare the reported filenames with sketch.ino and diagram.json before approving edits.

Help me check the Claude Code file changes

Copy the gauge into Wokwi

The diagram.json file acts as the circuit blueprint. It places the potentiometer beside the ESP32 and wires the inactive valve indicator to the firmware pins.

  • Copy the complete contents of diagram.json from Claude Code's file output.
  • Switch back to the Wokwi browser project from earlier.
  • Stop the running simulation.
  • Select the diagram.json tab.
  • Replace the entire file with the copied circuit definition.

You should see a potentiometer plus a blue Water valve LED with its resistor beside the ESP32.

  • Copy the complete contents of sketch.ino from Claude Code's file output.
  • Select the sketch.ino tab in Wokwi.
  • Replace the entire file with the copied moisture-gauge firmware.
  • Compare both Wokwi files with the reference below if you want to confirm every pin and value.

✔️ Awesome, I've got everything!

Both revised files are now in Wokwi. Your moisture gauge is ready for its first calibration test.

ⓧ I'd like to double check the full code

Compare your complete sketch.ino with this reference.

const uint8_t MOISTURE_PIN = 34;
const uint8_t VALVE_LED_PIN = 15;
const int DRY_RAW = 4095;
const int WET_RAW = 0;

int readMoisturePercent() {
  const int raw = analogRead(MOISTURE_PIN);
  const long mapped = map(raw, DRY_RAW, WET_RAW, 0, 100);
  return constrain(mapped, 0, 100);
}

void setup() {
  Serial.begin(115200);
  pinMode(MOISTURE_PIN, INPUT);
  pinMode(VALVE_LED_PIN, OUTPUT);
  digitalWrite(VALVE_LED_PIN, LOW);
}

void loop() {
  Serial.print("Moisture: ");
  Serial.print(readMoisturePercent());
  Serial.println("%");
  delay(500);
}

What should match in sketch.ino?

  • The pin constants connect moisture sensing to GPIO34 and valve output to GPIO15.
  • The calibration constants map raw 4095 to dry and raw 0 to wet.
  • The loop prints a constrained percentage every 500 milliseconds.

Compare your complete diagram.json with this reference.

{
  "version": 1,
  "author": "NextWork learner",
  "editor": "wokwi",
  "parts": [
    {
      "type": "board-esp32-devkit-c-v4",
      "id": "esp",
      "top": 0,
      "left": 0,
      "attrs": {}
    },
    {
      "type": "wokwi-potentiometer",
      "id": "pot1",
      "top": -20,
      "left": 260,
      "attrs": { "value": "700" }
    },
    {
      "type": "wokwi-led",
      "id": "led1",
      "top": 110,
      "left": 280,
      "attrs": { "color": "blue", "label": "Water valve" }
    },
    {
      "type": "wokwi-resistor",
      "id": "r1",
      "top": 170,
      "left": 270,
      "rotate": 90,
      "attrs": { "value": "220" }
    }
  ],
  "connections": [
    [ "pot1:VCC", "esp:3V3", "red", [] ],
    [ "pot1:GND", "esp:GND.1", "black", [] ],
    [ "pot1:SIG", "esp:34", "green", [] ],
    [ "esp:15", "r1:1", "blue", [] ],
    [ "r1:2", "led1:A", "blue", [] ],
    [ "led1:C", "esp:GND.2", "black", [] ],
    [ "esp:TX", "$serialMonitor:RX", "", [] ],
    [ "esp:RX", "$serialMonitor:TX", "", [] ]
  ],
  "serialMonitor": {
    "display": "always",
    "newline": "lf"
  },
  "dependencies": {}
}

What should match in diagram.json?

  • The potentiometer connects power to 3V3 and its signal to GPIO34.
  • The resistor plus LED path runs from GPIO15 to ground.
  • The Serial Monitor remains configured to display whenever the simulation starts.

Circuit did not redraw?

Check that the complete JSON object starts with an opening brace and ends with a closing brace. A missing comma or brace prevents Wokwi from loading the parts.

Confirm that the part identifiers match pot1, led1, and r1 throughout the connections list.

Help me fix my Wokwi circuit file

Test the calibration from end to end

Calibration gives each end of the electrical range a human meaning. Sweeping the full range proves that the conversion reaches both moisture endpoints.

  • Start the Wokwi simulation.

The Serial Monitor should print a new Moisture: reading every 500 milliseconds. The blue Water valve LED should remain off.

Before you sweep the input, which end do you expect to represent wet soil?

  • Select the potentiometer in the simulated circuit.
  • Press Home to move the knob to the start of its range.

At the raw low end, you should see approximately 100%. This endpoint represents wet soil in the model.

  • Press End to move the knob to the end of its range.

At the raw high end, you should see approximately 0%. This endpoint represents dry soil in the model.

  • Turn the potentiometer slowly between both endpoints.

You should see intermediate percentages stay within 0% through 100%. The valve LED should remain off throughout the sweep.

That is your first live sensor loop working. The knob now behaves like soil moving between wet and dry conditions.

Readings stuck or reversed unexpectedly?

Check that the potentiometer signal connects to GPIO34. Confirm that DRY_RAW is 4095.

Confirm that WET_RAW is 0. Check that readMoisturePercent() returns the constrained mapped value.

Help me debug my moisture readings

Your soil knob now produces a calibrated moisture percentage while the valve remains safely off. Next, you will give that valve a simple threshold and watch why one boundary creates unstable behavior.

Make the One-Threshold Controller Misbehave

Your Wokwi moisture gauge now converts the soil knob into a percentage. The blue valve indicator remains off.

This experiment gives the valve one fixed decision boundary. You will test whether that simple rule stays stable when readings hover near 40 percent.

In this step, get ready to:
  • Ask Claude Code to replace the moisture gauge with a one-threshold controller.
  • Run the revised firmware with the existing Wokwi circuit.
  • Sweep the moisture reading across 40 percent four times to document the valve response.
Generate the one-threshold controller

A decision threshold divides sensor readings into two outcomes. Claude Code will update the existing firmware so every reading controls the valve against one boundary.

  • Switch back to the authenticated Claude Code terminal session from earlier.
  • Paste this prompt into the interactive session:
Replace the moisture-gauge behavior with a deliberately naive controller for this experiment. Keep the same circuit and calibration. Use one moisture threshold of 40 percent. Turn GPIO15 HIGH when moisture is 40 percent or lower and LOW when moisture is above 40 percent. Sample every 250 milliseconds and log the moisture percentage plus VALVE_ON or VALVE_OFF. Do not add hysteresis or a timeout yet.

What is Claude Code changing?

  • The new THRESHOLD constant stores the 40 percent decision boundary.
  • The valveOn value is recalculated from the latest moisture reading during every loop.
  • The loop sets VALVE_LED_PIN to HIGH or LOW before logging the matching valve state.
  • The existing diagram.json stays unchanged because the circuit already contains the moisture input and valve indicator.
  • Approve the edit if Claude Code asks for permission to update sketch.ino.
  • Wait for Claude Code to finish updating the file.

Claude Code did not update the sketch?

If Claude Code only explains the change, ask it to apply the prompt to sketch.ino in the current project folder.

Use this if the revision still does not appear: Help me check why Claude Code did not update sketch.ino from my one-threshold controller prompt.

✔️ Awesome, I've got everything!

Your revised sketch.ino is ready to transfer to Wokwi.

ⓧ I'd like to double check the full code

  • Compare Claude Code's revised sketch.ino with this complete version:
const uint8_t MOISTURE_PIN = 34;
const uint8_t VALVE_LED_PIN = 15;
const int DRY_RAW = 4095;
const int WET_RAW = 0;
const int THRESHOLD = 40;

int readMoisturePercent() {
  const int raw = analogRead(MOISTURE_PIN);
  const long mapped = map(raw, DRY_RAW, WET_RAW, 0, 100);
  return constrain(mapped, 0, 100);
}

void setup() {
  Serial.begin(115200);
  pinMode(MOISTURE_PIN, INPUT);
  pinMode(VALVE_LED_PIN, OUTPUT);
}

void loop() {
  const int moisture = readMoisturePercent();
  const bool valveOn = moisture <= THRESHOLD;
  digitalWrite(VALVE_LED_PIN, valveOn ? HIGH : LOW);
  Serial.print("Moisture: ");
  Serial.print(moisture);
  Serial.println(valveOn ? "% VALVE_ON" : "% VALVE_OFF");
  delay(250);
}

What should match?

  • The constants include THRESHOLD = 40.
  • The setup() function configures both pins without forcing the valve state.
  • The loop() function writes the valve state before logging VALVE_ON or VALVE_OFF.
  • The final delay is 250 milliseconds.
Run the revised sketch in Wokwi

The browser project uses the code inside its own sketch.ino tab. Transfer the local revision so the existing circuit can run the new decision rule.

  • Copy the complete revised sketch.ino content from Claude Code.
  • Switch back to the open Wokwi browser project from earlier.
  • Select the sketch.ino tab above the editor.
  • Press Cmd+A (macOS) or Ctrl+A (Windows) inside the editor to select the old firmware.
  • Paste the revised firmware into the editor.
  • Start the simulation with the green play control above the diagram.

You will see a new moisture line every 250 milliseconds. Each line ends with VALVE_ON or VALVE_OFF.

Still seeing the old moisture log?

If each line only shows a percentage, the Wokwi editor still contains the earlier gauge firmware. Stop the simulation before pasting the revised sketch.ino again.

Use this if the new valve labels still do not appear: Help me compare my Wokwi sketch with the one-threshold controller.

Sweep across the decision boundary

The controller is now making valve decisions. The next check focuses on the exact point where those decisions can reverse.

Before you test the boundary, think about whether the valve will hold one state as readings cross 40 percent.

  • Click the potentiometer inside the running simulation.
  • Move its knob slowly until the latest moisture reading reaches 40% or lower.

You will see the blue Water valve LED turn on. The latest Serial Monitor line ends with VALVE_ON.

  • Move the knob until the latest moisture reading reaches 41% or higher.

You will see the blue Water valve LED turn off. The latest Serial Monitor line ends with VALVE_OFF.

  • Cross the boundary in both directions at least four times by moving between 39% and 41%.

The valve LED reverses at every crossing. You found the intended failure in the one-threshold controller.

What just went wrong?

This repeated reversal is threshold chatter. Each sample is judged only against 40 percent.

A tiny change can immediately reverse the output. The controller has no decision memory.

It also has no timeout. A reading that stays dry could keep the valve on indefinitely.

You have exposed the weakness of a single decision boundary. Next, you will add two-threshold hysteresis plus bounded watering safeguards.

Add Hysteresis and Watering Safeguards

Your Wokwi simulation has exposed a weakness in the ESP32 controller. One threshold makes the blue valve LED switch every time moisture crosses the same boundary.

A real actuator needs protection from that chatter. It also needs protection from watering forever. In this step, hysteresis creates a 35-to-60 percent decision gap while timed safeguards monitor each watering cycle.

In this step, get ready to:
  • Replace the single 40 percent boundary with a 35-to-60 percent hysteresis gap.
  • Protect each watering cycle with no-rise monitoring plus a hard runtime limit.
  • Run recovery and fault tests that prove the valve stops safely.
Generate the safety controller

The revised controller needs memory during an active watering cycle. Claude Code can replace the one-threshold loop with a bounded cycle that keeps the valve on through the gap.

  • Switch back to the Claude Code terminal session from earlier.
  • Paste this upgrade request into Claude Code:
Upgrade the naive controller into a safety controller. Start watering only at or below 35 percent. Once watering starts, keep the blue LED on until moisture reaches 60 percent or 8000 milliseconds elapse. Read and log moisture every 500 milliseconds while watering. At 4000 milliseconds, if moisture has risen by less than 5 percentage points from the starting reading, print exactly WARNING_NO_MOISTURE_RISE once but continue until the wet target or hard limit. At the hard limit, turn the LED off and print exactly MAX_RUNTIME_STOP. Keep the controller awake for now.

What is Claude changing?

  • The dry threshold starts watering at 35 percent or lower.
  • The wet threshold ends watering when moisture reaches 60 percent.
  • The four-second check reports whether moisture has risen by at least five percentage points.
  • The eight-second limit turns the valve off even when the wet target is never reached.
  • Allow Claude Code to edit sketch.ino if it requests permission.
  • Wait for Claude Code to finish updating sketch.ino.
  • Copy the revised contents of sketch.ino from Claude Code.
  • Switch back to the Wokwi project from earlier.
  • Select the sketch.ino tab.
  • Replace the existing controller code with the revised contents.

The circuit in diagram.json stays unchanged. Use the tabs below to confirm that your revised sketch.ino matches the safety controller exactly.

✔️ Awesome, I've got everything!

Your local sketch.ino now matches the code in Wokwi. The controller is ready for its recovery test.

ⓧ I'd like to double check the full code

Compare your complete sketch.ino with this reference. Replace your file contents with this version if you find any differences.

const uint8_t MOISTURE_PIN = 34;
const uint8_t VALVE_LED_PIN = 15;

const int DRY_RAW = 4095;
const int WET_RAW = 0;
const int DRY_THRESHOLD = 35;
const int WET_THRESHOLD = 60;
const int MIN_RISE_PERCENT = 5;

const unsigned long SAMPLE_INTERVAL_MS = 500;
const unsigned long RISE_CHECK_MS = 4000;
const unsigned long WATER_LIMIT_MS = 8000;

int readMoisturePercent() {
  const int raw = analogRead(MOISTURE_PIN);
  const long mapped = map(raw, DRY_RAW, WET_RAW, 0, 100);
  return constrain(mapped, 0, 100);
}

void logReading(const char *event, int moisture, bool valveOn, unsigned long elapsedMs) {
  Serial.print("event=");
  Serial.print(event);
  Serial.print(", moisture=");
  Serial.print(moisture);
  Serial.print("%, valve=");
  Serial.print(valveOn ? "ON" : "OFF");
  Serial.print(", elapsed_ms=");
  Serial.println(elapsedMs);
}

void runWateringCycle(int startingMoisture) {
  const unsigned long wateringStart = millis();
  bool warningPrinted = false;
  bool wetTargetReached = false;

  digitalWrite(VALVE_LED_PIN, HIGH);
  Serial.println("event=WATERING_STARTED");

  while (true) {
    const unsigned long elapsed = millis() - wateringStart;
    const int moisture = readMoisturePercent();
    logReading("WATERING_SAMPLE", moisture, true, elapsed);

    if (moisture >= WET_THRESHOLD) {
      wetTargetReached = true;
      Serial.println("event=WET_TARGET_REACHED");
      break;
    }

    if (!warningPrinted && elapsed >= RISE_CHECK_MS &&
        moisture < startingMoisture + MIN_RISE_PERCENT) {
      Serial.println("WARNING_NO_MOISTURE_RISE");
      warningPrinted = true;
    }

    if (elapsed >= WATER_LIMIT_MS) {
      break;
    }

    delay(SAMPLE_INTERVAL_MS);
  }

  digitalWrite(VALVE_LED_PIN, LOW);

  if (!wetTargetReached) {
    Serial.println("MAX_RUNTIME_STOP");
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(MOISTURE_PIN, INPUT);
  pinMode(VALVE_LED_PIN, OUTPUT);
  digitalWrite(VALVE_LED_PIN, LOW);
}

void loop() {
  const int moisture = readMoisturePercent();
  logReading("SAMPLE", moisture, false, 0);

  if (moisture <= DRY_THRESHOLD) {
    runWateringCycle(moisture);
  } else if (moisture >= WET_THRESHOLD) {
    Serial.println("event=SOIL_WET_NO_WATERING");
  } else {
    Serial.println("event=HYSTERESIS_GAP_NO_WATERING");
  }

  delay(SAMPLE_INTERVAL_MS);
}

How is the safety controller structured?

  • The threshold constants define when a new watering cycle starts or ends.
  • The timing constants define the sampling interval plus both safety checkpoints.
  • The logReading() function produces structured moisture records for the Serial Monitor.
  • The runWateringCycle() function holds the valve on through the hysteresis gap.
  • The main loop starts a watering cycle only when moisture is at or below DRY_THRESHOLD.
Test recovery through the hysteresis gap

The recovery test checks whether the controller remembers that watering has already started. A reading inside the gap should preserve the active valve state until moisture reaches the wet target.

Before you start the test, do you expect the blue valve LED to switch off when moisture moves from 30 percent to 50 percent?

  • Start the Wokwi simulation.
  • Select the potentiometer in the circuit.
  • Move the knob until the Serial Monitor reports approximately 30% moisture.

The blue valve LED turns on. The Serial Monitor prints event=WATERING_STARTED followed by WATERING_SAMPLE records.

  • Move the potentiometer until the Serial Monitor reports approximately 50% moisture.

The blue valve LED stays on at 50 percent. The active watering cycle remembers its state through the hysteresis gap.

  • Move the potentiometer until the Serial Monitor reports at least 60% moisture.

The Serial Monitor prints event=WET_TARGET_REACHED. The blue valve LED turns off at the wet target.

Valve stops inside the gap?

Check that runWateringCycle() keeps sampling until moisture reaches WET_THRESHOLD. Confirm that WET_THRESHOLD is set to 60.

If watering never starts, move the potentiometer lower until the reported moisture is 35% or less.

Help me debug the hysteresis test

Prove the safeguards stop a fault

A no-rise warning reports that simulated watering is failing to improve moisture. The independent hard limit still enforces the final stop.

  • Move the potentiometer until the Serial Monitor reports less than 35% moisture.

This check uses the complete eight-second safety window. Give the controller time to reach both checkpoints.

Before you restart the simulation, which log message do you expect to appear first?

  • Restart the Wokwi simulation.
  • Leave the potentiometer unchanged for the entire watering cycle.

After about four seconds, the Serial Monitor prints WARNING_NO_MOISTURE_RISE once. The blue valve LED remains on while monitoring continues.

By eight seconds, the Serial Monitor prints MAX_RUNTIME_STOP. The blue valve LED turns off even though moisture never reached 60 percent.

That is the safety layer proven. Your controller now detects a failed moisture rise while guaranteeing a bounded valve runtime.

Missing a safety message?

Check that RISE_CHECK_MS is 4000. Confirm that warningPrinted prevents duplicate warnings.

If the valve stays on beyond eight seconds, check that WATER_LIMIT_MS is 8000. Confirm that GPIO15 is set to LOW after the watering loop.

Help me debug the watering safeguards

Your valve controller now handles a recovery path plus an unchanged-moisture fault. Next up, you will measure its awake time before sending the ESP32 into timer-based deep sleep.

Sleep, Wake, and Log Every Cycle

Your safety controller in Wokwi already prevents endless watering. The ESP32 still stays awake between every moisture reading.

A battery-oriented controller should spend most of its time in deep sleep. This step gives each wake a bounded job before the timer sends the controller back to sleep.

In this step, get ready to:
  • Convert setup into one bounded wake cycle.
  • Wake the ESP32 from a 10-second deep-sleep timer.
  • Compare the wet sensing path with the dry safety path.
Generate the sleep-aware sketch

A timer wake gives the controller one bounded cycle per boot. Each cycle measures its awake time before returning to sleep.

Why one cycle per wake?

Continuous sampling keeps the processor active between readings. A timer wake creates a repeatable sense, act, log, sleep pattern.

  • The bootCount value survives deep sleep through RTC_DATA_ATTR.
  • The getWakeSourceLabel() helper distinguishes a timer wake from a power-on or reset.
  • The setup() function performs one moisture decision during each boot.
  • The esp_sleep_enable_timer_wakeup(SLEEP_SECONDS * MICROSECONDS_PER_SECOND) call schedules the next wake after 10 seconds.
  • The Serial.flush() call sends the final log output before sleep begins.
  • The esp_deep_sleep_start() call places the controller into deep sleep.
  • Switch back to the authenticated Claude Code session in your plant-watering-simulator folder.
  • Ask Claude Code to update sketch.ino with the bounded wake cycle described above.

Claude Code shows the proposed file changes. It may also request permission before editing the file.

  • Approve the edit if Claude Code requests permission.
  • Compare the completed sketch.ino with the reference below.

✔️ Awesome, I've got everything!

  • Save sketch.ino in your plant-watering-simulator folder.

Your local sketch is ready to copy into the simulation.

ⓧ I'd like to double check the full code

  • Compare your complete sketch.ino with this reference:
#include <Arduino.h>

const uint8_t MOISTURE_PIN = 34;
const uint8_t VALVE_LED_PIN = 15;

const int DRY_RAW = 4095;
const int WET_RAW = 0;
const int DRY_THRESHOLD = 35;
const int WET_THRESHOLD = 60;
const int MIN_RISE_PERCENT = 5;

const unsigned long SAMPLE_INTERVAL_MS = 500;
const unsigned long RISE_CHECK_MS = 4000;
const unsigned long WATER_LIMIT_MS = 8000;
const uint64_t SLEEP_SECONDS = 10;
const uint64_t MICROSECONDS_PER_SECOND = 1000000ULL;

RTC_DATA_ATTR int bootCount = 0;

int readMoisturePercent() {
  const int raw = analogRead(MOISTURE_PIN);
  const long mapped = map(raw, DRY_RAW, WET_RAW, 0, 100);
  return constrain(mapped, 0, 100);
}

void logReading(const char *event, int moisture, bool valveOn, unsigned long elapsedMs) {
  Serial.print("event=");
  Serial.print(event);
  Serial.print(", moisture=");
  Serial.print(moisture);
  Serial.print("%, valve=");
  Serial.print(valveOn ? "ON" : "OFF");
  Serial.print(", elapsed_ms=");
  Serial.println(elapsedMs);
}

void runWateringCycle(int startingMoisture) {
  const unsigned long wateringStart = millis();
  bool warningPrinted = false;
  bool wetTargetReached = false;

  digitalWrite(VALVE_LED_PIN, HIGH);
  Serial.println("event=WATERING_STARTED");

  while (true) {
    const unsigned long elapsed = millis() - wateringStart;
    const int moisture = readMoisturePercent();
    logReading("WATERING_SAMPLE", moisture, true, elapsed);

    if (moisture >= WET_THRESHOLD) {
      wetTargetReached = true;
      Serial.println("event=WET_TARGET_REACHED");
      break;
    }

    if (!warningPrinted && elapsed >= RISE_CHECK_MS &&
        moisture < startingMoisture + MIN_RISE_PERCENT) {
      Serial.println("WARNING_NO_MOISTURE_RISE");
      warningPrinted = true;
    }

    if (elapsed >= WATER_LIMIT_MS) {
      break;
    }

    delay(SAMPLE_INTERVAL_MS);
  }

  digitalWrite(VALVE_LED_PIN, LOW);

  if (!wetTargetReached) {
    Serial.println("MAX_RUNTIME_STOP");
  }
}

const char *getWakeSourceLabel() {
  if (esp_sleep_get_wakeup_cause() == ESP_SLEEP_WAKEUP_TIMER) {
    return "timer";
  }
  return "power-on or reset";
}

void setup() {
  const unsigned long awakeStart = millis();

  Serial.begin(115200);
  delay(1000);

  pinMode(MOISTURE_PIN, INPUT);
  pinMode(VALVE_LED_PIN, OUTPUT);
  digitalWrite(VALVE_LED_PIN, LOW);

  ++bootCount;
  Serial.print("Boot number: ");
  Serial.println(bootCount);
  Serial.print("Wake source: ");
  Serial.println(getWakeSourceLabel());

  const int moisture = readMoisturePercent();
  logReading("WAKE_SAMPLE", moisture, false, 0);

  if (moisture <= DRY_THRESHOLD) {
    runWateringCycle(moisture);
  } else if (moisture >= WET_THRESHOLD) {
    Serial.println("event=SOIL_WET_NO_WATERING");
  } else {
    Serial.println("event=HYSTERESIS_GAP_NO_WATERING");
  }

  const unsigned long awakeMs = millis() - awakeStart;
  Serial.print("Awake ms: ");
  Serial.println(awakeMs);
  Serial.print("Sleeping for seconds: ");
  Serial.println(SLEEP_SECONDS);

  esp_sleep_enable_timer_wakeup(SLEEP_SECONDS * MICROSECONDS_PER_SECOND);
  Serial.flush();
  esp_deep_sleep_start();
}

void loop() {
}

How does the full cycle work?

  • The retained bootCount value reveals whether multiple wake cycles occurred.
  • The getWakeSourceLabel() helper labels each boot according to its wake cause.
  • The setup() function records awake time around the complete control cycle.
  • The empty loop() function prevents continuous sampling after setup finishes.
  • Replace any differing content in your local sketch.ino with the reference above.
  • Save the corrected sketch.ino file.
  • Switch back to the Wokwi project from earlier.
  • Select the sketch.ino tab.
  • Replace its entire content with the completed local sketch.ino.
  • Select the diagram.json tab.
  • Confirm that pot1 remains connected to GPIO34.
  • Confirm that the blue Water valve LED remains connected to GPIO15 through the 220 ohm resistor.

The circuit stays unchanged because this step updates firmware behavior. The existing potentiometer still drives every wake-cycle decision.

Did Claude Code change something unexpected?

Use the full-file reference to restore sketch.ino. Keep diagram.json unchanged from the previous step.

Help me compare the generated sleep-cycle sketch with the required version.

Test the wet wake path

Wet soil takes the shortest path through the controller. The ESP32 records one reading before returning to sleep.

Before you start the simulation, do you expect the wet cycle's Awake ms: value to be closer to the sensing delay or the 8-second safety limit?

Setting the first input is a little fiddly because the controller waits only one second before reading moisture. Move the knob as soon as the simulation starts.

  • Start the simulation.
  • Immediately click the potentiometer.
  • Press Home to move the potentiometer to its raw-low wet end.
  • Leave the simulation running through two wakeups.

What should you see?

  • The first Boot number: line shows the initial boot count.
  • The first Wake source: line ends with power-on or reset.
  • The wet decision prints event=SOIL_WET_NO_WATERING.
  • The cycle prints Awake ms: before sleep begins.
  • The cycle prints Sleeping for seconds: followed by 10.
  • The next Wake source: line ends with timer.

That confirms the timer can wake your controller for a short sensing-only cycle.

Missing the timer wake?

  • Keep the simulation running for longer than 10 seconds after the first sleep message.
  • Check that SLEEP_SECONDS remains set to 10.
  • Check that esp_sleep_enable_timer_wakeup(SLEEP_SECONDS * MICROSECONDS_PER_SECOND) appears before esp_deep_sleep_start().
  • Check that bootCount uses RTC_DATA_ATTR if its value keeps returning to one.

Help me debug the timer wake cycle.

Test the dry safety path

Dry soil keeps the controller awake while the bounded watering cycle runs. Leaving the input unchanged triggers both safety logs.

Before the next wake, do you expect the dry cycle's Awake ms: value to be smaller or larger than the wet result?

  • Press End while the controller sleeps to move the potentiometer to its raw-high dry end.
  • Leave the potentiometer unchanged through the next wake.
  • Watch the Serial Monitor through the watering cycle.
  • Keep the simulation running until the following timer wake.

What should you see?

  • The dry wake prints event=WATERING_STARTED.
  • The blue valve LED stays on during the watering samples.
  • The unchanged reading triggers WARNING_NO_MOISTURE_RISE after 4 seconds.
  • The hard limit prints MAX_RUNTIME_STOP by 8 seconds.
  • The blue valve LED turns off at the hard limit.
  • The dry Awake ms: value is larger than the wet result.
  • The following boot reports timer as its wake source.

Missing a safety event?

  • Check that the event=WAKE_SAMPLE moisture value is 35 percent or lower.
  • Keep the potentiometer unchanged until WARNING_NO_MOISTURE_RISE appears.
  • Keep the input below the wet target until MAX_RUNTIME_STOP appears.
  • Compare RISE_CHECK_MS with the full-file reference if the warning timing differs.

Help me debug the dry safety cycle.

You've now proved that the controller repeats a bounded wake cycle without manual resets. The log captures the safety stop before every return to deep sleep.

Secret mission

Measure the Awake Duty Cycle

Awake milliseconds tell you how long each boot spends doing work. Convert that timing into an estimated percentage. Then compare a wet sensing cycle with a dry 8-second safety cycle.

Clean Up Your Resources

Clean Up Your Resources

Your Wokwi Community project costs €0 per month. Choose whether to keep the public project plus local files, pause the simulation, or delete the resources.

Cost warning

Wokwi Community remains free. Claude Code billing continues according to the access option you selected.

Individual subscribers can avoid the next charge by cancelling at least 24 hours before renewal. Console API billing is managed separately through Console billing settings.

Resources you used:

  • One public Wokwi Community project containing the ESP32-DevKitC V4 simulation.
  • The local project folder at ~/Documents/plant-watering-simulator on macOS or $HOME\Documents\plant-watering-simulator on Windows.
  • An individual Claude subscription if you started one for Claude Code access.

Keep everything running

Leave everything in place if you want to keep testing moisture levels or changing the controller.

  • Your public Wokwi project remains available from the projects dashboard.
  • Your local sketch.ino plus diagram.json files remain in the plant-watering-simulator folder.
  • Your Claude billing continues according to the access option you selected.

Pause - I'll come back to this later

Pausing ends the running simulation while preserving the public project plus local files for another session.

  • Switch back to the Wokwi project from earlier.
  • Use the simulation control to stop the running simulation.
  • Confirm the Serial Monitor no longer adds wake-cycle logs.

Your saved Wokwi project remains public. Pausing the simulation does not pause Claude billing.

Delete - I don't want to use this again

Choose this path to remove the public simulation plus local files. Each action names its target before anything is permanently deleted.

Public Wokwi project:

  • Return to the Wokwi projects dashboard.
  • Select the public ESP32 project you created.
  • Use the project dashboard controls to remove the public project.
  • Return to the projects dashboard to confirm the removed project no longer appears.

Local project files:

  • Delete the local plant-watering-simulator folder with the commands for your system below:

macOS

  • Remove the project folder from Documents by running these commands:
cd ~/Documents
rm -rf plant-watering-simulator
What Do These Commands Do?
  • The first command moves the terminal to your Documents folder.
  • The second command permanently removes only the plant-watering-simulator folder.
  • Confirm plant-watering-simulator no longer appears in your Documents folder.

Windows

  • Remove the project folder from Documents by running these commands in Windows PowerShell:
Set-Location -Path "$HOME\Documents"
Remove-Item -Recurse -Force plant-watering-simulator
What Do These Commands Do?
  • The first command moves Windows PowerShell to your Documents folder.
  • The second command permanently removes only the plant-watering-simulator folder.
  • Confirm plant-watering-simulator no longer appears in your Documents folder.

Claude billing:

  • In Claude, select Settings if you started an individual subscription for this project.
  • Select Billing.
  • Select Cancel.
  • Cancel at least 24 hours before renewal to avoid the next charge.

Console API billing is managed separately through Console billing settings.

Nice Work!

Nice Work!

You did it! You used Claude Code to build a Wokwi ESP32 watering controller. Your simulation now makes bounded valve decisions from changing moisture readings.

You've learned how to:

  • Convert raw ADC readings into a calibrated moisture gauge that moves from 0 percent dry to 100 percent wet.
  • Expose one-threshold chatter by repeatedly crossing 40 percent. Stabilize the simulated valve with 35-to-60 percent hysteresis.
  • Protect the simulated valve with a no-rise warning. Enforce an 8-second hard stop. Trace each timer wakeup through structured logs. Measure awake time before deep sleep.
  • Secret Mission: Calculate an estimated awake duty cycle for the wet path. Compare it with the unchanged dry watering path. Explain why the ratio compares firmware behavior without predicting real battery life.

Ready to quiz yourself?