Community project

Dual H-Bridge Motor Control

Photo of Dual H-Bridge Motor Control

AntoniW-AW

Last updated October 21, 2026

This project builds a bioreaktor controller using an ESP32 to manage a dual H-Bridge motor driver, relay-controlled air compressor, and multiple temperature sensors. The system cycles through mixing, pumping, and resting phases with configurable timing and motor ramp profiles, all controlled via a web interface.

The guide provides a complete wiring diagram connecting the IBT-2 H-Bridge motor driver to the 380/390 brushed DC motor, the relay module to the 12 V compressor, the MAX6675 thermocouple module to a process temperature probe, and the AM2320 humidity sensor to the chamber. Assembly steps cover power distribution from the 12 V supply through the buck converter, firmware configuration for WiFi and sensor calibration, and safe venting of the air path.

Wiring diagram

Wiring diagram for Dual H-Bridge Motor Control
Loading diagram…

Gather all the parts

QtyComponent
1

MAX6675 K-type Thermocouple Module

The small module that converts a K-type thermocouple probe's water temperature into a signal the ESP32 can read.

1

K-type Thermocouple Probe

The metal temperature probe placed in the water so the controller can measure water temperature.

1

2-Channel 5 V Relay Module

The relay board that uses one low-voltage control signal to switch the compressor's 12 V power line.

1

12 V Air Compressor

The 12 V air pump that provides air flow through the water vessel.

1

12 V 5 A DC Power Supply

The external low-voltage supply that powers the compressor and the 5 V converter.

1

Adjustable 12 V to 5 V Buck Converter

The small converter that reduces 12 V to a measured 5 V supply for the ESP32 and relay.

1

AM2320 I2C Temperature & Humidity Sensor

A small sensor that measures the fungi container's air temperature and humidity through four wires.

1

IBT-2 BTS7960 43A High-Current H-Bridge Motor Driver

IBT-2 high-current H-bridge motor driver module built around BTS7960 half-bridge devices. Common modules are sold for 6V-27V motor supplies and 5V logic, with 43A as a module headline rating; practical continuous current depends on board cooling and wiring. Direction and speed are controlled with RPWM/LPWM PWM inputs plus R_EN/L_EN enable lines. Logic-side VCC is separate from the high-power motor supply, and grounds must be common.

1

380/390 Brushed DC Motor

7.4 V

A 7.4 V brushed DC motor that slowly moves the fungi grid back and forth.

Assemble it in 6 steps

1. Keep the air path safely vented

Keep the water jar and grow container vented through suitable filters; do not seal either glass container. Put the metal tip of thermocouple_1 into the water, but keep its cable joint dry.

  • A sealed glass jar can burst when air is pumped into it, causing flying glass and liquid injuries.

2. Wire the permanently connected water probe

Leave thermocouple_1 permanently connected to max6675_1: probe `+` to `T+` and probe `−` to `T−` (water-temperature signal). Connect MAX6675 `VCC` to ESP32 `3V3` (power), `GND` to ESP32 `GND` (ground), `SCK` to GPIO23 (clock), `CS` to GPIO32 (select signal), and `SO` to GPIO33 (temperature data).

  • Only the metal probe tip goes in the water. Keep the MAX6675 board dry outside the container.

3. Wire the chamber air sensor

Place aht20_1, your AM2320 sensor, where it senses chamber air but cannot be splashed or covered by condensation. Connect `VCC` to ESP32 `3V3` (power), `GND` to ESP32 `GND` (ground), `SDA` to GPIO21 (data), and `SCL` to GPIO22 (data timing).

  • Water on the sensor board can cause incorrect readings or damage it.

4. Set the 5 V controller supply

With power disconnected, connect power_supply_12v_1 `+12V` to buck_converter_1 `IN+` (power) and supply `GND` to `IN−` (ground). Adjust and measure `OUT+` at exactly 5.0 V before connecting it to ESP32 `5V` or `VIN` (power), relay_1 `VCC` (power), and motor_driver_hw039_1 `VCC` (logic power). Connect `OUT−` to ESP32 `GND`, relay_1 `GND`, and motor_driver_hw039_1 `GND` (shared ground).

  • Do not connect 12 V directly to the ESP32 5V or 3V pins; it can permanently damage the board.

5. Wire the HW-039 motor controller directly to 12 V

Connect power_supply_12v_1 `+12V` directly to motor_driver_hw039_1 `B+` (motor power) and supply `GND` directly to `B−` (motor ground). Connect `RPWM` to ESP32 GPIO18 (forward speed signal), `LPWM` to GPIO19 (reverse speed signal), `R_EN` to GPIO25 (right-channel enable), and `L_EN` to GPIO26 (left-channel enable). Connect `M+` to grid_motor_380_1 `M+` (motor wire) and `M−` to grid_motor_380_1 `M−` (motor wire).

  • Your working sketch uses 20 kHz PWM. Secure the motor and grid so moving parts cannot catch wires.
  • There is no 12 V-to-7.4 V converter in this build. Before using the mechanism, confirm the motor itself is suitable for the 12 V supplied at HW-039 B+ and B−; PWM reduces average drive but does not change the supply voltage.

6. Wire the compressor relay

Connect relay_1 `VCC` to measured 5 V (power), relay_1 `GND` to ESP32 `GND` (ground), and relay_1 `IN1` to ESP32 GPIO15 (compressor switch signal). Connect supply `+12V` directly to relay_1 `COM1` (incoming switched power), relay_1 `NO1` to compressor_1 `+12V` (power when switched on), and compressor_1 `GND` to supply `GND` (ground).

  • Use `NO1`, not `NC1`, so loss of controller power turns the compressor off.
  • A 5 V relay input connected straight to an ESP32 GPIO can fail to switch or send an unsafe voltage into the ESP32.

Review all connections

1. Connections between "thermocouple_1" and "ESP32"

Functionthermocouple_1ESP32
analog+ → MAX6675 K-type Thermocouple Module T+EXT
analog- → MAX6675 K-type Thermocouple Module T-EXT

2. Connections between "max6675_1" and "ESP32"

Functionmax6675_1ESP32
powerVCC3V3
groundGNDGND
spiSCKGPIO 23
spiCSGPIO 32
spiSOGPIO 33

3. Connections between "aht20_1" and "ESP32"

Functionaht20_1ESP32
powerVCC3V3
groundGNDGND
i2cSDAGPIO 21
i2cSCLGPIO 22

4. Connections between "power_supply_12v_1" and "ESP32"

Functionpower_supply_12v_1ESP32
power+12V → 2-Channel 5 V Relay Module COM1EXT
power+12V → Adjustable 12 V to 5 V Buck Converter IN+EXT
power+12V → IBT-2 BTS7960 43A High-Current H-Bridge Motor Driver B+EXT
groundGND → Adjustable 12 V to 5 V Buck Converter IN-EXT
groundGND → IBT-2 BTS7960 43A High-Current H-Bridge Motor Driver B-EXT

5. Connections between "relay_1" and "ESP32"

Functionrelay_1ESP32
powerVCC5V
groundGNDGND
digitalIN1GPIO 15
powerNO1 → 12 V Air Compressor +12VEXT

6. Connections between "compressor_1" and "ESP32"

Functioncompressor_1ESP32
groundGND → 12 V 5 A DC Power Supply GNDEXT

7. Connections between "buck_converter_1" and "ESP32"

Functionbuck_converter_1ESP32
powerOUT+5V
groundOUT-GND

8. Connections between "motor_driver_hw039_1" and "ESP32"

Functionmotor_driver_hw039_1ESP32
powerVCC5V
groundGNDGND
pwmRPWMGPIO 18
pwmLPWMGPIO 19
digitalR_ENGPIO 25
digitalL_ENGPIO 26
dataM+ → 380/390 Brushed DC Motor M+EXT
dataM- → 380/390 Brushed DC Motor M-EXT

Deploy the firmware

#include <WiFi.h>
#include <WebServer.h>
#include <Preferences.h>
#include <Wire.h>
#include <Adafruit_AM2320.h>
#include <max6675.h>

const char* AP_SSID = "Bioreaktor_WiFi";
const char* AP_PASS = "12345678";
constexpr int R_PWM_PIN=18,L_PWM_PIN=19,R_EN_PIN=25,L_EN_PIN=26;
constexpr int RELAY_PIN=15;
constexpr bool RELAY_ACTIVE_HIGH=false;
constexpr int MAX6675_CLK=23,MAX6675_CS=32,MAX6675_DO=33;
constexpr int I2C_SDA=21,I2C_SCL=22;
constexpr uint32_t PWM_FREQ=20000;
constexpr uint8_t PWM_RESOLUTION=8;
constexpr int STRICT_MAX_MOTOR_PWM=50;
constexpr uint32_t SENSOR_INTERVAL_MS=2000;
WebServer server(80); Preferences prefs; Adafruit_AM2320 am2320; MAX6675 thermocouple(MAX6675_CLK,MAX6675_CS,MAX6675_DO);
struct Config{uint16_t waitSeconds=60,mixSeconds=5,pumpSeconds=15,restSeconds=5;uint8_t startPWM=5,targetPWM=25,rampStep=1;uint16_t rampIntervalMs=200;} cfg;
enum State:uint8_t{STOPPED,WAITING,MOTOR_RAMP_UP_FWD,MOTOR_RUNNING_FWD,MOTOR_RAMP_DOWN_FWD,PUMPING,MOTOR_RAMP_UP_REV,MOTOR_RUNNING_REV,MOTOR_RAMP_DOWN_REV,RESTING,FAULT}; State state=STOPPED;
bool configConfirmed=false,am2320Available=false,thermoAvailable=false,pwmReady=false,cycleRunning=false,pumpRequested=false; float airTemperature=NAN,humidity=NAN,processTemperature=NAN; int currentPWM=0; String faultMessage=""; uint32_t stateStartedAt=0,lastRampAt=0,lastSensorAt=0;
const char* stateName(State s){switch(s){case STOPPED:return "ZATRZYMANY (CZEKA NA START)";case WAITING:return "OCZEKIWANIE W SPOCZYNKU";case MOTOR_RAMP_UP_FWD:return "ROZPĘDZANIE (PRZÓD)";case MOTOR_RUNNING_FWD:return "MIESZANIE (PRZÓD)";case MOTOR_RAMP_DOWN_FWD:return "HAMOWANIE (PRZÓD)";case PUMPING:return "POMPOWANIE & NAPOWIETRZANIE";case MOTOR_RAMP_UP_REV:return "ROZPĘDZANIE (TYŁ)";case MOTOR_RUNNING_REV:return "MIESZANIE (TYŁ)";case MOTOR_RAMP_DOWN_REV:return "HAMOWANIE (TYŁ)";case RESTING:return "PRZERWA MIĘDZYCYKLOWA";case FAULT:return "STAN AWARII";default:return "NIEZNANY";}}
bool elapsed(uint32_t n,uint32_t s,uint32_t i){return(uint32_t)(n-s)>=i;} void setPump(bool on){pumpRequested=on;digitalWrite(RELAY_PIN,(RELAY_ACTIVE_HIGH?on:!on)?HIGH:LOW);} void setMotorPWM(int v,bool rev=false){v=constrain(v,0,STRICT_MAX_MOTOR_PWM);if(!pwmReady){currentPWM=0;return;}ledcWrite(R_PWM_PIN,v&&!rev?v:0);ledcWrite(L_PWM_PIN,v&&rev?v:0);currentPWM=v;} void disableMotorDriver(){if(pwmReady){ledcWrite(R_PWM_PIN,0);ledcWrite(L_PWM_PIN,0);}currentPWM=0;digitalWrite(R_EN_PIN,LOW);digitalWrite(L_EN_PIN,LOW);} void enableMotorDriver(){if(pwmReady){digitalWrite(R_EN_PIN,HIGH);digitalWrite(L_EN_PIN,HIGH);}} void allOutputsOff(){setPump(false);disableMotorDriver();} void enterState(State n){state=n;stateStartedAt=millis();lastRampAt=stateStartedAt;} void triggerFault(const String&r){allOutputsOff();cycleRunning=false;configConfirmed=false;faultMessage=r;enterState(FAULT);}
void updateSensors(){uint32_t now=millis();if(!elapsed(now,lastSensorAt,SENSOR_INTERVAL_MS))return;lastSensorAt=now;double t=thermocouple.readCelsius();if(isnan(t)||t<=0||t>1024){thermoAvailable=false;processTemperature=NAN;}else{thermoAvailable=true;processTemperature=t;}float ta=am2320.readTemperature(),rh=am2320.readHumidity();if(isnan(ta)||isnan(rh)||ta<-40||ta>80||rh<0||rh>100){am2320Available=false;airTemperature=NAN;humidity=NAN;}else{am2320Available=true;airTemperature=ta;humidity=rh;}}
bool configValid(const Config&c){return c.waitSeconds>=1&&c.waitSeconds<=3600&&c.mixSeconds>=1&&c.mixSeconds<=600&&c.pumpSeconds>=1&&c.pumpSeconds<=600&&c.restSeconds<=3600&&c.startPWM>=1&&c.startPWM<=50&&c.targetPWM>=c.startPWM&&c.targetPWM<=50&&c.rampStep>=1&&c.rampStep<=10&&c.rampIntervalMs>=50&&c.rampIntervalMs<=2000;}
void saveConfig(){prefs.begin("bioreaktor",false);prefs.putUShort("wait",cfg.waitSeconds);prefs.putUShort("mix",cfg.mixSeconds);prefs.putUShort("pump",cfg.pumpSeconds);prefs.putUShort("rest",cfg.restSeconds);prefs.putUChar("startPWM",cfg.startPWM);prefs.putUChar("targetPWM",cfg.targetPWM);prefs.putUChar("rampStep",cfg.rampStep);prefs.putUShort("rampMs",cfg.rampIntervalMs);prefs.end();} void loadConfig(){prefs.begin("bioreaktor",true);cfg.waitSeconds=prefs.getUShort("wait",60);cfg.mixSeconds=prefs.getUShort("mix",5);cfg.pumpSeconds=prefs.getUShort("pump",15);cfg.restSeconds=prefs.getUShort("rest",5);cfg.startPWM=prefs.getUChar("startPWM",5);cfg.targetPWM=prefs.getUChar("targetPWM",25);cfg.rampStep=prefs.getUChar("rampStep",1);cfg.rampIntervalMs=prefs.getUShort("rampMs",200);prefs.end();if(!configValid(cfg)){cfg=Config();configConfirmed=false;}}
void startCycle(){if(state==FAULT||cycleRunning||!configConfirmed||!configValid(cfg))return;if(!pwmReady){triggerFault("Inicjalizacja PWM nie powiodla sie");return;}allOutputsOff();enableMotorDriver();cycleRunning=true;currentPWM=0;enterState(WAITING);} void stopCycle(){allOutputsOff();cycleRunning=false;configConfirmed=false;faultMessage="";enterState(STOPPED);} void resetFault(){stopCycle();}
void updateProcedure(){if(!cycleRunning||state==FAULT)return;uint32_t now=millis();int n;switch(state){case WAITING:setPump(false);disableMotorDriver();if(elapsed(now,stateStartedAt,(uint32_t)cfg.waitSeconds*1000UL)){currentPWM=0;enableMotorDriver();enterState(MOTOR_RAMP_UP_FWD);}break;case MOTOR_RAMP_UP_FWD:if(elapsed(now,lastRampAt,cfg.rampIntervalMs)){lastRampAt=now;n=currentPWM==0?cfg.startPWM:currentPWM+cfg.rampStep;if(n>=cfg.targetPWM){setMotorPWM(cfg.targetPWM);enterState(MOTOR_RUNNING_FWD);}else setMotorPWM(n);}break;case MOTOR_RUNNING_FWD:if(elapsed(now,stateStartedAt,(uint32_t)cfg.mixSeconds*1000UL))enterState(MOTOR_RAMP_DOWN_FWD);break;case MOTOR_RAMP_DOWN_FWD:if(elapsed(now,lastRampAt,cfg.rampIntervalMs)){lastRampAt=now;n=currentPWM-cfg.rampStep;if(n<=0){setMotorPWM(0);disableMotorDriver();delay(300);enableMotorDriver();enterState(PUMPING);setPump(true);}else setMotorPWM(n);}break;case PUMPING:setPump(true);if(elapsed(now,stateStartedAt,(uint32_t)cfg.pumpSeconds*1000UL)){setPump(false);enterState(MOTOR_RAMP_UP_REV);}break;case MOTOR_RAMP_UP_REV:if(elapsed(now,lastRampAt,cfg.rampIntervalMs)){lastRampAt=now;n=currentPWM==0?cfg.startPWM:currentPWM+cfg.rampStep;if(n>=cfg.targetPWM){setMotorPWM(cfg.targetPWM,true);enterState(MOTOR_RUNNING_REV);}else setMotorPWM(n,true);}break;case MOTOR_RUNNING_REV:if(elapsed(now,stateStartedAt,(uint32_t)cfg.mixSeconds*1000UL))enterState(MOTOR_RAMP_DOWN_REV);break;case MOTOR_RAMP_DOWN_REV:if(elapsed(now,lastRampAt,cfg.rampIntervalMs)){lastRampAt=now;n=currentPWM-cfg.rampStep;if(n<=0){setMotorPWM(0,true);disableMotorDriver();enterState(RESTING);}else setMotorPWM(n,true);}break;case RESTING:if(elapsed(now,stateStartedAt,(uint32_t)cfg.restSeconds*1000UL))enterState(WAITING);break;default:break;}}
const char PAGE[] PROGMEM=R"HTML(<!doctype html><html lang="pl"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Bioreaktor Grzybowy</title><style>body{font-family:Arial;max-width:720px;margin:auto;padding:14px}section{padding:12px;margin:12px 0;border:1px solid #aaa;border-radius:8px}input{width:100%;padding:8px;box-sizing:border-box}button{padding:10px;margin:4px}</style></head><body><h1>Bioreaktor Grzybowy</h1><section><p>Stan: <b id="state"></b></p><p>Temp. Procesu: <span id="tp"></span> °C</p><p>Temp. Otoczenia: <span id="ta"></span> °C</p><p>Wilgotność: <span id="rh"></span> %</p><p>Aktualny PWM: <span id="pwm"></span></p><p>Pompa: <span id="pump"></span></p><button onclick="cmd('/stop')">STOP</button><button onclick="cmd('/reset')">Reset Awarii</button></section><section><form id="settings"><label>Oczekiwanie (s)</label><input name="wait" type="number" min="1" max="3600" value="60"><label>Mieszanie (s)</label><input name="mix" type="number" min="1" max="600" value="5"><label>Pompa (s)</label><input name="pump" type="number" min="1" max="600" value="15"><label>Przerwa (s)</label><input name="rest" type="number" min="0" max="3600" value="5"><label>Start PWM</label><input name="startPWM" type="number" min="1" max="50" value="5"><label>Docelowy PWM</label><input name="targetPWM" type="number" min="1" max="50" value="25"><label>Krok rampy</label><input name="rampStep" type="number" min="1" max="10" value="1"><label>Rampa ms</label><input name="rampMs" type="number" min="50" max="2000" value="200"><button type="submit">Zapisz Parametry</button></form><button onclick="cmd('/confirm')">Potwierdź konfigurację</button><button onclick="cmd('/start')">URUCHOM CYKL</button></section><script>async function cmd(p){alert(await(await fetch(p,{method:'POST'})).text());refresh()}settings.onsubmit=async e=>{e.preventDefault();alert(await(await fetch('/settings',{method:'POST',body:new URLSearchParams(new FormData(e.target))})).text());refresh()};async function refresh(){let d=await(await fetch('/status')).json();state.textContent=d.state;tp.textContent=d.tp;ta.textContent=d.ta;rh.textContent=d.rh;pwm.textContent=d.pwm;pump.textContent=d.pump?'WŁĄCZONA':'WYŁĄCZONA'}setInterval(refresh,2000);refresh()</script></body></html>)HTML";
void plain(int c,const String&m){server.send(c,"text/plain; charset=utf-8",m);} void status(){String j="{\"state\":\""+String(stateName(state))+"\",\"tp\":\""+(isnan(processTemperature)?String("BRAK ODCZYTU"):String(processTemperature,1))+"\",\"ta\":\""+(isnan(airTemperature)?String("BRAK ODCZYTU"):String(airTemperature,1))+"\",\"rh\":\""+(isnan(humidity)?String("BRAK ODCZYTU"):String(humidity,1))+"\",\"pwm\":"+String(currentPWM)+",\"pump\":"+String(pumpRequested?"true":"false")+"}";server.send(200,"application/json",j);} bool arg(const char*n,uint32_t lo,uint32_t hi,uint32_t&r){if(!server.hasArg(n))return false;String v=server.arg(n);for(size_t i=0;i<v.length();i++)if(!isDigit(v[i]))return false;unsigned long x=v.toInt();if(x<lo||x>hi)return false;r=x;return true;}
void settings(){if(cycleRunning||state==FAULT){plain(409,"Najpierw zatrzymaj procedurę.");return;}Config c;uint32_t n;if(!arg("wait",1,3600,n)){plain(400,"Błąd wait");return;}c.waitSeconds=n;if(!arg("mix",1,600,n)){plain(400,"Błąd mix");return;}c.mixSeconds=n;if(!arg("pump",1,600,n)){plain(400,"Błąd pump");return;}c.pumpSeconds=n;if(!arg("rest",0,3600,n)){plain(400,"Błąd rest");return;}c.restSeconds=n;if(!arg("startPWM",1,50,n)){plain(400,"Błąd startPWM");return;}c.startPWM=n;if(!arg("targetPWM",1,50,n)){plain(400,"Błąd targetPWM");return;}c.targetPWM=n;if(!arg("rampStep",1,10,n)){plain(400,"Błąd rampStep");return;}c.rampStep=n;if(!arg("rampMs",50,2000,n)){plain(400,"Błąd rampMs");return;}c.rampIntervalMs=n;cfg=c;saveConfig();configConfirmed=false;plain(200,"Parametry zapisane. Potwierdź konfigurację.");}
void setup(){Serial.begin(115200);delay(500);pinMode(RELAY_PIN,OUTPUT);setPump(false);pinMode(R_EN_PIN,OUTPUT);pinMode(L_EN_PIN,OUTPUT);digitalWrite(R_EN_PIN,LOW);digitalWrite(L_EN_PIN,LOW);Wire.begin(I2C_SDA,I2C_SCL);delay(300);am2320.begin();pwmReady=ledcAttach(R_PWM_PIN,PWM_FREQ,PWM_RESOLUTION)&&ledcAttach(L_PWM_PIN,PWM_FREQ,PWM_RESOLUTION);if(pwmReady){ledcWrite(R_PWM_PIN,0);ledcWrite(L_PWM_PIN,0);}loadConfig();allOutputsOff();WiFi.mode(WIFI_AP);WiFi.softAP(AP_SSID,AP_PASS);server.on("/",HTTP_GET,[]{server.send_P(200,"text/html",PAGE);});server.on("/status",HTTP_GET,status);server.on("/settings",HTTP_POST,settings);server.on("/confirm",HTTP_POST,[]{configConfirmed=true;plain(200,"Konfiguracja potwierdzona.");});server.on("/start",HTTP_POST,[]{startCycle();plain(cycleRunning?200:409,cycleRunning?"Cykl uruchomiony.":"Nie udało się uruchomić.");});server.on("/stop",HTTP_POST,[]{stopCycle();plain(200,"Cykl zatrzymany.");});server.on("/reset",HTTP_POST,[]{resetFault();plain(200,"Stan zresetowany.");});server.begin();lastSensorAt=millis();enterState(STOPPED);} void loop(){server.handleClient();updateSensors();if(state!=FAULT)updateProcedure();else allOutputsOff();}

Remix this project

Make it yours in one click

Open a full copy of this project in your own Schematik workspace, diagram, code, parts, and assembly steps included. Swap the sensor, add features, or redesign the whole thing with AI. The author's original stays untouched.

Open in Schematik