/// <summary> /// Gets a reading from the sensor. /// </summary> /// <returns>Returns an IDhtReading instance containing /// the data from the sensor.</returns> public async Task <IDhtReading> GetReadingAsync() { IDhtReading returnValue = new DhtReading(); if (this.ChangeReader != null) { try { // *** // *** Clear and start the Change Reader. // *** this.ChangeReader.Clear(); this.ChangeReader.Start(); // *** // *** Bring the line low for 18 ms (this is needed for the DHT11), the DHT22 does need // *** need as long. // *** this.TriggerPin.Write(GpioPinValue.High); await Task.Delay(TimeSpan.FromMilliseconds(18)); this.TriggerPin.Write(GpioPinValue.Low); // *** // *** Wait for 43 falling edges, but do not wait for more than the timeout. // *** CancellationTokenSource source = new CancellationTokenSource((int)this.Timeout.TotalMilliseconds); await this.ChangeReader.WaitForItemsAsync(43).AsTask(source.Token); // *** // *** Get all of the change records. // *** IList <GpioChangeRecord> changeRecords = this.ChangeReader.GetAllItems(); // *** // *** Convert the change records to the 5 bytes of data that the sensor // *** sends out. // *** byte[] data = changeRecords.ToByteArray(); // *** // *** Convert the 5 bytes of data to an IDhtReading instance. // *** returnValue = DhtReading.FromData(data); } catch (TaskCanceledException) { // *** // *** The sensor did not respond to the // *** data request. // *** returnValue = DhtReading.FromTimeout(); } finally { this.ChangeReader.Stop(); } } else { throw new DhtNotInitializedException(); } return(returnValue); }
private IDhtReading GetReading() { Array.Clear(DataBuffer, 0, DataBuffer.Length); // *** // *** Bring the line low for 18 ms (this is needed for the DHT11), the DHT22 does need // *** need as long. // *** pin.Write(GpioPinValue.Low); SpinWaitPerformanceCounts(perf_counts_18ms); pin.Write(GpioPinValue.High); SpinWaitPerformanceCounts(perf_counts_40us); pin.SetDriveMode(GpioPinDriveMode.Input); SpinWaitPerformanceCounts(perf_counts_10us); // *** // *** Capture every falling edge until all bits are received or // *** timeout occurs // *** var endTickCount = GetTickCount64() + ReadTimeout; var previousValue = pin.Read(); var prevTime = 0L; for (var i = -1; i < DataBufferBits;) { if (GetTickCount64() > endTickCount) { return(DhtReading.FromTimeout()); } var value = pin.Read(); if ((previousValue == GpioPinValue.High) && (value == GpioPinValue.Low)) { // *** // *** A falling edge was detected // *** var now = PerformanceCounterValue; if (i >= 0) { var difference = unchecked (now - prevTime); if (difference > OneThreshold) { DataBuffer.SetBit(i); } } prevTime = now; ++i; } previousValue = value; } // *** // *** Convert the 5 bytes of data to an IDhtReading instance. // *** return(ParseData(DataBuffer)); }