Reading and writing to the DS2413 is via the read() and write() functions of the Onewire library:

myWire.read();

Read a byte.

myWire.write(num);

Write a byte.

These functions read and write a byte at a time. So you need to use a little binary arithmetic to separate out the 2 bits corresponding to the 2 GPIO pins.

In the example code, the 2 LEDs are flashed by alternately writing 0x0 and 0x3.
/* Write */
  bool ok = false;
  ok = write(0x3);
  if (!ok) Serial.println(F("Wire failed"));
  delay(1000);
  ok = write(0x0);
  if (!ok) Serial.println(F("Wire failed"));
  delay(1000);

Binary and Hexadecimal

The 0x3 in the example is the hexadecimal equivalent to the binary number B00000011. In the DS2413, the low-order bit (the one to the far right) corresponds to IOA and the one next to it corresponds to IOB. Writing 0x3 writes a binary '1' to both pins and turns them both on.

To turn on just IOA you could write 0x1 (B00000001). And to turn on just IOB, you could write 0x2 (B00000010).

If you substitute the following code, the LEDs will flash alternately:
/* Write */
  bool ok = false;
  ok = write(0x1);
  if (!ok) Serial.println(F("Wire failed"));
  delay(1000);
  ok = write(0x2);
  if (!ok) Serial.println(F("Wire failed"));
  delay(1000);
Or, if you prefer, you can use the binary representation instead:
/* Write */
  bool ok = false;
  ok = write(B00000001);
  if (!ok) Serial.println(F("Wire failed"));
  delay(1000);
  ok = write(B00000010);
  if (!ok) Serial.println(F("Wire failed"));
  delay(1000);
For more on integer constants in the different number bases, see the Arduino Integer Constants page.

Reading GPIO Pins

Reading is a little trickier: You need to separate the individual pin values from the byte that is returned from the read(). A read can return one of 5 values:

  • 0x0 (B00000000) - Both pins LOW
  • 0x1 (B00000001) - IOA = HIGH, IOB = LOW
  • 0x2 (B00000010) - IOA = LOW, IOB = HIGH
  • 0x3 (B00000011) - Both pins HIGH
  • 0xFF (B11111111) - Read Failed!
To extract the state of an individual pin, you will need to use a little binary math. In particular the "bitwise AND" operator: "&".

If you AND the read value from the GPIO breakout with the bit pattern of the pin you are interested in, you will get a boolean "TRUE" if the pin is HIGH and a "FALSE" if the pin is LOW. The following code snippet prints "A" if IOA is HIGH and "B" if IOB is HIGH.
uint8_t state = read();
  const int IOA = 0x1;
  const int IOB = 0x2;
  
  if (state == -1)
  {
    Serial.println(F("Failed reading the DS2413"));
  }
  else
  {
    if (state & IOA)
    {
       Serial.println("A");
    }
    if (state & IOB)
    {
       Serial.println("B");
    }
  }

This guide was first published on Mar 28, 2014. It was last updated on Mar 28, 2024.

This page (Reading, Writing and Arithmetic) was last updated on Mar 23, 2014.

Text editor powered by tinymce.