코딩에 앞서 몇가지 예제를 분석해 보려고 합니다.
먼저 Push button입니다.
Push button예제에 가시면 좀 더 자세한 정보를 보실 수 있습니다.
위와 같이 Push button과 LED를 연결하고 버튼을 누를때마다 LED가 On/Off되는 예제입니다.
위 링크를 클릭하여 예제소스코드를 받으시면 시간이 절약됩니다.^^
소스코드를 열어보시면 왼쪽에 솔루션 탐색기가 나옵니다.
MainPage.xaml이 UI이고, MainPage.xaml.cs가 code가 있는 곳입니다.
UI파일을 열어보시면 사이즈를 정할 수 있습니다.
사이즈를 좀 키워 봤습니다.
이제 코드를 볼께요.
먼저 전역변수입니다.
1 2 3 4 5 6 7 | private const int LED_PIN = 6; private const int BUTTON_PIN = 5; private GpioPin ledPin; private GpioPin buttonPin; private GpioPinValue ledPinValue = GpioPinValue.High; private SolidColorBrush redBrush = new SolidColorBrush(Windows.UI.Colors.Red); private SolidColorBrush grayBrush = new SolidColorBrush(Windows.UI.Colors.LightGray); | cs |
Line 1~2 : GPIO 번호입니다.
Line 3~4 : GPIO변수입니다.
Line 5 : Led상태를 바꾸기 위한 GPIO Value 변수입니다. 초기 high로 설정합니다.
(High로 하면 LED는 꺼집니다.)
Line 6~7 : UI측면에서 동그란 부분의 색상변수입니다.
메인코드입니다.
1 2 3 4 5 | public MainPage() { InitializeComponent(); InitGPIO(); } | cs |
Line 3 : UI를 쓰기위한 초기화 메소드입니다.
Line 4: GPIO관련 초기화 메소드로 아래에 정의되어 있습니다.
InitGPIO() 입니다.
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 | private void InitGPIO() { var gpio = GpioController.GetDefault(); // Show an error if there is no GPIO controller if (gpio == null) { GpioStatus.Text = "There is no GPIO controller on this device."; return; } buttonPin = gpio.OpenPin(BUTTON_PIN); ledPin = gpio.OpenPin(LED_PIN); // Initialize LED to the OFF state by first writing a HIGH value // We write HIGH because the LED is wired in a active LOW configuration ledPin.Write(GpioPinValue.High); ledPin.SetDriveMode(GpioPinDriveMode.Output); // Check if input pull-up resistors are supported if (buttonPin.IsDriveModeSupported(GpioPinDriveMode.InputPullUp)) buttonPin.SetDriveMode(GpioPinDriveMode.InputPullUp); else buttonPin.SetDriveMode(GpioPinDriveMode.Input); // Set a debounce timeout to filter out switch bounce noise from a button press buttonPin.DebounceTimeout = TimeSpan.FromMilliseconds(50); // Register for the ValueChanged event so our buttonPin_ValueChanged // function is called when the button is pressed buttonPin.ValueChanged += buttonPin_ValueChanged; GpioStatus.Text = "GPIO pins initialized correctly."; } | cs |
Line 3 : 범용 GPIO 컨트롤러를 가져옵니다.
Line 6~10 : 만약 컨트롤러를 못가져오면 메세지를 뿌려줍니다.
Line 12~13 : 앞서 선언한 gpio핀을 초기화 해줍니다.
Line 17~18 : Led가 연결된 GPIO에 출력을 내보냅니다. 초기는 High를 내보내 LED를 끕니다.
그리고 GPIO는 출력으로 설정합니다.
Line 21~24 : button이 연결된 GPIO는 Input모드로 설정합니다. pullup모드가 지원되면 pullup으로 설정합니다.
Line 27 : 푸시버튼이기에 디바운스 처리를 해줘야하는데 내부적으로 지원합니다. 30ms로 설정.
Line 31 : 버튼의 상태가 변할때(이벤트 발생)마다 buttonPin_valueChanged를 호출합니다.
Line 33 : 모든 초기화가 끝났음을 UI의 Text에 뿌려줍니다.
buttonPin_valueChanged() 이벤트가 처리되는 부분입니다.
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 | private void buttonPin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs e) { // toggle the state of the LED every time the button is pressed if (e.Edge == GpioPinEdge.FallingEdge) { ledPinValue = (ledPinValue == GpioPinValue.Low) ? GpioPinValue.High : GpioPinValue.Low; ledPin.Write(ledPinValue); } // need to invoke UI updates on the UI thread because this event // handler gets invoked on a separate thread. var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { if (e.Edge == GpioPinEdge.FallingEdge) { ledEllipse.Fill = (ledPinValue == GpioPinValue.Low) ? redBrush : grayBrush; GpioStatus.Text = "Button Pressed"; } else { GpioStatus.Text = "Button Released"; } }); } | cs |
Line 4~9 : 버튼이 눌려진상태(FallingEdge)에 들어옵니다.
ledPinValue가 low이면 high로 high이면 low로 변수를 토글합니다.
그리고 Gpio에 ledPinValue를 넣어 LED를 On/Off 합니다.
Line 13~24 : UI 업데이트라 별도의 스레드를 쓰는 것같습니다.
Line 14~19 : Push button이 눌려졌을때, UI의 원의 색을 변경해 줍니다.
Led pin이 low이면 red(LED On), high이면 gray(Led Off)
그리고 UI의 text도 변경해줍니다. "Button Pressed"
Line 20~23 : Push button이 떨어졌을때 UI의 text가 변경됩니다. "Button Released"
'Study > Raspberry Pi' 카테고리의 다른 글
Rufus (image writer) (0) | 2018.12.10 |
---|---|
xrdp 오류날때 (error - problem connecting) (0) | 2017.03.16 |
RaspberryPi 에서 Windows10 iot C#으로 코딩하기 준비 (2) | 2017.01.24 |
RaspberryPi] Windows10 IoT 원격접속하기 (0) | 2017.01.19 |
라즈베리파이(Raspberry Pi)에 Windows10 IoT설치하기 (0) | 2017.01.18 |