// Code from the following github repo: https://github.com/ControlEverythingCommunity/TSL2561/blob/master/C/TSL2561.c #include "./Include/TSL2561.h" void printSpectrum(int file) { // Read 4 bytes of data from register(0x0C | 0x80) // ch0 lsb, ch0 msb, ch1 lsb, ch1 msb char reg[1] = {0x0C | 0x80}; write(file, reg, 1); char data[4] = {0}; if (read(file, data, 4) != 4) { printf("Erorr : Input/output Erorr \n"); } else { // Convert the data float ch0 = (data[1] * 256 + data[0]); // Full Spectrum(IR + Visible) float ch1 = (data[3] * 256 + data[2]); // Infrared Value // Output data to screen printf("Full Spectrum(IR + Visible) : %.1f lux \n", ch0); printf("Infrared Value : %.1f lux \n", ch1); printf("Visible Value : %.1f lux \n", (ch0 - ch1)); } } float getFullSpectrum(int file) { // Read 4 bytes of data from register(0x0C | 0x80) // ch0 lsb, ch0 msb, ch1 lsb, ch1 msb char reg[1] = {0x0C | 0x80}; write(file, reg, 1); char data[4] = {0}; if (read(file, data, 4) != 4) { printf("Erorr : Input/output Erorr \n"); } else { // Convert the data float ch0 = (data[1] * 256 + data[0]); // Full Spectrum(IR + Visible) return ch0; } } float getInfraredLight(int file) { // Read 4 bytes of data from register(0x0C | 0x80) // ch0 lsb, ch0 msb, ch1 lsb, ch1 msb char reg[1] = {0x0C | 0x80}; write(file, reg, 1); char data[4] = {0}; if (read(file, data, 4) != 4) { printf("Erorr : Input/output Erorr \n"); } else { // Convert the data float ch1 = (data[3] * 256 + data[2]); // Infrared Value return ch1; } } int init_TSL2561(char *bus) { int file; if ((file = open(bus, O_RDWR)) < 0) { printf("Failed to open the bus. \n"); exit(1); } // Get I2C device, TSL2561 I2C address is 0x39(57) ioctl(file, I2C_SLAVE, 0x39); // Select control register(0x00 | 0x80) // Power ON mode(0x03) char config[2] = {0}; config[0] = 0x00 | 0x80; config[1] = 0x03; write(file, config, 2); // Select timing register(0x01 | 0x80) // Nominal integration time = 402ms(0x02) config[0] = 0x01 | 0x80; config[1] = 0x02; write(file, config, 2); return file; } void TSL2561() { int fe = 1; int file; file = init_TSL2561(bus); while (1) { sleep(1 / fe); float a = getFullSpectrum(file); float b = getInfraredLight(file); printf("%.1f\n", a); printf("%.1f\n", b); printSpectrum(file); } } void main() { TSL2561(); }