■ DHT11 온도/습도 센서를 사용하는 방법을 보여준다.
▶ 부품 내역
1 2 3 4 5 6 7 |
─────────────────── 구분 모델 수량 비고 ───────── ─── ── ── SENSOR/TEMPERATURE DHT11 1 ─────────────────── |
[회로 구성도]
▶ MainPage.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 |
<Page x:Class="TestProject.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" RequestedTheme="Dark"> <Page.Resources> <Thickness x:Key="DashboardBorderMarginKey">3 3 3 3</Thickness> <Thickness x:Key="DashboardBorderThicknessKey">2</Thickness> <SolidColorBrush x:Key="DashboardBorderBrushKey">#ff0063b1</SolidColorBrush> <x:Double x:Key="DashboardFontSizeKey">25</x:Double> <SolidColorBrush x:Key="DashboardHeaderTextBrushKey">#ff0063b1</SolidColorBrush> <SolidColorBrush x:Key="DashboardTextBrushKey">White</SolidColorBrush> <SolidColorBrush x:Key="DisplayHeaderTextBrushKey">Yellow</SolidColorBrush> <SolidColorBrush x:Key="DisplayTextBrushKey">White</SolidColorBrush> </Page.Resources> <Grid Background="Black"> <Grid.RowDefinitions> <RowDefinition Height="1*" /> <RowDefinition Height="3*" /> </Grid.RowDefinitions> <Grid Grid.Row="0"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Border Grid.Column="0" Grid.Row="0" Margin="{StaticResource DashboardBorderMarginKey}" BorderThickness="{StaticResource DashboardBorderThicknessKey}" BorderBrush="{StaticResource DashboardBorderBrushKey}"> <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="{StaticResource DashboardFontSizeKey}" Foreground="{StaticResource DashboardHeaderTextBrushKey}" TextWrapping="WrapWholeWords" Text="시도 건수" /> </Border> <Border Grid.Column="0" Grid.Row="1" Margin="{StaticResource DashboardBorderMarginKey}" BorderThickness="{StaticResource DashboardBorderThicknessKey}" BorderBrush="{StaticResource DashboardBorderBrushKey}"> <TextBlock x:Name="attemptCountTextBlock" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="{StaticResource DashboardFontSizeKey}" Foreground="{StaticResource DashboardTextBrushKey}" TextWrapping="WrapWholeWords" /> </Border> <Border Grid.Column="1" Grid.Row="0" Margin="{StaticResource DashboardBorderMarginKey}" BorderThickness="{StaticResource DashboardBorderThicknessKey}" BorderBrush="{StaticResource DashboardBorderBrushKey}"> <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="{StaticResource DashboardFontSizeKey}" Foreground="{StaticResource DashboardHeaderTextBrushKey}" TextWrapping="WrapWholeWords" Text="평균 재시도 건수" /> </Border> <Border Grid.Column="1" Grid.Row="1" Margin="{StaticResource DashboardBorderMarginKey}" BorderThickness="{StaticResource DashboardBorderThicknessKey}" BorderBrush="{StaticResource DashboardBorderBrushKey}" > <TextBlock x:Name="averageRetryCountTextBlock" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="{StaticResource DashboardFontSizeKey}" Foreground="{StaticResource DashboardTextBrushKey}" TextWrapping="WrapWholeWords" /> </Border> <Border Grid.Column="2" Grid.Row="0" Margin="{StaticResource DashboardBorderMarginKey}" BorderThickness="{StaticResource DashboardBorderThicknessKey}" BorderBrush="{StaticResource DashboardBorderBrushKey}"> <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="{StaticResource DashboardFontSizeKey}" Foreground="{StaticResource DashboardHeaderTextBrushKey}" TextWrapping="WrapWholeWords" Text="성공 건수" /> </Border> <Border Grid.Column="2" Grid.Row="1" Margin="{StaticResource DashboardBorderMarginKey}" BorderThickness="{StaticResource DashboardBorderThicknessKey}" BorderBrush="{StaticResource DashboardBorderBrushKey}"> <TextBlock x:Name="successCountTextBlock" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="{StaticResource DashboardFontSizeKey}" Foreground="{StaticResource DashboardTextBrushKey}" TextWrapping="WrapWholeWords" /> </Border> <Border Grid.Column="3" Grid.Row="0" Margin="{StaticResource DashboardBorderMarginKey}" BorderThickness="{StaticResource DashboardBorderThicknessKey}" BorderBrush="{StaticResource DashboardBorderBrushKey}"> <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="{StaticResource DashboardFontSizeKey}" Foreground="{StaticResource DashboardHeaderTextBrushKey}" TextWrapping="WrapWholeWords" Text="성공율" /> </Border> <Border Grid.Column="3" Grid.Row="1" Margin="{StaticResource DashboardBorderMarginKey}" BorderThickness="{StaticResource DashboardBorderThicknessKey}" BorderBrush="{StaticResource DashboardBorderBrushKey}"> <TextBlock x:Name="successRateTextBlock" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="{StaticResource DashboardFontSizeKey}" Foreground="{StaticResource DashboardTextBrushKey}" TextWrapping="WrapWholeWords" /> </Border> <Border Grid.Column="4" Grid.Row="0" Margin="{StaticResource DashboardBorderMarginKey}" BorderThickness="{StaticResource DashboardBorderThicknessKey}" BorderBrush="{StaticResource DashboardBorderBrushKey}"> <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="{StaticResource DashboardFontSizeKey}" Foreground="{StaticResource DashboardHeaderTextBrushKey}" TextWrapping="WrapWholeWords" Text="비율" /> </Border> <Border Grid.Column="4" Grid.Row="1" Margin="{StaticResource DashboardBorderMarginKey}" BorderThickness="{StaticResource DashboardBorderThicknessKey}" BorderBrush="{StaticResource DashboardBorderBrushKey}"> <TextBlock x:Name="rateTextBlock" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="{StaticResource DashboardFontSizeKey}" Foreground="{StaticResource DashboardTextBrushKey}" TextWrapping="WrapWholeWords" /> </Border> </Grid> <Grid Grid.Row="1"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="*" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <TextBlock Grid.Column="0" Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Bottom" FontSize="50" Foreground="{StaticResource DisplayHeaderTextBrushKey}" Text="습도" /> <TextBlock x:Name="humidityTextBlock" Grid.Column="0" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="10 10 10 10" FontSize="90" Foreground="{StaticResource DisplayTextBrushKey}" /> <TextBlock Grid.Column="1" Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Bottom" FontSize="50" Foreground="{StaticResource DisplayHeaderTextBrushKey}" Text="온도" /> <TextBlock x:Name="temperatureTextBlock" Grid.Column="1" Grid.Row="1" Margin="10 10 10 10" HorizontalAlignment="Center" VerticalAlignment="Top" FontSize="90" Foreground="{StaticResource DisplayTextBrushKey}" /> <TextBlock Grid.Column="0" Grid.Row="2" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0 0 20 0" FontSize="35" Foreground="{StaticResource DisplayHeaderTextBrushKey}" Text="최근 갱신 일시 :" /> <TextBlock x:Name="lastUpdatedOffsetTextBlock" Grid.Column="1" Grid.Row="2" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="20 0 0 0" FontSize="35" Foreground="{StaticResource DisplayTextBrushKey}" /> </Grid> </Grid> </Page> |
▶ MainPage.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 |
using System; using System.Collections.Generic; using System.Linq; using Windows.Devices.Gpio; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using Sensors.DHT; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public sealed partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Field #region Field /// <summary> /// 디스패처 타이머 /// </summary> private DispatcherTimer dispatcherTimer = null; /// <summary> /// DHT 인터페이스 /// </summary> private IDHT dht = null; /// <summary> /// GPIO 핀 /// </summary> private GpioPin gpioPin = null; /// <summary> /// 현재 일시 오프셋 /// </summary> private DateTimeOffset currentDateTimeOffset = DateTimeOffset.MinValue; /// <summary> /// 시도 건수 /// </summary> private int attemptCount = 0; /// <summary> /// 재시도 카운트 리스트 /// </summary> private List<int> retryCountList = new List<int>(); /// <summary> /// 성공 건수 /// </summary> private int successCount = 0; /// <summary> /// 습도 /// </summary> private float humidity = 0f; /// <summary> /// 온도 /// </summary> private float temperature = 0f; /// <summary> /// 최근 갱신 오프셋 /// </summary> private DateTimeOffset lastUpdatedOffset = DateTimeOffset.MinValue; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainPage() /// <summary> /// 생성자 /// </summary> public MainPage() { InitializeComponent(); this.dispatcherTimer = new DispatcherTimer(); this.dispatcherTimer.Interval = TimeSpan.FromSeconds(1); this.dispatcherTimer.Tick += dispatcherTimer_Tick; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 네비게이션 올 때 처리하기 - OnNavigatedTo(e) /// <summary> /// 네비게이션 올 때 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); GpioController gpioController = GpioController.GetDefault(); if(gpioController != null) { this.gpioPin = gpioController.OpenPin(17, GpioSharingMode.Exclusive); this.dht = new DHT11(this.gpioPin, GpioPinDriveMode.Input); this.dispatcherTimer.Start(); this.currentDateTimeOffset = DateTimeOffset.Now; } } #endregion #region 네비게이션 갈 때 처리하기 - OnNavigatedFrom(e) /// <summary> /// 네비게이션 갈 때 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnNavigatedFrom(NavigationEventArgs e) { this.dispatcherTimer.Stop(); if(this.gpioPin != null) { this.gpioPin.Dispose(); this.gpioPin = null; } this.dht = null; base.OnNavigatedFrom(e); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 디스패처 타이머 틱 처리하기 - dispatcherTimer_Tick(sender, e) /// <summary> /// 디스패처 타이머 틱 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void dispatcherTimer_Tick(object sender, object e) { try { this.dispatcherTimer.Stop(); DHTReading dhtReading = await this.dht.GetReadingAsync().AsTask(); #region 시도 건수를 표시한다. this.attemptCount++; this.attemptCountTextBlock.Text = string.Format("{0:0}", this.attemptCount); #endregion #region 평균 재시도 건수를 표시한다. this.retryCountList.Add(dhtReading.RetryCount); int averageRetryCount = 0; if(this.retryCountList.Count() > 0) { averageRetryCount = (int)this.retryCountList.Average(); } this.averageRetryCountTextBlock.Text = string.Format("{0:0}", averageRetryCount); #endregion #region 성공 건수를 표시한다. if(dhtReading.IsValid) { this.successCount++; } this.successCountTextBlock.Text = string.Format("{0:0}", this.successCount); #endregion #region 성공율을 표시한다. this.successRateTextBlock.Text = attemptCount > 0 ? string.Format("{0:0.0}%", 100f * (float)this.successCount / (float)attemptCount) : "0.0%"; #endregion #region 비율을 표시한다. double totalSecondCount = DateTimeOffset.Now.Subtract(this.currentDateTimeOffset).TotalSeconds; double rate = this.successCount / totalSecondCount; this.rateTextBlock.Text = rate < 1 ? string.Format("{0:0.00} 초/읽기", 1d / rate) : string.Format("{0:0.00} 읽기/초", rate); #endregion if(dhtReading.IsValid) { #region 습도를 표시한다. this.humidity = Convert.ToSingle(dhtReading.Humidity); this.humidityTextBlock.Text = string.Format("{0:0.0}% RH", this.humidity); #endregion #region 온도를 표시한다. this.temperature = Convert.ToSingle(dhtReading.Temperature); this.temperatureTextBlock.Text = string.Format("{0:0.0} ℃", this.temperature); #endregion #region 최근 갱신 일시를 표시한다. this.lastUpdatedOffset = DateTimeOffset.Now; this.lastUpdatedOffsetTextBlock.Text = GetLastUpdatedOffsetString(); #endregion } } finally { this.dispatcherTimer.Start(); } } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 최근 갱신 오프셋 문자열 구하기 - GetLastUpdatedOffsetString() /// <summary> /// 최근 갱신 오프셋 문자열 구하기 /// </summary> private string GetLastUpdatedOffsetString() { string returnValue = string.Empty; TimeSpan elapsed = DateTimeOffset.Now.Subtract(this.lastUpdatedOffset); if(this.lastUpdatedOffset == DateTimeOffset.MinValue) { returnValue = "미갱신"; } else if(elapsed.TotalSeconds < 60d) { int totalSecondCount = (int)elapsed.TotalSeconds; if(totalSecondCount < 2) { returnValue = "방금 갱신"; } else { returnValue = string.Format("{0:0} {1} 전", totalSecondCount, totalSecondCount == 1 ? "초" : "초"); } } else if(elapsed.TotalMinutes < 60d) { int totalMinuteCount = (int)elapsed.TotalMinutes == 0 ? 1 : (int)elapsed.TotalMinutes; returnValue = string.Format("{0:0} {1} 전", totalMinuteCount, totalMinuteCount == 1 ? "분" : "분"); } else if(elapsed.TotalHours < 24d) { int totalHourCount = (int)elapsed.TotalHours == 0 ? 1 : (int)elapsed.TotalHours; returnValue = string.Format("{0:0} {1} 전", totalHourCount, totalHourCount == 1 ? "시간" : "시간"); } else { returnValue = "오래 전"; } return returnValue; } #endregion } } |