-
-
Notifications
You must be signed in to change notification settings - Fork 111
/
Copy pathAD5328.cs
77 lines (67 loc) · 2.94 KB
/
AD5328.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
// 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.Buffers.Binary;
using System.Device.Spi;
using UnitsNet;
namespace Iot.Device.DAC
{
/// <summary>
/// Driver for the AD5328 DAC.
/// </summary>
public class AD5328 : IDisposable
{
private SpiDevice _spiDevice;
private ElectricPotential _referenceVoltageA;
private ElectricPotential _referenceVoltageB;
private bool _disposedValue = false;
/// <summary>
/// Initializes a new instance of the <see cref="AD5328"/> class.
/// </summary>
/// <param name="spiDevice">The SPI device used for communication.</param>
/// <param name="referenceVoltageA">The reference voltage for the first 4 channels.</param>
/// <param name="referenceVoltageB">The reference voltage for the last 4 channels.</param>
public AD5328(SpiDevice spiDevice, ElectricPotential referenceVoltageA, ElectricPotential referenceVoltageB)
{
_spiDevice = spiDevice;
_referenceVoltageA = referenceVoltageA;
_referenceVoltageB = referenceVoltageB;
}
/// <summary>
/// Sets the voltage of a certain channel.
/// </summary>
/// <param name="channel">The channel number. Zero based. channel A = 0.</param>
/// <param name="voltage">The voltage.</param>
public void SetVoltage(ushort channel, ElectricPotential voltage)
{
// Check what reference voltage is used: Channel 0..3 = refA, Channel 4..7 = refB
var refV = (channel > 3) ? _referenceVoltageB : _referenceVoltageA;
// Check if requested voltage is not higher than reference voltage
if (voltage.Volts > refV.Volts)
{
throw new ArgumentOutOfRangeException(nameof(voltage), $"Value should be equal or lower than {refV.Volts} V");
}
// Calculate the DAC value of the voltage
var dacvalue = (ushort)Math.Round(voltage.Volts / (refV.Volts / 4095));
// The 16-bit word consists of 1 control bit and 3 address bits followed by 12 bits of DAC data.
// In the case of a DAC write, the MSB is a 0.
// The next 3 address bits determine whether the data is for DAC A, DAC B,
// DAC C, DAC D, DAC E, DAC F, DAC G, or DAC H.
var temp = (ushort)((channel << 12) | dacvalue);
// Swap bytes, MSB should go out first
SpanByte tempBytes = new byte[2];
BinaryPrimitives.WriteUInt16BigEndian(tempBytes, temp);
_spiDevice.Write(tempBytes);
}
/// <inheritdoc/>
public void Dispose()
{
if (!_disposedValue)
{
_spiDevice?.Dispose();
_disposedValue = true;
}
GC.SuppressFinalize(this);
}
}
}