summaryrefslogtreecommitdiffstats
path: root/radiator-plc/stm32/app/ds18b20.c
blob: 3bd63edf63d8d4f40f6298a0f0947f7815759a19 (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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include "project.h"

#define DS18B20_CONVERT 0x44
#define DS18B20_WRITE_SCRATCHPAD 0x4e
#define DS18B20_READ_SCRATCHPAD 0xbe


#define TIMEOUT 150


unsigned extract_leu16 (uint8_t *d)
{
  uint32_t u;

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


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

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

  return (int) u;
}


/* do not call from interrupt context (ie ticker)*/
int
ds18b20_read_sp (const Onewire_addr *a, uint8_t *buf, unsigned len)
{
  if (onewire_reset_and_select (a))
    return ~0U;

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


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

  return 0;
}

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

  onewire_write_byte (DS18B20_WRITE_SCRATCHPAD);
  onewire_write_bytes (buf, len);

  return 0;
}

int ds18b20_convert (const Onewire_addr *a, unsigned timeout)
{

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

  onewire_write_byte (DS18B20_CONVERT);

  if (timeout && onewire_wait_complete (timeout))
    return ~0U;

  return 0;
}

int
ds18b20_set_12 (const Onewire_addr *a)
{
  uint8_t buf[9];


  if (ds18b20_read_sp (a, buf, 9))
    return 1;

  buf[0] = 0x0;
  buf[1] = 0x0;
  buf[2] = 0x7f; /* 12 bit conversions */

  return ds18b20_write_sp (a, buf, 3);

}

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

  if (ds18b20_read_sp (a, buf, 9))
    return 1;

  *temp = (extract_les16 (buf) * 500) >> 3;
  return 0;
}


int
ds18b20_set_12_convert (const Onewire_addr *a)
{

  if (ds18b20_set_12 (a))
    return 1;

  if (ds18b20_convert (a, 0))
    return 1;

  return 0;
}

/* do not call from interrupt context (ie ticker)*/
int
ds18b20_set_12_convert_and_read (const Onewire_addr *a, int *temp)
{
  if (ds18b20_set_12 (a))
    return 1;

  if (ds18b20_convert (a, TIMEOUT))
    return 1;

  return ds18b20_read (a, temp);
}