LoginSignup
1
0

More than 1 year has passed since last update.

.NET nanoFrameworkでマイコンプログラミング(LEDとボタン)

Posted at

.NET nanoFrameWorkのサンプルプログラム2つ目です。
今回はM5ATOM MatrixのボタンとLEDを使ったプログラムです。

使用するハードウェア

・M5ATOM Matrix

使用するソフトウェア

・VisualStudio2019
・ファームウェア ESP32_PICO 1.7.4-preview.45

追加するNuGetパッケージ

・nanoFramework.AtomMatrix 1.0.1-preview43

プログラム解説

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

//追加
using Iot.Device.Button;
using nanoFramework.AtomMatrix;
using System.Drawing;

・パッケージの参照設定を3行追加します。
・System.DrawingではLEDの色を設定するためのColorが定義されています。

Program.cs
    public class Program
    {
        private static PixelController led;            //LedMatrixオブジェクト

        public static void Main()
        {
            led = AtomMatrix.LedMatrix;
            GpioButton button = AtomMatrix.Button;     //ボタンオブジェクト

            //次のようにも記述可能
            //GpioButton button = new(buttonPin: 39);  //MatrixのボタンはG39に接続

            //Led消灯
            led.TurnOff();

            //イベントの登録
            button.Press += Button_Press;

            Thread.Sleep(Timeout.Infinite);
        }

・MainプロシージャではLedオブジェクト、Buttonオブジェクトの生成とPressイベントの登録を行います。

Program.cs
        private static void Button_Press(object sender, EventArgs e)
        {
            Debug.WriteLine("Button Pressed!");

            //LEDの状態を取得
            var color = led.Pixels;                    //LEDの状態はPixelsプロパティで取得

            if (color[12] == Color.Green){             //各LEDは0~24の一次配列で設定できる
                led.TurnOff();                         //12番目のLEDがちょうど真ん中
            }
            else
            {
                led.SetColor(12, Color.Green);
                led.Update();                          //LEDを点灯する際には最後にUpdateメソッドが必要
            }
        }

・LEDを全灯にしたい場合はFillColorメソッドを使うと一度に色の設定ができます。ただし相当明るいのでサンプルでは1つだけ点灯しています。
・LEDの番号は左上を0として次の右が1となり、最後右下のLEDが24になります。

以上サンプルプログラムの解説でした。

コード全体はこちらになります。

1
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
1
0