pleasedontcode

ESP32 CarLock rev_01

Dec 23rd, 2025
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 15.04 KB | None | 0 0
  1. /********* Pleasedontcode.com **********
  2.  
  3.     Pleasedontcode thanks you for automatic code generation! Enjoy your code!
  4.  
  5.     - Terms and Conditions:
  6.     You have a non-exclusive, revocable, worldwide, royalty-free license
  7.     for personal and commercial use. Attribution is optional; modifications
  8.     are allowed, but you're responsible for code maintenance. We're not
  9.     liable for any loss or damage. For full terms,
  10.     please visit pleasedontcode.com/termsandconditions.
  11.  
  12.     - Project: ESP32 CarLock
  13.     - Source Code NOT compiled for: XIAO ESP32S3
  14.     - Source Code created on: 2025-12-23 14:39:08
  15.  
  16. ********* Pleasedontcode.com **********/
  17.  
  18. /****** SYSTEM REQUIREMENTS *****/
  19. /****** SYSTEM REQUIREMENT 1 *****/
  20.     /* jute corect the code */
  21. /****** END SYSTEM REQUIREMENTS *****/
  22.  
  23.  
  24. /* START CODE */
  25.  
  26. /****** DEFINITION OF LIBRARIES *****/
  27. #include <BLEDevice.h>
  28. #include <BLEUtils.h>
  29. #include <BLEScan.h>
  30. #include <BLEAdvertisedDevice.h>
  31. #include <ArduinoBLE.h>
  32.  
  33. /****** FUNCTION PROTOTYPES *****/
  34. void setup(void);
  35. void loop(void);
  36.  
  37. /****** DEFINITION OF LIBRARIES CLASS INSTANCES*****/
  38.  
  39. // ==================== LIBRARY CODE AND SYSTEM SETUP STARTS ====================
  40.  
  41. // ==================== LIBRARY CODE AND SYSTEM SETUP ENDS ====================
  42.  
  43. // ==================== SYSTEM SETUP AND LOOP STARTS ====================
  44.  
  45. // ==================== SYSTEM SETUP AND LOOP ENDS ====================
  46.  
  47. // ==================== USER CODE START ====================
  48.  
  49. /**
  50.  * ESP32_Car_Lock_System.ino
  51.  *
  52.  * ESP32-H2 Secure Car Door Lock System
  53.  * Compatible with Web Bluetooth App
  54.  *
  55.  * Features:
  56.  * - BLE Pairing with PIN authentication
  57.  * - Encrypted communication
  58.  * - 5 door sensors (Front L/R, Rear L/R, Trunk)
  59.  * - Lock/Unlock control
  60.  *
  61.  * Hardware:
  62.  * - ESP32-H2 Development Board
  63.  * - 5V Relay Module
  64.  * - 12V Door Lock Actuator
  65.  * - 5x Reed Switch/Magnetic Door Sensors
  66.  *
  67.  * Pin Configuration:
  68.  * - GPIO 2: Lock Control (Relay)
  69.  * - GPIO 3: Front Left Door Sensor
  70.  * - GPIO 4: Front Right Door Sensor
  71.  * - GPIO 5: Rear Left Door Sensor
  72.  * - GPIO 6: Rear Right Door Sensor
  73.  * - GPIO 7: Trunk Sensor
  74.  *
  75.  * Author: Your Name
  76.  * Version: 1.0
  77.  * Date: 2025
  78.  */
  79.  
  80. // ==================== LIBRARY INCLUDES ====================
  81. #include <BLEDevice.h>
  82. #include <BLEServer.h>
  83. #include <BLEUtils.h>
  84. #include <BLE2902.h>
  85. #include <BLESecurity.h>
  86.  
  87. // ==================== CONFIGURATION ====================
  88.  
  89. // Service UUIDs - MUST match web app
  90. #define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
  91. #define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
  92. #define SENSOR_SERVICE_UUID "6e400001-b5a3-f393-e0a9-e50e24dcca9e"
  93. #define SENSOR_CHAR_UUID    "6e400002-b5a3-f393-e0a9-e50e24dcca9e"
  94.  
  95. // Device Configuration
  96. #define DEVICE_NAME "ESP32 Car Lock"
  97.  
  98. // Security PIN - CHANGE THIS FOR YOUR SECURITY!
  99. #define SECURITY_PIN "1234"
  100.  
  101. // Pin Configuration
  102. #define LOCK_PIN           2  // Lock control relay
  103. #define SENSOR_FRONT_LEFT  3  // Front left door sensor
  104. #define SENSOR_FRONT_RIGHT 4  // Front right door sensor
  105. #define SENSOR_REAR_LEFT   5  // Rear left door sensor
  106. #define SENSOR_REAR_RIGHT  6  // Rear right door sensor
  107. #define SENSOR_TRUNK       7  // Trunk sensor
  108.  
  109. // Timing Configuration
  110. #define LOCK_PULSE_DURATION     500  // Lock pulse duration (ms)
  111. #define SENSOR_UPDATE_INTERVAL  200  // Sensor polling interval (ms)
  112.  
  113. // ==================== GLOBAL VARIABLES ====================
  114.  
  115. // BLE Objects
  116. BLEServer* pServer = NULL;
  117. BLECharacteristic* pCharacteristic = NULL;
  118. BLECharacteristic* pSensorCharacteristic = NULL;
  119.  
  120. // Connection State
  121. bool deviceConnected = false;
  122. bool oldDeviceConnected = false;
  123. bool isAuthenticated = false;
  124. bool isLocked = false;
  125.  
  126. // Door Sensor States
  127. struct DoorSensors {
  128.   bool frontLeft = false;
  129.   bool frontRight = false;
  130.   bool rearLeft = false;
  131.   bool rearRight = false;
  132.   bool trunk = false;
  133. } doorStates;
  134.  
  135. // Timing
  136. unsigned long lastSensorUpdate = 0;
  137.  
  138. // ==================== FORWARD DECLARATIONS ====================
  139.  
  140. void lockDoor();
  141. void unlockDoor();
  142. void readDoorSensors();
  143. void sendSensorData();
  144. void handleConnectionState();
  145.  
  146. // ==================== BLE SECURITY CALLBACKS ====================
  147.  
  148. class MySecurityCallbacks : public BLESecurityCallbacks {
  149.   uint32_t onPassKeyRequest() {
  150.     Serial.println("[Security] PassKey Request");
  151.     return atoi(SECURITY_PIN);
  152.   }
  153.  
  154.   void onPassKeyNotify(uint32_t pass_key) {
  155.     Serial.printf("[Security] PassKey Notify: %d\n", pass_key);
  156.   }
  157.  
  158.   bool onConfirmPIN(uint32_t pass_key) {
  159.     Serial.printf("[Security] Confirm PIN: %d\n", pass_key);
  160.     return true;
  161.   }
  162.  
  163.   bool onSecurityRequest() {
  164.     Serial.println("[Security] Security Request");
  165.     return true;
  166.   }
  167.  
  168.   void onAuthenticationComplete(esp_ble_auth_cmpl_t cmpl) {
  169.     if (cmpl.success) {
  170.       Serial.println("[Security] ulfilling pairing success!");
  171.       isAuthenticated = true;
  172.     } else {
  173.       Serial.println("[Security] 7 Pairing failed!");
  174.       isAuthenticated = false;
  175.     }
  176.   }
  177. };
  178.  
  179. // ==================== BLE SERVER CALLBACKS ====================
  180.  
  181. class MyServerCallbacks: public BLEServerCallbacks {
  182.     void onConnect(BLEServer* pServer) {
  183.       deviceConnected = true;
  184.       isAuthenticated = false;
  185.       Serial.println("[BLE] Device connected - Waiting for authentication");
  186.     }
  187.  
  188.     void onDisconnect(BLEServer* pServer) {
  189.       deviceConnected = false;
  190.       isAuthenticated = false;
  191.       Serial.println("[BLE] Device disconnected");
  192.     }
  193. };
  194.  
  195. // ==================== BLE CHARACTERISTIC CALLBACKS ====================
  196.  
  197. class MyCharacteristicCallbacks: public BLECharacteristicCallbacks {
  198.     void onWrite(BLECharacteristic *pCharacteristic) {
  199.       std::string value = pCharacteristic->getValue();
  200.  
  201.       if (value.length() == 0) {
  202.         Serial.println("[Command] Empty command received");
  203.         return;
  204.       }
  205.  
  206.       uint8_t command = value[0];
  207.      
  208.       // Handle authentication command (0x02)
  209.       if (command == 0x02) {
  210.         handleAuthentication(value, pCharacteristic);
  211.         return;
  212.       }
  213.  
  214.       // Check authentication before processing commands
  215.       if (!isAuthenticated) {
  216.         Serial.println("[Command] 7 Unauthorized - Authentication required");
  217.         return;
  218.       }
  219.  
  220.       // Process lock/unlock commands
  221.       Serial.printf("[Command] Authenticated command received: 0x%02X\n", command);
  222.  
  223.       if (command == 0x01) {
  224.         lockDoor();
  225.       } else if (command == 0x00) {
  226.         unlockDoor();
  227.       } else {
  228.         Serial.printf("[Command] Unknown command: 0x%02X\n", command);
  229.       }
  230.     }
  231.  
  232.     void onRead(BLECharacteristic *pCharacteristic) {
  233.       // Return current authentication status
  234.       uint8_t authStatus = isAuthenticated ? 1 : 0;
  235.       pCharacteristic->setValue(&authStatus, 1);
  236.       Serial.printf("[Command] Auth status read: %d\n", authStatus);
  237.     }
  238.  
  239.   private:
  240.     void handleAuthentication(const std::string& value, BLECharacteristic* pChar) {
  241.       // Extract PIN from bytes after command byte
  242.       std::string receivedPin = value.substr(1);
  243.      
  244.       Serial.print("[Auth] Authenticating with PIN: ");
  245.       for (size_t i = 0; i < receivedPin.length(); i++) {
  246.         Serial.print("*");
  247.       }
  248.       Serial.println();
  249.      
  250.       if (receivedPin == SECURITY_PIN) {
  251.         isAuthenticated = true;
  252.         Serial.println("[Auth] ulfilling authentication success!");
  253.        
  254.         // Send success response
  255.         uint8_t response = 1;
  256.         pChar->setValue(&response, 1);
  257.       } else {
  258.         isAuthenticated = false;
  259.         Serial.println("[Auth] 7 Authentication failed - Invalid PIN");
  260.        
  261.         // Send failure response
  262.         uint8_t response = 0;
  263.         pChar->setValue(&response, 1);
  264.       }
  265.     }
  266. };
  267.  
  268. // ==================== ARDUINO SETUP ====================
  269.  
  270. void setup() {
  271.   // Initialize Serial
  272.   Serial.begin(115200);
  273.   delay(1000);
  274.  
  275.   Serial.println("\n\n");
  276.   Serial.println("========================================");
  277.   Serial.println("  ESP32-H2 Secure Car Lock System");
  278.   Serial.println("========================================");
  279.   Serial.println();
  280.  
  281.   // Configure lock control pin
  282.   pinMode(LOCK_PIN, OUTPUT);
  283.   digitalWrite(LOCK_PIN, LOW);
  284.   Serial.println("[GPIO] Lock control pin configured");
  285.  
  286.   // Configure door sensor pins (INPUT_PULLUP)
  287.   pinMode(SENSOR_FRONT_LEFT, INPUT_PULLUP);
  288.   pinMode(SENSOR_FRONT_RIGHT, INPUT_PULLUP);
  289.   pinMode(SENSOR_REAR_LEFT, INPUT_PULLUP);
  290.   pinMode(SENSOR_REAR_RIGHT, INPUT_PULLUP);
  291.   pinMode(SENSOR_TRUNK, INPUT_PULLUP);
  292.   Serial.println("[GPIO] Door sensor pins configured");
  293.  
  294.   // Initialize BLE
  295.   Serial.println("[BLE] Initializing Bluetooth...");
  296.   BLEDevice::init(DEVICE_NAME);
  297.  
  298.   // Configure security
  299.   Serial.println("[BLE] Configuring security...");
  300.   BLEDevice::setEncryptionLevel(ESP_BLE_SEC_ENCRYPT);
  301.   BLEDevice::setSecurityCallbacks(new MySecurityCallbacks());
  302.  
  303.   // Create BLE Server
  304.   pServer = BLEDevice::createServer();
  305.   pServer->setCallbacks(new MyServerCallbacks());
  306.  
  307.   // Configure BLE Security
  308.   BLESecurity *pSecurity = new BLESecurity();
  309.   pSecurity->setAuthenticationMode(ESP_LE_AUTH_REQ_SC_MITM_BOND);
  310.   pSecurity->setCapability(ESP_IO_CAP_OUT);
  311.   pSecurity->setInitEncryptionKey(ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK);
  312.   Serial.println("[BLE] Security configured");
  313.  
  314.   // Create main control service
  315.   Serial.println("[BLE] Creating control service...");
  316.   BLEService *pService = pServer->createService(SERVICE_UUID);
  317.  
  318.   // Create control characteristic with encryption
  319.   pCharacteristic = pService->createCharacteristic(
  320.                       CHARACTERISTIC_UUID,
  321.                       BLECharacteristic::PROPERTY_READ |
  322.                       BLECharacteristic::PROPERTY_WRITE
  323.                     );
  324.  
  325.   pCharacteristic->setAccessPermissions(
  326.     ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED
  327.   );
  328.   pCharacteristic->setCallbacks(new MyCharacteristicCallbacks());
  329.   pCharacteristic->addDescriptor(new BLE2902());
  330.  
  331.   pService->start();
  332.   Serial.println("[BLE] Control service started");
  333.  
  334.   // Create sensor service
  335.   Serial.println("[BLE] Creating sensor service...");
  336.   BLEService *pSensorService = pServer->createService(SENSOR_SERVICE_UUID);
  337.  
  338.   pSensorCharacteristic = pSensorService->createCharacteristic(
  339.                             SENSOR_CHAR_UUID,
  340.                             BLECharacteristic::PROPERTY_READ |
  341.                             BLECharacteristic::PROPERTY_NOTIFY
  342.                           );
  343.  
  344.   pSensorCharacteristic->addDescriptor(new BLE2902());
  345.   pSensorService->start();
  346.   Serial.println("[BLE] Sensor service started");
  347.  
  348.   // Start advertising
  349.   Serial.println("[BLE] Starting advertising...");
  350.   BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
  351.   pAdvertising->addServiceUUID(SERVICE_UUID);
  352.   pAdvertising->addServiceUUID(SENSOR_SERVICE_UUID);
  353.   pAdvertising->setScanResponse(false);
  354.   pAdvertising->setMinPreferred(0x0);
  355.   BLEDevice::startAdvertising();
  356.  
  357.   Serial.println();
  358.   Serial.println("========================================");
  359.   Serial.println("  System Ready!");
  360.   Serial.println("========================================");
  361.   Serial.printf("Device Name: %s\n", DEVICE_NAME);
  362.   Serial.printf("Security PIN: %s\n", SECURITY_PIN);
  363.   Serial.println("Waiting for connections...");
  364.   Serial.println();
  365. }
  366.  
  367. // ==================== ARDUINO LOOP ====================
  368.  
  369. void loop() {
  370.   // Handle connection state changes
  371.   handleConnectionState();
  372.  
  373.   // Process sensors if connected
  374.   if (deviceConnected) {
  375.     unsigned long currentMillis = millis();
  376.    
  377.     if (currentMillis - lastSensorUpdate >= SENSOR_UPDATE_INTERVAL) {
  378.       readDoorSensors();
  379.       sendSensorData();
  380.       lastSensorUpdate = currentMillis;
  381.     }
  382.   }
  383.  
  384.   delay(10); // Small delay to prevent watchdog issues
  385. }
  386.  
  387. // ==================== HELPER FUNCTIONS ====================
  388.  
  389. void handleConnectionState() {
  390.   // Handle disconnection
  391.   if (!deviceConnected && oldDeviceConnected) {
  392.     delay(500);
  393.     pServer->startAdvertising();
  394.     Serial.println("[BLE] Restarting advertising");
  395.     oldDeviceConnected = deviceConnected;
  396.   }
  397.  
  398.   // Handle new connection
  399.   if (deviceConnected && !oldDeviceConnected) {
  400.     oldDeviceConnected = deviceConnected;
  401.     Serial.println("[BLE] New client connected");
  402.   }
  403. }
  404.  
  405. void readDoorSensors() {
  406.   // Read all door sensors
  407.   // Sensors are INPUT_PULLUP: LOW = closed (normal), HIGH = open (alarm)
  408.   bool newFrontLeft = digitalRead(SENSOR_FRONT_LEFT) == HIGH;
  409.   bool newFrontRight = digitalRead(SENSOR_FRONT_RIGHT) == HIGH;
  410.   bool newRearLeft = digitalRead(SENSOR_REAR_LEFT) == HIGH;
  411.   bool newRearRight = digitalRead(SENSOR_REAR_RIGHT) == HIGH;
  412.   bool newTrunk = digitalRead(SENSOR_TRUNK) == HIGH;
  413.  
  414.   // Log changes
  415.   if (newFrontLeft != doorStates.frontLeft) {
  416.     Serial.printf("[Sensor] Front Left: %s\n", newFrontLeft ? "OPEN" : "CLOSED");
  417.   }
  418.   if (newFrontRight != doorStates.frontRight) {
  419.     Serial.printf("[Sensor] Front Right: %s\n", newFrontRight ? "OPEN" : "CLOSED");
  420.   }
  421.   if (newRearLeft != doorStates.rearLeft) {
  422.     Serial.printf("[Sensor] Rear Left: %s\n", newRearLeft ? "OPEN" : "CLOSED");
  423.   }
  424.   if (newRearRight != doorStates.rearRight) {
  425.     Serial.printf("[Sensor] Rear Right: %s\n", newRearRight ? "OPEN" : "CLOSED");
  426.   }
  427.   if (newTrunk != doorStates.trunk) {
  428.     Serial.printf("[Sensor] Trunk: %s\n", newTrunk ? "OPEN" : "CLOSED");
  429.   }
  430.  
  431.   // Update states
  432.   doorStates.frontLeft = newFrontLeft;
  433.   doorStates.frontRight = newFrontRight;
  434.   doorStates.rearLeft = newRearLeft;
  435.   doorStates.rearRight = newRearRight;
  436.   doorStates.trunk = newTrunk;
  437. }
  438.  
  439. void sendSensorData() {
  440.   if (!pSensorCharacteristic) return;
  441.  
  442.   // Pack sensor data into single byte using bit flags
  443.   uint8_t sensorByte = 0;
  444.  
  445.   if (doorStates.frontLeft)  sensorByte |= 0b00001;  // Bit 0
  446.   if (doorStates.frontRight) sensorByte |= 0b00010;  // Bit 1
  447.   if (doorStates.rearLeft)   sensorByte |= 0b00100;  // Bit 2
  448.   if (doorStates.rearRight)  sensorByte |= 0b01000;  // Bit 3
  449.   if (doorStates.trunk)      sensorByte |= 0b10000;  // Bit 4
  450.  
  451.   pSensorCharacteristic->setValue(&sensorByte, 1);
  452.   pSensorCharacteristic->notify();
  453. }
  454.  
  455. void lockDoor() {
  456.   Serial.println("[Lock] LOCKING door...");
  457.  
  458.   // Activate lock relay
  459.   digitalWrite(LOCK_PIN, HIGH);
  460.   delay(LOCK_PULSE_DURATION);
  461.   digitalWrite(LOCK_PIN, LOW);
  462.  
  463.   isLocked = true;
  464.   Serial.println("[Lock] Door LOCKED");
  465. }
  466.  
  467. void unlockDoor() {
  468.   Serial.println("[Lock] UNLOCKING door...");
  469.  
  470.   // Activate unlock relay
  471.   digitalWrite(LOCK_PIN, HIGH);
  472.   delay(LOCK_PULSE_DURATION);
  473.   digitalWrite(LOCK_PIN, LOW);
  474.  
  475.   isLocked = false;
  476.   Serial.println("[Lock] Door UNLOCKED");
  477. }
  478.  
  479. // ==================== OPTIONAL FEATURES ====================
  480.  
  481. /*
  482. // Add buzzer feedback
  483. #define BUZZER_PIN 8
  484.  
  485. void beep(int count, int duration) {
  486.   for (int i = 0; i < count; i++) {
  487.     digitalWrite(BUZZER_PIN, HIGH);
  488.     delay(duration);
  489.     digitalWrite(BUZZER_PIN, LOW);
  490.     if (i < count - 1) delay(100);
  491.   }
  492. }
  493. */
  494.  
  495. /*
  496. // Read battery voltage
  497. #define BATTERY_PIN 34
  498.  
  499. float readBatteryVoltage() {
  500.   int raw = analogRead(BATTERY_PIN);
  501.   float voltage = (raw / 4095.0) * 3.3 * 2; // Voltage divider
  502.   return voltage;
  503. }
  504. */
  505.  
  506. /*
  507. // Emergency unlock button
  508. #define EMERGENCY_BUTTON_PIN 9
  509.  
  510. void checkEmergencyButton() {
  511.   if (digitalRead(EMERGENCY_BUTTON_PIN) == LOW) {
  512.     unlockDoor();
  513.     Serial.println("[Emergency] Manual unlock triggered");
  514.   }
  515. }
  516. */
  517.  
  518. // ==================== END OF USER CODE ====================
  519.  
  520. /* END CODE */
  521.  
Advertisement
Add Comment
Please, Sign In to add comment