Friday, May 22, 2020

ATOM Matrix: Temperature Sensor

The temperature sensor included in the MPU6886 is not terribly useful for measuring ambient temperature. It is better used for detecting hardware overheating.

To read the temperature in Celsius, first declare a float (called tempC in the following application), and then pass-in the address of that float into the getTempData method like this:

M5.IMU.getTempData(&tempC)

For the sake of completeness, though, here is a simple application using the sensor.


Change Display Color Based on Temperature

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
 * TemperatureSensor01.ino
 * 
 * By: Mike Klepper
 * Date: 26 April 2020
 * 
 * Changes display based on internal temperature
 */

#include "M5Atom.h"

int GRB_COLOR_WHITE = 0xffffff;
int GRB_COLOR_BLACK = 0x000000;
int GRB_COLOR_RED = 0x00ff00;
int GRB_COLOR_ORANGE = 0xa5ff00;
int GRB_COLOR_YELLOW = 0xffff00;
int GRB_COLOR_GREEN = 0xff0000;
int GRB_COLOR_BLUE = 0x0000ff;
int GRB_COLOR_PURPLE = 0x008080;

float lowTempF = 103;
float highTempF = 105;

float tempC = 0;
bool IMU6886Flag = false;

void setup() 
{
    M5.begin(true, false, true);
    delay(20);
    
    IMU6886Flag = M5.IMU.Init() == 0;

    if(!IMU6886Flag)
    {
        Serial.println("Error initializing the IMU! :-(");
    }
}

void loop() 
{
    if(IMU6886Flag)
    {
        M5.IMU.getTempData(&tempC);
        Serial.printf(" Temp : %.2f C \r\n", tempC);
        float tempF = tempC * 9 / 5 + 32;
        Serial.printf(" Temp : %.2f F \r\n", tempF);
    
        if(tempF < lowTempF)
        {
            fillDisplay(GRB_COLOR_BLUE);
        }
        else if(tempF > highTempF)
        {
            fillDisplay(GRB_COLOR_RED);
        }
        else
        {
            fillDisplay(GRB_COLOR_GREEN);
        }
        
        delay(500);
        M5.update();
    }
}

void fillDisplay(int fillColor)
{
    for(int i = 0; i < 25; i++)
    {
        M5.dis.drawpix(i, fillColor);
    }
}

The delay(20) found on line 30 is necessary, as the MPU6886 is sometimes not found without it.

Click here to go to the table of contents for this series.

No comments:

Post a Comment