첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
본 블로그는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 블로그 콘텐츠 향상을 위해 쓰여집니다.

728x90
반응형
728x170

TestApplication.zip
다운로드

▶ 부품 내역

구분 모델 수량 비고
SENSOR/TEMPERATURE JMOD-TEMP-1 1  

 

728x90

 

▶ 회로 구성도

 

300x250

 

▶ MainPage.xaml

<Page x:Class="TestApplication.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"
    xmlns:local="using:TestApplication"
    mc:Ignorable="d">
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock x:Name="textBlock"
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            TextWrapping="Wrap"
            FontWeight="Bold"
            FontSize="48" />
    </Grid>
</Page>

 

▶ MainPage.xaml.cs

using System;
using System.Diagnostics;
using System.Threading;
using Windows.Devices.Enumeration;
using Windows.Devices.I2c;
using Windows.Foundation;
using Windows.UI.Core;
using Windows.UI.Xaml.Controls;

namespace TestApplication
{
    /// <summary>
    /// 메인 페이지
    /// </summary>
    public sealed partial class MainPage : Page
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Field
        ////////////////////////////////////////////////////////////////////////////////////////// Private

        #region Field

        /// <summary>
        /// I2C 장치
        /// </summary>
        private I2cDevice i2cDevice = null;

        /// <summary>
        /// 타이머
        /// </summary>
        private Timer timer = null;

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 생성자 - MainPage()

        /// <summary>
        /// 생성자
        /// </summary>
        public MainPage()
        {
            this.InitializeComponent();

            InitializeI2CDevice();

            Unloaded += Page_Unloaded;
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Private
        //////////////////////////////////////////////////////////////////////////////// Event

        #region 페이지 언로드시 처리하기 - Page_Unloaded(sender, e)

        /// <summary>
        /// 페이지 언로드시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        private void Page_Unloaded(object sender, object e)
        {
            if(this.i2cDevice != null)
            {
                this.i2cDevice.Dispose();
            }
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////// Function

        #region 온도 계산하기 - CalculateTemperature(highValue, logValue)

        /// <summary>
        /// 온도 계산하기
        /// </summary>
        /// <param name="highValue">상위 값</param>
        /// <param name="logValue">하위 값</param>
        /// <returns>온도</returns>
        private static double CalculateTemperature(int highValue, int logValue)
        {
            int value = (highValue << 3) + (logValue >> 5);

            if(value >= 1024) // 온도가 영하인 경우
            {
                value -= 2048;
            }

            double temperature = value * 0.0625;

            return temperature;
        }

        #endregion
        #region 타이머 콜백 처리하기 - TimerCallback(state)

        /// <summary>
        /// 타이머 콜백 처리하기
        /// </summary>
        /// <param name="state">상태</param>
        private void TimerCallback(object state)
        {
            string temperatureString;

            byte[] byteArray = new byte[2];

            try
            {
                this.i2cDevice.Read(byteArray);
            }
            catch(Exception error)
            {
                Debug.WriteLine("예외 : " + error.Message);
            }

            int highValue = ((int)byteArray[0]);
            int lowValue  = ((int)byteArray[1]);

            double temperature = CalculateTemperature(highValue, lowValue);

            Debug.WriteLine(temperature);

            temperatureString = string.Format("온도 : {0:F4} ℃", temperature);

            IAsyncAction task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                this.textBlock.Text = temperatureString;
            });
        }

        #endregion
        #region I2C 장치 초기화 하기 - InitializeI2CDevice()

        /// <summary>
        /// I2C 장치 초기화 하기
        /// </summary>
        private async void InitializeI2CDevice()
        {
            try
            {
                string advancedQuerySyntax = I2cDevice.GetDeviceSelector();

                DeviceInformationCollection deviceInformationCollection = await DeviceInformation.FindAllAsync(advancedQuerySyntax);

                I2cConnectionSettings i2cConnectionSettings = new I2cConnectionSettings(0x48);

                i2cConnectionSettings.BusSpeed = I2cBusSpeed.FastMode;

                this.i2cDevice = await I2cDevice.FromIdAsync(deviceInformationCollection[0].Id, i2cConnectionSettings);
            }
            catch(Exception exception)
            {
                Debug.WriteLine("예외 : " + exception.Message);
            }

            this.timer = new Timer(TimerCallback, null, 0, 1000);
        }

        #endregion
    }
}
728x90
반응형
그리드형
Posted by 사용자 icodebroker

댓글을 달아 주세요