forked from nanoframework/nanoFramework.IoT.Device
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDCMotor2PinNoEnable.cs
85 lines (71 loc) · 2.17 KB
/
DCMotor2PinNoEnable.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
// 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
{
internal class DCMotor2PinNoEnable : DCMotor
{
private PwmChannel _pwm;
private int _pin1;
private double _speed;
public DCMotor2PinNoEnable(
PwmChannel pwmChannel,
int pin1,
GpioController? controller,
bool shouldDispose)
: base(controller ?? ((pin1 == -1) ? null : new GpioController()), controller is null ? true : shouldDispose)
{
_pwm = pwmChannel;
_pin1 = pin1;
_speed = 0;
_pwm.Start();
if (_pin1 != -1)
{
Controller.OpenPin(_pin1, PinMode.Output);
Controller.Write(_pin1, PinValue.Low);
}
}
/// <summary>
/// Gets or sets the speed of the motor.
/// Speed is a value from 0 to 1 or -1 to 1 if direction pin has been provided.
/// 1 means maximum speed, signed value changes the direction.
/// </summary>
public override double Speed
{
get => _speed;
set
{
double val = value < -1.0 ? -1.0 : value > 1.0 ? 1.0 : value;
if (_speed == val)
{
return;
}
if (val >= 0.0)
{
if (_pin1 != -1)
{
Controller.Write(_pin1, PinValue.Low);
}
_pwm.DutyCycle = val;
}
else
{
if (_pin1 != -1)
{
Controller.Write(_pin1, PinValue.High);
}
_pwm.DutyCycle = 1.0 + val;
}
_speed = val;
}
}
public override void Dispose()
{
_pwm?.Dispose();
_pwm = null!;
base.Dispose();
}
}
}