Guides · 8 min read

Arduino C# Serial Port: Windows Forms LED and Sensor App

Arduino C# serial port tutorial: list ports with SerialPort, LED button and sensor value in Windows Forms, baud and DTR settings, UI freeze fix and ESP32.

Arduino C# serial port communication is the most common way to control an Arduino over a USB cable from a Windows application you write in Visual Studio. .NET's SerialPort class opens the COM port the Arduino creates on your computer; your program writes commands to that port and reads the sensor values the Arduino sends. That way you can build your own desktop interface that lights an LED at the click of a button, shows a potentiometer value live or logs measurements, in a few hundred lines.

In this guide you'll first set up a Windows Forms project in Visual Studio and see in a table what settings such as baud rate, line ending and DTR do. Then we'll write the Arduino sketch and a complete C# form with a port list, an LED button and a sensor display. We also explain step by step why the interface freezes and how to fix it with the DataReceived event or an async read loop, the most common port errors, and how the same application works with an ESP32 over USB and Bluetooth.

Arduino Uno controlled over the serial port by a C# application
The Arduino Uno shows up in Windows as a COM port over USB; the C# application opens that port with the SerialPort class.

How does C# talk to an Arduino?

The USB-serial converter on the Arduino Uno (an ATmega16U2 on the original board, usually a CH340 on clones) creates a virtual serial port such as COM3 or COM4 in Windows. On the C# side, a SerialPort object from the System.IO.Ports namespace opens that port and a byte stream starts flowing between the two. You decide where messages begin and end; the easiest way is to send each message as a single line of text. In this guide the Arduino sends a line such as A0:512 every 100 milliseconds, and the C# program answers with LED:1 or LED:0 lines. Both sides just need the same baud rate, the same line ending and the same data format.

TaskArduino sideC# side (SerialPort)
Open the portSerial.begin(9600)BaudRate = 9600, PortName = "COM3", Open()
Send a lineSerial.println("A0:512")WriteLine("LED:1")
Receive dataSerial.available() + Serial.read()DataReceived event + ReadExisting()
Bytes waitingSerial.available()BytesToRead
List ports-SerialPort.GetPortNames()
Close the connection-Close()

Setting up a Windows Forms project in Visual Studio

  1. When installing the free Visual Studio 2022 Community, select the .NET desktop development workload.
  2. Create a new project from the Windows Forms App (C#) template, name it ArduinoSerial and keep .NET 8 as the target framework.
  3. In Project > Manage NuGet Packages > Browse, search for the System.IO.Ports package and install it. If you picked the older .NET Framework 4.x template, skip this step; the class is built in.
  4. Replace the entire content of Form1.cs with the code below; don't touch Form1.Designer.cs.
  5. Upload the Arduino sketch, close the Arduino IDE Serial Monitor and start the application in Visual Studio with F5.
The namespace line in the code must match your project name. If you named the project differently, change the namespace ArduinoSerial line to your own project name; otherwise Visual Studio sees two separate Form1 classes and opens an empty window. On .NET 6 and 8, compiling without the System.IO.Ports package gives a type or namespace SerialPort could not be found error.

Serial port settings table: baud rate, line ending, DTR

SerialPort's default settings (8 data bits, no parity, 1 stop bit) already match the Arduino's defaults; the first thing you need to change is the baud rate. Line endings cause confusion: Arduino's println() adds \r\n to the end of a line, whereas C#'s NewLine property is just \n by default. So a \r is left at the end of each line you read and has to be removed with Trim(). The DTR and RTS lines behave differently depending on the board: on the Uno, enabling DTR restarts the board; on the Leonardo, the board sends nothing at all if DTR is off; on the ESP32, enabling RTS on its own keeps the board in reset.

SettingC# property (default)Arduino sideRecommendation
Baud rateBaudRate (9600)Serial.begin(9600)Same on both sides; 115200 for the ESP32
Data formatDataBits 8, Parity.None, StopBits.One8N1 (default)Leave unchanged
Line endingNewLine ("\n")println() sends \r\nApply Trim() to each line you read
DTRDtrEnable (false)Uno: true causes a reset on open; Leonardo/Pro Micro: true is requiredfalse on the Uno, true on the Leonardo
RTSRtsEnable (false)ESP32: RTS true on its own holds EN lowfalse on the ESP32
Read timeoutReadTimeout (-1, infinite)-500–1000 ms if you use ReadLine()
Character encodingEncoding (ASCII)-Avoid non-ASCII characters in commands or choose Encoding.UTF8

Arduino code: send a sensor value, receive LED commands

The circuit is very simple: connect the outer legs of a potentiometer to 5V and GND and the middle leg to A0. The LED is the one on the board at D13; if you like, add an external LED with a 220 Ω resistor on D13. The sketch collects incoming characters in a String, runs the command when \n arrives and sends the A0 value every 100 milliseconds. Because it doesn't use delay(), LED commands are applied instantly. It also answers PING with PONG, which is handy for testing the connection from C#.

C++ (Arduino IDE)
1// Arduino Uno <-> C# Windows Forms: A0 değeri gönder, LED komutu al / send A0, receive LED commands
2const int LED_PIN = 13;            // dahili LED (ya da 220 Ω ile harici LED) / onboard LED (or external LED with 220 Ω)
3const int SENSOR_PIN = A0;         // potansiyometre orta bacak / potentiometer wiper
4unsigned long lastSend = 0;
5String cmd;                        // gelen satır / incoming line
6
7void setup() {
8  Serial.begin(9600);              // C# tarafında BaudRate = 9600 / BaudRate = 9600 in C#
9  pinMode(LED_PIN, OUTPUT);
10  cmd.reserve(16);
11}
12
13void loop() {
14  while (Serial.available() > 0) {
15    char c = Serial.read();
16    if (c == '\n') {               // C# WriteLine satırı \n ile biter / C# WriteLine ends with \n
17      cmd.trim();                  // olası \r ve boşlukları sil / strip a possible \r and spaces
18      if (cmd == "LED:1") digitalWrite(LED_PIN, HIGH);
19      else if (cmd == "LED:0") digitalWrite(LED_PIN, LOW);
20      else if (cmd == "PING") Serial.println("PONG");   // bağlantı testi / connection test
21      cmd = "";
22    } else if (cmd.length() < 16) {
23      cmd += c;
24    }
25  }
26  if (millis() - lastSend >= 100) {          // saniyede 10 ölçüm / 10 readings per second
27    lastSend = millis();
28    Serial.print("A0:");
29    Serial.println(analogRead(SENSOR_PIN));  // örnek / example: A0:512
30  }
31}
32

Before opening the C# application, test the sketch with the Arduino IDE Serial Monitor: set the speed to 9600 baud and the line ending to Newline. You should see lines like A0:512 scrolling by; the value changes between 0 and 1023 as you turn the potentiometer. Typing LED:1 in the input box and sending it should light the D13 LED. If everything works, close the Serial Monitor, because the C# application can't connect while the port is open. For more Serial Monitor details, see the Arduino Serial Monitor guide.

Windows Forms application: port list, LED button and sensor value

The Form1.cs below creates the controls in code without the designer, so copying one file is enough. At the top there's a port list with Refresh and Connect buttons, in the middle an LED button, and at the bottom a large label showing the A0 value and a progress bar from 0 to 1023. Clicking Connect opens the selected port; the LED button sends LED:1 or LED:0 on each click. Incoming data is read in the DataReceived event and passed to the interface with BeginInvoke. The button labels are in Turkish (Yenile = Refresh, Bağlan = Connect, Kes = Disconnect, AÇIK/KAPALI = ON/OFF); change the strings to your language.

Code
1// Form1.cs: Arduino seri port arayüzü / Arduino serial port UI (Windows Forms)
2// .NET 6/8: NuGet "System.IO.Ports" paketi gerekir / needs the System.IO.Ports NuGet package
3// .NET Framework 4.x: paket gerekmez / no package needed
4using System;
5using System.Drawing;
6using System.IO.Ports;
7using System.Text;
8using System.Windows.Forms;
9
10namespace ArduinoSerial   // proje adınla aynı olmalı / must match your project name
11{
12    public partial class Form1 : Form
13    {
14        private readonly SerialPort port = new SerialPort();
15        private readonly StringBuilder rxBuffer = new StringBuilder();   // yarım satırlar / partial lines
16        private readonly ComboBox cmbPorts = new ComboBox { Left = 12, Top = 12, Width = 120, DropDownStyle = ComboBoxStyle.DropDownList };
17        private readonly Button btnRefresh = new Button { Left = 140, Top = 11, Width = 80, Text = "Yenile" };
18        private readonly Button btnConnect = new Button { Left = 228, Top = 11, Width = 100, Text = "Bağlan" };
19        private readonly Button btnLed = new Button { Left = 12, Top = 50, Width = 316, Height = 40, Text = "LED: KAPALI", Enabled = false };
20        private readonly Label lblValue = new Label { Left = 12, Top = 100, Width = 316, Height = 40, Font = new Font("Segoe UI", 18), Text = "A0: -" };
21        private readonly ProgressBar bar = new ProgressBar { Left = 12, Top = 145, Width = 316, Maximum = 1023 };
22        private bool ledOn = false;
23
24        public Form1()
25        {
26            InitializeComponent();                       // Form1.Designer.cs (boş form / empty form)
27            Text = "Arduino C# Seri Port";
28            ClientSize = new Size(340, 185);
29            Controls.AddRange(new Control[] { cmbPorts, btnRefresh, btnConnect, btnLed, lblValue, bar });
30
31            port.BaudRate = 9600;                        // Serial.begin(9600) ile aynı / same as Serial.begin(9600)
32            port.NewLine = "\n";                         // WriteLine sonuna \n ekler / WriteLine appends \n
33            port.DtrEnable = false;                      // Leonardo / Pro Micro için true / true for Leonardo / Pro Micro
34            port.RtsEnable = false;                      // ESP32'de false kalsın / keep false on ESP32
35            port.DataReceived += Port_DataReceived;      // ayrı iş parçacığında çalışır / runs on a worker thread
36
37            btnRefresh.Click += (s, e) => RefreshPorts();
38            btnConnect.Click += BtnConnect_Click;
39            btnLed.Click += BtnLed_Click;
40            FormClosing += (s, e) => { if (port.IsOpen) port.Close(); };
41            RefreshPorts();
42        }
43
44        private void RefreshPorts()
45        {
46            cmbPorts.Items.Clear();
47            cmbPorts.Items.AddRange(SerialPort.GetPortNames());   // ör. COM3, COM4 / e.g. COM3, COM4
48            if (cmbPorts.Items.Count > 0) cmbPorts.SelectedIndex = 0;
49        }
50
51        private void BtnConnect_Click(object sender, EventArgs e)
52        {
53            try
54            {
55                if (port.IsOpen)                         // bağlıysa kes / disconnect if connected
56                {
57                    port.Close();
58                    btnConnect.Text = "Bağlan";
59                    btnLed.Enabled = false;
60                    return;
61                }
62                if (cmbPorts.SelectedItem == null) return;
63                port.PortName = cmbPorts.SelectedItem.ToString();
64                port.Open();
65                port.DiscardInBuffer();                  // eski baytları at / drop stale bytes
66                btnConnect.Text = "Kes";
67                btnLed.Enabled = true;
68            }
69            catch (UnauthorizedAccessException)         // port başka programda açık / port is open elsewhere
70            {
71                MessageBox.Show("Port meşgul: Seri Monitör'ü kapat.", "Port hatası");
72            }
73            catch (Exception ex)
74            {
75                MessageBox.Show(ex.Message, "Port hatası");
76            }
77        }
78
79        private void BtnLed_Click(object sender, EventArgs e)
80        {
81            if (!port.IsOpen) return;
82            ledOn = !ledOn;
83            port.WriteLine(ledOn ? "LED:1" : "LED:0");
84            btnLed.Text = ledOn ? "LED: AÇIK" : "LED: KAPALI";
85        }
86
87        // Arka planda gelir, arayüze BeginInvoke ile aktarılır / arrives on a background thread, handed to the UI with BeginInvoke
88        private void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
89        {
90            string chunk;
91            try { chunk = port.ReadExisting(); }         // ne geldiyse al, bekleme yok / take what arrived, no waiting
92            catch (InvalidOperationException) { return; }   // port kapandı / port closed
93            lock (rxBuffer)
94            {
95                rxBuffer.Append(chunk);
96                string text = rxBuffer.ToString();
97                int nl;
98                while ((nl = text.IndexOf('\n')) >= 0)   // tam satırları ayır / split complete lines
99                {
100                    string line = text.Substring(0, nl).Trim();   // \r karakterini sil / strip \r
101                    text = text.Substring(nl + 1);
102                    if (IsHandleCreated && !IsDisposed) BeginInvoke(new Action(() => ShowLine(line)));
103                }
104                rxBuffer.Clear().Append(text);           // yarım satır kalsın / keep the partial line
105            }
106        }
107
108        private void ShowLine(string line)               // UI iş parçacığında çalışır / runs on the UI thread
109        {
110            if (line.StartsWith("A0:") && int.TryParse(line.Substring(3), out int value))
111            {
112                lblValue.Text = "A0: " + value;
113                bar.Value = Math.Max(0, Math.Min(1023, value));
114            }
115        }
116    }
117}
118
Code partWhat it does
SerialPort.GetPortNames()Returns the COM ports Windows knows about as an array
port.DiscardInBuffer()Clears old bytes that piled up before the port was opened
UnauthorizedAccessExceptionOpen() throws this when the port is open in another program
ReadExisting() + StringBuilderCollects incoming chunks and only processes complete lines
BeginInvoke(…)Safely updates a control from the background thread
Math.Max / Math.MinPrevents out-of-range values on the progress bar

Why does the interface freeze and how do you fix it?

In Windows Forms, all controls belong to a single thread, the UI thread. If you call port.ReadLine() in a button event or a Timer, that thread waits until a line arrives; since ReadTimeout is infinite by default, the window locks up completely if the Arduino sends nothing. The fix is to move reading to the background. The DataReceived event already runs on a separate thread, but if you write to a Label directly from there, you get a cross-thread operation error. That's why we hand the value to the UI thread with BeginInvoke. We choose BeginInvoke over Invoke to avoid a deadlock: Invoke waits until the UI responds; if the form tries to close the port with Close() at that exact moment, the two threads wait for each other and the application hangs.

MethodInterfaceNote
ReadLine() in a button or TimerFreezesReadTimeout is infinite; don't use it
Timer + ReadExisting()Doesn't freezeSimple, but data is delayed by the timer interval
DataReceived + BeginInvokeDoesn't freezeThe classic, reliable method used in this guide
async ReadLineAsync loopDoesn't freezeMost readable code on .NET 6/8; the UI can be updated directly after await

In modern .NET you can write the same thing more readably with async and await. The loop below wraps the port's BaseStream in a StreamReader and waits for lines with ReadLineAsync(). While waiting, the UI thread is free; when a line arrives, the code continues where it left off, again on the UI thread, so BeginInvoke isn't needed. Don't use both methods at once: if you choose the async loop, delete the DataReceived line.

Code
1// Alternatif: DataReceived yerine async okuma döngüsü (.NET 6/8) / alternative: async read loop instead of DataReceived
2// Form1 sınıfına ekle, port.Open() sonrasında _ = ReadLoopAsync(); çağır / add to Form1, call _ = ReadLoopAsync(); after port.Open()
3// Bu yöntemde port.DataReceived satırını sil / remove the port.DataReceived line when using this
4// Gerekenler / needs: using System.IO; using System.Threading.Tasks; (.NET 6/8'de örtük / implicit)
5private async Task ReadLoopAsync()
6{
7    using var reader = new StreamReader(port.BaseStream, Encoding.ASCII, false, 256, leaveOpen: true);
8    try
9    {
10        while (port.IsOpen)
11        {
12            string? line = await reader.ReadLineAsync();   // beklerken arayüz donmaz / the UI stays responsive while waiting
13            if (line == null) break;
14            ShowLine(line.Trim());                          // await sonrası yine UI iş parçacığındayız / back on the UI thread after await
15        }
16    }
17    catch (IOException) { }                                 // port kapatıldı / port was closed
18    catch (InvalidOperationException) { }                   // nesne kapatıldı / object disposed
19    catch (OperationCanceledException) { }
20}
21
If the interface still stutters, check three things: is there a Thread.Sleep() in UI code, is the interface being flooded with hundreds of BeginInvoke calls per second, and is Invoke used while the port is closing? If the Arduino sends very often, set the send interval to 50–100 ms or collect the values and update the interface 10 times per second.

Port listing and connection problems

Symptom or errorLikely causeFix
Access to the port 'COM3' is deniedThe Serial Monitor, Serial Plotter or another application is using the portClose the other program, then click Connect
The port 'COM3' does not existThe board was unplugged or the port number changedClick Refresh and check Ports in Device Manager
The port list is emptyDriver not installed or a charge-only cableInstall the CH340 driver and use a data cable
The port opens but no data arrives (Leonardo, Pro Micro)Native USB boards don't send while DTR is offSet DtrEnable = true
The ESP32 stops working when you connectRtsEnable is true, the EN line is held lowSet both RtsEnable and DtrEnable to false
The first line is garbled or incompleteThe board reset on open or a half line arrivedCheck the line format before parsing and skip the first line
Garbage charactersBaud rates differMake BaudRate match Serial.begin()

GetPortNames() only returns short names like COM3, and their order isn't guaranteed. To show descriptive names such as Arduino Uno (COM3) in the list, you can query the Win32_PnPEntity class with the System.Management library; for simple projects, a look at Device Manager is enough. If your clone board doesn't show up at all, the CH340 driver installation guide walks you through it. If you're curious about the UART protocol itself, take a look at the UART serial communication guide.

The same application with an ESP32 (USB and Bluetooth)

The same C# application also works with an ESP32; you only need to set BaudRate to 115200. The sketch below reads the potentiometer on GPIO 34 and converts the 12-bit value to the 0–1023 range, so not a single line changes on the C# side. Because the ESP32 pins are 3.3 V, connect the potentiometer's outer leg to 3V3, not 5 V. A nice extra is the classic ESP32's Bluetooth serial port: the BluetoothSerial library turns the board into a wireless COM port, and the C# application opens it just like a USB port.

C++ (Arduino IDE)
1// ESP32 <-> C#: aynı uygulama, USB ya da Bluetooth seri port / same app over USB or Bluetooth serial
2#include <BluetoothSerial.h>        // yalnız klasik ESP32 (S3/C3'te yok) / classic ESP32 only (not S3/C3)
3
4BluetoothSerial SerialBT;
5const int LED_PIN = 2;              // çoğu kartta dahili LED / onboard LED on most boards
6const int SENSOR_PIN = 34;          // ADC1, yalnız giriş / input only
7unsigned long lastSend = 0;
8String usbCmd, btCmd;               // her kaynak için ayrı tampon / one buffer per source
9
10void handleCommand(String& cmd) {
11  cmd.trim();
12  if (cmd == "LED:1") digitalWrite(LED_PIN, HIGH);
13  else if (cmd == "LED:0") digitalWrite(LED_PIN, LOW);
14  cmd = "";
15}
16
17void readFrom(Stream& s, String& buf) {   // Serial ve SerialBT için ortak / shared by Serial and SerialBT
18  while (s.available() > 0) {
19    char c = s.read();
20    if (c == '\n') handleCommand(buf);
21    else if (buf.length() < 16) buf += c;
22  }
23}
24
25void setup() {
26  Serial.begin(115200);                // C#'ta BaudRate = 115200 / set BaudRate = 115200 in C#
27  SerialBT.begin("BlueGrays-ESP32");   // Windows'ta eşleştir, COM portu çıkar / pair in Windows to get a COM port
28  pinMode(LED_PIN, OUTPUT);
29}
30
31void loop() {
32  readFrom(Serial, usbCmd);
33  readFrom(SerialBT, btCmd);
34  if (millis() - lastSend >= 100) {
35    lastSend = millis();
36    int v = map(analogRead(SENSOR_PIN), 0, 4095, 0, 1023);   // 12 bit -> 10 bit, C# kodu değişmez / C# code unchanged
37    Serial.printf("A0:%d\n", v);
38    if (SerialBT.hasClient()) SerialBT.printf("A0:%d\n", v);
39  }
40}
41

For Bluetooth, pair the BlueGrays-ESP32 device in Windows under Settings > Bluetooth & devices > Add device. Then, on the More Bluetooth settings > COM Ports tab, you'll see two ports; in the C# application, select the one marked Outgoing. Classic Bluetooth (SPP) is only available on the original ESP32; the ESP32-S3 and ESP32-C3 support BLE only and don't create a COM port this way. On a wired connection, the ESP32 board's DTR and RTS lines go to the auto-program circuit, so leaving both false is the safest choice.

Project ideas with C# and Arduino

  • Data logger: write the A0 values with a timestamp to a CSV file and chart them in Excel (Arduino to Excel data export).
  • Temperature panel: plot DHT11 readings live with the C# Chart control.
  • Relay control panel: switch four relay channels on and off with four buttons.
  • Servo slider: set the angle of a servo motor between 0 and 180 degrees with a TrackBar.
  • RFID attendance: list and save the card numbers read by an RC522 in the C# application.

If you want to test the Arduino side step by step before writing the C# application, the BlueGrays app has projects such as lighting an LED, reading light intensity with an LDR and switching an LED from your phone over Bluetooth, each with a circuit diagram and ready-made code; once the serial values look right, connecting the C# interface takes just a few minutes. If you'd rather do the same in Python, the Arduino Python serial communication article is ready too.

Frequently asked questions

How do I connect C# to an Arduino?

With the SerialPort class from the System.IO.Ports namespace. Set PortName to the Arduino's COM port and BaudRate to the value in the Arduino's Serial.begin(), then call Open(). After that, send commands with WriteLine() and read incoming data with the DataReceived event.

Why do I get a SerialPort could not be found error?

In .NET 6, 7 and 8 projects, the SerialPort class is a separate NuGet package. You need to install System.IO.Ports from Project > Manage NuGet Packages. In older .NET Framework 4.x projects, the class is built in.

Why does my C# application freeze while reading the serial port?

When ReadLine() is called on the UI thread, it waits until a line arrives, and ReadTimeout is infinite by default. Move reading to the DataReceived event or an async loop, and update the interface with BeginInvoke or after await.

How do I fix Access to the port COM3 is denied?

This error means another program has the port open. Close the Arduino IDE Serial Monitor, the Serial Plotter or a second copy of your application. Also disconnect in the C# application while uploading code.

Why doesn't my Arduino Leonardo send data to C#?

Boards with native USB such as the Leonardo and Pro Micro don't send serial data until the computer asserts DTR. SerialPort's DtrEnable property is false by default, so the port opens but no data arrives. Setting DtrEnable = true fixes it.

Does the C# application work with an ESP32?

Yes. The ESP32 also appears as a COM port over USB; just set BaudRate to 115200. On a classic ESP32, a board paired via the BluetoothSerial library also creates a wireless COM port in Windows, and the same application can connect to it.

See all projects
LED Blink
AR-1Beginner

LED Blink

The very first hello of electronics: switching a single LED on and off. The Arduino keeps the LED on for one second and off for one second, so you can easily follow every blink.

4.6(203)
1382
Measuring Light Intensity with an LDR
AR-11Beginner

Measuring Light Intensity with an LDR

Want to see how bright your room is as a number? The LDR, a small part that reacts to light, measures the light around it, and the Arduino writes the value to your computer screen every half second.

4.5(86)
154
HC-SR04 Distance Measurement (Serial Display)
AR-27Beginner

HC-SR04 Distance Measurement (Serial Display)

The HC-SR04 sensor works just like a bat finding its way in the dark: it sends out a sound you cannot hear, listens for the echo and measures how far away the object in front of it is.

4.6(52)
94
Temperature and Humidity with DHT11
AR-55Intermediate

Temperature and Humidity with DHT11

How warm is your room, and is the air humid or dry? The DHT11 sensor measures temperature and humidity, and the Arduino writes the values on a two-line LCD screen, refreshing every couple of seconds.

4.7(47)
96
Control an LED from Your Phone via Bluetooth
AR-34Beginner
Premium

Control an LED from Your Phone via Bluetooth

A small rehearsal for switching the lights in your room on and off from your phone.

4.8(69)
91
One-Way Communication Between 2 Arduinos
AR-57Intermediate
Premium

One-Way Communication Between 2 Arduinos

You get two Arduinos talking over a single wire: press the button on one and the LED on the other lights up, press it again and it goes off.

4.5(38)
51
LED Blink with ESP32
ES-1Beginner

LED Blink with ESP32

Teaches basic GPIO output usage with ESP32. We achieve a blinking effect by turning an LED on and off from a digital pin. ESP32 version of the classic blink project on Arduino UNO; the basic blink commands in the Arduino environment are the same, but the ESP32's pin layout and 3.3 V GPIO levels differ from those of the Arduino UNO.

4.7(38)
114
ESP32 LED Brightness Control with a Potentiometer (Analog → PWM)
ES-13Intermediate
Premium

ESP32 LED Brightness Control with a Potentiometer (Analog → PWM)

In this project, we control the brightness of an LED analogically using a potentiometer. The ESP32's ADC pin reads the 0-3.3V voltage from the potentiometer, and this value is then converted into a PWM (Pulse Width Modulation) signal and sent to the LED. As a result, as you turn the potentiometer, the LED gradually brightens and dims. With Arduino Core 3.0+, analogWrite() can be used directly; on the ESP32-S2/S3, the ADC resolution is fixed at 12-bit.

4.4(20)
32