Skip to content

Instantly share code, notes, and snippets.

@kenji21
Forked from kenkeiter/lmutracker.mm
Created October 11, 2015 11:45
Show Gist options
  • Save kenji21/29ac2f82dd246539d6c3 to your computer and use it in GitHub Desktop.
Save kenji21/29ac2f82dd246539d6c3 to your computer and use it in GitHub Desktop.
Read lux measurement using MBP ambient light sensor.
// lmutracker.mm -- Provides lux measurement using MacBook Ambient Light Sensor
//
// clang -o lmutracker lmutracker.mm -framework IOKit -framework CoreFoundation
//
// Adaptation of code originally posted at https://bugzilla.mozilla.org/show_bug.cgi?id=793728
// by Reuben Morais. Modified by Ken Keiter <ken@kenkeiter.com> to output a single *lux* value
// and exit, rather than repeating measurements on the sensor's arbitrary scale.
#include <mach/mach.h>
#include <math.h>
#import <IOKit/IOKitLib.h>
#import <CoreFoundation/CoreFoundation.h>
static double updateInterval = 1;
static io_connect_t dataPort = 0;
int main(void) {
kern_return_t kr;
io_service_t serviceObject;
uint32_t outputs = 2;
uint64_t values[outputs];
uint64_t x;
uint64_t lux;
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);
kr = IOConnectCallMethod(dataPort, 0, nil, 0, nil, 0, values, &outputs, nil, 0);
if (kr == KERN_SUCCESS) {
x = values[0];
lux = (-3*pow(10, -27))*pow(x, 4) + (2.6*pow(10, -19))*pow(x, 3) - (3.4*pow(10,-12))*pow(x, 2) + (3.9*pow(10, -5))*x - 0.19;
printf("%lld\n", lux);
}
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment