-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtmp123.c
104 lines (94 loc) · 2.34 KB
/
tmp123.c
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <spibus/spibus.h>
#include <stdlib.h>
#include <stdio.h>
#include "tmp123.h"
int tmp123_init(tmp123 *dev, unsigned spi_bus, unsigned spi_cs, int gpio_cs)
{
if (dev == NULL)
{
fprintf(stderr, "%s, %d: Memory for device not allocated, exiting...\n", __func__, __LINE__);
fflush(stderr);
return -1;
}
if (dev->bus == NULL)
{
fprintf(stderr, "%s, %d: Memory for bus not allocated, exiting...\n", __func__, __LINE__);
fflush(stderr);
return -1;
}
dev->bus->bus = spi_bus;
dev->bus->cs = spi_cs;
dev->bus->mode = SPI_MODE_0;
dev->bus->bits = 8;
dev->bus->speed = 1000000;
dev->bus->lsb = 0;
dev->bus->sleeplen = 0;
dev->bus->internal_rotation = true;
if (gpio_cs < 0)
dev->bus->cs_internal = CS_INTERNAL;
else
dev->bus->cs_internal = CS_EXTERNAL;
dev->bus->cs_gpio = gpio_cs;
return spibus_init(dev->bus);
}
int tmp123_read(tmp123 *dev)
{
static unsigned char b[2] = {0, 0};
int status = spibus_xfer_full(dev->bus, (uint8_t *)(&(dev->temp)), 2, b, 2);
if (status < 0)
{
fprintf(stderr, "TMP123: Temperature readout error\n");
return -5600;
}
return (dev->temp * 6.25 / 8);
}
void tmp123_destroy(tmp123 *dev)
{
spibus_destroy(dev->bus);
}
#ifdef UNIT_TEST_TMP123
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
volatile sig_atomic_t done = 0;
void sighandler(int sig)
{
done = 1;
}
#define NUM_CS 7
int main(int argc, char *argv[])
{
signal(SIGINT, &sighandler);
int tmp_cs[NUM_CS] = {
0x0,
};
tmp123 **dev = (tmp123 **)malloc(NUM_CS * sizeof(tmp123 *));
for (int i = 0; i < NUM_CS; i++)
{
dev[i] = (tmp123 *)malloc(sizeof(tmp123));
tmp_cs[i] = i + 8;
int stat = tmp123_init(dev[i], 1, 2, tmp_cs[i]);
if (stat < 0)
{
printf("Error initializing tmpsensor error %d\n", stat);
goto end;
}
}
while (!done)
{
printf("Temperature sensor readout: ");
for (int i = 0; i < NUM_CS; i++)
printf("%.2f C ", tmp123_read(dev[i])/100.0);
fflush(stdout);
sleep(1);
printf("\r");
}
printf("\n");
end:
for (int i = 0; i < NUM_CS; i++)
free(dev[i]);
free(dev);
return 0;
}
#endif // UNIT_TEST