AI & MLIntermediatePRJ-094

AI Anti-Sleep Alarm with Eye Detection

Watches your eyes through a webcam and sounds a buzzer if you start to doze off.

Built and tested by Aboobacker sidheeq K P · Industrial Robotics Institute

Laptop + Arduino Uno

Python 3.11, Arduino IDE, OpenCV, MediaPipe, NumPy, PySerial

LevelIntermediate
Build time2–3 hours
BoardLaptop + Arduino Uno
Parts6 components

What is the AI Anti-Sleep Alarm with Eye Detection?

A drowsiness alarm for drivers and late-night studying. A webcam and MediaPipe Face Mesh track your eyelids and calculate the Eye Aspect Ratio (EAR). If your eyes stay closed for more than 2 seconds, Python tells an Arduino over USB to sound a buzzer, which stops as soon as your eyes open.

How it works

  1. The webcam captures your face and MediaPipe finds 468 face landmarks.
  2. Six points around each eye give the Eye Aspect Ratio (EAR); it drops when eyes close.
  3. If EAR stays below 0.22 for more than 2 seconds, sleep is detected.
  4. Python sends "1" to the Arduino over serial, which turns the buzzer on.
  5. When your eyes reopen, Python sends "0" and the buzzer stops.

Parts list

ComponentQty
Laptop / Computer1
Webcam1
Arduino Uno / Nano1
Buzzer1
Jumper WiresAs needed
USB Cable1

Software

  • Python 3.11
  • Arduino IDE
  • OpenCV
  • MediaPipe
  • NumPy
  • PySerial

Wiring and connections

FromConnect to
Buzzer +Arduino Pin 8
Buzzer −GND
ArduinoLaptop USB

How to build the AI Anti-Sleep Alarm with Eye Detection

  1. Connect the buzzer to Arduino pin 8 and GND.
  2. Upload the Arduino sketch (at the end of the code block) from the Arduino IDE.
  3. Note the Arduino’s COM port (e.g. COM3) and close the Serial Monitor.
  4. Run: pip install opencv-python mediapipe numpy pyserial
  5. Set the COM port in the Python code and run it.
  6. Close your eyes for 2 seconds to test the alarm. Press q to quit.

AI Anti-Sleep Alarm with Eye Detection code

Complete, tested Python code for this project. Copy it into Python 3.11 and upload it and run it.

import cv2
import mediapipe as mp
import numpy as np
import time
import serial

# Change COM port according to your system (e.g. /dev/ttyUSB0 on Linux)
arduino = serial.Serial('COM3', 9600)
time.sleep(2)

mp_face_mesh = mp.solutions.face_mesh
face_mesh = mp_face_mesh.FaceMesh(max_num_faces=1, refine_landmarks=True,
                                  min_detection_confidence=0.7,
                                  min_tracking_confidence=0.7)
cap = cv2.VideoCapture(0)

EAR_THRESHOLD = 0.22   # eye closed threshold
SLEEP_TIME = 2         # seconds before alarm
sleep_start = None
alarm_on = False

LEFT_EYE = [33, 160, 158, 133, 153, 144]
RIGHT_EYE = [362, 385, 387, 263, 373, 380]


def eye_aspect_ratio(landmarks, eye_points, w, h):
    pts = [np.array((landmarks[p].x * w, landmarks[p].y * h)) for p in eye_points]
    v1 = np.linalg.norm(pts[1] - pts[5])
    v2 = np.linalg.norm(pts[2] - pts[4])
    h1 = np.linalg.norm(pts[0] - pts[3])
    return (v1 + v2) / (2.0 * h1)


def buzzer_on():
    global alarm_on
    if not alarm_on:
        arduino.write(b'1')
        alarm_on = True


def buzzer_off():
    global alarm_on
    if alarm_on:
        arduino.write(b'0')
        alarm_on = False


while True:
    success, frame = cap.read()
    if not success:
        break
    frame = cv2.flip(frame, 1)
    h, w, _ = frame.shape
    result = face_mesh.process(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))

    if result.multi_face_landmarks:
        lm = result.multi_face_landmarks[0].landmark
        ear = (eye_aspect_ratio(lm, LEFT_EYE, w, h) + eye_aspect_ratio(lm, RIGHT_EYE, w, h)) / 2
        cv2.putText(frame, f"EAR: {ear:.2f}", (30, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

        if ear < EAR_THRESHOLD:
            if sleep_start is None:
                sleep_start = time.time()
            cv2.putText(frame, "DROWSINESS DETECTED!", (30, 80), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 3)
            if time.time() - sleep_start > SLEEP_TIME:
                buzzer_on()
        else:
            sleep_start = None
            buzzer_off()
    else:
        buzzer_off()

    cv2.imshow("Anti Sleep Alarm", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

buzzer_off()
cap.release()
cv2.destroyAllWindows()
arduino.close()

# ---------------- Arduino sketch (upload separately) ----------------
# int buzzer = 8;
# void setup() { pinMode(buzzer, OUTPUT); Serial.begin(9600); }
# void loop() {
#   if (Serial.available()) {
#     char data = Serial.read();
#     if (data == '1') digitalWrite(buzzer, HIGH);
#     else if (data == '0') digitalWrite(buzzer, LOW);
#   }
# }

Real-world uses

  • Driver drowsiness alerts
  • Late-night study helper
  • Night-shift workers
  • Learning face landmark AI

Frequently asked questions

What is a AI Anti-Sleep Alarm with Eye Detection?

A drowsiness alarm for drivers and late-night studying. A webcam and MediaPipe Face Mesh track your eyelids and calculate the Eye Aspect Ratio (EAR).

What components are needed for the AI Anti-Sleep Alarm with Eye Detection?

You need: Laptop / Computer (1), Webcam (1), Arduino Uno / Nano (1), Buzzer (1), Jumper Wires, USB Cable (1). Software: Python 3.11, Arduino IDE, OpenCV, MediaPipe, NumPy, PySerial.

Is the AI Anti-Sleep Alarm with Eye Detection project good for beginners?

It is rated intermediate and takes about 2–3 hours to build, using the Laptop + Arduino Uno. The guide on this page explains every connection and step.

Where can I get the code for the AI Anti-Sleep Alarm with Eye Detection?

The complete, tested Python code is free on this page. Copy it into Python 3.11 and upload it and run it.

Can I buy a kit for the AI Anti-Sleep Alarm with Eye Detection?

Yes. IRI sells a kit with the parts for this project (PRJ-094). Message IRI on WhatsApp at +91 86060 82634 for the kit price and delivery details.

Industrial Robotics Institute
Logo