Solutions for the Analog Input experiments for LPC812 MAX

Dependencies:   lpc812_exp_lib_PCF8591 mbed

main.cpp

Committer:
embeddedartists
Date:
2013-11-22
Revision:
0:24709c18bbe0

File content as of revision 0:24709c18bbe0:

#include "mbed.h"
#include "PCF8591.h"
 
Serial pc(USBTX, USBRX); // tx, rx
 
PCF8591 adc;

float getTrimpotValue()
{
    // read a value
    int v = adc.read(PCF8591::A0);
        
    // convert it from 0..255 to 0-3.3V
    float b = v;
    return (b / 256) * 3.3;
}

static void experiment1()
{
    pc.printf("Analog input tests\n");
    while(1) {
        pc.printf("%f V\n", getTrimpotValue());
        wait(0.25);
    }
}

int getDigit()
{
    // read a value
    int v = adc.read(PCF8591::A0);
        
    // convert it from 0..255 to 0-9
    return (10 * v) / 256;
}

static void experiment2()
{
    pc.printf("Digit input tests\n");
    while(1) {
        pc.printf("%d\n", getDigit());
        wait(0.25);
    }
}

int getLightSensorValue(bool filter)
{
    static int lastValue = -1;

    // read a value
    int v = adc.read(PCF8591::A1);
    
    if (lastValue == -1) {
        lastValue = v;
    }
    
    // apply filter
    if (filter) {
        lastValue = ((7*lastValue) + v) >> 3;
    } else {
        lastValue = v;
    }
    
    return lastValue;
}

static void experiment3_alt1()
{
    pc.printf("Light sensor tests - unfiltered\n");
    while(1) {
        pc.printf("%d\n", getLightSensorValue(false));
        wait(0.25);
    }
}

static void experiment3_alt2()
{
    pc.printf("Light sensor tests - filtered\n");
    while(1) {
        pc.printf("%d\n", getLightSensorValue(true));
        wait(0.25);
    }
}

static void experiment4()
{
    int lastValue = -1000;
    
    pc.printf("Trimpot tests with threshold\n");
    while(1) {
        // read a value
        int value = adc.read(PCF8591::A0);
        if (abs(value - lastValue) >= 5) {
            pc.printf("%d\n", value);
            lastValue = value;
        }
        wait(0.1);
    }
}

int main()
{
    //experiment1();      // read 0-3.3V
    //experiment2();      // read digits
    //experiment3_alt1(); // read light sensor data
    //experiment3_alt2(); // read filtered light sensor data
    experiment4();      // read trimpot data, print only big changes
}