Author Topic: Automatic Screen Lock  (Read 3665 times)

rmd6502

  • Newbie
  • *
  • Posts: 1
Automatic Screen Lock
« on: June 10, 2013, 09:47:55 am »
Code: [Select]
I took a cheap PIR sensor from Digikey and used to to automatically lock my screen when I get up from my desk.  The PIR can come from pretty much anywhere, I think Radio Shack even sells the ones from Parallax.


Connect to USB, make sure +5 and ground are properly connected, and the output pin from the PIR to P2.  Modify the attached sketch to send the proper keystroke combination to lock your screen, this will work for OS/X.



#include "DigiKeyboard.h"


#define KEY_EJECT 102


const uint8_t led = 1;
const uint8_t sensor = 2;


unsigned long lastMotion;
uint8_t isLocked;
const unsigned long NO_MOVE_THRESHOLD_MS = 30000;


void setup() {
  pinMode(led, OUTPUT);
  pinMode(sensor, INPUT);
  digitalWrite(sensor, HIGH);
  lastMotion = 0;
  isLocked = 0;
  //Mouse.begin();
  //DigiKeyboard.begin();
  DigiKeyboard.sendKeyStroke(0);
}


void lockScreen() {
  //unsigned long now = millis();
  DigiKeyboard.sendKeyStroke(KEY_EJECT, MOD_CONTROL_LEFT | MOD_SHIFT_LEFT);
  DigiKeyboard.delay(25);
//  Keyboard.press(KEY_LEFT_CONTROL);
//  Keyboard.press(KEY_LEFT_ALT);
//  Keyboard.press('l');
//  delay(25);
//  Keyboard.releaseAll();
}


void loop() {
  uint8_t moved = digitalRead(sensor);
  digitalWrite(led, moved);
  if (moved) {
    lastMotion = millis();
    if (isLocked) {
      DigiKeyboard.sendKeyStroke(KEY_ENTER);
      DigiKeyboard.delay(100);
      isLocked = 0;
    }
  } else {
    if (!isLocked && millis() - lastMotion >= NO_MOVE_THRESHOLD_MS) {
      lockScreen();
      isLocked = 1;
    }
  }
}

DeuxVis

  • Full Member
  • ***
  • Posts: 107
Re: Automatic Screen Lock
« Reply #1 on: June 13, 2013, 07:32:27 am »
Excellent idea. I'm going to make one too.

What is the sensor you use, have any experience to share about it (distance, sensibility...) ?