forked from nanoframework/nanoFramework.IoT.Device
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDCMotor2PinWithBiDirectionalPin.cs
91 lines (78 loc) · 2.38 KB
/
DCMotor2PinWithBiDirectionalPin.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
79
80
81
82
83
84
85
86
87
88
89
90
91
// 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.Gpio;
using System.Device.Pwm;
namespace Iot.Device.DCMotor
{
/// <summary>
/// class for H-bridge controller with only one direction input and PWM input
/// </summary>
internal class DCMotor2PinWithBiDirectionalPin : DCMotor
{
private PwmChannel _pwm;
private int _dirPin;
private double _speed;
public DCMotor2PinWithBiDirectionalPin(
PwmChannel pwmChannel,
int dirpin,
GpioController? controller,
bool shouldDispose)
: base(controller ?? ((dirpin == -1) ? null : new GpioController()), controller is null || shouldDispose)
{
_pwm = pwmChannel;
_dirPin = dirpin;
_speed = 0;
_pwm.Start();
if (_dirPin == -1)
{
throw new ArgumentOutOfRangeException(nameof(_dirPin));
}
Controller.OpenPin(_dirPin, PinMode.Output);
Controller.Write(_dirPin, PinValue.Low);
}
/// <summary>
/// Gets or sets the speed of the motor.
/// Speed is a value from -1 to 1
/// 1 means maximum speed, signed value changes the direction.
/// </summary>
public override double Speed
{
get
{
return _speed;
}
set
{
double val = value < -1.0 ? -1.0 : value > 1.0 ? 1.0 : value;
if (_speed == val)
{
return;
}
if (val >= 0.0)
{
if (_dirPin != -1)
{
Controller.Write(_dirPin, PinValue.High);
}
_pwm.DutyCycle = val;
}
else
{
if (_dirPin != -1)
{
Controller.Write(_dirPin, PinValue.Low);
}
_pwm.DutyCycle = -val;
}
_speed = val;
}
}
public override void Dispose()
{
_pwm?.Dispose();
_pwm = null!;
base.Dispose();
}
}
}