Software Methods to Achieve Robust 1 Wire® Communication in iButton® Applications - kr1spyK/DS1991SecureViewer GitHub Wiki

APPLICATION NOTE 159

Software Methods to Achieve Robust 1-Wire® Communication in iButton® Applications

Abstract: 1-Wire devices communicate using a single data line plus ground reference. The 1-Wire protocol includes special provisions to handle highly intermittent ("touch") connections that are common when using 1-Wire devices in the stainless steel iButton package. This application note explains when special attention to data integrity is advised, and discusses techniques to achieve the most reliable communication in iButton applications. The reader should be familiar with the 1-Wire bus protocol and the methods to generate 1-Wire communication using a microcontroller. Although the main focus of this document is on applications with unreliable connections, some of the methods described can improve the reliability in hardwired 1-Wire applications.

Introduction

1-Wire devices communicate using a single data line plus ground reference. The 1-Wire protocol together with additional built-in features make iButtons suitable for applications that need to cope with highly intermittent ("touch") connections. When iButtons are used for applications such as high-security identification or monetary transactions, then highly reliable communication is most critical for successful operation.

General 1-Wire device communication involves several functions: searching (to identify the devices present on the bus), reading device identification number (also known as network address, registration number, 64-bit unique ID, and 64-bit lasered ROM), reading device data or status, and writing memory data or control information. In some cases, it is simple for the software to detect and correct communication failures. When a failure occurs while reading, for example, the software may attempt to read the iButton again, or may rely on the user to remove and reconnect the iButton to start a new transaction. Such a corrective action causes only a minor delay or annoyance to the user.

Writing to an iButton, however, is a much more critical task. If the iButton has departed before a read back to verify, one may not even know that the data was miswritten. If the data was written in error, there may not be an opportunity to rewrite it. The consequences of an unsuccessful write can be quite serious. If an iButton contains monetary data, debits (purchases) usually include writing revised monetary amounts to the iButton each time that a purchase is made. Should one of these updates fail and leave the data in an undefined state, the user may lose the entire monetary balance.

Programs that perform 1-Wire communications over intermittent connections must have a well thought-out plan for handling retries when failures occur. The software developer must consider everything that could have occurred during the failed attempt. Detecting errors sooner rather than later yields a faster system response and reduces the risk of updating data in the wrong (swapped) iButton. This rapid action, in turn, improves the confidence of the users in the technology. Whenever customer satisfaction is critical, the extra step to make 1-Wire communication most robust is strongly advised.

Error Mechanisms

The 1-Wire bus is a wired-OR arrangement. The idle state of the bus is logic high. For communication, the 1-Wire bus is pulled down by low-impedance drivers in the master and slave devices (iButtons), and returns to a high level due to weaker pullup currents provided by the master. Besides communication initiated by the master, the bus can be pulled low from presence pulses generated by arriving iButton devices and electrical short circuits caused when an iButton is improperly seated in the probe.

An external source of interference can turn a logic 1 bit into a logic 0 bit by short-circuiting the bus. A logic 0 bit can be turned into a logic 1 bit, if the interference has sufficient energy to overcome the low-impedance driver generating the 0 bit. For this reason, the probability of a logic 1 being turned into a logic 0 is much higher than the reverse. Loss of contact when the slave returns a 0 bit will result in a 1 bit read by the master. Slave devices can, moreover, mistake a noise pulse of either polarity injected into the 1-Wire bus as a new time slot, which causes all the subsequent bits to be returned out-of-step with the master. The software developer must be aware of bit errors such as inverted bits, dropped bits, extra bits, and shorts. In iButton applications, the bus should always be presumed unreliable; every precaution should be taken to ensure data integrity.

Error Detection/Prevention Methods Provided by iButtons

The cyclic redundancy check (CRC) is one of the error detection methods used by all 1-Wire devices and iButtons. An 8-bit CRC is part of each device’s identification number to verify error-free transmission. Memory iButtons often have a built-in 16-bit CRC generator to safeguard data when reading from the device. The 1-Wire file system (see application note 114, "1-Wire File Structure") appends a 16-bit CRC at the end of each data record. To compute this CRC, the CRC generator is preloaded with the page number. Should an error occur in the transmission of the address bits that select the memory page, the CRC verification will fail when the wrong page was accessed.

Although CRCs are a powerful tool to discover the presence of bit errors, they also have a weakness: the CRC of all zeros is zero. This means that a shorted bus (which returns all zero bits) shows a valid CRC, despite the fact that the data is entirely in error. Therefore, additional checks or redundancy mechanisms must be used, such as verifying the validity of the family code contained in the first byte of the identification number. To help alleviate the all-zeros CRC problem, a bit-wise inverted CRC is often used in iButton devices and data structures.

To prevent data from corrupting during a memory write access, memory iButtons have a temporary storage area called the scratchpad. Once the data is written to the scratchpad and a read-back confirms that it is error free, the data can be transferred to the target destination in an uninterruptible operation. The data transfer mechanics from the scratchpad to the target location depend on the memory technology. See the sections Reliably Writing to NVSRAM and Reliably Writing to EEPROM for details.

Obtaining the Device Identification Number

Since the iButton touch contact should be considered unreliable, it is important to watch for communication errors and to detect them as early as possible. This allows the software to start a retry sooner, saving time and improving the performance of the application.

When arriving at a probe and following a bus reset, iButton devices generate a presence pulse. The 1-Wire master (microcontroller) may use the presence pulse or any activity such as a short on the bus to cause an interrupt, thus invoking program code to process the arrival of the iButton. In battery-powered applications, this presence pulse is used first to wake-up a sleeping microcontroller and then to invoke the arrival routine. Alternatively, a reader (master) may simply poll, or issue repeated reset pulses, and watch for the appearance of a presence pulse as evidence of a device on the bus. The polling method, however, is applicable only in systems that, by design, cannot have more than one iButton on the bus. If this condition is not met, a more elaborate method is required. See the section Maintaining a List of Devices Present on the Bus for details.

When the master has detected the presence pulse from an iButton at the probe, there are two ways to learn the device identification number: the Read ROM method and the Search ROM method.

The Read ROM method uses the Read ROM command. This method yields a valid result only if a single 1-Wire device is on the bus. The key to verifying a correct reading is the CRC at the end of the identification number. In case of bit errors caused by temporary loss of contact or short, the CRC read will not match the CRC computed by the master, thus indicating that the reading was not successful. Executing the Read ROM command without an iButton at the probe results in an identification number of eight FFh bytes. The CRC check unveils the error. Reading the ROM while the probe is shorted yields an identification number of eight 00h bytes. In this case, the CRC check fails. However, with the knowledge that a 00h family code is not assigned, the data is identified as invalid. Since there is a 1 in 256 chance of a valid CRC despite a bit error, it is advisable to read the identification number again and to compare the two results for a match. This action will ensure that the reading was error free.

The Search ROM method uses the Search ROM command, which is a more interactive process to read the identification number. Search ROM uses a binary search technique in which the iButton participates in a two-way communication over 192 time slots. In this way, bit errors such as disconnect, short, and losing synchronization are easily detected. A single pass through Search ROM takes slightly more time than two passes of Read ROM. Successful completion of Search ROM, even without checking the CRC, is a strong indication that a device is present and ready for subsequent communications. For more information on the use of the Search ROM technique see application note 187, "1-Wire Search Algorithm."

Maintaining a List of Devices Present on the Bus

Many applications require the reliable detection of iButton arrivals at and departure from the bus. To detect arrivals and departures, one needs a table of the devices known to be present on the bus plus some management information. One component of the management information is called "age." This age information is used for debouncing and to decide whether a device has departed from the bus. Debouncing reduces the number of false arrivals/departures reported due to read errors. One scheme to detect arrivals and departures is described by the following algorithm:

  1. The bus is continually scanned using Search ROM to discover each identification number in turn. Without any errors, one scan cycle requires as many Search ROM passes as there are devices on the bus.
  2. After a device has been identified, the device table is referenced to determine whether the device has been found in a previous cycle. If the device is not listed in the table, then it just arrived. It is added to the table and reported as a new arrival.
  3. When a device is added to the table and when a device just identified is already in the table, the age data for that device is set to "n" (n represents a numeric value, such as 5).
  4. Before a new scan cycle begins, the age information for all devices in the table is decremented. If an age value reaches zero, then the device has not been observed in n scan cycles. This device is removed from the table and reported as a departure.

To implement this scheme, one needs a table with a 9-byte entry for each device. The table must be large enough to store as many entries as there can be devices on the bus.

To increase the reliability of the arrivals/departure algorithm, it is necessary to test the validity of the family code, to check for a valid CRC, and to make new arrivals tentative. The expanded algorithm looks like this:

  1. The bus is continually scanned using Search ROM to discover each identification number in turn. Without any errors, one scan cycle requires as many Search ROM passes as there are devices on the bus.
  2. After a device has been identified, the identification number is checked for nonzero family code and for a valid CRC.
  3. An identification number with valid family code and CRC is looked up in the device table to determine whether the device was found in a previous cycle.
  4. If the device is not listed in the table, then it just arrived. It is added to the table. The age data is set to 3, and a flag is set to mark the arrival as tentative.
  5. If the device is already listed in the table and flagged as tentative, then the age value is incremented by two. If the age value is greater than 3, then: the age byte is set to n; the tentative flag is cleared; and an arrival event is reported.
  6. If the device is already listed in the table and not flagged as tentative, the age value is incremented by 1 up to, but not beyond, n.
  7. Before a new scan cycle begins and the bus is not shorted, the age information for all devices in the table is decremented by 1. If an age value reaches zero, then the device has not been observed in n scan cycles. This device is removed from the table, and, if the device was not flagged as tentative, reported as a departure.

To be reported as an arrival, a device must be discovered in two consecutive scan cycles. To be reported as a departure, a device must not be found in n consecutive scans cycles. If the bus is performing well, then none of the entries is flagged as tentative, and the age values are equal to n. Devices that are occasionally missed in a scan cycle have age values lower than n. This algorithm has proven most reliable in reporting arrivals and departures from the 1-Wire bus. If a short is detected on the 1-Wire bus, then the arrivals/departures algorithm may be suspended until the short is removed. Without this exception all devices could be marked as departures in a short amount of time.

Reliably Addressing a Device

Once the identification number of a device that has newly arrived at the probe has been verified as correct, this number is used to select the device for subsequent communications. In systems where only one device may exist on the bus, one may be tempted to use Skip ROM instead of the Match ROM. This is not advisable, because the device that was identified before could have departed and a different device could have arrived. Therefore, it is necessary to begin each transaction at least using a Match ROM sequence.

Besides Match ROM, there is another method called "Strong Access" to address a 1-Wire device. Strong Access uses the Search ROM function with a predetermined direction for every bit in the sequence. In other words, the device is discovered in a search that already knows the device that it expects to find. The end result is the same as with Match ROM, but Search ROM requires 128 correct bits of feedback from the device, thereby assuring that the device to be addressed is still present. Since a missing device cannot return the proper responses, the Search ROM method discovers that a device is missing within a few bit times.

To decide whether Match ROM or Search ROM is the right choice for a given application, it is necessary to know the system response for the two methods. Match ROM at standard speed takes approximately 5.6ms to complete (0.7ms at overdrive speed). A Search ROM sequence requires approximately 14ms to complete (1.7ms at overdrive speed). For an application that requires 10 access cycles to complete a transaction—for example, the Strong Access method adds 84ms at standard speed—this may not be accepted by the users. Newer 1-Wire devices support a ROM function command called "Resume." This command takes the same time as Skip ROM, but ensures that maximum one device can respond to the subsequent memory or control function command. This eliminates the risk of accidentally deleting data if the target device has departed from the bus. In general, if a short system response time is critical for user acceptance, one should consider using overdrive speed. See the section on 1-Wire Speed Considerations for additional information.

Reliably Reading from a Device

Once a device is reliably addressed, the master sends: the Read Memory command; the memory target address; and as many read time slots as needed to read the memory data of interest. If the Read Memory command was received error free, errors could still corrupt the transmission of the memory target address and affect the memory data on its way to the master. If the Read Memory command was not received error free, the iButton would, with high probability, ignore the command.

The memory of iButtons is organized in pages of 32 or 64 bytes. With the exception of the DS1920, DS1971, DS1990, and DS1991, iButtons are compatible to the 1-Wire File Structure described in application note 114 mentioned above. This file system puts a length byte at the beginning of each page and appends a continuation pointer and inverted CRC16 at the end of the data field. This system provides a high level of error control when reading iButton memory data. Since the CRC generator is preloaded with the memory page number, the 1-Wire File Structure not only safeguards against bit errors in the data stream, but also uncovers target address errors. When using the DS1971 or DS1991, data packets should be formatted similar to that described in application note 114.

Besides their compatibility with the 1-Wire File Structure, the following iButtons have a built-in CRC generator to safeguard memory read access: DS1921, DS1922, DS1923, DS196x series, DS1977, and DS198x series. Except for the DS1982, the device-generated CRC is a 16-bit type. The built-in CRC generator, which usually requires an extended read command for activation, inserts a CRC after the last byte of a memory page is transmitted. When relying on this CRC generator, the page data does not need to be formatted (saving 4 bytes per page vs. the format in application note 114). If the page data is formatted, the device-generated CRC provides another layer to verify the data integrity.

If a read error is uncovered, the standard remedy is to read the same data (or page) again. Multiple reading is also advised if memory data is unformatted and the iButton does not generate a CRC.

Some applications may require that the data be encrypted or that a Message Authentication Code (e.g., a SHA-1 MAC) be embedded in the page. One could argue that a failed decryption or invalid MAC is an indication of a read error. Although this is true, it is imprudent to set up a system this way, since one could not distinguish between read error and intentional tampering to commit fraud. Therefore, the data should first be checked for physical integrity using the means explained above, and then, in a second step, the cryptographic validation should be applied. Only then can the appropriate action be taken and valid statistics be collected.

Reliably Writing to NVSRAM

NVSRAM-based memory iButtons have a built-in battery that provides backup of the scratchpad data and energy to complete the transfer to the target memory, regardless of the activities on the 1-Wire bus during the transfer. To ensure that the communication was successful, it is necessary: 1) to verify the data in the scratchpad, 2) to read back the memory page that was updated, and 3) to compare with the intended data.

The entire process is best explained by an example, such as a purchase at a vending machine. In this case the data is encrypted for security. The steps below use functions explained on preceding pages. For more details refer to the eCash Evaluation Kit (part number: DSECASH).

  1. Detect the iButton arrival.
  2. Obtain the iButton’s identification number and check for integrity (i.e., family code, CRC).
  3. Reliably address the iButton. If addressing fails, END (failure).
  4. Reliably read the page that stores the monetary balance. This includes verification of data integrity. (Using the 1-Wire data structure, this step requires reading multiple pages, sequentially or randomly.) If there is no success after multiple attempts, wait for iButton departure. END (failure).
  5. Cryptographic validation of page data, check for sufficient funds. If steps fails, display error message, wait for iButton departure. END (failure).
  6. Reliably address the iButton. If addressing fails, END (failure).
  7. Write new encrypted balance to scratchpad. Depending on iButton model, byte offset, and number of bytes written, the Write Scratchpad command may return a CRC for transfer integrity check. If so, use this CRC accordingly.
  8. Reliably address the iButton. If addressing fails, END (failure).
  9. Read scratchpad; compare address and data for match with data written to the scratchpad. If no match, go to 6).
  10. Reliably address the iButton. If addressing fails, END (failure).
  11. Issue Copy Scratchpad command, wait 32µs.
  12. Reliably address the iButton. If addressing fails, END (failure).
  13. Read updated page, compare to intended data. If data matches, dispense product; END (completed). If no match, go to 8).

This example assumes an iButton without special security features. The DS1963S has several write cycle counters that increment with every write access to an associated memory page. The counter value can be included in the encryption to create unique instances of the monetary value, e.g., to prevent replay attacks. As a side effect, the recovery from errors such as writing the same data twice is more complicated. Attempts to recover from a failed write must go back several steps so that the new counter value can be properly included in the encryption of the data.

© Maxim Integrated Products, Inc. (2008). Software Methods to Achieve Robust 1 Wire® Communication in iButton® Applications. AN159. https://www.maximintegrated.com/en/design/technical-documents/app-notes/1/159.html