aboutsummaryrefslogtreecommitdiffstats
path: root/temp.c
blob: 38e873d4bfc3edd56054469b86f6c9fdaeeb135c (plain)
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
74
75
76
77
78
79
80
81
82
83
84
85
/**
 * @file temp.c
 * Provides support for the TMP006 temperature sensor.
 *
 * Copyright (C) 2019  Clyne Sullivan
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include "board.h"
#include "i2c/i2c.h"

// TMP006 I2C address
#define TEMP_ADDR (0x40)

// TMP006 registers
#define TMP006_CONFIG (0x02)
#define TMP006_VOBJ   (0x00)
#define TMP006_TAMB   (0x01)
#define TMP006_MANID  (0xFE)
#define TMP006_DEVID  (0xFF)

// TMP006 CONFIG register parameters
#define TMP006_CFG_RESET    (0x8000)
#define TMP006_CFG_MODEON   (0x7000)
#define TMP006_CFG_1SAMPLE  (0x0000)
#define TMP006_CFG_2SAMPLE  (0x0200)
#define TMP006_CFG_4SAMPLE  (0x0400)
#define TMP006_CFG_8SAMPLE  (0x0600)
#define TMP006_CFG_16SAMPLE (0x0800)
#define TMP006_CFG_DRDYEN   (0x0100)
#define TMP006_CFG_DRDY     (0x0080)

static void tempI2CWrite(uint8_t reg, uint16_t value);
static uint16_t tempI2CRead(uint8_t reg);

int tempInit(void)
{
	// Prepare I2C
	I2C_init(TEMP_ADDR);

	// Initialize the TMP006 sensor
	tempI2CWrite(TMP006_CONFIG, TMP006_CFG_MODEON | TMP006_CFG_DRDYEN |
		TMP006_CFG_16SAMPLE);

	// Check that the device is in fact the TMP006
	if (tempI2CRead(TMP006_MANID) != 0x5449 ||
		tempI2CRead(TMP006_DEVID) != 0x67)
		return -1;

	return 0;
}

void tempI2CWrite(uint8_t reg, uint16_t value)
{
	uint8_t data[3] = {
		reg,
		value >> 8,
		value & 0xFF
	};
	I2C_write(3, data);
}

uint16_t tempI2CRead(uint8_t reg)
{
	uint8_t data[2] = {
		reg,
		0
	};
	I2C_write(1, data);
	I2C_read(2, data);
	return *((uint16_t *)data);
}