#include <SparkFunTSL2561.h>
#include <Wire.h>

#define aref_voltage 3.3 

SFE_TSL2561 light;

boolean gain;
unsigned int ms;
int sensorPin = 15;
boolean debug = true;

void setup () {
    analogReference(EXTERNAL);
    Serial.begin(9600);
    light.begin();
    unsigned char ID;
    if (light.getID(ID)) {
        Serial.print("light sensor ID: 0x");
        Serial.print(ID, HEX);
        Serial.println(", should be 0x5X");
    } else {
        byte error = light.getError();
        printError(error);
    }
    gain = 0;
    unsigned char time = 2;
    Serial.println("light sensor setting timing");
    light.setTiming(gain, time, ms);
    Serial.println("light sensor powering up light sensor");
    light.setPowerUp();
}

String read_sensor_light (double *luxVal) {
    delay(ms);
    unsigned int data0, data1;
    if (light.getData(data0, data1)) {
        double lux;
        boolean good;
        good = light.getLux(gain, ms, data0, data1, lux);
        *luxVal = lux;
        return "data0=" + (String)data0 + ", data1=" + data1 + ", lux=" + lux + 
            ", valid=" + (good ? "yes" : "no");
    } else {
        byte error = light.getError();
        printError(error);
        return "";
    }
}

String read_sensor_temp (double *tempVal) {
    int reading = analogRead(sensorPin);  
    float voltage = (reading * aref_voltage) / 1024.0;
    float tempC = (voltage - 0.5) * 100;
    float tempF = (tempC * 9.0 / 5.0) + 32.0;
    *tempVal = tempC;
    return "reading=" + (String)(reading * aref_voltage) + ", voltage=" + voltage +
        "V, temp=" + tempC + "°C, temp=" + tempF + "°F";
}

void loop () {
    double luxVal;
    double tempVal;
    String data;
    data = read_sensor_light(&luxVal);
    if (debug) {
        Serial.println("light sensor RAW DATA: " + data);
    } else {
        Serial.println("lux=" + (String)luxVal);
    }
    data = read_sensor_temp(&tempVal);
    if (debug) {
        Serial.println("temp sensor RAW DATA: " + read_sensor_temp(&luxVal));
    } else {
        Serial.println("temp=" + (String)tempVal);
    }
}

void printError (byte error) {
    Serial.print("I2C error: ");
    Serial.print(error, DEC);
    Serial.print(", ");
    switch(error) {
        case 0:
            Serial.println("success");
            break;
        case 1:
            Serial.println("data too long for transmit buffer");
            break;
        case 2:
            Serial.println("received NACK on address (disconnected?)");
            break;
        case 3:
            Serial.println("received NACK on data");
            break;
        case 4:
            Serial.println("other error");
            break;
        default:
            Serial.println("unknown error");
    }
}
