|
|
```cpp
|
|
|
#pragma once
|
|
|
|
|
|
#include "SpiDriver.h"
|
|
|
|
|
|
class TempSensor
|
|
|
{
|
|
|
|
|
|
public:
|
|
|
TempSensor(uint8_t odr = ODR_25_HZ,
|
|
|
uint8_t bdu = UPDATE_AFTER_READ_MODE)
|
|
|
: odr(odr), bdu(bdu)
|
|
|
{
|
|
|
}
|
|
|
|
|
|
bool init()
|
|
|
{
|
|
|
if (!checkWhoAmI())
|
|
|
{
|
|
|
TRACE("[TempSensor] Init failed \n");
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
// set the output data rate and the BDU in CTRL_REG4
|
|
|
uint8_t ctrl_reg4_value = (odr << 4) | (bdu << 3);
|
|
|
spi_driver.write(CTRL_REG4, ctrl_reg4_value);
|
|
|
|
|
|
TRACE("[TempSensor] Init ok \n");
|
|
|
return true; // correctly initialized
|
|
|
}
|
|
|
|
|
|
bool checkWhoAmI()
|
|
|
{
|
|
|
uint8_t who_am_i = spi_driver.read(WHO_AM_I_REG);
|
|
|
|
|
|
TRACE("[TempSensor] WHO_AM_I value : %d \n", who_am_i);
|
|
|
|
|
|
if (who_am_i == WHO_AM_I_DEFAULT_VALUE)
|
|
|
{
|
|
|
TRACE("[TempSensor] WHO_AM_I ok \n");
|
|
|
return true;
|
|
|
}
|
|
|
|
|
|
TRACE("[TempSensor] wrong WHO_AM_I \n");
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
int8_t getTemperature()
|
|
|
{
|
|
|
// the temperature is given as a 8-bits integer (in 2-complement)
|
|
|
// 1 LSB/deg - 8-bit resolution
|
|
|
// also, reading zero means 25 °C, so add the temperature reference
|
|
|
return spi_driver.read(OUT_T) + TEMPERATURE_REF;
|
|
|
}
|
|
|
|
|
|
enum OutputDataRate : uint8_t
|
|
|
{
|
|
|
ODR_POWER_DOWN = 0, // 0000
|
|
|
ODR_3_125_HZ = 1, // 0001, 3.125 Hz
|
|
|
ODR_6_25_HZ = 2, // 0010, 6.25 Hz
|
|
|
ODR_12_5_HZ = 3, // 0011, 12.5 Hz
|
|
|
ODR_25_HZ = 4, // 0100
|
|
|
ODR_50_HZ = 5, // 0101
|
|
|
ODR_100_HZ = 6, // 0110, default value
|
|
|
ODR_400_HZ = 7, // 0111
|
|
|
ODR_800_HZ = 8, // 1000
|
|
|
ODR_1600_HZ = 9 // 1001
|
|
|
};
|
|
|
|
|
|
enum BlockDataUpdate : uint8_t
|
|
|
{
|
|
|
CONTINUOUS_UPDATE_MODE = 0, // continuous update of accelerometer data
|
|
|
UPDATE_AFTER_READ_MODE =
|
|
|
1 // values updated only when MSB and LSB are read (recommended)
|
|
|
};
|
|
|
|
|
|
private:
|
|
|
enum Registers : uint8_t
|
|
|
{
|
|
|
WHO_AM_I_REG = 0x0F,
|
|
|
CTRL_REG4 = 0x20, // control register to set ODR and BDU
|
|
|
OUT_T = 0x0C // temperature output register
|
|
|
};
|
|
|
|
|
|
SpiDriver spi_driver;
|
|
|
|
|
|
uint8_t odr; // output data rate (25 Hz)
|
|
|
uint8_t bdu; // continuous mode or not (continuous update)
|
|
|
|
|
|
const uint8_t WHO_AM_I_DEFAULT_VALUE = 63; // 00111111
|
|
|
const uint8_t TEMPERATURE_REF = 25;
|
|
|
};
|
|
|
```
|
|
|
|
|
|
```cpp
|
|
|
#include <Common.h>
|
|
|
#include "TempSensor.h"
|
|
|
|
|
|
int main()
|
|
|
{
|
|
|
TempSensor temp_driver;
|
|
|
|
|
|
if (temp_driver.init())
|
|
|
{
|
|
|
while(true)
|
|
|
{
|
|
|
TRACE("Temp : %d °C \n", temp_driver.getTemperature());
|
|
|
|
|
|
Thread::sleep(2000);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
return 0;
|
|
|
}
|
|
|
``` |
|
|
\ No newline at end of file |