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 #4

Posted at

今回のプログラムはオンボード上のRGBLED(NeoPixel)でレインボーカラーを表示します。
#2のサンプルではカラーネームを指定して色を変更していましたが、今回のプログラムではRed,Green,Blueの各色の明るさを変化させてレインボーカラーを表現します。

ハードウェア

・Freenove ESP32-S3-WROOM Board
 (他のボードでも動作するかもしれませんが、LEDの型番が違う場合コードの一部を修正する必要があります。)

導入するパッケージ

・nanoFramework.iot.Device.Ws28xx.Esp32

プログラミング

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

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

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

Program.cs
using Iot.Device.Ws28xx.Esp32;
using System.Threading;

namespace ESP32S3_RGBLED_Rainbow
{
    public class Program
    {
        public static void Main()
        {
            const int count = 1;    //LEDの数 オンボードLEDが対象なので1
            const int ledPin = 48;  //LEDを接続しているGPIO番号

            int red, green, blue;

            Ws28xx led = new Ws2812c(ledPin, count);

            BitmapImage img = led.Image;

            while (true)
            {
                for(int i = 0; i < 255; i++)
                {
                    //色相の位置
                    int pos = i % 255;

                    //赤>(黄)>緑と変化する
                    if (pos < 85)
                    {
                        red = 255 - pos * 3;
                        green = pos * 3;
                        blue = 0;
                    }
                    //緑>(水色)>青と変化する
                    else if(pos>=85 && pos < 170)
                    {
                        pos -= 85;
                        red = 0;
                        green = 255 - pos * 3;
                        blue = pos * 3;
                    }
                    //青>(紫)>赤と変化する
                    else
                    {
                        pos -= 170;
                        red = pos * 3;
                        green = 0;
                        blue = 255 - pos * 3;
                    }

                    //色の指定はバイト型なので(byte)でキャストします。
                    img.SetPixel(0, 0, (byte)red, (byte)green, (byte)blue);
                    led.Update();
                    //20ms毎に変化
                    Thread.Sleep(20);
                }
            }
            
        }
    }
}

・色相グラフ見ると0~255の間で0の位置で赤色、85の位置で緑色、170の位置で青色、255の位置で再び赤色に戻ります。色相の位置によって各色の明るさを決めると滑らかに色を変化させることができます。

色相.png

数値で色を表現できるのでランダムな値を設定して複雑なパターンの光も出すことができます。

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?