-
Notifications
You must be signed in to change notification settings - Fork 0
/
ds18b20.c
95 lines (71 loc) · 1.93 KB
/
ds18b20.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
// An interface to a Maxim DS18B20 digital thermometer
// Allen Snook
// 23 February 2020
#include "ds18b20.h"
#include "onewire.h"
#include "stdio.h" // TODO REMOVE AFTER DEBUGGING
#define DS18B20_SCRATCHPAD_LENGTH 9
static uint8_t ds18b20DataValid = 0;
static uint8_t scratchpad[DS18B20_SCRATCHPAD_LENGTH];
static uint16_t scratchpadByteCount = 0;
uint8_t DS18B20_Data_Valid() {
return ds18b20DataValid;
}
void _DS18B20_Devices_Present_CB( uint8_t data ) {
// TODO
printf( "_DS18B20_Devices_Present_CB: %hu\n", data );
}
void _DS18B20_Read_Scratchpad_Callback( uint8_t data ) {
if ( scratchpadByteCount >= DS18B20_SCRATCHPAD_LENGTH ) {
return;
}
scratchpad[scratchpadByteCount] = data;
scratchpadByteCount++;
if ( DS18B20_SCRATCHPAD_LENGTH == scratchpadByteCount ) {
// TODO - validate the CRC
if ( DS18B20_Get_Temperature_F() < 150 ) {
ds18b20DataValid = 1;
} else {
ds18b20DataValid = 0;
}
}
}
void DS18B20_Init() {
ds18b20DataValid = 0;
OneWire_Init();
for ( uint8_t i=0; i < DS18B20_SCRATCHPAD_LENGTH; i++ ) {
scratchpad[i] = 0;
}
}
void DS18B20_Initiate_Measurement() {
// Reset the one-wire bus
// TODO - detect no devices
OneWire_Reset( 0 );
// Skip ROM
OneWire_WriteByte( 0xCC );
// Initiate temperature conversion
OneWire_WriteByte( 0x44 );
// Wait for conversion to complete
// TODO - detect timeout
//OneWire_WaitForHigh( 0 );
}
void DS18B20_Read_Scratchpad() {
// Reset which byte we are working on
scratchpadByteCount = 0;
// Reset the bus
OneWire_Reset( 0 );
// Skip ROM
OneWire_WriteByte( 0xCC );
// Read the scratchpad
OneWire_WriteByte( 0xBE );
// Read the data
for ( uint8_t i=0; i < DS18B20_SCRATCHPAD_LENGTH; i++ ) {
OneWire_ReadByte( _DS18B20_Read_Scratchpad_Callback );
}
}
int16_t DS18B20_Get_Temperature_F() {
int16_t rawTemp = ( scratchpad[1] << 8 ) | (scratchpad[0] & 0xFF );
int16_t tempC = rawTemp / 16;
int16_t tempF = ( tempC * 9 / 5 ) + 32;
return tempF;
}