-
-
Save krackers/e7cdcc4d210c7fe42f92790cadbd0e85 to your computer and use it in GitHub Desktop.
Read lux measurement using MBP ambient light sensor.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 <[email protected]> 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