#include <WiFi.h>
#include <HTTPClient.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// ==================================================
// Wi-Fi Configuration
// ==================================================
const char* wifiSsid = "Wokwi-GUEST";
const char* wifiPassword = "";
// ==================================================
// API Configuration
// ==================================================
const char* attendanceBaseUrl =
"https://prathammardhekar.pythonanywhere.com/api/v1/iot/attendance";
const char* heartbeatUrl =
"https://prathammardhekar.pythonanywhere.com/api/v1/iot/heartbeat";
const char* deviceId = "device01-lab";
const char* apiToken = "0WXZQKcAlM7fKf1Yi9f6dPbRRQ64imGD";
// ==================================================
// Pin Configuration
// ==================================================
const int blinkLedPin = 18; // Yellow LED
const int greenLedPin = 4; // Green LED
const int pushButtonPin = 5; // Push button
const int potentiometerPin = 34; // Potentiometer SIG
// ==================================================
// LCD Configuration
// ==================================================
const int lcdAddress = 0x27;
const int lcdColumns = 16;
const int lcdRows = 2;
LiquidCrystal_I2C lcd(
lcdAddress,
lcdColumns,
lcdRows
);
// ==================================================
// Fingerprint Selection
// ==================================================
int selectedFingerprint = 1;
const int minFingerprint = 1;
const int maxFingerprint = 5;
bool buttonPressed = false;
// ==================================================
// Heartbeat Timing
// ==================================================
unsigned long lastHeartbeatTime = 0;
const unsigned long heartbeatInterval = 10000;
// ==================================================
// LCD: Ready Screen
// ==================================================
void displayBioTrack() {
lcd.setCursor(0, 0);
lcd.print("BioTrack ");
lcd.setCursor(0, 1);
lcd.print("FP Number: ");
lcd.print(selectedFingerprint);
lcd.print(" ");
}
// ==================================================
// LCD: Fingerprint Triggered
// ==================================================
void displayFingerprintTriggered() {
lcd.setCursor(0, 0);
lcd.print("Fingerprint ");
lcd.setCursor(0, 1);
lcd.print("Triggered FP:");
lcd.print(selectedFingerprint);
lcd.print(" ");
}
// ==================================================
// Potentiometer Reading
// ==================================================
void updatePotentiometer() {
// ESP32 ADC range: 0 to 4095.
int adcValue = analogRead(potentiometerPin);
// Reverse the reading:
// Rightmost (4095) -> Fingerprint 1
// Leftmost (0) -> Fingerprint 5
//
// Five equal ranges, with safe endpoint handling.
int reversedValue = 4095 - adcValue;
int newFingerprint =
1 + (reversedValue * 5L) / 4096;
newFingerprint = constrain(
newFingerprint,
minFingerprint,
maxFingerprint
);
// Update the LCD only when the selected number changes.
if (newFingerprint != selectedFingerprint) {
selectedFingerprint = newFingerprint;
Serial.print("Selected fingerprint: ");
Serial.println(selectedFingerprint);
if (buttonPressed) {
displayFingerprintTriggered();
} else {
displayBioTrack();
}
}
}
// ==================================================
// Extract Simple JSON String Value
// ==================================================
String extractJsonValue(String response, String key) {
String searchKey = "\"" + key + "\":\"";
int startPosition = response.indexOf(searchKey);
if (startPosition < 0) {
return "N/A";
}
startPosition += searchKey.length();
int endPosition = response.indexOf(
"\"",
startPosition
);
if (endPosition < 0) {
return "N/A";
}
return response.substring(
startPosition,
endPosition
);
}
// ==================================================
// Wi-Fi Connection
// ==================================================
void connectToWiFi() {
Serial.println();
Serial.println("Connecting to Wi-Fi...");
WiFi.mode(WIFI_STA);
WiFi.begin(wifiSsid, wifiPassword);
int retryCount = 0;
while (
WiFi.status() != WL_CONNECTED &&
retryCount < 30
) {
delay(500);
Serial.print(".");
retryCount++;
}
Serial.println();
if (WiFi.status() == WL_CONNECTED) {
Serial.println("Wi-Fi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
} else {
Serial.println("Wi-Fi connection failed");
}
}
// ==================================================
// Attendance API Request
// ==================================================
void sendAttendanceRequest() {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("Attendance: Wi-Fi not connected");
return;
}
// Construct the URL using the currently selected FP.
String attendanceUrl =
String(attendanceBaseUrl) +
"?device=" + String(deviceId) +
"&fp=" + String(selectedFingerprint) +
"&token=" + String(apiToken);
Serial.println();
Serial.println("========== ATTENDANCE ==========");
Serial.print("Selected FP: ");
Serial.println(selectedFingerprint);
Serial.println("Request URL:");
Serial.println(attendanceUrl);
HTTPClient http;
if (!http.begin(attendanceUrl)) {
Serial.println("Failed to initialize HTTP request");
return;
}
http.setConnectTimeout(5000);
http.setTimeout(8000);
int httpCode = http.GET();
Serial.print("HTTP Code: ");
Serial.println(httpCode);
if (httpCode > 0) {
String response = http.getString();
Serial.println("Raw API Response:");
Serial.println(response);
if (httpCode == 200) {
Serial.println("Status: SUCCESS");
} else {
Serial.println("Status: HTTP RESPONSE RECEIVED");
}
} else {
Serial.println("Status: REQUEST FAILED");
Serial.print("Error: ");
Serial.println(http.errorToString(httpCode));
}
http.end();
Serial.println("================================");
}
// ==================================================
// Heartbeat API Request
// ==================================================
void sendHeartbeatRequest() {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("Heartbeat: Wi-Fi not connected");
return;
}
Serial.println();
Serial.println("========== HEARTBEAT ==========");
HTTPClient http;
if (!http.begin(String(heartbeatUrl) +
"?device=" + String(deviceId) +
"&token=" + String(apiToken))) {
Serial.println("Failed to initialize heartbeat request");
return;
}
http.setConnectTimeout(5000);
http.setTimeout(8000);
int httpCode = http.GET();
Serial.print("HTTP Code: ");
Serial.println(httpCode);
if (httpCode > 0) {
String response = http.getString();
Serial.println("Raw API Response:");
Serial.println(response);
String code = extractJsonValue(response, "code");
String device = extractJsonValue(response, "device");
String serverTime = extractJsonValue(response, "serverTime");
String timezone = extractJsonValue(response, "timezone");
// Accept JSON with or without whitespace after the colon.
bool heartbeatOK =
response.indexOf("\"ok\":true") >= 0 ||
response.indexOf("\"ok\": true") >= 0;
if (
httpCode == 200 &&
code == "heartbeat" &&
heartbeatOK
) {
Serial.println("Status: SUCCESS");
Serial.print("Code: ");
Serial.println(code);
Serial.print("Device: ");
Serial.println(device);
Serial.println("OK: true");
Serial.print("ServerTime: ");
Serial.println(serverTime);
Serial.print("Timezone: ");
Serial.println(timezone);
} else {
Serial.println("Status: UNEXPECTED RESPONSE");
}
} else {
Serial.println("Status: REQUEST FAILED");
Serial.print("Error: ");
Serial.println(http.errorToString(httpCode));
}
http.end();
Serial.println("================================");
}
// ==================================================
// Push Button Handler
// ==================================================
void handlePushButton() {
int currentButtonState = digitalRead(pushButtonPin);
// Button uses INPUT_PULLUP, so LOW means pressed.
if (currentButtonState == LOW && !buttonPressed) {
buttonPressed = true;
// Indicate the trigger.
digitalWrite(greenLedPin, HIGH);
displayFingerprintTriggered();
Serial.println("Fingerprint triggered");
// Send the selected fingerprint number to the API.
sendAttendanceRequest();
}
// Button released.
if (currentButtonState == HIGH && buttonPressed) {
buttonPressed = false;
digitalWrite(greenLedPin, LOW);
displayBioTrack();
Serial.println("Fingerprint released");
}
}
// ==================================================
// Setup
// ==================================================
void setup() {
Serial.begin(115200);
// GPIO setup.
pinMode(blinkLedPin, OUTPUT);
pinMode(greenLedPin, OUTPUT);
pinMode(pushButtonPin, INPUT_PULLUP);
pinMode(potentiometerPin, INPUT);
// ESP32 ADC configuration.
analogReadResolution(12);
digitalWrite(blinkLedPin, LOW);
digitalWrite(greenLedPin, LOW);
// I2C and LCD initialization.
Wire.begin(21, 22);
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("BioTrack");
lcd.setCursor(0, 1);
lcd.print("Starting...");
// Startup LED indication.
digitalWrite(blinkLedPin, HIGH);
delay(200);
digitalWrite(blinkLedPin, LOW);
// Read initial potentiometer position.
updatePotentiometer();
// Connect to Wi-Fi.
connectToWiFi();
// Initial ready screen.
displayBioTrack();
Serial.println();
Serial.println("BioTrack started");
Serial.println("Heartbeat monitoring active");
Serial.println("Fingerprint selection: 1 to 5");
Serial.println("Rotate pot right -> left to select 1 -> 5");
// Make the first heartbeat due immediately.
lastHeartbeatTime = millis() - heartbeatInterval;
}
// ==================================================
// Main Loop
// ==================================================
void loop() {
// Keep the selected fingerprint updated.
updatePotentiometer();
// Process the push button.
handlePushButton();
// Send heartbeat at regular intervals.
unsigned long currentTime = millis();
if (currentTime - lastHeartbeatTime >= heartbeatInterval) {
lastHeartbeatTime = currentTime;
// Short yellow LED pulse.
digitalWrite(blinkLedPin, HIGH);
delay(100);
digitalWrite(blinkLedPin, LOW);
sendHeartbeatRequest();
}
// Small delay to reduce unnecessary polling.
delay(20);
}
Loading
esp32-devkit-c-v4
esp32-devkit-c-v4