With the code below i'll read the temperature from 2 sensors. After starting up the program will display the addresses from all connected sensors. The addresses are needed to read the sensors one by one (add sensor address in beginning of the code). After that the program will display the temperature every 10 seconds.
using System;using System.Net;using System.Net.Sockets;using System.Threading;using Microsoft.SPOT;using Microsoft.SPOT.Hardware;using SecretLabs.NETMF.Hardware;using SecretLabs.NETMF.Hardware.Netduino;namespace ReadOneWire{ public class Program { static OutputPort port = new OutputPort(Pins.GPIO_PIN_D0, false); static OneWire oneWire = new OneWire(port); static string DS18s20 = ""; static byte[] owSensor1 = new byte[8] { 40, 32, 55, 148, 4, 0, 0, 12 }; //sensor 1 inside building static byte[] owSensor2 = new byte[8] { 40, 188, 93, 148, 4, 0, 0, 108 }; //sensor 2 outside building static float owSensor1Temp = -99; static float owSensor2Temp = -99; static DateTime tempReadingTimestamp = DateTime.Now; const int SKIP_ROM = 0xCC; const int READ_SCRATCHPAD = 0xBE; const int CONVERT_T = 0x44; const int MATCH_ROM = 0x55; public static void Main() { Array listOneWire = oneWire.FindAllDevices().ToArray(); foreach(byte[] owAddress in listOneWire) { DS18s20 =""; foreach (byte b in owAddress) { DS18s20 = DS18s20 + b + " "; } Debug.Print("The serial number is: "+ DS18s20); } //thread to read temps every 10 seconds Thread readTempsThread = new Thread(ReadTemps_Delegate); readTempsThread.Start(); //loop while (true) { //stay alive } } private static void ReadTemps_Delegate() { Timer readTempsTimer = new Timer(new TimerCallback(ReadTemps_Tick), null, 0, 10000); } private static void ReadTemps_Tick(Object obj) { tempReadingTimestamp = DateTime.Now; owSensor1Temp = GetOneWireTempByByteArray(owSensor1) / 16; //convert temp to C owSensor2Temp = GetOneWireTempByByteArray(owSensor2) / 16; //convert temp to C string debugString = tempReadingTimestamp.ToString(); debugString += " Temp Inside: " + owSensor1Temp.ToString("N1"); debugString += " Temp Outside: " + owSensor2Temp.ToString("N1"); Debug.Print(debugString); } static float GetOneWireTempByByteArray(byte[] sensor) { ushort temperature; oneWire.TouchReset(); //reset oneWire.TouchByte(MATCH_ROM); //match rom foreach (byte b in sensor) //send the whole byte array { oneWire.TouchByte(b); } oneWire.TouchByte(CONVERT_T); //start temp conversion while (oneWire.ReadByte() == 0) ; //wait while busy oneWire.TouchReset(); //reset oneWire.TouchByte(MATCH_ROM); //match rom foreach (byte b in sensor) //send the whole byte array { oneWire.TouchByte(b); } oneWire.TouchByte(READ_SCRATCHPAD); //read scratchpad temperature = (byte) oneWire.ReadByte(); //LSB temperature |= (ushort)(oneWire.ReadByte() << 8); //MSB return (float) (temperature); } } }