1
+ # The program takes an initial word or phrase from
2
+ # the command line (or in the absence of a
3
+ # parameter from the first line of standard
4
+ # input). In then reads successive words or
5
+ # phrases from standard input and reports whether
6
+ # they are angrams of the first word.
7
+ #
8
+ # Author:: Dave Thomas (mailto:[email protected] )
9
+ # Copyright:: Copyright (c) 2002 The Pragmatic Programmers, LLC
10
+ # License:: Distributes under the same terms as Ruby
11
+
1
12
require "serialport"
2
13
14
+ # The main Arduino class.
15
+ # Allows managing connection to board and getting & setting pin states.
16
+
3
17
class Arduino
4
18
19
+ # initialize port and baudrate
5
20
def initialize ( port , baudrate = 115200 )
6
21
@serial = SerialPort . new port , baudrate
7
22
@serial . sync
8
- @port = port #Cannot get connected port via SerialPort class
23
+ @port = port
9
24
@outputPins = [ ]
10
25
end
11
26
27
+ # Print information about connected board
12
28
def to_s
13
29
"Arduino is on port #{ @port } at #{ @serial . baud } baudrate"
14
30
end
15
-
31
+
32
+ # Set output pins. This is a must.
16
33
def output ( *pinList )
17
34
sendData ( pinList . length )
18
35
@@ -26,22 +43,26 @@ def output(*pinList)
26
43
end
27
44
end
28
45
46
+ # Get state of a digital pin. Returns true if high and false if low.
29
47
def getState ( pin )
30
48
sendData ( '2' )
31
49
sendPin ( pin )
32
50
return formatPinState ( getData ( ) )
33
51
end
34
52
53
+ # Set a pin state to low
35
54
def setLow ( pin )
36
55
sendData ( '0' )
37
56
sendPin ( pin )
38
57
end
39
-
58
+
59
+ # Set a pin state to high
40
60
def setHigh ( pin )
41
61
sendData ( '1' )
42
62
sendPin ( pin )
43
63
end
44
-
64
+
65
+ # Write to an analog pin
45
66
def analogWrite ( pin , value )
46
67
sendData ( '3' )
47
68
fullHexValue = value . to_s ( base = 16 )
@@ -54,18 +75,21 @@ def analogWrite(pin, value)
54
75
sendData ( hexValue [ 1 ] )
55
76
end
56
77
78
+ # Read from an analog pin
57
79
def analogRead ( pin )
58
80
sendData ( '4' )
59
81
sendPin ( pin )
60
82
getData ( )
61
83
end
62
84
85
+ # set all pins to low
63
86
def turnOff
64
87
@outputPins . each do |pin |
65
88
setLow ( pin )
66
89
end
67
90
end
68
91
92
+ # close serial connection to connected board
69
93
def close
70
94
@serial . close
71
95
end
@@ -93,7 +117,6 @@ def getData
93
117
def formatPinState ( pinValue )
94
118
return true if pinValue =="1"
95
119
return false #if pinValue=="0"
96
- #raise Exception, "Data/Connection error"
97
120
end
98
121
99
122
end
0 commit comments