첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
유용한 소스 코드가 있으면 icodebroker@naver.com으로 보내주시면 감사합니다.
블로그 자료는 자유롭게 사용하세요.

■ RGB LED 모듈 사용하기

----------------------------------------------------------------------------------------------------

부품 내역

 

구분

모델

수량

비고

RGB LED Module

 

1

 

 

회로 구성도

 


TestApplication.zip


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"

    FontFamily="나눔고딕코딩"

    FontSize="16"

    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

        <StackPanel

            HorizontalAlignment="Center"

            VerticalAlignment="Center">

            <Ellipse x:Name="ledEllipse"

                Width="100"

                Height="100"

                Margin="10"

                Fill="LightGray"

                Stroke="White" />

            <TextBlock x:Name="delayTextBlock"

                Margin="10"

                TextAlignment="Center"

                FontSize="24"

                Text="500ms" />

            <Slider x:Name="delaySlider"

                Margin="10"

                Width="200"

                Maximum="1000"

                LargeChange="100"

                SmallChange="10"

                StepFrequency="10"

                Value="500" />

            <TextBlock x:Name="messageTextBlock"

                Margin="10 50 10 10"

                TextAlignment="Center"

                FontSize="24"

                Text="GPIO 초기화 대기중..." />

        </StackPanel>

    </Grid>

</Page>

 

 

MainPage.xaml.cs

 

 

using System;

using System.Collections.Generic;

using System.Diagnostics;

using Windows.Devices.Gpio;

using Windows.Security.ExchangeActiveSyncProvisioning;

using Windows.UI;

using Windows.UI.Xaml;

using Windows.UI.Xaml.Controls;

using Windows.UI.Xaml.Controls.Primitives;

using Windows.UI.Xaml.Media;

 

namespace TestApplication

{

    /// <summary>

    /// 메인 페이지

    /// </summary>

    public sealed partial class MainPage : Page

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Enumeration

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 장치 모델 - DeviceModel

 

        /// <summary>

        /// 장치 모델

        /// </summary>

        public enum DeviceModel

        {

            /// <summary>

            /// 라즈베리 파이

            /// </summary>

            RaspberryPi,

 

            /// <summary>

            /// 미노우 보드 맥스

            /// </summary>

            MinnowBoardMax,

 

            /// <summary>

            /// 드래곤 보드 410

            /// </summary>

            DragonBoard410,

 

            /// <summary>

            /// 알 수 없슴

            /// </summary>

            Unknown

        };

 

        #endregion

        #region LED 상태 - LEDStatus

 

        /// <summary>

        /// LED 상태

        /// </summary>

        public enum LEDStatus

        {

            /// <summary>

            /// 빨강색

            /// </summary>

            Red,

 

            /// <summary>

            /// 녹색

            /// </summary>

            Green,

 

            /// <summary>

            /// 파랑색

            /// </summary>

            Blue

        };

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Field

        ////////////////////////////////////////////////////////////////////////////////////////// Private

 

        #region Field

 

        /// <summary>

        /// 빨강색 LED 핀 번호

        /// </summary>

        private const int RED_LED_PIN_NUMBER = 5;

 

        /// <summary>

        /// 녹색 LED 핀 번호

        /// </summary>

        private const int GREEN_LED_PIN_NUMBER = 13;

 

        /// <summary>

        /// 파랑색 LED 핀 번호

        /// </summary>

        private const int BLUE_LED_PIN_NUMBER = 6;

 

 

        /// <summary>

        /// 빨강색 브러시

        /// </summary>

        private SolidColorBrush redBrush = null;

 

        /// <summary>

        /// 녹색 브러시

        /// </summary>

        private SolidColorBrush greenBrush = null;

 

        /// <summary>

        /// 파랑색 브러시

        /// </summary>

        private SolidColorBrush blueBrush = null;

 

 

        /// <summary>

        /// LED 상태

        /// </summary>

        private LEDStatus ledStatus;

 

 

        /// <summary>

        /// 빨강색 GPIO 핀

        /// </summary>

        private GpioPin redGpioPin;

 

        /// <summary>

        /// 녹색 GPIO 핀

        /// </summary>

        private GpioPin greenGpioPin;

 

        /// <summary>

        /// 파랑색 GPIO 핀

        /// </summary>

        private GpioPin blueGpioPin;

 

 

        /// <summary>

        /// 타이머

        /// </summary>

        private DispatcherTimer timer;

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 생성자 - MainPage()

 

        /// <summary>

        /// 생성자

        /// </summary>

        public MainPage()

        {

            InitializeComponent();

 

 

            this.redBrush   = new SolidColorBrush(Colors.Red  );

            this.greenBrush = new SolidColorBrush(Colors.Green);

            this.blueBrush  = new SolidColorBrush(Colors.Blue );

 

 

            Loaded                        += Page_Loaded;

            this.delaySlider.ValueChanged += delaySlider_ValueChanged;

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Private

        //////////////////////////////////////////////////////////////////////////////// Event

 

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

 

        /// <summary>

        /// 페이지 로드시 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void Page_Loaded(object sender, RoutedEventArgs e)

        {

            GpioController gpioController = GpioController.GetDefault();

 

            if(gpioController == null)

            {

                this.messageTextBlock.Text = "이 장치에 GPIO 컨트롤러가 없습니다..";

 

                return;

            }

 

            DeviceModel deviceModel = GetDeviceModel();

 

            if(deviceModel == DeviceModel.RaspberryPi)

            {

                this.redGpioPin   = gpioController.OpenPin(RED_LED_PIN_NUMBER  );

                this.greenGpioPin = gpioController.OpenPin(GREEN_LED_PIN_NUMBER);

                this.blueGpioPin  = gpioController.OpenPin(BLUE_LED_PIN_NUMBER );

            }

            else

            {

                List<GpioPin> gpioPinList = new List<GpioPin>(3);

 

                for(int i = 0; i < gpioController.PinCount; i++)

                {

                    switch(deviceModel)

                    {

                        case DeviceModel.DragonBoard410 :

                        {

                            if(i == 21 || i == 120)

                            {

                                continue;

                            }

 

                            break;

                        }

                    }

 

                    GpioPin        gpioPin;

                    GpioOpenStatus gpioOpenStatus;

 

                    if(gpioController.TryOpenPin(i, GpioSharingMode.Exclusive, out gpioPin, out gpioOpenStatus))

                    {

                        gpioPinList.Add(gpioPin);

 

                        if(gpioPinList.Count == 3)

                        {

                            break;

                        }

                    }

                }

 

                if(gpioPinList.Count != 3)

                {

                    this.messageTextBlock.Text = "3개의 이용 가능한 핀들을 찾을 수 없습니다. 이 샘플은 3개의 GPIO 핀들이 필요합니다.";

 

                    return;

                }

 

                this.redGpioPin   = gpioPinList[0];

                this.greenGpioPin = gpioPinList[1];

                this.blueGpioPin  = gpioPinList[2];

            }

 

 

            this.redGpioPin.Write(GpioPinValue.High);

            this.redGpioPin.SetDriveMode(GpioPinDriveMode.Output);

 

            this.greenGpioPin.Write(GpioPinValue.High);

            this.greenGpioPin.SetDriveMode(GpioPinDriveMode.Output);

 

            this.blueGpioPin.Write(GpioPinValue.High);

            this.blueGpioPin.SetDriveMode(GpioPinDriveMode.Output);

 

 

            this.messageTextBlock.Text = string.Format

            (

                "빨강색 핀 = {0}, 녹색 핀 = {1}, 파랑색 핀 = {2}",

                this.redGpioPin.PinNumber,

                this.greenGpioPin.PinNumber,

                this.blueGpioPin.PinNumber

            );

 

 

            this.timer = new DispatcherTimer();

 

            this.timer.Interval = TimeSpan.FromMilliseconds(500);

 

            this.timer.Tick += timer_Tick;

 

            this.timer.Start();

        }

 

        #endregion

        #region 타이머 틱 처리하기 - timer_Tick(sender, e)

 

        /// <summary>

        /// 타이머 틱 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void timer_Tick(object sender, object e)

        {

            FlipLED();

        }

 

        #endregion

        #region 지연 슬라이더 값 변경시 처리하기 - delaySlider_ValueChanged(sender, e)

 

        /// <summary>

        /// 지연 슬라이더 값 변경시 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void delaySlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)

        {            

            if(this.timer == null)

            {

                return;

            }

 

            if(e.NewValue == this.delaySlider.Minimum)

            {

                this.delayTextBlock.Text = "Stopped";

 

                this.timer.Stop();

 

                TurnOffLED();

            }

            else

            {

                this.delayTextBlock.Text = e.NewValue + "ms";

 

                this.timer.Interval = TimeSpan.FromMilliseconds(e.NewValue);

 

                this.timer.Start();

            }

        }

 

        #endregion

 

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

 

        #region 장치 모델 구하기 - GetDeviceModel()

 

        /// <summary>

        /// 장치 모델 구하기

        /// </summary>

        /// <returns>장치 모델</returns>

        private DeviceModel GetDeviceModel()

        {

            EasClientDeviceInformation easClientDeviceInformation = new EasClientDeviceInformation();

 

            if(easClientDeviceInformation.SystemProductName.IndexOf("Raspberry", StringComparison.OrdinalIgnoreCase) >= 0)

            {

                return DeviceModel.RaspberryPi;

            }

            else if(easClientDeviceInformation.SystemProductName.IndexOf("MinnowBoard", StringComparison.OrdinalIgnoreCase) >= 0)

            {

                return DeviceModel.MinnowBoardMax;

            }

            else if(easClientDeviceInformation.SystemProductName == "SBC")

            {

                return DeviceModel.DragonBoard410;

            }

            else

            {

                return DeviceModel.Unknown;

            }

        }

 

        #endregion

        #region LED 깜박이기 - FlipLED()

 

        /// <summary>

        /// LED 깜박이기

        /// </summary>

        private void FlipLED()

        {

            Debug.Assert(this.redGpioPin != null && this.blueGpioPin != null && this.greenGpioPin != null);

 

            switch(this.ledStatus)

            {

                case LEDStatus.Red :

                {

                    this.redGpioPin.Write  (GpioPinValue.High);

                    this.blueGpioPin.Write (GpioPinValue.Low );

                    this.greenGpioPin.Write(GpioPinValue.Low );

 

                    this.ledEllipse.Fill = this.redBrush;

 

                    this.ledStatus = LEDStatus.Green; // 다음 상태를 설정한다.

 

                    break;

                }

                case LEDStatus.Green :

                {

                    this.redGpioPin.Write  (GpioPinValue.Low );

                    this.greenGpioPin.Write(GpioPinValue.High);

                    this.blueGpioPin.Write (GpioPinValue.Low );

 

                    this.ledEllipse.Fill = this.greenBrush;

 

                    this.ledStatus = LEDStatus.Blue; // 다음 상태를 설정한다.

 

                    break;

                }

                case LEDStatus.Blue :

                {

                    this.redGpioPin.Write  (GpioPinValue.Low );

                    this.greenGpioPin.Write(GpioPinValue.Low );

                    this.blueGpioPin.Write (GpioPinValue.High);

 

                    this.ledEllipse.Fill = this.blueBrush;

 

                    this.ledStatus = LEDStatus.Red; // 다음 상태를 설정한다.

 

                    break;

                }

            }

        }

 

        #endregion

        #region LED 끄기 - TurnOffLED()

 

        /// <summary>

        /// LED 끄기

        /// </summary>

        private void TurnOffLED()

        {

            this.redGpioPin.Write  (GpioPinValue.Low);

            this.greenGpioPin.Write(GpioPinValue.Low);

            this.blueGpioPin.Write (GpioPinValue.Low);

        }

 

        #endregion

    }

}

 

----------------------------------------------------------------------------------------------------

Posted by 사용자 icodebroker
TAG

댓글을 달아 주세요