forked from simonbarker/pic-libraries
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathonewire.c
89 lines (76 loc) · 1.69 KB
/
onewire.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
#include <xc.h>
#include "onewire.h"
void onewireWriteBit(int b) {
b = b & 0x01;
if (b) {
// Write '1' bit
onewirePinDirection = 0;
onewirePin = 0;
__delay_us(5);
onewirePinDirection = 1;
__delay_us(60);
} else {
// Write '0' bit
onewirePinDirection = 0;
onewirePin = 0;
__delay_us(70);
onewirePinDirection = 1;
__delay_us(2);
}
}
unsigned char onewireReadBit() {
unsigned char result;
onewirePinDirection = 0;
onewirePin = 0;
__delay_us(1);
onewirePinDirection = 1;
__delay_us(5);
result = onewirePin;
__delay_us(55);
return result;
}
unsigned char onewireInit() {
onewirePinDirection = 0;
onewirePin = 0;
__delay_us(480);
onewirePinDirection = 1;
__delay_us(60);
if (onewirePin == 0) {
__delay_us(100);
return 1;
}
return 0;
}
unsigned char onewireReadByte() {
unsigned char result = 0;
for (unsigned char loop = 0; loop < 8; loop++) {
// shift the result to get it ready for the next bit
result >>= 1;
// if result is one, then set MS bit
if (onewireReadBit())
result |= 0x80;
}
return result;
}
void onewireWriteByte(char data) {
// Loop to write each bit in the byte, LS-bit first
for (unsigned char loop = 0; loop < 8; loop++) {
onewireWriteBit(data & 0x01);
// shift the data byte for the next bit
data >>= 1;
}
}
unsigned char onewireCRC(unsigned char* addr, unsigned char len) {
unsigned char i, j;
unsigned char crc = 0;
for (i = 0; i < len; i++) {
unsigned char inbyte = addr[i];
for (j = 0; j < 8; j++) {
unsigned char mix = (crc ^ inbyte) & 0x01;
crc >>= 1;
if (mix) crc ^= 0x8C;
inbyte >>= 1;
}
}
return crc;
}