summaryrefslogtreecommitdiffstats
path: root/boiler-monster/stm32/app/ds1820.c
blob: 200f4b724ed99983e6bd39b6d4b8dd9d59285509 (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
86
87
88
89
90
91
92
93
#include "project.h"

#define DS1820_READ_SCRATCHPAD 0xbe
#define DS1820_CONVERT_T 0x44


#define TIMEOUT 150



static unsigned extract_leu16 (uint8_t *d)
{
  uint32_t u;

  u = (uint32_t) d[0] | (((uint32_t) d[1]) << 8);
  return u;
}



static int extract_les16 (uint8_t *d)
{
  uint32_t u;
  u = extract_leu16 (d);

  if (u & 0x8000) u |= 0xffff0000;

  return (int) u;
}





static int
ds1820_read_sp (const Onewire_addr *a, unsigned page, uint8_t *buf, unsigned len)
{
  if (onewire_reset_and_select (a))
    return ~0U;

  onewire_write_byte (DS1820_READ_SCRATCHPAD);
  onewire_read_bytes (buf, len);

  if ((len == 9) && onewire_check_crc (buf, 8, buf[8]))
    return ~0U;

  return 0;
}



static int ds1820_convert_t (const Onewire_addr *a)
{

  if (onewire_reset_and_select (a))
    return ~0U;

  onewire_write_byte (DS1820_CONVERT_T);

  if (onewire_wait_complete (TIMEOUT))
    return ~0U;

  return 0;
}

int
ds1820_read (const Onewire_addr *a, int *temp)
{
  uint8_t buf[9];
  int t;

  if (ds1820_read_sp (a, 0, buf, 9))
    return 1;

  if (ds1820_convert_t (a))
    return 1;

  if (ds1820_read_sp (a, 0, buf, 9))
    return 1;

  t = extract_les16 (&buf[0]);

  t <<= 4 ;

  if (temp)
    *temp = t;


  return 0;
}