MatrixMiniR4 1.1.5
Matrix Mini R4 Arduino Library API Documentation
Loading...
Searching...
No Matches
MiniR4_DS18B20.h
Go to the documentation of this file.
1
14#ifndef MINIR4_DS18B20_H
15#define MINIR4_DS18B20_H
16
17#include <Arduino.h>
18
19#define DS_PROGMEM 1
20
21#ifndef DS_CHECK_CRC
22#define DS_CHECK_CRC true // true/false - проверка контрольной суммы принятых данных - надежнее, но тратит немного больше flash
23#endif
24
25#ifndef DS_CRC_USE_TABLE
26#define DS_CRC_USE_TABLE false // true/false - использовать готовую таблицу контрольной суммы - значительно быстрее, +256 байт flash
27#endif
28
29#ifdef __AVR__
30#define MOW_CLI() uint8_t oldSreg = SREG; cli();
31#define MOW_SEI() SREG = oldSreg
32#else
33#define MOW_CLI()
34#define MOW_SEI()
35#endif
36
37// ====================== CRC TABLE ======================
38#if (DS_CRC_USE_TABLE == true)
39static const uint8_t PROGMEM _ds_crc8_table[] = {
40 0x00, 0x5e, 0xbc, 0xe2, 0x61, 0x3f, 0xdd, 0x83, 0xc2, 0x9c, 0x7e, 0x20, 0xa3, 0xfd, 0x1f, 0x41,
41 0x9d, 0xc3, 0x21, 0x7f, 0xfc, 0xa2, 0x40, 0x1e, 0x5f, 0x01, 0xe3, 0xbd, 0x3e, 0x60, 0x82, 0xdc,
42 0x23, 0x7d, 0x9f, 0xc1, 0x42, 0x1c, 0xfe, 0xa0, 0xe1, 0xbf, 0x5d, 0x03, 0x80, 0xde, 0x3c, 0x62,
43 0xbe, 0xe0, 0x02, 0x5c, 0xdf, 0x81, 0x63, 0x3d, 0x7c, 0x22, 0xc0, 0x9e, 0x1d, 0x43, 0xa1, 0xff,
44 0x46, 0x18, 0xfa, 0xa4, 0x27, 0x79, 0x9b, 0xc5, 0x84, 0xda, 0x38, 0x66, 0xe5, 0xbb, 0x59, 0x07,
45 0xdb, 0x85, 0x67, 0x39, 0xba, 0xe4, 0x06, 0x58, 0x19, 0x47, 0xa5, 0xfb, 0x78, 0x26, 0xc4, 0x9a,
46 0x65, 0x3b, 0xd9, 0x87, 0x04, 0x5a, 0xb8, 0xe6, 0xa7, 0xf9, 0x1b, 0x45, 0xc6, 0x98, 0x7a, 0x24,
47 0xf8, 0xa6, 0x44, 0x1a, 0x99, 0xc7, 0x25, 0x7b, 0x3a, 0x64, 0x86, 0xd8, 0x5b, 0x05, 0xe7, 0xb9,
48 0x8c, 0xd2, 0x30, 0x6e, 0xed, 0xb3, 0x51, 0x0f, 0x4e, 0x10, 0xf2, 0xac, 0x2f, 0x71, 0x93, 0xcd,
49 0x11, 0x4f, 0xad, 0xf3, 0x70, 0x2e, 0xcc, 0x92, 0xd3, 0x8d, 0x6f, 0x31, 0xb2, 0xec, 0x0e, 0x50,
50 0xaf, 0xf1, 0x13, 0x4d, 0xce, 0x90, 0x72, 0x2c, 0x6d, 0x33, 0xd1, 0x8f, 0x0c, 0x52, 0xb0, 0xee,
51 0x32, 0x6c, 0x8e, 0xd0, 0x53, 0x0d, 0xef, 0xb1, 0xf0, 0xae, 0x4c, 0x12, 0x91, 0xcf, 0x2d, 0x73,
52 0xca, 0x94, 0x76, 0x28, 0xab, 0xf5, 0x17, 0x49, 0x08, 0x56, 0xb4, 0xea, 0x69, 0x37, 0xd5, 0x8b,
53 0x57, 0x09, 0xeb, 0xb5, 0x36, 0x68, 0x8a, 0xd4, 0x95, 0xcb, 0x29, 0x77, 0xf4, 0xaa, 0x48, 0x16,
54 0xe9, 0xb7, 0x55, 0x0b, 0x88, 0xd6, 0x34, 0x6a, 0x2b, 0x75, 0x97, 0xc9, 0x4a, 0x14, 0xf6, 0xa8,
55 0x74, 0x2a, 0xc8, 0x96, 0x15, 0x4b, 0xa9, 0xf7, 0xb6, 0xe8, 0x0a, 0x54, 0xd7, 0x89, 0x6b, 0x35
56};
57#endif
58
59#pragma GCC diagnostic push
60#pragma GCC diagnostic ignored "-Wunused-variable"
61static uint8_t _empDsAddr[1] = {1};
62#pragma GCC diagnostic pop
63#define DS_ADDR_MODE _empDsAddr
64
78template <uint8_t PIN1, uint8_t PIN2, uint8_t * DS_ADDR = (uint8_t * ) nullptr, uint8_t DS_AM = 1, bool DS_PGM = 0> class MiniR4DS18B20 {
79 public:
80
82 DS_PIN = PIN2; //PIN設定在DI_R位置,通過MiniR4Digital_h模板Pin1_2順序來初始化Grove或MATRIX物件
83 pinMode(DS_PIN, INPUT);
84 digitalWrite(DS_PIN, LOW);
85 }
86
92 void setResolution(uint8_t res, uint8_t idx = 0) {
93 if (!oneWire_reset(DS_PIN)) return; // Проверка присутствия
94 addressRoutine(idx); // Процедура адресации
95 oneWire_write(0x4E, DS_PIN); // Запись RAM
96 oneWire_write(0xFF, DS_PIN); // Максимум в верхний регистр тревоги
97 oneWire_write(0x00, DS_PIN); // Минимум в верхний регистр тревоги
98 oneWire_write(((constrain(res, 9, 12) - 9) << 5) | 0x1F, DS_PIN); // Запись конфигурации разрешения
99 }
100
105 void setResolutionAll(uint8_t res) {
106 for (int i = 0; i < DS_AM; i++) setResolution(res, i);
107 }
108
113 void setAddress(uint8_t * addr) {
114 _addr = addr;
115 }
116
122 bool readAddress(uint8_t * addr) {
123 if (!oneWire_reset(DS_PIN)) return 0; // Проверка присутствия
124 oneWire_write(0x33, DS_PIN); // Запрос адреса
125 uint16_t sum = 0; // контрольная сумма
126 uint8_t crc = 0; // обнуляем crc
127 for (uint8_t i = 0; i < 8; i++) { // Прочитать 8 байт адреса
128 addr[i] = oneWire_read(DS_PIN); // Записать в массив
129 sum += addr[i]; // контрольная сумма
130 #if(DS_CHECK_CRC == true)
131 _ds_crc8_upd(crc, addr[i]); // Обновить значение CRC8
132 #endif
133 }
134 return !(sum == 0x8F7 || !sum || crc); // CRC не сошелся или адрес нулевой - ошибка
135 }
136
141 void requestTemp(uint8_t idx = 0) {
142 state[idx] = 0; // запрошена новая температура
143 if (!oneWire_reset(DS_PIN)) return; // Проверка присутствия
144 addressRoutine(idx); // Процедура адресации
145 oneWire_write(0x44, DS_PIN); // Запросить преобразование
146 }
147
152 for (int i = 0; i < DS_AM; i++) requestTemp(i);
153 }
154
160 float getTemp(uint8_t idx = 0) {
161 if (!state[idx]) readTemp(idx);
162 return (_buf[idx] / 16.0);
163 }
164
170 float requestAndGetTemp(uint8_t idx = 0) {
171 requestTemp(idx);
172 delay(1);
173 if (!state[idx]) readTemp(idx);
174 return (_buf[idx] / 16.0);
175 }
176
182 int16_t getTempInt(uint8_t idx = 0) {
183 if (!state[idx]) readTemp(idx);
184 return (_buf[idx] >> 4);
185 }
186
192 int16_t getRaw(uint8_t idx = 0) {
193 if (!state[idx]) readTemp(idx);
194 return _buf[idx];
195 }
196
202 bool readTemp(uint8_t idx = 0) {
203 state[idx] = 1;
204 if (!oneWire_reset(DS_PIN)) return 0; // датчик оффлайн
205 addressRoutine(idx); // Процедура адресации
206 oneWire_write(0xBE, DS_PIN); // Запросить температуру
207 uint8_t crc = 0; // обнуляем crc
208 int16_t temp; // переменная для расчёта температуры
209 uint16_t sum = 0; // контрольная сумма
210 for (uint8_t i = 0; i < 9; i++) { // Считать RAM
211 uint8_t data = oneWire_read(DS_PIN); // Прочитать данные
212 sum += data;
213 #if(DS_CHECK_CRC == true)
214 _ds_crc8_upd(crc, data); // Обновить значение CRC8
215 #endif
216 if (i == 0) temp = data;
217 else if (i == 1) temp |= (data << 8);
218 }
219 if (sum == 0x8F7 || !sum || crc) return 0; // датчик оффлайн или данные повреждены
220 if (temp != 0x0550) _buf[idx] = temp; // пропускаем первое чтение (85 градусов)
221 return 1;
222 }
223
229 bool online(uint8_t idx = 0) {
230 if (DS_ADDR != nullptr) {
231 if (!oneWire_reset(DS_PIN)) return 0;
232 addressRoutine(idx);
233 oneWire_write(0xBE, DS_PIN);
234 uint16_t sum = 0;
235 for (uint8_t i = 0; i < 5; i++) sum += oneWire_read(DS_PIN);
236 return (sum != 0x4FB);
237 } else return oneWire_reset(DS_PIN);
238 }
239
240 private:
241 int DS_PIN; // Pin number for the DS18B20 sensor.
242 bool state[DS_AM];
243 int16_t _buf[DS_AM];
244 uint8_t * _addr = DS_ADDR;
245
246 void addressRoutine(uint8_t idx) { // Addressing procedure
247 if (DS_ADDR != nullptr) { // Адрес определен?
248 oneWire_write(0x55, DS_PIN); // Говорим термометрам слушать адрес
249 for (uint8_t i = 0; i < 8; i++) {
250 if (DS_PGM) oneWire_write(pgm_read_byte( & _addr[i + idx * 8]), DS_PIN);
251 else oneWire_write(_addr[i + idx * 8], DS_PIN);
252 }
253 } else oneWire_write(0xCC, DS_PIN); // Адреса нет - пропускаем адресацию на линии
254 }
255
256 bool oneWire_reset(uint8_t pin) {
257 pinMode(pin, OUTPUT);
258 delayMicroseconds(600);
259 pinMode(pin, INPUT);
260 MOW_CLI();
261 delayMicroseconds(60);
262 bool pulse = digitalRead(pin);
263 MOW_SEI();
264 delayMicroseconds(600);
265 return !pulse;
266 }
267
268 void oneWire_write(uint8_t data, uint8_t pin) {
269 for (uint8_t i = 8; i; i--) {
270 pinMode(pin, OUTPUT);
271 MOW_CLI();
272 if (data & 1) {
273 delayMicroseconds(5);
274 pinMode(pin, INPUT);
275 delayMicroseconds(60);
276 } else {
277 delayMicroseconds(60);
278 pinMode(pin, INPUT);
279 delayMicroseconds(5);
280 }
281 MOW_SEI();
282 data >>= 1;
283 }
284 }
285
286 uint8_t oneWire_read(uint8_t pin) {
287 uint8_t data = 0;
288 for (uint8_t i = 8; i; i--) {
289 data >>= 1;
290 MOW_CLI();
291 pinMode(pin, OUTPUT);
292 delayMicroseconds(2);
293 pinMode(pin, INPUT);
294 delayMicroseconds(8);
295 if (digitalRead(pin)) data |= (1 << 7);
296 delayMicroseconds(60);
297 MOW_SEI();
298 }
299 return data;
300 }
301
302 void _ds_crc8_upd(uint8_t & crc, uint8_t data) {
303 #if(DS_CRC_USE_TABLE == true) // Используем таблицу?
304 crc = pgm_read_byte( & _ds_crc8_table[crc ^ data]); // Тогда берем готовое значение
305 #else // считаем вручную
306 #ifdef __AVR__
307 // резкий алгоритм для AVR
308 uint8_t counter;
309 uint8_t buffer;
310 asm volatile(
311 "EOR %[crc_out], %[data_in] \n\t"
312 "LDI %[counter], 8 \n\t"
313 "LDI %[buffer], 0x8C \n\t"
314 "_loop_start_%=: \n\t"
315 "LSR %[crc_out] \n\t"
316 "BRCC _loop_end_%= \n\t"
317 "EOR %[crc_out], %[buffer] \n\t"
318 "_loop_end_%=: \n\t"
319 "DEC %[counter] \n\t"
320 "BRNE _loop_start_%=": [crc_out]
321 "=r"(crc), [counter]
322 "=d"(counter), [buffer]
323 "=d"(buffer): [crc_in]
324 "0"(crc), [data_in]
325 "r"(data)
326 );
327 #else
328 // обычный для всех остальных
329 uint8_t i = 8;
330 while (i--) {
331 crc = ((crc ^ data) & 1) ? (crc >> 1) ^ 0x8C : (crc >> 1);
332 data >>= 1;
333 }
334 #endif
335 #endif
336 }
337};
338
339#endif // MINIR4_DS18B20_H
#define MOW_SEI()
#define MOW_CLI()
#define pgm_read_byte(addr)
#define PROGMEM
Template class for interfacing with DS18B20 temperature sensors.
float requestAndGetTemp(uint8_t idx=0)
Combines request and get temperature operations.
int16_t getTempInt(uint8_t idx=0)
Gets the temperature as an integer from a specific sensor.
bool readAddress(uint8_t *addr)
Reads the unique address of the sensor.
void setResolutionAll(uint8_t res)
Sets the resolution for all sensors on the line.
bool online(uint8_t idx=0)
Checks if the sensor is online.
void requestTempAll()
Requests a temperature conversion from all sensors on the line.
void setResolution(uint8_t res, uint8_t idx=0)
Sets the resolution for a specific sensor.
int16_t getRaw(uint8_t idx=0)
Gets the raw temperature data from a specific sensor.
float getTemp(uint8_t idx=0)
Gets the temperature as a float from a specific sensor.
void setAddress(uint8_t *addr)
Set the address of the sensor.
bool readTemp(uint8_t idx=0)
Reads the temperature from a specific sensor.
void requestTemp(uint8_t idx=0)
Requests a temperature conversion from a specific sensor.