Open a Greenhouse Vent from Your Phone
Control a simulated greenhouse vent from Telegram with an ESP32 and Wokwi.
Introduction
30 Second Summary
A greenhouse can overheat while you are nowhere near it. Checking a vent by hand makes every temperature change your problem.
In this project, you will build a virtual greenhouse controller in Wokwi. You will use Telegram on your phone to control a simulated ESP32 vent.
What You'll Build
By the end, a /open command from your phone moves the Wokwi servo to 90° while Telegram Web shows the bot's authorized reply.
By the end of this project, you'll have:
- Live temperature readings in the Serial Monitor that change when you adjust the virtual DHT22.
- Chat authorization that limits /status, /open, /close, and /auto to your Telegram chat.
- Stable automatic control that opens above 28°C. It closes below 24°C. Hysteresis holds the previous vent state inside the gap. Each automatic movement sends a message to your phone.
- Secret Mission: Stress-test hysteresis with an adversarial eight-temperature sequence. Produce a pass or fail log that proves the vent moves exactly twice.
Are there any prerequisites?
No prior coding or electronics experience is required. You need a Mac or Windows computer with internet access, a Telegram-capable phone, and Claude Pro access for Claude Code.
Before We Start
Before any hands-on work, commit to building a simulated greenhouse vent that you can observe and control from your phone. You will use Wokwi to test the idea safely without buying or wiring physical hardware.
Set Up Claude Code and Your Simulator
A growing simulated circuit is much easier to debug when every tool already works. This step builds that verified foundation before sensors or actuators enter the project.
You will use Claude Code to create a tiny ESP32 starter. The starter proves the simulator is using Arduino-ESP32 Core version 3 before the greenhouse circuit grows.
In this step, get ready to:
- Install Claude Code 2.1.322 through a supported paid account path.
- Prepare the browser plus the Telegram apps for later remote control.
- Create the three-file Wokwi starter and verify its Core 3 output.
Install and verify Claude Code
This project uses Claude Code release 2.1.322. Checking the installed version first gives you the correct path without repeating setup work.
- Press Cmd+Space on macOS or the Windows key on Windows to open system search.
- Type Terminal on macOS or PowerShell on Windows to find the command-line app.
- Press Enter to open the selected app.
- Check the installed Claude Code version by running this command:
claude --version
What does this check do?
The command asks Claude Code to print its installed version. A working project setup reports release 2.1.322.
✔️ I see version 2.1.322
Your Claude Code installation matches the release used in this project. Continue with authentication below.
ⓧ I see an older version
Install the current Claude Code release with the official native installer for your platform.
macOS
- Install the current release by running this command:
curl -fsSL https://claude.ai/install.sh | bash
What does this installer do?
This command downloads the official Claude Code native installer. The installer updates the local command-line application.
- Close Terminal after the installer finishes.
- Reopen Terminal through system search.
- Confirm the updated version by running this command:
claude --version
What does this second check prove?
This check confirms the updated command is available in the new terminal session. You should now see version 2.1.322.
Windows
- Install the current release in PowerShell by running this command:
irm https://claude.ai/install.ps1 | iex
What does this installer do?
This command downloads the official Claude Code native installer for Windows. The installer updates the local command-line application.
- Close PowerShell after the installer finishes.
- Reopen PowerShell through system search.
- Confirm the updated version by running this command:
claude --version
What does this second check prove?
This check confirms the updated command is available in the new PowerShell session. You should now see version 2.1.322.
ⓧ Command not found
Claude Code is not installed yet. Use the official native installer for your platform.
macOS
- Install Claude Code by running this command:
curl -fsSL https://claude.ai/install.sh | bash
What does this installer do?
This command downloads the official Claude Code native installer. The installer adds the command-line application to your computer.
- Close Terminal after the installer finishes.
- Reopen Terminal through system search.
- Verify the installation by running this command:
claude --version
What does this verification prove?
The command confirms that your new terminal session can find Claude Code. You should see version 2.1.322.
Windows
- Install Claude Code in PowerShell by running this command:
irm https://claude.ai/install.ps1 | iex
What does this installer do?
This command downloads the official Claude Code native installer for Windows. The installer adds the command-line application to your computer.
- Close PowerShell after the installer finishes.
- Reopen PowerShell through system search.
- Verify the installation by running this command:
claude --version
What does this verification prove?
The command confirms that your new PowerShell session can find Claude Code. You should see version 2.1.322.
Claude Code still unavailable?
Make sure you closed the terminal after installation. The installer becomes available to a fresh terminal session.
Help me troubleshoot my Claude Code installation.
That setup hurdle is cleared. Claude Code now answers from your terminal with the project release.
Choose a supported account path
Claude Code requires a supported paid account path. Claude Pro is the beginner path used here.
Claude Pro costs $20 when billed monthly. Applicable tax is separate.
- Start the Claude Code authentication flow by running this command:
claude
What happens next?
Claude Code opens a browser-based authentication flow. The terminal waits while you complete the account steps.
- Follow the browser prompts to authenticate through your supported paid account.
- Return to the terminal after authentication completes.
- End this first Claude Code session with Ctrl+C.
Authentication did not complete?
Return to the browser window opened by Claude Code. Complete every account prompt before returning to the terminal.
Help me finish Claude Code authentication.
Prepare Wokwi and Telegram
Your Wokwi project provides the virtual board that runs the greenhouse code. Telegram provides the phone plus computer views used for the final remote-control proof.
- Press Cmd+Space on macOS or the Windows key on Windows to open system search.
- Type Safari on macOS or Microsoft Edge on Windows to find the browser.
- Press Enter to open the selected browser.
- Navigate to https://wokwi.com/projects/new/esp32 to create a project from the current ESP32 template.
You should see a new ESP32 project with sketch.ino plus diagram.json. The Library Manager is also available for adding the pinned dependencies.
Why wait to create the bot?
Free Wokwi projects are public. Connections through its public gateway are monitored.
A Telegram bot token works like a password. You will create a disposable token only when the finished simulation is ready for its remote-control test.
- Install the official Telegram mobile app from your phone's app store.
- Sign in to Telegram on your phone.
- Navigate to https://telegram.org/apps in a second browser window on your computer.
- Select an official Telegram Web app from the applications page.
- Sign in to Telegram Web.
Your phone plus computer now show the same Telegram account. No bot or token exists yet.
Create and run the starter
The first program has one job. It proves the local files can run in the current Wokwi template before the project gains sensors or networking.
- Return to the terminal from the installation work.
- Choose the command for your operating system below.
macOS
- Create the local project folder and start Claude Code inside it by running this command:
mkdir -p ~/greenhouse-vent-simulator && cd ~/greenhouse-vent-simulator && claude
What does this command do?
The command creates greenhouse-vent-simulator in your home folder. It moves the terminal into that folder before starting Claude Code.
Windows
- Create the local project folder and start Claude Code inside it by running this command:
mkdir "$HOME\greenhouse-vent-simulator"; cd "$HOME\greenhouse-vent-simulator"; claude
What does this command do?
The command creates greenhouse-vent-simulator in your home folder. It moves PowerShell into that folder before starting Claude Code.
- Create the exact three-file starter by pasting this prompt into Claude Code:
Create a beginner Wokwi ESP32 Arduino project with exactly three files: sketch.ino, diagram.json, and libraries.txt.
For sketch.ino:
- Start Serial at 115200 baud.
- Print exactly: Greenhouse vent simulator ready
- Print the value returned by ESP.getCoreVersion().
- Keep loop nonblocking except for delay(10).
For diagram.json:
- Use one wokwi-esp32-devkit-v1 board.
- Do not add sensors or actuators yet.
For libraries.txt, add these exact version pins on separate lines:
DHT sensor library for ESPx@1.19
ArduinoJson@7.4.3
Do not add WiFi, Telegram, a DHT22, or a servo yet. After writing the files, summarize what changed.
What does this prompt protect?
- The three filenames match the tabs used by Wokwi.
- The Serial output creates a visible proof that the code is running.
- The empty board keeps this step focused on the toolchain.
- The dependency versions keep later sensor plus messaging code consistent.
The local greenhouse-vent-simulator folder now contains the three starter files. Claude Code has also summarized the changes it made.
- Copy the contents of the local sketch.ino file into the matching Wokwi tab.
- Copy the contents of the local diagram.json file into the matching Wokwi tab.
Before you start the simulation, what two messages do you expect the Serial Monitor to report?
- Start the Wokwi simulation using its play control.
You should see Greenhouse vent simulator ready in the Serial Monitor. The next line should begin with ESP32 core version: 3.
Core version does not begin with 3?
- Create a fresh project from the current template at https://wokwi.com/projects/new/esp32.
- Copy the two local files into their matching Wokwi tabs again.
Help me check the Wokwi ESP32 core version.
The DHT sensor library for ESPx supports the virtual temperature sensor added next. ArduinoJson prepares the project to process Telegram responses later.
- Open the Library Manager in Wokwi.
- Search for DHT sensor library for ESPx.
- Add the matching library to the project.
You should see the DHT sensor library listed among the project dependencies.
- Search the Library Manager for ArduinoJson.
- Add the matching library to the project.
You should now see both libraries in the project. Wokwi also provides a libraries.txt tab for their version pins.
- Select the libraries.txt tab in Wokwi.
- Replace its contents with these exact version pins:
DHT sensor library for ESPx@1.19
ArduinoJson@7.4.3
What do these pins do?
- DHT sensor library for ESPx uses version 1.19 for the sensor API used later.
- ArduinoJson uses version 7.4.3 for the future Telegram response parser.
✔️ Awesome, I've got everything!
Your local folder plus Wokwi project contain the same three-file starter. Continue to the final simulation check below.
ⓧ I'd like to double check the full code
- Compare each local file with the matching reference below.
- Compare each Wokwi tab with the same reference.
Your sketch.ino file should contain:
#include <Arduino.h>
void setup() {
Serial.begin(115200);
Serial.println("Greenhouse vent simulator ready");
Serial.print("ESP32 core version: ");
Serial.println(ESP.getCoreVersion());
}
void loop() {
delay(10);
}
What should this file do?
The setup function starts the Serial connection before printing the readiness line plus the ESP32 core version. The loop yields briefly without adding any greenhouse behavior.
Your diagram.json file should contain:
{
"version": 1,
"author": "NextWork learner",
"editor": "wokwi",
"parts": [
{
"type": "wokwi-esp32-devkit-v1",
"id": "esp",
"top": 0,
"left": 0,
"attrs": {}
}
],
"connections": [],
"dependencies": {}
}
What should this file do?
The diagram contains one ESP32 development board. Empty connections plus dependencies confirm that no sensor or actuator has been added.
Your libraries.txt file should contain:
DHT sensor library for ESPx@1.19
ArduinoJson@7.4.3
What should this file do?
The file pins both libraries to the project versions. No additional dependency belongs in this starter.
Before the final run, do you expect the pinned but unused libraries to change the two Serial messages?
- Restart the Wokwi simulation using its play control.
You should still see Greenhouse vent simulator ready followed by an ESP32 core version beginning with 3. Your toolchain plus starter project are working together.
Readiness line missing?
- Compare the Wokwi sketch.ino tab with the full-code reference above.
- Confirm the Serial Monitor is visible while the simulation runs.
Help me find the missing Serial output.
Your local starter plus browser tools are ready for the greenhouse circuit. Next, you will add the virtual temperature sensor and watch its readings change.
Read the Greenhouse Temperature
Your Wokwi ESP32 simulation can boot successfully. It still cannot observe the greenhouse conditions.
A greenhouse controller needs sensor input before it can make useful decisions. You will add a virtual DHT22 that reports changing temperature readings through the Serial Monitor.
In this step, get ready to:
- Ask Claude Code to add sensor input to the existing project files.
- Connect the virtual temperature sensor to the simulated circuit.
- Verify that the reported temperature follows the sensor slider.
Ask Claude Code to add the sensor
The sensor update touches the virtual circuit plus the Arduino program. Claude Code can update both local files from one set of requirements.
- Switch back to the Claude Code session for the greenhouse-vent-simulator folder from the previous step.
- Paste this prompt into Claude Code:
Update my existing Wokwi project to add its first input.
In diagram.json:
- Add one wokwi-dht22.
- Connect VCC to ESP32 3V3.
- Connect GND to ESP32 GND.1.
- Connect SDA to ESP32 D15.
- Set the starting temperature to 24 and humidity to 40.
In sketch.ino:
- Include DHTesp.h.
- Create a DHTesp object on GPIO 15 configured as DHTesp::DHT22.
- Read with getTempAndHumidity() no faster than once every 2000 ms.
- Print one line in this shape: Temperature: 24.0 C | Humidity: 40.0 %
- If a read fails, print the DHT status string.
- Keep the ESP core version output.
Do not add a servo, automation, WiFi, or Telegram yet. Explain DHT22, GPIO, and Serial Monitor in one plain sentence each after editing the files.
What does this prompt ask for?
- The circuit requirements add one sensor with a starting temperature of 24.
- The program requirements read the sensor through GPIO 15.
- The timing requirement protects the DHT22 by leaving at least 2000 ms between readings.
- The scope limits keep the project focused on sensor input.
- Submit the prompt in Claude Code.
- Review Claude Code's summary after the file edits finish.
The summary should name changes to diagram.json plus sketch.ino. It should leave libraries.txt unchanged.
Did Claude change the wrong files?
Check that Claude Code is working inside the existing greenhouse-vent-simulator folder. Resubmit the same prompt if its summary mentions a new project folder.
Ask for help with the unexpected edits: help me compare Claude Code's edits with the sensor requirements
Copy and run the sensor update
The local files now describe the sensor. Wokwi needs the same circuit plus program before the simulation can read it.
- Stop the running simulation in Wokwi.
- Select the diagram.json tab.
- Replace its entire contents with this circuit definition:
{
"version": 1,
"author": "NextWork learner",
"editor": "wokwi",
"parts": [
{"type":"wokwi-esp32-devkit-v1","id":"esp","top":0,"left":0,"attrs":{}},
{"type":"wokwi-dht22","id":"dht1","top":-120,"left":250,"attrs":{"temperature":"24","humidity":"40"}}
],
"connections": [
["esp:3V3","dht1:VCC","red",[]],
["esp:GND.1","dht1:GND","black",[]],
["esp:D15","dht1:SDA","green",[]]
],
"dependencies": {}
}
What does this circuit change do?
- The dht1 part represents the virtual DHT22.
- The esp:3V3 connection supplies simulated power.
- The esp:GND.1 connection completes the simulated electrical path.
- The esp:D15 connection carries sensor data to the program.
- Check the Wokwi circuit canvas.
You should see a DHT22 beside the ESP32. Its data connection runs to pin D15.
Do not see the DHT22?
Check that the second object inside parts has the type wokwi-dht22. Also check every brace plus comma against the reference.
Ask for help with the circuit file: help me find the JSON problem hiding my Wokwi DHT22
The circuit now has an input device. The first program chunk defines how the ESP32 stores plus prints each reading.
- Select the sketch.ino tab in Wokwi.
- Replace the top of sketch.ino through the line immediately before void setup() with this code:
#include <Arduino.h>
#include "DHTesp.h"
const int DHT_PIN = 15;
const unsigned long SENSOR_INTERVAL_MS = 2000;
DHTesp dht;
unsigned long lastSensorRead = 0;
void readSensor() {
TempAndHumidity reading = dht.getTempAndHumidity();
if (isnan(reading.temperature) || isnan(reading.humidity)) {
Serial.print("Sensor error: ");
Serial.println(dht.getStatusString());
return;
}
Serial.print("Temperature: ");
Serial.print(reading.temperature, 1);
Serial.print(" C | Humidity: ");
Serial.print(reading.humidity, 1);
Serial.println(" %");
}
What does this code do?
- DHTesp.h provides the sensor-reading functions used by the sketch.
- DHT_PIN matches the D15 circuit connection.
- SENSOR_INTERVAL_MS sets a two-second gap between readings.
- readSensor() prints one formatted reading or a sensor status string.
- Start the Wokwi simulation to compile the updated sketch.
You should still see Greenhouse vent simulator ready plus the ESP32 core version. This confirms that the sensor-reading function compiles with the existing starter.
Does the updated sketch fail to compile?
Check the spelling and capitalization of DHTesp.h. Confirm that the existing DHT sensor library remains listed in Wokwi's Library Manager.
Ask for help with the compile failure: help me debug the DHTesp compile problem in this sketch
The final program chunk configures the DHT22. It also schedules each reading without blocking the rest of the loop.
- Stop the Wokwi simulation.
- Replace the existing setup() plus loop() with this code:
void setup() {
Serial.begin(115200);
Serial.println("Greenhouse vent simulator ready");
Serial.print("ESP32 core version: ");
Serial.println(ESP.getCoreVersion());
dht.setup(DHT_PIN, DHTesp::DHT22);
}
void loop() {
unsigned long now = millis();
if (now - lastSensorRead >= SENSOR_INTERVAL_MS) {
lastSensorRead = now;
readSensor();
}
delay(10);
}
How does the reading schedule work?
- dht.setup() configures the device on DHT_PIN as a DHT22.
- millis() measures elapsed time since the simulation started.
- lastSensorRead records when the previous reading happened.
- The interval check calls readSensor() no faster than once every two seconds.
Before you start the simulation, what values do you expect from a sensor configured to begin at 24 plus 40?
- Start the Wokwi simulation.
You should see a new sensor line about once every two seconds. The first lines should report about Temperature: 24.0 C | Humidity: 40.0 %.
That is the sensing loop working. Your simulated greenhouse now produces live environmental data.
Do not see sensor readings?
Confirm that loop() calls readSensor() inside the interval check. Check that the Serial Monitor remains visible while the simulation runs.
Ask for help with the missing readings: help me debug why my Wokwi Serial Monitor does not show DHT22 readings
✔️ Awesome, I've got everything!
Your circuit now includes the DHT22. Make sure the three project files are saved with the contents shown in Wokwi.
ⓧ I'd like to double check the full code
Your diagram.json should match this.
{
"version": 1,
"author": "NextWork learner",
"editor": "wokwi",
"parts": [
{"type":"wokwi-esp32-devkit-v1","id":"esp","top":0,"left":0,"attrs":{}},
{"type":"wokwi-dht22","id":"dht1","top":-120,"left":250,"attrs":{"temperature":"24","humidity":"40"}}
],
"connections": [
["esp:3V3","dht1:VCC","red",[]],
["esp:GND.1","dht1:GND","black",[]],
["esp:D15","dht1:SDA","green",[]]
],
"dependencies": {}
}
Your libraries.txt should remain unchanged.
DHT sensor library for ESPx@1.19
ArduinoJson@7.4.3
Your sketch.ino should match this.
#include <Arduino.h>
#include "DHTesp.h"
const int DHT_PIN = 15;
const unsigned long SENSOR_INTERVAL_MS = 2000;
DHTesp dht;
unsigned long lastSensorRead = 0;
void readSensor() {
TempAndHumidity reading = dht.getTempAndHumidity();
if (isnan(reading.temperature) || isnan(reading.humidity)) {
Serial.print("Sensor error: ");
Serial.println(dht.getStatusString());
return;
}
Serial.print("Temperature: ");
Serial.print(reading.temperature, 1);
Serial.print(" C | Humidity: ");
Serial.print(reading.humidity, 1);
Serial.println(" %");
}
void setup() {
Serial.begin(115200);
Serial.println("Greenhouse vent simulator ready");
Serial.print("ESP32 core version: ");
Serial.println(ESP.getCoreVersion());
dht.setup(DHT_PIN, DHTesp::DHT22);
}
void loop() {
unsigned long now = millis();
if (now - lastSensorRead >= SENSOR_INTERVAL_MS) {
lastSensorRead = now;
readSensor();
}
delay(10);
}
Change the greenhouse conditions
The virtual sensor lets you change the greenhouse conditions while the program runs. The next reading proves that the ESP32 responds to the simulated environment.
Before you move the temperature slider, what value do you expect the next sensor line to report?
- Keep the Wokwi simulation running.
- Click the virtual DHT22 on the circuit canvas.
- Move its temperature slider to 31.
- Wait for the next sensor reading in the Serial Monitor.
You should see the next sensor line change to about 31.0 C. The humidity should remain near its configured value.
You have closed the loop between a changing greenhouse condition and the controller's live reading. The ESP32 can now observe the heat it needs to respond to.
Does the reading stay at 24.0 C?
Confirm that you changed the temperature slider on the running DHT22. Wait for the next two-second reading after releasing the slider.
Ask for help with the unchanged value: help me debug why the Wokwi DHT22 temperature stays at 24.0 C
Your greenhouse can now sense a temperature change. Next, you will add a vent that moves when you send a manual command.
Move the Vent Manually
Your Wokwi ESP32 can now observe the greenhouse through its DHT22 sensor. The next piece is a vent that responds to your commands.
Manual control lets you prove that the servo moves to known angles. A high temperature reading then exposes the limitation of relying on manual commands.
In this step, get ready to:
- Ask Claude Code to add a virtual servo with manual Serial commands.
- Open and close the vent while confirming its angle and reported state.
- Raise the temperature to reveal what manual control cannot do by itself.
Ask Claude Code to add manual control
The next prompt gives Claude Code exact wiring rules and control behavior. These boundaries preserve the working sensor while adding one actuator.
- Switch back to the authenticated Claude Code session from earlier.
- Paste the following prompt into Claude Code:
Update the working Wokwi greenhouse project with a manually controlled vent.
In diagram.json:
- Add one wokwi-servo.
- Connect PWM to ESP32 D18.
- Connect V+ to ESP32 VIN for simulation only.
- Connect GND to ESP32 GND.2.
In sketch.ino:
- Do not add a servo library.
- Use Arduino-ESP32 Core 3 LEDC with ledcAttach on GPIO 18 at 50 Hz and 16-bit resolution.
- Create writeServoAngle() that maps 0 to 180 degrees into 544 to 2400 microseconds within a 20000 microsecond period, then calls ledcWrite.
- Treat 0 degrees as CLOSED and 90 degrees as OPEN.
- Add nonblocking Serial input commands: open, close, and status.
- open and close must set MANUAL mode, move only when the requested state differs, and print the angle, vent state, and mode.
- status must print temperature, humidity, vent state, and mode.
- Keep printing sensor readings, but do not let temperature move the servo yet.
After editing, explain PWM, servo angle, and manual mode in plain language. Also state that powering the simulated servo from VIN is not the wiring plan for the later physical motor.
What is Claude adding?
- The virtual servo turns pulse timing into a visible angle. This timing technique is called PWM.
- The writeServoAngle() function converts an angle into a servo pulse before calling ledcWrite.
- The open and close commands move the vent only when its current state differs from the requested state.
- The status command combines the latest sensor values with the vent state and manual mode.
- Review Claude Code's summary for changes to sketch.ino and diagram.json.
You should see that Claude Code added servo1 on pin D18 plus the three Serial commands. Good progress. Your project now has an actuator layer ready for simulation.
Claude did not update both files?
Check that Claude Code is still working in the folder containing sketch.ino and diagram.json. Paste the prompt again after switching to that folder.
Help me check why Claude Code did not update both greenhouse project files.
Prove manual control works
The virtual servo uses a 50 Hz signal on D18. An angle of 0 represents a closed vent. An angle of 90 represents an open vent.
Keep this wiring in the simulator
The VIN connection powers the virtual servo for this simulation only.
A physical vent actuator needs a separate supply sized for its motor. Its driver may also require a shared ground reference.
- Switch back to the Wokwi project from earlier.
- Stop the running simulation from the simulation controls.
- Replace all contents of sketch.ino with Claude Code's updated sketch.ino.
- Replace all contents of diagram.json with Claude Code's updated diagram.json.
- Start the simulation from the simulation controls.
You should see servo1 beside the DHT22. The servo begins at the closed position while temperature readings continue in the Serial Monitor.
Before you send the first command, which angle do you expect the open position to use?
- Enter open in the Serial Monitor input.
You'll see the servo turn to 90 degrees. The Serial Monitor reports Vent moved to 90 degrees. State: OPEN.
- Enter close in the Serial Monitor input.
You'll see the servo return to 0 degrees. The Serial Monitor reports Vent moved to 0 degrees. State: CLOSED.
- Enter status in the Serial Monitor input.
You'll see the latest temperature and humidity. The same line reports Vent: CLOSED and Mode: MANUAL.
Servo not moving?
Check that servo1:PWM connects to esp:D18. Confirm that the Serial Monitor sends each command with a newline.
Help me debug why the Wokwi servo does not move after I enter open or close.
Experience the limitation
The vent is closed in manual mode. Temperature readings can describe the greenhouse, but the current control path only reacts to commands.
Before you raise the temperature, do you think the closed vent will move without another command?
- Click the virtual DHT22 while the simulation is running.
- Set its temperature slider to 31.
- Watch the next sensor reading in the Serial Monitor.
You'll see a temperature of about 31.0 C. You'll also see the servo remain closed at 0 degrees.
Why is this expected?
Manual mode moves the vent only after an open or close command. The sensor reading has no decision rule connected to it.
This shortfall is intentional. You have proved that a working sensor and a working actuator still need control logic between them.
Did the servo move with temperature?
Your current readSensor() function should update the readings without calling moveVent(). Compare your files with the checkpoint below if the servo reacts to temperature.
Help me find why my manual greenhouse vent moves when the temperature changes.
✔️ Awesome, I've got everything!
Your sensor still reports changing conditions. Your manual commands now move the vent between its open and closed positions.
ⓧ I'd like to double check the full code
These are the exact files for this checkpoint.
diagram.json.
{
"version": 1,
"author": "NextWork learner",
"editor": "wokwi",
"parts": [
{"type":"wokwi-esp32-devkit-v1","id":"esp","top":0,"left":0,"attrs":{}},
{"type":"wokwi-dht22","id":"dht1","top":-120,"left":250,"attrs":{"temperature":"24","humidity":"40"}},
{"type":"wokwi-servo","id":"servo1","top":130,"left":250,"attrs":{"horn":"single"}}
],
"connections": [
["esp:3V3","dht1:VCC","red",[]], ["esp:GND.1","dht1:GND","black",[]], ["esp:D15","dht1:SDA","green",[]],
["esp:VIN","servo1:V+","red",[]], ["esp:GND.2","servo1:GND","black",[]], ["esp:D18","servo1:PWM","orange",[]]
],
"dependencies": {}
}
libraries.txt.
DHT sensor library for ESPx@1.19
ArduinoJson@7.4.3
sketch.ino.
#include <Arduino.h>
#include "DHTesp.h"
const int DHT_PIN = 15;
const int SERVO_PIN = 18;
const uint32_t SERVO_FREQUENCY_HZ = 50;
const uint8_t SERVO_RESOLUTION_BITS = 16;
const uint16_t SERVO_PERIOD_US = 20000;
const uint16_t SERVO_MIN_US = 544;
const uint16_t SERVO_MAX_US = 2400;
const int CLOSED_ANGLE = 0;
const int OPEN_ANGLE = 90;
const unsigned long SENSOR_INTERVAL_MS = 2000;
DHTesp dht;
bool ventOpen = false;
float currentTemperature = NAN;
float currentHumidity = NAN;
unsigned long lastSensorRead = 0;
String serialBuffer;
uint32_t pulseToDuty(uint16_t pulseWidthUs) {
const uint32_t maxDuty = (1UL << SERVO_RESOLUTION_BITS) - 1;
return static_cast<uint32_t>((static_cast<uint64_t>(pulseWidthUs) * maxDuty) / SERVO_PERIOD_US);
}
bool writeServoAngle(int angle) {
angle = constrain(angle, 0, 180);
uint16_t pulseWidthUs = SERVO_MIN_US + (static_cast<uint32_t>(angle) * (SERVO_MAX_US - SERVO_MIN_US)) / 180;
return ledcWrite(SERVO_PIN, pulseToDuty(pulseWidthUs));
}
String ventText() { return ventOpen ? "OPEN" : "CLOSED"; }
String modeText() { return "MANUAL"; }
bool moveVent(bool shouldOpen, const String &reason) {
if (ventOpen == shouldOpen) return false;
int angle = shouldOpen ? OPEN_ANGLE : CLOSED_ANGLE;
if (!writeServoAngle(angle)) return false;
ventOpen = shouldOpen;
Serial.print("Vent moved to ");
Serial.print(angle);
Serial.print(" degrees. State: ");
Serial.println(ventText());
return true;
}
void readSensor() {
TempAndHumidity reading = dht.getTempAndHumidity();
if (isnan(reading.temperature) || isnan(reading.humidity)) {
Serial.println(dht.getStatusString());
return;
}
currentTemperature = reading.temperature;
currentHumidity = reading.humidity;
Serial.printf("Temperature: %.1f C | Humidity: %.1f %%\n", currentTemperature, currentHumidity);
}
void handleCommand(String command) {
command.trim();
command.toLowerCase();
if (command == "open") moveVent(true, "manual open command");
else if (command == "close") moveVent(false, "manual close command");
else if (command == "status") Serial.printf("Temperature: %.1f C | Humidity: %.1f %% | Vent: %s | Mode: MANUAL\n", currentTemperature, currentHumidity, ventText().c_str());
}
void readSerialCommands() {
while (Serial.available() > 0) {
char incoming = static_cast<char>(Serial.read());
if (incoming == '\n') { handleCommand(serialBuffer); serialBuffer = ""; }
else if (incoming != '\r') serialBuffer += incoming;
}
}
void setup() {
Serial.begin(115200);
Serial.println("Greenhouse vent simulator ready");
Serial.print("ESP32 core version: ");
Serial.println(ESP.getCoreVersion());
dht.setup(DHT_PIN, DHTesp::DHT22);
ledcAttach(SERVO_PIN, SERVO_FREQUENCY_HZ, SERVO_RESOLUTION_BITS);
writeServoAngle(CLOSED_ANGLE);
}
void loop() {
unsigned long now = millis();
readSerialCommands();
if (now - lastSensorRead >= SENSOR_INTERVAL_MS) { lastSensorRead = now; readSensor(); }
delay(10);
}
You have proved that the sensor and servo both work. You have also exposed the gap between observing heat and responding to it. Next, you will add automatic control that keeps the vent stable near its thresholds.
Add Stable Automatic Control
Your Wokwi greenhouse now responds to manual commands. However, the servo stays closed when the temperature rises unless you intervene.
A controller that uses one switching temperature can move repeatedly when readings hover near that boundary. Separate opening and closing thresholds create a stable gap.
This pattern is called hysteresis. Claude Code will add it while preserving manual control.
In this step, get ready to:
- Add automatic control with separate opening and closing thresholds.
- Test the complete opening and closing path.
- Challenge the controller with readings inside the hysteresis gap.
Add automatic mode with Claude Code
The existing ventOpen value records the vent's current position. Automatic control can use that memory to preserve the previous state inside the safe temperature gap.
- Return to the authenticated Claude Code session for greenhouse-vent-simulator.
- Give Claude Code the automatic control requirements by pasting this prompt:
Add a stable AUTO mode to the working greenhouse vent simulation.
Requirements:
- Keep MANUAL mode and all existing Serial commands.
- Add Serial commands auto and manual.
- Use an OPEN_THRESHOLD of 28.0 C and a CLOSE_THRESHOLD of 24.0 C.
- In AUTO mode, open only when temperature is greater than 28.0 C and the vent is closed.
- In AUTO mode, close only when temperature is less than 24.0 C and the vent is open.
- Between 24.0 C and 28.0 C, preserve the previous vent state.
- Never issue a second servo movement when the requested state already matches the current state.
- Print the reason after each automatic movement.
- status must include both thresholds.
- Keep the loop nonblocking so Telegram polling can be added later.
After editing, explain threshold and hysteresis in plain language and describe why the 4-degree gap prevents repeated movement.
What does this prompt add?
- The ControlMode values let the controller distinguish manual commands from automatic decisions.
- The OPEN_THRESHOLD value controls when a closed vent can open.
- The CLOSE_THRESHOLD value controls when an open vent can close.
- The applyAutomaticControl() function checks the current mode before requesting movement.
- The existing ventOpen state prevents repeated movement when the vent already matches the request.
- Review Claude Code's summary after it finishes editing sketch.ino.
- Select the complete contents of the updated local sketch.ino file.
- Copy the selected code.
- Switch back to the Wokwi project from earlier.
- Stop the running simulation with the simulator control.
- Replace the contents of the Wokwi sketch.ino tab with the copied code.
- Start the simulation.
You'll see the readiness message followed by temperature readings. The vent begins closed while the controller waits for a command.
Does the updated sketch fail to compile?
Confirm that ControlMode contains both MANUAL and AUTO. Check that applyAutomaticControl() is defined before readSensor() calls it.
Compare the threshold names with OPEN_THRESHOLD and CLOSE_THRESHOLD. C++ identifiers are case-sensitive.
Ask for help with the compilation failure.
Run the full hysteresis path
The first test crosses both thresholds with one reading inside the gap. Each stage reveals whether the controller remembers the vent's previous state.
Before you begin, where do you expect the vent to move during the 30, 26, 22 sequence?
- Enter auto in the Serial Monitor input.
- Click the virtual DHT22 in the running simulation.
- Set the temperature slider to 30.
On the next sensor reading, you'll see the servo turn to 90 degrees. The Serial Monitor reports that the temperature rose above the opening threshold.
- Set the temperature slider to 26.
You'll see the next temperature reading without another movement report. The servo stays open because 26 is inside the hysteresis gap.
- Set the temperature slider to 22.
On the next sensor reading, you'll see the servo return to 0 degrees. The Serial Monitor reports that the temperature fell below the closing threshold.
That is the core controller working. Your vent now opens once in heat, holds its position through the safe gap, then closes once in cooler conditions.
Does the servo move at the wrong temperature?
Check that the opening comparison uses a value greater than OPEN_THRESHOLD. Check that the closing comparison uses a value less than CLOSE_THRESHOLD.
Confirm that readSensor() stores the latest reading before it calls applyAutomaticControl().
Ask for help tracing the automatic decision.
Prove the vent stays stable
The previous sequence leaves the vent closed in AUTO mode. Repeated readings inside the gap should preserve that closed state.
Before you test the gap, do you expect any of these four readings to move the servo?
- Set the temperature slider to 25.
- Set the temperature slider to 27.
- Set the temperature slider to 26.
- Set the temperature slider to 25.
You'll see each temperature reading in the Serial Monitor without a movement report. The servo remains closed throughout the sequence.
- Enter status in the Serial Monitor input.
You'll see AUTO mode with a closed vent. The status also shows an opening threshold of 28.0 C plus a closing threshold of 24.0 C.
✔️ Awesome, I've got everything!
Your automatic controller passed both checks. Make sure the updated sketch.ino file is saved in Claude Code and Wokwi.
ⓧ I'd like to double check the full code
Compare your pre-Telegram sketch.ino with this cumulative version.
#include <Arduino.h>
#include "DHTesp.h"
const int DHT_PIN = 15;
const int SERVO_PIN = 18;
const uint32_t SERVO_FREQUENCY_HZ = 50;
const uint8_t SERVO_RESOLUTION_BITS = 16;
const uint16_t SERVO_PERIOD_US = 20000;
const uint16_t SERVO_MIN_US = 544;
const uint16_t SERVO_MAX_US = 2400;
const int CLOSED_ANGLE = 0;
const int OPEN_ANGLE = 90;
const float OPEN_THRESHOLD = 28.0;
const float CLOSE_THRESHOLD = 24.0;
const unsigned long SENSOR_INTERVAL_MS = 2000;
DHTesp dht;
enum ControlMode {
MANUAL,
AUTO
};
ControlMode controlMode = MANUAL;
bool ventOpen = false;
float currentTemperature = NAN;
float currentHumidity = NAN;
unsigned long lastSensorRead = 0;
String serialBuffer;
uint32_t pulseToDuty(uint16_t pulseWidthUs) {
const uint32_t maxDuty = (1UL << SERVO_RESOLUTION_BITS) - 1;
return static_cast<uint32_t>(
(static_cast<uint64_t>(pulseWidthUs) * maxDuty) / SERVO_PERIOD_US
);
}
bool writeServoAngle(int angle) {
angle = constrain(angle, 0, 180);
uint16_t pulseWidthUs = SERVO_MIN_US +
(static_cast<uint32_t>(angle) * (SERVO_MAX_US - SERVO_MIN_US)) / 180;
return ledcWrite(SERVO_PIN, pulseToDuty(pulseWidthUs));
}
String modeText() {
return controlMode == AUTO ? "AUTO" : "MANUAL";
}
String ventText() {
return ventOpen ? "OPEN" : "CLOSED";
}
String statusMessage() {
String message = "Temperature: ";
message += isnan(currentTemperature) ? "unavailable" : String(currentTemperature, 1) + " C";
message += "\nHumidity: ";
message += isnan(currentHumidity) ? "unavailable" : String(currentHumidity, 1) + " %";
message += "\nVent: " + ventText();
message += "\nMode: " + modeText();
message += "\nOpen above: " + String(OPEN_THRESHOLD, 1) + " C";
message += "\nClose below: " + String(CLOSE_THRESHOLD, 1) + " C";
return message;
}
void printStatus() {
Serial.println("Status");
Serial.println(statusMessage());
}
bool moveVent(bool shouldOpen, const String &reason) {
if (ventOpen == shouldOpen) {
Serial.print("No movement. Vent is already ");
Serial.println(ventText());
return false;
}
int angle = shouldOpen ? OPEN_ANGLE : CLOSED_ANGLE;
if (!writeServoAngle(angle)) {
Serial.println("Servo PWM write failed");
return false;
}
ventOpen = shouldOpen;
Serial.print("Vent moved to ");
Serial.print(angle);
Serial.print(" degrees. State: ");
Serial.print(ventText());
Serial.print(". Mode: ");
Serial.print(modeText());
Serial.print(". Reason: ");
Serial.println(reason);
return true;
}
void applyAutomaticControl() {
if (controlMode != AUTO || isnan(currentTemperature)) {
return;
}
if (!ventOpen && currentTemperature > OPEN_THRESHOLD) {
moveVent(true, "temperature rose above 28 C");
} else if (ventOpen && currentTemperature < CLOSE_THRESHOLD) {
moveVent(false, "temperature fell below 24 C");
}
}
void readSensor() {
TempAndHumidity reading = dht.getTempAndHumidity();
if (isnan(reading.temperature) || isnan(reading.humidity)) {
Serial.print("Sensor error: ");
Serial.println(dht.getStatusString());
return;
}
currentTemperature = reading.temperature;
currentHumidity = reading.humidity;
Serial.print("Temperature: ");
Serial.print(currentTemperature, 1);
Serial.print(" C | Humidity: ");
Serial.print(currentHumidity, 1);
Serial.println(" %");
applyAutomaticControl();
}
void handleCommand(String command) {
command.trim();
command.toLowerCase();
if (command == "status") {
printStatus();
return;
}
if (command == "open") {
controlMode = MANUAL;
moveVent(true, "manual open command");
return;
}
if (command == "close") {
controlMode = MANUAL;
moveVent(false, "manual close command");
return;
}
if (command == "auto") {
controlMode = AUTO;
Serial.println("AUTO mode enabled");
applyAutomaticControl();
return;
}
if (command == "manual") {
controlMode = MANUAL;
Serial.println("MANUAL mode enabled");
return;
}
Serial.print("Unknown command: ");
Serial.println(command);
}
void readSerialCommands() {
while (Serial.available() > 0) {
char incoming = static_cast<char>(Serial.read());
if (incoming == '\n') {
if (serialBuffer.length() > 0) {
handleCommand(serialBuffer);
serialBuffer = "";
}
} else if (incoming != '\r') {
serialBuffer += incoming;
}
}
}
void setup() {
Serial.begin(115200);
Serial.println("Greenhouse vent simulator ready");
Serial.print("ESP32 core version: ");
Serial.println(ESP.getCoreVersion());
dht.setup(DHT_PIN, DHTesp::DHT22);
if (!ledcAttach(SERVO_PIN, SERVO_FREQUENCY_HZ, SERVO_RESOLUTION_BITS)) {
Serial.println("Servo PWM setup failed");
while (true) {
delay(1000);
}
}
writeServoAngle(CLOSED_ANGLE);
}
void loop() {
unsigned long now = millis();
readSerialCommands();
if (now - lastSensorRead >= SENSOR_INTERVAL_MS) {
lastSensorRead = now;
readSensor();
}
delay(10);
}
Your greenhouse now reacts to heat without chattering inside the safe gap. Next, you'll connect this stable controller to an authorized phone.
Control the Vent from Telegram
Your controller now keeps the vent stable across changing temperatures. The next goal is to control that same vent from your phone.
You will use Claude Code to connect the ESP32 simulation to Telegram through HTTPS polling. Authorization will limit commands to your numeric chat ID.
In this step, get ready to:
- Create a temporary Telegram bot and connect the greenhouse simulation.
- Control the vent from an authorized phone and receive automatic movement notifications.
- Record the phone-to-servo proof and revoke the exposed token.
Create a temporary bot and connect the sketch
A Telegram bot receives commands through the Telegram Bot API. Your numeric chat ID identifies the one conversation allowed to operate the vent.
Use a disposable token
A bot token works like a password because anyone holding it can control the bot. This credential will pass through the public Wokwi simulation only long enough to complete the demonstration.
You will replace the token immediately after recording. The public project will finish with a harmless placeholder.
- Return to Telegram on your phone.
- Use Telegram's search field to find @BotFather.
- Select the official @BotFather conversation.
- Send /newbot.
- Follow the prompts to choose a display name and an available username.
- Copy the temporary authentication token when BotFather returns it.
- Switch back to the authenticated Claude Code session from earlier.
- Ask Claude Code to update the existing greenhouse project using every requirement below.
What the Telegram update must include
- Import WiFi.h, NetworkClientSecure.h, HTTPClient.h, and ArduinoJson.h.
- Connect with WiFi.begin("Wokwi-GUEST", "", 6);.
- Define BOT_TOKEN with the placeholder your-bot-token-here.
- Define AUTHORIZED_CHAT_ID as a signed 64-bit integer starting at 0.
- Create a NetworkClientSecure client that calls setInsecure() only for this disposable simulator test.
- Poll getUpdates every 1000 milliseconds with a stored update offset.
- Parse update_id, message.text, and message.chat.id with ArduinoJson.
- Print detected chat IDs without executing commands while AUTHORIZED_CHAT_ID is 0.
- Accept exactly /status, /open, /close, and /auto from the authorized chat.
- Send no reply to any other chat ID.
- Switch /open and /close to manual mode.
- Make /auto enable automatic mode and evaluate the current temperature immediately.
- URL-encode every sendMessage response.
- Notify the authorized chat after each automatic movement with the vent state and temperature.
- Preserve the existing sensor timing, Serial commands, thresholds, and hysteresis behavior.
- Review Claude Code's summary to confirm that it changed only sketch.ino.
- Replace your-bot-token-here in the local BOT_TOKEN constant with the temporary token.
- Copy the updated local sketch.ino into the existing Wokwi sketch tab.
- Start the Wokwi simulation.
The first connection can take a little longer while the simulation compiles and joins the virtual network. You will see the WiFi connection progress in the Serial Monitor.
Before you send the first message, do you think the bot can execute a command while its authorized chat ID is still set to zero?
- Send /status to the temporary bot from your phone.
The Serial Monitor prints a detected numeric chat ID without executing the command. That result proves polling works while authorization still blocks control.
- Record the detected value here: your numeric Telegram chat ID.
- In Wokwi's sketch.ino tab, replace the 0 assigned to AUTHORIZED_CHAT_ID with your numeric Telegram chat ID.
- Restart the Wokwi simulation.
The queued /status update is processed after the restart. You will receive a reply containing the current temperature, humidity, vent state, mode, and thresholds.
No chat ID or reply?
Confirm the simulation reports that it connected to Wokwi's virtual WiFi. Check that the temporary token contains no missing characters or spaces.
If the ID appears but no reply arrives, confirm that AUTHORIZED_CHAT_ID contains the exact number printed in Serial.
Ask for help with the Telegram connection.
Test commands and automatic notifications
The bot now connects a phone command to the same state machine you already tested through Serial. Manual commands override the vent while automatic mode keeps the hysteresis rules active.
- Send /open from your phone.
You will see the servo move to 90 degrees. The Telegram reply reports that the vent is open in manual mode.
- Send /close from your phone.
You will see the servo return to 0 degrees. The reply reports that the vent is closed in manual mode.
- Send /status from your phone.
You will receive the latest temperature, humidity, vent state, mode, and both control thresholds.
- Send /auto from your phone.
The reply confirms automatic mode. The controller immediately evaluates the current temperature.
Before you change the sensor, do you expect each threshold crossing to produce both servo movement and a Telegram notification?
- Click the running DHT22 in Wokwi.
- Set its temperature to 30.
You will see the servo open once. Telegram reports the open state and the temperature that caused the automatic movement.
- Set the DHT22 temperature to 22.
You will see the servo close once. A second Telegram notification reports the closed state and temperature.
Commands work but notifications do not arrive?
Confirm that /auto changed the reported mode to AUTO before you moved the DHT22 slider. Automatic notifications are sent only when a threshold causes the vent state to change.
Ask for help tracing automatic notifications.
Record the proof and revoke the token
The final demonstration needs to show one command traveling from your phone to the simulated vent. Telegram Web provides a synchronized computer view while Wokwi shows the physical effect.
- Arrange the existing Wokwi window beside the existing Telegram Web window.
- Keep the Wokwi code editor hidden so the temporary token cannot appear in the recording.
macOS
- Press Shift+Command+5 to open the Screenshot app controls.
- Choose a screen recording option.
- Start the recording.
Windows
- Press the Windows logo key+Shift+R to open the Snipping Tool recording overlay.
- Select the region containing Wokwi and Telegram Web.
- Start the recording.
Before you send the command, do you expect the phone, Telegram Web, and the servo to show the same action?
- Send /open from your phone.
You will see the command appear in Telegram Web. The authorized reply follows while the Wokwi servo moves to 90 degrees.
- Stop the recording after all three results are visible.
- Return to the @BotFather conversation from earlier.
- Send /token.
- Select the temporary test bot.
- Generate a replacement token.
- Leave the replacement token out of every project file.
Replacing a token is deliberately final for the credential used in Wokwi. Your recording still proves the remote path while the exposed token can no longer control the bot.
- Ask Claude Code to restore these exact constants in the local sketch.ino file:
const String BOT_TOKEN = "your-bot-token-here";
const int64_t AUTHORIZED_CHAT_ID = 0;
Why restore both values?
The placeholder removes the used credential from the saved sketch. Resetting AUTHORIZED_CHAT_ID removes your personal chat identifier from the safe project copy.
Claude Code confirms that the two constants now contain the safe project values.
- Copy the complete local sketch.ino into the existing Wokwi sketch tab.
- Start the Wokwi simulation.
You will see Telegram disabled until the temporary token is added in the Serial Monitor. This confirms the public project contains no usable bot token.
Telegram still starts polling?
Check that BOT_TOKEN contains the exact placeholder from the reference. Confirm that you restarted the simulation after replacing the Wokwi sketch.
Ask for help checking the safe final state.
✔️ Awesome, I've got everything!
Your recording proves the phone-to-servo path. Your local and public project copies now contain no active Telegram credential.
ⓧ I'd like to double check the full code
Compare each project file with the safe final versions below.
#include <Arduino.h>
#include <WiFi.h>
#include <NetworkClientSecure.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include "DHTesp.h"
const int DHT_PIN = 15;
const int SERVO_PIN = 18;
const uint32_t SERVO_FREQUENCY_HZ = 50;
const uint8_t SERVO_RESOLUTION_BITS = 16;
const uint16_t SERVO_PERIOD_US = 20000;
const uint16_t SERVO_MIN_US = 544;
const uint16_t SERVO_MAX_US = 2400;
const int CLOSED_ANGLE = 0;
const int OPEN_ANGLE = 90;
const float OPEN_THRESHOLD = 28.0;
const float CLOSE_THRESHOLD = 24.0;
const unsigned long SENSOR_INTERVAL_MS = 2000;
const unsigned long TELEGRAM_INTERVAL_MS = 1000;
const String BOT_TOKEN = "your-bot-token-here";
const int64_t AUTHORIZED_CHAT_ID = 0;
const String TELEGRAM_API = "https://api.telegram.org/bot";
DHTesp dht;
NetworkClientSecure secureClient;
enum ControlMode {
MANUAL,
AUTO
};
ControlMode controlMode = MANUAL;
bool ventOpen = false;
float currentTemperature = NAN;
float currentHumidity = NAN;
long lastUpdateId = 0;
unsigned long lastSensorRead = 0;
unsigned long lastTelegramPoll = 0;
String serialBuffer;
String chatIdToString(int64_t chatId) {
char buffer[24];
snprintf(buffer, sizeof(buffer), "%lld", static_cast<long long>(chatId));
return String(buffer);
}
String urlEncode(const String &value) {
const char *hex = "0123456789ABCDEF";
String encoded;
for (size_t i = 0; i < value.length(); i++) {
uint8_t c = static_cast<uint8_t>(value[i]);
bool safe = (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
c == '-' || c == '_' || c == '.' || c == '~';
if (safe) {
encoded += static_cast<char>(c);
} else if (c == ' ') {
encoded += "%20";
} else {
encoded += '%';
encoded += hex[(c >> 4) & 0x0F];
encoded += hex[c & 0x0F];
}
}
return encoded;
}
bool botTokenConfigured() {
return BOT_TOKEN.length() > 0 && BOT_TOKEN != "your-bot-token-here";
}
bool authorizedChatConfigured() {
return AUTHORIZED_CHAT_ID != 0;
}
uint32_t pulseToDuty(uint16_t pulseWidthUs) {
const uint32_t maxDuty = (1UL << SERVO_RESOLUTION_BITS) - 1;
return static_cast<uint32_t>(
(static_cast<uint64_t>(pulseWidthUs) * maxDuty) / SERVO_PERIOD_US
);
}
bool writeServoAngle(int angle) {
angle = constrain(angle, 0, 180);
uint16_t pulseWidthUs = SERVO_MIN_US +
(static_cast<uint32_t>(angle) * (SERVO_MAX_US - SERVO_MIN_US)) / 180;
return ledcWrite(SERVO_PIN, pulseToDuty(pulseWidthUs));
}
String modeText() {
return controlMode == AUTO ? "AUTO" : "MANUAL";
}
String ventText() {
return ventOpen ? "OPEN" : "CLOSED";
}
String statusMessage() {
String message = "Temperature: ";
message += isnan(currentTemperature) ? "unavailable" : String(currentTemperature, 1) + " C";
message += "\nHumidity: ";
message += isnan(currentHumidity) ? "unavailable" : String(currentHumidity, 1) + " %";
message += "\nVent: " + ventText();
message += "\nMode: " + modeText();
message += "\nOpen above: " + String(OPEN_THRESHOLD, 1) + " C";
message += "\nClose below: " + String(CLOSE_THRESHOLD, 1) + " C";
return message;
}
void printStatus() {
Serial.println("Status");
Serial.println(statusMessage());
}
bool sendTelegramMessage(const String &message) {
if (!botTokenConfigured() || !authorizedChatConfigured()) {
return false;
}
HTTPClient https;
String url = TELEGRAM_API + BOT_TOKEN + "/sendMessage";
if (!https.begin(secureClient, url)) {
Serial.println("Telegram sendMessage connection failed");
return false;
}
https.addHeader("Content-Type", "application/x-www-form-urlencoded");
String body = "chat_id=" + urlEncode(chatIdToString(AUTHORIZED_CHAT_ID)) +
"&text=" + urlEncode(message);
int httpCode = https.POST(body);
https.end();
if (httpCode < 200 || httpCode >= 300) {
Serial.print("Telegram sendMessage HTTP code: ");
Serial.println(httpCode);
return false;
}
return true;
}
bool moveVent(bool shouldOpen, const String &reason, bool notifyTelegram) {
if (ventOpen == shouldOpen) {
Serial.print("No movement. Vent is already ");
Serial.println(ventText());
return false;
}
int angle = shouldOpen ? OPEN_ANGLE : CLOSED_ANGLE;
if (!writeServoAngle(angle)) {
Serial.println("Servo PWM write failed");
return false;
}
ventOpen = shouldOpen;
Serial.print("Vent moved to ");
Serial.print(angle);
Serial.print(" degrees. State: ");
Serial.print(ventText());
Serial.print(". Mode: ");
Serial.print(modeText());
Serial.print(". Reason: ");
Serial.println(reason);
if (notifyTelegram) {
String notification = "Automatic movement\nVent: " + ventText();
notification += "\nTemperature: " + String(currentTemperature, 1) + " C";
notification += "\nReason: " + reason;
sendTelegramMessage(notification);
}
return true;
}
void applyAutomaticControl() {
if (controlMode != AUTO || isnan(currentTemperature)) {
return;
}
if (!ventOpen && currentTemperature > OPEN_THRESHOLD) {
moveVent(true, "temperature rose above 28 C", true);
} else if (ventOpen && currentTemperature < CLOSE_THRESHOLD) {
moveVent(false, "temperature fell below 24 C", true);
}
}
void readSensor() {
TempAndHumidity reading = dht.getTempAndHumidity();
if (isnan(reading.temperature) || isnan(reading.humidity)) {
Serial.print("Sensor error: ");
Serial.println(dht.getStatusString());
return;
}
currentTemperature = reading.temperature;
currentHumidity = reading.humidity;
Serial.print("Temperature: ");
Serial.print(currentTemperature, 1);
Serial.print(" C | Humidity: ");
Serial.print(currentHumidity, 1);
Serial.println(" %");
applyAutomaticControl();
}
void handleCommand(String command, bool replyToTelegram) {
command.trim();
command.toLowerCase();
if (command == "/status" || command == "status") {
printStatus();
if (replyToTelegram) {
sendTelegramMessage(statusMessage());
}
return;
}
if (command == "/open" || command == "open") {
controlMode = MANUAL;
bool moved = moveVent(true, "manual open command", false);
if (replyToTelegram) {
sendTelegramMessage((moved ? "Vent opened manually.\n" : "Vent was already open.\n") + statusMessage());
}
return;
}
if (command == "/close" || command == "close") {
controlMode = MANUAL;
bool moved = moveVent(false, "manual close command", false);
if (replyToTelegram) {
sendTelegramMessage((moved ? "Vent closed manually.\n" : "Vent was already closed.\n") + statusMessage());
}
return;
}
if (command == "/auto" || command == "auto") {
controlMode = AUTO;
Serial.println("AUTO mode enabled");
if (replyToTelegram) {
sendTelegramMessage("AUTO mode enabled.\n" + statusMessage());
}
applyAutomaticControl();
return;
}
if (command == "manual") {
controlMode = MANUAL;
Serial.println("MANUAL mode enabled");
return;
}
Serial.print("Unknown command: ");
Serial.println(command);
if (replyToTelegram) {
sendTelegramMessage("Supported commands: /status /open /close /auto");
}
}
void pollTelegram() {
if (!botTokenConfigured()) {
return;
}
HTTPClient https;
String url = TELEGRAM_API + BOT_TOKEN + "/getUpdates?offset=" +
String(lastUpdateId + 1) + "&timeout=0";
if (!https.begin(secureClient, url)) {
Serial.println("Telegram getUpdates connection failed");
return;
}
int httpCode = https.GET();
String payload = httpCode == HTTP_CODE_OK ? https.getString() : "";
https.end();
if (httpCode != HTTP_CODE_OK) {
Serial.print("Telegram getUpdates HTTP code: ");
Serial.println(httpCode);
return;
}
JsonDocument document;
DeserializationError error = deserializeJson(document, payload);
if (error) {
Serial.print("Telegram JSON error: ");
Serial.println(error.c_str());
return;
}
JsonArray updates = document["result"].as<JsonArray>();
for (JsonObject update : updates) {
long updateId = update["update_id"].as<long>();
if (updateId > lastUpdateId) {
lastUpdateId = updateId;
}
JsonObject message = update["message"].as<JsonObject>();
if (message.isNull()) {
continue;
}
const char *textValue = message["text"] | "";
String text = String(textValue);
int64_t chatId = message["chat"]["id"].as<int64_t>();
if (!authorizedChatConfigured()) {
Serial.print("Detected Telegram chat ID: ");
Serial.println(chatIdToString(chatId));
continue;
}
if (chatId != AUTHORIZED_CHAT_ID) {
Serial.print("Rejected Telegram chat ID: ");
Serial.println(chatIdToString(chatId));
continue;
}
handleCommand(text, true);
}
}
void readSerialCommands() {
while (Serial.available() > 0) {
char incoming = static_cast<char>(Serial.read());
if (incoming == '\n') {
if (serialBuffer.length() > 0) {
handleCommand(serialBuffer, false);
serialBuffer = "";
}
} else if (incoming != '\r') {
serialBuffer += incoming;
}
}
}
void connectWiFi() {
WiFi.mode(WIFI_STA);
WiFi.begin("Wokwi-GUEST", "", 6);
Serial.print("Connecting to Wokwi-GUEST");
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println(" connected");
}
void setup() {
Serial.begin(115200);
Serial.println("Greenhouse vent simulator ready");
Serial.print("ESP32 core version: ");
Serial.println(ESP.getCoreVersion());
dht.setup(DHT_PIN, DHTesp::DHT22);
if (!ledcAttach(SERVO_PIN, SERVO_FREQUENCY_HZ, SERVO_RESOLUTION_BITS)) {
Serial.println("Servo PWM setup failed");
while (true) {
delay(1000);
}
}
writeServoAngle(CLOSED_ANGLE);
connectWiFi();
// Simulator-only shortcut. Use certificate validation in a production build.
secureClient.setInsecure();
readSensor();
printStatus();
if (!botTokenConfigured()) {
Serial.println("Telegram disabled until the temporary token is added");
} else if (!authorizedChatConfigured()) {
Serial.println("Send /status to the bot to reveal your chat ID in Serial");
} else {
Serial.println("Telegram bot ready for the authorized chat");
}
}
void loop() {
unsigned long now = millis();
readSerialCommands();
if (now - lastSensorRead >= SENSOR_INTERVAL_MS) {
lastSensorRead = now;
readSensor();
}
if (now - lastTelegramPoll >= TELEGRAM_INTERVAL_MS) {
lastTelegramPoll = now;
pollTelegram();
}
delay(10);
}
What should this file contain?
The final sketch preserves the DHT22, servo, manual mode, automatic mode, and hysteresis logic. It adds WiFi connectivity, authorized Telegram polling, URL-encoded replies, duplicate-update protection, and automatic movement notifications.
The saved constants contain the placeholder token and a zero chat ID. This is the safe version to keep after the demonstration.
{
"version": 1,
"author": "NextWork learner",
"editor": "wokwi",
"parts": [
{"type":"wokwi-esp32-devkit-v1","id":"esp","top":0,"left":0,"attrs":{}},
{"type":"wokwi-dht22","id":"dht1","top":-120,"left":250,"attrs":{"temperature":"24","humidity":"40"}},
{"type":"wokwi-servo","id":"servo1","top":130,"left":250,"attrs":{"horn":"single"}}
],
"connections": [
["esp:3V3","dht1:VCC","red",[]],
["esp:GND.1","dht1:GND","black",[]],
["esp:D15","dht1:SDA","green",[]],
["esp:VIN","servo1:V+","red",[]],
["esp:GND.2","servo1:GND","black",[]],
["esp:D18","servo1:PWM","orange",[]]
],
"dependencies": {}
}
What should the circuit contain?
The circuit remains unchanged in this step. The DHT22 stays on GPIO 15 while the servo PWM connection stays on GPIO 18.
DHT sensor library for ESPx@1.19
ArduinoJson@7.4.3
What should the library file contain?
The project keeps the pinned DHT sensor library. ArduinoJson supplies the JSON parsing used by Telegram polling.
That completes the remote path. Your phone controlled the simulated vent while the saved public project finished without a usable credential.
Secret mission
Prove the Vent Cannot Flap
A controller can look stable during a simple temperature change yet fail when readings hover near its thresholds. Replay an adversarial sequence to produce a pass or fail log with exactly one automatic opening and one automatic closing.
Clean Up Your Resources
Clean Up Your Resources
Your only possible recurring project cost comes from Claude Pro. Decide whether to keep your resources running, pause them to come back later, or delete them entirely.
Cost warning
Claude Pro costs $20 when billed monthly, excluding applicable tax.
Wokwi Community costs €0 /mo.
Normal Telegram Bot Platform use adds no project charge.
- Cancel Claude Pro before renewal if you purchased it only for this project.
Resources you used:
- Local greenhouse-vent-simulator folder in your home folder.
- Public Wokwi simulation containing the greenhouse controller.
- Telegram test bot created through @BotFather.
- Phone-to-servo demo recording from your screen recorder.
- Claude Pro subscription if you purchased one for this project.
Keep everything running
No action is needed. Choose this option if you are still testing the greenhouse controller or preparing a physical follow-on.
- Keep the public Wokwi project with BOT_TOKEN set to your-bot-token-here.
- Keep AUTHORIZED_CHAT_ID set to 0 in the safe final project copy.
- Leave the Telegram test bot's replacement token unused.
- Create a fresh disposable token when you run another public simulator test.
- Keep the local greenhouse-vent-simulator folder for future experiments.
- Keep the phone-to-servo demo recording as evidence of the working control path.
- Leave Claude Code installed for future projects.
Pause - I'll come back to this later
Stop the running simulation to free local resources. Your project files remain ready for another session.
- Switch back to the running Wokwi simulation from earlier.
- Stop the simulation using its simulator control.
- Confirm that BOT_TOKEN still contains your-bot-token-here.
- Leave the local greenhouse-vent-simulator folder in your home folder.
- Leave the Telegram test bot idle with its replacement token unused.
- Keep the phone-to-servo demo recording in its saved location.
- Cancel Claude Pro before renewal if you purchased it only for this project.
Delete - I don't want to use this again
Remove the greenhouse project resources if you want a clean slate. Each action below targets an artifact created for this project.
Deletion is permanent
These deletions cannot be undone. Your public Wokwi project already contains no active bot token.
- Switch back to the public Wokwi project from earlier.
- Stop its running simulation.
- Delete the simulation using the deletion control on that project page.
- Reload the former public project link to confirm that the simulation is no longer available.
Bot deletion is permanent
Deleting the Telegram test bot frees its username. The deletion cannot be undone.
- Switch back to the existing @BotFather chat in Telegram.
- Send /deletebot.
- Select the greenhouse test bot when prompted.
- Confirm the bot deletion when prompted.
Protect anything you want to keep
Deleting the local folder removes your controller code plus the completed hysteresis test log. The platform instructions below remove only the greenhouse-vent-simulator folder.
macOS
- Open Finder from the Dock.
- Select your home folder in the Finder sidebar.
- Move the greenhouse-vent-simulator folder to Trash.
- Empty Trash to remove the folder permanently.
- Confirm that greenhouse-vent-simulator no longer appears in your home folder.
Windows
- Open File Explorer from the taskbar.
- Select your user folder in the File Explorer sidebar.
- Move the greenhouse-vent-simulator folder to the Recycle Bin.
- Empty the Recycle Bin to remove the folder permanently.
- Confirm that greenhouse-vent-simulator no longer appears in your user folder.
- Delete the phone-to-servo demo recording from the location where your screen recorder saved it.
- Confirm that the recording no longer appears in its saved folder.
- Return to your Claude account subscription controls.
- Cancel Claude Pro before the next renewal if you no longer need it.
- Confirm that the subscription shows no upcoming Claude Pro renewal.
Nice Work!
Nice Work!
You did it! Your phone-controlled Wokwi greenhouse now responds to changing temperatures.
You've learned how to:
- Built a simulated greenhouse where an ESP32 turns DHT22 readings into visible servo movement.
- Created manual control for direct vent movement. You also created automatic control with separate opening and closing thresholds.
- Connected an authorized Telegram chat to the simulation for remote status checks. Your bot also sends automatic movement notifications.
- Completed the optional Secret Mission by producing a repeatable test log that proves the vent stays stable inside the hysteresis gap.
Ready to quiz yourself?