forked from nanoframework/nanoFramework.IoT.Device
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ak8963Attached.cs
78 lines (74 loc) · 2.78 KB
/
Ak8963Attached.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Device;
using System.Device.I2c;
using Iot.Device.Magnetometer;
namespace Iot.Device.Imu
{
internal class Ak8963Attached : Ak8963I2cBase
{
/// <summary>
/// Read a byte
/// </summary>
/// <param name="i2cDevice">An I2C device</param>
/// <param name="reg">The register to read</param>
/// <param name="data">A byte to write</param>
public override void WriteRegister(I2cDevice i2cDevice, byte reg, byte data)
{
SpanByte dataout = new byte[2]
{
(byte)Register.I2C_SLV0_ADDR, Magnetometer.Ak8963.DefaultI2cAddress
};
i2cDevice.Write(dataout);
dataout[0] = (byte)Register.I2C_SLV0_REG;
dataout[1] = reg;
i2cDevice.Write(dataout);
dataout[0] = (byte)Register.I2C_SLV0_DO;
dataout[1] = data;
i2cDevice.Write(dataout);
dataout[0] = (byte)Register.I2C_SLV0_CTRL;
dataout[1] = 0x81;
i2cDevice.Write(dataout);
}
/// <summary>
/// Read a byte array
/// </summary>
/// <param name="i2cDevice">An I2C device</param>
/// <param name="reg">>The register to read</param>
/// <returns>The register value</returns>
public override byte ReadByte(I2cDevice i2cDevice, byte reg)
{
SpanByte read = new byte[1]
{
0
};
ReadBytes(i2cDevice, reg, read);
return read[0];
}
/// <summary>
/// Write a byte
/// </summary>
/// <param name="i2cDevice">>An I2C device</param>
/// <param name="reg">The register to read</param>
/// <param name="readBytes">A span of bytes with the read values</param>
public override void ReadBytes(I2cDevice i2cDevice, byte reg, SpanByte readBytes)
{
SpanByte dataout = new byte[2]
{
(byte)Register.I2C_SLV0_ADDR, Magnetometer.Ak8963.DefaultI2cAddress | 0x80
};
i2cDevice.Write(dataout);
dataout[0] = (byte)Register.I2C_SLV0_REG;
dataout[1] = reg;
i2cDevice.Write(dataout);
dataout[0] = (byte)Register.I2C_SLV0_CTRL;
dataout[1] = (byte)(0x80 | readBytes.Length);
i2cDevice.Write(dataout);
// TODO: delay found empirically, spec does not mention delay but it is observable it is required
DelayHelper.DelayMicroseconds(200, false);
i2cDevice.WriteByte((byte)Register.EXT_SENS_DATA_00);
i2cDevice.Read(readBytes);
}
}
}