Pendahuluan
Dokumentasi ini menjelaskan implementasi sistem pengukur tinggi badan anak menggunakan ESP32 DevKitC v4 dan sensor ultrasonik HC-SR04. Sistem ini menggunakan filter moving average dan median untuk stabilisasi data, dilengkapi dengan validasi, kalibrasi, dan output JSON untuk integrasi sistem.
1. Persiapan Lingkungan Pengembangan
1.1 Membuat Virtual Environment Python
Virtual environment Python memastikan isolasi dependensi proyek untuk menghindari konflik versi package.
1.2 Mengaktifkan Virtual Environment
Aktifkan environment sebelum menjalankan perintah PlatformIO:
1
| source venv/bin/activate
|
PlatformIO adalah framework cross-platform untuk pengembangan embedded systems dan IoT.
2. Inisialisasi Proyek ESP32
2.1 Membuat Direktori Proyek
1
| mkdir sok-anak-hw && cd sok-anak-hw
|
1
| pio init --board esp32dev
|
Perintah ini menghasilkan struktur proyek:
platformio.ini - File konfigurasi utamasrc/ - Direktori source codelib/ - Library eksternalinclude/ - Header files (opsional)test/ - Unit tests (opsional)
1
2
3
4
5
6
7
8
9
10
| sok-anak-hw
├── include
│ └── README
├── lib
│ └── README
├── platformio.ini
├── src
│ └── main.cpp
└── test
└── README
|
4. Spesifikasi Hardware
| Komponen | Spesifikasi |
|---|
| Board | ESP32 DevKitC v4 |
| MCU | ESP32-WROOM-32 |
| Sensor | HC-SR04 Ultrasonic |
| Pin Trigger | GPIO23 |
| Pin Echo | GPIO22 |
| Tombol Kalibrasi | GPIO19 |
| LED Status | GPIO2 (onboard) |
5. Implementasi Kode Sensor Ultrasonik
5.1 Membuat File Source Utama
5.2 Kode Program Lengkap
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
| #include <Arduino.h>
#include <NewPing.h>
#include <ArduinoJson.h>
/**
* SISTEM PENGUKUR TINGGI BADAN ANAK
*
* Fitur:
* 1. Pengukuran tinggi badan anak (150cm - jarak)
* 2. Moving average filter untuk pembacaan stabil
* 3. Validasi data (outlier detection)
* 4. Output JSON untuk pemrosesan data lanjutan
* 5. Mode debugging dan kalibrasi
*/
// ==================== KONFIGURASI PIN ====================
#define TRIGGER_PIN 23
#define ECHO_PIN 22
#define CALIB_BUTTON 19
#define STATUS_LED 2 // LED onboard ESP32
// ==================== KONSTANTA SISTEM ====================
const float POLE_HEIGHT_CM = 150.0; // Tinggi tiang penyangga sensor
const float MIN_VALID_HEIGHT = 50.0; // Tinggi minimum valid (cm)
const float MAX_VALID_HEIGHT = 150.0; // Tinggi maksimum valid (cm)
const float MAX_SENSOR_RANGE = 200.0; // Maksimal jarak sensor (cm) - nama diubah
// Konfigurasi filter
const int NUM_READINGS = 15; // Jumlah sampel untuk moving average
const int MEDIAN_WINDOW = 5; // Ukuran window untuk median filter
// Threshold untuk deteksi outlier
const float DISTANCE_JUMP_THRESHOLD = 20.0; // cm
const int STABLE_READING_COUNT = 3; // Jumlah pembacaan stabil
// ==================== DEKLARASI OBJEK ====================
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_SENSOR_RANGE);
// ==================== VARIABEL SISTEM ====================
float readings[NUM_READINGS];
int readIndex = 0;
float total = 0;
float medianBuffer[MEDIAN_WINDOW];
int medianIndex = 0;
// State variables
float currentDistance = 0;
float currentHeight = 0;
float averageHeight = 0;
bool isStable = false;
int stableCount = 0;
unsigned long lastMeasurementTime = 0;
unsigned long measurementInterval = 250; // ms
// Kalibrasi
float calibrationOffset = 0.0;
bool debugMode = false;
// ==================== PROTOTIPE FUNGSI ====================
void initializeSystem();
void printSystemInfo();
float getFilteredDistance();
float getMedianDistance();
float calculateHeight(float distance);
bool validateHeight(float height);
void processMeasurement();
void printMeasurement();
void printJSONMeasurement();
void calibrationRoutine();
void printDebugInfo();
void blinkLED(int times, int delayTime);
void handleSerialCommands();
// ==================== SETUP SISTEM ====================
void setup() {
Serial.begin(115200);
delay(1000); // Tunggu Serial ready
// Inisialisasi pin
pinMode(STATUS_LED, OUTPUT);
pinMode(CALIB_BUTTON, INPUT_PULLUP);
// Inisialisasi array
for (int i = 0; i < NUM_READINGS; i++) {
readings[i] = 0;
}
for (int i = 0; i < MEDIAN_WINDOW; i++) {
medianBuffer[i] = 0;
}
initializeSystem();
printSystemInfo();
blinkLED(3, 200); // Indikator startup
}
// ==================== LOOP UTAMA ====================
void loop() {
// Handle serial commands
handleSerialCommands();
// Cek tombol kalibrasi
if (digitalRead(CALIB_BUTTON) == LOW) {
delay(50); // Debounce
if (digitalRead(CALIB_BUTTON) == LOW) {
calibrationRoutine();
}
}
// Pengukuran pada interval tertentu
unsigned long currentTime = millis();
if (currentTime - lastMeasurementTime >= measurementInterval) {
processMeasurement();
lastMeasurementTime = currentTime;
}
// Update LED status
digitalWrite(STATUS_LED, isStable ? HIGH : LOW);
}
// ==================== IMPLEMENTASI FUNGSI ====================
/**
* Inisialisasi sistem
*/
void initializeSystem() {
Serial.println("\n" + String(80, '='));
Serial.println("SISTEM PENGUKUR TINGGI BADAN ANAK");
Serial.println(String(80, '='));
Serial.println("Konfigurasi:");
Serial.println("- Tinggi tiang: " + String(POLE_HEIGHT_CM) + " cm");
Serial.println("- Rentang valid: " + String(MIN_VALID_HEIGHT) + " - " +
String(MAX_VALID_HEIGHT) + " cm");
Serial.println("- Filter: Moving Average (" + String(NUM_READINGS) + " samples)");
Serial.println("- Filter: Median (" + String(MEDIAN_WINDOW) + " samples)");
Serial.println(String(80, '-'));
Serial.println("Perintah Serial:");
Serial.println(" 'd' - Toggle debug mode");
Serial.println(" 'c' - Kalibrasi");
Serial.println(" 'j' - Toggle JSON output");
Serial.println(" 'r' - Reset filter");
Serial.println(" '?' - Tampilkan info sistem");
Serial.println(String(80, '=') + "\n");
}
/**
* Tampilkan info sistem
*/
void printSystemInfo() {
Serial.println("\n=== INFO SISTEM ===");
Serial.println("Status: " + String(isStable ? "STABIL" : "MENCARI"));
Serial.println("Offset Kalibrasi: " + String(calibrationOffset, 1) + " cm");
Serial.println("Interval Pengukuran: " + String(measurementInterval) + " ms");
Serial.println("Mode Debug: " + String(debugMode ? "AKTIF" : "NON-AKTIF"));
Serial.println("===================\n");
}
/**
* Dapatkan jarak terfilter dengan moving average
*/
float getFilteredDistance() {
// Kurangkan nilai lama dari total
total -= readings[readIndex];
// Baca jarak baru dari sensor
delay(30); // Waktu stabilisasi sensor
unsigned int pingTime = sonar.ping();
float newDistance = sonar.convert_cm(pingTime);
// Validasi pembacaan
if (newDistance <= 0 || newDistance > MAX_SENSOR_RANGE) {
newDistance = 0; // Invalid reading
}
// Update moving average
readings[readIndex] = newDistance;
total += newDistance;
readIndex = (readIndex + 1) % NUM_READINGS;
return total / NUM_READINGS;
}
/**
* Dapatkan jarak dengan median filter
*/
float getMedianDistance() {
float filteredDistance = getFilteredDistance();
// Update median buffer
medianBuffer[medianIndex] = filteredDistance;
medianIndex = (medianIndex + 1) % MEDIAN_WINDOW;
// Sort buffer untuk mencari median
float tempBuffer[MEDIAN_WINDOW];
memcpy(tempBuffer, medianBuffer, sizeof(tempBuffer));
// Bubble sort sederhana
for (int i = 0; i < MEDIAN_WINDOW - 1; i++) {
for (int j = 0; j < MEDIAN_WINDOW - i - 1; j++) {
if (tempBuffer[j] > tempBuffer[j + 1]) {
float temp = tempBuffer[j];
tempBuffer[j] = tempBuffer[j + 1];
tempBuffer[j + 1] = temp;
}
}
}
// Return median (middle value)
return tempBuffer[MEDIAN_WINDOW / 2];
}
/**
* Hitung tinggi badan dari jarak
*/
float calculateHeight(float distance) {
if (distance <= 0 || distance > POLE_HEIGHT_CM - MIN_VALID_HEIGHT) {
return 0; // Invalid
}
return POLE_HEIGHT_CM - distance + calibrationOffset;
}
/**
* Validasi tinggi badan
*/
bool validateHeight(float height) {
return (height >= MIN_VALID_HEIGHT && height <= MAX_VALID_HEIGHT);
}
/**
* Proses pengukuran
*/
void processMeasurement() {
// Dapatkan jarak terfilter
float distance = getMedianDistance();
currentDistance = distance;
// Hitung tinggi badan
float height = calculateHeight(distance);
currentHeight = height;
// Update average height jika valid
if (validateHeight(height)) {
// Deteksi perubahan mendadak (outlier)
static float lastValidHeight = 0;
if (abs(height - lastValidHeight) < DISTANCE_JUMP_THRESHOLD || lastValidHeight == 0) {
stableCount++;
lastValidHeight = height;
if (stableCount >= STABLE_READING_COUNT) {
isStable = true;
averageHeight = (averageHeight * 0.7) + (height * 0.3); // Exponential moving average
}
} else {
stableCount = 0;
isStable = false;
}
} else {
stableCount = 0;
isStable = false;
}
// Tampilkan hasil
printMeasurement();
if (debugMode) {
printDebugInfo();
}
}
/**
* Tampilkan hasil pengukuran
*/
void printMeasurement() {
static unsigned long lastPrint = 0;
if (millis() - lastPrint < 500 && !isStable) {
return; // Batasi output untuk pembacaan tidak stabil
}
Serial.print("T: ");
Serial.print(millis() / 1000.0, 1);
Serial.print("s | ");
if (isStable) {
Serial.print("TINGGI: ");
Serial.print(averageHeight, 1);
Serial.print(" cm");
// Tambahkan kategori berdasarkan tinggi
if (averageHeight < 100) {
Serial.print(" (Balita)");
} else if (averageHeight < 120) {
Serial.print(" (Anak Kecil)");
} else if (averageHeight < 140) {
Serial.print(" (Anak Besar)");
} else {
Serial.print(" (Remaja)");
}
} else {
Serial.print("Mengukur... ");
Serial.print(currentHeight, 1);
Serial.print(" cm");
if (currentHeight < MIN_VALID_HEIGHT) {
Serial.print(" (Terlalu dekat)");
} else if (currentHeight > MAX_VALID_HEIGHT) {
Serial.print(" (Tidak terdeteksi)");
}
}
if (debugMode) {
Serial.print(" | D: ");
Serial.print(currentDistance, 1);
Serial.print(" cm | S: ");
Serial.print(stableCount);
}
Serial.println();
lastPrint = millis();
}
/**
* Tampilkan output JSON (untuk integrasi dengan software lain)
*/
void printJSONMeasurement() {
JsonDocument doc; // Gunakan JsonDocument bukan StaticJsonDocument
doc["timestamp"] = millis();
doc["distance_cm"] = currentDistance;
doc["height_cm"] = currentHeight;
doc["average_height_cm"] = averageHeight;
doc["stable"] = isStable;
doc["stable_count"] = stableCount;
doc["valid"] = validateHeight(currentHeight);
serializeJson(doc, Serial);
Serial.println();
}
/**
* Rutin kalibrasi
*/
void calibrationRoutine() {
Serial.println("\n=== MULAI KALIBRASI ===");
Serial.println("Letakkan objek dengan tinggi diketahui di bawah sensor");
Serial.println("Tekan Enter untuk melanjutkan...");
while (Serial.available() == 0) {
delay(100);
}
Serial.readString(); // Clear buffer
Serial.print("Masukkan tinggi objek (cm): ");
while (Serial.available() == 0) {
delay(100);
}
float referenceHeight = Serial.parseFloat();
Serial.println(referenceHeight);
Serial.println("Mengukur...");
// Ambil beberapa sampel untuk kalibrasi
float totalMeasuredHeight = 0;
const int calibSamples = 10;
for (int i = 0; i < calibSamples; i++) {
float distance = getMedianDistance();
float height = POLE_HEIGHT_CM - distance;
totalMeasuredHeight += height;
Serial.print("Sampel ");
Serial.print(i + 1);
Serial.print(": ");
Serial.print(height, 1);
Serial.println(" cm");
delay(200);
}
float measuredHeight = totalMeasuredHeight / calibSamples;
calibrationOffset = referenceHeight - measuredHeight;
Serial.println("\n=== HASIL KALIBRASI ===");
Serial.print("Tinggi referensi: ");
Serial.print(referenceHeight, 1);
Serial.println(" cm");
Serial.print("Tinggi terukur: ");
Serial.print(measuredHeight, 1);
Serial.println(" cm");
Serial.print("Offset: ");
Serial.print(calibrationOffset, 1);
Serial.println(" cm");
Serial.println("=== KALIBRASI SELESAI ===\n");
blinkLED(5, 100); // Indikator kalibrasi selesai
}
/**
* Tampilkan info debug
*/
void printDebugInfo() {
static unsigned long lastDebugPrint = 0;
if (millis() - lastDebugPrint < 1000) {
return;
}
Serial.println("\n--- DEBUG INFO ---");
Serial.print("Raw Distance: ");
Serial.print(currentDistance);
Serial.println(" cm");
Serial.print("Readings Buffer: ");
for (int i = 0; i < NUM_READINGS; i++) {
Serial.print(readings[(readIndex + i) % NUM_READINGS], 0);
Serial.print(" ");
}
Serial.println();
Serial.print("Total: ");
Serial.print(total);
Serial.print(", Average: ");
Serial.print(total / NUM_READINGS, 1);
Serial.println();
Serial.print("Free Heap: ");
Serial.print(ESP.getFreeHeap());
Serial.println(" bytes");
Serial.println("-----------------\n");
lastDebugPrint = millis();
}
/**
* LED blinking untuk indikasi
*/
void blinkLED(int times, int delayTime) {
for (int i = 0; i < times; i++) {
digitalWrite(STATUS_LED, HIGH);
delay(delayTime);
digitalWrite(STATUS_LED, LOW);
delay(delayTime);
}
}
/**
* Handle serial commands
*/
void handleSerialCommands() {
if (Serial.available() > 0) {
char command = Serial.read();
switch (command) {
case 'd': // Toggle debug mode
debugMode = !debugMode;
Serial.println("Debug mode: " + String(debugMode ? "ON" : "OFF"));
break;
case 'c': // Kalibrasi
calibrationRoutine();
break;
case 'j': // JSON output
printJSONMeasurement();
break;
case 'r': // Reset filter
for (int i = 0; i < NUM_READINGS; i++) {
readings[i] = 0;
}
total = 0;
stableCount = 0;
isStable = false;
Serial.println("Filter reset");
break;
case '?': // System info
printSystemInfo();
break;
case 'i': // Increase interval
measurementInterval += 50;
Serial.println("Interval: " + String(measurementInterval) + " ms");
break;
case 'k': // Decrease interval
if (measurementInterval > 100) {
measurementInterval -= 50;
}
Serial.println("Interval: " + String(measurementInterval) + " ms");
break;
case '\n': // Ignore newline
case '\r':
break;
default:
Serial.println("Perintah tidak dikenal. Gunakan '?' untuk bantuan.");
}
}
}
|
6. Build dan Upload Program
6.1 Clean Build Project
6.2 Build dan Upload Project
1
| pio run --target upload
|
PlatformIO akan otomatis:
- Mengunduh dependensi yang diperlukan
- Mengompilasi source code
- Mengupload firmware ke ESP32
7. Troubleshooting Upload
7.1 Identifikasi Port Serial
7.2 Upload dengan Port Spesifik
1
| pio run --target upload --upload-port /dev/ttyUSB0
|
8. Serial Monitoring
8.1 Membuka Serial Monitor
8.2 Serial Monitor dengan Baudrate Khusus
1
| pio device monitor -b 115200
|
9. Mode Download untuk ESP32 DevKitC v4
Prosedur Masuk Mode Download Manual:
- Tahan tombol BOOT pada ESP32
- Tekan dan lepas tombol EN (reset)
- Lepas tombol BOOT
ESP32 DevKitC v4 memerlukan prosedur ini karena tidak memiliki auto-reset circuit untuk programming.
10. Dependencies dan Library
Proyek ini menggunakan library berikut:
- Framework: Arduino (via PlatformIO)
- NewPing: v1.9.7 (library sensor ultrasonik)
- ArduinoJson: v7.4.2 (untuk serialisasi JSON)
- Platform: espressif32
Kesimpulan
Dokumentasi ini memberikan panduan lengkap untuk mengembangkan sistem pengukur tinggi badan berbasis ESP32 dengan PlatformIO. Implementasi mencakup filter data, sistem kalibrasi, validasi, dan output multiple format. PlatformIO menyederhanakan workflow development dengan manajemen dependensi otomatis dan toolchain terintegrasi.