Adding Ads1115 (#11)
This commit is contained in:
Родитель
c00848a0ff
Коммит
f3a281b228
|
@ -0,0 +1,628 @@
|
|||
// 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.Threading;
|
||||
using System.Device;
|
||||
using System.Device.I2c;
|
||||
using System.Device.Gpio;
|
||||
using UnitsNet;
|
||||
using UnitsNet.Units;
|
||||
|
||||
namespace Iot.Device.Ads1115
|
||||
{
|
||||
/// <summary>
|
||||
/// Analog-to-Digital Converter ADS1115
|
||||
/// </summary>
|
||||
public class Ads1115 : IDisposable
|
||||
{
|
||||
private readonly bool _shouldDispose;
|
||||
|
||||
private I2cDevice _i2cDevice;
|
||||
|
||||
private GpioController? _gpioController;
|
||||
|
||||
private InputMultiplexer _inputMultiplexer;
|
||||
|
||||
private MeasuringRange _measuringRange;
|
||||
|
||||
private DataRate _dataRate;
|
||||
private DeviceMode _deviceMode;
|
||||
|
||||
/// <summary>
|
||||
/// The pin of the GPIO controller that is connected to the interrupt line of the ADS1115
|
||||
/// </summary>
|
||||
private int _gpioInterruptPin;
|
||||
|
||||
private ComparatorPolarity _comparatorPolarity;
|
||||
private ComparatorLatching _comparatorLatching;
|
||||
private ComparatorQueue _comparatorQueue;
|
||||
|
||||
/// <summary>
|
||||
/// Initialize a new Ads1115 device connected through I2C
|
||||
/// </summary>
|
||||
/// <param name="i2cDevice">The I2C device used for communication.</param>
|
||||
/// <param name="inputMultiplexer">Input Multiplexer</param>
|
||||
/// <param name="measuringRange">Programmable Gain Amplifier</param>
|
||||
/// <param name="dataRate">Data Rate</param>
|
||||
/// <param name="deviceMode">Initial device mode</param>
|
||||
public Ads1115(I2cDevice i2cDevice, InputMultiplexer inputMultiplexer = InputMultiplexer.AIN0, MeasuringRange measuringRange = MeasuringRange.FS4096,
|
||||
DataRate dataRate = DataRate.SPS128, DeviceMode deviceMode = DeviceMode.Continuous)
|
||||
{
|
||||
_i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
|
||||
_inputMultiplexer = inputMultiplexer;
|
||||
_measuringRange = measuringRange;
|
||||
_dataRate = dataRate;
|
||||
_gpioController = null;
|
||||
_gpioInterruptPin = -1;
|
||||
_deviceMode = deviceMode;
|
||||
ComparatorMode = ComparatorMode.Traditional;
|
||||
_comparatorPolarity = ComparatorPolarity.Low;
|
||||
_comparatorLatching = ComparatorLatching.NonLatching;
|
||||
_comparatorQueue = ComparatorQueue.Disable;
|
||||
|
||||
SetConfig();
|
||||
DisableAlertReadyPin();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initialize a new Ads1115 device connected through I2C with an additional GPIO controller for interrupt handling.
|
||||
/// </summary>
|
||||
/// <param name="i2cDevice">The I2C device used for communication.</param>
|
||||
/// <param name="gpioController">The GPIO Controller used for interrupt handling</param>
|
||||
/// <param name="gpioInterruptPin">The pin number where the interrupt line is attached on the GPIO controller</param>
|
||||
/// <param name="shouldDispose">True (the default) if the GPIO controller shall be disposed when disposing this instance</param>
|
||||
/// <param name="inputMultiplexer">Input Multiplexer</param>
|
||||
/// <param name="measuringRange">Programmable Gain Amplifier</param>
|
||||
/// <param name="dataRate">Data Rate</param>
|
||||
/// <param name="deviceMode">Initial device mode</param>
|
||||
public Ads1115(I2cDevice i2cDevice,
|
||||
GpioController? gpioController, int gpioInterruptPin, bool shouldDispose = true, InputMultiplexer inputMultiplexer = InputMultiplexer.AIN0, MeasuringRange measuringRange = MeasuringRange.FS4096,
|
||||
DataRate dataRate = DataRate.SPS128, DeviceMode deviceMode = DeviceMode.Continuous)
|
||||
: this(i2cDevice, inputMultiplexer, measuringRange, dataRate, deviceMode)
|
||||
{
|
||||
_gpioController = gpioController ?? new GpioController();
|
||||
if (gpioInterruptPin < 0 || gpioInterruptPin >= _gpioController.PinCount)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(gpioInterruptPin), $"The given GPIO Controller has no pin number {gpioInterruptPin}");
|
||||
}
|
||||
|
||||
_gpioInterruptPin = gpioInterruptPin;
|
||||
_shouldDispose = shouldDispose || gpioController is null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ADS1115 Input Multiplexer.
|
||||
/// This selects the channel(s) for the next read operation, <see cref="Iot.Device.Ads1115.InputMultiplexer"/>.
|
||||
/// Setting this property will wait until a value is available from the newly selected input channel.
|
||||
/// </summary>
|
||||
public InputMultiplexer InputMultiplexer
|
||||
{
|
||||
get => _inputMultiplexer;
|
||||
set
|
||||
{
|
||||
_inputMultiplexer = value;
|
||||
SetConfig();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ADS1115 Programmable Gain Amplifier
|
||||
/// This sets the maximum value that can be measured. Regardless of this setting, the input value on any pin must not exceed VDD + 0.3V,
|
||||
/// so high ranges are only usable with a VDD of more than 5V.
|
||||
/// Setting this property will wait until a new value is available.
|
||||
/// </summary>
|
||||
public MeasuringRange MeasuringRange
|
||||
{
|
||||
get => _measuringRange;
|
||||
set
|
||||
{
|
||||
_measuringRange = value;
|
||||
SetConfig();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ADS1115 Data Rate.
|
||||
/// The number of conversions per second that will take place. One conversion will take "1/rate" seconds to become ready. If in
|
||||
/// power-down mode, only one conversion will happen automatically, then another request is required.
|
||||
/// Setting this property will wait until a new value is available.
|
||||
/// </summary>
|
||||
public DataRate DataRate
|
||||
{
|
||||
get => _dataRate;
|
||||
set
|
||||
{
|
||||
_dataRate = value;
|
||||
SetConfig();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ADS1115 operation mode.
|
||||
/// When set to <see cref="DeviceMode.Continuous"/> the chip continously measures the input and the values can be read directly.
|
||||
/// If set to <see cref="DeviceMode.PowerDown"/> the chip enters idle mode after each conversion and
|
||||
/// a new value will be requested each time a read request is performed. This is the recommended setting when frequently
|
||||
/// swapping between input channels, because a change of the channel requires a new conversion anyway.
|
||||
/// </summary>
|
||||
public DeviceMode DeviceMode
|
||||
{
|
||||
get
|
||||
{
|
||||
return _deviceMode;
|
||||
}
|
||||
set
|
||||
{
|
||||
_deviceMode = value;
|
||||
SetConfig();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Comparator mode.
|
||||
/// Only relevant if the comparator trigger event is set up and is changed by <see cref="EnableComparator(short, short, ComparatorMode, ComparatorQueue)"/>.
|
||||
/// </summary>
|
||||
public ComparatorMode ComparatorMode { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Comparator polarity. Indicates whether the rising or the falling edge of the ALRT/RDY Pin is relevant.
|
||||
/// Default: Low (falling edge)
|
||||
/// </summary>
|
||||
public ComparatorPolarity ComparatorPolarity
|
||||
{
|
||||
get
|
||||
{
|
||||
return _comparatorPolarity;
|
||||
}
|
||||
set
|
||||
{
|
||||
_comparatorPolarity = value;
|
||||
SetConfig();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Comparator latching mode. If enabled, the ALRT/RDY Pin will be kept signaled until the conversion value is read.
|
||||
/// Only relevant when the comparator is enabled.
|
||||
/// </summary>
|
||||
public ComparatorLatching ComparatorLatching
|
||||
{
|
||||
get
|
||||
{
|
||||
return _comparatorLatching;
|
||||
}
|
||||
set
|
||||
{
|
||||
_comparatorLatching = value;
|
||||
SetConfig();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Minimum number of samples exceeding the lower/upper threshold before the ALRT pin is asserted.
|
||||
/// This can only be set with <see cref="EnableComparator(short, short, ComparatorMode, ComparatorQueue)"/>.
|
||||
/// </summary>
|
||||
public ComparatorQueue ComparatorQueue => _comparatorQueue;
|
||||
|
||||
/// <summary>
|
||||
/// This event fires when a new value is available (in conversion ready mode) or the comparator threshold is exceeded.
|
||||
/// Requires setup through <see cref="EnableConversionReady"/> or <see cref="EnableComparator(ElectricPotential, ElectricPotential, ComparatorMode, ComparatorQueue)"/>.
|
||||
/// </summary>
|
||||
public event Action? AlertReadyAsserted;
|
||||
|
||||
/// <summary>
|
||||
/// Set ADS1115 Config Register.
|
||||
/// Register Layout:
|
||||
/// 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
|
||||
/// OS | MUX | PGA | MODE | DATA RATE | COMP_MODE | COMP_POL | COMP_LAT | COMP_QUE
|
||||
/// </summary>
|
||||
private void SetConfig()
|
||||
{
|
||||
// Details in Datasheet P18
|
||||
byte configHi = (byte)(0x80 | // Set conversion enable bit, so we always do (at least) one conversion using the new settings
|
||||
((byte)_inputMultiplexer << 4) |
|
||||
((byte)_measuringRange << 1) |
|
||||
((byte)DeviceMode.PowerDown)); // Always in powerdown mode, otherwise we can't wait properly
|
||||
|
||||
byte configLo = (byte)(((byte)_dataRate << 5) |
|
||||
((byte)ComparatorMode << 4) |
|
||||
((byte)_comparatorPolarity << 3) |
|
||||
((byte)_comparatorLatching << 2) |
|
||||
(byte)_comparatorQueue);
|
||||
|
||||
SpanByte writeBuff = new byte[3]
|
||||
{
|
||||
(byte)Register.ADC_CONFIG_REG_ADDR,
|
||||
configHi,
|
||||
configLo
|
||||
};
|
||||
|
||||
_i2cDevice.Write(writeBuff);
|
||||
|
||||
// waiting for the sensor stability
|
||||
WaitWhileBusy();
|
||||
|
||||
if (_deviceMode == DeviceMode.Continuous)
|
||||
{
|
||||
// We need to wait two cycles when changing the configuration in continuous mode,
|
||||
// otherwise we may be getting a value from the wrong input
|
||||
_i2cDevice.Write(writeBuff);
|
||||
WaitWhileBusy();
|
||||
configHi &= 0xFE; // Clear last bit
|
||||
writeBuff[1] = configHi;
|
||||
_i2cDevice.Write(writeBuff); // And enable continuous mode
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the comparator registers to default values (effectively disabling the comparator) and disables the
|
||||
/// Alert / Ready pin (if configured)
|
||||
/// </summary>
|
||||
private void DisableAlertReadyPin()
|
||||
{
|
||||
_comparatorQueue = ComparatorQueue.Disable;
|
||||
SetConfig();
|
||||
// Reset to defaults
|
||||
SpanByte writeBuff = new byte[3]
|
||||
{
|
||||
(byte)Register.ADC_CONFIG_REG_LO_THRESH, 0x80, 0
|
||||
};
|
||||
_i2cDevice.Write(writeBuff);
|
||||
writeBuff = new byte[3]
|
||||
{
|
||||
(byte)Register.ADC_CONFIG_REG_HI_THRESH, 0x7F, 0xFF
|
||||
};
|
||||
_i2cDevice.Write(writeBuff);
|
||||
if (_gpioController is object)
|
||||
{
|
||||
_gpioController.UnregisterCallbackForPinValueChangedEvent(_gpioInterruptPin, ConversionReadyCallback);
|
||||
_gpioController.ClosePin(_gpioInterruptPin);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write the two comparator registers
|
||||
/// </summary>
|
||||
/// <param name="loThreshold">High threshold value (unsigned short)</param>
|
||||
/// <param name="hiThreshold">Low threshold value (unsigned short)</param>
|
||||
private void WriteComparatorRegisters(short loThreshold, short hiThreshold)
|
||||
{
|
||||
SpanByte writeBuff = new byte[3]
|
||||
{
|
||||
(byte)Register.ADC_CONFIG_REG_LO_THRESH, (byte)(loThreshold >> 8), (byte)(loThreshold & 0xFF)
|
||||
};
|
||||
_i2cDevice.Write(writeBuff);
|
||||
writeBuff = new byte[3]
|
||||
{
|
||||
(byte)Register.ADC_CONFIG_REG_HI_THRESH, (byte)(hiThreshold >> 8), (byte)(hiThreshold & 0xFF)
|
||||
};
|
||||
_i2cDevice.Write(writeBuff);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enable conversion ready event.
|
||||
/// The <see cref="AlertReadyAsserted"/> event fires each time a new value is available after this method is called.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException">The conversion ready event is already set up or no GPIO Controller configured
|
||||
/// for interrupt handling.</exception>
|
||||
public void EnableConversionReady()
|
||||
{
|
||||
if (_gpioController is null)
|
||||
{
|
||||
throw new InvalidOperationException("Must have provided a GPIO Controller for interrupt handling.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// The ALRT/RDY Pin requires a pull-up resistor
|
||||
_gpioController.OpenPin(_gpioInterruptPin, PinMode.InputPullUp);
|
||||
|
||||
// Must be set to something other than disable
|
||||
_comparatorQueue = ComparatorQueue.AssertAfterOne;
|
||||
_deviceMode = DeviceMode.Continuous;
|
||||
SetConfig();
|
||||
// Writing a negative value to the max value register and a positive value to the min value register
|
||||
// configures the ALRT/RDY pin to trigger after each conversion (with a transition from high to low, when ComparatorPolarity is Low)
|
||||
WriteComparatorRegisters(short.MaxValue, short.MinValue);
|
||||
|
||||
_gpioController.RegisterCallbackForPinValueChangedEvent(_gpioInterruptPin, ComparatorPolarity == ComparatorPolarity.Low ? PinEventTypes.Falling : PinEventTypes.Rising, ConversionReadyCallback);
|
||||
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
_gpioController.ClosePin(_gpioInterruptPin);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private void ConversionReadyCallback(object sender, PinValueChangedEventArgs pinValueChangedEventArgs)
|
||||
{
|
||||
if (AlertReadyAsserted is object)
|
||||
{
|
||||
AlertReadyAsserted();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enable comparator callback mode.
|
||||
/// In traditional comparator mode, the callback is triggered each time the measured value exceeds the given upper value (for
|
||||
/// the given queueLength number of samples). It deasserts when the lower value is reached.
|
||||
/// In window comparator mode, the callback is triggered each time the measured value exceeds the given upper value or gets
|
||||
/// less than the given lower value.
|
||||
/// </summary>
|
||||
/// <param name="lowerValue">Lower value for the comparator</param>
|
||||
/// <param name="upperValue">Upper value for the comparator</param>
|
||||
/// <param name="mode">Traditional or Window comparator mode</param>
|
||||
/// <param name="queueLength">Minimum number of samples that must exceed the threshold to trigger the event</param>
|
||||
/// <exception cref="InvalidOperationException">The GPIO Controller for the interrupt handler has not been set up</exception>
|
||||
public void EnableComparator(ElectricPotential lowerValue, ElectricPotential upperValue, ComparatorMode mode,
|
||||
ComparatorQueue queueLength) => EnableComparator(VoltageToRaw(lowerValue), VoltageToRaw(upperValue), mode, queueLength);
|
||||
|
||||
/// <summary>
|
||||
/// Enable comparator callback mode.
|
||||
/// In traditional comparator mode, the callback is triggered each time the measured value exceeds the given upper value (for
|
||||
/// the given queueLength number of samples). It deasserts when the lower value is reached.
|
||||
/// In window comparator mode, the callback is triggered each time the measured value exceeds the given upper value or gets
|
||||
/// less than the given lower value.
|
||||
/// </summary>
|
||||
/// <param name="lowerValue">Lower value for the comparator</param>
|
||||
/// <param name="upperValue">Upper value for the comparator</param>
|
||||
/// <param name="mode">Traditional or Window comparator mode</param>
|
||||
/// <param name="queueLength">Minimum number of samples that must exceed the threshold to trigger the event</param>
|
||||
/// <exception cref="InvalidOperationException">The GPIO Controller for the interrupt handler has not been set up</exception>
|
||||
public void EnableComparator(short lowerValue, short upperValue, ComparatorMode mode,
|
||||
ComparatorQueue queueLength)
|
||||
{
|
||||
if (_gpioController is null)
|
||||
{
|
||||
throw new InvalidOperationException("GPIO Controller must have been provided in constructor for this operation to work");
|
||||
}
|
||||
|
||||
if (queueLength == ComparatorQueue.Disable)
|
||||
{
|
||||
throw new ArgumentException("Must set the ComparatorQueue to something other than disable.", nameof(queueLength));
|
||||
}
|
||||
|
||||
if (upperValue <= lowerValue)
|
||||
{
|
||||
throw new ArgumentException("Lower comparator limit must be larger than upper comparator limit");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// The ALRT/RDY Pin requires a pull-up resistor
|
||||
_gpioController.OpenPin(_gpioInterruptPin, PinMode.InputPullUp);
|
||||
|
||||
_comparatorQueue = queueLength;
|
||||
ComparatorMode = mode;
|
||||
// Event callback mode is only useful in Continuous mode
|
||||
_deviceMode = DeviceMode.Continuous;
|
||||
SetConfig();
|
||||
// Writing a negative value to the max value register and a positive value to the min value register
|
||||
// configures the ALRT/RDY pin to trigger after each conversion (with a transition from high to low, when ComparatorPolarity is Low)
|
||||
WriteComparatorRegisters(lowerValue, upperValue);
|
||||
|
||||
_gpioController.RegisterCallbackForPinValueChangedEvent(_gpioInterruptPin, ComparatorPolarity == ComparatorPolarity.Low ? PinEventTypes.Falling : PinEventTypes.Rising, ConversionReadyCallback);
|
||||
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
_gpioController.ClosePin(_gpioInterruptPin);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private ushort ReadConfigRegister()
|
||||
{
|
||||
SpanByte retBuf = new byte[2];
|
||||
SpanByte request = new byte[1]
|
||||
{
|
||||
(byte)Register.ADC_CONFIG_REG_ADDR
|
||||
};
|
||||
|
||||
_i2cDevice.WriteRead(request, retBuf);
|
||||
return BinaryPrimitives.ReadUInt16BigEndian(retBuf);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wait until the current conversion finishes.
|
||||
/// This method must only be called in powerdown mode, otherwise it would timeout, since the busy bit never changes.
|
||||
/// Due to that, we always write the configuration first in power down mode and then enable the continuous bit.
|
||||
/// </summary>
|
||||
/// <exception cref="TimeoutException">A timeout occurred waiting for the ADC to finish the conversion</exception>
|
||||
private void WaitWhileBusy()
|
||||
{
|
||||
// In powerdown-mode, wait until the busy bit goes high
|
||||
ushort reg = ReadConfigRegister();
|
||||
int timeout = 10000; // microseconds
|
||||
while ((reg & 0x8000) == 0 && (timeout > 0))
|
||||
{
|
||||
DelayHelper.DelayMicroseconds(2, true);
|
||||
timeout -= 2;
|
||||
reg = ReadConfigRegister();
|
||||
}
|
||||
|
||||
if (timeout <= 0)
|
||||
{
|
||||
throw new TimeoutException("Timeout waiting for ADC to complete conversion");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read Raw Data.
|
||||
/// If in PowerDown (single-shot) mode, one new sample is requested first.
|
||||
/// </summary>
|
||||
/// <returns>Raw Value</returns>
|
||||
public short ReadRaw()
|
||||
{
|
||||
if (DeviceMode == DeviceMode.PowerDown)
|
||||
{
|
||||
// If we are in powerdown (single-conversion) mode, we have to set the configuration before each read, otherwise
|
||||
// we keep getting the same stored value.
|
||||
SetConfig();
|
||||
}
|
||||
|
||||
return ReadRawInternal();
|
||||
}
|
||||
|
||||
private short ReadRawInternal()
|
||||
{
|
||||
short val;
|
||||
SpanByte readBuff = new byte[2];
|
||||
|
||||
_i2cDevice.WriteByte((byte)Register.ADC_CONVERSION_REG_ADDR);
|
||||
_i2cDevice.Read(readBuff);
|
||||
|
||||
val = BinaryPrimitives.ReadInt16BigEndian(readBuff);
|
||||
|
||||
return val;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the next raw value, first switching to the given input and ranges.
|
||||
/// </summary>
|
||||
/// <param name="inputMultiplexer">New input multiplexer setting</param>
|
||||
/// <returns>Measured value as short</returns>
|
||||
/// <remarks>
|
||||
/// For performance reasons, it is advised to use this method if quick readings with different input channels are required,
|
||||
/// instead of setting all the properties first and then calling <see cref="ReadRaw()"/>.
|
||||
/// </remarks>
|
||||
public short ReadRaw(InputMultiplexer inputMultiplexer) => ReadRaw(inputMultiplexer, MeasuringRange, DataRate);
|
||||
|
||||
/// <summary>
|
||||
/// Reads the next raw value, first switching to the given input and ranges.
|
||||
/// </summary>
|
||||
/// <param name="inputMultiplexer">New input multiplexer setting</param>
|
||||
/// <param name="measuringRange">New measuring range</param>
|
||||
/// <param name="dataRate">New data rate</param>
|
||||
/// <returns>Measured value as short</returns>
|
||||
/// <remarks>
|
||||
/// For performance reasons, it is advised to use this method if quick readings with different settings
|
||||
/// (i.e. different input channels) are required, instead of setting all the properties first and then
|
||||
/// calling <see cref="ReadRaw()"/>.
|
||||
/// </remarks>
|
||||
public short ReadRaw(InputMultiplexer inputMultiplexer, MeasuringRange measuringRange, DataRate dataRate)
|
||||
{
|
||||
if (inputMultiplexer != InputMultiplexer || measuringRange != MeasuringRange || dataRate != DataRate)
|
||||
{
|
||||
_inputMultiplexer = inputMultiplexer;
|
||||
_measuringRange = measuringRange;
|
||||
_dataRate = dataRate;
|
||||
SetConfig();
|
||||
// We just set the config, so no need to query another sample
|
||||
return ReadRawInternal();
|
||||
}
|
||||
|
||||
return ReadRaw();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the electric potential (voltage) of the currently selected input.
|
||||
/// </summary>
|
||||
/// <returns>The measured voltage of the currently selected input channel. In volts. </returns>
|
||||
public ElectricPotential ReadVoltage()
|
||||
{
|
||||
short raw = ReadRaw();
|
||||
return RawToVoltage(raw);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the electric potential (voltage) of the given channel, performs a measurement first
|
||||
/// </summary>
|
||||
/// <param name="inputMultiplexer">Channel to use</param>
|
||||
/// <returns>The voltage at the selected channel</returns>
|
||||
public ElectricPotential ReadVoltage(InputMultiplexer inputMultiplexer)
|
||||
{
|
||||
short raw = ReadRaw(inputMultiplexer, MeasuringRange, DataRate);
|
||||
return RawToVoltage(raw);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convert Raw Data to Voltage
|
||||
/// </summary>
|
||||
/// <param name="val">Raw Data</param>
|
||||
/// <returns>Voltage, based on the current measuring range</returns>
|
||||
public ElectricPotential RawToVoltage(short val)
|
||||
{
|
||||
double resolution;
|
||||
|
||||
ElectricPotential maxVoltage = MaxVoltageFromMeasuringRange(MeasuringRange);
|
||||
|
||||
resolution = 32768.0;
|
||||
return ElectricPotential.FromVolts(val * (maxVoltage.Volts / resolution));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts voltage to raw data.
|
||||
/// </summary>
|
||||
/// <param name="voltage">Input voltage</param>
|
||||
/// <returns>Corresponding raw value, based on the current measuring range</returns>
|
||||
public short VoltageToRaw(ElectricPotential voltage)
|
||||
{
|
||||
double resolution;
|
||||
ElectricPotential maxVoltage = MaxVoltageFromMeasuringRange(MeasuringRange);
|
||||
resolution = 32768.0;
|
||||
return (short)Math.Round(voltage.Volts / (maxVoltage.Volts / resolution));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the voltage assigned to the given MeasuringRange enumeration value.
|
||||
/// </summary>
|
||||
/// <param name="measuringRange">One of the <see cref="MeasuringRange"/> enumeration members</param>
|
||||
/// <returns>An electric potential (voltage).</returns>
|
||||
public ElectricPotential MaxVoltageFromMeasuringRange(MeasuringRange measuringRange)
|
||||
{
|
||||
double voltage = measuringRange switch
|
||||
{
|
||||
MeasuringRange.FS6144 => 6.144,
|
||||
MeasuringRange.FS4096 => 4.096,
|
||||
MeasuringRange.FS2048 => 2.048,
|
||||
MeasuringRange.FS1024 => 1.024,
|
||||
MeasuringRange.FS0512 => 0.512,
|
||||
MeasuringRange.FS0256 => 0.256,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(measuringRange), "Unknown measuring range used")
|
||||
};
|
||||
|
||||
return ElectricPotential.FromVolts(voltage);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the sampling frequency in Hz for the given data rate enumeration member.
|
||||
/// </summary>
|
||||
/// <param name="dataRate">One of the <see cref="DataRate"/> enumeration members.</param>
|
||||
/// <returns>A frequency, in Hertz</returns>
|
||||
public double FrequencyFromDataRate(DataRate dataRate) => dataRate switch
|
||||
{
|
||||
DataRate.SPS008 => 8.0,
|
||||
DataRate.SPS016 => 16.0,
|
||||
DataRate.SPS032 => 32.0,
|
||||
DataRate.SPS064 => 64.0,
|
||||
DataRate.SPS128 => 128.0,
|
||||
DataRate.SPS250 => 250.0,
|
||||
DataRate.SPS475 => 475.0,
|
||||
DataRate.SPS860 => 860.0,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(dataRate), "Unknown data rate used")
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Cleanup.
|
||||
/// Failing to dispose this class, especially when callbacks are active, may lead to undefined behavior.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (_i2cDevice is object)
|
||||
{
|
||||
DisableAlertReadyPin();
|
||||
_i2cDevice.Dispose();
|
||||
_i2cDevice = null!;
|
||||
}
|
||||
|
||||
if (_shouldDispose)
|
||||
{
|
||||
_gpioController?.Dispose();
|
||||
_gpioController = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,89 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="Current" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup Label="Globals">
|
||||
<NanoFrameworkProjectSystemPath>$(MSBuildToolsPath)..\..\..\nanoFramework\v1.0\</NanoFrameworkProjectSystemPath>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(NanoFrameworkProjectSystemPath)NFProjectSystem.Default.props" Condition="Exists('$(NanoFrameworkProjectSystemPath)NFProjectSystem.Default.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectTypeGuids>{11A8DD76-328B-46DF-9F39-F559912D0360};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
|
||||
<ProjectGuid>{2004849F-2ADE-41A0-A825-F17625F461D9}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<RootNamespace>Iot.Device.Ads1115</RootNamespace>
|
||||
<AssemblyName>Iot.Device.Ads1115</AssemblyName>
|
||||
<TargetFrameworkVersion>v1.0</TargetFrameworkVersion>
|
||||
<DocumentationFile>bin\$(Configuration)\Iot.Device.Ads1115.xml</DocumentationFile>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(NanoFrameworkProjectSystemPath)NFProjectSystem.props" Condition="Exists('$(NanoFrameworkProjectSystemPath)NFProjectSystem.props')" />
|
||||
<ItemGroup>
|
||||
<Reference Include="mscorlib, Version=1.10.4.0, Culture=neutral, PublicKeyToken=c07d481e9758c731">
|
||||
<HintPath>packages\nanoFramework.CoreLibrary.1.10.4-preview.11\lib\mscorlib.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
<SpecificVersion>True</SpecificVersion>
|
||||
</Reference>
|
||||
<Reference Include="nanoFramework.Runtime.Events, Version=1.9.0.0, Culture=neutral, PublicKeyToken=c07d481e9758c731">
|
||||
<HintPath>packages\nanoFramework.Runtime.Events.1.9.0-preview.26\lib\nanoFramework.Runtime.Events.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
<SpecificVersion>True</SpecificVersion>
|
||||
</Reference>
|
||||
<Reference Include="System.Device.Gpio, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c07d481e9758c731">
|
||||
<HintPath>packages\nanoFramework.System.Device.Gpio.1.0.0-preview.40\lib\System.Device.Gpio.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
<SpecificVersion>True</SpecificVersion>
|
||||
</Reference>
|
||||
<Reference Include="System.Device.I2c, Version=1.0.1.0, Culture=neutral, PublicKeyToken=c07d481e9758c731">
|
||||
<HintPath>packages\nanoFramework.System.Device.I2c.1.0.1-preview.33\lib\System.Device.I2c.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
<SpecificVersion>True</SpecificVersion>
|
||||
</Reference>
|
||||
<Reference Include="System.Math, Version=1.4.0.0, Culture=neutral, PublicKeyToken=c07d481e9758c731">
|
||||
<HintPath>packages\nanoFramework.System.Math.1.4.0-preview.5\lib\System.Math.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
<SpecificVersion>True</SpecificVersion>
|
||||
</Reference>
|
||||
<Reference Include="UnitsNet.ElectricPotential">
|
||||
<HintPath>packages\UnitsNet.nanoFramework.ElectricPotential.4.91.0\lib\UnitsNet.ElectricPotential.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="UnitsNet.Length">
|
||||
<HintPath>packages\UnitsNet.nanoFramework.Length.4.91.0\lib\UnitsNet.Length.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="packages.config" />
|
||||
<Compile Include="I2cAddress.cs" />
|
||||
<Compile Include="ComparatorLatching.cs" />
|
||||
<Compile Include="ComparatorMode.cs" />
|
||||
<Compile Include="ComparatorPolarity.cs" />
|
||||
<Compile Include="ComparatorQueue.cs" />
|
||||
<Compile Include="DataRate.cs" />
|
||||
<Compile Include="DeviceMode.cs" />
|
||||
<Compile Include="InputMultiplexer.cs" />
|
||||
<Compile Include="MeasuringRange.cs" />
|
||||
<Compile Include="Register.cs" />
|
||||
<Compile Include="Ads1115.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<None Include="*.md" />
|
||||
</ItemGroup>
|
||||
<Import Project="..\..\src\Stopwatch\Stopwatch.projitems" Label="Shared" />
|
||||
<Import Project="..\..\src\BinaryPrimitives\BinaryPrimitives.projitems" Label="Shared" />
|
||||
<Import Project="$(NanoFrameworkProjectSystemPath)NFProjectSystem.CSharp.targets" Condition="Exists('$(NanoFrameworkProjectSystemPath)NFProjectSystem.CSharp.targets')" />
|
||||
<ProjectExtensions>
|
||||
<ProjectCapabilities>
|
||||
<ProjectConfigurationsDeclaredAsItems />
|
||||
</ProjectCapabilities>
|
||||
</ProjectExtensions>
|
||||
<Import Project="packages\Nerdbank.GitVersioning.3.4.194\build\Nerdbank.GitVersioning.targets" Condition="Exists('packages\Nerdbank.GitVersioning.3.4.194\build\Nerdbank.GitVersioning.targets')" />
|
||||
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
|
||||
<PropertyGroup>
|
||||
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}.</ErrorText>
|
||||
</PropertyGroup>
|
||||
<Error Condition="!Exists('packages\Nerdbank.GitVersioning.3.4.194\build\Nerdbank.GitVersioning.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Nerdbank.GitVersioning.3.4.194\build\Nerdbank.GitVersioning.targets'))" />
|
||||
</Target>
|
||||
</Project>
|
|
@ -0,0 +1,42 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
|
||||
<metadata>
|
||||
<id>nanoFramework.Iot.Device.Ads1115</id>
|
||||
<version>$version$</version>
|
||||
<title>nanoFramework.Iot.Device.Ads1115</title>
|
||||
<authors>nanoFramework project contributors</authors>
|
||||
<owners>nanoFramework project contributors,dotnetfoundation</owners>
|
||||
<requireLicenseAcceptance>false</requireLicenseAcceptance>
|
||||
<license type="file">LICENSE.md</license>
|
||||
<releaseNotes>
|
||||
</releaseNotes>
|
||||
<developmentDependency>false</developmentDependency>
|
||||
<projectUrl>https://github.com/nanoframework/nanoFramework.IoT.Device</projectUrl>
|
||||
<iconUrl>https://secure.gravatar.com/avatar/97d0e092247f0716db6d4b47b7d1d1ad</iconUrl>
|
||||
<icon>images\nf-logo.png</icon>
|
||||
<repository type="git" url="https://github.com/nanoframework/nanoFramework.IoT.Device" commit="$commit$" />
|
||||
<copyright>Copyright (c) .NET Foundation and Contributors</copyright>
|
||||
<description>This package includes the .NET IoT Core binding Iot.Device.Ads1115 for .NET nanoFramework C# projects.</description>
|
||||
<summary>Iot.Device.Ads1115 assembly for .NET nanoFramework C# projects</summary>
|
||||
<tags>nanoFramework C# csharp netmf netnf Iot.Device.Ads1115</tags>
|
||||
<dependencies>
|
||||
<dependency id="nanoFramework.CoreLibrary" version="1.10.4-preview.4" />
|
||||
<dependency id="nanoFramework.Runtime.Events" version="1.9.0-preview.26" />
|
||||
<dependency id="nanoFramework.System.Device.Gpio" version="1.0.0-preview.40" />
|
||||
<dependency id="nanoFramework.System.Device.I2c" version="1.0.1-preview.33" />
|
||||
<dependency id="nanoFramework.System.Math" version="1.4.0-preview.5" />
|
||||
<dependency id="UnitsNet.nanoFramework.ElectricPotential" version="4.91.0" />
|
||||
<dependency id="UnitsNet.nanoFramework.Length" version="4.91.0" />
|
||||
</dependencies>
|
||||
</metadata>
|
||||
<files>
|
||||
<file src="bin\Release\Iot.Device.Ads1115.dll" target="lib\Iot.Device.Ads1115.dll" />
|
||||
<file src="bin\Release\Iot.Device.Ads1115.pdb" target="lib\Iot.Device.Ads1115.pdb" />
|
||||
<file src="bin\Release\Iot.Device.Ads1115.pdbx" target="lib\Iot.Device.Ads1115.pdbx" />
|
||||
<file src="bin\Release\Iot.Device.Ads1115.pe" target="lib\Iot.Device.Ads1115.pe" />
|
||||
<file src="bin\Release\Iot.Device.Ads1115.xml" target="lib\Iot.Device.Ads1115.xml" />
|
||||
<file src="readme.md" target="" />
|
||||
<file src="..\..\assets\nf-logo.png" target="images" />
|
||||
<file src="..\..\LICENSE.md" target="" />
|
||||
</files>
|
||||
</package>
|
|
@ -0,0 +1,42 @@
|
|||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 16
|
||||
VisualStudioVersion = 16.0.30413.136
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{11A8DD76-328B-46DF-9F39-F559912D0360}") = "Ads1115", "Ads1115.nfproj", "{2004849F-2ADE-41A0-A825-F17625F461D9}"
|
||||
EndProject
|
||||
Project("{11A8DD76-328B-46DF-9F39-F559912D0360}") = "Ads1115.Samples", "samples\Ads1115.Samples.nfproj", "{85C2E5A8-9322-42C5-95E4-46CFCE11BEC5}"
|
||||
EndProject
|
||||
Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Stopwatch", "..\..\src\Stopwatch\Stopwatch.shproj", "{875D133B-033B-4D11-B1A2-DEF898349AD5}"
|
||||
EndProject
|
||||
Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "BinaryPrimitives", "..\..\src\BinaryPrimitives\BinaryPrimitives.shproj", "{E86896A2-B40C-4C03-B0E3-979DAF764CD6}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SharedMSBuildProjectFiles) = preSolution
|
||||
..\..\src\Stopwatch\Stopwatch.projitems*{875d133b-033b-4d11-b1a2-def898349ad5}*SharedItemsImports = 13
|
||||
..\..\src\BinaryPrimitives\BinaryPrimitives.projitems*{e86896a2-b40c-4c03-b0e3-979daf764cd6}*SharedItemsImports = 13
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{2004849F-2ADE-41A0-A825-F17625F461D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{2004849F-2ADE-41A0-A825-F17625F461D9}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{2004849F-2ADE-41A0-A825-F17625F461D9}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
|
||||
{2004849F-2ADE-41A0-A825-F17625F461D9}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{2004849F-2ADE-41A0-A825-F17625F461D9}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{2004849F-2ADE-41A0-A825-F17625F461D9}.Release|Any CPU.Deploy.0 = Release|Any CPU
|
||||
{85C2E5A8-9322-42C5-95E4-46CFCE11BEC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{85C2E5A8-9322-42C5-95E4-46CFCE11BEC5}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{85C2E5A8-9322-42C5-95E4-46CFCE11BEC5}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
|
||||
{85C2E5A8-9322-42C5-95E4-46CFCE11BEC5}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{85C2E5A8-9322-42C5-95E4-46CFCE11BEC5}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{85C2E5A8-9322-42C5-95E4-46CFCE11BEC5}.Release|Any CPU.Deploy.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {7ACBAC82-A0D4-48A9-8B12-63E8DC55360D}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
|
@ -0,0 +1,17 @@
|
|||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
|
||||
namespace Iot.Device.Ads1115
|
||||
{
|
||||
/// <summary>
|
||||
/// Set Comparator Latching
|
||||
/// </summary>
|
||||
public enum ComparatorLatching
|
||||
{
|
||||
/// <summary>Non-latching</summary>
|
||||
NonLatching = 0x00,
|
||||
|
||||
/// <summary>Latching</summary>
|
||||
Latching = 0x01
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
|
||||
namespace Iot.Device.Ads1115
|
||||
{
|
||||
/// <summary>
|
||||
/// Comparator Mode of Operation
|
||||
/// </summary>
|
||||
public enum ComparatorMode
|
||||
{
|
||||
/// <summary>Traditional mode</summary>
|
||||
Traditional = 0x00,
|
||||
|
||||
/// <summary>Window mode</summary>
|
||||
Window = 0x01
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
|
||||
namespace Iot.Device.Ads1115
|
||||
{
|
||||
/// <summary>
|
||||
/// Controls the Polarity of the ALERT Pin
|
||||
/// </summary>
|
||||
public enum ComparatorPolarity
|
||||
{
|
||||
/// <summary>Low</summary>
|
||||
Low = 0x00,
|
||||
|
||||
/// <summary>High</summary>
|
||||
High = 0x01
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
|
||||
namespace Iot.Device.Ads1115
|
||||
{
|
||||
/// <summary>
|
||||
/// Comparator Queue.
|
||||
/// </summary>
|
||||
public enum ComparatorQueue
|
||||
{
|
||||
/// <summary>Assert after one</summary>
|
||||
AssertAfterOne = 0x00,
|
||||
|
||||
/// <summary>Assert after two</summary>
|
||||
AssertAfterTwo = 0x01,
|
||||
|
||||
/// <summary>Assert after four</summary>
|
||||
AssertAfterFour = 0x02,
|
||||
|
||||
/// <summary>Disable</summary>
|
||||
Disable = 0x03
|
||||
}
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
|
||||
namespace Iot.Device.Ads1115
|
||||
{
|
||||
/// <summary>
|
||||
/// Control the Data Rate (SPS, sample per second)
|
||||
/// </summary>
|
||||
public enum DataRate
|
||||
{
|
||||
/// <summary>
|
||||
/// 8 SPS
|
||||
/// </summary>
|
||||
SPS008 = 0x00,
|
||||
|
||||
/// <summary>
|
||||
/// 16 SPS
|
||||
/// </summary>
|
||||
SPS016 = 0x01,
|
||||
|
||||
/// <summary>
|
||||
/// 32 SPS
|
||||
/// </summary>
|
||||
SPS032 = 0x02,
|
||||
|
||||
/// <summary>
|
||||
/// 64 SPS
|
||||
/// </summary>
|
||||
SPS064 = 0x03,
|
||||
|
||||
/// <summary>
|
||||
/// 128 SPS
|
||||
/// </summary>
|
||||
SPS128 = 0x04,
|
||||
|
||||
/// <summary>
|
||||
/// 250 SPS
|
||||
/// </summary>
|
||||
SPS250 = 0x05,
|
||||
|
||||
/// <summary>
|
||||
/// 475 SPS
|
||||
/// </summary>
|
||||
SPS475 = 0x06,
|
||||
|
||||
/// <summary>
|
||||
/// 860 SPS
|
||||
/// </summary>
|
||||
SPS860 = 0x07
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
|
||||
namespace Iot.Device.Ads1115
|
||||
{
|
||||
/// <summary>
|
||||
/// Set the Mode of ADS1115
|
||||
/// </summary>
|
||||
public enum DeviceMode
|
||||
{
|
||||
/// <summary>Continuous mode</summary>
|
||||
Continuous = 0x00,
|
||||
|
||||
/// <summary>Power down mode, the chip is shutting down after the next conversion</summary>
|
||||
PowerDown = 0x01
|
||||
}
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
|
||||
namespace Iot.Device.Ads1115
|
||||
{
|
||||
/// <summary>
|
||||
/// ADS1115 I2C Address Setting
|
||||
/// </summary>
|
||||
public enum I2cAddress
|
||||
{
|
||||
// Details in Datasheet P17 Table5
|
||||
|
||||
/// <summary>
|
||||
/// ADDR Pin connect to GND
|
||||
/// </summary>
|
||||
GND = 0x48,
|
||||
|
||||
/// <summary>
|
||||
/// ADDR Pin connect to VCC
|
||||
/// </summary>
|
||||
VCC = 0x49,
|
||||
|
||||
/// <summary>
|
||||
/// ADDR Pin connect to SDA
|
||||
/// </summary>
|
||||
SDA = 0x4A,
|
||||
|
||||
/// <summary>
|
||||
/// ADDR Pin connect to SCL
|
||||
/// </summary>
|
||||
SCL = 0x4B
|
||||
}
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
|
||||
namespace Iot.Device.Ads1115
|
||||
{
|
||||
/// <summary>
|
||||
/// Configure the Input Multiplexer
|
||||
/// </summary>
|
||||
public enum InputMultiplexer
|
||||
{
|
||||
// Details in Datasheet P12 Figure24
|
||||
|
||||
/// <summary>
|
||||
/// AIN Positive = AIN0 and AIN Negative = GND
|
||||
/// Measure the Voltage between AIN0 and GND
|
||||
/// </summary>
|
||||
AIN0 = 0x04,
|
||||
|
||||
/// <summary>
|
||||
/// AIN Positive = AIN1 and AIN Negative = GND
|
||||
/// Measure the Voltage between AIN1 and GND
|
||||
/// </summary>
|
||||
AIN1 = 0x05,
|
||||
|
||||
/// <summary>
|
||||
/// AIN Positive = AIN2 and AIN Negative = GND
|
||||
/// Measure the Voltage between AIN2 and GND
|
||||
/// </summary>
|
||||
AIN2 = 0x06,
|
||||
|
||||
/// <summary>
|
||||
/// AIN Positive = AIN3 and AIN Negative = GND
|
||||
/// Measure the Voltage between AIN3 and GND
|
||||
/// </summary>
|
||||
AIN3 = 0x07,
|
||||
|
||||
/// <summary>
|
||||
/// AIN Positive = AIN0 and AIN Negative = AIN1
|
||||
/// Measure the Voltage between AIN0 and AIN1
|
||||
/// </summary>
|
||||
AIN0_AIN1 = 0x00,
|
||||
|
||||
/// <summary>
|
||||
/// AIN Positive = AIN0 and AIN Negative = AIN3
|
||||
/// Measure the Voltage between AIN0 and AIN3
|
||||
/// </summary>
|
||||
AIN0_AIN3 = 0x01,
|
||||
|
||||
/// <summary>
|
||||
/// AIN Positive = AIN1 and AIN Negative = AIN3
|
||||
/// Measure the Voltage between AIN1 and AIN3
|
||||
/// </summary>
|
||||
AIN1_AIN3 = 0x02,
|
||||
|
||||
/// <summary>
|
||||
/// AIN Positive = AIN2 and AIN Negative = AIN3
|
||||
/// Measure the Voltage between AIN2 and AIN3
|
||||
/// </summary>
|
||||
AIN2_AIN3 = 0x03,
|
||||
}
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
|
||||
namespace Iot.Device.Ads1115
|
||||
{
|
||||
/// <summary>
|
||||
/// Configure the Programmable Gain Amplifier, i.e. Measuring Range
|
||||
/// Note that the maximum input value on any input pin is VDD+0.3V and the maximum value that can be measured is VDD.
|
||||
/// So if the supply voltage is 3.3V, using FS6144 may not be useful, because it just reduces the accuracy to 14 bit
|
||||
/// (excluding the sign bit).
|
||||
/// </summary>
|
||||
public enum MeasuringRange
|
||||
{
|
||||
// Details in Datasheet P19
|
||||
|
||||
/// <summary>
|
||||
/// ±6.144V.
|
||||
/// </summary>
|
||||
FS6144 = 0x00,
|
||||
|
||||
/// <summary>
|
||||
/// ±4.096V
|
||||
/// </summary>
|
||||
FS4096 = 0x01,
|
||||
|
||||
/// <summary>
|
||||
/// ±2.048V
|
||||
/// </summary>
|
||||
FS2048 = 0x02,
|
||||
|
||||
/// <summary>
|
||||
/// ±1.024V
|
||||
/// </summary>
|
||||
FS1024 = 0x03,
|
||||
|
||||
/// <summary>
|
||||
/// ±0.512V
|
||||
/// </summary>
|
||||
FS0512 = 0x04,
|
||||
|
||||
/// <summary>
|
||||
/// ±0.256V
|
||||
/// </summary>
|
||||
FS0256 = 0x05
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
[assembly: AssemblyTitle("Iot.Device.Ads1115")]
|
||||
[assembly: AssemblyCompany("nanoFramework Contributors")]
|
||||
[assembly: AssemblyCopyright("Copyright(c).NET Foundation and Contributors")]
|
||||
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
/////////////////////////////////////////////////////////////////
|
||||
// This attribute is mandatory when building Interop libraries //
|
||||
[assembly: AssemblyNativeVersion("0.0.0.0")]
|
||||
/////////////////////////////////////////////////////////////////
|
Двоичный файл не отображается.
После Ширина: | Высота: | Размер: 128 KiB |
|
@ -0,0 +1,33 @@
|
|||
# ADS1115 - Analog to Digital Converter
|
||||
ADS1115 is an Analog-to-Digital converter (ADC) with 16 bits of resolution.
|
||||
|
||||
## Sensor Image
|
||||
![](sensor.jpg)
|
||||
|
||||
## Usage
|
||||
```C#
|
||||
// set I2C bus ID: 1
|
||||
// ADS1115 Addr Pin connect to GND
|
||||
I2cConnectionSettings settings = new I2cConnectionSettings(1, (int)I2cAddress.GND);
|
||||
I2cDevice device = I2cDevice.Create(settings);
|
||||
|
||||
// pass in I2cDevice
|
||||
// measure the voltage AIN0
|
||||
// set the maximum range to 6.144V
|
||||
using (Ads1115 adc = new Ads1115(device, InputMultiplexer.AIN0, MeasuringRange.FS6144))
|
||||
{
|
||||
// read raw data form the sensor
|
||||
short raw = adc.ReadRaw();
|
||||
// raw data convert to voltage
|
||||
double voltage = adc.RawToVoltage(raw);
|
||||
}
|
||||
```
|
||||
|
||||
See the samples project for more examples and usage for different applications.
|
||||
|
||||
If you want to use the interrupt pin, the pulses generated by the ADS1115 might be to short to be properly recognized in the software, i.e. on a Raspberry Pi. The schematic below shows a way of increasing the pulse length so that it is properly recognized (from about 10us to 150us). This uses discrete electronics, but an implementation with an NE555 or equivalent would likely work as well (Just note that you need a type that works at 3.3V).
|
||||
|
||||
![](Pulse_lengthener_schema.png)
|
||||
|
||||
## References
|
||||
https://cdn-shop.adafruit.com/datasheets/ads1115.pdf
|
|
@ -0,0 +1,16 @@
|
|||
// Licensed to the .NET Foundation under one or more agreements.
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
|
||||
namespace Iot.Device.Ads1115
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers of ADS1115
|
||||
/// </summary>
|
||||
internal enum Register : byte
|
||||
{
|
||||
ADC_CONVERSION_REG_ADDR = 0x00,
|
||||
ADC_CONFIG_REG_ADDR = 0x01,
|
||||
ADC_CONFIG_REG_LO_THRESH = 0x02,
|
||||
ADC_CONFIG_REG_HI_THRESH = 0x03
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
adc
|
|
@ -0,0 +1,11 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="nanoFramework.CoreLibrary" version="1.10.4-preview.11" targetFramework="netnanoframework10" />
|
||||
<package id="nanoFramework.Runtime.Events" version="1.9.0-preview.26" targetFramework="netnanoframework10" />
|
||||
<package id="nanoFramework.System.Device.Gpio" version="1.0.0-preview.40" targetFramework="netnanoframework10" />
|
||||
<package id="nanoFramework.System.Device.I2c" version="1.0.1-preview.33" targetFramework="netnanoframework10" />
|
||||
<package id="nanoFramework.System.Math" version="1.4.0-preview.5" targetFramework="netnanoframework10" />
|
||||
<package id="UnitsNet.nanoFramework.ElectricPotential" version="4.91.0" targetFramework="netnanoframework10" />
|
||||
<package id="UnitsNet.nanoFramework.Length" version="4.91.0" targetFramework="netnanoframework10" />
|
||||
<package id="Nerdbank.GitVersioning" version="3.4.194" developmentDependency="true" targetFramework="netnanoframework10" />
|
||||
</packages>
|
Двоичный файл не отображается.
Двоичный файл не отображается.
После Ширина: | Высота: | Размер: 108 KiB |
|
@ -0,0 +1,66 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="Current" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup Label="Globals">
|
||||
<NanoFrameworkProjectSystemPath>$(MSBuildToolsPath)..\..\..\nanoFramework\v1.0\</NanoFrameworkProjectSystemPath>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(NanoFrameworkProjectSystemPath)NFProjectSystem.Default.props" Condition="Exists('$(NanoFrameworkProjectSystemPath)NFProjectSystem.Default.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectTypeGuids>{11A8DD76-328B-46DF-9F39-F559912D0360};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
|
||||
<ProjectGuid>{85C2E5A8-9322-42C5-95E4-46CFCE11BEC5}</ProjectGuid>
|
||||
<OutputType>Exe</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<RootNamespace>Iot.Device.Ads1115.Samples</RootNamespace>
|
||||
<AssemblyName>Iot.Device.Ads1115.Samples</AssemblyName>
|
||||
<TargetFrameworkVersion>v1.0</TargetFrameworkVersion>
|
||||
<DocumentationFile>bin\$(Configuration)\Iot.Device.Ads1115.Samples.xml</DocumentationFile>
|
||||
<LangVersion>9.0</LangVersion>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(NanoFrameworkProjectSystemPath)NFProjectSystem.props" Condition="Exists('$(NanoFrameworkProjectSystemPath)NFProjectSystem.props')" />
|
||||
<ItemGroup>
|
||||
<Reference Include="mscorlib, Version=1.10.4.0, Culture=neutral, PublicKeyToken=c07d481e9758c731">
|
||||
<HintPath>..\packages\nanoFramework.CoreLibrary.1.10.4-preview.11\lib\mscorlib.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
<SpecificVersion>True</SpecificVersion>
|
||||
</Reference>
|
||||
<Reference Include="nanoFramework.Runtime.Events, Version=1.9.0.0, Culture=neutral, PublicKeyToken=c07d481e9758c731">
|
||||
<HintPath>..\packages\nanoFramework.Runtime.Events.1.9.0-preview.26\lib\nanoFramework.Runtime.Events.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
<SpecificVersion>True</SpecificVersion>
|
||||
</Reference>
|
||||
<Reference Include="System.Device.Gpio, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c07d481e9758c731">
|
||||
<HintPath>..\packages\nanoFramework.System.Device.Gpio.1.0.0-preview.40\lib\System.Device.Gpio.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
<SpecificVersion>True</SpecificVersion>
|
||||
</Reference>
|
||||
<Reference Include="System.Device.I2c, Version=1.0.1.0, Culture=neutral, PublicKeyToken=c07d481e9758c731">
|
||||
<HintPath>..\packages\nanoFramework.System.Device.I2c.1.0.1-preview.33\lib\System.Device.I2c.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
<SpecificVersion>True</SpecificVersion>
|
||||
</Reference>
|
||||
<Reference Include="UnitsNet.ElectricPotential">
|
||||
<HintPath>..\packages\UnitsNet.nanoFramework.ElectricPotential.4.91.0\lib\UnitsNet.ElectricPotential.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="packages.config" />
|
||||
<!-- INSERT FILE REFERENCES HERE -->
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="*.cs" />
|
||||
<None Include="*.md" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Ads1115.nfproj" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(NanoFrameworkProjectSystemPath)NFProjectSystem.CSharp.targets" Condition="Exists('$(NanoFrameworkProjectSystemPath)NFProjectSystem.CSharp.targets')" />
|
||||
<ProjectExtensions>
|
||||
<ProjectCapabilities>
|
||||
<ProjectConfigurationsDeclaredAsItems />
|
||||
</ProjectCapabilities>
|
||||
</ProjectExtensions>
|
||||
</Project>
|
Двоичный файл не отображается.
После Ширина: | Высота: | Размер: 61 KiB |
|
@ -0,0 +1,143 @@
|
|||
// 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.I2c;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using System.Device.Gpio;
|
||||
using Iot.Device.Ads1115;
|
||||
using UnitsNet;
|
||||
|
||||
// set I2C bus ID: 1
|
||||
// ADS1115 Addr Pin connect to GND
|
||||
I2cConnectionSettings settings = new(1, (int)I2cAddress.GND);
|
||||
// get I2cDevice (in Linux)
|
||||
I2cDevice device = I2cDevice.Create(settings);
|
||||
|
||||
Debug.WriteLine("Press any key to continue");
|
||||
// pass in I2cDevice
|
||||
// repeatedly measure the voltage AIN0
|
||||
// set the maximum range to 4.096V
|
||||
using (Iot.Device.Ads1115.Ads1115 adc = new Iot.Device.Ads1115.Ads1115(device, InputMultiplexer.AIN0, MeasuringRange.FS4096))
|
||||
{
|
||||
int i = 0;
|
||||
while (i < 10)
|
||||
{
|
||||
// read raw data form the sensor
|
||||
short raw = adc.ReadRaw();
|
||||
// raw data convert to voltage
|
||||
ElectricPotential voltage = adc.RawToVoltage(raw);
|
||||
|
||||
Debug.WriteLine($"ADS1115 Raw Data: {raw}");
|
||||
Debug.WriteLine($"Voltage: {voltage}");
|
||||
Debug.WriteLine("");
|
||||
|
||||
// wait for 2s
|
||||
Thread.Sleep(2000);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
// Read all channels in a loop.
|
||||
// We set the device mode to power-down, because we have to wait for a sample after each channel swap anyway.
|
||||
using (var adc = new Iot.Device.Ads1115.Ads1115(device, InputMultiplexer.AIN0, MeasuringRange.FS4096, DataRate.SPS250, DeviceMode.PowerDown))
|
||||
{
|
||||
int i = 0;
|
||||
while (i < 10)
|
||||
{
|
||||
ElectricPotential voltage0 = adc.ReadVoltage(InputMultiplexer.AIN0);
|
||||
ElectricPotential voltage1 = adc.ReadVoltage(InputMultiplexer.AIN1);
|
||||
ElectricPotential voltage2 = adc.ReadVoltage(InputMultiplexer.AIN2);
|
||||
ElectricPotential voltage3 = adc.ReadVoltage(InputMultiplexer.AIN3);
|
||||
|
||||
Debug.WriteLine($"ADS1115 Voltages: (Any key to continue)");
|
||||
Debug.WriteLine($"Channel0: {voltage0:s3}");
|
||||
Debug.WriteLine($"Channel1: {voltage1:s3}");
|
||||
Debug.WriteLine($"Channel2: {voltage2:s3}");
|
||||
Debug.WriteLine($"Channel3: {voltage3:s3}");
|
||||
Debug.WriteLine("");
|
||||
|
||||
// wait for 100ms
|
||||
Thread.Sleep(100);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
// Provide a callback that triggers each time the ADC has a new value available. The DataRate parameter will define the sample rate.
|
||||
// We are using pin 23 as interrupt input from the ADC, but note that the trigger signal from the ADC may be to short to be properly recognized by the Raspberry Pi and
|
||||
// some extra electronics is required to make this reliably work (see readme).
|
||||
using (var controller = new GpioController(PinNumberingScheme.Logical))
|
||||
{
|
||||
Debug.WriteLine("This triggers an interrupt each time a new value is available on AIN0");
|
||||
using Iot.Device.Ads1115.Ads1115 adc = new Iot.Device.Ads1115.Ads1115(device, controller, 23, false, InputMultiplexer.AIN0, MeasuringRange.FS2048, DataRate.SPS250);
|
||||
Stopwatch w = Stopwatch.StartNew();
|
||||
int totalInterruptsSeen = 0;
|
||||
int previousNumberOfInterrupts = 0;
|
||||
ElectricPotential lastVoltage = default;
|
||||
adc.AlertReadyAsserted += () =>
|
||||
{
|
||||
ElectricPotential voltage = adc.ReadVoltage();
|
||||
lastVoltage = voltage;
|
||||
totalInterruptsSeen++;
|
||||
};
|
||||
|
||||
adc.EnableConversionReady();
|
||||
// (Do something else, here we print the output (as the console operations use to much time in the interrupt callback)
|
||||
int i = 0;
|
||||
while (i < 10)
|
||||
{
|
||||
int interruptsThisPeriod = totalInterruptsSeen - previousNumberOfInterrupts;
|
||||
double intsSecond = interruptsThisPeriod / w.Elapsed.TotalSeconds;
|
||||
|
||||
Debug.WriteLine($"ADS1115 Voltage: {lastVoltage}");
|
||||
Debug.WriteLine($"Interrups total: {totalInterruptsSeen}, last: {interruptsThisPeriod} Average: {intsSecond}/s (should be ~ {adc.FrequencyFromDataRate(adc.DataRate)})");
|
||||
w.Restart();
|
||||
previousNumberOfInterrupts = totalInterruptsSeen;
|
||||
// wait for 2s
|
||||
Thread.Sleep(2000);i++;
|
||||
}
|
||||
}
|
||||
|
||||
// Use an interrupt handler, but this time when the value on AIN1 exceeds a threshold
|
||||
using (var controller = new GpioController(PinNumberingScheme.Logical))
|
||||
{
|
||||
Debug.WriteLine("This triggers an interrupt as long as the value is above 2.0V (and then stays above 1.8V)");
|
||||
using Iot.Device.Ads1115.Ads1115 adc = new Iot.Device.Ads1115.Ads1115(device, controller, 23, false, InputMultiplexer.AIN1, MeasuringRange.FS4096, DataRate.SPS860);
|
||||
Stopwatch w = Stopwatch.StartNew();
|
||||
int totalInterruptsSeen = 0;
|
||||
int previousNumberOfInterrupts = 0;
|
||||
ElectricPotential lastVoltage = default;
|
||||
adc.AlertReadyAsserted += () =>
|
||||
{
|
||||
ElectricPotential voltage = adc.ReadVoltage();
|
||||
lastVoltage = voltage;
|
||||
totalInterruptsSeen++;
|
||||
};
|
||||
|
||||
adc.EnableComparator(adc.VoltageToRaw(ElectricPotential.FromVolts(1.8)), adc.VoltageToRaw(ElectricPotential.FromVolts(2.0)), ComparatorMode.Traditional, ComparatorQueue.AssertAfterTwo);
|
||||
// Do something else, here we print the output (as the console operations use to much time in the interrupt callback)
|
||||
int i = 0;
|
||||
while (i < 10)
|
||||
{
|
||||
int interruptsThisPeriod = totalInterruptsSeen - previousNumberOfInterrupts;
|
||||
double intsSecond = interruptsThisPeriod / w.Elapsed.TotalSeconds;
|
||||
|
||||
if (interruptsThisPeriod > 0)
|
||||
{
|
||||
Debug.WriteLine($"Interrupt voltage: {lastVoltage}");
|
||||
Debug.WriteLine($"Interrups total: {totalInterruptsSeen}, last: {interruptsThisPeriod} Average: {intsSecond}/s");
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.WriteLine($"Current Voltage (no interrupts seen): {adc.ReadVoltage()}");
|
||||
}
|
||||
|
||||
lastVoltage = default;
|
||||
w.Restart();
|
||||
previousNumberOfInterrupts = totalInterruptsSeen;
|
||||
// wait for 2s
|
||||
Thread.Sleep(2000);
|
||||
i++;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
[assembly: AssemblyTitle("Iot.Device.Ads1115.Samples")]
|
||||
[assembly: AssemblyCompany("nanoFramework Contributors")]
|
||||
[assembly: AssemblyCopyright("Copyright(c).NET Foundation and Contributors")]
|
||||
|
||||
[assembly: ComVisible(false)]
|
|
@ -0,0 +1,56 @@
|
|||
# ADS1115 - Samples
|
||||
|
||||
## Hardware Required
|
||||
* ADS1115
|
||||
* Rotary Potentiometer
|
||||
* Male/Female Jumper Wires
|
||||
|
||||
## Circuit
|
||||
![](ADS1115_circuit_bb.png)
|
||||
|
||||
ADS1115
|
||||
* ADDR - GND
|
||||
* SCL - SCL
|
||||
* SDA - SDA
|
||||
* VCC - 5V
|
||||
* GND - GND
|
||||
* A0 - Rotary Potentiometer Pin 2
|
||||
|
||||
Rotary Potentiometer
|
||||
* Pin 1 - 5V
|
||||
* Pin 2 - ADS1115 Pin A0
|
||||
* Pin 3 - GND
|
||||
|
||||
## Code
|
||||
```C#
|
||||
// set I2C bus ID: 1
|
||||
// ADS1115 Addr Pin connect to GND
|
||||
I2cConnectionSettings settings = new I2cConnectionSettings(1, (int)I2cAddress.GND);
|
||||
I2cDevice device = I2cDevice.Create(settings);
|
||||
|
||||
// pass in I2cDevice
|
||||
// measure the voltage AIN0
|
||||
// set the maximum range to 6.144V
|
||||
using (Ads1115 adc = new Ads1115(device, InputMultiplexer.AIN0, MeasuringRange.FS6144))
|
||||
{
|
||||
// loop
|
||||
while (true)
|
||||
{
|
||||
// read raw data form the sensor
|
||||
short raw = adc.ReadRaw();
|
||||
// raw data convert to voltage
|
||||
double voltage = adc.RawToVoltage(raw);
|
||||
|
||||
Console.WriteLine($"ADS1115 Raw Data: {raw}");
|
||||
Console.WriteLine($"Voltage: {voltage}");
|
||||
Console.WriteLine();
|
||||
|
||||
// wait for 2s
|
||||
Thread.Sleep(2000);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Results
|
||||
![](RunningResult.jpg)
|
||||
![](InterruptResult.png)
|
Двоичный файл не отображается.
После Ширина: | Высота: | Размер: 36 KiB |
|
@ -0,0 +1,8 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="nanoFramework.CoreLibrary" version="1.10.4-preview.11" targetFramework="netnanoframework10" />
|
||||
<package id="nanoFramework.Runtime.Events" version="1.9.0-preview.26" targetFramework="netnanoframework10" />
|
||||
<package id="nanoFramework.System.Device.Gpio" version="1.0.0-preview.40" targetFramework="netnanoframework10" />
|
||||
<package id="nanoFramework.System.Device.I2c" version="1.0.1-preview.33" targetFramework="netnanoframework10" />
|
||||
<package id="UnitsNet.nanoFramework.ElectricPotential" version="4.91.0" targetFramework="netnanoframework10" />
|
||||
</packages>
|
Двоичный файл не отображается.
После Ширина: | Высота: | Размер: 49 KiB |
|
@ -0,0 +1,19 @@
|
|||
{
|
||||
"$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json",
|
||||
"version": "1.0",
|
||||
"assemblyVersion": {
|
||||
"precision": "minor"
|
||||
},
|
||||
"semVer1NumericIdentifierPadding": 3,
|
||||
"nuGetPackageVersion": {
|
||||
"semVer": 2.0
|
||||
},
|
||||
"publicReleaseRefSpec": [
|
||||
"^refs/heads/develop$",
|
||||
"^refs/heads/main$",
|
||||
"^refs/heads/v\\d+(?:\\.\\d+)?$"
|
||||
],
|
||||
"cloudBuild": {
|
||||
"setAllVariables": true
|
||||
}
|
||||
}
|
Загрузка…
Ссылка в новой задаче