Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /********* Pleasedontcode.com **********
- Pleasedontcode thanks you for automatic code generation! Enjoy your code!
- - Terms and Conditions:
- You have a non-exclusive, revocable, worldwide, royalty-free license
- for personal and commercial use. Attribution is optional; modifications
- are allowed, but you're responsible for code maintenance. We're not
- liable for any loss or damage. For full terms,
- please visit pleasedontcode.com/termsandconditions.
- - Project: ESP32 CarLock
- - Source Code NOT compiled for: XIAO ESP32S3
- - Source Code created on: 2025-12-23 14:39:08
- ********* Pleasedontcode.com **********/
- /****** SYSTEM REQUIREMENTS *****/
- /****** SYSTEM REQUIREMENT 1 *****/
- /* jute corect the code */
- /****** END SYSTEM REQUIREMENTS *****/
- /* START CODE */
- /****** DEFINITION OF LIBRARIES *****/
- #include <BLEDevice.h>
- #include <BLEUtils.h>
- #include <BLEScan.h>
- #include <BLEAdvertisedDevice.h>
- #include <ArduinoBLE.h>
- /****** FUNCTION PROTOTYPES *****/
- void setup(void);
- void loop(void);
- /****** DEFINITION OF LIBRARIES CLASS INSTANCES*****/
- // ==================== LIBRARY CODE AND SYSTEM SETUP STARTS ====================
- // ==================== LIBRARY CODE AND SYSTEM SETUP ENDS ====================
- // ==================== SYSTEM SETUP AND LOOP STARTS ====================
- // ==================== SYSTEM SETUP AND LOOP ENDS ====================
- // ==================== USER CODE START ====================
- /**
- * ESP32_Car_Lock_System.ino
- *
- * ESP32-H2 Secure Car Door Lock System
- * Compatible with Web Bluetooth App
- *
- * Features:
- * - BLE Pairing with PIN authentication
- * - Encrypted communication
- * - 5 door sensors (Front L/R, Rear L/R, Trunk)
- * - Lock/Unlock control
- *
- * Hardware:
- * - ESP32-H2 Development Board
- * - 5V Relay Module
- * - 12V Door Lock Actuator
- * - 5x Reed Switch/Magnetic Door Sensors
- *
- * Pin Configuration:
- * - GPIO 2: Lock Control (Relay)
- * - GPIO 3: Front Left Door Sensor
- * - GPIO 4: Front Right Door Sensor
- * - GPIO 5: Rear Left Door Sensor
- * - GPIO 6: Rear Right Door Sensor
- * - GPIO 7: Trunk Sensor
- *
- * Author: Your Name
- * Version: 1.0
- * Date: 2025
- */
- // ==================== LIBRARY INCLUDES ====================
- #include <BLEDevice.h>
- #include <BLEServer.h>
- #include <BLEUtils.h>
- #include <BLE2902.h>
- #include <BLESecurity.h>
- // ==================== CONFIGURATION ====================
- // Service UUIDs - MUST match web app
- #define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
- #define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
- #define SENSOR_SERVICE_UUID "6e400001-b5a3-f393-e0a9-e50e24dcca9e"
- #define SENSOR_CHAR_UUID "6e400002-b5a3-f393-e0a9-e50e24dcca9e"
- // Device Configuration
- #define DEVICE_NAME "ESP32 Car Lock"
- // Security PIN - CHANGE THIS FOR YOUR SECURITY!
- #define SECURITY_PIN "1234"
- // Pin Configuration
- #define LOCK_PIN 2 // Lock control relay
- #define SENSOR_FRONT_LEFT 3 // Front left door sensor
- #define SENSOR_FRONT_RIGHT 4 // Front right door sensor
- #define SENSOR_REAR_LEFT 5 // Rear left door sensor
- #define SENSOR_REAR_RIGHT 6 // Rear right door sensor
- #define SENSOR_TRUNK 7 // Trunk sensor
- // Timing Configuration
- #define LOCK_PULSE_DURATION 500 // Lock pulse duration (ms)
- #define SENSOR_UPDATE_INTERVAL 200 // Sensor polling interval (ms)
- // ==================== GLOBAL VARIABLES ====================
- // BLE Objects
- BLEServer* pServer = NULL;
- BLECharacteristic* pCharacteristic = NULL;
- BLECharacteristic* pSensorCharacteristic = NULL;
- // Connection State
- bool deviceConnected = false;
- bool oldDeviceConnected = false;
- bool isAuthenticated = false;
- bool isLocked = false;
- // Door Sensor States
- struct DoorSensors {
- bool frontLeft = false;
- bool frontRight = false;
- bool rearLeft = false;
- bool rearRight = false;
- bool trunk = false;
- } doorStates;
- // Timing
- unsigned long lastSensorUpdate = 0;
- // ==================== FORWARD DECLARATIONS ====================
- void lockDoor();
- void unlockDoor();
- void readDoorSensors();
- void sendSensorData();
- void handleConnectionState();
- // ==================== BLE SECURITY CALLBACKS ====================
- class MySecurityCallbacks : public BLESecurityCallbacks {
- uint32_t onPassKeyRequest() {
- Serial.println("[Security] PassKey Request");
- return atoi(SECURITY_PIN);
- }
- void onPassKeyNotify(uint32_t pass_key) {
- Serial.printf("[Security] PassKey Notify: %d\n", pass_key);
- }
- bool onConfirmPIN(uint32_t pass_key) {
- Serial.printf("[Security] Confirm PIN: %d\n", pass_key);
- return true;
- }
- bool onSecurityRequest() {
- Serial.println("[Security] Security Request");
- return true;
- }
- void onAuthenticationComplete(esp_ble_auth_cmpl_t cmpl) {
- if (cmpl.success) {
- Serial.println("[Security] ulfilling pairing success!");
- isAuthenticated = true;
- } else {
- Serial.println("[Security] 7 Pairing failed!");
- isAuthenticated = false;
- }
- }
- };
- // ==================== BLE SERVER CALLBACKS ====================
- class MyServerCallbacks: public BLEServerCallbacks {
- void onConnect(BLEServer* pServer) {
- deviceConnected = true;
- isAuthenticated = false;
- Serial.println("[BLE] Device connected - Waiting for authentication");
- }
- void onDisconnect(BLEServer* pServer) {
- deviceConnected = false;
- isAuthenticated = false;
- Serial.println("[BLE] Device disconnected");
- }
- };
- // ==================== BLE CHARACTERISTIC CALLBACKS ====================
- class MyCharacteristicCallbacks: public BLECharacteristicCallbacks {
- void onWrite(BLECharacteristic *pCharacteristic) {
- std::string value = pCharacteristic->getValue();
- if (value.length() == 0) {
- Serial.println("[Command] Empty command received");
- return;
- }
- uint8_t command = value[0];
- // Handle authentication command (0x02)
- if (command == 0x02) {
- handleAuthentication(value, pCharacteristic);
- return;
- }
- // Check authentication before processing commands
- if (!isAuthenticated) {
- Serial.println("[Command] 7 Unauthorized - Authentication required");
- return;
- }
- // Process lock/unlock commands
- Serial.printf("[Command] Authenticated command received: 0x%02X\n", command);
- if (command == 0x01) {
- lockDoor();
- } else if (command == 0x00) {
- unlockDoor();
- } else {
- Serial.printf("[Command] Unknown command: 0x%02X\n", command);
- }
- }
- void onRead(BLECharacteristic *pCharacteristic) {
- // Return current authentication status
- uint8_t authStatus = isAuthenticated ? 1 : 0;
- pCharacteristic->setValue(&authStatus, 1);
- Serial.printf("[Command] Auth status read: %d\n", authStatus);
- }
- private:
- void handleAuthentication(const std::string& value, BLECharacteristic* pChar) {
- // Extract PIN from bytes after command byte
- std::string receivedPin = value.substr(1);
- Serial.print("[Auth] Authenticating with PIN: ");
- for (size_t i = 0; i < receivedPin.length(); i++) {
- Serial.print("*");
- }
- Serial.println();
- if (receivedPin == SECURITY_PIN) {
- isAuthenticated = true;
- Serial.println("[Auth] ulfilling authentication success!");
- // Send success response
- uint8_t response = 1;
- pChar->setValue(&response, 1);
- } else {
- isAuthenticated = false;
- Serial.println("[Auth] 7 Authentication failed - Invalid PIN");
- // Send failure response
- uint8_t response = 0;
- pChar->setValue(&response, 1);
- }
- }
- };
- // ==================== ARDUINO SETUP ====================
- void setup() {
- // Initialize Serial
- Serial.begin(115200);
- delay(1000);
- Serial.println("\n\n");
- Serial.println("========================================");
- Serial.println(" ESP32-H2 Secure Car Lock System");
- Serial.println("========================================");
- Serial.println();
- // Configure lock control pin
- pinMode(LOCK_PIN, OUTPUT);
- digitalWrite(LOCK_PIN, LOW);
- Serial.println("[GPIO] Lock control pin configured");
- // Configure door sensor pins (INPUT_PULLUP)
- pinMode(SENSOR_FRONT_LEFT, INPUT_PULLUP);
- pinMode(SENSOR_FRONT_RIGHT, INPUT_PULLUP);
- pinMode(SENSOR_REAR_LEFT, INPUT_PULLUP);
- pinMode(SENSOR_REAR_RIGHT, INPUT_PULLUP);
- pinMode(SENSOR_TRUNK, INPUT_PULLUP);
- Serial.println("[GPIO] Door sensor pins configured");
- // Initialize BLE
- Serial.println("[BLE] Initializing Bluetooth...");
- BLEDevice::init(DEVICE_NAME);
- // Configure security
- Serial.println("[BLE] Configuring security...");
- BLEDevice::setEncryptionLevel(ESP_BLE_SEC_ENCRYPT);
- BLEDevice::setSecurityCallbacks(new MySecurityCallbacks());
- // Create BLE Server
- pServer = BLEDevice::createServer();
- pServer->setCallbacks(new MyServerCallbacks());
- // Configure BLE Security
- BLESecurity *pSecurity = new BLESecurity();
- pSecurity->setAuthenticationMode(ESP_LE_AUTH_REQ_SC_MITM_BOND);
- pSecurity->setCapability(ESP_IO_CAP_OUT);
- pSecurity->setInitEncryptionKey(ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK);
- Serial.println("[BLE] Security configured");
- // Create main control service
- Serial.println("[BLE] Creating control service...");
- BLEService *pService = pServer->createService(SERVICE_UUID);
- // Create control characteristic with encryption
- pCharacteristic = pService->createCharacteristic(
- CHARACTERISTIC_UUID,
- BLECharacteristic::PROPERTY_READ |
- BLECharacteristic::PROPERTY_WRITE
- );
- pCharacteristic->setAccessPermissions(
- ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED
- );
- pCharacteristic->setCallbacks(new MyCharacteristicCallbacks());
- pCharacteristic->addDescriptor(new BLE2902());
- pService->start();
- Serial.println("[BLE] Control service started");
- // Create sensor service
- Serial.println("[BLE] Creating sensor service...");
- BLEService *pSensorService = pServer->createService(SENSOR_SERVICE_UUID);
- pSensorCharacteristic = pSensorService->createCharacteristic(
- SENSOR_CHAR_UUID,
- BLECharacteristic::PROPERTY_READ |
- BLECharacteristic::PROPERTY_NOTIFY
- );
- pSensorCharacteristic->addDescriptor(new BLE2902());
- pSensorService->start();
- Serial.println("[BLE] Sensor service started");
- // Start advertising
- Serial.println("[BLE] Starting advertising...");
- BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
- pAdvertising->addServiceUUID(SERVICE_UUID);
- pAdvertising->addServiceUUID(SENSOR_SERVICE_UUID);
- pAdvertising->setScanResponse(false);
- pAdvertising->setMinPreferred(0x0);
- BLEDevice::startAdvertising();
- Serial.println();
- Serial.println("========================================");
- Serial.println(" System Ready!");
- Serial.println("========================================");
- Serial.printf("Device Name: %s\n", DEVICE_NAME);
- Serial.printf("Security PIN: %s\n", SECURITY_PIN);
- Serial.println("Waiting for connections...");
- Serial.println();
- }
- // ==================== ARDUINO LOOP ====================
- void loop() {
- // Handle connection state changes
- handleConnectionState();
- // Process sensors if connected
- if (deviceConnected) {
- unsigned long currentMillis = millis();
- if (currentMillis - lastSensorUpdate >= SENSOR_UPDATE_INTERVAL) {
- readDoorSensors();
- sendSensorData();
- lastSensorUpdate = currentMillis;
- }
- }
- delay(10); // Small delay to prevent watchdog issues
- }
- // ==================== HELPER FUNCTIONS ====================
- void handleConnectionState() {
- // Handle disconnection
- if (!deviceConnected && oldDeviceConnected) {
- delay(500);
- pServer->startAdvertising();
- Serial.println("[BLE] Restarting advertising");
- oldDeviceConnected = deviceConnected;
- }
- // Handle new connection
- if (deviceConnected && !oldDeviceConnected) {
- oldDeviceConnected = deviceConnected;
- Serial.println("[BLE] New client connected");
- }
- }
- void readDoorSensors() {
- // Read all door sensors
- // Sensors are INPUT_PULLUP: LOW = closed (normal), HIGH = open (alarm)
- bool newFrontLeft = digitalRead(SENSOR_FRONT_LEFT) == HIGH;
- bool newFrontRight = digitalRead(SENSOR_FRONT_RIGHT) == HIGH;
- bool newRearLeft = digitalRead(SENSOR_REAR_LEFT) == HIGH;
- bool newRearRight = digitalRead(SENSOR_REAR_RIGHT) == HIGH;
- bool newTrunk = digitalRead(SENSOR_TRUNK) == HIGH;
- // Log changes
- if (newFrontLeft != doorStates.frontLeft) {
- Serial.printf("[Sensor] Front Left: %s\n", newFrontLeft ? "OPEN" : "CLOSED");
- }
- if (newFrontRight != doorStates.frontRight) {
- Serial.printf("[Sensor] Front Right: %s\n", newFrontRight ? "OPEN" : "CLOSED");
- }
- if (newRearLeft != doorStates.rearLeft) {
- Serial.printf("[Sensor] Rear Left: %s\n", newRearLeft ? "OPEN" : "CLOSED");
- }
- if (newRearRight != doorStates.rearRight) {
- Serial.printf("[Sensor] Rear Right: %s\n", newRearRight ? "OPEN" : "CLOSED");
- }
- if (newTrunk != doorStates.trunk) {
- Serial.printf("[Sensor] Trunk: %s\n", newTrunk ? "OPEN" : "CLOSED");
- }
- // Update states
- doorStates.frontLeft = newFrontLeft;
- doorStates.frontRight = newFrontRight;
- doorStates.rearLeft = newRearLeft;
- doorStates.rearRight = newRearRight;
- doorStates.trunk = newTrunk;
- }
- void sendSensorData() {
- if (!pSensorCharacteristic) return;
- // Pack sensor data into single byte using bit flags
- uint8_t sensorByte = 0;
- if (doorStates.frontLeft) sensorByte |= 0b00001; // Bit 0
- if (doorStates.frontRight) sensorByte |= 0b00010; // Bit 1
- if (doorStates.rearLeft) sensorByte |= 0b00100; // Bit 2
- if (doorStates.rearRight) sensorByte |= 0b01000; // Bit 3
- if (doorStates.trunk) sensorByte |= 0b10000; // Bit 4
- pSensorCharacteristic->setValue(&sensorByte, 1);
- pSensorCharacteristic->notify();
- }
- void lockDoor() {
- Serial.println("[Lock] LOCKING door...");
- // Activate lock relay
- digitalWrite(LOCK_PIN, HIGH);
- delay(LOCK_PULSE_DURATION);
- digitalWrite(LOCK_PIN, LOW);
- isLocked = true;
- Serial.println("[Lock] Door LOCKED");
- }
- void unlockDoor() {
- Serial.println("[Lock] UNLOCKING door...");
- // Activate unlock relay
- digitalWrite(LOCK_PIN, HIGH);
- delay(LOCK_PULSE_DURATION);
- digitalWrite(LOCK_PIN, LOW);
- isLocked = false;
- Serial.println("[Lock] Door UNLOCKED");
- }
- // ==================== OPTIONAL FEATURES ====================
- /*
- // Add buzzer feedback
- #define BUZZER_PIN 8
- void beep(int count, int duration) {
- for (int i = 0; i < count; i++) {
- digitalWrite(BUZZER_PIN, HIGH);
- delay(duration);
- digitalWrite(BUZZER_PIN, LOW);
- if (i < count - 1) delay(100);
- }
- }
- */
- /*
- // Read battery voltage
- #define BATTERY_PIN 34
- float readBatteryVoltage() {
- int raw = analogRead(BATTERY_PIN);
- float voltage = (raw / 4095.0) * 3.3 * 2; // Voltage divider
- return voltage;
- }
- */
- /*
- // Emergency unlock button
- #define EMERGENCY_BUTTON_PIN 9
- void checkEmergencyButton() {
- if (digitalRead(EMERGENCY_BUTTON_PIN) == LOW) {
- unlockDoor();
- Serial.println("[Emergency] Manual unlock triggered");
- }
- }
- */
- // ==================== END OF USER CODE ====================
- /* END CODE */
Advertisement
Add Comment
Please, Sign In to add comment