-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathButton.cs
More file actions
71 lines (50 loc) · 1.87 KB
/
Button.cs
File metadata and controls
71 lines (50 loc) · 1.87 KB
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
using System;
using GHIElectronics.TinyCLR.Devices.Gpio;
using GHIElectronics.TinyCLR.Pins;
namespace BrainPad {
public class Button : IOModule {
private GpioPin gpioPin;
private bool wasPressed;
private double detectPeriod = 0;
private DateTime lastPressed;
private bool WasPressed {
get {
if (this.wasPressed) {
this.wasPressed = false;
var diff = (DateTime.Now - this.lastPressed).TotalMilliseconds;
return diff <= this.detectPeriod;
}
return false;
}
set => this.wasPressed = value;
}
public Button(double button, double detectPeriod) {
var pinNum = Controller.GetGpioFromPin(button);
this.Initialize(pinNum, detectPeriod);
}
private void Initialize(int pinNum, double detectPeriod) {
if (pinNum < 0) {
throw new ArgumentException("Invalid button.");
}
this.detectPeriod = detectPeriod * 1000;
this.gpioPin = Controller.Gpio.OpenPin(pinNum);
this.gpioPin.SetDriveMode(GpioPinDriveMode.InputPullUp);
this.gpioPin.ValueChangedEdge = GpioPinEdge.FallingEdge;
this.gpioPin.ValueChanged += this.Btn_ValueChanged;
this.lastPressed = DateTime.Now;
}
private void Btn_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs e) {
this.wasPressed = true;
this.lastPressed = DateTime.Now;
}
public override double In() {
if (this.gpioPin.Read() == GpioPinValue.Low || this.WasPressed)
return 1;
return 0;
}
public override void Dispose() {
this.gpioPin?.Dispose();
this.gpioPin = null;
}
}
}