-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpyduino.py
254 lines (205 loc) · 7.78 KB
/
pyduino.py
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
#! /usr/bin/env python
"""pyduino - A python library to interface with the firmata arduino firmware.
Copyright (C) 2007 Joe Turner <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
# https://github.com/firmata/protocol/blob/master/protocol.md
__version__ = "0.1"
import machine
import esp
class IOError(BaseException):
def __init__(self,message):
print(message)
# Message command bytes - straight outta Pd_firmware.pde
DIGITAL_MESSAGE = 0x90 # send data for a digital pin
ANALOG_MESSAGE = 0xE0 # send data for an analog pin (or PWM)
# PULSE_MESSAGE = 0xA0 # proposed pulseIn/Out message (SysEx)
# SHIFTOUT_MESSAGE = 0xB0 # proposed shiftOut message (SysEx)
REPORT_ANALOG_PIN = 0xC0 # enable analog input by pin #
REPORT_DIGITAL_PORTS = 0xD0 # enable digital input by port pair
START_SYSEX = 0xF0 # start a MIDI SysEx message
SET_DIGITAL_PIN_MODE = 0xF4 # set a digital pin to INPUT or OUTPUT
SET_DIGITAL_PIN = 0xF5 # set digital pin value
END_SYSEX = 0xF7 # end a MIDI SysEx message
REPORT_VERSION = 0xF9 # report firmware version
SYSTEM_RESET = 0xFF # reset from MIDI
# Pin modes
DIGITAL_INPUT = 0
DIGITAL_OUTPUT = 1
ANALOG = 2
DIGITAL_PWM = 3
boards= {
'arduino': {
'digital': tuple(x for x in range(14)),
'analog': tuple(x for x in range(6)),
'pwm': (3, 5, 6, 9, 10, 11),
'use_ports': True,
'disabled': (0, 1) # Rx, Tx, Crystal
},
}
class Arduino:
"""Base class for the arduino board"""
def __init__(self, debug=True):
self.sp = machine.UART(0,57600,timeout=0)
esp.uart_nostdio(1)
self.board=boards['arduino']
self.debug=debug
flush=self.sp.read()
self.digital = [Digital(self,i) for i in self.board['digital']]
self.analog = [Analog(self,i) for i in self.board['analog']]
#Obtain firmata version
self.write(REPORT_VERSION)
self.iterate()
def read(self,n=1):
return self.sp.read(n)
def readbyte(self):
b=self.read()
while b is None:
b=self.read()
return ord(b)
def write(self,raw):
b=None
if isinstance(raw,bytearray):
b=raw
elif isinstance(raw,str):
b=raw.encode('utf8')
elif isinstance(raw,list):
b=bytearray(raw)
elif isinstance(raw,int):
b=bytearray([raw])
if self.debug: print("<>sending {}".format(b))
return self.sp.write(b)
def __repr__(self):
return "<Arduino: %s>"% self.sp
def iterate(self):
"""Read and handle a command byte from Arduino's serial port"""
data = self.read()
if data is not None:
self._process_input(ord(data))
def _process_input(self, data):
"""Process a command byte and any additional information bytes"""
if data < 0xF0:
#Multibyte
message = data & 0xF0
pin = data & 0x0F
if message == DIGITAL_MESSAGE:
if self.debug:
print("# DIGITAL_MESSAGE")
#Digital in
lsb = self.readbyte()
msb = self.readbyte()
Digital.mask = lsb + (msb << 7)
elif message == ANALOG_MESSAGE:
#Analog in
if self.debug:
print("# ANALOG_MESSAGE")
lsb = self.readbyte()
msb = self.readbyte()
self.analog[pin].value = msb << 7 | lsb
elif data == REPORT_VERSION:
if self.debug:
print("# REPORT_VERSION")
major, minor = self.read(2)
self.firmata_version = (ord(major), ord(minor))
def get_firmata_version(self):
"""Return a (major, minor) version tuple for the firmata firmware"""
return self.firmata_version
def exit(self):
"""Exit the application cleanly"""
pass
class Digital:
"""Digital pin on the arduino board"""
mask = 0
def __init__(self, sp, pin):
self.sp = sp
self.pin = pin
self.is_active = 0
self.value = 0
self.mode = DIGITAL_INPUT
def __repr__(self):
return "<Digital Port {}: {}>".format(self.pin,self.read())
def set_active(self, active):
"""Set the pin to report values"""
self.is_active = 1
pin = REPORT_DIGITAL_PORTS + self.pin
self.sp.write([pin,active])
def get_active(self):
"""Return whether the pin is reporting values"""
return self.is_active
def set_mode(self, mode):
"""Set the mode of operation for the pin
Argument:
mode, takes a value of: - DIGITAL_INPUT
- DIGITAL_OUTPUT
- DIGITAL_PWM
"""
if mode == DIGITAL_PWM and self.pin not in self.sp.board['pwm']:
error_message = "Digital pin %i does not have PWM capabilities" \
% (self.pin)
raise IOError(error_message)
if self.pin < 2:
raise IOError( "Cannot set mode for Rx/Tx pins")
self.mode = mode
command = [SET_DIGITAL_PIN_MODE,self.pin,mode]
self.sp.write(command)
def get_mode(self):
"""Return the pin mode, values explained in set_mode()"""
return self.mode
def read(self):
"""Return the output value of the pin, values explained in write()"""
if self.mode == DIGITAL_PWM:
return self.value
else:
return (self.__class__.mask & 1 << self.pin) > 0
def write(self, value):
"""Output a voltage from the pin
Argument:
value, takes a boolean if the pin is in output mode, or a value from 0
to 255 if the pin is in PWM mode
"""
if self.mode == DIGITAL_INPUT:
error_message = "Digital pin %i is not an output"% self.pin
raise IOError(error_message)
elif value != self.read():
if self.mode == DIGITAL_OUTPUT:
#Shorter variable dammit!
mask = self.__class__.mask
mask ^= 1 << self.pin
message = [SET_DIGITAL_PIN,self.pin,value]
self.sp.write(message)
#Set the attribute to the new mask
self.__class__.mask = mask
elif self.mode == DIGITAL_PWM:
self.value = value
pin = ANALOG_MESSAGE + self.pin
self.sp.write([pin,value % 128,value >> 7])
class Analog:
"""Analog pin on the arduino board"""
def __init__(self, sp, pin):
self.sp = sp
self.pin = pin
self.active = 0
self.value = 0
def __repr__(self):
return "<Analog Input {}: {}>".format(self.pin,self.value)
def set_active(self, active):
"""Set the pin to report values"""
self.active = active
pin = REPORT_ANALOG_PIN + self.pin
self.sp.write([pin,active])
def get_active(self):
"""Return whether the pin is reporting values"""
return self.active
def read(self):
"""Return the input in the range 0-1024"""
return self.value