1-Wire
1-Wire is a low-cost serial protocol designed by Dallas Semiconductor (now Maxim Integrated). It's similar to I²C — but with lower data rates, much longer cable runs, and the ability to power remote sensors over the same two wires used for data and ground. Common uses include the DS18B20 temperature sensor and small EEPROMs/iButton tags.
NuGet packages: GHIElectronics.TinyCLR.Devices.Onewire for the API, and GHIElectronics.TinyCLR.Pins for pin name constants.
Reading DS18B20 temperature sensors
The example below targets the SC20100S Dev Board with one or more DS18B20 temperature sensors powered from the dev board's 3.3V rail and connected to pin PA1.
The DS18B20 protocol uses a few well-known commands:
0x55— Match ROM (address one specific device by serial number)0x44— Convert temperature (start a conversion)0xBE— Read scratchpad (returns the last conversion result)
using GHIElectronics.TinyCLR.Devices.Onewire;
using GHIElectronics.TinyCLR.Pins;
using System.Diagnostics;
var oneWireBus = new OneWireController(SC20100.GpioPin.PA1);
var oneWireDevices = oneWireBus.FindAllDevices();
Debug.WriteLine("Number of sensors found = " + oneWireDevices.Count.ToString());
foreach (byte[] serialNumber in oneWireDevices) {
// Trigger a temperature conversion on this specific device.
oneWireBus.TouchReset();
oneWireBus.WriteByte(0x55); // Match ROM
for (int i = 0; i < serialNumber.Length; i++)
oneWireBus.WriteByte(serialNumber[i]);
oneWireBus.WriteByte(0x44); // Convert T
while (oneWireBus.ReadByte() == 0) { } // Wait for conversion.
// Read the scratchpad from this specific device.
oneWireBus.TouchReset();
oneWireBus.WriteByte(0x55); // Match ROM
for (int i = 0; i < serialNumber.Length; i++)
oneWireBus.WriteByte(serialNumber[i]);
oneWireBus.WriteByte(0xBE); // Read scratchpad
var temperature = (float)(oneWireBus.ReadByte() + (oneWireBus.ReadByte() << 8)) / 16.0;
Debug.WriteLine("Temperature: " + temperature.ToString());
Debug.WriteLine("Remaining 7 bytes of scratchpad:");
for (int i = 0; i < 7; i++) {
Debug.WriteLine(oneWireBus.ReadByte().ToString());
}
Debug.WriteLine("--------");
}
Sample output with three sensors on the bus:
Number of sensors found = 3
Temperature: 21.125
Remaining 7 bytes of scratchpad:
75
70
127
255
14
16
255
--------
Temperature: 21
Remaining 7 bytes of scratchpad:
75
70
127
255
16
16
73
--------
Temperature: 21.1875
Remaining 7 bytes of scratchpad:
75
70
127
255
13
16
233
--------
API reference
| Namespace | Description |
|---|---|
| GHIElectronics.TinyCLR.Devices.Onewire | 1-Wire bus controller and device classes |