ESP32-CAM RTSP Streaming: Setup Guide for VLC and NVR

The ESP32-CAM is a cheap way to build a WiFi camera, but the sketch most beginners start with does not speak RTSP. The stock Espressif CameraWebServer example streams MJPEG over HTTP, and that is all it does. If you want VLC, Frigate, Blue Iris, or an NVR to pick the camera up as a standard network camera, you need RTSP, which needs different firmware or a different library.

This guide covers the working routes, the board each one fits, the exact RTSP URL each serves, VLC viewing, Frigate and Home Assistant setup, and expected frame rate. Nothing here needs a paid app or a cloud account.

What is RTSP, and when does it beat MJPEG?

RTSP, Real Time Streaming Protocol, is the standard way network cameras hand video to players and recorders. A client asks for a stream, the two agree on transport settings, and video flows over RTP. VLC, ffmpeg, Frigate, Blue Iris, ZoneMinder, and most NVR software all speak RTSP.

MJPEG over HTTP, the /stream endpoint in the stock CameraWebServer sketch, is simpler: the camera sends one JPEG image after another in a single HTTP response, and any browser can show it. NVR software generally cannot record it, and detection tools cannot consume it directly.

Use RTSP to record footage, run motion or person detection, watch several cameras in one app, or feed the camera into Home Assistant through Frigate or go2rtc. Stick with MJPEG over HTTP for a quick live view in a browser. If you have not set up the board yet, start with our ESP32-CAM getting started guide first.

Which board works for RTSP?

Any ESP32 camera board with PSRAM can run an RTSP server. The classic AI-Thinker style ESP32-CAM has an ESP32 chip with 4 MB PSRAM and an OV2640 camera. The ESP32-S3-N16R8 CAM board runs an ESP32-S3 chip with 8 MB PSRAM and an OV5640 camera, and its two USB-C ports mean no serial adapter is needed. Both boards stream MJPEG video over RTSP, not H.264, which matters for bandwidth and Home Assistant (see the frame rate section).

Pin tables conflict across sources. A wrong camera pin map is the most common reason a build compiles cleanly and shows no video, so verify the pins against your exact board variant before flashing, using that variant’s own documentation.

What are the RTSP setup options?

There is no single official RTSP example from Espressif for the classic ESP32-CAM. The working routes are community firmware and libraries. Pick one row and follow its section.

Approach Best for Boards RTSP URL pattern Code or config needed
esp32cam-rtsp firmware by rzeldent Fastest setup, no code changes ESP32, ESP32-S2, ESP32-S3 camera modules rtsp://IP:554/mjpeg/1 Flash with PlatformIO, configure in a browser
Micro-RTSP library by geeksville Arduino or PlatformIO sketch you control Classic ESP32-CAM (OV2640) rtsp://IP:8554/mjpeg/1 Arduino sketch plus the Micro-RTSP library
Tasmota32 webcam firmware Users who already run Tasmota and want MQTT control Classic ESP32-CAM (AI-Thinker template) rtsp://IP:8554/mjpeg/1 Flash the webcam binary, run one command
ESPHome rtsp_server component ESP32-S3 boards already in ESPHome ESP32 camera boards running ESPHome rtsp://IP:554/ Add two lines to your ESPHome YAML

Sources: esp32cam-rtsp at https://www.esp32.diy/esp32cam-rtsp/ ; Micro-RTSP at https://github.com/geeksville/Micro-RTSP ; circuit.rocks tutorial at https://learn.circuit.rocks/esp32-cam-with-rtsp-video-streaming ; Tasmota guide at https://cgomesu.com/blog/Esp32cam-tasmota-webcam-server/ ; ESPHome docs at https://beta.esphome.io/components/rtsp_server/ .

How do I set up esp32cam-rtsp, the no-code route?

Recommended route for most buyers. The firmware turns the board into an RTSP server, an HTTP MJPEG streamer, and a snapshot endpoint at once, all configured through a web page, with no code changes. Latest release at the time of writing: 1.0.8 (2026-09-29).

  1. Install PlatformIO (VS Code extension or CLI) and clone the project: git clone https://github.com/rzeldent/esp32cam-rtsp.git.
  2. Enter download mode. USB-C boards do this on their own; if an upload fails, hold BOOT, press and release RESET, then release BOOT. On a classic ESP32-CAM, use a 3.3 V USB-to-serial adapter or an ESP32-CAM-MB carrier, and hold GPIO0 low while resetting. 5 V logic damages the board.
  3. Flash your board target, for example pio run -t upload -e esp32cam_ai_thinker for the AI-Thinker board.
  4. On first boot the firmware starts its own WiFi access point. Join it, open the config page shown in the serial monitor, enter your WiFi credentials and camera settings, then save. The board reboots onto your network.
  5. Open VLC and play rtsp://<ip address>:554/mjpeg/1.

The same firmware also serves MJPEG at http://<ip address>/stream and a still at http://<ip address>/snapshot. Turn on RTSP authentication in the web interface if anyone outside your household can reach your network, and never forward port 554 through your router.

How do I set up Micro-RTSP in an Arduino sketch?

Use this route when you want the RTSP server inside your own sketch, for example a camera that also reads sensors or drives outputs. Micro-RTSP is a small RTSP server library implementing RTSP and JPEG-over-RTP, with a reference streamer built for the OV2640 on the classic ESP32-CAM.

  1. Install Micro-RTSP from the ZIP in the circuit.rocks ESP32-RTSP repo, or as a PlatformIO dependency; it is not in the Arduino Library Manager. Full example: https://github.com/circuitrocks/ESP32-RTSP .
  2. Put your WiFi credentials in the sketch’s credentials header before compiling.
  3. Wire the classic ESP32-CAM: 5 V and ground to the header pins, adapter TX to board U0R and RX to U0T, and a button between IO0 and ground. Use a 5 V, 2 A supply; a computer USB port is often not enough.
  4. Hold the download button while powering up or resetting, then upload. The serial monitor at 115200 baud shows the boot message and board IP.
  5. In VLC play rtsp://<ip address>:8554/mjpeg/1. Note the port: 8554, not 554.

The example loop sends a frame about every 100 ms, roughly 10 fps at 800 by 600, per the Micro-RTSP docs for that example. Run only one streaming server at a time; enabling both web and RTSP makes streaming very slow.

How do I enable RTSP on Tasmota?

Use this route only if you already run Tasmota or want its MQTT control and web interface. Flash the tasmota32-webcam firmware, apply the AI-Thinker template, then enable the RTSP server from the Tasmota console:

WcRtsp 1

The stream is then live at rtsp://<device IP>:8554/mjpeg/1. Enable it once; the RTSP server runs independently of the HTTP stream. The Tasmota guide reports VLC is the most reliable viewer. Full steps: https://cgomesu.com/blog/Esp32cam-tasmota-webcam-server/ .

How do I add RTSP to an ESPHome camera?

If your camera already runs ESPHome, add the RTSP server component next to your configured esp32_camera block:

rtsp_server:

That is the whole configuration. The stream is served at rtsp://<device IP>:554/ with no path after the port. Optional settings: port (default 554), max_connections (1 to 4, default 2), and allowed_ips (addresses or networks allowed to connect).

Two facts catch people out. First, the stream is MJPEG over RTSP, and the camera only streams while at least one client is playing. Second, there is no encryption or authentication; allowed_ips filters by address but authenticates nobody, so use it only on a trusted local network. Source: ESPHome RTSP docs.

How do I watch the stream in VLC?

VLC is the best first test for any of the four routes, because its RTSP support is solid and its error messages point at the real problem.

  1. Open VLC, go to Media, then Open Network Stream, or press Ctrl+N.
  2. Paste the RTSP URL for your firmware: port 554 for esp32cam-rtsp and ESPHome, port 8554 for Micro-RTSP and Tasmota. The path is /mjpeg/1 for esp32cam-rtsp, Micro-RTSP, and Tasmota, and the root path / for ESPHome.
  3. Click Play. If the picture appears, the camera, firmware, and network path all work, and any later failure is in the next app, not the camera.

If the video lags by a second or more, the cause is usually VLC network caching, not the camera. VLC buffers network streams at 1000 ms by default. In the stream dialog, click Show more options and lower caching to 300 ms, or to 0 ms for the lowest delay. Zero caching makes the picture more sensitive to WiFi jitter, so on a weak signal keep some caching and fix the signal instead.

How do I add the camera to Home Assistant and Frigate?

Two warnings first, because most tutorials get this part wrong.

Warning one: Home Assistant Generic Camera cannot play this stream. Its pipeline plays only H.264 and HEVC, and every RTSP route in this guide serves MJPEG. The ESPHome docs state this directly. Source: ESPHome RTSP docs.

Warning two: if the camera runs ESPHome, Home Assistant does not need RTSP at all. The ESPHome native API already exposes the camera entity. RTSP is for other software.

The route that works is Frigate, with go2rtc if your Frigate version uses it. Frigate reads the MJPEG RTSP stream with ffmpeg and handles detection and recording. A working Frigate camera entry from the Home Assistant community, using the Tasmota or Micro-RTSP URL:

cameras:
  esp32_cam:
    ffmpeg:
      inputs:
        - path: rtsp://192.168.1.72:8554/mjpeg/1
          roles:
            - detect
            - record
    detect:
      width: 640
      height: 360
      fps: 5

Replace the IP address with your camera IP, and use port 554 with the matching path for esp32cam-rtsp or ESPHome. Keep detection resolution low; community users run 640 by 360 at 5 frames per second. Source: Home Assistant community Frigate thread.

If you only want a live dashboard view, skip RTSP and use the ESPHome native camera entity or the HTTP MJPEG stream. RTSP earns its place when Frigate or an NVR must record or analyze the feed.

What latency and frame rate should I expect?

No source gives one tested frame rate for every board and firmware, so this guide gives no universal number. The numbers below are what named sources measured on their own setups. Your result moves with resolution, JPEG quality, WiFi signal, and client count.

  • ESPHome measured about 5 fps over WiFi and 10 over Ethernet at 640 by 480 on an ESP32-S3 with an OV5640, using its high performance network settings; without them the same test ran at about 1 fps over WiFi. Source: ESPHome RTSP docs.
  • The Micro-RTSP example sends a frame about every 100 ms, roughly 10 fps at 800 by 600 in its own documentation. Source: Micro-RTSP docs.
  • The esp32cam-rtsp project states that resolution and frame rate are bounded by the ESP32 processor and available PSRAM. Source: esp32cam-rtsp project page.

Start at 640 by 480 and raise resolution only after the stream is stable. MJPEG uses more bandwidth than H.264 at the same picture quality, since every frame is a full JPEG. Assume one viewer at a time on a classic ESP32-CAM; ESPHome defaults to two RTSP clients.

What are the common mistakes?

  • Flashing the stock CameraWebServer sketch and expecting RTSP. It serves MJPEG over HTTP only.
  • Using the wrong port. Port 554 belongs to esp32cam-rtsp and ESPHome; port 8554 belongs to Micro-RTSP and Tasmota. The wrong port gives a connection refused error even when the camera runs fine.
  • Using the wrong path. The path is /mjpeg/1 for esp32cam-rtsp, Micro-RTSP, and Tasmota, and the root path / for ESPHome.
  • Powering the classic ESP32-CAM from a weak USB port. The board needs a stable 5 V, 2 A supply. Brownouts during WiFi connection look like firmware bugs and are usually power.
  • Running two streaming servers at once in the Micro-RTSP sketch. The tutorial warns this makes streaming very slow. Pick one.
  • Pointing Home Assistant Generic Camera at an MJPEG RTSP URL. It cannot play it. Use Frigate or go2rtc, or the ESPHome native camera entity.
  • Opening RTSP to the internet. None of these routes is built for that, and ESPHome RTSP has no authentication at all. Keep the camera on your local network.
  • Trusting a pin table from a different board variant. Pin maps conflict across sources. Verify the camera pins against your exact board variant before blaming the firmware.

How do I troubleshoot a stream that will not play?

Work through this list in order; each step rules out one layer.

VLC says “Your input can’t be opened” or times out. Check the board IP in the serial monitor or your router, confirm the camera and computer share a network, and confirm the port and path match your firmware in the table above. Check the router is not isolating WiFi clients (AP isolation) and that no firewall blocks the RTSP port.

VLC connects but shows a black or frozen frame. Drop to 640 by 480 and move closer to the router. The ESP32-CAM is 2.4 GHz only, so a 5 GHz network name will never work.

The stream stutters or drops frames. Lower the resolution and frame rate, disconnect other viewers, and check the power supply, since a marginal 5 V supply causes this under load. In VLC, force RTP over RTSP (TCP) when UDP packets drop.

The camera boots but never joins WiFi. Re-enter the network name and password, watching case and trailing spaces. Check the serial monitor at 115200 baud for connection messages and the assigned IP. A reboot loop usually means power first, then a loose camera ribbon cable.

The camera works in VLC but Frigate reports “Unable to read frames”. Confirm the URL in VLC first, then copy it exactly into Frigate. The common cause is port 554 when the firmware serves on 8554, or an ESPHome web server port, which is HTTP, not RTSP. Source: Home Assistant community thread.

Wrong colors or artifacts. Reseat the camera ribbon cable and lower the resolution.

Parts used in this guide

Prices and stock were verified live on qualityrcparts.com on 2026-11-21 through the public Store API. All three items are in stock and purchasable; the live product page is the current price.

Shipped fast and securely from our secure facility in Queensbury, NY. QRC ships within the USA only.

Related guides

FAQ

Does the ESP32-CAM support RTSP out of the box? No. The stock CameraWebServer example serves MJPEG over HTTP only, with no RTSP server. Add RTSP with esp32cam-rtsp firmware, the Micro-RTSP library, Tasmota webcam firmware, or the ESPHome rtsp_server component. Source: Home Assistant community, Tasmota guide.

What is the RTSP URL for an ESP32-CAM? It depends on the firmware: rtsp://IP:554/mjpeg/1 for esp32cam-rtsp, rtsp://IP:8554/mjpeg/1 for Micro-RTSP and Tasmota, rtsp://IP:554/ for ESPHome. Replace IP with the camera IP from your router or serial monitor. Source: esp32cam-rtsp, Micro-RTSP, Tasmota, and ESPHome docs.

Can I add an ESP32-CAM RTSP stream to Home Assistant? Not through Generic Camera: its pipeline plays only H.264 and HEVC, and ESP32-CAM RTSP serves MJPEG. Feed the stream to Frigate or go2rtc instead, or use the ESPHome native camera entity. Source: ESPHome RTSP docs.

Why does VLC say it cannot open my ESP32-CAM stream? The usual causes are a wrong IP address, the wrong port (554 vs 8554), the wrong path (/mjpeg/1 vs the ESPHome root path), AP isolation, or a firewall blocking the RTSP port. Check the stream in VLC first, then copy that working URL into any other app. Source: Micro-RTSP and circuit.rocks docs.

What frame rate will I get from an ESP32-CAM over RTSP? There is no single tested number. ESPHome measured about 5 fps over WiFi and 10 over Ethernet at 640 by 480 on an ESP32-S3 with an OV5640, and the Micro-RTSP example runs about 10 fps at 800 by 600. Start at 640 by 480. Source: ESPHome and Micro-RTSP docs.

Is RTSP better than MJPEG for an ESP32-CAM? RTSP is better when a recorder, NVR, or detection tool needs the feed, because those tools speak RTSP and generally cannot consume an MJPEG HTTP stream. MJPEG over HTTP is better for a quick live view in a browser. Both carry the same MJPEG video, so RTSP does not improve the picture, it makes the feed usable by more software. Source: ESPHome docs, esp32cam-rtsp page.

Can I view an RTSP stream in a web browser? No, not directly. Browsers do not play RTSP. Use VLC or an NVR app for RTSP, the HTTP MJPEG stream at http://IP/stream for a browser view, or Frigate or go2rtc between the camera and the browser. Source: circuit.rocks docs, esp32cam-rtsp page.

Sources

Last updated: 2026-11-21

Pull-Up Pull-Down Resistors: Why Floating Pins Misbehave

Push button wired to an Arduino input pin with a 10k pull-up resistor

Pull-Up Pull-Down Resistors: Why Floating Pins Misbehave

A floating pin reads randomly because nothing drives it, and the fix is one resistor. A pull-up resistor ties the pin to the supply voltage, so it reads high. A pull-down resistor ties the pin to ground, so it reads low. The value for a button is 10 kOhm, and microcontrollers have a pull-up you can turn on with INPUT_PULLUP.

What is a floating pin?

A digital input pin has a very high input impedance, in the range of hundreds of megaohms, so it draws almost no current and only senses voltage. When nothing is connected to the pin, or when a button connected to it is open, the pin voltage is undefined. That state is called floating. The pin acts like a small antenna: it picks up noise from nearby wires, the mains field and your hand as it approaches, and the reading flips between high and low dozens of times per second.

On an Arduino Uno at 5 V, the ATmega328P treats anything above 3.0 V, or 60 percent of VCC, as a definite high, and anything below 1.5 V, or 30 percent of VCC, as a definite low. The region between 1.5 V and 3.0 V is undefined, and a floating pin wanders through it. The result is an LED that lights without a button press, a counter that increases randomly, or an interrupt that fires constantly. None of that means the board is broken. It means the pin has no default level.

You can see it yourself. Connect a loose jumper wire to digital pin 2 with no button, upload a sketch that prints digitalRead to the serial monitor, and touch the end of the wire. The readings flicker. That flicker is the floating pin picking up your body as an antenna.

Pull-up pull-down resistors: how does a pull-up resistor work?

A pull-up resistor connects the input pin to the supply voltage, VCC, through a resistor, typically 10 kOhm, while the button connects the pin to ground. With the button open, almost no current flows through the pin, so there is no voltage drop across the resistor, and the pin sees VCC, which reads high. When you press the button, the pin connects directly to ground, which reads low. A small current flows through the resistor at that moment: by Ohm law, current equals voltage divided by resistance, so 5 V divided by 10 kOhm is 0.5 mA.

The resistor also prevents a short circuit. If you connected the pin directly to VCC instead of through a resistor, pressing the button would short the supply to ground. The resistor limits that current to 0.5 mA, which is safe. A pull-up makes the logic active low: released reads high, pressed reads low. That trips beginners up at first, but it is the most common arrangement, because most microcontrollers have built in pull-ups and a button to ground is the simplest wiring.

How does a pull-down resistor work?

A pull-down resistor is the mirror image. The resistor connects the pin to ground, and the button connects the pin to VCC. With the button open, the pin is tied to ground through the resistor and reads low. When you press the button, the pin connects directly to VCC and reads high. The same 10 kOhm value applies, and the same 0.5 mA flows while the button is held at 5 V.

Pull-down logic is active high: released reads low, pressed reads high. That reads more naturally in code, because pressed equals true. The trade off is that most microcontrollers have built in pull-ups but no built in pull-downs, so a pull-down usually needs an external resistor, while a pull-up often needs only one line of code. The ESP32 is an exception: most of its GPIO pins have both internal pull-ups and internal pull-downs.

Why is 10 kOhm the standard value?

The value is a trade off between current waste and noise rejection. Too low a value wastes current: a 100 Ohm pull-up at 5 V draws 50 mA while the button is held, which is wasteful and can exceed the resistor rating. Too high a value is too weak: a 1 MOhm pull-up lets noise overcome it, and the pin is slow to return to high because of its own capacitance. The range of 4.7 kOhm to 10 kOhm is the sweet spot for buttons: 5 V divided by 10 kOhm is 0.5 mA when pressed, and the pull is strong enough to reject noise.

A CMOS input pin draws almost no current, so the pull-up value is set by noise and speed, not by the pin impedance: a stronger pull rejects more noise and pulls the line high faster, at the cost of more current while the button is held. For I2C buses, the value is lower, typically 4.7 kOhm, because the bus must rise fast enough for the clock speed. For a long wire or a noisy environment, use 4.7 kOhm instead of 10 kOhm for a stronger pull.

How do internal pull-ups work?

Most microcontrollers include switchable pull-up resistors inside the chip. On an Arduino, you turn one on with a single line in setup: pinMode with INPUT_PULLUP. The ATmega328P internal pull-up is 20 kOhm to 50 kOhm, which is weaker than an external 10 kOhm resistor but strong enough for a button on a short wire. The ESP32 internal pull-ups are similar, and the ESP32 also offers INPUT_PULLDOWN on most GPIO pins. The Raspberry Pi Pico offers both pull-up and pull-down through its GPIO configuration.

Internal pull-ups have two limits. First, GPIO 34 to 39 on the original ESP32 are input only and have no internal pull resistors at all, so a button on those pins needs an external resistor. Second, a long wire picks up more noise than a weak internal pull-up can reject, so a button at the end of a 3 foot cable needs an external 4.7 kOhm or 10 kOhm resistor. Use the internal pull-up for a button on the breadboard next to the board, and an external resistor for a button on a long cable or in a noisy robot.

What about I2C pull-ups?

I2C needs pull-up resistors on both lines, SDA and SCL, because the bus is open drain: devices pull the line low, and only the resistor pulls it high. Without pull-ups, the bus floats and no device answers. The typical value is 4.7 kOhm to the logic voltage, and many breakout boards include them already. If two boards on the same bus each include pull-ups, the parallel combination halves the resistance, which is usually still fine, but three or more boards with pull-ups can make the pull too strong for a weak device to pull low.

The same rule applies to any open drain signal, including a one wire bus and some interrupt lines. A push pull output, such as a normal GPIO output or an SPI line, does not need a pull-up, because the driver actively drives the line high and low. When in doubt, read the device datasheet: it states whether the output is open drain or push pull, and what pull-up value it expects.

How do you debounce a button?

A mechanical button bounces: its contacts open and close several times in a few milliseconds when pressed, and each bounce looks like a separate press to a fast microcontroller. A pull-up resistor does not fix bounce. Debouncing does, and the simplest fix is a short delay in code: when the pin changes, wait 20 ms to 50 ms and read it again. If it still reads the same value, accept the press.

A hardware debounce uses a capacitor across the button, typically 0.1 uF, which smooths the bounces into one transition. A software debounce is cheaper and more common in Arduino code, and the Bounce2 library implements it cleanly. Debounce after you fix the floating pin: a floating pin with a debounce delay still reads randomly, because the pin never settles.

Code: button with internal pull-up

The sketch below reads a button on digital pin 2 with the internal pull-up, and it prints the state to the serial monitor. It uses the Arduino core and it runs on an Uno, a Nano or an ESP32 with the pin number changed. It was not compiled in this draft, and the compile result is logged as code not compiled in the header.

// Button with internal pull-up, active low
// Wiring: button between digital pin 2 and ground. No external resistor.
const int buttonPin = 2;
const int ledPin = 13;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP); // Enable the internal pull-up resistor
  pinMode(ledPin, OUTPUT);
  Serial.begin(115200);
}

void loop() {
  bool pressed = digitalRead(buttonPin) == LOW; // Pressed reads LOW with a pull-up
  digitalWrite(ledPin, pressed ? HIGH : LOW);
  Serial.println(pressed ? "Pressed" : "Released");
  delay(100);
}

For the UNO pins in these examples, see the Arduino UNO R3 pinout guide.

FAQ

What value resistor do I need for a pull-up?

10 kOhm is the standard value for a button. Use 4.7 kOhm for a stronger pull on a long wire or a noisy environment, and for I2C buses. The range of 4.7 kOhm to 10 kOhm covers most button and sensor work.

Can I use INPUT_PULLUP instead of a resistor?

Yes, for a button on a short wire. The internal pull-up on an Arduino is 20 kOhm to 50 kOhm, which is strong enough for a bench test. Use an external 10 kOhm resistor for a long wire, a noisy environment, or a pin with no internal pull-up, such as GPIO 34 to 39 on the ESP32.

Why does my button read pressed when nobody touches it?

The pin is floating. Nothing drives it when the button is open, so noise flips the reading. Add a pull-up resistor, or enable INPUT_PULLUP, and the pin reads a stable high when released.

Should I use a pull-up or a pull-down?

Use a pull-up when your microcontroller has a built in pull-up, which most do, and when a button to ground is the simplest wiring. Use a pull-down when you need pressed to read high, or when the sensor output is open drain to ground.

Do I need a pull-up on every input pin?

Every input pin that can float needs a default level, either from a pull-up, a pull-down, or a device that always drives it. A pin connected to a sensor output that always drives the line does not need one. A pin connected to a button or a switch always does.

Parts used

ELEGOO UNO R3 Microcontroller Board: the Arduino board used in the button examples. ELEGOO Dupont Jumper Wire Set, 120-Piece: the jumper wires for the breadboard button wiring.

Sources

Last updated: 2026-11-21. Search volume: not verified. Product links use the store short link form with the product ID; confirm the product slug at publish time.

ADC Explained: Resolution, Reference Voltage, and ESP32 Limits

Push button wired to an Arduino input pin with a 10k pull-up resistor

ADC Explained: Resolution, Reference Voltage, and ESP32 Limits

An ADC, or analog to digital converter, turns a voltage into a number. A 12-bit ADC divides its input range into 4,096 steps, numbered 0 to 4,095. A 10-bit ADC divides the range into 1,024 steps, numbered 0 to 1,023. The reference voltage sets the top of that range, and on the ESP32 ADC2 pins stop working while Wi-Fi runs.

ADC explained: what is an ADC?

An ADC measures a voltage on a pin and returns a digital number. The number is proportional to the input voltage divided by the reference voltage, times the number of steps. A sensor that outputs a voltage, such as a temperature sensor, a light sensor or a potentiometer, needs an ADC to turn its signal into a number your code can use. A sensor that outputs a digital signal, such as an I2C temperature sensor, does not need an ADC, because the sensor chip does the conversion itself.

Most microcontroller ADCs use successive approximation, or SAR. The ADC samples the pin voltage, compares it against an internal reference in a series of steps, and writes a digital value. The conversion takes microseconds, and the result is a single number per read. That number is not a voltage until your code converts it, using the resolution and the reference voltage.

What is resolution and why does it matter?

Resolution is the number of bits in the ADC result, and it decides the smallest voltage change the ADC can see. A 10-bit ADC has 1,024 steps. A 12-bit ADC has 4,096 steps. On a 3.3 V range, a 10-bit step is 3.3 V divided by 1,024, or about 3.22 mV per step. A 12-bit step is 3.3 V divided by 4,096, or about 0.81 mV per step. The 12-bit ADC sees a change four times smaller than the 10-bit ADC.

ADC resolution (bits) Steps (count) Step size on 3.3 V (mV) Boards
10 1,024 3.22 Arduino Uno, Nano, ESP8266
12 4,096 0.81 ESP32, ESP32-S3, Raspberry Pi Pico, RP2040

More bits do not always mean more accuracy. The ESP32 ADC is 12-bit, but its effective resolution is about 10 to 11 bits, because noise and nonlinearity eat the last bits. Averaging 16 to 64 readings gives a steadier result than chasing the last bit of a single read. A 10-bit ADC on an Arduino Uno with a clean supply and a short wire can beat a noisy 12-bit reading on a long wire next to a Wi-Fi antenna.

What is reference voltage?

The reference voltage is the voltage that maps to the top ADC value. On an Arduino Uno, the default reference is the 5 V supply, so a 5 V input reads 1,023 and a 2.5 V input reads about 511. On the Raspberry Pi Pico, the reference is 3.3 V, so a 3.3 V input reads 4,095. On the ESP32, the reference voltage is about 1.1 V at the ADC itself, not 3.3 V, and the chip applies attenuation to scale the input before it reaches the ADC.

That ESP32 detail causes the most confusion. A 3.3 V signal on an ESP32 ADC pin does not damage the pin, because the attenuation scales it down before the converter, but the raw reading does not map linearly to 3.3 V without the attenuation setting. Use analogReadMilliVolts on the ESP32 Arduino core, which applies the factory calibration and returns millivolts, instead of converting the raw count yourself with a 3.3 V assumption.

What is attenuation on the ESP32?

Attenuation reduces the input voltage before it reaches the ADC, which widens the measurable range. The ESP32 Arduino core offers four settings: 0 dB, 2.5 dB, 6 dB and 11 dB. At 0 dB, the measurable range is about 0 mV to 950 mV. At 2.5 dB, it is about 100 mV to 1,250 mV. At 6 dB, it is about 150 mV to 1,750 mV. At 11 dB, it is about 150 mV to 2,450 mV, which is the widest range and the default in the Arduino core.

Set the attenuation per pin for your sensor range. A sensor that outputs 0 V to 1 V needs 2.5 dB attenuation. A sensor that outputs 0 V to 3.3 V needs 11 dB attenuation, and even then the top of the range saturates at about 3.1 V. The ESP32 ADC is also nonlinear near the ends of its range, so readings near 0 mV and near the top are compressed. For a battery voltage measurement, use a voltage divider that keeps the ADC input in the middle of its range, and average many readings.

Why does ADC2 stop working with Wi-Fi on the ESP32?

The original ESP32 has two ADC units. ADC1 has 8 channels on GPIO 32 to 39. ADC2 has 10 channels on GPIO 0, 2, 4, 12 to 15 and 25 to 27. The Wi-Fi driver uses ADC2 internally, so ADC2 cannot be read while Wi-Fi is active. The Espressif ESP-IDF ADC guide states this directly: the application can only use ADC2 when the Wi-Fi driver has not started, and a read on ADC2 fails between Wi-Fi start and Wi-Fi stop.

The symptom is a sensor that reads correctly before WiFi.begin and returns zero or a stale value after the connection starts. The fix is to move the sensor to an ADC1 pin, GPIO 32 to 39. Remember that GPIO 34 to 39 are input only, so they read a sensor but cannot drive an output. The S3 also restricts ADC2 while Wi-Fi runs. The C3 has only one ADC unit, so it has no ADC2 conflict at all. Check the ADC section of your chip datasheet before you wire a sensor.

Some ADC2 pins carry extra traps. GPIO 0, 2 and 15 are strapping pins, so a sensor on those pins can stop the board from booting. On the ESP32 DevKitC, GPIO 0 cannot be used freely because of the auto program circuit. Prefer ADC1 pins for any sensor in a Wi-Fi project, and keep ADC2 for projects with no Wi-Fi at all.

How do Arduino, ESP32 and Pico ADCs compare?

Spec (unit) Arduino Uno ATmega328P ESP32 Raspberry Pi Pico RP2040
Resolution (bits) 10 12 12
Steps (count) 1,024 4,096 4,096
ADC channels (count) 6 on DIP, 8 on TQFP 18 across two units 4 external plus temperature
Reference voltage (V) 5, supply by default About 1.1 before attenuation 3.3
Max sample rate About 10 ksps Up to 2 Msps with DMA 500 ksps
Wi-Fi conflict None ADC2 blocked by Wi-Fi None on base Pico

The Pico ADC is the simplest to use: a 3.3 V reference, 12-bit resolution, and no Wi-Fi conflict on the base board. The Arduino ADC is the simplest to understand: a 5 V reference and a direct count to voltage conversion. The ESP32 ADC is the most capable and the most confusing, because of its attenuation settings and its ADC2 conflict, so read the ADC section of the ESP-IDF guide before you trust a reading.

How do you get an accurate reading?

Follow five steps. First, pick an ADC1 pin on the ESP32, or any ADC pin on the Pico or Arduino. Second, set the attenuation for your sensor range on the ESP32, or set the reference on the Arduino. Third, keep the wires short and add a 0.1 uF capacitor from the ADC pin to ground to filter noise. Fourth, average 16 to 64 readings instead of trusting one. Fifth, use the calibrated millivolt function where the core provides one, such as analogReadMilliVolts on the ESP32, instead of converting the raw count with an assumed reference.

Never exceed the ADC input voltage. On the ESP32, the pin tolerates 3.3 V, but the measurable range tops out near 3.1 V at 11 dB attenuation. On the Pico, the pin tolerates 3.3 V and the ADC input must stay below the 3.3 V supply plus a small margin. On the Arduino Uno, the pin tolerates 5 V. A sensor that outputs more than the ADC range needs a voltage divider, and the divider ratio must be included in your conversion math.

Code: read an ESP32 ADC pin with averaging

The sketch below reads an ESP32 ADC1 pin with 11 dB attenuation and averages 32 readings. It uses the ESP32 Arduino core. It was not compiled in this draft, and the compile result is logged as code not compiled in the header.

// ESP32 ADC read with averaging on an ADC1 pin
// Board: ESP32 DevKit V1. Sensor on GPIO 34, which is ADC1 channel 6.
const int adcPin = 34; // ADC1 only, so Wi-Fi can run at the same time

void setup() {
  Serial.begin(115200);
  analogSetPinAttenuation(adcPin, ADC_11db); // Widest range, about 0 to 3.1 V
  analogReadResolution(12); // 12-bit result, 0 to 4095
}

void loop() {
  long total = 0;
  for (int i = 0; i < 32; i++) {
    total += analogReadMilliVolts(adcPin); // Calibrated millivolts, not raw counts
    delay(2);
  }
  long averageMilliVolts = total / 32;
  Serial.print("Sensor voltage (mV): ");
  Serial.println(averageMilliVolts);
  delay(500);
}

For the Pico ADC pins in this guide, see the Raspberry Pi Pico pinout guide.

FAQ

Why does my ESP32 analogRead return 0 when Wi-Fi is on?

Your sensor is on an ADC2 pin, and the Wi-Fi driver uses ADC2. Move the sensor to an ADC1 pin, GPIO 32 to 39, and the readings return.

Is a 12-bit ADC always better than a 10-bit ADC?

No. A 12-bit ADC has finer steps, but noise and nonlinearity limit its effective resolution to about 10 to 11 bits on the ESP32. A clean 10-bit reading beats a noisy 12-bit reading, so average many samples and keep wires short.

What voltage can I put on an ESP32 ADC pin?

Up to 3.3 V on the pin. The measurable range tops out near 3.1 V at 11 dB attenuation, so a sensor above that needs a voltage divider.

How many ADC pins does the ESP32 have?

18 channels across two ADC units: 8 on ADC1 at GPIO 32 to 39, and 10 on ADC2 at GPIO 0, 2, 4, 12 to 15 and 25 to 27. A 30-pin board exposes 16 of them, because GPIO 37 and 38 are not broken out.

What is the ADC reference voltage on an Arduino Uno?

5 V by default, from the supply. A 5 V input reads 1,023 and a 2.5 V input reads about 511. The reference can be changed to the internal 1.1 V bandgap or an external AREF voltage.

Parts used

ESP32 DevKit V1 Development Board, 30-Pin WROOM-32: the ESP32 board for the ADC examples, with 18 ADC channels. ELEGOO UNO R3 Microcontroller Board: the Arduino board for the 10-bit ADC comparison.

Sources

Last updated: 2026-11-21. Search volume: not verified. Product links use the store short link form with the product ID; confirm the product slug at publish time.

How to Read a Microcontroller Datasheet: Specs That Matter

Microcontroller datasheet open beside an ESP32 board and a Raspberry Pi Pico

How to Read a Microcontroller Datasheet: Specs That Matter

Read a microcontroller datasheet in this order: absolute maximum ratings first, recommended operating conditions second, the pinout and pin function table third, and the electrical characteristics fourth. The single most important distinction is that absolute maximum ratings are stress limits that damage the chip when exceeded, while recommended operating conditions are the values the chip is guaranteed to work at.

Microcontroller datasheet: what is a datasheet and which document do you need?

A datasheet is the manufacturer document that defines a chip: its features, its pinout, its electrical limits, its timing and its package. It is the primary source for every spec in a project, and it outranks tutorials, forum posts and product listings. When two sources disagree, the datasheet wins.

Three documents are often confused. The chip datasheet covers the silicon, such as the ESP32 or the RP2040. The module datasheet covers the module built on that chip, such as the ESP32-WROOM-32, including its antenna and its flash. The board schematic and board guide cover the development board, such as the ESP32 DevKit V1 or the Raspberry Pi Pico, including which chip pins reach the header and which are used by the USB chip or the flash. Chip pins and board pins differ, so read the board document for wiring and the chip datasheet for limits.

Check the revision and the date on the first page. The Espressif ESP32 Series Datasheet is at version 5.3 in the copy checked for this post. The ESP32-C3 Series Datasheet is at version 2.5. The Raspberry Pi RP2040 Datasheet is at build date 2025-02-20, build version 3184e62-clean. The Microchip ATmega328P datasheet is DS40002061B. A revision changes pin functions, current limits and errata, so a tutorial written against an old revision can be wrong for the chip you hold.

What are absolute maximum ratings?

Absolute maximum ratings are the stress limits beyond which the chip can be damaged. They are not operating conditions, and the chip is not guaranteed to work at them. The ATmega328P datasheet, DS40002061B, lists the absolute maximum supply voltage as 6.0 V, the voltage on any pin except RESET as minus 0.5 V to VCC plus 0.5 V, the DC current per I/O pin as 40 mA, and the DC current through the VCC and GND pins as 200 mA. Those numbers describe the point of damage, not a design target.

The recommended operating conditions for the same chip are stricter: the supply voltage is 1.8 V to 5.5 V, and the output voltages are guaranteed only up to 20 mA per pin. Design to 5.5 V and 20 mA, not to 6.0 V and 40 mA. A pin that survives 40 mA for a minute can still degrade, and a design that relies on an absolute maximum rating is a design that fails in the field.

The ESP32 datasheet follows the same pattern. Its GPIO pins are 3.3 V logic and are not 5 V tolerant, so a 5 V signal on an ESP32 GPIO pin exceeds the absolute maximum input voltage and can damage the pin. The RP2040 datasheet lists its I/O voltage range as 1.8 V to 3.3 V, with the same rule: a 5 V signal on a 3.3 V pin is out of spec. Read the absolute maximum input voltage row before you connect any signal, and use a level shifter when the voltages differ.

How do you read the pinout and pin function tables?

Start with the pinout diagram, which shows the physical package and the pin numbers. Then read the pin function table, which lists every pin, its name, its type and its alternate functions. A single GPIO pin on an ESP32 can serve as a digital input, a PWM output, an ADC input, an I2C line, a UART line or a touch input, depending on the configuration. The table tells you which functions each pin supports, and which pins support none of them.

Watch for four traps in the pin table. First, input only pins: GPIO 34 to 39 on the original ESP32 can read a signal but cannot drive one, and they have no internal pull-up or pull-down resistors. Second, strapping pins: GPIO 0, 2 and 15 on the ESP32, and GPIO 0, 2 and 15 on the ESP8266, must sit at specific levels at boot, so a sensor on those pins can stop the board from starting. Third, pins shared with flash memory: on many ESP32 boards, GPIO 6 to 11 connect to the flash chip and are not usable. Fourth, ADC pins shared with Wi-Fi: ADC2 pins on the ESP32 cannot be read while Wi-Fi runs.

On the RP2040, the pin function table shows that all 30 GPIO pins support PIO, and that GPIO 26 to 29 double as the four ADC inputs. On the ATmega328P, the table shows 23 programmable I/O lines, with 6 ADC inputs on the DIP package and 8 on the TQFP package, because ADC6 and ADC7 exist only on the surface mount package. That package difference is the kind of detail that only the datasheet gives you.

What do the electrical characteristics tell you?

The electrical characteristics section lists the numbers your circuit design depends on: input high and low voltage thresholds, output high and low voltages at a given current, input leakage current, pull-up resistor values and supply current in each sleep mode. Two rows matter most for a beginner build: the input high threshold, called VIH, and the input low threshold, called VIL.

On the ATmega328P at 5 V, the datasheet treats anything above 3.0 V, or 60 percent of VCC, as a definite high, and anything below 1.5 V, or 30 percent of VCC, as a definite low. The region between 1.5 V and 3.0 V is undefined, and a floating pin wanders through it. That is why a floating input reads randomly, and why a pull-up or pull-down resistor is needed. The ESP32 and RP2040 have their own VIH and VIL rows, and they differ, so check the row for your chip before you assume a 3.3 V signal is high enough for a 5 V input.

Current limits live in the same section. The ATmega328P guarantees its output voltages only up to 20 mA per pin, with a 200 mA total through the VCC and GND pins, and a 100 mA limit per pin group for sinking current. The ESP32 datasheet lists a recommended maximum of about 12 mA per GPIO pin for a reliable output level, with higher currents allowed only as absolute maximums. The RP2040 datasheet lists a 12 mA drive strength setting per pin. Never drive a motor, a relay or a solenoid directly from a GPIO pin on any of these chips: use a transistor or a driver board.

How do you use the ADC, PWM and peripheral sections?

Each peripheral has its own section with its own limits. The ADC section gives the resolution, the channel count, the reference voltage and the input range. The ESP32 has two 12-bit SAR ADCs with 18 channels, and its reference voltage is about 1.1 V before attenuation. The RP2040 has a 12-bit ADC with 4 external channels plus a temperature sensor, running at up to 500 ksps. The ATmega328P has a 10-bit ADC with 6 or 8 channels, depending on the package.

The PWM section gives the channel count and the resolution. The ESP32 has 16 LEDC channels. The RP2040 has 16 PWM channels in 8 slices. The ATmega328P has 6 PWM channels from its three timers. The UART, SPI and I2C sections give the maximum clock rates and the pin assignments, which decide whether a display or a sensor can run at the speed your project needs.

What is the errata and why should you read it?

The errata, or chip revision document, lists the known bugs in a specific chip revision and the workarounds. The ESP32 has a chip revision guide that documents differences between revision 0, 1 and 3 silicon. A bug that affects your project may already be documented there with a workaround, and a tutorial written before the errata may describe behaviour that no longer applies.

Check the chip revision of your board against the errata before you blame your code. The revision is printed on the chip or reported by the development tools. A project that works on one revision and fails on another is usually an errata issue, not a wiring fault.

Worked example: check a sensor pin before you wire it

Follow these steps for any new sensor. First, open the chip datasheet for your board and find the pin function table. Confirm the pin you plan to use supports the function you need, such as ADC input or I2C. Second, check the absolute maximum ratings for the input voltage on that pin, and confirm your sensor output stays inside it. Third, check whether the pin is a strapping pin, an input only pin or an ADC2 pin that conflicts with Wi-Fi. Fourth, check the board schematic to confirm the pin reaches the header and is not used by the USB chip or the flash. Fifth, wire it and test it on the bench before you solder it.

For one datasheet section in depth, see the ADC explained guide.

FAQ

What is the difference between absolute maximum and recommended ratings?

Absolute maximum ratings are stress limits that damage the chip when exceeded. Recommended operating conditions are the values the chip is guaranteed to work at. Design to the recommended values, never to the absolute maximums.

How much current can a GPIO pin supply?

On the ATmega328P, outputs are guaranteed only up to 20 mA per pin, with 40 mA as the absolute maximum. On the ESP32 and RP2040, plan for about 12 mA per pin. Never drive a motor or relay directly from a GPIO pin.

Where do I find the pinout for my exact board?

Read the board schematic or board guide for your exact board variant, not the chip datasheet alone. Chip pins and board pins differ, because the board uses some chip pins for flash, USB and the power circuit.

Why does the datasheet revision matter?

A revision changes pin functions, current limits and errata. A tutorial written against an old revision can be wrong for the chip you hold, so check the revision on the first page of the datasheet you read.

What is a strapping pin?

A strapping pin is a pin whose level at boot selects a boot mode, such as flash boot or download mode. A sensor on a strapping pin can stop the board from starting, so check the strapping table before you wire a sensor to GPIO 0, 2 or 15 on an ESP32.

Parts used

ESP32 DevKit V1 Development Board, 30-Pin WROOM-32: the ESP32 board used in the worked examples. Raspberry Pi Pico Development Board, 2-Pack: the RP2040 board used in the worked examples.

Sources

Last updated: 2026-11-21. Search volume: not verified. Product links use the store short link form with the product ID; confirm the product slug at publish time.

How Stepper Motors Work: Steps, Coils, and Microstepping

NEMA 17 stepper motor beside a 28BYJ-48 stepper motor and A4988 driver

How Stepper Motors Work: Steps, Coils, and Microstepping

A stepper motor turns in fixed steps instead of spinning freely. A standard NEMA 17 motor has a step angle of 1.8 degrees, so it takes exactly 200 steps to turn one full revolution. Each pulse from the driver moves the rotor one step, so counting pulses tells you exactly how far the shaft has turned, with no encoder.

How stepper motors work: what is a stepper motor?

A stepper motor is a brushless DC motor that divides a full rotation into a fixed number of equal steps. Inside the motor, a stator carries coil windings and a rotor carries a permanent magnet or a toothed iron assembly. When current flows through a pair of stator coils, the magnetic field pulls the rotor into line with the energised coils. When the driver energises the next pair of coils in sequence, the rotor moves one step further round. Keep the coils energised and the motor holds its position firmly, with no brake needed.

A standard NEMA 17 motor has 50 rotor teeth and 4 magnetic field orientations from its two phases, which gives 50 times 4, or 200 steps per revolution. Divide 360 degrees by 200 steps and the step angle is 1.8 degrees. A 0.9 degree motor has 400 steps per revolution and gives finer resolution at the cost of less torque per step.

NEMA 17 describes the mounting face, not the motor performance. NEMA 17 means a 1.7 inch square face, or 42.3 mm square. Two NEMA 17 motors can have very different lengths, torques and currents. Always read the current rating and the holding torque of your exact motor, not just the NEMA size.

How does a stepper differ from a DC motor and a servo?

A DC motor spins freely when power is applied, and its speed depends on voltage and load. It has no built in position, so a robot that needs to know how far a wheel turned must add an encoder. A servo moves to a commanded angle and holds it with a closed loop, but its range is usually limited to 180 degrees. A stepper moves in fixed steps over unlimited rotations, and the step count is the position, so it needs no encoder for open loop positioning.

Spec (unit) DC motor Servo Stepper motor
Motion Continuous rotation Limited angle, usually 180 degrees Fixed steps, unlimited rotation
Position feedback None, add encoder Built in potentiometer None, step count is position
Typical control PWM duty for speed PWM pulse width for angle STEP pulses for distance
Holding torque at rest None without power Holds angle under load Holds position with coils energised
Best for Wheels, fans, pumps Steering, arms, pan tilt 3D printers, CNC, precise positioning

The trade off is speed and efficiency. A stepper draws full current even when it holds still, so it runs hotter and uses more power than a DC motor at rest. A stepper also loses steps when the load exceeds its torque, and because there is no feedback, the controller never knows the steps were lost. Size the motor and the driver for the load with margin, and never trust a stepper position after a stall.

What are unipolar and bipolar steppers?

A unipolar stepper has four coils with centre taps, and it is driven by energising one half of each coil at a time. It has five or six wires, and it is simple to drive with a transistor array such as the ULN2003. The 28BYJ-48 is the common unipolar example: a small 5 V geared stepper with a ULN2003 driver board. Unipolar drive is simple, but it uses only half of each coil at a time, so it gives less torque per size than a bipolar motor.

A bipolar stepper has two coils and four wires, with no centre taps. It is driven by an H-bridge that reverses the current through the full coil, which gives 30 to 40 percent more torque than a unipolar motor of the same size. The NEMA 17 is the common bipolar example, and it needs a bipolar driver such as the A4988 or the TMC2208. Bipolar drive is more complex, but it is the standard for 3D printers and CNC machines, where torque matters.

Identify your motor by its wire count before you buy a driver. Five or six wires means unipolar, and a ULN2003 board is the pick. Four wires means bipolar, and an A4988 board is the pick. A four wire motor on a ULN2003 board does not work, and a five wire motor on an A4988 board does not work either.

How does microstepping work?

Microstepping divides each full step into smaller increments by driving the two coils with different currents at the same time. Instead of switching one coil fully on and the other fully off, the driver sets the two coil currents to intermediate values that hold the rotor between two full step positions. The A4988 supports five resolutions, set by its MS1, MS2 and MS3 pins: full step, 1/2 step, 1/4 step, 1/8 step and 1/16 step.

MS1 MS2 MS3 Resolution Steps per revolution (count)
LOW LOW LOW Full step 200
HIGH LOW LOW 1/2 step 400
LOW HIGH LOW 1/4 step 800
HIGH HIGH LOW 1/8 step 1600
HIGH HIGH HIGH 1/16 step 3200

Microstepping makes motion smoother and quieter, and it reduces resonance at low speeds. It does not increase accuracy by the same factor as the step count, because the intermediate positions depend on the exact coil currents and the load. A 1/16 microstep is finer than a full step, but the holding torque at a microstep is lower than at a full step, and the rotor position at a microstep is less exact under load. Use microstepping for smooth motion, not for a promise of 16 times the precision.

How does the 28BYJ-48 work?

The 28BYJ-48 is a geared unipolar stepper. The inner motor takes 32 full steps per turn, at 11.25 degrees per full step, and a gear train of about 64:1 sits behind it, so the output shaft needs about 2,048 steps for one full turn, from 32 times 64. The datasheet ratio is 64:1, so 2,048 is the nominal figure. Teardown counts of the gear teeth give an exact ratio of 63.68395:1, or 283712/4455, on the units counted, which works out to 2037.9 full steps, or 4075.8 half steps, per output turn. The ratio varies by manufacturer, and some units are a true 64:1, so use 2,048 as the nominal value. Over many turns, the small error adds up, so do not use the 28BYJ-48 for long distance odometry without a home sensor.

The 28BYJ-48 runs on 5 V and it is easy to drive with its ULN2003 board, which takes four logic inputs, IN1 to IN4, from the microcontroller. It is slow, under about 15 RPM, and light on torque, but it is ideal for learning, for clocks, for curtain pullers and for a pan tilt head that moves slowly. The standard Arduino Stepper library drives it with 2,048 steps per revolution, and the pin order matters: the sequence 8, 10, 9, 11 is correct for the common wiring, and 8, 9, 10, 11 makes the motor twitch instead of turning.

How does the A4988 driver work?

The A4988, datasheet 4988-DS Rev. 8, April 5, 2022, is a microstepping driver IC from Allegro MicroSystems for bipolar steppers. It drives motors at up to 2 A per coil with proper cooling, and it supports up to 1/16 microstepping. From the microcontroller it needs only two signal pins: STEP, where one pulse advances the motor one microstep, and DIR, where high or low selects the direction. The EN pin enables or disables the driver, and the MS1 to MS3 pins set the microstep resolution.

Setting the current limit correctly is the most important A4988 job. The driver has a small potentiometer that sets Vref, and the current limit follows the formula Vref equals current times 8 times Rsense. Set Vref to about 80 percent of your motor rated current, fit the heatsink, and never power the board with the motor disconnected, because the driver can fail permanently. The motor supply, VMOT, runs from 8 V to 35 V, and a 100 uF capacitor across VMOT close to the board absorbs current spikes.

The A4988 is the standard driver for a NEMA 17 in a 3D printer or a CNC axis. The TMC2208 is the quieter successor, with StealthChop silent operation, but the A4988 is cheaper and its current setting procedure is the one every tutorial covers.

How do you pick a stepper for a project?

Project type Pick this motor Why
Learning, slow pan tilt, clock 28BYJ-48 plus ULN2003 5 V, simple wiring, cheap, 2,048 steps per turn
3D printer axis, CNC axis NEMA 17 plus A4988 200 steps per turn, 1/16 microstepping, high holding torque
Quiet printer axis NEMA 17 plus TMC2208 StealthChop silent stepping, same 200 step motor
Precise positioning, no feedback NEMA 17, 0.9 degree version 400 steps per turn, finer resolution than 1.8 degree

For the drivers behind the motor signals, see L298N vs TB6612 vs DRV8833: Which Motor Driver for Your Robot.

FAQ

How many steps does a NEMA 17 take per revolution?

200 steps at full step, because its step angle is 1.8 degrees and 360 divided by 1.8 is 200. At 1/16 microstepping, it takes 3,200 microsteps per revolution.

Why does my stepper lose steps?

The load exceeds the motor torque, the speed is too high for the torque curve, or the driver current limit is set too low. Reduce the speed, raise the current limit within the motor rating, or use a larger motor.

Can I drive a stepper directly from a GPIO pin?

No. A stepper coil draws far more current than a GPIO pin supplies. Always use a driver board, such as a ULN2003 for a unipolar motor or an A4988 for a bipolar motor, between the pins and the motor.

Does microstepping increase torque?

No. Microstepping makes motion smoother and quieter, but the holding torque at a microstep is lower than at a full step. Use it for smooth motion, not for more torque.

What is the difference between unipolar and bipolar?

A unipolar motor has centre tapped coils and five or six wires, and it is driven by a ULN2003. A bipolar motor has two coils and four wires, and it is driven by an H-bridge such as the A4988. Bipolar gives more torque per size.

Parts used

28BYJ-48 Stepper Motor 5V plus ULN2003 Driver, 2-Set: the geared unipolar stepper for learning and slow positioning. A4988 Stepper Motor Driver: the bipolar microstepping driver for NEMA 17 motors. Nema 17 Stepper Motor: the bipolar stepper for 3D printer and CNC axes.

Sources

Last updated: 2026-11-21. Search volume: not verified. Product links use the store short link form with the product ID; confirm the product slug at publish time.

ESP32 Battery Sensor Node: Deep Sleep and Power Budget

Battery powered ESP32 sensor node with DHT22 sensor and buck converter

ESP32 Battery Sensor Node: Deep Sleep and Power Budget

This battery sensor node runs an ESP32 on battery by waking it on a timer, reading a DHT22 sensor, and putting it back into deep sleep. The ESP32 chip draws about 10 microamps in deep sleep, against 160 to 240 mA with Wi-Fi transmitting. The board keeps drawing milliamps: the regulator, the USB serial chip, and the power LED.

Quick facts

Item Value
Sleep current, chip About 10 uA in deep sleep, ESP32 Series Datasheet v5.3
Awake current 80 to 160 mA, peaks near 240 mA on Wi-Fi transmit
Wake source RTC timer, every 10 minutes
Sensor DHT22, temperature and humidity
Power Battery pack through an XL4015 buck converter set to 5 V
No solar This build uses battery power only; no solar panel is fitted

Battery sensor node: how does deep sleep save battery?

Deep sleep powers down the main CPUs, the Wi-Fi and Bluetooth radios, and most peripherals. Only the RTC domain stays alive, with its timer and a small block of RTC memory. The chip draws about 10 microamps in that state, against 160 to 240 mA with Wi-Fi transmitting. That is a reduction of about 24,000 times.

Deep sleep is effectively a reboot. When the timer fires, the bootloader runs, the sketch loads from flash again, and setup() starts from the top. Normal variables are lost. Only variables tagged RTC_DATA_ATTR survive, in the 8 KB RTC slow memory, so the sketch keeps its boot count there and does its work in setup().

The pattern is wake, work, sleep. The node wakes every 10 minutes, reads the DHT22, connects to Wi-Fi, sends the reading, and sleeps again. The awake time is a few seconds. The sleep time is 597 seconds. Average current is what decides battery life, and the average is dominated by the few awake seconds, not the long sleep.

Why does a dev board never reach 10 microamps?

The 10 microamp figure is the bare ESP32 chip, from the Espressif ESP32 Series Datasheet v5.3. A DevKit V1 board adds an always-on power LED, a USB to serial chip, and a linear regulator, and each of those draws current around the clock. A typical DevKit V1 measures a few milliamps in deep sleep, not 10 microamps. That is still a large saving over 160 mA awake, but it changes the battery math by a factor of 100.

Measure your own board before you promise battery life. Put a USB power meter inline, or a multimeter on the battery lead, and read the current in deep sleep. Write the number down. Every battery estimate in this post uses a 1 mA planning figure for the whole node, not a measured board value, because no bench measurement of the stocked board exists. Replace the planning figure with your measured value before you promise a battery life.

You can cut the board overhead further by removing the power LED or by using a bare module, but that is a hardware modification and it voids any return. For a first build, measure the board as it ships and size the battery for the measured figure.

How do you work out the battery life?

Average current is the awake share times the awake current, plus the sleep share times the sleep current. Wake for 3 seconds at 150 mA every 600 seconds, and sleep at 1 mA the rest of the time. The awake share is 3 divided by 600, or 0.5 percent. The average is 0.005 times 150 mA plus 1 mA, which is about 1.75 mA.

Divide the battery capacity by the average current to get the life. A 2500 mAh pack at 1.75 mA average lasts about 1400 hours, or about 59 days. That is an estimate, not a promise. Cold weather cuts capacity, the buck converter wastes 10 to 20 percent, and the Wi-Fi connect time varies with signal strength.

The biggest lever is the awake time. Every second of Wi-Fi connect time at 150 mA costs as much as 150 seconds of sleep at 1 mA. Keep the awake work short: read the sensor first, connect, send one small packet, and sleep. Do not wait for a slow server, and do not retry forever. Three tries, then sleep and try again next cycle.

How do you power the node from a battery?

The XL4015 buck converter steps the battery voltage down to a steady 5 V for the ESP32 USB input or the 5 V pin. Set the output to 5 V with a multimeter before you connect the board, and never adjust the trimmer while the board is connected. A wrong turn can send the full battery voltage into the board.

The buck converter itself draws current, even with no load. That quiescent draw joins the sleep current, so measure the whole node, converter included, not the board alone. The XL4015 chip draws 2.1 mA typical and 5 mA maximum quiescent current (XLSEMI datasheet Rev 1.6), and the stocked module adds an LED display that draws more, so a converter that draws 5 mA idle will dominate a node that sleeps at 1 mA. The chip runs from 8 to 36 V in and 1.25 to 32 V out; the module is advertised at 4 to 38 V in, 1.25 to 36 V out, and 5 A. Feed it from a battery inside the module range and set the output to 5 V.

This build uses battery power only. No solar panel is fitted, and no solar claim is made, because no solar panel is stocked for this build. If you add solar later, size the panel for the average current plus the charge controller losses, and test it through a cloudy week before you trust it.

Wiring

Wire the build with the power off. Check every connection in the table before you connect any battery or USB cable.

From To Notes
Battery pack positive XL4015 IN+ Battery input to the buck converter; set the output before connecting the board
Battery pack negative XL4015 IN- and ESP32 GND Common ground
XL4015 OUT+ ESP32 5 V pin or USB 5 V Regulated 5 V output; set to 5.0 V with a multimeter first
XL4015 OUT- ESP32 GND Common ground
DHT22 VCC ESP32 3V3 Module supply 3.3 to 6 V per the Aosong datasheet; the stocked module is a wired 3-wire module (+, -, Out)
DHT22 GND ESP32 GND Common ground
DHT22 DATA ESP32 GPIO 4 Single-wire data; 10 k pull-up resistor between DATA and 3V3 if the module has none

Power budget

The budget below uses a 1 mA planning figure for the sleep current of the whole node, board plus buck converter, because that is the honest planning figure for a DevKit V1 as shipped. It is a planning figure, not a bench measurement: no measured sleep current exists for the stocked board. The chip alone sleeps at about 10 microamps, but the board overhead dominates. Measure your node and redo the math with the measured value.

Awake for 3 seconds at 150 mA every 600 seconds, asleep at 1 mA otherwise, gives an average of about 1.75 mA. A 2500 mAh pack lasts about 59 days at that average, before converter losses and cold weather. Cut the wake interval to 30 minutes and the same pack lasts about 83 days, not 4 months: the awake share falls to one third, but the 1 mA sleep current dominates the average, so tripling the interval only stretches the life by about 40 percent. A slow Wi-Fi join stretches the awake time too: about 13 seconds awake per cycle cuts the same pack to about 25 days.

The DHT22 draws 1 to 1.5 mA while measuring and 40 to 50 uA in standby, per the Aosong datasheet, and the bare sensor pins run VCC, DATA, NC, GND with the grille facing you. Do not read it more often than once every 2 seconds. It is a rounding error next to the Wi-Fi radio. The radio is the cost. Keep the awake time short, send one small packet, and sleep.

Build steps

  1. Set the XL4015 output to 5.0 V with a multimeter, with no board connected. Lock the trimmer and recheck the output.
  2. Wire the battery, the buck converter, and the ESP32 from the wiring table. Wire the DHT22 to GPIO 4 with its pull-up resistor.
  3. Install the Adafruit DHT sensor library and the Adafruit Unified Sensor library from the Library Manager.
  4. Upload the sketch below. Open the serial monitor at 115200 baud and confirm the node reads the DHT22 and prints the boot count.
  5. Measure the deep sleep current with a USB power meter or a multimeter on the battery lead. Record the value and update the battery math in this post.
  6. Leave the node running on battery for 24 hours. Confirm it wakes every 10 minutes and the boot count rises by about 144 per day.
  7. Calculate the battery life from your measured sleep current, not from the 10 microamp chip figure. Replace the planning figure in this post with the measured value.

Code

Libraries: Adafruit DHT sensor library, Adafruit Unified Sensor library. Board: ESP32 DevKit V1. The sketch does its work in setup() because deep sleep restarts the chip on every wake.

// Battery ESP32 sensor node: DHT22 + deep sleep, timer wake
// Board: ESP32 DevKit V1. Libraries: Adafruit DHT sensor library.
#include 
#include 
#include 

#define DHT_PIN 4
#define DHT_TYPE DHT22
#define uS_TO_S 1000000ULL
#define SLEEP_SECONDS 600  // Wake every 10 minutes

const char* WIFI_SSID = "YOUR_WIFI_NAME";      // Replace with your network
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";  // Replace with your password

DHT dht(DHT_PIN, DHT_TYPE);

// RTC memory survives deep sleep; normal variables do not.
RTC_DATA_ATTR int bootCount = 0;

void setup() {
  Serial.begin(115200);
  bootCount++;
  Serial.print("Boot count: ");
  Serial.println(bootCount);

  dht.begin();
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();
  if (isnan(temperature) || isnan(humidity)) {
    Serial.println("DHT22 read failed");
  } else {
    Serial.print("Temp: "); Serial.print(temperature, 1);
    Serial.print(" C, Hum: "); Serial.print(humidity, 1);
    Serial.println(" %");
    // Join Wi-Fi with a bounded wait, then send the reading here:
    // HTTP POST, MQTT, or ESP-NOW. Keep it short: connect, send
    // once, then sleep. A slow join stretches the awake time, so
    // the 10 second cap below keeps one bad cycle from draining
    // the battery.
    WiFi.begin(WIFI_SSID, WIFI_PASS);
    unsigned long wifiStart = millis();
    while (WiFi.status() != WL_CONNECTED && millis() - wifiStart < 10000) {
      delay(500);
    }
  }

  // Arm the RTC timer, then sleep. This call never returns.
  esp_sleep_enable_timer_wakeup(SLEEP_SECONDS * uS_TO_S);
  Serial.println("Going to sleep for 10 minutes");
  Serial.flush();  // Let the text leave before power drops
  esp_deep_sleep_start();
}

void loop() {
  // Never reached: deep sleep restarts the chip from setup().
}

Test and tune it

Confirm the node wakes every 10 minutes by watching the boot count rise by 6 per hour. A count that rises faster means the node is resetting instead of sleeping, usually from a weak battery or a loose wire.

Measure the sleep current with the USB cable unplugged and the battery connected. If the meter reads over 5 mA in sleep, the buck converter quiescent draw or the power LED is the cause. Measure the board alone, then the converter alone, to find which one dominates.

Run the node for a week on battery and log the battery voltage at each wake. A steady fall is normal. A sudden drop means the Wi-Fi connect time grew, usually from a weak signal, so move the node closer to the router.

FAQ

How long will an ESP32 sensor node last on battery?

It depends on the measured sleep current, not the 10 microamp chip figure. At 1.75 mA average, a 2500 mAh pack lasts about 59 days. Measure your board in deep sleep and redo the math with that number.

Why does my ESP32 use more power asleep than the datasheet says?

The datasheet figure is the bare chip. The DevKit board adds a power LED, a USB serial chip, and a regulator, and each draws current around the clock. Measure the whole board, not the chip.

What wakes the ESP32 from deep sleep?

The RTC timer is the workhorse: wake every N minutes to sample and report. A pin, a touch pad, or the ULP coprocessor can also wake it. This build uses the timer only.

Does deep sleep keep my variables?

No. Deep sleep restarts the chip, so normal variables are lost. Only variables tagged RTC_DATA_ATTR survive, in the 8 KB RTC slow memory. Keep counters and last readings there.

Can I add solar power to this node?

Not in this build. No solar panel is stocked for it, so no solar claim is made here. A solar version needs a panel, a charge controller, and a cloudy-week test before you trust it.

Parts used

Build it with the ESP32 DevKit V1 Development Board, 30-Pin WROOM-32, the DHT22 / AM2302 Digital Temperature & Humidity Sensor Module, and the XL4015 5A DC-DC Step Down Buck Converter Module with LED Display, 2-Pack. The always-on version is ESP32 WiFi Sensor Telemetry: Live Dashboard with BME280, and the flash logging version is ESP32 Sensor Data Logger: Flash Logging and WiFi Download. For the chip radios behind the choice, see ESP32 vs ESP32-S3 vs ESP32-C3 vs ESP32-C6.

Sources

Last updated: 2026-11-21. Search volume: not verified. Product links use the store short link form with the product ID; confirm the product slug at publish time.

Mecanum Wheel Robot Car Build: Omni-Directional Drive

Mecanum wheel robot car chassis with four omni wheels

Mecanum Wheel Robot Car Build: Omni-Directional Drive

Build a mecanum wheel robot car that drives forward, sideways, and diagonally without turning. Each wheel carries rollers set at 45 degrees, and the four wheels spin in matched patterns to strafe. The build uses two L298N drivers, one per wheel pair, because one L298N drives only two motors and a mecanum car has four.

Quick facts

Item Value
Chassis Mecanum 4WD chassis, aluminum alloy, 0.20 feet omni wheels
Drivers 2 x L298N, one per wheel pair
Motors 4 x TT gear motors, 3 to 6 V
Controller ESP32 DevKit V1, 3.3 V logic
Roller angle 45 degrees on each wheel
Moves Forward, back, strafe left, strafe right, rotate, diagonal

Mecanum wheel robot car: how does a wheel move sideways?

A mecanum wheel has small rollers around its rim, each set at 45 degrees to the wheel axle. When the wheel spins, the roller pushes the car partly forward and partly sideways. One wheel alone would slide diagonally, but four wheels in the right pattern cancel the unwanted parts.

For a strafe left, the front left and rear right wheels spin one way while the front right and rear left spin the other way. The forward parts cancel and the sideways parts add. The car slides left without turning. Reverse the pattern and it strafes right. That is the move a normal car cannot make.

Wheel orientation matters. The rollers on the front left and rear right wheels must angle one way, and the rollers on the front right and rear left must angle the other way, forming an X pattern when viewed from above. If one wheel is fitted backward, the car will crab and spin instead of strafing. Check the X before you wire anything.

Why does this build need two L298N drivers?

One L298N drives two DC motors. A mecanum car has four motors, so it needs two L298N modules. Each module drives one diagonal pair: the first drives the front left and rear right wheels, and the second drives the front right and rear left wheels. That pairing matches the strafe pattern and keeps the wiring tidy. Buy the 4WD Kit variant of the chassis kit: it ships with 4 TT gear motors and one L298N, so buy one more L298N for the second pair. The Plate Set variants ship with plates and wheels only, no motors or electronics. The 4WD Kit also includes a UNO R3 board and sensor shield; this build uses an ESP32 DevKit V1 in its place.

Each L298N needs its own enable and direction pins, so the build uses 12 control pins on the ESP32. The ESP32 DevKit V1 has enough GPIO pins for that, but a small board such as a SuperMini would not. Check the pinout post for your exact board before you substitute it.

Both L298N modules share one motor battery. Join the battery positive to both 12 V terminals and the battery negative to both grounds and to the ESP32 ground. Keep the 5 V jumper on at 6 V, and remove it above 12 V, on both modules.

How does the drive mix work?

The drive mix takes three inputs: forward speed, strafe speed, and rotation speed. Each wheel speed is a sum of those three with signs that depend on the wheel position. Front left equals forward plus strafe plus rotation. Front right equals forward minus strafe minus rotation. Rear left equals forward minus strafe plus rotation. Rear right equals forward plus strafe minus rotation.

The sketch below implements that mix for serial control. Type f for forward, s for strafe left, d for strafe right, l to rotate left, r to rotate right, and x to stop. Each key sets the four wheel speeds from the mix, clamps them to -255 to 255, and writes them to the two L298N modules.

Test the mix with the car lifted. Strafe left should spin the front left and rear right wheels one way and the other two the opposite way. If one wheel spins the wrong way, swap its two motor wires at its L298N output. Do not fix wheel direction in code, because the wiring is the fault.

What are the limits of a mecanum car?

Mecanum wheels slip more than normal wheels, because the rollers are always partly sliding. The car will not climb as well, will not push as hard, and will drift on smooth floors. It also draws more current, because two wheels fight each other in every strafe. Expect shorter battery life than a normal 4WD car on the same pack.

The rollers also wear faster than a solid tire, and they pick up grit. Keep the floor clean and the rollers free. A stuck roller turns a mecanum wheel into a bad normal wheel, and the car will crab instead of strafing.

For all that, the strafe is worth it on a bench or a small course. A mecanum car can slide sideways into a gap a normal car cannot reach, and it can rotate in place without a turning circle. That is why warehouse robots and camera dollies use the same wheel.

Wiring

Wire the build with the power off. Check every connection in the table before you connect any battery or USB cable.

From To Notes
Battery box positive Both L298N 12 V terminals Motor supply, 6 V from 4 AA cells
Battery box negative Both L298N GND and ESP32 GND Common ground for both drivers and the logic
L298N A OUT1, OUT2 Front left TT motor First module, left channel
L298N A OUT3, OUT4 Rear right TT motor First module, right channel
L298N B OUT1, OUT2 Front right TT motor Second module, left channel
L298N B OUT3, OUT4 Rear left TT motor Second module, right channel
ESP32 GPIO 25, 27, 14 L298N A ENA, IN1, IN2 Front left motor: PWM, direction A, direction B
ESP32 GPIO 26, 12, 13 L298N A ENB, IN3, IN4 Rear right motor: PWM, direction A, direction B; GPIO 12 is a strapping pin, keep low at boot
ESP32 GPIO 32, 33, 15 L298N B ENA, IN1, IN2 Front right motor: PWM, direction A, direction B
ESP32 GPIO 18, 19, 21 L298N B ENB, IN3, IN4 Rear left motor: PWM, direction A, direction B; GPIO 21 is also I2C SDA, so do not add I2C parts to this build
Both L298N 5 V pins Leave unconnected Jumpers fitted at 6 V; do not feed 5 V in as well
USB 5 V ESP32 USB port Logic supply only; motor current never passes through USB

Power budget

Four TT motors draw more than two. At full load the four motors together draw about 2 to 4 A from the 6 V pack, split across two L298N modules at about 1 to 2 A per module. Each L298N drops about 2 V, so each motor sees about 4 V. The heatsinks on both modules will get warm, so give them airflow.

The ESP32 runs from USB 5 V and draws about 80 to 160 mA. Each L298N logic side draws only a few milliamps from its onboard regulator. The motor battery and the logic supply share only a ground wire. Never power the motors from the ESP32 5 V pin.

A 4 AA alkaline pack sags under a 4 A load, so the car will slow during a strafe. A 5-cell NiMH pack (6 V) holds voltage better than alkalines under load. Do not use a 2-cell lithium pack here: 7.4 V nominal is above the TT motor 3 to 6 V rating. Size the pack for the stall total, not the cruise current.

Build steps

  1. Assemble the mecanum chassis. Fit the four wheels in the X roller pattern: front left and rear right angle one way, front right and rear left the other way.
  2. Mount the two L298N modules and the ESP32 on the top plate. Label the modules A and B before you wire them.
  3. Wire the motors to the L298N outputs from the wiring table. Wire both modules to the same battery and to the ESP32 ground.
  4. Remove all four enable jumpers. Wire the 12 control pins from the wiring table.
  5. Upload the sketch below to the ESP32 DevKit V1. Lift the car off the floor for the first test.
  6. Type f, s, d, l, and r in the serial monitor and confirm each wheel spins the right way for each move.
  7. Set the car on the floor and strafe left and right. If it crabs instead of strafing, one wheel is fitted backward or wired in reverse.

Code

Libraries: none beyond the ESP32 Arduino core. Board: ESP32 DevKit V1. Control from the serial monitor: f forward, b back, s strafe left, d strafe right, l rotate left, r rotate right, x stop.

// Mecanum wheel robot car: 4 motors, 2 x L298N, ESP32
// Board: ESP32 DevKit V1. No extra libraries needed.
// Module A drives front-left (FL) and rear-right (RR).
// Module B drives front-right (FR) and rear-left (RL).
struct MotorPins { int pwm, inA, inB; };
MotorPins FL = {25, 27, 14};  // Module A, channel 1
MotorPins RR = {26, 12, 13};  // Module A, channel 2
MotorPins FR = {32, 33, 15};  // Module B, channel 1
MotorPins RL = {18, 19, 21};  // Module B, channel 2

const int SPEED = 200;  // 0 to 255; TT motors stall below about 80

void driveMotor(MotorPins m, int speed) {
  if (speed >= 0) {
    digitalWrite(m.inA, HIGH);
    digitalWrite(m.inB, LOW);
    analogWrite(m.pwm, speed);
  } else {
    digitalWrite(m.inA, LOW);
    digitalWrite(m.inB, HIGH);
    analogWrite(m.pwm, -speed);
  }
}

void stopAll() {
  driveMotor(FL, 0); driveMotor(FR, 0);
  driveMotor(RL, 0); driveMotor(RR, 0);
}

// Mix: forward, strafe (right is positive), rotation (right is positive).
void mix(int fwd, int strafe, int rot) {
  int fl = constrain(fwd + strafe + rot, -255, 255);
  int fr = constrain(fwd - strafe - rot, -255, 255);
  int rl = constrain(fwd - strafe + rot, -255, 255);
  int rr = constrain(fwd + strafe - rot, -255, 255);
  driveMotor(FL, fl); driveMotor(FR, fr);
  driveMotor(RL, rl); driveMotor(RR, rr);
}

void setup() {
  Serial.begin(115200);
  MotorPins all[4] = {FL, FR, RL, RR};
  for (int i = 0; i < 4; i++) {
    pinMode(all[i].pwm, OUTPUT);
    pinMode(all[i].inA, OUTPUT);
    pinMode(all[i].inB, OUTPUT);
  }
  stopAll();
  Serial.println("Keys: f forward, b back, s strafe left, d strafe right,");
  Serial.println("l rotate left, r rotate right, x stop.");
}

void loop() {
  if (Serial.available() > 0) {
    char c = Serial.read();
    if (c == 'f') mix(SPEED, 0, 0);
    else if (c == 'b') mix(-SPEED, 0, 0);
    else if (c == 's') mix(0, -SPEED, 0);  // Strafe left
    else if (c == 'd') mix(0, SPEED, 0);   // Strafe right
    else if (c == 'l') mix(0, 0, -SPEED);  // Rotate left
    else if (c == 'r') mix(0, 0, SPEED);   // Rotate right
    else if (c == 'x') stopAll();
  }
}

Test and tune it

Lift the car and type s for strafe left. The front left and rear right wheels should spin one way, and the front right and rear left the opposite way. If one wheel is wrong, swap its two motor wires at its L298N output.

Set the car on a hard floor and strafe left 1 foot. The car should slide sideways without turning. If it rotates while strafing, one wheel is fitted backward. Check the X roller pattern from above.

Drive forward 3 feet and mark the end point. Then strafe back to the start. A mecanum car drifts more than a normal car, so expect about 0.25 feet of error. That drift is normal roller slip, not a code fault.

FAQ

Why does my mecanum car need two L298N drivers?

One L298N drives two motors, and a mecanum car has four. Two modules drive one diagonal pair each, which matches the strafe pattern and keeps the wiring tidy.

Why does my mecanum car crab instead of strafing?

One wheel is fitted backward or wired in reverse. Check the X roller pattern from above, then check that each wheel spins the right way for a strafe while the car is lifted.

Why does the car drift sideways when driving forward?

Mecanum rollers always slip a little, and uneven floors make it worse. Small drift is normal. Large drift means one wheel is slower, usually from a loose motor wire or a low battery.

Can I use one driver board with four channels instead?

Yes, if it supplies four independent channels at the motor current. Two L298N modules are the stocked route in this build. A single four-channel MOSFET board is a later upgrade, not a first build change.

How fast can a mecanum car strafe?

Slower than it drives forward, because two wheels fight each other in every strafe and the rollers slip. Keep strafe speed at or below forward speed, and expect shorter battery life than a normal 4WD car.

Parts used

Build it with the Mecanum Wheel 4WD Robot Car Chassis Kit, Aluminum Alloy, 60mm Omni Wheels in the 4WD Kit variant (Single or Double Layer) and one more L298N Dual H-Bridge Motor Driver Module for Arduino (the kit already includes one L298N; one L298N drives two motors, so a four-motor car needs two) and the ESP32 DevKit V1 Development Board, 30-Pin WROOM-32 as the controller. The two-motor version is L298N Robot Car: Wire and Drive Two DC Motors, and the wireless version is ESP-NOW Joystick Robot Car: Two ESP32 Boards, No Router. For the driver comparison, see L298N vs TB6612 vs DRV8833: Which Motor Driver for Your Robot.

Sources

Last updated: 2026-11-21. Search volume: not verified. Product links use the store short link form with the product ID; confirm the product slug at publish time.

Bluetooth Robot Car with ESP32 BLE and a Phone

Phone showing a BLE control app next to an ESP32 robot car

Bluetooth Robot Car with ESP32 BLE and a Phone

Control this Bluetooth robot car from your phone with the ESP32 native Bluetooth Low Energy radio. No HC-05 or HC-06 module is needed, because the ESP32 DevKit V1 already has BLE built in. The car runs a BLE server with one writable characteristic, the phone writes drive commands to it, and the car stops by itself when the phone disconnects.

Quick facts

Item Value
Radio ESP32 native BLE 4.2, no extra module
Control app nRF Connect or any BLE scanner app, free
Service One custom service, one writable drive characteristic
Commands Single letters: F, B, L, R, S, plus speed digits 0 to 9
Driver L298N, 2 A per channel
Failsafe Car stops on BLE disconnect

Why use ESP32 native BLE instead of a Bluetooth module?

The ESP32 DevKit V1 has a Bluetooth radio on the chip. It supports Bluetooth Classic and Bluetooth Low Energy 4.2. A separate HC-05 module adds a second radio, a second serial port, and a second power draw for no benefit. This build uses the radio that is already on the board.

BLE is not a wireless serial port. It is a tree of named values. The car publishes a service with a characteristic, and the phone writes values to that characteristic. That sounds more complex than serial, but it gives you connection handling for free. The ESP32 knows when the phone connects and when it drops, and the sketch uses that event as the failsafe.

No HC-05 or HC-06 module is stocked for this build, so the design does not spec one. The phone app is a generic BLE scanner, not a custom app. That keeps the build to two parts: the car and the phone you already own.

Bluetooth robot car: how does BLE control work?

The car runs a BLE server. The server holds one service, identified by a UUID, and one characteristic inside it, identified by a second UUID. The characteristic accepts writes and sends notifications. The phone scans, finds the car by its advertised name, connects, and writes a short string to the characteristic.

The string is a drive command. F drives forward, B reverses, L turns left, R turns right, and S stops. A digit after the letter sets the speed from 0 to 9, so F8 means forward at speed 8. The sketch parses the letter and the digit, then drives the L298N the same way the wired car build does. Commands are two characters, far under the default 20-byte BLE payload, so no MTU change is needed.

The UUIDs in the code are examples from the standard BLE tutorial set. Generate your own UUIDs for a finished project, because reused UUIDs can confuse scanner apps when two devices advertise the same service. A free UUID generator online makes a fresh pair in seconds.

How do you drive it from a phone?

Install nRF Connect, a free BLE scanner app, on your phone. Power the car, open the app, and scan. The car advertises as ESP32-Robot-Car. Tap Connect, then open the service and the drive characteristic. Write F8 as text or bytes to drive forward at speed 8, and write S to stop.

nRF Connect is a test tool, not a joystick. Each command is a manual write, so the car holds the last command until you write a new one. That is fine for testing, but it is not smooth driving. A proper control app with buttons or a joystick sends commands continuously, and any app that writes to a BLE characteristic will work with this sketch.

Keep the phone within a few meters of the car for the first test. BLE range in open air is tens of meters, but walls and the metal chassis cut it. If commands lag, move closer before you blame the code.

What happens when the phone disconnects?

The sketch registers server callbacks for connect and disconnect. On disconnect it sets a flag, stops both motors, and restarts advertising so the phone can reconnect. That is the failsafe. A car that kept its last command after the phone died would drive until it hit a wall.

Test the failsafe on purpose. Drive forward, then switch the phone Bluetooth off or walk out of range. The car should stop within a second. If it keeps driving, the disconnect callback is not running, so check that the callbacks are set before the service starts.

The sketch also stops the car if no command arrives for 2 seconds while connected. That covers the case where the app is open but stops sending. Both timers together mean the car never runs away from a dead link.

Wiring

Wire the build with the power off. Check every connection in the table before you connect any battery or USB cable.

From To Notes
Battery box positive L298N 12 V terminal Motor supply, 6 V from 4 AA cells
Battery box negative L298N GND and ESP32 GND Common ground is required
L298N OUT1, OUT2 Left TT motor Swap these two wires to fix a reversed wheel
L298N OUT3, OUT4 Right TT motor Swap these two wires to fix a reversed wheel
ESP32 GPIO 25 L298N ENA Remove the ENA jumper; PWM speed, left motor
ESP32 GPIO 27 L298N IN1 Left motor direction A
ESP32 GPIO 14 L298N IN2 Left motor direction B
ESP32 GPIO 26 L298N ENB Remove the ENB jumper; PWM speed, right motor
ESP32 GPIO 12 L298N IN3 Right motor direction A; keep low at boot
ESP32 GPIO 13 L298N IN4 Right motor direction B
USB 5 V or battery 5 V ESP32 USB port Logic supply only; motor current never passes through USB

Power budget

The motors run from 4 AA cells at about 6 V into the L298N, which drops about 2 V, so each TT motor sees about 4 V. Two TT motors draw about 1 to 2 A together at full load. The ESP32 runs from USB 5 V or a separate 5 V supply and draws about 80 to 160 mA with BLE advertising and connected.

BLE uses less power than Wi-Fi, but the car still needs its motors on a separate supply. Never power the motors from the ESP32 5 V pin. The L298N logic draws only a few milliamps from its onboard regulator when the 5 V jumper is fitted at 6 V.

For outdoor driving, a USB power bank powers the ESP32 while the AA box powers the motors. Keep both supplies separate except for the shared ground between the battery negative, the L298N ground, and the ESP32 ground.

Build steps

  1. Assemble the chassis kit, fit the TT motors and wheels, and mount the L298N and the ESP32 on the top plate.
  2. Wire the L298N and the motors from the wiring table. Leave the 5 V jumper on for a 6 V pack.
  3. Remove the ENA and ENB jumpers. Wire the six control pins and join the battery negative to the ESP32 ground.
  4. Upload the sketch below to the ESP32 DevKit V1. No extra library is needed, because BLE ships with the core.
  5. Install nRF Connect on your phone. Power the car and scan for ESP32-Robot-Car.
  6. Connect, open the drive characteristic, and write S to confirm the link. Then write F5 and confirm both wheels spin forward.
  7. Lift the car first, then set it on the floor. Test the disconnect failsafe by switching the phone Bluetooth off while driving.

Code

Libraries: none beyond the ESP32 Arduino core (BLE ships with the core). Board: ESP32 DevKit V1. The sketch uses the core 4.0.0 BLE API (BLE.h handles, BLEProperty/BLEPermission) and will not compile on core 2.x/3.x, whose BLEDevice pointer API was removed in 4.0. The UUIDs below are the standard tutorial pair; generate your own for a finished project.

// Bluetooth robot car: ESP32 native BLE server + L298N
// Board: ESP32 DevKit V1. Library: BLE (ships with the core).
// Requires Arduino ESP32 core 4.0.0 or later (ESP-IDF 6.1.1).
// The core 2.x/3.x BLEDevice pointer API does not compile on 4.0.
#include 

static const BLEUUID SERVICE_UUID("4fafc201-1fb5-459e-8fcc-c5c9c331914b");
static const BLEUUID CHARACTERISTIC_UUID("beb5483e-36e1-4688-b7f5-ea07361b26a8");

const int ENA = 25;  // Left motor PWM (remove the ENA jumper)
const int IN1 = 27;
const int IN2 = 14;
const int ENB = 26;  // Right motor PWM (remove the ENB jumper)
const int IN3 = 12;
const int IN4 = 13;

bool deviceConnected = false;
unsigned long lastCommandMs = 0;
const unsigned long COMMAND_TIMEOUT_MS = 2000;  // Stop if silent for 2 s

void driveMotor(int pwmPin, int inA, int inB, int speed) {
  if (speed >= 0) {
    digitalWrite(inA, HIGH);
    digitalWrite(inB, LOW);
    analogWrite(pwmPin, speed);
  } else {
    digitalWrite(inA, LOW);
    digitalWrite(inB, HIGH);
    analogWrite(pwmPin, -speed);
  }
}

void drive(int left, int right) {
  driveMotor(ENA, IN1, IN2, left);
  driveMotor(ENB, IN3, IN4, right);
}

void stopCar() {
  analogWrite(ENA, 0);
  analogWrite(ENB, 0);
}

// Command format: letter plus speed digit 0 to 9.
// F8 = forward speed 8, L5 = left speed 5, S = stop.
void handleCommand(String cmd) {
  if (cmd.length() < 1) return;
  char dir = cmd.charAt(0);
  int level = 5;  // Default speed level
  if (cmd.length() > 1 && isDigit(cmd.charAt(1))) {
    level = cmd.charAt(1) - '0';
  }
  int speed = map(level, 0, 9, 0, 255);
  lastCommandMs = millis();
  if (dir == 'F') drive(speed, speed);
  else if (dir == 'B') drive(-speed, -speed);
  else if (dir == 'L') drive(-speed, speed);
  else if (dir == 'R') drive(speed, -speed);
  else if (dir == 'S') stopCar();
}

void setup() {
  Serial.begin(115200);
  pinMode(ENA, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT);
  pinMode(ENB, OUTPUT); pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT);
  stopCar();
  BLE.begin("ESP32-Robot-Car");
  BLEServer server = BLE.createServer();
  server.onConnect([](BLEServer &s, const BLEConnInfo &conn) {
    deviceConnected = true;
    lastCommandMs = millis();
  });
  server.onDisconnect([](BLEServer &s, const BLEConnInfo &conn, uint8_t reason) {
    deviceConnected = false;
    stopCar();  // Failsafe: halt on disconnect
  });
  server.advertiseOnDisconnect(true);
  BLEService svc = server.createService(SERVICE_UUID);
  BLECharacteristic chr = svc.createCharacteristic(
    CHARACTERISTIC_UUID,
    BLEProperty::Read | BLEProperty::Write | BLEProperty::Notify,
    BLEPermission::ReadWriteOpen);
  // Notify auto-creates the CCCD on core 4.0; no BLE2902 descriptor needed.
  chr.onWrite([](BLECharacteristic &c, const BLEConnInfo &conn) {
    handleCommand(c.getStringValue());
  });
  server.start();
  BLE.getAdvertising().addServiceUUID(SERVICE_UUID);
  BLE.startAdvertising();
  Serial.println("BLE car advertising as ESP32-Robot-Car");
}

void loop() {
  // Stop if connected but silent for 2 seconds.
  if (deviceConnected && millis() - lastCommandMs > COMMAND_TIMEOUT_MS) {
    stopCar();
  }
  delay(50);
}

Test and tune it

Write F5 in nRF Connect and confirm both wheels spin forward while the car is lifted. Write S and confirm they stop. If nothing moves, check that the characteristic accepts writes and that the command letter is uppercase.

Write R5 and confirm the car turns right. If it turns left, swap the left and right motor wiring as a pair, or swap the L and R cases in handleCommand().

Switch the phone Bluetooth off while driving forward. The car should stop within a second. If it keeps driving, the disconnect callback is not registered, so check that onDisconnect is registered before server.start().

FAQ

Do I need an HC-05 module for Bluetooth on an ESP32?

No. The ESP32 DevKit V1 has Bluetooth Classic and BLE built in. This build uses native BLE, so no extra module is fitted and no second serial port is needed.

What phone app controls the car?

Any BLE scanner app that can write to a characteristic works. nRF Connect is free and shows the service, the characteristic, and the write box. A custom app with buttons is smoother, but it is not needed to test the build.

Why does the car stop when my phone locks?

Many phones drop BLE connections when the screen locks to save power. Keep the screen on while driving, or reconnect and write a new command after unlocking.

Can BLE and Wi-Fi run at the same time on an ESP32?

Yes, but they share the 2.4 GHz radio, so throughput drops when both are active. This build uses BLE only, so the radio is free for the car link.

How far can the phone control the car?

BLE range in open air is tens of meters, but walls and the metal chassis cut it. Test outdoors in open space, and keep the phone within a few meters for the first run.

Parts used

Build it with the ESP32 DevKit V1 Development Board, 30-Pin WROOM-32, the Smart Robot Car Chassis Kit with Speed Encoder and Battery Box for Arduino, 2WD / 4WD, and the L298N Dual H-Bridge Motor Driver Module for Arduino. The wired version is L298N Robot Car: Wire and Drive Two DC Motors, and the no-router radio version is ESP-NOW Joystick Robot Car: Two ESP32 Boards, No Router. For the chip radios behind the choice, see ESP32 vs ESP32-S3 vs ESP32-C3 vs ESP32-C6.

Sources

Last updated: 2026-11-21. Search volume: not verified. Product links use the store short link form with the product ID; confirm the product slug at publish time.

ESP32 Sensor Data Logger: Flash Logging and WiFi Download

ESP32 data logger with BME280 sensor and a downloaded CSV log

ESP32 Sensor Data Logger: Flash Logging and WiFi Download

This ESP32 sensor data logger logs BME280 readings to onboard flash with LittleFS, then downloads the CSV file over Wi-Fi. No SD card module is needed, because the ESP32 DevKit V1 has megabytes of flash to spare. The logger records a timestamped row every minute, and a web page at the board IP address offers the file for download.

Quick facts

Item Value
Storage LittleFS on onboard flash, no SD card module
Sensor BME280, temperature, humidity, pressure
Log format CSV, one row per minute
Download Web page at the board IP address, /download
Display 0.96 inch SSD1306 OLED shows the latest reading
Flash wear LittleFS spreads writes; log once per minute, not once per second

ESP32 sensor data logger: why log to onboard flash instead of an SD card?

LittleFS replaced SPIFFS as the filesystem in the Arduino ESP32 core. SPIFFS was deprecated in core 2.x and removed in core 3.x, so new sketches use LittleFS throughout. The ESP32 DevKit V1 ships with 4 MB of flash, and the sketch uses only part of it. LittleFS carves a filesystem out of the spare flash, so the board can store weeks of one-per-minute readings with no extra hardware. A CSV row is about 40 bytes, so one day of minute readings is about 58 KB.

No SD card module is stocked for this build, so the design uses what the board already has. That also removes a failure point: no card socket, no card formatting, and no card to shake loose on a robot. The trade is capacity. Flash holds far less than a card, so this logger suits weeks of data, not years.

LittleFS also handles wear. Flash cells wear out after many writes, and LittleFS spreads writes across the filesystem instead of hammering one spot. Logging once per minute keeps the write count low. Logging once per second would wear the flash far faster for no benefit in a room weather log.

What does each log row hold?

Each row holds the uptime in seconds, the temperature in degrees C, the humidity in percent, and the pressure in hPa. The ESP32 has no real-time clock, so uptime is the timestamp. If you need wall-clock time, note the download time and count back, or add an NTP sync step when Wi-Fi connects.

The file is plain CSV with a header row: uptime_s,temperature_c,humidity_pct,pressure_hpa. Any spreadsheet opens it, and any script can parse it. Keep the format fixed. Changing column order between firmware versions breaks every script that reads the file.

The logger appends one row per minute. It opens the file, writes the row, and closes it. Closing after every write protects the data if power fails. An open file with unwritten data is lost on a reset, but a closed file survives.

How do you download the log over Wi-Fi?

The ESP32 runs a web server with three routes. The root route returns a small status page with the latest reading and a download link. The /data route returns the latest reading as JSON. The /download route streams the CSV file with a download header, so the browser saves it instead of showing it.

Connect the ESP32 to your Wi-Fi network, read its IP address from the serial monitor, and open it in a browser on the same network. The page shows the latest values and a link labeled Download log. Click it and the CSV lands in your downloads folder.

The download reads the file in chunks, so a large log does not need to fit in RAM. The file is closed between writes, so a download started between writes reads a complete file. A download that overlaps a write can catch a partial last row, so download between samples when the data must be exact. In practice the one-per-minute write takes milliseconds, so overlaps are rare.

How do you keep the log from filling the flash?

LittleFS on a 4 MB board gives roughly 1.5 MB of filesystem space, depending on the partition scheme. At 58 KB per day, that is about 26 days of minute readings. The sketch checks the file size on every write. When the file passes 1 MB, it renames the old file to log_old.csv and starts a fresh log.csv.

That rotation keeps one current file and one old file. Download both before they rotate again, or the oldest data is lost. If you need longer retention, lower the sample rate to once per 5 minutes, which stretches the same space to about 4 months.

Check the free space with LittleFS.totalBytes() and LittleFS.usedBytes() at startup and print both to the serial monitor. If used space grows faster than your estimate, a bug is writing too often. Fix the sample interval before the flash fills.

Wiring

Wire the build with the power off. Check every connection in the table before you connect any battery or USB cable.

From To Notes
BME280 VCC ESP32 3V3 3.3 V; bare chip maximum is 3.6 V
BME280 GND ESP32 GND Common ground
BME280 SDA ESP32 GPIO 21 Default I2C data pin
BME280 SCL ESP32 GPIO 22 Default I2C clock pin
BME280 SDO GND Sets I2C address 0x76; tie to 3V3 for 0x77
BME280 CSB 3V3 Tie high for I2C mode
OLED VCC ESP32 3V3 3.3 V logic
OLED GND ESP32 GND Common ground
OLED SDA ESP32 GPIO 21 Shared I2C bus with the BME280
OLED SCL ESP32 GPIO 22 Shared I2C bus with the BME280

Power budget

The ESP32 draws about 80 to 160 mA with Wi-Fi on, and peaks near 240 mA while transmitting. The BME280 draws only a few microamps between readings, and the OLED draws about 20 mA lit. A USB 5 V supply at 500 mA covers the build.

Flash writes add a short current spike, but the spike lasts milliseconds and the supply capacitor on the board absorbs it. The real power cost is Wi-Fi staying on so the download page is always available. If you need battery life, use the deep sleep node build instead, which wakes, logs, sends, and sleeps.

Do not power this logger from a laptop USB port that sleeps. When the laptop sleeps, the USB port may cut power and the log stops. Use a wall USB supply for any unattended logging run.

Build steps

  1. Install the Adafruit BME280 Library and Adafruit Unified Sensor, plus the Adafruit SSD1306 and GFX libraries.
  2. Wire the BME280 and the OLED to the ESP32 from the wiring table.
  3. Edit the Wi-Fi name and password in the sketch, then upload it to the ESP32 DevKit V1.
  4. Open the serial monitor at 115200 baud and confirm the BME280 is found and LittleFS mounts. Copy the IP address.
  5. Open the IP address in a browser. The status page should show the latest reading and a download link.
  6. Leave the logger running for an hour, then download the CSV. Open it in a spreadsheet and confirm one row per minute.
  7. Check the file size after a day. At 58 KB per day, the 1 MB rotation should not trigger for about 17 days.

Code

Libraries: Adafruit BME280 Library, Adafruit Unified Sensor, Adafruit SSD1306, Adafruit GFX Library. LittleFS and WebServer ship with the ESP32 Arduino core. Board: ESP32 DevKit V1.

// ESP32 sensor data logger: BME280 to LittleFS, CSV download over WiFi
// Board: ESP32 DevKit V1. No SD card module is used.
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

const char* WIFI_SSID = "YOUR_WIFI_NAME";      // Replace with your network
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";  // Replace with your password

Adafruit_BME280 bme;  // I2C, address 0x76 or 0x77
Adafruit_SSD1306 display(128, 64, &Wire, -1);
WebServer server(80);

const char* LOG_PATH = "/log.csv";
const char* OLD_PATH = "/log_old.csv";
const size_t MAX_LOG_BYTES = 1000000;  // Rotate at 1 MB
const unsigned long SAMPLE_MS = 60000; // One row per minute

void logReading() {
  float t = bme.readTemperature();
  float h = bme.readHumidity();
  float p = bme.readPressure() / 100.0F;
  File f = LittleFS.open(LOG_PATH, FILE_APPEND);
  if (!f) {
    Serial.println("Failed to open log file");
    return;
  }
  // Uptime seconds; the ESP32 has no real-time clock.
  f.printf("%lu,%.1f,%.1f,%.1f\n", millis() / 1000, t, h, p);
  // Read the size while the file is still open; size() after close() returns 0.
  size_t logSize = f.size();
  f.close();
  if (logSize > MAX_LOG_BYTES) {
    LittleFS.remove(OLD_PATH);
    LittleFS.rename(LOG_PATH, OLD_PATH);
  }
}

void handleRoot() {
  float t = bme.readTemperature();
  float h = bme.readHumidity();
  float p = bme.readPressure() / 100.0F;
  String html = ""
    "ESP32 Data Logger"
    "

ESP32 Data Logger

" "

Temperature: " + String(t, 1) + " C

" "

Humidity: " + String(h, 1) + " %

" "

Pressure: " + String(p, 1) + " hPa

" "

Download log.csv

" ""; server.send(200, "text/html", html); } void handleDownload() { File f = LittleFS.open(LOG_PATH, FILE_READ); if (!f) { server.send(404, "text/plain", "No log file yet"); return; } server.sendHeader("Content-Disposition", "attachment; filename=log.csv"); server.streamFile(f, "text/csv"); f.close(); } void setup() { Serial.begin(115200); Wire.begin(21, 22); if (!LittleFS.begin(true)) { Serial.println("LittleFS mount failed"); while (1) delay(100); } Serial.print("LittleFS free bytes: "); Serial.println(LittleFS.totalBytes() - LittleFS.usedBytes()); if (!bme.begin(0x76) && !bme.begin(0x77)) { Serial.println("BME280 not found. Check wiring and address."); while (1) delay(100); } if (!LittleFS.exists(LOG_PATH)) { File f = LittleFS.open(LOG_PATH, FILE_WRITE); f.println("uptime_s,temperature_c,humidity_pct,pressure_hpa"); f.close(); } display.begin(SSD1306_SWITCHCAPVCC, 0x3C); WiFi.begin(WIFI_SSID, WIFI_PASS); while (WiFi.status() != WL_CONNECTED) delay(500); Serial.print("Logger at http://"); Serial.println(WiFi.localIP()); server.on("/", handleRoot); server.on("/download", handleDownload); server.begin(); } void loop() { server.handleClient(); static unsigned long lastSample = 0; if (millis() - lastSample >= SAMPLE_MS) { lastSample = millis(); logReading(); display.clearDisplay(); display.setTextSize(1); display.setTextColor(SSD1306_WHITE); display.setCursor(0, 0); display.print("Logged: "); display.print(millis() / 1000); display.println(" s"); display.display(); } }

Test and tune it

Download the CSV after one hour and count the rows. You should see about 60 rows plus the header. Fewer rows means the sample timer is wrong or the board reset. Check the serial monitor for reboot messages.

Open the CSV in a spreadsheet and plot temperature against uptime. The line should be smooth. A jump of several degrees in one minute means the sensor moved, the sun hit it, or the board heat reached it.

If the download returns 404, the log file does not exist yet. Wait one minute for the first sample, then retry. If it still fails, check the LittleFS free space printed at startup.

FAQ

Does this logger need an SD card?

No. It logs to the ESP32 onboard flash with LittleFS. A CSV row is about 40 bytes, so one day of minute readings is about 58 KB, and the filesystem holds about 26 days before rotation.

How long will the log last before it rotates?

About 17 days at one row per minute before the 1 MB rotation renames the file. Lower the sample rate to once per 5 minutes to stretch the same space to about 4 months.

Why is the timestamp in uptime seconds?

The ESP32 has no real-time clock, so uptime is the only clock it has without network time. Note the download time and count back, or add an NTP sync step when Wi-Fi connects.

What happens if power fails during a write?

The sketch closes the file after every row, so at most one row is lost. Rows already written survive a reset because LittleFS commits them on close.

Can I log faster than once per minute?

Yes, but flash wear rises with write count. Once per minute is ample for room weather. Log faster only when the signal changes fast, and rotate the file sooner.

Parts used

Build it with the ESP32 DevKit V1 Development Board, 30-Pin WROOM-32, the BME280 Temperature, Humidity and Barometric Pressure Sensor Module, 5V, I2C and SPI, and the 0.96 Inch OLED Display Module, SSD1306, I2C, 128×64, for Arduino / ESP32 / ESP8266. The live dashboard version is ESP32 WiFi Sensor Telemetry: Live Dashboard with BME280, and the battery version is Battery-Powered ESP32 Sensor Node: Deep Sleep and Power Budget. For the protocol behind the wiring, see I2C vs SPI vs UART: Which Protocol for Your Sensor or Display.

Sources

Last updated: 2026-11-21. Search volume: not verified. Product links use the store short link form with the product ID; confirm the product slug at publish time.

L298N Robot Car: Wire and Drive Two DC Motors

Phone showing a BLE control app next to an ESP32 robot car

L298N Robot Car: Wire and Drive Two DC Motors

Wire an L298N between your battery and two TT motors, then drive them from an ESP32 with PWM on the enable pins. The L298N handles up to 2 A per channel, drops about 2 V across the bridge, and needs its own motor supply. The ESP32 only sends low-current direction and speed signals, and the supplies share only a ground.

Quick facts

Item Value
Driver L298N dual H-bridge, 2 A per channel, 3 A peak non-repetitive for 100 ms
Motor supply 5 to 35 V on the module, up to 46 V on the bare chip
Logic supply 4.5 to 7 V; onboard 5 V regulator with jumper
Voltage drop 1.8 to 3.2 V at 1 A, up to 4.9 V at 2 A
Motors 2 x TT 130 gear motors, 3 to 6 V
Speed control PWM on ENA and ENB, 0 to 255

L298N robot car: what does the L298N do?

The L298N is a dual H-bridge driver built on the ST L298 chip. It lets a microcontroller run two DC motors in either direction, at variable speed, from a supply the microcontroller could never deliver itself. Each channel switches up to 2 A of continuous current, with a 3 A peak allowed only non-repetitively for 100 ms.

An H-bridge is four switches arranged so the motor current can flow either way. The IN1 and IN2 pins set the direction for the first motor, and IN3 and IN4 set it for the second. The ENA and ENB pins enable each channel, and a PWM signal on an enable pin sets the speed. With the enable jumpers fitted, each motor runs at full speed whenever the direction pins command movement.

The bridge is built from bipolar transistors, not MOSFETs, so it drops voltage. At 1 A the drop is 1.8 to 3.2 V, and at 2 A it reaches 4.9 V. That drop becomes heat in the chip, which is why the module carries a large heatsink. A 12 V supply gives the motor about 10 V. A 6 V supply gives the motor about 4 V.

When do you remove the 5 V jumper?

The module has an onboard 5 V regulator and a jumper that enables it. With the jumper fitted and a motor supply of 12 V or less, the regulator makes 5 V on the 5 V pin, and you can use that pin to power your logic. With a motor supply above 12 V, remove the jumper first, or the regulator overheats.

With the jumper removed, the 5 V pin becomes an input. You must feed 5 V into it yourself to power the chip logic. This build uses a 6 V motor pack, so the jumper stays on. The regulator then supplies the logic, and the ESP32 runs from its own USB supply.

Never connect two 5 V supplies to the same pin. If the jumper is fitted, leave the 5 V pin unconnected, or the regulator and your other supply will fight. If the jumper is removed, feed 5 V in and do not expect 5 V out.

How do you wire the L298N to an ESP32?

Connect the motor battery positive to the 12 V terminal and the battery negative to GND. Connect the two TT motors to OUT1 and OUT2 for the left motor, and OUT3 and OUT4 for the right motor. Connect ENA, IN1, IN2, ENB, IN3 and IN4 to the ESP32 pins in the wiring table.

The L298N inputs read high from 2.3 V, so the ESP32 3.3 V logic drives them directly. No level shifter is needed. Join the battery negative to the ESP32 ground. Without that common ground, the direction signals have no reference and the motors will not respond.

Remove the ENA and ENB jumpers before you connect PWM. With the jumpers fitted, the enable pins sit at 5 V and the motors run at full speed regardless of your code. With the jumpers removed, the ESP32 PWM signal on each enable pin sets the speed from 0 to 255.

How does PWM speed control work?

PWM switches the enable pin on and off about 1,000 times per second at the core 3.3.13 default of 1 kHz. The motor sees the average voltage, so a 50 percent duty cycle gives about half speed. The sketch below uses analogWrite() with values from 0 to 255. A value of 0 stops the motor, and 255 runs it at full speed for the supply voltage.

TT motors stall at low PWM values. Below about 80 out of 255, many TT motors do not turn at all, because the average voltage cannot overcome friction. Start your speed tests at 150 and work down. If the car creeps at low speed, that is normal for a geared TT motor on an L298N with a 2 V drop.

Direction and speed are separate. The IN pins set forward or reverse, and the enable PWM sets how fast. To stop, set the enable PWM to zero. To brake hard, set both IN pins the same way, but a simple stop is enough for a first build.

Wiring

Wire the build with the power off. Check every connection in the table before you connect any battery or USB cable.

From To Notes
Battery box positive L298N 12 V terminal Motor supply, 6 V from 4 AA cells
Battery box negative L298N GND and ESP32 GND Common ground is required
L298N OUT1, OUT2 Left TT motor Swap these two wires to fix a reversed wheel
L298N OUT3, OUT4 Right TT motor Swap these two wires to fix a reversed wheel
ESP32 GPIO 25 L298N ENA Remove the ENA jumper; PWM speed, left motor
ESP32 GPIO 27 L298N IN1 Left motor direction A
ESP32 GPIO 14 L298N IN2 Left motor direction B
ESP32 GPIO 26 L298N ENB Remove the ENB jumper; PWM speed, right motor
ESP32 GPIO 33 L298N IN3 Right motor direction A; GPIO 33 is used instead of GPIO 12, which is a flash-voltage strapping pin and must stay low at boot
ESP32 GPIO 13 L298N IN4 Right motor direction B
L298N 5 V pin Leave unconnected Jumper fitted at 6 V, so the regulator makes 5 V here; do not feed 5 V in as well
USB 5 V ESP32 USB port Logic supply only; motor current never passes through USB

Power budget

The motors run from 4 AA cells at about 6 V into the L298N. The bridge drops about 2 V, so each TT motor sees about 4 V. Two TT motors at full load draw about 1 to 2 A together, which the L298N handles with its heatsink. At 1 A per channel the chip dissipates about 2 W as heat, so give it airflow and do not cover the heatsink.

The ESP32 runs from USB 5 V and draws about 80 to 160 mA with the radio on. The L298N logic draws about 40 to 60 mA from the motor supply through its onboard regulator. The two supplies share only a ground wire. Never power the motors from the ESP32 5 V pin, and never power the ESP32 from the L298N 5 V pin while USB is also connected, because two 5 V sources will fight.

If you raise the motor supply above 12 V, remove the 5 V jumper first and feed 5 V into the 5 V pin yourself. Above 12 V the onboard regulator overheats. The TT motors in this build are rated 3 to 6 V, so a 6 V pack is the right match and the jumper stays on.

Build steps

  1. Assemble the chassis kit, fit the TT motors and wheels, and mount the L298N and the ESP32 on the top plate.
  2. Connect the motors to OUT1 and OUT2, and OUT3 and OUT4. Connect the battery box to the 12 V terminal and GND. Leave the 5 V jumper on for a 6 V pack.
  3. Remove the ENA and ENB jumpers. Wire the six control pins from the wiring table and join the battery negative to the ESP32 ground.
  4. Upload the sketch below to the ESP32 DevKit V1. Keep the car lifted off the floor for the first test.
  5. Open the serial monitor at 115200 baud and type f, b, l, r, or s, then press Enter. Each key drives the car forward, back, left, right, or stop.
  6. Set the car on the floor and drive it forward. If a wheel runs backward, swap that motor’s two wires at the L298N output.
  7. Test low speed. If the motors stall below a PWM value of about 80, raise your minimum drive speed in the sketch.

Code

Libraries: none beyond the ESP32 Arduino core. Board: ESP32 DevKit V1, Arduino core 3.3.13 (analogWrite arrived in core 3.0). Control the car from the serial monitor: type f, b, l, r, or s and press Enter.

// L298N robot car: two TT motors, PWM speed, serial control
// Board: ESP32 DevKit V1, Arduino core 3.3.13. No extra libraries needed.
const int ENA = 25;  // Left motor PWM (remove the ENA jumper)
const int IN1 = 27;  // Left motor direction A
const int IN2 = 14;  // Left motor direction B
const int ENB = 26;  // Right motor PWM (remove the ENB jumper)
const int IN3 = 33;  // Right motor direction A (GPIO 12 avoided: strapping pin)
const int IN4 = 13;  // Right motor direction B
const int SPEED = 200;  // 0 to 255; TT motors stall below about 80

void driveMotor(int pwmPin, int inA, int inB, int speed) {
  if (speed >= 0) {
    digitalWrite(inA, HIGH);
    digitalWrite(inB, LOW);
    analogWrite(pwmPin, speed);
  } else {
    digitalWrite(inA, LOW);
    digitalWrite(inB, HIGH);
    analogWrite(pwmPin, -speed);
  }
}

void drive(int left, int right) {
  driveMotor(ENA, IN1, IN2, left);
  driveMotor(ENB, IN3, IN4, right);
}

void stopCar() {
  analogWrite(ENA, 0);
  analogWrite(ENB, 0);
}

void setup() {
  Serial.begin(115200);
  pinMode(ENA, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT);
  pinMode(ENB, OUTPUT); pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT);
  stopCar();
  Serial.println("Type f, b, l, r, or s, then Enter.");
}

void loop() {
  if (Serial.available() > 0) {
    char c = Serial.read();
    if (c == 'f') drive(SPEED, SPEED);        // Forward
    else if (c == 'b') drive(-SPEED, -SPEED); // Reverse
    else if (c == 'l') drive(-SPEED, SPEED);  // Turn left
    else if (c == 'r') drive(SPEED, -SPEED);  // Turn right
    else if (c == 's') stopCar();             // Stop
  }
}

Test and tune it

Lift the car and type f. Both wheels should spin forward at the same speed. If one wheel is slower, check that its motor wires are tight in the screw terminal and that its enable PWM pin is connected.

Type s and confirm both wheels stop within a second. A wheel that keeps spinning has a stuck enable jumper or a shorted IN pin. Remove power and recheck the wiring table.

Drive the car on a hard floor, then on carpet. The car will slow on carpet because the TT motors draw more current under load and the L298N drop grows. That is normal. A MOSFET driver such as the TB6612FNG loses less voltage and is the next step if battery life matters.

FAQ

Why does my L298N get hot?

The bipolar bridge drops about 2 V, and that drop becomes heat. At 1 A per channel the chip dissipates about 2 W. The heatsink is supposed to get warm. Give it airflow and keep the current under 2 A per channel.

Do I remove the 5V jumper on the L298N?

Remove it when the motor supply is above 12 V, because the onboard regulator overheats. Leave it on at 12 V or less. With the jumper removed, feed 5 V into the 5 V pin yourself.

Why do the motors run slow on a 6 V battery?

The L298N drops about 2 V, so a 6 V pack gives each motor about 4 V. That is normal for this driver. A higher supply is not an option here: the pack is already 6 V and the TT motors are rated 3 to 6 V. A MOSFET driver such as the TB6612FNG loses less voltage and gives more speed.

Can the ESP32 drive the L298N directly?

Yes. The L298N inputs read high from 2.3 V, so 3.3 V logic works with no level shifter. Join the battery negative to the ESP32 ground so the signals share a reference.

Why does one wheel spin backward?

That motor is wired in reverse. Swap its two wires at the L298N output terminals. Do not fix it in code, because the wiring is the fault.

Parts used

Build it with the L298N Dual H-Bridge Motor Driver Module for Arduino, the Smart Robot Car Chassis Kit with Speed Encoder and Battery Box for Arduino, 2WD / 4WD, and the TT Motor 130 Gear Motor + 65mm Wheel, 3-6V DC, for Arduino Smart Car Robot, plus the ESP32 DevKit V1 Development Board, 30-Pin WROOM-32 as the controller. The wireless version is ESP-NOW Joystick Robot Car: Two ESP32 Boards, No Router, and the driver comparison is L298N vs TB6612 vs DRV8833: Which Motor Driver for Your Robot. For the driver behind the speed control, see How to Choose the Right Motor Drivers for Arduino Use.

Sources

Last updated: 2026-11-21. Search volume: not verified. Product links use the store short link form with the product ID; confirm the product slug at publish time.