DS2408_Switch.ino 1.8 KB

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