The Ambient Light Sensor

Besides the sudden motion sensor, Apple notebook computers contain other sensors (depending on the specific model). These other sensors can also be queried by user programs. The following source code is a crude example that periodically retrieves readings from the ambient light sensors.

// lmutracker.m // // gcc -o lmutracker lmutracker.m -framework IOKit -framework CoreFoundation #include <mach/mach.h> #import <IOKit/IOKitLib.h> #import <CoreFoundation/CoreFoundation.h> static double updateInterval = 0.1; static io_connect_t dataPort = 0; void updateTimerCallBack(CFRunLoopTimerRef timer, void *info) { kern_return_t kr; unsigned int gIndex = 0; IOItemCount scalarInputCount = 0; IOItemCount scalarOutputCount = 2; SInt32 left = 0, right = 0; kr = IOConnectMethodScalarIScalarO(dataPort, gIndex, scalarInputCount, scalarOutputCount, &left, &right); if (kr == KERN_SUCCESS) { printf("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b%8ld %8ld", left, right); return; } if (kr == kIOReturnBusy) return; mach_error("I/O Kit error:", kr); exit(kr); } int main(void) { kern_return_t kr; io_service_t serviceObject; CFRunLoopTimerRef updateTimer; serviceObject = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("AppleLMUController")); if (!serviceObject) { fprintf(stderr, "failed to find ambient light sensors\n"); exit(1); } kr = IOServiceOpen(serviceObject, mach_task_self(), 0, &dataPort); IOObjectRelease(serviceObject); if (kr != KERN_SUCCESS) { mach_error("IOServiceOpen:", kr); exit(kr); } setbuf(stdout, NULL); printf("%8ld %8ld", 0L, 0L); updateTimer = CFRunLoopTimerCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + updateInterval, updateInterval, 0, 0, updateTimerCallBack, NULL); CFRunLoopAddTimer(CFRunLoopGetCurrent(), updateTimer, kCFRunLoopDefaultMode); CFRunLoopRun(); exit(0); }