Arduino GPS Geofence: Virtual Fence Alarm with NEO-6M and SMS
Build an Arduino GPS geofence: NEO-6M safe zone, Haversine distance, circle and polygon fences, buzzer and SMS alerts, animal tracking and battery life.
An Arduino GPS geofence is an invisible boundary defined by GPS coordinates instead of a physical wire or wall: when the device leaves this safe zone, a buzzer sounds and, if you like, your phone gets an SMS with a link to its location. This kind of virtual fence is used to keep track of goats and sheep on a pasture, a dog that escapes from the garden, a parked motorbike or a robot lawn mower. With an Arduino or ESP32, a NEO-6M GPS module and a buzzer you can build your first geofence over a weekend.
In this guide you'll first see the Haversine formula, which calculates the distance between two positions, and why you can't convert a difference in degrees straight into metres. Then we'll compare circle, rectangle and polygon fences in a table, learn to filter out the false alarms caused by GPS drift, and code a circular fence on an Arduino Uno and a polygon fence on an ESP32 that sends an SMS through a SIM800L. Finally we'll cover animal tracking and garden uses, battery life and common mistakes.

What is a geofence and how does it work?
In a virtual fence the boundary is just a few numbers in the code: the centre and radius of a circle, or the corners of a polygon. The GPS module gives a new position every second, and the microcontroller works out whether that position is inside or outside the boundary. The hard part isn't the maths but the decision: the GPS position wanders a few metres even on a device that never moves, and a single bad reading means a false alarm. That's why a good geofence works in four steps:
- Get the position: The NEO-6M sends latitude, longitude, satellite count and HDOP every second.
- Check it can be trusted: Ignore the reading if fewer than 5 satellites are used, HDOP is above 3, or the fix is more than 2 seconds old.
- Compare it with the boundary: For a circle, calculate the distance to the centre with Haversine; for a polygon, find out whether the point is inside with the ray casting method.
- Filter the decision and raise the alarm: Change state only when several readings in a row agree and the boundary is crossed by a margin, then sound the buzzer and send an SMS.
Parts list
| Part | Job | Note |
|---|---|---|
| Arduino Uno or ESP32 | Maths and decisions | For the SMS version, an ESP32 with two hardware UARTs |
| NEO-6M GPS module | Position | The ceramic antenna must face the sky |
| SIM800L GSM module | Sending SMS | 2G networks only, current peaks up to 2 A |
| Active buzzer | Local audible alarm | On the ESP32, a model that beeps at 3.3 V or a transistor |
| 18650 Li-ion cell and TP4056 charger module | Portable power | The SIM800L can run straight from the cell |
| 3.3 V LDO regulator (e.g. HT7833) | Powers the ESP32 and GPS | Low quiescent current, at least 500 mA |
| 1 kΩ, 2 kΩ and 5.6 kΩ resistors | Voltage dividers | For GPS RX (Uno) and SIM800L RXD |
The Haversine formula: distance between two positions
Latitude and longitude are in degrees and the Earth isn't flat, so you can't take the difference in degrees between two points and multiply it by a fixed number. One degree of latitude is about 111.2 km everywhere. For longitude, though, the meridians get closer together towards the poles, so the length of one degree shrinks with the cosine of the latitude:
| Latitude (example place) | Length of 1° of longitude | 0.001° of longitude |
|---|---|---|
| 0° (equator) | 111.2 km | 111 m |
| 37° (Antalya) | 88.8 km | 89 m |
| 41° (Istanbul, New York) | 83.9 km | 84 m |
| 52° (Berlin, London) | 68.5 km | 68 m |
The Haversine formula takes this curvature into account and gives the shortest surface distance between two points: a = sin²(Δφ/2) + cos φ1 · cos φ2 · sin²(Δλ/2) and d = 2R · atan2(√a, √(1−a)). Here φ is latitude and λ is longitude (in radians), and R is the Earth's mean radius, 6,371,000 metres. For example, at 41° latitude a point 0.0009 degrees north and 0.001 degrees east of the centre is 100.1 m away to the north, 83.9 m to the east and 130.6 m in total. Because most geofences are a few hundred metres across, a simpler flat approximation gives the same result: multiply the longitude difference by the cosine of the mean latitude and apply Pythagoras. The short sketch below compares the two:
1// İki konum arası mesafe: Haversine ve hızlı düz yaklaşım / distance between two points: Haversine and the fast flat approximation
2double haversineM(double lat1, double lon1, double lat2, double lon2) {
3 const double R = 6371000.0;
4 double dLat = radians(lat2 - lat1);
5 double dLon = radians(lon2 - lon1);
6 double a = sin(dLat / 2) * sin(dLat / 2) +
7 cos(radians(lat1)) * cos(radians(lat2)) * sin(dLon / 2) * sin(dLon / 2);
8 return 2 * R * atan2(sqrt(a), sqrt(1 - a));
9}
10
11double flatM(double lat1, double lon1, double lat2, double lon2) {
12 const double R = 6371000.0;
13 double x = radians(lon2 - lon1) * cos(radians((lat1 + lat2) / 2)); // doğu-batı / east-west
14 double y = radians(lat2 - lat1); // kuzey-güney / north-south
15 return R * sqrt(x * x + y * y);
16}
17
18void setup() {
19 Serial.begin(115200);
20 // Merkez ve bir nokta: kuzeyde 0,0009°, doğuda 0,001° / centre and a point 0.0009° north, 0.001° east
21 Serial.println(haversineM(41.015137, 28.979530, 41.016037, 28.980530), 1);
22 Serial.println(flatM(41.015137, 28.979530, 41.016037, 28.980530), 1);
23}
24
25void loop() {
26}Both functions print about 130.6 to the Serial Monitor; at this scale the difference between them is less than a centimetre. The flat approximation starts to drift beyond a few kilometres, while Haversine stays accurate over hundreds of kilometres. On an Arduino Uno, double is really a 32-bit float and holds coordinates to about 0.4 metres, which is more than enough for a geofence. The TinyGPSPlus library's distanceBetween() function does the same job; we cover installing the library and wiring the GPS in detail in NEO-6M GPS module.
Fence types: circle, rectangle and polygon
| Fence type | How it's defined | How it's checked | Where it's used |
|---|---|---|---|
| Circle | Centre point and radius | Is the Haversine distance less than the radius? | Around a house or garden, a park, a campsite |
| Rectangle (box) | Minimum and maximum latitude and longitude | Four simple comparisons | A field aligned north-south, a car park |
| Polygon | Corner points in order along the boundary | Ray casting algorithm | Irregular pasture, garden or plot boundary |
| Ring (two circles) | Inner warning and outer alarm radius | Two distance comparisons | Graded warning: beep first, then SMS |
| Corridor | Route line and width | Distance from the point to the line | School bus or tour route |
A circle is the easiest place to start: one centre and one radius are all you need. If your land is four-sided or irregular, use a polygon. To get the corner coordinates, right-click the spot in Google Maps on a computer and copy the numbers in the first line; on a phone, long-press the spot and the coordinates appear in the search box. Six decimal places mean a precision of about 11 centimetres. Write the polygon's corners in order along the boundary, clockwise or anticlockwise; corners in a jumbled order make a self-intersecting shape and the inside/outside decision becomes nonsense.
GPS accuracy: how to choose the radius
The 2.5 m CEP in the NEO-6M datasheet means half of the readings are within 2.5 metres of the true position; the other half are further away. Trees, buildings and metal roofs reflect the satellite signals, and the position can jump 10–30 metres within seconds. If you plot the position of a GPS sitting on a desk, you don't get a single point but a cloud several metres across. That's why you should choose the radius to suit the surroundings:
| Surroundings | Typical drift | Recommended minimum radius |
|---|---|---|
| Open land, pasture | 2–5 m | 20 m |
| Garden, near trees | 5–15 m | 30–40 m |
| Between buildings, city | 10–30 m, sometimes more | 50 m or more |
| Indoors, inside a barn | No fix or large drift | GPS isn't suitable |
Wiring diagram
| Part and pin | Arduino Uno | ESP32 | Note |
|---|---|---|---|
| NEO-6M VCC | 5V | 3V3 | The board has a regulator |
| NEO-6M TX | D4 (SoftwareSerial RX) | GPIO 16 (RX2) | Module output |
| NEO-6M RX | D3, via a 1 kΩ + 2 kΩ divider | GPIO 17 (TX2) | Input max 3.6 V |
| SIM800L VCC | Not used | 18650 (+) or a 4.0 V supply | 2 A current peaks |
| SIM800L TXD | Not used | GPIO 26 (RX1) | 2.8 V output |
| SIM800L RXD | Not used | GPIO 27 (TX1), via a 1 kΩ + 5.6 kΩ divider | Input max 3.1 V |
| Buzzer (+) | D8 | GPIO 25 | Active buzzer |
| GND | GND | GND | Battery, GPS, SIM800L and board share a common ground |
Circular geofence with a buzzer on the Arduino Uno
The first version needs no internet or SIM card: when the device is more than 50 metres from the centre, the buzzer beeps once a second and the distance is printed to the Serial Monitor. Replace HOME_LAT and HOME_LNG with your own centre point from Google Maps. The code doesn't use delay() in loop(); the GPS sends about 500 bytes a second, and SoftwareSerial's 64-byte buffer overflows during long waits:
1// Sanal çit (daire): NEO-6M + aktif buzzer, Arduino Uno / virtual fence (circle): NEO-6M + active buzzer
2#include <TinyGPSPlus.h>
3#include <SoftwareSerial.h>
4
5const double HOME_LAT = 41.015137; // güvenli bölgenin merkezi / centre of the safe zone
6const double HOME_LNG = 28.979530;
7const double RADIUS_M = 50.0; // yarıçap, metre / radius in metres
8const double MARGIN_M = 5.0; // histerezis payı / hysteresis margin
9const byte NEED_FIXES = 3; // art arda kaç ölçüm / how many readings in a row
10const int BUZZER_PIN = 8;
11
12TinyGPSPlus gps;
13SoftwareSerial gpsSerial(4, 3); // RX = D4 ← GPS TX, TX = D3 → GPS RX (bölücüyle / via divider)
14bool outside = false;
15byte outCount = 0, inCount = 0;
16unsigned long lastCheck = 0;
17
18double haversineM(double lat1, double lon1, double lat2, double lon2) {
19 const double R = 6371000.0; // Dünya yarıçapı, metre / Earth radius in metres
20 double dLat = radians(lat2 - lat1);
21 double dLon = radians(lon2 - lon1);
22 double a = sin(dLat / 2) * sin(dLat / 2) +
23 cos(radians(lat1)) * cos(radians(lat2)) * sin(dLon / 2) * sin(dLon / 2);
24 return 2 * R * atan2(sqrt(a), sqrt(1 - a));
25}
26
27void checkFence() {
28 if (!gps.location.isValid() || gps.location.age() > 2000) return; // eski konumu yok say / ignore stale fixes
29 if (gps.hdop.hdop() > 3.0 || gps.satellites.value() < 5) return; // zayıf konumu yok say / ignore weak fixes
30 double d = haversineM(HOME_LAT, HOME_LNG, gps.location.lat(), gps.location.lng());
31 if (d > RADIUS_M + MARGIN_M) { outCount++; inCount = 0; }
32 else if (d < RADIUS_M - MARGIN_M) { inCount++; outCount = 0; }
33 if (!outside && outCount >= NEED_FIXES) {
34 outside = true;
35 Serial.println(F("ALARM: bolge disi / outside the fence"));
36 }
37 if (outside && inCount >= NEED_FIXES) {
38 outside = false;
39 Serial.println(F("Bolgeye dondu / back inside"));
40 }
41 Serial.print(F("Mesafe / distance: "));
42 Serial.print(d, 1);
43 Serial.println(F(" m"));
44}
45
46void setup() {
47 Serial.begin(115200);
48 gpsSerial.begin(9600); // NEO-6M varsayılan hızı / NEO-6M default baud rate
49 pinMode(BUZZER_PIN, OUTPUT);
50}
51
52void loop() {
53 while (gpsSerial.available()) gps.encode(gpsSerial.read()); // her baytı ayrıştırıcıya ver / feed every byte
54 if (millis() - lastCheck >= 1000) { // saniyede bir kontrol / check once per second
55 lastCheck = millis();
56 checkFence();
57 }
58 // Bölge dışında 200 ms aç, 800 ms kapat / outside: 200 ms on, 800 ms off
59 bool beep = outside && (millis() % 1000 < 200);
60 digitalWrite(BUZZER_PIN, beep ? HIGH : LOW);
61}| Code part | What it does |
|---|---|
| HOME_LAT, HOME_LNG, RADIUS_M | Define the centre and radius of the safe zone |
| MARGIN_M = 5 | Hysteresis margin: going out means passing 55 m, coming back means dropping below 45 m |
| NEED_FIXES = 3 | How many readings in a row must agree before the state changes |
| hdop() > 3.0, satellites() < 5 | Leaves weak readings out of the calculation |
| location.age() > 2000 | Stops decisions being made on an old position if the GPS goes quiet |
| millis() % 1000 < 200 | Turns the buzzer on for the first 200 ms of every second while outside the zone |
Polygon geofence with SMS alerts on the ESP32
The second version defines the real shape of the land with corner points, and when the device leaves the zone it sends an SMS through the SIM800L with a Google Maps link to the position. Because the ESP32 has three hardware UARTs, the GPS goes on Serial2 and the SIM800L on Serial1, and both can be listened to at the same time without trouble. The polygon check uses the ray casting method: an imaginary ray is drawn eastwards from the point and the number of times it crosses the polygon's edges is counted; an odd number means inside, an even number means outside. The code waits at least 10 minutes between SMS messages and also sends one when the device comes back:
1// ESP32 sanal çit (çokgen) + SIM800L ile SMS / ESP32 virtual fence (polygon) + SMS with a SIM800L
2#include <TinyGPSPlus.h>
3
4#define GPS_RX 16 // ESP32 RX2 ← GPS TX
5#define GPS_TX 17 // ESP32 TX2 → GPS RX
6#define SIM_RX 26 // ESP32 RX1 ← SIM800L TXD
7#define SIM_TX 27 // ESP32 TX1 → SIM800L RXD (1k + 5,6k bölücü / divider)
8const int BUZZER_PIN = 25;
9const char PHONE[] = "+905551112233"; // SMS gidecek numara / number that gets the SMS
10
11// Güvenli bölgenin köşeleri: {enlem, boylam}, sırayla / corners of the safe zone in order: {lat, lng}
12const double POLY[][2] = {
13 {41.015600, 28.978900},
14 {41.015650, 28.980300},
15 {41.014700, 28.980450},
16 {41.014550, 28.979000}
17};
18const int N = sizeof(POLY) / sizeof(POLY[0]);
19const byte NEED_FIXES = 5; // 5 ölçüm üst üste / 5 readings in a row
20const unsigned long SMS_COOLDOWN_MS = 600000; // iki SMS arası en az 10 dk / at least 10 min between SMS
21
22TinyGPSPlus gps;
23HardwareSerial &gpsSerial = Serial2;
24HardwareSerial &sim = Serial1;
25bool outside = false;
26byte outCount = 0, inCount = 0;
27unsigned long lastCheck = 0, lastSms = 0;
28bool smsSent = false;
29
30// Işın atma: nokta çokgenin içinde mi? / ray casting: is the point inside the polygon?
31bool insidePolygon(double lat, double lng) {
32 bool in = false;
33 for (int i = 0, j = N - 1; i < N; j = i++) {
34 bool crosses = (POLY[i][0] > lat) != (POLY[j][0] > lat);
35 if (crosses) {
36 double lngAtLat = (POLY[j][1] - POLY[i][1]) * (lat - POLY[i][0]) / (POLY[j][0] - POLY[i][0]) + POLY[i][1];
37 if (lng < lngAtLat) in = !in;
38 }
39 }
40 return in;
41}
42
43bool waitFor(const char *word, unsigned long timeoutMs) { // cevapta kelimeyi bekle / wait for a word in the reply
44 String reply = "";
45 unsigned long start = millis();
46 while (millis() - start < timeoutMs) {
47 while (sim.available()) reply += (char)sim.read();
48 if (reply.indexOf(word) >= 0) return true;
49 if (reply.indexOf("ERROR") >= 0) return false;
50 }
51 return false;
52}
53
54bool sendSms(const String &text) {
55 sim.println("AT+CMGF=1"); // metin modu / text mode
56 if (!waitFor("OK", 2000)) return false;
57 sim.print("AT+CMGS=\"");
58 sim.print(PHONE);
59 sim.println("\"");
60 if (!waitFor(">", 5000)) return false;
61 sim.print(text);
62 sim.write(26); // Ctrl+Z: gönder / Ctrl+Z: send
63 return waitFor("+CMGS", 15000);
64}
65
66String mapsLink() {
67 return "https://www.google.com/maps/search/?api=1&query=" +
68 String(gps.location.lat(), 6) + "," + String(gps.location.lng(), 6);
69}
70
71void checkFence() {
72 if (!gps.location.isValid() || gps.location.age() > 2000) return;
73 if (gps.hdop.hdop() > 3.0 || gps.satellites.value() < 5) return;
74 bool in = insidePolygon(gps.location.lat(), gps.location.lng());
75 if (in) { inCount++; outCount = 0; } else { outCount++; inCount = 0; }
76
77 if (!outside && outCount >= NEED_FIXES) {
78 outside = true;
79 smsSent = false;
80 Serial.println("ALARM: bolge disi / outside the fence");
81 }
82 if (outside && inCount >= NEED_FIXES) {
83 outside = false;
84 Serial.println("Bolgeye dondu / back inside");
85 if (millis() - lastSms > SMS_COOLDOWN_MS) {
86 sendSms("Bolgeye dondu / back inside " + mapsLink());
87 lastSms = millis();
88 }
89 }
90 if (outside && !smsSent && (lastSms == 0 || millis() - lastSms > SMS_COOLDOWN_MS)) {
91 smsSent = sendSms("SANAL CIT ALARMI / FENCE ALARM " + mapsLink());
92 lastSms = millis();
93 Serial.println(smsSent ? "SMS gonderildi / sent" : "SMS gonderilemedi / failed");
94 }
95}
96
97void setup() {
98 Serial.begin(115200);
99 gpsSerial.setRxBufferSize(1024); // SMS sırasında veri taşmasın / room for data while sending SMS
100 gpsSerial.begin(9600, SERIAL_8N1, GPS_RX, GPS_TX);
101 sim.begin(9600, SERIAL_8N1, SIM_RX, SIM_TX);
102 pinMode(BUZZER_PIN, OUTPUT);
103 delay(3000); // SIM800L açılsın / let the SIM800L start
104 sim.println("ATE0"); // yankıyı kapat / echo off
105 waitFor("OK", 2000);
106}
107
108void loop() {
109 while (gpsSerial.available()) gps.encode(gpsSerial.read());
110 if (millis() - lastCheck >= 1000) {
111 lastCheck = millis();
112 checkFence();
113 }
114 bool beep = outside && (millis() % 1000 < 200);
115 digitalWrite(BUZZER_PIN, beep ? HIGH : LOW);
116}Animal tracking and garden uses
- Pasture and herd tracking: Fit a waterproof collar box to the goat or sheep that leads the herd and make sure the antenna faces up. To reach the farmhouse, a LoRa module needs no carrier and gives kilometres of range instead of SMS.
- Escaped dog alert: Define the garden as a polygon; if the dog slips out while the gate is open, you get an SMS with its position.
- Robot lawn mower and garden vehicles: Add an output that stops the motors if the robot crosses the boundary; because of GPS accuracy, use it as extra safety alongside a physical boundary wire.
- Motorbike, bicycle and boat: Define a 30–50 m circle where you park; if the vehicle leaves it, get an SMS in case it's being stolen.
- Camping and trips: A portable alarm that warns when a group of children wanders away from the campsite; use it only with the group's knowledge and consent.
Battery life: how many days does a geofence last?
In a portable geofence, the GPS uses the most energy. The NEO-6M draws about 47 mA while searching for satellites and 39 mA while tracking; an ESP32 with Wi-Fi off needs 30–50 mA and an idle SIM800L around 15 mA. If everything stays on, a 3000 mAh 18650 cell lasts only about a day. The solution is to run the system in bursts: the ESP32 wakes from deep sleep at set intervals, switches on the GPS, gets a fix, checks the boundary and goes back to sleep. The figures below are rough estimates for a 3000 mAh cell, a bare ESP32 module and a low-quiescent-current LDO:
| Operating mode | Average current | Approximate battery life |
|---|---|---|
| Everything always on (ESP32 + NEO-6M + idle SIM800L) | About 120 mA | 1 day |
| A 30-second fix every 5 minutes, deep sleep in between, SIM800L in sleep mode | About 11 mA | 11 days |
| A 20-second fix every 15 minutes, SIM800L switched on only for alarms | About 2–3 mA | 6–8 weeks |
Two details matter when running in bursts. First, to get a GPS fix quickly, the backup battery on the NEO-6M board must be charged; if the module keeps its ephemeris data it finds a position within seconds (hot start), but after more than a few hours off it needs 30 seconds or more for a warm start. Second, switching the GPS and SIM800L off completely with a P-channel MOSFET uses less energy than leaving them in their sleep modes, but the SIM800L needs 10–30 seconds to register on the network every time it starts. You'll find the sleep modes and RTC memory in ESP32 deep sleep, battery safety in 18650 Li-ion battery and TP4056 charger module, and you can work out your own scenario with the Battery Life tool.
Common mistakes and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| No distance is ever printed | The module hasn't found a position yet, or the device is indoors | Go outside and wait 1–5 minutes for the first fix |
| Alarm while the device is standing still | GPS drift is bigger than the radius | Increase the radius, MARGIN_M and NEED_FIXES |
| Distance comes out as thousands of kilometres | Latitude and longitude swapped, or a sign error | Write latitude first; south and west coordinates are negative |
| The polygon says outside everywhere | Corners in a jumbled order, or latitude and longitude swapped | Write the corners in order along the boundary as {lat, lng} |
| SMS isn't sent | SIM800L supply too weak, no 2G coverage or SIM PIN enabled | Use a supply that can deliver 2 A, test with AT commands, disable the PIN |
| ESP32 restarts while sending an SMS | The voltage collapses on a supply shared with the SIM800L | Power the SIM800L on its own line from the battery, add a 1000 µF capacitor |
| Position occasionally garbled on the Uno | delay() in loop() or SoftwareSerial buffer overflow | Don't use delay(); switch to an ESP32 if needed |
A GPS geofence brings GPS, maths and communication together in one project, so it's both educational and genuinely useful. Try the circular fence with an Uno in your garden first, tune the radius to your surroundings, then move on to the polygon fence and SMS alarm with an ESP32 and SIM800L. In the BlueGrays app you can build up the alarm side of the system step by step with the buzzer alarm sound and ESP32 alarm system with Telegram notifications projects, complete with circuit diagrams and ready-made code.
Frequently asked questions
What is a GPS geofence?
A geofence is an invisible boundary defined by GPS coordinates instead of a physical wire. When the device leaves this safe zone, a buzzer sounds or the owner gets an SMS or notification. It's used for animal tracking, gardens, vehicle security and robot lawn mowers.
How do you make a geofence with Arduino?
Connect a GPS module such as the NEO-6M to an Arduino or ESP32 and define the safe zone in code as a centre and radius or as corner points. Every second, the microcontroller works out whether the position is inside the zone using the Haversine formula or a polygon test. When the device leaves the zone, a buzzer sounds and an SMS can be sent with a SIM800L.
How accurate is a GPS geofence?
On open land the NEO-6M usually gives a position within 2–5 metres, but near trees and buildings the drift can reach 10–30 metres. So the radius of a geofence should be at least 20 metres on open land and 30–40 metres in a garden. Requiring several readings in a row plus a hysteresis margin prevents most false alarms.
Does a geofence need internet?
No. GPS works from satellites, and a geofence with a buzzer runs with no connection at all. If you want remote alerts, you can use SMS with a SIM800L, Telegram where there's Wi-Fi, or LoRa over large areas such as farms.
Are virtual fences safe for animals?
A virtual fence that only uses sound and notifications won't harm an animal. The electric pulse in commercial collars belongs to tightly regulated products and shouldn't be built into hobby projects. Make the collar box light, waterproof and loose enough not to squeeze the animal's neck.
How long does a GPS tracker battery last?
With the GPS, ESP32 and SIM800L always on, a 3000 mAh cell lasts about a day. If the device wakes from deep sleep every 5–15 minutes to get a fix, that rises to several weeks. Using a bare ESP32 module and a low-quiescent-current regulator instead of a dev board also makes a big difference.
Projects to build after reading this
See all projects
Using a Buzzer
Ever wondered how a doorbell or an alarm makes its sound? The Arduino makes a small buzzer beep at short intervals: beep, pause, beep, pause.

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.

ESP32 Melody Playback with Buzzer
Playing a simple melody (Twinkle Twinkle Little Star) with a passive buzzer. We play notes with tone() and noTone() functions like in Arduino - ESP32 works with the same syntax as Arduino Core 3.0+. Passive buzzer must be used (active buzzer does not play melody).

ESP32 Motion Alarm System (PIR + Buzzer + LED + Telegram)
A smart security alarm: when the PIR sensor detects motion, it sounds the buzzer, lights the LED and sends the owner an instant Telegram notification. A 30-second cooldown limits how often the alarm repeats; it does not filter out the PIR sensor's false detections. Use it at home, in a garage, a storeroom or a study.

ESP32 Deep Sleep — Battery Saving (OLED + RTC RAM Counter)
The ESP32's Deep Sleep mode shuts down the CPU and most peripherals, cutting current draw to about 10µA, which is vital for battery-powered IoT devices. This project uses three wake-up sources: a timer (15 s), an external pin (EXT0, the button on GPIO 33) and a touch pin (T0/GPIO 4). Counters marked with RTC_DATA_ATTR survive deep sleep.

ESP32 Temperature Data Logger (DHT22 + DS1307 RTC + microSD + OLED)
Build a timed temperature and humidity logger with the ESP32! A DHT22 sensor reads temperature and humidity once a minute, and each reading is saved to a microSD card in CSV format with a real-time stamp from the DS1307 RTC module. The OLED display shows the latest temperature, humidity, timestamp and total number of records live, in large text.

ESP32 HTTPClient + Weather API (with SSD1306 OLED Display)
In this project the ESP32 makes a REST API call over the internet to a weather API (wttr.in) using HTTPClient.h. Unlike the I2C LCD version, it uses an SSD1306 OLED (128×64) display, with large text and vector icons for a richer look. Seven weather icons (sunny, rainy, snowy and more) are drawn on the fly, with no bitmap files.
More articles
BlueGrays app
Build this circuit step by step on your phone
Wiring diagram, code and parts list on one screen. 500+ Arduino, ESP32 and Pico projects ready to build.
Scan with your phone
Point your camera at the code and your phone's app store opens.
or open the store

