2 Firmata.cpp - Firmata library v2.5.7 - 2017-08-19
3 Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved.
4 Copyright (C) 2009-2017 Jeff Hoefs. All rights reserved.
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
11 See file LICENSE.txt for further informations on licensing terms.
14 //******************************************************************************
16 //******************************************************************************
19 #include "HardwareSerial.h"
24 using namespace firmata;
26 //******************************************************************************
28 //******************************************************************************
29 // make one instance for the user to use
32 /* callback functions */
33 callbackFunction FirmataClass::currentAnalogCallback = (callbackFunction)NULL;
34 callbackFunction FirmataClass::currentDigitalCallback = (callbackFunction)NULL;
35 callbackFunction FirmataClass::currentPinModeCallback = (callbackFunction)NULL;
36 callbackFunction FirmataClass::currentPinValueCallback = (callbackFunction)NULL;
37 callbackFunction FirmataClass::currentReportAnalogCallback = (callbackFunction)NULL;
38 callbackFunction FirmataClass::currentReportDigitalCallback = (callbackFunction)NULL;
39 stringCallbackFunction FirmataClass::currentStringCallback = (stringCallbackFunction)NULL;
40 sysexCallbackFunction FirmataClass::currentSysexCallback = (sysexCallbackFunction)NULL;
41 systemCallbackFunction FirmataClass::currentSystemResetCallback = (systemCallbackFunction)NULL;
43 //******************************************************************************
45 //******************************************************************************
48 * Split a 16-bit byte into two 7-bit values and write each value.
49 * @param value The 16-bit value to be split and written separately.
51 void FirmataClass::sendValueAsTwo7bitBytes(int value)
53 marshaller.encodeByteStream(sizeof(value), reinterpret_cast<uint8_t *>(&value), sizeof(value));
57 * A helper method to write the beginning of a Sysex message transmission.
59 void FirmataClass::startSysex(void)
61 FirmataStream->write(START_SYSEX);
65 * A helper method to write the end of a Sysex message transmission.
67 void FirmataClass::endSysex(void)
69 FirmataStream->write(END_SYSEX);
72 //******************************************************************************
74 //******************************************************************************
78 * An instance named "Firmata" is created automatically for the user.
80 FirmataClass::FirmataClass()
82 parser(FirmataParser(parserBuffer, MAX_DATA_BYTES))
84 firmwareVersionCount = 0;
85 firmwareVersionVector = 0;
86 blinkVersionDisabled = false;
88 // Establish callback translation to parser callbacks
89 parser.attach(ANALOG_MESSAGE, (FirmataParser::callbackFunction)staticAnalogCallback, (void *)NULL);
90 parser.attach(DIGITAL_MESSAGE, (FirmataParser::callbackFunction)staticDigitalCallback, (void *)NULL);
91 parser.attach(REPORT_ANALOG, (FirmataParser::callbackFunction)staticReportAnalogCallback, (void *)NULL);
92 parser.attach(REPORT_DIGITAL, (FirmataParser::callbackFunction)staticReportDigitalCallback, (void *)NULL);
93 parser.attach(SET_PIN_MODE, (FirmataParser::callbackFunction)staticPinModeCallback, (void *)NULL);
94 parser.attach(SET_DIGITAL_PIN_VALUE, (FirmataParser::callbackFunction)staticPinValueCallback, (void *)NULL);
95 parser.attach(STRING_DATA, (FirmataParser::stringCallbackFunction)staticStringCallback, (void *)NULL);
96 parser.attach(START_SYSEX, (FirmataParser::sysexCallbackFunction)staticSysexCallback, (void *)NULL);
97 parser.attach(REPORT_FIRMWARE, (FirmataParser::versionCallbackFunction)staticReportFirmwareCallback, this);
98 parser.attach(REPORT_VERSION, (FirmataParser::systemCallbackFunction)staticReportVersionCallback, this);
99 parser.attach(SYSTEM_RESET, (FirmataParser::systemCallbackFunction)staticSystemResetCallback, (void *)NULL);
102 //******************************************************************************
104 //******************************************************************************
107 * Initialize the default Serial transport at the default baud of 57600.
109 void FirmataClass::begin(void)
115 * Initialize the default Serial transport and override the default baud.
116 * Sends the protocol version to the host application followed by the firmware version and name.
117 * blinkVersion is also called. To skip the call to blinkVersion, call Firmata.disableBlinkVersion()
118 * before calling Firmata.begin(baud).
119 * @param speed The baud to use. 57600 baud is the default value.
121 void FirmataClass::begin(long speed)
129 * Reassign the Firmata stream transport.
130 * @param s A reference to the Stream transport object. This can be any type of
131 * transport that implements the Stream interface. Some examples include Ethernet, WiFi
132 * and other UARTs on the board (Serial1, Serial2, etc).
134 void FirmataClass::begin(Stream &s)
138 // do not call blinkVersion() here because some hardware such as the
139 // Ethernet shield use pin 13
140 printVersion(); // send the protocol version
141 printFirmwareVersion(); // send the firmware name and version
145 * Send the Firmata protocol version to the Firmata host application.
147 void FirmataClass::printVersion(void)
149 marshaller.sendVersion(FIRMATA_PROTOCOL_MAJOR_VERSION, FIRMATA_PROTOCOL_MINOR_VERSION);
153 * Blink the Firmata protocol version to the onboard LEDs (if the board has an onboard LED).
154 * If VERSION_BLINK_PIN is not defined in Boards.h for a particular board, then this method
156 * The first series of flashes indicates the firmware major version (2 flashes = 2).
157 * The second series of flashes indicates the firmware minor version (5 flashes = 5).
159 void FirmataClass::blinkVersion(void)
161 #if defined(VERSION_BLINK_PIN)
162 if (blinkVersionDisabled) return;
163 // flash the pin with the protocol version
164 pinMode(VERSION_BLINK_PIN, OUTPUT);
165 strobeBlinkPin(VERSION_BLINK_PIN, FIRMATA_FIRMWARE_MAJOR_VERSION, 40, 210);
167 strobeBlinkPin(VERSION_BLINK_PIN, FIRMATA_FIRMWARE_MINOR_VERSION, 40, 210);
173 * Provides a means to disable the version blink sequence on the onboard LED, trimming startup
174 * time by a couple of seconds.
175 * Call this before Firmata.begin(). It only applies when using the default Serial transport.
177 void FirmataClass::disableBlinkVersion()
179 blinkVersionDisabled = true;
183 * Sends the firmware name and version to the Firmata host application. The major and minor version
184 * numbers are the first 2 bytes in the message. The following bytes are the characters of the
187 void FirmataClass::printFirmwareVersion(void)
189 if (firmwareVersionCount) { // make sure that the name has been set before reporting
190 marshaller.sendFirmwareVersion(static_cast<uint8_t>(firmwareVersionVector[0]), static_cast<uint8_t>(firmwareVersionVector[1]), (firmwareVersionCount - 2), reinterpret_cast<uint8_t *>(&firmwareVersionVector[2]));
195 * Sets the name and version of the firmware. This is not the same version as the Firmata protocol
196 * (although at times the firmware version and protocol version may be the same number).
197 * @param name A pointer to the name char array
198 * @param major The major version number
199 * @param minor The minor version number
201 void FirmataClass::setFirmwareNameAndVersion(const char *name, byte major, byte minor)
203 const char *firmwareName;
204 const char *extension;
206 // parse out ".cpp" and "applet/" that comes from using __FILE__
207 extension = strstr(name, ".cpp");
208 firmwareName = strrchr(name, '/');
212 firmwareName = strrchr(name, '\\');
215 // user passed firmware name
222 firmwareVersionCount = strlen(firmwareName) + 2;
224 firmwareVersionCount = extension - firmwareName + 2;
227 // in case anyone calls setFirmwareNameAndVersion more than once
228 free(firmwareVersionVector);
230 firmwareVersionVector = (byte *) malloc(firmwareVersionCount + 1);
231 firmwareVersionVector[firmwareVersionCount] = 0;
232 firmwareVersionVector[0] = major;
233 firmwareVersionVector[1] = minor;
234 strncpy((char *)firmwareVersionVector + 2, firmwareName, firmwareVersionCount - 2);
237 //------------------------------------------------------------------------------
238 // Serial Receive Handling
241 * A wrapper for Stream::available()
242 * @return The number of bytes remaining in the input stream buffer.
244 int FirmataClass::available(void)
246 return FirmataStream->available();
250 * Read a single int from the input stream. If the value is not = -1, pass it on to parse(byte)
252 void FirmataClass::processInput(void)
254 int inputData = FirmataStream->read(); // this is 'int' to handle -1 when no data
255 if (inputData != -1) {
256 parser.parse(inputData);
261 * Parse data from the input stream.
262 * @param inputData A single byte to be added to the parser.
264 void FirmataClass::parse(byte inputData)
266 parser.parse(inputData);
270 * @return Returns true if the parser is actively parsing data.
272 boolean FirmataClass::isParsingMessage(void)
274 return parser.isParsingMessage();
277 //------------------------------------------------------------------------------
278 // Output Stream Handling
281 * Send an analog message to the Firmata host application. The range of pins is limited to [0..15]
282 * when using the ANALOG_MESSAGE. The maximum value of the ANALOG_MESSAGE is limited to 14 bits
283 * (16384). To increase the pin range or value, see the documentation for the EXTENDED_ANALOG
285 * @param pin The analog pin to send the value of (limited to pins 0 - 15).
286 * @param value The value of the analog pin (0 - 1024 for 10-bit analog, 0 - 4096 for 12-bit, etc).
287 * The maximum value is 14-bits (16384).
289 void FirmataClass::sendAnalog(byte pin, int value)
291 marshaller.sendAnalog(pin, value);
294 /* (intentionally left out asterix here)
295 * STUB - NOT IMPLEMENTED
296 * Send a single digital pin value to the Firmata host application.
297 * @param pin The digital pin to send the value of.
298 * @param value The value of the pin.
300 void FirmataClass::sendDigital(byte pin, int value)
304 /* TODO add single pin digital messages to the protocol, this needs to
305 * track the last digital data sent so that it can be sure to change just
306 * one bit in the packet. This is complicated by the fact that the
307 * numbering of the pins will probably differ on Arduino, Wiring, and
311 // TODO: the digital message should not be sent on the serial port every
312 // time sendDigital() is called. Instead, it should add it to an int
313 // which will be sent on a schedule. If a pin changes more than once
314 // before the digital message is sent on the serial port, it should send a
315 // digital message for each change.
318 // sendDigitalPortPair();
323 * Send an 8-bit port in a single digital message (protocol v2 and later).
324 * Send 14-bits in a single digital message (protocol v1).
325 * @param portNumber The port number to send. Note that this is not the same as a "port" on the
326 * physical microcontroller. Ports are defined in order per every 8 pins in ascending order
327 * of the Arduino digital pin numbering scheme. Port 0 = pins D0 - D7, port 1 = pins D8 - D15, etc.
328 * @param portData The value of the port. The value of each pin in the port is represented by a bit.
330 void FirmataClass::sendDigitalPort(byte portNumber, int portData)
332 marshaller.sendDigitalPort(portNumber, portData);
336 * Send a sysex message where all values after the command byte are packet as 2 7-bit bytes
337 * (this is not always the case so this function is not always used to send sysex messages).
338 * @param command The sysex command byte.
339 * @param bytec The number of data bytes in the message (excludes start, command and end bytes).
340 * @param bytev A pointer to the array of data bytes to send in the message.
342 void FirmataClass::sendSysex(byte command, byte bytec, byte *bytev)
344 marshaller.sendSysex(command, bytec, bytev);
348 * Send a string to the Firmata host application.
349 * @param command Must be STRING_DATA
350 * @param string A pointer to the char string
352 void FirmataClass::sendString(byte command, const char *string)
354 if (command == STRING_DATA) {
355 marshaller.sendString(string);
360 * Send a string to the Firmata host application.
361 * @param string A pointer to the char string
363 void FirmataClass::sendString(const char *string)
365 marshaller.sendString(string);
369 * A wrapper for Stream::available().
370 * Write a single byte to the output stream.
371 * @param c The byte to be written.
373 void FirmataClass::write(byte c)
375 FirmataStream->write(c);
379 * Attach a generic sysex callback function to a command (options are: ANALOG_MESSAGE,
380 * DIGITAL_MESSAGE, REPORT_ANALOG, REPORT DIGITAL, SET_PIN_MODE and SET_DIGITAL_PIN_VALUE).
381 * @param command The ID of the command to attach a callback function to.
382 * @param newFunction A reference to the callback function to attach.
384 void FirmataClass::attach(uint8_t command, ::callbackFunction newFunction)
388 currentAnalogCallback = newFunction;
390 case DIGITAL_MESSAGE:
391 currentDigitalCallback = newFunction;
394 currentReportAnalogCallback = newFunction;
397 currentReportDigitalCallback = newFunction;
400 currentPinModeCallback = newFunction;
402 case SET_DIGITAL_PIN_VALUE:
403 currentPinValueCallback = newFunction;
409 * Attach a callback function for the SYSTEM_RESET command.
410 * @param command Must be set to SYSTEM_RESET or it will be ignored.
411 * @param newFunction A reference to the system reset callback function to attach.
413 void FirmataClass::attach(uint8_t command, systemCallbackFunction newFunction)
417 currentSystemResetCallback = newFunction;
423 * Attach a callback function for the STRING_DATA command.
424 * @param command Must be set to STRING_DATA or it will be ignored.
425 * @param newFunction A reference to the string callback function to attach.
427 void FirmataClass::attach(uint8_t command, stringCallbackFunction newFunction)
431 currentStringCallback = newFunction;
437 * Attach a generic sysex callback function to sysex command.
438 * @param command The ID of the command to attach a callback function to.
439 * @param newFunction A reference to the sysex callback function to attach.
441 void FirmataClass::attach(uint8_t command, sysexCallbackFunction newFunction)
444 currentSysexCallback = newFunction;
448 * Detach a callback function for a specified command (such as SYSTEM_RESET, STRING_DATA,
449 * ANALOG_MESSAGE, DIGITAL_MESSAGE, etc).
450 * @param command The ID of the command to detatch the callback function from.
452 void FirmataClass::detach(uint8_t command)
456 attach(command, (systemCallbackFunction)NULL);
459 attach(command, (stringCallbackFunction)NULL);
462 attach(command, (sysexCallbackFunction)NULL);
465 attach(command, (callbackFunction)NULL);
471 * @param pin The pin to get the configuration of.
472 * @return The configuration of the specified pin.
474 byte FirmataClass::getPinMode(byte pin)
476 return pinConfig[pin];
480 * Set the pin mode/configuration. The pin configuration (or mode) in Firmata represents the
481 * current function of the pin. Examples are digital input or output, analog input, pwm, i2c,
482 * serial (uart), etc.
483 * @param pin The pin to configure.
484 * @param config The configuration value for the specified pin.
486 void FirmataClass::setPinMode(byte pin, byte config)
488 if (pinConfig[pin] == PIN_MODE_IGNORE)
491 pinConfig[pin] = config;
495 * @param pin The pin to get the state of.
496 * @return The state of the specified pin.
498 int FirmataClass::getPinState(byte pin)
500 return pinState[pin];
504 * Set the pin state. The pin state of an output pin is the pin value. The state of an
505 * input pin is 0, unless the pin has it's internal pull up resistor enabled, then the value is 1.
506 * @param pin The pin to set the state of
507 * @param state Set the state of the specified pin
509 void FirmataClass::setPinState(byte pin, int state)
511 pinState[pin] = state;
516 * this is too complicated for analogReceive, but maybe for Sysex?
517 void FirmataClass::attachSysex(sysexFunction newFunction)
520 byte tmpCount = analogReceiveFunctionCount;
521 analogReceiveFunction* tmpArray = analogReceiveFunctionArray;
522 analogReceiveFunctionCount++;
523 analogReceiveFunctionArray = (analogReceiveFunction*) calloc(analogReceiveFunctionCount, sizeof(analogReceiveFunction));
524 for(i = 0; i < tmpCount; i++) {
525 analogReceiveFunctionArray[i] = tmpArray[i];
527 analogReceiveFunctionArray[tmpCount] = newFunction;
532 //******************************************************************************
534 //******************************************************************************
537 * Flashing the pin for the version number
539 * @param pin The pin the LED is attached to.
540 * @param count The number of times to flash the LED.
541 * @param onInterval The number of milliseconds for the LED to be ON during each interval.
542 * @param offInterval The number of milliseconds for the LED to be OFF during each interval.
544 void FirmataClass::strobeBlinkPin(byte pin, int count, int onInterval, int offInterval)
547 for (i = 0; i < count; i++) {
549 digitalWrite(pin, HIGH);
551 digitalWrite(pin, LOW);