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;
}
}
}