Simple autodimmer program with ldr. Calibration is done by setting minimum and maximum brightness. Linear interpolation is used to calculate pwm-output value. AutoDimmer o'lux + Set maximum brightness - Set minimum brightness t Test current settings a Enable/Disable AutoDimmer o'lux

Dependencies:   mbed

main.cpp

Committer:
bitfox
Date:
2010-12-05
Revision:
0:69c5332e36da

File content as of revision 0:69c5332e36da:

/*  Simple program for reading ldr.
 *  1. Read min and max values
 *  2. test values to output
 *  3. Use autodimmer to autodim :)
 *  
 *  If you don't have a ldr, you could use a linear variable resistor. etc.
 *  - Juha Viitanen, 5.12.2010, viidakkovekara@gmail.com
 */


#include "mbed.h"

Serial pc(USBTX, USBRX); // tx, rx

PwmOut led(LED1);
PwmOut led2(LED2);
PwmOut led3(LED3);
PwmOut led4(LED4);
AnalogIn ldr(p20);

static int activate = 0;
static float min, max;
float output, reading;

char c;

// aka. linear interpolation
float outputCalculation(float reading, float min, float max) {
    return 1.0-(reading-min)*((1.0-0.0)/(max-min));
}

float rc_filter(float input) {
    static float Old_input=0;
    float AB=255.0;
    float result=0,temp_result=0;
    unsigned char B=AB-100.0;

    result=input;
    Old_input = ((input*100.0)/AB) + ((Old_input*B)/AB);
    temp_result=temp_result+Old_input;

    return temp_result;
}

int main() {
    pc.baud(115200);
    pc.printf("AutoDimmer o'lux\n\r+ Set maximum brightness\n\r- Set minimum brightness\n\rt Test current settings\n\ra Enable/Disable AutoDimmer o'lux\n\r");

    while (1) {

        if (activate == 1) {
            reading = ldr.read();
            if (reading < min)
                reading = min;
            else if (reading >= max)
                reading = max;
            output = outputCalculation(reading, min, max);
            led = rc_filter(output);
        }

        if (pc.readable())
            c = pc.getc();
        else
            c = 0;

        switch (c) {
            case 't':
                pc.printf("Testing current settings\n\r");
                reading = ldr.read();
                if (reading < min)
                    reading = min;
                else if (reading >= max)
                    reading = max;
                output = outputCalculation(reading, min, max);
                pc.printf("ldr %f\n\r", output);
                led = output;
                break;
            case '+':
                max = ldr.read();
                pc.printf("max ldr value set to: %f\n\r",max);
                break;
            case '-':
                min = ldr.read();
                pc.printf("min ldr value set to: %f\n\r",min);
                break;
            case 'a':
                if (activate != 0)
                    pc.printf("Autodimming disabled\n\r");
                else if (activate == 0)
                    pc.printf("Autodimming enabled\n\r");
                activate ^= 1;
                break;
        }
    }
}