0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C#でIoTプログラミング on ESP32 #6 - ボタンスイッチ2

Last updated at Posted at 2025-02-21

今回はイベントを使ってボタンの状態を検出するプログラムを消化します。
前回と同じ回路を使用します。

ハードウェア

・Freenove ESP32-S3-WROOM Board or Espressif ESP32-S3-DevKitC
・ブレッドボード
・タクトスイッチ
・ジャンパーワイヤ

配線

前回と同じ回路です。
button.PNG

導入するパッケージ

・nanoFramework.System.Device.Gpio

プログラミング

・新規プロジェクトを作成します。プロジェクト名は「ESP32S3_Button_event」としました。

・コードを入力する前にパッケージは導入してください。

・コードは次のようになります。

Program.cs
using System;
using System.Diagnostics;
using System.Threading;

using System.Device.Gpio;

namespace ESP32S3_button_event
{
    public class Program
    {
        private static GpioPin ledPin;
        private static GpioPin buttonPin;

        public static void Main()
        {
            GpioController controller = new GpioController();

            ledPin = controller.OpenPin(2, PinMode.Output);
            ledPin.Write(PinValue.Low);

            buttonPin = controller.OpenPin(35, PinMode.InputPullDown);

            buttonPin.ValueChanged += ButtonPin_ValueChanged;

            Thread.Sleep(Timeout.Infinite);
        }

        private static void ButtonPin_ValueChanged(object sender, PinValueChangedEventArgs e)
        {
            Debug.WriteLine(buttonPin.Read().ToString());
            if (e.ChangeType == PinEventTypes.Rising)   //Pinの電圧が低い状態から高い状態に変化した時
            {
                ledPin.Write(PinValue.High);
            }
            else
            {
                ledPin.Write(PinValue.Low); 
            }
        }
    }
}

 実行するとスイッチを押した時(この回路ではスイッチをオンにすることでPinに電圧がかかります。)にオンボードLEDが点灯します。
 前回のプログラムではPinの状態を定期的に監視して電圧がかかっているときにLEDを点灯するようにしていました。
 今回のプログラムではPinにかかる電圧が変化した時にイベントが発生し、そのイベントの状態によってLEDを制御するようにしています。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?