2571 |
kaklik |
1 |
#include <OneWire.h> |
|
|
2 |
|
|
|
3 |
/* |
|
|
4 |
* DS2408 8-Channel Addressable Switch |
|
|
5 |
* |
|
|
6 |
* Writte by Glenn Trewitt, glenn at trewitt dot org |
|
|
7 |
* |
|
|
8 |
* Some notes about the DS2408: |
|
|
9 |
* - Unlike most input/output ports, the DS2408 doesn't have mode bits to |
|
|
10 |
* set whether the pins are input or output. If you issue a read command, |
|
|
11 |
* they're inputs. If you write to them, they're outputs. |
|
|
12 |
* - For reading from a switch, you should use 10K pull-up resisters. |
|
|
13 |
*/ |
|
|
14 |
|
|
|
15 |
void PrintBytes(uint8_t* addr, uint8_t count, bool newline=0) { |
|
|
16 |
for (uint8_t i = 0; i < count; i++) { |
|
|
17 |
Serial.print(addr[i]>>4, HEX); |
|
|
18 |
Serial.print(addr[i]&0x0f, HEX); |
|
|
19 |
} |
|
|
20 |
if (newline) |
|
|
21 |
Serial.println(); |
|
|
22 |
} |
|
|
23 |
|
|
|
24 |
void ReadAndReport(OneWire* net, uint8_t* addr) { |
|
|
25 |
Serial.print(" Reading DS2408 "); |
|
|
26 |
PrintBytes(addr, 8); |
|
|
27 |
Serial.println(); |
|
|
28 |
|
|
|
29 |
uint8_t buf[13]; // Put everything in the buffer so we can compute CRC easily. |
|
|
30 |
buf[0] = 0xF0; // Read PIO Registers |
|
|
31 |
buf[1] = 0x88; // LSB address |
|
|
32 |
buf[2] = 0x00; // MSB address |
|
|
33 |
net->write_bytes(buf, 3); |
|
|
34 |
net->read_bytes(buf+3, 10); // 3 cmd bytes, 6 data bytes, 2 0xFF, 2 CRC16 |
|
|
35 |
net->reset(); |
|
|
36 |
|
|
|
37 |
if (!OneWire::check_crc16(buf, 11, &buf[11])) { |
|
|
38 |
Serial.print("CRC failure in DS2408 at "); |
|
|
39 |
PrintBytes(addr, 8, true); |
|
|
40 |
return; |
|
|
41 |
} |
|
|
42 |
Serial.print(" DS2408 data = "); |
|
|
43 |
// First 3 bytes contain command, register address. |
|
|
44 |
Serial.println(buf[3], BIN); |
|
|
45 |
} |
|
|
46 |
|
|
|
47 |
OneWire net(10); // on pin 10 |
|
|
48 |
|
|
|
49 |
void setup(void) { |
|
|
50 |
Serial.begin(9600); |
|
|
51 |
} |
|
|
52 |
|
|
|
53 |
void loop(void) { |
|
|
54 |
byte i; |
|
|
55 |
byte present = 0; |
|
|
56 |
byte addr[8]; |
|
|
57 |
|
|
|
58 |
if (!net.search(addr)) { |
|
|
59 |
Serial.print("No more addresses.\n"); |
|
|
60 |
net.reset_search(); |
|
|
61 |
delay(1000); |
|
|
62 |
return; |
|
|
63 |
} |
|
|
64 |
|
|
|
65 |
if (OneWire::crc8(addr, 7) != addr[7]) { |
|
|
66 |
Serial.print("CRC is not valid!\n"); |
|
|
67 |
return; |
|
|
68 |
} |
|
|
69 |
|
|
|
70 |
if (addr[0] != 0x29) { |
|
|
71 |
PrintBytes(addr, 8); |
|
|
72 |
Serial.print(" is not a DS2408.\n"); |
|
|
73 |
return; |
|
|
74 |
} |
|
|
75 |
|
|
|
76 |
ReadAndReport(&net, addr); |
|
|
77 |
} |