forked from nanoframework/nanoFramework.IoT.Device
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDCMotor3Pin.cs
96 lines (81 loc) · 2.5 KB
/
DCMotor3Pin.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
92
93
94
95
96
// 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 DCMotor3Pin : DCMotor
{
private PwmChannel _pwm;
private int _pin0;
private int _pin1;
private double _speed;
public DCMotor3Pin(
PwmChannel pwmChannel,
int pin0,
int pin1,
GpioController? controller,
bool shouldDispose)
: base(controller ?? new GpioController(), controller is null ? true : shouldDispose)
{
if (pwmChannel is null)
{
throw new ArgumentNullException(nameof(pwmChannel));
}
_pwm = pwmChannel;
_pin0 = pin0;
_pin1 = pin1;
_speed = 0;
_pwm.Start();
Controller.OpenPin(_pin0, PinMode.Output);
Controller.Write(_pin0, PinValue.Low);
Controller.OpenPin(_pin1, PinMode.Output);
Controller.Write(_pin1, 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)
{
Controller.Write(_pin0, PinValue.Low);
Controller.Write(_pin1, PinValue.Low);
}
else if (val > 0.0)
{
Controller.Write(_pin0, PinValue.Low);
Controller.Write(_pin1, PinValue.High);
}
else
{
Controller.Write(_pin0, PinValue.High);
Controller.Write(_pin1, PinValue.Low);
}
_pwm.DutyCycle = val < 0 ? -val : val;
_speed = val;
}
}
public override void Dispose()
{
_speed = 0.0;
_pwm?.Dispose();
_pwm = null!;
base.Dispose();
}
}
}