Test of DS18B20 Digital temperature sensor using k22f board.

Dependencies:   DS1820

main.cpp

Committer:
javibenjas
Date:
2018-04-19
Revision:
0:6367a3d990f2

File content as of revision 0:6367a3d990f2:

#include "mbed.h"
#include "DS1820.h"

#define SLEEP_S 2

// I'm using DS18B20, connections
// red -> 5v
// blue -> GND
// yellow -> D6
DigitalOut led_r(LED1);
DigitalOut led_g(LED2);
DigitalOut led_b(LED3);
DS1820 temp_probe(D6);

//we will use the first read as environment temperature
float env_temperature = -99;
// red means higher than environment
// blue means cooler than environment
// green means same as env

float read_temperature() {
    float tmp_temp;
    temp_probe.convertTemperature(true, DS1820::this_device);
    do {
        // TODO limit the n of tries
        // if device is not responding, will cycle forever
        tmp_temp = temp_probe.temperature();
        wait_ms(10);
    } while(tmp_temp == -1000);
    return tmp_temp;
}

int main() {
    printf("Temperature probe test\r\n");
    float temperature = 0;
    temp_probe.setResolution(9); //9bits
    
    //read env temperature
    wait(1); //wait for device to be ready
    env_temperature = read_temperature();
    
    while(1) {
        temperature = read_temperature();
        printf("Temperature %3.1foC\r\n", temperature);
        if(temperature < env_temperature) {
            led_r = 1; // 1 is off in this board
            led_g = 1;
            led_b = 0;
        } else if(temperature > env_temperature) {
            led_r = 0;
            led_g = 1;
            led_b = 1;
        } else {
            led_r = 1;
            led_g = 0;
            led_b = 1;
        }
        // sleep
        wait(SLEEP_S);
    }
}