Remarks

Gp2d12
Status Status badge: in-progress
Source code GitHub
Datasheet(s) GitHub
NuGet package NuGet Gallery for Meadow.Foundation.Sensors.Distance.Gp2d12
Gp2d12 sensor;

public MeadowApp()
{
    Console.WriteLine("Initializing...");

    sensor = new Gp2d12(Device, Device.Pins.A03);

    //==== IObservable Pattern with an optional notification filter.
    var consumer = Gp2d12.CreateObserver(
        handler: result => {
            Console.WriteLine($"Observer filter satisfied: {result.New.Centimeters:N2}cm, old: {result.Old?.Centimeters:N2}cm");
        },
        // only notify if the change is greater than 5cm
        filter: result => {
            if (result.Old is { } old) { //c# 8 pattern match syntax. checks for !null and assigns var.
                return (result.New - old).Abs().Centimeters > 5; // returns true if > 5cm change.
            }
            return false;
        }
    );
    sensor.Subscribe(consumer);

    // classical .NET events can also be used
    sensor.DistanceUpdated += (sender, result) => {
        Console.WriteLine($"Temp Changed, temp: {result.New.Centimeters:N2}cm, old: {result.Old?.Centimeters:N2}cm");
    };

    //==== One-off reading use case/pattern
    ReadSensor().Wait();

    sensor.StartUpdating(TimeSpan.FromMilliseconds(1000));
}

protected async Task ReadSensor()
{
    var temperature = await sensor.Read();
    Console.WriteLine($"Initial temp: {temperature.Centimeters:N2}cm");
}

Sample project(s) available on GitHub

|

Code Example

Gp2d12 sensor;

public override Task Initialize()
{
    Console.WriteLine("Initializing...");

    sensor = new Gp2d12(Device, Device.Pins.A03);

    var consumer = Gp2d12.CreateObserver(
        handler: result => 
        {
            Console.WriteLine($"Observer filter satisfied: {result.New.Centimeters:N2}cm, old: {result.Old?.Centimeters:N2}cm");
        },
        // only notify if the change is greater than 5cm
        filter: result => 
        {
            if (result.Old is { } old)
            {   //c# 8 pattern match syntax. checks for !null and assigns var.
                return (result.New - old).Abs().Centimeters > 5;
            }
            return false;
        }
    );
    sensor.Subscribe(consumer);

    sensor.DistanceUpdated += (sender, result) => 
    {
        Console.WriteLine($"Temp Changed, temp: {result.New.Centimeters:N2}cm, old: {result.Old?.Centimeters:N2}cm");
    };

    return Task.CompletedTask;
}

public override async Task Run()
{
    var temperature = await sensor.Read();
    Console.WriteLine($"Initial temp: {temperature.Centimeters:N2}cm");

    sensor.StartUpdating(TimeSpan.FromMilliseconds(1000));
}

Sample project(s) available on GitHub

Characteristic Locus
Inheritance System.Object ObservableBase<Length> SensorBase<Length> > Gp2d12
Implements IRangeFinder
Inherited Members SensorBase<Length>.Updated SensorBase<Length>.samplingLock SensorBase<Length>.SamplingTokenSource SensorBase<Length>.Conditions SensorBase<Length>.IsSampling SensorBase<Length>.UpdateInterval SensorBase<Length>.RaiseEventsAndNotify(IChangeResult<>) SensorBase<Length>.Read() ObservableBase<Length>.observers ObservableBase<Length>.NotifyObservers(IChangeResult<>) Meadow.Foundation.ObservableBase<Length>.Subscribe(IObserver<>) Meadow.Foundation.ObservableBase<Length>.CreateObserver(Action<>, System.Nullable<Predicate<IChangeResult<UNIT>>>)
Namespace Meadow.Foundation.Sensors.Distance
Assembly Gp2d12.dll

Syntax

public class Gp2d12 : SensorBase<Length>, IRangeFinder

Constructors

Gp2d12(IAnalogInputController, IPin, Int32, Nullable<TimeSpan>, Nullable<Voltage>)

Create a new Gp2d12 object with an IO Device

Declaration
public Gp2d12(IAnalogInputController device, IPin analogInputPin, int sampleCount = 5, TimeSpan? sampleInterval = null, Voltage? voltage = null)

Parameters

Type Name Description
IAnalogInputController device
IPin analogInputPin
System.Int32 sampleCount
System.Nullable<TimeSpan> sampleInterval
System.Nullable<Voltage> voltage

Properties

AnalogInputPort

Declaration
protected IAnalogInputPort AnalogInputPort { get; set; }

Property Value

Type Description
IAnalogInputPort

Distance

Returns current distance

Declaration
public Length? Distance { get; }

Property Value

Type Description
System.Nullable<Length>

MaximumDistance

Maximum valid distance in cm

Declaration
public double MaximumDistance { get; }

Property Value

Type Description
System.Double

MinimumDistance

Minimum valid distance in cm

Declaration
public double MinimumDistance { get; }

Property Value

Type Description
System.Double

Methods

MeasureDistance()

Declaration
public void MeasureDistance()

RaiseEventsAndNotify(IChangeResult<Length>)

Declaration
protected override void RaiseEventsAndNotify(IChangeResult<Length> changeResult)

Parameters

Type Name Description
IChangeResult<Length> changeResult

ReadSensor()

Convenience method to get the current distance. For frequent reads, use StartSampling() and StopSampling() in conjunction with the SampleBuffer.

Declaration
protected override Task<Length> ReadSensor()

Returns

Type Description
Task<Length>

A float value that's ann average value of all the samples taken.

Overrides

Meadow.Foundation.SensorBase<Length>.ReadSensor()

StartUpdating(Nullable<TimeSpan>)

Starts continuously sampling the sensor.

This method also starts raising Changed events and IObservable subscribers getting notified. Use the readIntervalDuration parameter to specify how often events and notifications are raised/sent.

Declaration
public void StartUpdating(TimeSpan? updateInterval)

Parameters

Type Name Description
System.Nullable<TimeSpan> updateInterval

A TimeSpan that specifies how long to wait between readings. This value influences how often *Updated events are raised and IObservable consumers are notified. The default is 5 seconds.

StopUpdating()

Stops sampling the sensor.

Declaration
public void StopUpdating()

VoltageToDistance(Voltage)

Declaration
protected Length VoltageToDistance(Voltage voltage)

Parameters

Type Name Description
Voltage voltage

Returns

Type Description
Length

Events

DistanceUpdated

Raised when an received a rebound trigger signal

Declaration
public event EventHandler<IChangeResult<Length>> DistanceUpdated

Event Type

Type Description
EventHandler<IChangeResult<Length>>