Exemplo n.º 1
0
        static void ReadScratchPad(ref DS18B20 sensor)
        {
            //********************* Read Scratchpad ********************************
            Console.WriteLine("Reset Bus");
            if (!sensor.Reset())
            {
                Console.WriteLine("Nix Sensor\r\n");
                return;
            }

            //Select Sensor
            Console.WriteLine("Read Scratchpad für Sensor:\t{0}", sensor.GetSensorAddress());

            //Transfer Command und Sensor Adresse 8 Bytes
            sensor.Transfer(DS18B20.Command.MatchRom, DS18B20.TranferCounts.MatchRom);
            ScratchPad = sensor.Transfer(DS18B20.Command.ReadScratchpad, DS18B20.TranferCounts.ReadScratchpad);

            Console.Write("Scratchpad:\t\t\t");
            //PrintBytes(ScratchPad.Serialize());
            Console.WriteLine(ScratchPad);


            Console.Write("Check CRC\t\t\t{0:x2} ", DS18B20.CRC8(ScratchPad));
            Console.WriteLine("{0}", ScratchPad.CheckCRC() ? "OK" : "Fehler");

            Console.WriteLine("Configregister:\t\t\t{0:x2}", (byte)ScratchPad.ConfigRegister);


            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Temp: {0:F4}°C\r\n", ScratchPad.GetTemp());
            Console.ResetColor();
        }
Exemplo n.º 2
0
        /// <summary>
        ///     Main program sets things up and then goes to sleep.
        /// </summary>
        public static void Main()
        {
            DS18B20 ds18B20 = new DS18B20(Pins.GPIO_PIN_D3, updateInterval: 1000, temperatureChangeNotificationThreshold: 0.5F);

            ds18B20.TemperatureChanged += ds18b20_TemperatureChanged;
            Thread.Sleep(Timeout.Infinite);
        }
Exemplo n.º 3
0
        public void GetDeviceName()
        {
            var device   = new DS18B20("deviceID");
            var deviceID = device.deviceID;

            Assert.AreEqual("deviceID", deviceID);
        }
        protected override void DoStartAsync(object stoppingToken)
        {
            uart = new UART_Adapter(UARTSettings.COMPort);
            uart.Open();
            Logger.LogInformation($"UART is now listennig port {UARTSettings.COMPort}");
            OneWireSensor sensor = new DS18B20(uart);
            List <byte[]> ROMs   = sensor.GetConnectedROMs();

            Logger.LogInformation($"{ROMs.Count} connected sensor(s)");

            foreach (byte[] item in ROMs)
            {
                OneWireSensor physSensor = Utils.CreateSensor(item[0], uart, item);
                using (var scope = ScopeFactory.CreateScope())
                {
                    IUnitOfWork <Sensor> sensorsUnitOfWork = scope.ServiceProvider.GetRequiredService <IUnitOfWork <Sensor> >();
                    var dbSensor = sensorsUnitOfWork.GetRepository().Query().FirstOrDefault(sn => sn.ROM == physSensor.ROM);
                    if (dbSensor == null)
                    {
                        Sensors.Add(new UARTSensorDTO(physSensor)
                        {
                            SensorID = (Sensors.Count + 1) * -1, Name = "Not in DB", ROM = physSensor.ROM, DeviceName = physSensor.DeviceName(physSensor.FamilyCode)
                        });
                    }
                    else
                    {
                        Sensors.Add(new UARTSensorDTO(physSensor)
                        {
                            SensorID = dbSensor.snID, Name = dbSensor.Name, ROM = physSensor.ROM, DeviceName = physSensor.DeviceName(physSensor.FamilyCode)
                        });
                    }
                    Logger.LogInformation($"Added to list sensor with ROM: {physSensor.ROM}, Family Code = {physSensor.FamilyCode}");
                }
            }
        }
Exemplo n.º 5
0
        /// <summary>
        ///     Read the configuration and ID from the DS18B20 and display the information
        ///     retrieved in the Debug Output window.
        ///
        ///     Note that this sample will only work if there is only one device on the
        ///     one wire bus.
        ///
        ///     Connect the DS18B20 temperature sensor to GPIO D3.
        /// </summary>
        public static void Main()
        {
            DS18B20 ds18b20 = new DS18B20(Pins.GPIO_PIN_D3, updateInterval: 0);

            ds18b20.ReadDeviceID();
            Debug.Print("Device ID: 0x" + ds18b20.DeviceID.ToString("X16"));
            Debug.Print("Resolution: " + ds18b20.Resolution + " bits");
            Thread.Sleep(Timeout.Infinite);
        }
        static void ReadTemperature()
        {
            while (true)
            {
                int temperature = DS18B20.GetTemperature("28-031662b19cff");

                Console.WriteLine(string.Format("Temperature: {0}", temperature.ToString()));
                Thread.Sleep(1000);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        ///     Main program sets things up and then goes to sleep.
        /// </summary>
        public static void Main()
        {
            DS18B20 sensor1 = new DS18B20(Pins.GPIO_PIN_D3, 0x75000006DE7FE728, 1000);

            sensor1.TemperatureChanged += Sensor1_TemperatureChanged;
            DS18B20 sensor2 = new DS18B20(Pins.GPIO_PIN_D3, 0x64000006DCA35528, 1000, 0.5F);

            sensor2.TemperatureChanged += Sensor2_TemperatureChanged;
            Thread.Sleep(Timeout.Infinite);
        }
Exemplo n.º 8
0
        /// <summary>
        ///     This application demonstrates how to create a new DS18B20 object and read
        ///     the temperature from the sensor.  The current temperature will be displayed
        ///     in the Debug Output window every 500-1250ms.
        ///
        ///     Note that the rate of display is dependent upon the time it take to perform
        ///     the conversion of the temperature into a digital value.
        ///
        ///     Connect the DS18B20 data pin to GPIO D3 and then apply power and ground to
        ///     the sensor.
        /// </summary>
        public static void Main()
        {
            DS18B20 ds18b20 = new DS18B20(Pins.GPIO_PIN_D3, updateInterval: 0);

            while (true)
            {
                ds18b20.Update();
                Debug.Print("Current temperature: " + ds18b20.Temperature);
                Thread.Sleep(500);
            }
        }
Exemplo n.º 9
0
        public void MeasureDeviceThrowErrorWhenCRCIncorrect()
        {
            var deviceID = "28-000006cc02c9";
            var mock     = new Mock <IFileWrapper>();

            mock.Setup(fileWrapper => fileWrapper.Read($"./sys/bus/w1/devices/{deviceID}/w1_slave"))
            .Returns("56 01 4b 46 7f ff 0a 10 d1 : crc=d2 NO\n56 01 4b 46 7f ff 0a 10 d1 t=01200\n");
            var device = new DS18B20(deviceID, mock.Object);

            Assert.Throws <System.Exception>(() => device.GetValue());
        }
Exemplo n.º 10
0
        public void MeasureDeviceShouldReturnCorrectValue()
        {
            var deviceID = "28-000006cc02c9";
            var mock     = new Mock <IFileWrapper>();

            mock.Setup(fileWrapper => fileWrapper.Read($"./sys/bus/w1/devices/{deviceID}/w1_slave"))
            .Returns("56 01 4b 46 7f ff 0a 10 d1 : crc=d1 YES\n56 01 4b 46 7f ff 0a 10 d1 t=21375\n");
            var device       = new DS18B20(deviceID, mock.Object);
            var measureValue = device.GetValue();

            Assert.AreEqual(21.375f, measureValue);
            Assert.AreEqual(21.375f, device.lastValue);
        }
Exemplo n.º 11
0
        public void TemperatureConversions()
        {
            var ds18b20 = new DS18B20();

            Assert.Equal(125, ds18b20.GetTemp_Read(0x07, 0xD0));
            Assert.Equal(85, ds18b20.GetTemp_Read(0x05, 0x50));
            Assert.Equal(25.0625, ds18b20.GetTemp_Read(0x01, 0x91));
            Assert.Equal(10.125, ds18b20.GetTemp_Read(0x00, 0xA2));
            Assert.Equal(0.5, ds18b20.GetTemp_Read(0x00, 0x08));
            Assert.Equal(0, ds18b20.GetTemp_Read(0x00, 0x00));
            Assert.Equal(-0.5, ds18b20.GetTemp_Read(0xFF, 0xF8));
            Assert.Equal(-10.125, ds18b20.GetTemp_Read(0xFF, 0x5E));
            Assert.Equal(-25.0625, ds18b20.GetTemp_Read(0xFE, 0x6F));
            Assert.Equal(-55, ds18b20.GetTemp_Read(0xFC, 0x90));
        }
Exemplo n.º 12
0
        public void TemperatureConversions()
        {
            var ds18b20 = new DS18B20();

            Assert.Equal(125, ds18b20.GetTemp_Read(0x07, 0xD0));
            Assert.Equal(85, ds18b20.GetTemp_Read(0x05, 0x50));
            Assert.Equal(25.0625, ds18b20.GetTemp_Read(0x01, 0x91));
            Assert.Equal(10.125, ds18b20.GetTemp_Read(0x00, 0xA2));
            Assert.Equal(0.5, ds18b20.GetTemp_Read(0x00, 0x08));
            Assert.Equal(0, ds18b20.GetTemp_Read(0x00, 0x00));
            Assert.Equal(-0.5, ds18b20.GetTemp_Read(0xFF, 0xF8));
            Assert.Equal(-10.125, ds18b20.GetTemp_Read(0xFF, 0x5E));
            Assert.Equal(-25.0625, ds18b20.GetTemp_Read(0xFE, 0x6F));
            Assert.Equal(-55, ds18b20.GetTemp_Read(0xFC, 0x90));
        }
Exemplo n.º 13
0
        public static void Main()
        {
            _ds18B20 = new DS18B20(Hardware.SC20100_2.AnPin);

            // Run this first if you want to obtain a list of current DS18B20 Sensors on the OneWire Bus.
            // To get your 64-Bit DeviceIds Uncomment the line DisplayDeviceIds()

            // I am using three sensors for this Demo1, you will need to change the values of Device0, Device1 and Device2 to reflect your
            // sensor id for the Demo1 Code to work. Or just Comment out "RunDemo1(); and Uncomment RunDemo2();

            //DisplayDeviceIds();

            //RunDemo1();

            RunDemo2();

            new Thread(Capture).Start();

            Thread.Sleep(Timeout.Infinite);
        }
Exemplo n.º 14
0
        public static void Main()
        {
            try
            {
                _ds18B20 = new DS18B20(Hardware.SocketTwo);
            }

            catch (PinInUseException ex) // Some pins are already used by another driver
            {
                Debug.Print("Some pins are in use while creating instances : " + ex.Message);
                Debug.Print("Stack trace : " + ex.StackTrace);
            }
            catch (DeviceInitialisationException ex) // Device initialization failed. Maybe a retry could be enough
            {
                Debug.Print("Exception during device initialization : " + ex.Message);
                _ds18B20 = new DS18B20(Hardware.SocketThree);
            }
            catch (Exception ex) // Other exception from NETMF core
            {
                Debug.Print("Exception while creating instances : " + ex.Message);
            }

            // Run this first if you want to obtain a list of current DS18B20 Sensors on the OneWire Bus.
            // To get your 64-Bit DeviceIds Uncomment the line DisplayDeviceIds()

            // I am using three sensors for this Demo1, you will need to change the values of Device0, Device1 and Device2 to reflect your
            // sensor id for the Demo1 Code to work. Or just Comment out "RunDemo1(); and Un-Comment RunDemo2();

            //DisplayDeviceIds();

            //RunDemo1();

            RunDemo2();

            new Thread(Capture).Start();

            Thread.Sleep(Timeout.Infinite);
        }
Exemplo n.º 15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="SkipRom">true SkipROM oder nicht</param>
        static void StartConvertion(bool SkipRom, ref DS18B20 sensor)
        {
            //********************* Start Convertion ********************************

            Console.WriteLine("Reset Bus");
            if (!sensor.Reset())
            {
                Console.WriteLine("Nix Sensor\r\n");
                return;
            }


            if (SkipRom)
            {
                Console.WriteLine("Skip ROM, alle Sensoren messen zusammen ");
                sensor.Transfer(DS18B20.Command.SkipRom);
            }
            else
            {
                //Select Sensor
                Console.Write("Match ROM jeder Sensor misst Separat. Select Sensor ");


                Console.WriteLine(sensor.GetSensorAddress());

                //Transfer Command und Sensor Adresse 8 Bytes
                sensor.Transfer(DS18B20.Command.MatchRom, DS18B20.TranferCounts.MatchRom);
            }

            //Start Temp Convertion nur Command
            Console.WriteLine("Start Convertion\r\n");
            sensor.Transfer(DS18B20.Command.ConvertT);

            //Datenblatt max Convertion Time
            System.Threading.Thread.Sleep(800);
        }
Exemplo n.º 16
0
        public static void Main()
        {
            Console.WriteLine("");
            Console.WriteLine("** nanoFramework OneWire ESP32 DEV KITV1 Sample! **");

            OneWireController oneWire = new OneWireController();

            DS18B20 ds18b20 = new DS18B20(oneWire, /* The 1-wire bus*/
                                          null,    /*Let this driver find out a DS18B20 on the bus*/
                                          true,    /* Multidrop, network*/
                                          3        /* 3 decimal places is enough for us while reading temperature changes*/
                                          );

            string devAddrStr = "";//store the device address as string...

            ds18b20.SetSearchMode = DS18B20.NORMAL;
            if (ds18b20.Initialize())    //Initialize sensors | search for 18B20 devices
            {
                Console.WriteLine("");
                Console.WriteLine("Devices found = " + ds18b20.Found);
                Console.WriteLine("");

                for (int i = 0; i < ds18b20.Found; i++)
                {
                    ds18b20.Address = ds18b20.AddressNet[i];

                    foreach (var addrByte in ds18b20.AddressNet[i])
                    {
                        devAddrStr += addrByte.ToString("X2");
                    }
                    Console.WriteLine("18b20-" + i.ToString("X2") + " " + devAddrStr);
                    devAddrStr = "";
                    CheckPowerMode();
                    setAlarmSetPoints(); // Set same setpoint for selected device
                }
                Console.WriteLine("");
                loopReadAll();
                alarmSearch();
            }
            else
            {
                notFound();
            }

            void loopReadAll()
            {
                int loopRead = 10;

                while (loopRead > 0)
                {
                    Console.WriteLine("LoopRead " + loopRead);
                    ds18b20.PrepareToRead(); // Update temp. value in all devices

                    for (int index = 0; index < ds18b20.Found; index++)
                    {
                        //Select the device
                        ds18b20.Address = ds18b20.AddressNet[index];
                        devAddrStr      = "";
                        foreach (var addrByte in ds18b20.AddressNet[index])
                        {
                            devAddrStr += addrByte.ToString("X2");
                        }

                        //Read Temperature on selected device
                        ds18b20.Read();
                        Console.WriteLine("DS18B20[" + devAddrStr + "] Sensor reading in One-Shot-mode; T = " + ds18b20.TemperatureInCelcius.ToString("f2") + " C"); //"f2" two decimal point format.
                    }

                    Console.WriteLine("");
                    loopRead--;
                }
            }

            // Set alarm setpoint for selected device
            void setAlarmSetPoints()
            {
                //ds18b20.ConfigurationRead(false);
                //Console.WriteLine("Alarm Setpoints before:");
                //Console.WriteLine("Hi alarm = " + ds18b20.TempHiAlarm + " C");
                //Console.WriteLine("Lo alarm = " + ds18b20.TempLoAlarm + " C");
                //Console.WriteLine("");

                ds18b20.TempHiAlarm = 30;
                ds18b20.TempLoAlarm = 25;
                ds18b20.ConfigurationWrite(false); //Write configuration on ScratchPad,
                                                   //If true, save it on EEPROM too.
                ds18b20.ConfigurationRead(true);
                Console.WriteLine("Alarm Setpoints-RecallE2:");
                Console.WriteLine("Hi alarm = " + ds18b20.TempHiAlarm + " C");
                Console.WriteLine("Lo alarm = " + ds18b20.TempLoAlarm + " C");
                Console.WriteLine("");
            }

            void alarmSearch()
            {
                int loopRead = 40;

                ds18b20.SetSearchMode = DS18B20.SEARCH_ALARM;

                while (loopRead > 0)
                {
                    Console.WriteLine("LoopRead " + loopRead);

                    if (ds18b20.SearchForAlarmCondition())
                    {
                        for (int index = 0; index < ds18b20.Found; index++)
                        {
                            //Select the device
                            ds18b20.Address = ds18b20.AddressNet[index];
                            //Read Temperature on selected device
                            ds18b20.Read();

                            devAddrStr = "";
                            foreach (var addrByte in ds18b20.AddressNet[index])
                            {
                                devAddrStr += addrByte.ToString("X2");
                            }
                            Console.WriteLine("DS18B20[" + devAddrStr + "] Sensor reading in One-Shot-mode; T = " + ds18b20.TemperatureInCelcius.ToString("f2") + " C");

                            ds18b20.ConfigurationRead(false); //Read alarm setpoint.
                            Console.WriteLine("Alarm Setpoints:");
                            Console.WriteLine("Hi alarm = " + ds18b20.TempHiAlarm + " C");
                            Console.WriteLine("Lo alarm = " + ds18b20.TempLoAlarm + " C");
                            Console.WriteLine("");
                        }
                    }
                    else
                    {
                        Console.WriteLine("***** No devices in alarm ****");
                    }

                    loopRead--;
                }
                Console.WriteLine("");
            }

            void notFound()
            {
                Console.WriteLine("*****************");
                Console.WriteLine("No devices found.");
                Console.WriteLine("*****************");
            };

            void CheckPowerMode()
            {
                if (ds18b20.IsParasitePowered())
                {
                    Console.WriteLine("Parasite powered");
                }
                else
                {
                    Console.WriteLine("External powered");
                }
            }

            #region Other Examples
            //OneWireController oneWire = new OneWireController();

            //DS18B20 ds18b20 = new DS18B20(oneWire,/* The 1-wire bus*/
            //                        null, /*Let this driver find out a DS18B20 on the bus*/
            //                        false, /* single drop, no network*/
            //                        3 /*3 decimal places is enough for us while reading temperature changes*/
            //                        );

            ///*
            // * NOTE: Limiting to the decimal places will not work when you do a "ToString" on floats.
            // * The limit to decimal places is only for comparison. For exmaple, if last measured temperature value
            // * was 25.3343567 and the next value is 25.3343667, then the difference between the two is about 0.00001.
            // * If we limit to 3 decimal places, then the values are read as 25.334 and 25.334, resulting in a difference
            // * of zero. This is used to compute if sensors changed or not...more the number of decimal places, higher
            // * is the change event possibility (because even a very small change will be registered)
            // */

            //int loopCount = 3; //used later to limit test duration
            //string devAddrStr = "";//store the device address as string...

            ///*********************************************************************************************************
            // * This driver supports, one-shot , poll mode (meaning,you check the sensor for changes
            // * in temperature values) and event mode (meaning, the driver will alert you when
            // * temperature changes)
            // *********************************************************************************************************/
            ////One-Shot-mode example...
            //ds18b20.Initialize(); //Initialize sensor
            ///*After device gets initialized and if initialization is successful, the class DS18B20 should have an address*/
            //if (ds18b20.Address != null && ds18b20.Address.Length == 8 && ds18b20.Address[0] == DS18B20.FAMILY_CODE)
            //{
            //    //Initialization successful...let's try to read the address
            //    /*
            //     * Since this class was initialized without an address, the Initialize() method will search for valid
            //     * devices on the bus, and select the first device of type DS18B20 on the bus. If you have multiple devices,
            //     * You can use the OneWireController class's "Find" methods to first search for devices, and then initialize
            //     * the class with an address.
            //     */
            //    foreach (var addrByte in ds18b20.Address) devAddrStr += addrByte.ToString("X2");

            //    ds18b20.PrepareToRead();
            //    ds18b20.ConfigurationRead();
            //    Console.WriteLine("Resolution = " + ds18b20.Resolution);
            //    Console.WriteLine("Temperute Hi alarm =" + ds18b20.TempHiAlarm + " C");
            //    Console.WriteLine("Temperute Lo alarm =" + ds18b20.TempLoAlarm + " C");

            //    ds18b20.Resolution = -4;
            //    ds18b20.TempHiAlarm = -10;
            //    ds18b20.TempLoAlarm = 10;
            //    ds18b20.ConfigurationWrite();
            //    ds18b20.PrepareToRead();
            //    ds18b20.ConfigurationRead();
            //    Console.WriteLine("New Resolution = " + ds18b20.Resolution);
            //    Console.WriteLine("New Temperute Hi alarm = " + ds18b20.TempHiAlarm + " C");
            //    Console.WriteLine("New Temperute Lo alarm = " + ds18b20.TempLoAlarm + " C");

            //    int loopRead = 20;

            //    while (loopRead > 0)
            //    {
            //        ds18b20.PrepareToRead();
            //        ds18b20.Read();
            //        Console.WriteLine("DS18B20[" + devAddrStr + "] Sensor reading in One-Shot-mode; T=" + ds18b20.TemperatureInCelcius.ToString() + " C"); //"f2" two decimal point format.
            //        Thread.Sleep(4000);
            //        loopRead--;
            //    }
            //}

            ///*Polled example*/
            //loopCount = 3;
            //ds18b20.Reset();
            //ds18b20.Initialize();//after this device should have valid address...see above on how to check

            //while (loopCount > 0)
            //{
            //    if (ds18b20.HasSensorValueChanged())
            //    {
            //        //no need to read again (like HTU21D)
            //        Console.WriteLine("DS18B20[" + devAddrStr + "] in Poll-mode;T=" + ds18b20.TemperatureInCelcius.ToString());
            //    }
            //    loopCount--;
            //}

            ///*Event mode...*/
            //loopCount = 3;
            //ds18b20.Reset();
            //ds18b20.Initialize(); //again, if initialization is successful, object will have valid address (see above)
            //if (ds18b20.CanTrackChanges())
            //{
            //    ds18b20.SensorValueChanged += () =>
            //    {
            //        //no need to read again (like HTU21D)
            //        Console.WriteLine("DS18B20 (" + devAddrStr + ") in Event-mode;T=" + ds18b20.TemperatureInCelcius.ToString());
            //    };
            //    ds18b20.BeginTrackChanges(2000/*track changes every 2 seconds*/);
            //    while (loopCount > 0)
            //    {
            //        Thread.Sleep(3000);//Wait for a change...
            //        loopCount--;
            //    }
            //    ds18b20.EndTrackChanges();
            //}
            //ds18b20.Dispose();
            #endregion
        }
Exemplo n.º 17
0
        static void Main(string[] args)
        {
            Console.Clear();
            // DS18B20 sensor = new DS18B20("COM27");
            DS18B20 sensor = new DS18B20("COM2");

            DS18B20_Address        SensorAddress   = new DS18B20_Address();
            List <DS18B20_Address> SensorAddresses = new List <DS18B20_Address>(8);

            //********************* Ist wer da ? ********************************
            if (!sensor.Reset())
            {
                Console.WriteLine("Nix Sensor\r\n");
                return;
            }

            Console.WriteLine("Sensor da :-)\r\n");



            while (!sensor.Search(ref SensorAddress))
            {
                Console.Write("Sensor ");

                //PrintBytes(Address);
                Console.WriteLine("Adresse:\t{0}", SensorAddress.Address);
                Console.WriteLine("CRC:\t\t{0}", SensorAddress.CRC.ToString("x2"));
                Console.Write("CRC Check\t{0:x2} ", DS18B20.CRC8(SensorAddress));

                Console.WriteLine("{0}", SensorAddress.CheckCRC() ? "OK":"Fehler");
                Console.WriteLine("Seriennummer:\t{0}", SensorAddress.ToString("SN"));
                Console.WriteLine("Device Typ:\t{0}\r\n", SensorAddress.ToString("DEV"));


                SensorAddresses.Add(SensorAddress);



                sensor.Reset();
            }

            Console.WriteLine("{0} Sensor(en) gefunden", sensor.Devices);
            Console.WriteLine("Weiter Taste drücken");
            Console.ReadKey();



            //********************* Nur ein Sensor am Bus. Wer da ist da ? ********************************

            /*
             *          bytes = ow.Transfer(0x33, 8, OnWire.TransferDirection.Read);
             *
             *
             *          Console.Write("Memory:");
             *          for (byte ix = 1; ix < bytes.Length - 1; ix++) Console.Write("{0:x2}:", bytes[ix]);
             *          Console.WriteLine("{0:x2}\r\n", bytes[bytes.Length - 1]);
             *
             */


            //Beispiel
            //Ersten Sensor auf 12 Bit umstellen
            //MatchRom = Gezielt Sensor auswählen, Skiprom = alle Sensoren

            //Aktuelles Scratchpad auslesen

            //Sensor Adresse in Buffer laden
            sensor.SetSensorAddress(SensorAddresses[0]);
            sensor.Transfer(DS18B20.Command.MatchRom, DS18B20.TranferCounts.MatchRom);
            ScratchPad = sensor.Transfer(DS18B20.Command.ReadScratchpad, DS18B20.TranferCounts.ReadScratchpad);

            DS18B20_SctatchPad.Resolution r = DS18B20_SctatchPad.Resolution.Bits12;


            if (ScratchPad.ConfigRegister != r)
            {
                Console.WriteLine("Configregister auf gewünschte Auflösung umstellen");
                sensor.Reset();

                //Config Register auf 12Bit Setzen
                ScratchPad.ConfigRegister = r;

                //Sensor Adresse in Buffer laden

                sensor.SetSensorAddress(SensorAddresses[0]);
                sensor.Transfer(DS18B20.Command.MatchRom, DS18B20.TranferCounts.MatchRom);

                //Die 3 Bytes aus dem Scratchpad retour schreiben
                sensor.Scratchpad2Buffer(ScratchPad.SerializeForWrite());
                sensor.Transfer(DS18B20.Command.WriteScratchpad, DS18B20.TranferCounts.WriteScratchpad);
            }
            else
            {
                Console.WriteLine("Configregister hat bereits die gewünschte Auflösung");
            }

            System.Threading.Thread.Sleep(2000);

            while (true)
            {
                Console.Clear();

#if !MATCH_ROM
                //Skip Rom
                StartConvertion(true, ref sensor);
#endif

                for (byte iy = 0; iy < SensorAddresses.Count; iy++)
                {
                    //Sensor Adresse in Buffer laden
                    sensor.SetSensorAddress(SensorAddresses[iy]);

#if MATCH_ROM
                    //Ohne SkipRom, Match ROM
                    StartConvertion(false, ref sensor);
#endif

                    ReadScratchPad(ref sensor);
                }
                //Console.WriteLine("Nächste Messung Taste drücken");
                //Console.ReadKey();
                System.Threading.Thread.Sleep(5000);
            }
        }
Exemplo n.º 18
0
 public SensorTemp(Cpu.Pin pin, int SampleRateMilliseconds, string name)
     : base(SensorType.Temperature, ValuesPerSample.One, SampleRateMilliseconds, name)
 {
     ds = new DS18B20(pin);
     StartMeasuring();
 }
 /// <summary>
 /// Create and start a temperature senor.  Note temperature is cached for 10 minutes
 /// as temperature chip tends to heat up if read too often
 /// </summary>
 /// <param name="pin">From the SecretLabs.NETMF.Hardware.NetduinoPlus.Pins namespace</param>
 /// <param name="SampleRateMilliseconds">How often to measure in milliseconds or -1 to disable auto timed sensor readings</param>
 /// <param name="name">Unique identifying name for command and control</param>
 public SensorTempCached(Cpu.Pin pin, int SampleRateMilliseconds, string name)
     : base("temp", "c", ValuesPerSample.One, SampleRateMilliseconds, name)
 {
     ds = new DS18B20(pin);
     StartMeasuring();
 }
Exemplo n.º 20
0
        /// <summary>
        /// The run method
        /// </summary>
        public void RunSample()
        {
            OneWireController oneWire = new OneWireController();
            DS18B20           ds18b20 = new DS18B20(oneWire, /* The 1-wire bus*/
                                                    null,    /*Let this driver find out a DS18B20 on the bus*/
                                                    3 /*3 decimal places is enough for us while reading temperature changes*/);

            /*
             * NOTE: Limiting to the decimal places will not work when you do a "ToString" on floats.
             * The limit to decimal places is only for comparison. For exmaple, if last measured temperature value
             * was 25.3343567 and the next value is 25.3343667, then the difference between the two is about 0.00001.
             * If we limit to 3 decimla places, then the values are read as 25.334 and 25.334, resulting in a difference
             * of zero. This is used to compute if sensors changed or not...more the number of decimal places, higher
             * is the change event possibility (because even a very small change will be registered)
             */

            int    loopCount  = 3;  //used later to limit test duration
            string devAddrStr = ""; //store the device address as string...

            /*********************************************************************************************************
            * This driver supports, one-shot , poll mode (meaning,you check the sensor for changes
            * in temperature values) and event mode (meaning, the driver will alert you when
            * temperature changes)
            *********************************************************************************************************/
            //One-Shot-mode example...
            ds18b20.Initialize(); //Initialize sensor
            /*After device gets initialized and if initialization is successful, the class DS18B20 should have an address*/
            if (ds18b20.Address != null && ds18b20.Address.Length == 8 && ds18b20.Address[0] == DS18B20.FAMILY_CODE)
            {
                //Initialization successful...let's try to read the address

                /*
                 * Since this class was initialized without an address, the Initialize() method will search for valid
                 * devices on the bus, and select the first device of type DS18B20 on the bus. If you have multiple devices,
                 * You can use the OneWireController class's "Find" methods to first search for devices, and then initialize
                 * the class with an address.
                 */
                foreach (var addrByte in ds18b20.Address)
                {
                    devAddrStr += addrByte.ToString("X2");
                }

                ds18b20.PrepareToRead();
                ds18b20.Read();
                Console.WriteLine("DS18B20[" + devAddrStr + "] Sensor reading in One-Shot-mode; T=" + ds18b20.TemperatureInCelcius.ToString() + " C");
            }

            /*Polled example*/
            loopCount = 3;
            ds18b20.Reset();
            ds18b20.Initialize();//after this device should have valid address...see above on how to check

            while (loopCount > 0)
            {
                if (ds18b20.HasSensorValueChanged())
                {
                    //no need to read again (like HTU21D)
                    Console.WriteLine("DS18B20[" + devAddrStr + "] in Poll-mode;T=" + ds18b20.TemperatureInCelcius.ToString());
                }
                loopCount--;
            }

            /*Event mode...*/
            loopCount = 3;
            ds18b20.Reset();
            ds18b20.Initialize(); //again, if initialization is successful, object will have valid address (see above)
            if (ds18b20.CanTrackChanges())
            {
                ds18b20.SensorValueChanged += () => {
                    //no need to read again (like HTU21D)
                    Console.WriteLine("DS18B20 (" + devAddrStr + ") in Event-mode;T=" + ds18b20.TemperatureInCelcius.ToString());
                };
                ds18b20.BeginTrackChanges(2000 /*track changes every 2 seconds*/);
                while (loopCount > 0)
                {
                    Thread.Sleep(3000);//Wait for a change...
                    loopCount--;
                }
                ds18b20.EndTrackChanges();
            }
            ds18b20.Dispose();
        }