Hmc5883l.cs 5.1 KB
Newer Older
Z
Zhang Yuexin 已提交
1 2 3 4 5 6
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Buffers.Binary;
7
using System.Device.I2c.Devices;
Z
Zhang Yuexin 已提交
8 9 10 11 12 13 14 15 16 17
using System.Numerics;

namespace Iot.Device.Hmc5883l
{
    /// <summary>
    /// 3-Axis Digital Compass HMC5883L
    /// </summary>
    public class Hmc5883l : IDisposable
    {
        /// <summary>
Z
Zhang Yuexin 已提交
18
        /// HMC5883L Default I2C Address
Z
Zhang Yuexin 已提交
19
        /// </summary>
Z
Zhang Yuexin 已提交
20
        public const byte DefaultI2cAddress = 0x1E;
Z
Zhang Yuexin 已提交
21 22 23 24 25 26

        private I2cDevice _sensor;

        private readonly byte _measuringMode;
        private readonly byte _outputRate;
        private readonly byte _gain;
D
Dmitriy Shelpanov 已提交
27 28
        private readonly byte _samplesAmount;
        private readonly byte _measurementConfig;
Z
Zhang Yuexin 已提交
29 30 31 32 33 34 35 36 37 38 39

        /// <summary>
        /// HMC5883L Direction Vector
        /// </summary>
        public Vector3 DirectionVector => ReadDirectionVector();

        /// <summary>
        /// HMC5883L Heading (DEG)
        /// </summary>
        public double Heading => VectorToHeading(ReadDirectionVector());

D
Dmitriy Shelpanov 已提交
40 41 42 43 44
        /// <summary>
        /// HMC5883L Status
        /// </summary>
        public Status DeviceStatus => GetStatus();

Z
Zhang Yuexin 已提交
45 46 47 48 49 50 51
        /// <summary>
        /// Initialize a new HMC5883L device connected through I2C
        /// </summary>
        /// <param name="sensor">I2C Device, like UnixI2cDevice or Windows10I2cDevice</param>
        /// <param name="gain">Gain Setting</param>
        /// <param name="measuringMode">The Mode of Measuring</param>
        /// <param name="outputRate">Typical Data Output Rate (Hz)</param>
D
Dmitriy Shelpanov 已提交
52 53 54 55 56 57 58 59 60
        /// <param name="samplesAmount">Number of samples averaged per measurement output</param>
        /// <param name="measurementConfig">Measurement configuration</param>
        public Hmc5883l(
            I2cDevice sensor, 
            Gain gain = Gain.Gain1090, 
            MeasuringMode measuringMode = MeasuringMode.Continuous, 
            OutputRate outputRate = OutputRate.Rate15,
            SamplesAmount samplesAmount = SamplesAmount.One,
            MeasurementConfiguration measurementConfig = MeasurementConfiguration.Normal)
Z
Zhang Yuexin 已提交
61 62 63 64 65
        {
            _sensor = sensor;
            _gain = (byte)gain;
            _measuringMode = (byte)measuringMode;
            _outputRate = (byte)outputRate;
D
Dmitriy Shelpanov 已提交
66 67
            _samplesAmount = (byte)samplesAmount;
            _measurementConfig = (byte)measurementConfig;
Z
Zhang Yuexin 已提交
68 69 70 71 72 73 74 75 76 77

            Initialize();
        }

        /// <summary>
        /// Initialize the sensor
        /// </summary>
        private void Initialize()
        {
            // Details in Datasheet P12
D
Dmitriy Shelpanov 已提交
78
            byte configA = (byte)(_samplesAmount | (_outputRate << 2) | _measurementConfig);
Z
Zhang Yuexin 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
            byte configB = (byte)(_gain << 5);

            Span<byte> commandA = stackalloc byte[] { (byte)Register.HMC_CONFIG_REG_A_ADDR, configA };
            Span<byte> commandB = stackalloc byte[] { (byte)Register.HMC_CONFIG_REG_B_ADDR, configB };
            Span<byte> commandMode = stackalloc byte[] { (byte)Register.HMC_MODE_REG_ADDR, _measuringMode };

            _sensor.Write(commandA);
            _sensor.Write(commandB);
            _sensor.Write(commandMode);
        }

        /// <summary>
        /// Read raw data from HMC5883L
        /// </summary>
        /// <returns>Raw Data</returns>
        private Vector3 ReadDirectionVector()
        {
            Span<byte> xRead = stackalloc byte[2];
            Span<byte> yRead = stackalloc byte[2];
            Span<byte> zRead = stackalloc byte[2];

            _sensor.WriteByte((byte)Register.HMC_X_MSB_REG_ADDR);
            _sensor.Read(xRead);
            _sensor.WriteByte((byte)Register.HMC_Y_MSB_REG_ADDR);
            _sensor.Read(yRead);
            _sensor.WriteByte((byte)Register.HMC_Z_MSB_REG_ADDR);
            _sensor.Read(zRead);

            short x = BinaryPrimitives.ReadInt16BigEndian(xRead);
            short y = BinaryPrimitives.ReadInt16BigEndian(yRead);
            short z = BinaryPrimitives.ReadInt16BigEndian(zRead);

            return new Vector3(x, y, z);
        }

        /// <summary>
        /// Calculate heading
        /// </summary>
        /// <param name="vector">HMC5883L Direction Vector</param>
        /// <returns>Heading (DEG)</returns>
        private double VectorToHeading(Vector3 vector)
        {
            double deg = Math.Atan2(vector.Y, vector.X) * 180 / Math.PI;

            if (deg < 0)
                deg += 360;

            return deg;
        }

        /// <summary>
        /// Cleanup
        /// </summary>
        public void Dispose()
        {
            if (_sensor != null)
            {
                _sensor.Dispose();
                _sensor = null;
            }
        }
D
Dmitriy Shelpanov 已提交
140 141 142 143 144 145 146 147 148 149 150 151

        /// <summary>
        /// Reads device statuses.
        /// </summary>
        /// <returns>Device statuses</returns>
        private Status GetStatus()
        {
            _sensor.WriteByte((byte)Register.HMC_STATUS_REG_ADDR);
            byte status = _sensor.ReadByte();

            return (Status)status;
        }
Z
Zhang Yuexin 已提交
152 153
    }
}