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 #13 - SCD40

Posted at

Co2センサー SCD40のサンプルプログラムです。

ハードウェア

・Freenove ESP32-S3-WROOM Board or Espressif ESP32-S3-DevKitC
・Adafruit SCD40

配線

SCD40.PNG

導入パッケージ

・nanoFramework.Hardware.Esp32
・nanoFramework.System.Device.I2c
・nanoFramework.System.Buffers.Binary.BinaryPrimitives

プログラミング

Program.cs
using nanoFramework.Hardware.Esp32;
using System;
using System.Buffers.Binary;
using System.Device.I2c;
using System.Threading;

namespace ESP32S3_SCD40
{
    public class Program
    {
        private static SpanByte start => new byte[] { 0x21, 0xb1 };         //スタートコマンド
        private static SpanByte read => new byte[] { 0xec, 0x05 };          //リードコマンド
        private static I2cDevice device;

        public static void Main()
        {
            Configuration.SetPinFunction(8, DeviceFunction.I2C1_DATA);
            Configuration.SetPinFunction(9, DeviceFunction.I2C1_CLOCK);

            I2cConnectionSettings settings = new(1, 0x62, I2cBusSpeed.FastMode);
            device = I2cDevice.Create(settings);

            device.Write(start);
            Thread.Sleep(1000);

            device.Write(read);

            Thread.Sleep(50);

            Timer timer = new Timer(getData, null, 0, 10000);

            Thread.Sleep(Timeout.Infinite);
        }

        private static void getData(object state)
        {
            SpanByte buffer = new byte[9];

            device.Read(buffer);

            var co2 = BinaryPrimitives.ReadInt16BigEndian(buffer.Slice(0, 3));
            var tmp = -45 + 175 * (float)(BinaryPrimitives.ReadUInt16BigEndian(buffer.Slice(3, 3))) / 65536;
            var hum = 100 * (float)(BinaryPrimitives.ReadUInt16BigEndian(buffer.Slice(6, 3))) / 65536;

            Console.WriteLine($"Temp: {tmp.ToString("F")}, Hum: {hum.ToString("F")}, Co2: {co2}");
        }
    }
}
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?