Skip to content

Commit 7083b81

Browse files
authored
create pin object and add underscore methods
1 parent e765b5b commit 7083b81

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

mrblib/gpio.rb

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,84 @@
11
module ESP32
22
module GPIO
33
include Constants
4+
5+
class << self
6+
alias :digital_write :digitalWrite
7+
alias :digital_read :digitalRead
8+
alias :analog_write :analogWrite
9+
alias :analog_read :analogRead
10+
alias :pin_mode :pinMode
11+
alias :hall_read :hallRead
12+
end
13+
14+
class Pin
15+
PIN_MODE = {
16+
pullup: ESP32::GPIO::INPUT_PULLUP,
17+
pulldown: ESP32::GPIO::INPUT_PULLDOWN,
18+
input: ESP32::GPIO::INPUT,
19+
output: ESP32::GPIO::OUTPUT,
20+
inout: ESP32::GPIO::INPUT_OUTPUT
21+
}
22+
23+
attr_reader :pin
24+
def initialize pin, mode = :input
25+
mode = PIN_MODE[mode] unless mode.is_a?(Integer)
26+
@pin = pin
27+
self.mode= mode
28+
end
29+
30+
def analog_read
31+
GPIO.analog_read pin
32+
end
33+
34+
def read
35+
GPIO.digital_read pin
36+
end
37+
38+
def analog_write val
39+
GPIO.analog_write pin, val
40+
end
41+
42+
def write val
43+
GPIO.digital_write pin, val
44+
val
45+
end
46+
47+
def high!
48+
write HIGH
49+
end
50+
51+
def low!
52+
write LOW
53+
end
54+
55+
def off
56+
low!
57+
end
58+
59+
def on
60+
high!
61+
end
62+
63+
def mode= mode
64+
GPIO.pin_mode pin, mode
65+
end
66+
67+
alias :digital_write :write
68+
alias :digital_read :read
69+
70+
def high?
71+
read == LOW
72+
end
73+
74+
def low?
75+
read == HIGH
76+
end
77+
78+
# the following only work if GPIO_MODE_INPUT_OUTPUT ie, Pin.new(io_num, :inout)
79+
def toggle
80+
write((read==HIGH) ? LOW : HIGH)
81+
end
82+
end
483
end
584
end

0 commit comments

Comments
 (0)