├── .github ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── Adafruit_BLE_Firmata.cpp ├── Adafruit_BLE_Firmata.h ├── Adafruit_BLE_Firmata_Boards.h ├── LICENSE.txt ├── README.md ├── examples ├── BluefruitLE_nrf51822 │ ├── BluefruitConfig.h │ └── BluefruitLE_nrf51822.ino ├── CircuitPlayground_nrf51822 │ ├── BluefruitConfig.h │ └── CircuitPlayground_nrf51822.ino ├── Firmata_nRF8001 │ ├── BluefruitConfig.h │ └── Firmata_nRF8001.ino └── StandardFirmata │ ├── LICENSE.txt │ ├── Makefile │ └── StandardFirmata.ino ├── keywords.txt └── library.properties /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Thank you for opening an issue on an Adafruit Arduino library repository. To 2 | improve the speed of resolution please review the following guidelines and 3 | common troubleshooting steps below before creating the issue: 4 | 5 | - **Do not use GitHub issues for troubleshooting projects and issues.** Instead use 6 | the forums at http://forums.adafruit.com to ask questions and troubleshoot why 7 | something isn't working as expected. In many cases the problem is a common issue 8 | that you will more quickly receive help from the forum community. GitHub issues 9 | are meant for known defects in the code. If you don't know if there is a defect 10 | in the code then start with troubleshooting on the forum first. 11 | 12 | - **If following a tutorial or guide be sure you didn't miss a step.** Carefully 13 | check all of the steps and commands to run have been followed. Consult the 14 | forum if you're unsure or have questions about steps in a guide/tutorial. 15 | 16 | - **For Arduino projects check these very common issues to ensure they don't apply**: 17 | 18 | - For uploading sketches or communicating with the board make sure you're using 19 | a **USB data cable** and **not** a **USB charge-only cable**. It is sometimes 20 | very hard to tell the difference between a data and charge cable! Try using the 21 | cable with other devices or swapping to another cable to confirm it is not 22 | the problem. 23 | 24 | - **Be sure you are supplying adequate power to the board.** Check the specs of 25 | your board and plug in an external power supply. In many cases just 26 | plugging a board into your computer is not enough to power it and other 27 | peripherals. 28 | 29 | - **Double check all soldering joints and connections.** Flakey connections 30 | cause many mysterious problems. See the [guide to excellent soldering](https://learn.adafruit.com/adafruit-guide-excellent-soldering/tools) for examples of good solder joints. 31 | 32 | - **Ensure you are using an official Arduino or Adafruit board.** We can't 33 | guarantee a clone board will have the same functionality and work as expected 34 | with this code and don't support them. 35 | 36 | If you're sure this issue is a defect in the code and checked the steps above 37 | please fill in the following fields to provide enough troubleshooting information. 38 | You may delete the guideline and text above to just leave the following details: 39 | 40 | - Arduino board: **INSERT ARDUINO BOARD NAME/TYPE HERE** 41 | 42 | - Arduino IDE version (found in Arduino -> About Arduino menu): **INSERT ARDUINO 43 | VERSION HERE** 44 | 45 | - List the steps to reproduce the problem below (if possible attach a sketch or 46 | copy the sketch code in too): **LIST REPRO STEPS BELOW** 47 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Thank you for creating a pull request to contribute to Adafruit's GitHub code! 2 | Before you open the request please review the following guidelines and tips to 3 | help it be more easily integrated: 4 | 5 | - **Describe the scope of your change--i.e. what the change does and what parts 6 | of the code were modified.** This will help us understand any risks of integrating 7 | the code. 8 | 9 | - **Describe any known limitations with your change.** For example if the change 10 | doesn't apply to a supported platform of the library please mention it. 11 | 12 | - **Please run any tests or examples that can exercise your modified code.** We 13 | strive to not break users of the code and running tests/examples helps with this 14 | process. 15 | 16 | Thank you again for contributing! We will try to test and integrate the change 17 | as soon as we can, but be aware we have many GitHub repositories to manage and 18 | can't immediately respond to every request. There is no need to bump or check in 19 | on a pull request (it will clutter the discussion of the request). 20 | 21 | Also don't be worried if the request is closed or not integrated--sometimes the 22 | priorities of Adafruit's GitHub code (education, ease of use) might not match the 23 | priorities of the pull request. Don't fret, the open source community thrives on 24 | forks and GitHub makes it easy to keep your changes in a forked repo. 25 | 26 | After reviewing the guidelines above you can delete this text from the pull request. 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | release.sh 3 | -------------------------------------------------------------------------------- /Adafruit_BLE_Firmata.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Firmata.cpp - Firmata library 3 | Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. 4 | 5 | Modified for Adafruit_BLE_Uart by Limor Fried/Kevin Townsend for 6 | Adafruit Industries, 2014 7 | 8 | This library is free software; you can redistribute it and/or 9 | modify it under the terms of the GNU Lesser General Public 10 | License as published by the Free Software Foundation; either 11 | version 2.1 of the License, or (at your option) any later version. 12 | 13 | See file LICENSE.txt for further informations on licensing terms. 14 | */ 15 | 16 | //****************************************************************************** 17 | //* Includes 18 | //****************************************************************************** 19 | 20 | #include "Adafruit_BLE_Firmata.h" 21 | 22 | extern "C" { 23 | #include 24 | #include 25 | } 26 | 27 | //****************************************************************************** 28 | //* Support Functions 29 | //****************************************************************************** 30 | 31 | void Adafruit_BLE_FirmataClass::sendValueAsTwo7bitBytes(int value) 32 | { 33 | FirmataSerial.write(value & B01111111); // LSB 34 | FirmataSerial.write(value >> 7 & B01111111); // MSB 35 | } 36 | 37 | void Adafruit_BLE_FirmataClass::startSysex(void) 38 | { 39 | FirmataSerial.write(START_SYSEX); 40 | } 41 | 42 | void Adafruit_BLE_FirmataClass::endSysex(void) 43 | { 44 | FirmataSerial.write(END_SYSEX); 45 | } 46 | 47 | //****************************************************************************** 48 | //* Constructors 49 | //****************************************************************************** 50 | 51 | Adafruit_BLE_FirmataClass::Adafruit_BLE_FirmataClass(Stream &s) : FirmataSerial(s) 52 | { 53 | firmwareVersionCount = 0; 54 | systemReset(); 55 | } 56 | 57 | //****************************************************************************** 58 | //* Public Methods 59 | //****************************************************************************** 60 | 61 | /* begin method for overriding default serial bitrate */ 62 | void Adafruit_BLE_FirmataClass::begin(void) 63 | { 64 | printVersion(); 65 | printFirmwareVersion(); 66 | } 67 | 68 | void Adafruit_BLE_FirmataClass::begin(Stream &s) 69 | { 70 | FirmataSerial = s; 71 | systemReset(); 72 | printVersion(); 73 | printFirmwareVersion(); 74 | } 75 | 76 | // output the protocol version message to the serial port 77 | void Adafruit_BLE_FirmataClass::printVersion(void) { 78 | FirmataSerial.write(REPORT_VERSION); 79 | FirmataSerial.write(FIRMATA_MAJOR_VERSION); 80 | FirmataSerial.write(FIRMATA_MINOR_VERSION); 81 | } 82 | 83 | void Adafruit_BLE_FirmataClass::printFirmwareVersion(void) 84 | { 85 | byte i; 86 | 87 | if(firmwareVersionCount) { // make sure that the name has been set before reporting 88 | startSysex(); 89 | FirmataSerial.write(REPORT_FIRMWARE); 90 | FirmataSerial.write(firmwareVersionVector[0]); // major version number 91 | FirmataSerial.write(firmwareVersionVector[1]); // minor version number 92 | for(i=2; i 0) && (inputData < 128) ) { 182 | waitForData--; 183 | storedInputData[waitForData] = inputData; 184 | #ifdef BLE_DEBUG 185 | Serial.print(F(" 0x")); Serial.print(inputData, HEX); 186 | #endif 187 | 188 | if( (waitForData==0) && executeMultiByteCommand ) { // got the whole message 189 | 190 | #ifdef BLE_DEBUG 191 | Serial.println(); 192 | #endif 193 | 194 | 195 | switch(executeMultiByteCommand) { 196 | case ANALOG_MESSAGE: 197 | if(currentAnalogCallback) { 198 | (*currentAnalogCallback)(multiByteChannel, 199 | (storedInputData[0] << 7) 200 | + storedInputData[1]); 201 | } 202 | break; 203 | case DIGITAL_MESSAGE: 204 | if(currentDigitalCallback) { 205 | (*currentDigitalCallback)(multiByteChannel, 206 | (storedInputData[0] << 7) 207 | + storedInputData[1]); 208 | } 209 | break; 210 | case SET_PIN_MODE: 211 | if(currentPinModeCallback) 212 | (*currentPinModeCallback)(storedInputData[1], storedInputData[0]); 213 | break; 214 | case REPORT_ANALOG: 215 | if(currentReportAnalogCallback) 216 | (*currentReportAnalogCallback)(multiByteChannel,storedInputData[0]); 217 | break; 218 | case REPORT_DIGITAL: 219 | if(currentReportDigitalCallback) 220 | (*currentReportDigitalCallback)(multiByteChannel,storedInputData[0]); 221 | break; 222 | } 223 | executeMultiByteCommand = 0; 224 | } 225 | } else { 226 | #ifdef BLE_DEBUG 227 | Serial.print(F("\tReceived 0x")); Serial.print(inputData, HEX); 228 | #endif 229 | // remove channel info from command byte if less than 0xF0 230 | if(inputData < 0xF0) { 231 | command = inputData & 0xF0; 232 | multiByteChannel = inputData & 0x0F; 233 | } else { 234 | command = inputData; 235 | // commands in the 0xF* range don't use channel data 236 | } 237 | switch (command) { 238 | case ANALOG_MESSAGE: 239 | case DIGITAL_MESSAGE: 240 | case SET_PIN_MODE: 241 | waitForData = 2; // two data bytes needed 242 | executeMultiByteCommand = command; 243 | break; 244 | case REPORT_ANALOG: 245 | case REPORT_DIGITAL: 246 | waitForData = 1; // two data bytes needed 247 | executeMultiByteCommand = command; 248 | break; 249 | case START_SYSEX: 250 | parsingSysex = true; 251 | sysexBytesRead = 0; 252 | break; 253 | case SYSTEM_RESET: 254 | systemReset(); 255 | break; 256 | case REPORT_VERSION: 257 | printVersion(); 258 | break; 259 | } 260 | } 261 | 262 | return inputData; 263 | } 264 | 265 | //------------------------------------------------------------------------------ 266 | // Serial Send Handling 267 | 268 | // send an analog message 269 | void Adafruit_BLE_FirmataClass::sendAnalog(byte pin, int value) 270 | { 271 | // create a three byte buffer 272 | uint8_t sendbuffer[3]; 273 | 274 | // pin can only be 0-15, so chop higher bits 275 | //FirmataSerial.write(ANALOG_MESSAGE | (pin & 0xF)); 276 | sendbuffer[0] = ANALOG_MESSAGE | (pin & 0xF); 277 | 278 | //sendValueAsTwo7bitBytes(value); 279 | sendbuffer[1] = value % 128; // Tx bits 0-6 280 | sendbuffer[2] = (value >> 7) &0x7F; // Tx bits 7-13 281 | 282 | FirmataSerial.write(sendbuffer, 3); 283 | } 284 | 285 | // send a single digital pin in a digital message 286 | void Adafruit_BLE_FirmataClass::sendDigital(byte pin, int value) 287 | { 288 | /* TODO add single pin digital messages to the protocol, this needs to 289 | * track the last digital data sent so that it can be sure to change just 290 | * one bit in the packet. This is complicated by the fact that the 291 | * numbering of the pins will probably differ on Arduino, Wiring, and 292 | * other boards. The DIGITAL_MESSAGE sends 14 bits at a time, but it is 293 | * probably easier to send 8 bit ports for any board with more than 14 294 | * digital pins. 295 | */ 296 | 297 | // TODO: the digital message should not be sent on the serial port every 298 | // time sendDigital() is called. Instead, it should add it to an int 299 | // which will be sent on a schedule. If a pin changes more than once 300 | // before the digital message is sent on the serial port, it should send a 301 | // digital message for each change. 302 | 303 | // if(value == 0) 304 | // sendDigitalPortPair(); 305 | } 306 | 307 | 308 | // send 14-bits in a single digital message (protocol v1) 309 | // send an 8-bit port in a single digital message (protocol v2) 310 | void Adafruit_BLE_FirmataClass::sendDigitalPort(byte portNumber, int portData) 311 | { 312 | // create a three byte buffer 313 | uint8_t sendbuffer[3]; 314 | 315 | sendbuffer[0] = DIGITAL_MESSAGE | (portNumber & 0xF); 316 | sendbuffer[1] = (byte)portData % 128; // Tx bits 0-6 317 | sendbuffer[2] = portData >> 7; // Tx bits 7-13 318 | FirmataSerial.write(sendbuffer, 3); 319 | } 320 | 321 | 322 | void Adafruit_BLE_FirmataClass::sendSysex(byte command, byte bytec, byte* bytev) 323 | { 324 | byte i; 325 | startSysex(); 326 | FirmataSerial.write(command); 327 | for(i=0; i 21 | 22 | //#include "Boards.h" /* Hardware Abstraction Layer + Wiring/Arduino */ 23 | 24 | //#define BLE_DEBUG 25 | 26 | // move the following defines to Firmata.h? 27 | #define I2C_WRITE B00000000 28 | #define I2C_READ B00001000 29 | #define I2C_READ_CONTINUOUSLY B00010000 30 | #define I2C_STOP_READING B00011000 31 | #define I2C_READ_WRITE_MODE_MASK B00011000 32 | #define I2C_10BIT_ADDRESS_MODE_MASK B00100000 33 | 34 | #define MAX_QUERIES 8 35 | #define MINIMUM_SAMPLING_INTERVAL 10 36 | 37 | #define REGISTER_NOT_SPECIFIED -1 38 | 39 | /* Version numbers for the protocol. The protocol is still changing, so these 40 | * version numbers are important. This number can be queried so that host 41 | * software can test whether it will be compatible with the currently 42 | * installed firmware. */ 43 | #define FIRMATA_MAJOR_VERSION 2 // for non-compatible changes 44 | #define FIRMATA_MINOR_VERSION 3 // for backwards compatible changes 45 | #define FIRMATA_BUGFIX_VERSION 1 // for bugfix releases 46 | 47 | #define MAX_DATA_BYTES 32 // max number of data bytes in non-Sysex messages 48 | 49 | // message command bytes (128-255/0x80-0xFF) 50 | #define DIGITAL_MESSAGE 0x90 // send data for a digital pin 51 | #define ANALOG_MESSAGE 0xE0 // send data for an analog pin (or PWM) 52 | #define REPORT_ANALOG 0xC0 // enable analog input by pin # 53 | #define REPORT_DIGITAL 0xD0 // enable digital input by port pair 54 | // 55 | #define SET_PIN_MODE 0xF4 // set a pin to INPUT/OUTPUT/PWM/etc 56 | // 57 | #define REPORT_VERSION 0xF9 // report protocol version 58 | #define SYSTEM_RESET 0xFF // reset from MIDI 59 | // 60 | #define START_SYSEX 0xF0 // start a MIDI Sysex message 61 | #define END_SYSEX 0xF7 // end a MIDI Sysex message 62 | 63 | // extended command set using sysex (0-127/0x00-0x7F) 64 | /* 0x00-0x0F reserved for user-defined commands */ 65 | #define SERVO_CONFIG 0x70 // set max angle, minPulse, maxPulse, freq 66 | #define STRING_DATA 0x71 // a string message with 14-bits per char 67 | #define SHIFT_DATA 0x75 // a bitstream to/from a shift register 68 | #define I2C_REQUEST 0x76 // send an I2C read/write request 69 | #define I2C_REPLY 0x77 // a reply to an I2C read request 70 | #define I2C_CONFIG 0x78 // config I2C settings such as delay times and power pins 71 | #define EXTENDED_ANALOG 0x6F // analog write (PWM, Servo, etc) to any pin 72 | #define PIN_STATE_QUERY 0x6D // ask for a pin's current mode and value 73 | #define PIN_STATE_RESPONSE 0x6E // reply with pin's current mode and value 74 | #define CAPABILITY_QUERY 0x6B // ask for supported modes and resolution of all pins 75 | #define CAPABILITY_RESPONSE 0x6C // reply with supported modes and resolution 76 | #define ANALOG_MAPPING_QUERY 0x69 // ask for mapping of analog to pin numbers 77 | #define ANALOG_MAPPING_RESPONSE 0x6A // reply with mapping info 78 | #define REPORT_FIRMWARE 0x79 // report name and version of the firmware 79 | #define SAMPLING_INTERVAL 0x7A // set the poll rate of the main loop 80 | #define SYSEX_NON_REALTIME 0x7E // MIDI Reserved for non-realtime messages 81 | #define SYSEX_REALTIME 0x7F // MIDI Reserved for realtime messages 82 | // these are DEPRECATED to make the naming more consistent 83 | #define FIRMATA_STRING 0x71 // same as STRING_DATA 84 | #define SYSEX_I2C_REQUEST 0x76 // same as I2C_REQUEST 85 | #define SYSEX_I2C_REPLY 0x77 // same as I2C_REPLY 86 | #define SYSEX_SAMPLING_INTERVAL 0x7A // same as SAMPLING_INTERVAL 87 | 88 | // pin modes 89 | //#define INPUT 0x00 // defined in wiring.h 90 | //#define OUTPUT 0x01 // defined in wiring.h 91 | #define ANALOG 0x02 // analog pin in analogInput mode 92 | #define PWM 0x03 // digital pin in PWM output mode 93 | #define SERVO 0x04 // digital pin in Servo output mode 94 | #define SHIFT 0x05 // shiftIn/shiftOut mode 95 | #define I2C 0x06 // pin included in I2C setup 96 | #define TOTAL_PIN_MODES 7 97 | 98 | extern "C" { 99 | // callback function types 100 | typedef void (*callbackFunction)(byte, int); 101 | typedef void (*systemResetCallbackFunction)(void); 102 | typedef void (*stringCallbackFunction)(char*); 103 | typedef void (*sysexCallbackFunction)(byte command, byte argc, byte*argv); 104 | } 105 | 106 | 107 | // TODO make it a subclass of a generic Serial/Stream base class 108 | class Adafruit_BLE_FirmataClass 109 | { 110 | public: 111 | Adafruit_BLE_FirmataClass(Stream &s); 112 | 113 | /* Arduino constructors */ 114 | void begin(); 115 | void begin(Stream &s); 116 | /* querying functions */ 117 | void printVersion(void); 118 | void blinkVersion(void); 119 | void printFirmwareVersion(void); 120 | //void setFirmwareVersion(byte major, byte minor); // see macro below 121 | void setFirmwareNameAndVersion(const char *name, byte major, byte minor); 122 | /* serial receive handling */ 123 | int available(void); 124 | int processInput(void); 125 | /* serial send handling */ 126 | void sendAnalog(byte pin, int value); 127 | void sendDigital(byte pin, int value); // TODO implement this 128 | void sendDigitalPort(byte portNumber, int portData); 129 | void sendString(const char* string); 130 | void sendString(byte command, const char* string); 131 | void sendSysex(byte command, byte bytec, byte* bytev); 132 | /* attach & detach callback functions to messages */ 133 | void attach(byte command, callbackFunction newFunction); 134 | void attach(byte command, systemResetCallbackFunction newFunction); 135 | void attach(byte command, stringCallbackFunction newFunction); 136 | void attach(byte command, sysexCallbackFunction newFunction); 137 | void detach(byte command); 138 | 139 | 140 | /* board details */ 141 | void setUsablePins(uint8_t *digitaliopins, uint8_t num_digitaliopins, 142 | uint8_t *analogiopins, uint8_t num_analogiopins, 143 | uint8_t *pwmpins, uint8_t num_pwmpins, 144 | uint8_t *servopins, uint8_t num_servopins, 145 | uint8_t sdapin, uint8_t sclpin); 146 | 147 | boolean IS_PIN_DIGITAL(uint8_t p) { return contains(_digitaliopins,_num_digitaliopins, p); } 148 | uint8_t PIN_TO_DIGITAL(uint8_t p) { return p; } 149 | boolean IS_PIN_ANALOG(uint8_t p) { return contains(_analogiopins, _num_analogiopins, p); } 150 | uint8_t PIN_TO_ANALOG(uint8_t p); 151 | boolean IS_PIN_PWM(uint8_t p) { return contains(_pwmpins, _num_pwmpins, p); } 152 | uint8_t PIN_TO_PWM(uint8_t p) { return p; } 153 | boolean IS_PIN_SERVO(uint8_t p) { return contains(_servopins, _num_servopins, p); } 154 | uint8_t PIN_TO_SERVO(uint8_t p) { return p-2;} 155 | boolean IS_PIN_I2C(uint8_t p) { return (p == _sdapin) || (p == _sclpin); } 156 | 157 | unsigned char readPort(byte port, byte bitmask); 158 | unsigned char writePort(byte port, byte value, byte bitmask); 159 | 160 | 161 | uint8_t _num_analogiopins; 162 | 163 | private: 164 | Stream &FirmataSerial; 165 | 166 | uint8_t *_digitaliopins, _num_digitaliopins; 167 | uint8_t *_pwmpins, _num_pwmpins; 168 | uint8_t *_analogiopins; 169 | uint8_t *_servopins, _num_servopins; 170 | uint8_t _sdapin, _sclpin; 171 | 172 | boolean contains(uint8_t *set, uint8_t num, uint8_t test); 173 | uint8_t location(uint8_t *set, uint8_t num, uint8_t test); 174 | 175 | /* firmware name and version */ 176 | byte firmwareVersionCount; 177 | byte *firmwareVersionVector; 178 | /* input message handling */ 179 | byte waitForData; // this flag says the next serial input will be data 180 | byte executeMultiByteCommand; // execute this after getting multi-byte data 181 | byte multiByteChannel; // channel data for multiByteCommands 182 | byte storedInputData[MAX_DATA_BYTES]; // multi-byte data 183 | /* sysex */ 184 | boolean parsingSysex; 185 | int sysexBytesRead; 186 | /* callback functions */ 187 | callbackFunction currentAnalogCallback; 188 | callbackFunction currentDigitalCallback; 189 | callbackFunction currentReportAnalogCallback; 190 | callbackFunction currentReportDigitalCallback; 191 | callbackFunction currentPinModeCallback; 192 | systemResetCallbackFunction currentSystemResetCallback; 193 | stringCallbackFunction currentStringCallback; 194 | sysexCallbackFunction currentSysexCallback; 195 | 196 | /* private methods ------------------------------ */ 197 | void processSysexMessage(void); 198 | void systemReset(void); 199 | void pin13strobe(int count, int onInterval, int offInterval); 200 | void sendValueAsTwo7bitBytes(int value); 201 | void startSysex(void); 202 | void endSysex(void); 203 | 204 | }; 205 | 206 | extern Adafruit_BLE_FirmataClass BLE_Firmata; 207 | 208 | /*============================================================================== 209 | * MACROS 210 | *============================================================================*/ 211 | 212 | /* shortcut for setFirmwareNameAndVersion() that uses __FILE__ to set the 213 | * firmware name. It needs to be a macro so that __FILE__ is included in the 214 | * firmware source file rather than the library source file. 215 | */ 216 | #define setFirmwareVersion(x, y) setFirmwareNameAndVersion(__FILE__, x, y) 217 | 218 | #endif /* BLE_Firmata_h */ 219 | 220 | -------------------------------------------------------------------------------- /Adafruit_BLE_Firmata_Boards.h: -------------------------------------------------------------------------------- 1 | /* Boards.h - Hardware Abstraction Layer for Firmata library */ 2 | 3 | #ifndef BLE_Firmata_Boards_h 4 | #define BLE_Firmata_Boards_h 5 | 6 | #include 7 | 8 | #if defined(ARDUINO) && ARDUINO >= 100 9 | #include "Arduino.h" // for digitalRead, digitalWrite, etc 10 | #else 11 | #include "WProgram.h" 12 | #endif 13 | 14 | // Normally Servo.h must be included before Firmata.h (which then includes 15 | // this file). If Servo.h wasn't included, this allows the code to still 16 | // compile, but without support for any Servos. Hopefully that's what the 17 | // user intended by not including Servo.h 18 | #ifndef MAX_SERVOS 19 | #define MAX_SERVOS 0 20 | #endif 21 | 22 | /* 23 | Firmata Hardware Abstraction Layer 24 | 25 | Firmata is built on top of the hardware abstraction functions of Arduino, 26 | specifically digitalWrite, digitalRead, analogWrite, analogRead, and 27 | pinMode. While these functions offer simple integer pin numbers, Firmata 28 | needs more information than is provided by Arduino. This file provides 29 | all other hardware specific details. To make Firmata support a new board, 30 | only this file should require editing. 31 | 32 | The key concept is every "pin" implemented by Firmata may be mapped to 33 | any pin as implemented by Arduino. Usually a simple 1-to-1 mapping is 34 | best, but such mapping should not be assumed. This hardware abstraction 35 | layer allows Firmata to implement any number of pins which map onto the 36 | Arduino implemented pins in almost any arbitrary way. 37 | 38 | 39 | General Constants: 40 | 41 | These constants provide basic information Firmata requires. 42 | 43 | TOTAL_PINS: The total number of pins Firmata implemented by Firmata. 44 | Usually this will match the number of pins the Arduino functions 45 | implement, including any pins pins capable of analog or digital. 46 | However, Firmata may implement any number of pins. For example, 47 | on Arduino Mini with 8 analog inputs, 6 of these may be used 48 | for digital functions, and 2 are analog only. On such boards, 49 | Firmata can implement more pins than Arduino's pinMode() 50 | function, in order to accommodate those special pins. The 51 | Firmata protocol supports a maximum of 128 pins, so this 52 | constant must not exceed 128. 53 | 54 | TOTAL_ANALOG_PINS: The total number of analog input pins implemented. 55 | The Firmata protocol allows up to 16 analog inputs, accessed 56 | using offsets 0 to 15. Because Firmata presents the analog 57 | inputs using different offsets than the actual pin numbers 58 | (a legacy of Arduino's analogRead function, and the way the 59 | analog input capable pins are physically labeled on all 60 | Arduino boards), the total number of analog input signals 61 | must be specified. 16 is the maximum. 62 | 63 | VERSION_BLINK_PIN: When Firmata starts up, it will blink the version 64 | number. This constant is the Arduino pin number where a 65 | LED is connected. 66 | 67 | 68 | Pin Mapping Macros: 69 | 70 | These macros provide the mapping between pins as implemented by 71 | Firmata protocol and the actual pin numbers used by the Arduino 72 | functions. Even though such mappings are often simple, pin 73 | numbers received by Firmata protocol should always be used as 74 | input to these macros, and the result of the macro should be 75 | used with with any Arduino function. 76 | 77 | When Firmata is extended to support a new pin mode or feature, 78 | a pair of macros should be added and used for all hardware 79 | access. For simple 1:1 mapping, these macros add no actual 80 | overhead, yet their consistent use allows source code which 81 | uses them consistently to be easily adapted to all other boards 82 | with different requirements. 83 | 84 | IS_PIN_XXXX(pin): The IS_PIN macros resolve to true or non-zero 85 | if a pin as implemented by Firmata corresponds to a pin 86 | that actually implements the named feature. 87 | 88 | PIN_TO_XXXX(pin): The PIN_TO macros translate pin numbers as 89 | implemented by Firmata to the pin numbers needed as inputs 90 | to the Arduino functions. The corresponding IS_PIN macro 91 | should always be tested before using a PIN_TO macro, so 92 | these macros only need to handle valid Firmata pin 93 | numbers for the named feature. 94 | 95 | 96 | Port Access Inline Funtions: 97 | 98 | For efficiency, Firmata protocol provides access to digital 99 | input and output pins grouped by 8 bit ports. When these 100 | groups of 8 correspond to actual 8 bit ports as implemented 101 | by the hardware, these inline functions can provide high 102 | speed direct port access. Otherwise, a default implementation 103 | using 8 calls to digitalWrite or digitalRead is used. 104 | 105 | When porting Firmata to a new board, it is recommended to 106 | use the default functions first and focus only on the constants 107 | and macros above. When those are working, if optimized port 108 | access is desired, these inline functions may be extended. 109 | The recommended approach defines a symbol indicating which 110 | optimization to use, and then conditional complication is 111 | used within these functions. 112 | 113 | readPort(port, bitmask): Read an 8 bit port, returning the value. 114 | port: The port number, Firmata pins port*8 to port*8+7 115 | bitmask: The actual pins to read, indicated by 1 bits. 116 | 117 | writePort(port, value, bitmask): Write an 8 bit port. 118 | port: The port number, Firmata pins port*8 to port*8+7 119 | value: The 8 bit value to write 120 | bitmask: The actual pins to write, indicated by 1 bits. 121 | */ 122 | 123 | /*============================================================================== 124 | * Board Specific Configuration 125 | *============================================================================*/ 126 | 127 | 128 | #define VERSION_BLINK_PIN 99 129 | #define ARDUINO_PINOUT_OPTIMIZE 0 130 | 131 | 132 | 133 | 134 | #endif /* BLE_Firmata_Boards_h */ 135 | 136 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | GNU LESSER GENERAL PUBLIC LICENSE 3 | Version 2.1, February 1999 4 | 5 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 6 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 7 | Everyone is permitted to copy and distribute verbatim copies 8 | of this license document, but changing it is not allowed. 9 | 10 | [This is the first released version of the Lesser GPL. It also counts 11 | as the successor of the GNU Library Public License, version 2, hence 12 | the version number 2.1.] 13 | 14 | Preamble 15 | 16 | The licenses for most software are designed to take away your 17 | freedom to share and change it. By contrast, the GNU General Public 18 | Licenses are intended to guarantee your freedom to share and change 19 | free software--to make sure the software is free for all its users. 20 | 21 | This license, the Lesser General Public License, applies to some 22 | specially designated software packages--typically libraries--of the 23 | Free Software Foundation and other authors who decide to use it. You 24 | can use it too, but we suggest you first think carefully about whether 25 | this license or the ordinary General Public License is the better 26 | strategy to use in any particular case, based on the explanations below. 27 | 28 | When we speak of free software, we are referring to freedom of use, 29 | not price. Our General Public Licenses are designed to make sure that 30 | you have the freedom to distribute copies of free software (and charge 31 | for this service if you wish); that you receive source code or can get 32 | it if you want it; that you can change the software and use pieces of 33 | it in new free programs; and that you are informed that you can do 34 | these things. 35 | 36 | To protect your rights, we need to make restrictions that forbid 37 | distributors to deny you these rights or to ask you to surrender these 38 | rights. These restrictions translate to certain responsibilities for 39 | you if you distribute copies of the library or if you modify it. 40 | 41 | For example, if you distribute copies of the library, whether gratis 42 | or for a fee, you must give the recipients all the rights that we gave 43 | you. You must make sure that they, too, receive or can get the source 44 | code. If you link other code with the library, you must provide 45 | complete object files to the recipients, so that they can relink them 46 | with the library after making changes to the library and recompiling 47 | it. And you must show them these terms so they know their rights. 48 | 49 | We protect your rights with a two-step method: (1) we copyright the 50 | library, and (2) we offer you this license, which gives you legal 51 | permission to copy, distribute and/or modify the library. 52 | 53 | To protect each distributor, we want to make it very clear that 54 | there is no warranty for the free library. Also, if the library is 55 | modified by someone else and passed on, the recipients should know 56 | that what they have is not the original version, so that the original 57 | author's reputation will not be affected by problems that might be 58 | introduced by others. 59 | 60 | Finally, software patents pose a constant threat to the existence of 61 | any free program. We wish to make sure that a company cannot 62 | effectively restrict the users of a free program by obtaining a 63 | restrictive license from a patent holder. Therefore, we insist that 64 | any patent license obtained for a version of the library must be 65 | consistent with the full freedom of use specified in this license. 66 | 67 | Most GNU software, including some libraries, is covered by the 68 | ordinary GNU General Public License. This license, the GNU Lesser 69 | General Public License, applies to certain designated libraries, and 70 | is quite different from the ordinary General Public License. We use 71 | this license for certain libraries in order to permit linking those 72 | libraries into non-free programs. 73 | 74 | When a program is linked with a library, whether statically or using 75 | a shared library, the combination of the two is legally speaking a 76 | combined work, a derivative of the original library. The ordinary 77 | General Public License therefore permits such linking only if the 78 | entire combination fits its criteria of freedom. The Lesser General 79 | Public License permits more lax criteria for linking other code with 80 | the library. 81 | 82 | We call this license the "Lesser" General Public License because it 83 | does Less to protect the user's freedom than the ordinary General 84 | Public License. It also provides other free software developers Less 85 | of an advantage over competing non-free programs. These disadvantages 86 | are the reason we use the ordinary General Public License for many 87 | libraries. However, the Lesser license provides advantages in certain 88 | special circumstances. 89 | 90 | For example, on rare occasions, there may be a special need to 91 | encourage the widest possible use of a certain library, so that it becomes 92 | a de-facto standard. To achieve this, non-free programs must be 93 | allowed to use the library. A more frequent case is that a free 94 | library does the same job as widely used non-free libraries. In this 95 | case, there is little to gain by limiting the free library to free 96 | software only, so we use the Lesser General Public License. 97 | 98 | In other cases, permission to use a particular library in non-free 99 | programs enables a greater number of people to use a large body of 100 | free software. For example, permission to use the GNU C Library in 101 | non-free programs enables many more people to use the whole GNU 102 | operating system, as well as its variant, the GNU/Linux operating 103 | system. 104 | 105 | Although the Lesser General Public License is Less protective of the 106 | users' freedom, it does ensure that the user of a program that is 107 | linked with the Library has the freedom and the wherewithal to run 108 | that program using a modified version of the Library. 109 | 110 | The precise terms and conditions for copying, distribution and 111 | modification follow. Pay close attention to the difference between a 112 | "work based on the library" and a "work that uses the library". The 113 | former contains code derived from the library, whereas the latter must 114 | be combined with the library in order to run. 115 | 116 | GNU LESSER GENERAL PUBLIC LICENSE 117 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 118 | 119 | 0. This License Agreement applies to any software library or other 120 | program which contains a notice placed by the copyright holder or 121 | other authorized party saying it may be distributed under the terms of 122 | this Lesser General Public License (also called "this License"). 123 | Each licensee is addressed as "you". 124 | 125 | A "library" means a collection of software functions and/or data 126 | prepared so as to be conveniently linked with application programs 127 | (which use some of those functions and data) to form executables. 128 | 129 | The "Library", below, refers to any such software library or work 130 | which has been distributed under these terms. A "work based on the 131 | Library" means either the Library or any derivative work under 132 | copyright law: that is to say, a work containing the Library or a 133 | portion of it, either verbatim or with modifications and/or translated 134 | straightforwardly into another language. (Hereinafter, translation is 135 | included without limitation in the term "modification".) 136 | 137 | "Source code" for a work means the preferred form of the work for 138 | making modifications to it. For a library, complete source code means 139 | all the source code for all modules it contains, plus any associated 140 | interface definition files, plus the scripts used to control compilation 141 | and installation of the library. 142 | 143 | Activities other than copying, distribution and modification are not 144 | covered by this License; they are outside its scope. The act of 145 | running a program using the Library is not restricted, and output from 146 | such a program is covered only if its contents constitute a work based 147 | on the Library (independent of the use of the Library in a tool for 148 | writing it). Whether that is true depends on what the Library does 149 | and what the program that uses the Library does. 150 | 151 | 1. You may copy and distribute verbatim copies of the Library's 152 | complete source code as you receive it, in any medium, provided that 153 | you conspicuously and appropriately publish on each copy an 154 | appropriate copyright notice and disclaimer of warranty; keep intact 155 | all the notices that refer to this License and to the absence of any 156 | warranty; and distribute a copy of this License along with the 157 | Library. 158 | 159 | You may charge a fee for the physical act of transferring a copy, 160 | and you may at your option offer warranty protection in exchange for a 161 | fee. 162 | 163 | 2. You may modify your copy or copies of the Library or any portion 164 | of it, thus forming a work based on the Library, and copy and 165 | distribute such modifications or work under the terms of Section 1 166 | above, provided that you also meet all of these conditions: 167 | 168 | a) The modified work must itself be a software library. 169 | 170 | b) You must cause the files modified to carry prominent notices 171 | stating that you changed the files and the date of any change. 172 | 173 | c) You must cause the whole of the work to be licensed at no 174 | charge to all third parties under the terms of this License. 175 | 176 | d) If a facility in the modified Library refers to a function or a 177 | table of data to be supplied by an application program that uses 178 | the facility, other than as an argument passed when the facility 179 | is invoked, then you must make a good faith effort to ensure that, 180 | in the event an application does not supply such function or 181 | table, the facility still operates, and performs whatever part of 182 | its purpose remains meaningful. 183 | 184 | (For example, a function in a library to compute square roots has 185 | a purpose that is entirely well-defined independent of the 186 | application. Therefore, Subsection 2d requires that any 187 | application-supplied function or table used by this function must 188 | be optional: if the application does not supply it, the square 189 | root function must still compute square roots.) 190 | 191 | These requirements apply to the modified work as a whole. If 192 | identifiable sections of that work are not derived from the Library, 193 | and can be reasonably considered independent and separate works in 194 | themselves, then this License, and its terms, do not apply to those 195 | sections when you distribute them as separate works. But when you 196 | distribute the same sections as part of a whole which is a work based 197 | on the Library, the distribution of the whole must be on the terms of 198 | this License, whose permissions for other licensees extend to the 199 | entire whole, and thus to each and every part regardless of who wrote 200 | it. 201 | 202 | Thus, it is not the intent of this section to claim rights or contest 203 | your rights to work written entirely by you; rather, the intent is to 204 | exercise the right to control the distribution of derivative or 205 | collective works based on the Library. 206 | 207 | In addition, mere aggregation of another work not based on the Library 208 | with the Library (or with a work based on the Library) on a volume of 209 | a storage or distribution medium does not bring the other work under 210 | the scope of this License. 211 | 212 | 3. You may opt to apply the terms of the ordinary GNU General Public 213 | License instead of this License to a given copy of the Library. To do 214 | this, you must alter all the notices that refer to this License, so 215 | that they refer to the ordinary GNU General Public License, version 2, 216 | instead of to this License. (If a newer version than version 2 of the 217 | ordinary GNU General Public License has appeared, then you can specify 218 | that version instead if you wish.) Do not make any other change in 219 | these notices. 220 | 221 | Once this change is made in a given copy, it is irreversible for 222 | that copy, so the ordinary GNU General Public License applies to all 223 | subsequent copies and derivative works made from that copy. 224 | 225 | This option is useful when you wish to copy part of the code of 226 | the Library into a program that is not a library. 227 | 228 | 4. You may copy and distribute the Library (or a portion or 229 | derivative of it, under Section 2) in object code or executable form 230 | under the terms of Sections 1 and 2 above provided that you accompany 231 | it with the complete corresponding machine-readable source code, which 232 | must be distributed under the terms of Sections 1 and 2 above on a 233 | medium customarily used for software interchange. 234 | 235 | If distribution of object code is made by offering access to copy 236 | from a designated place, then offering equivalent access to copy the 237 | source code from the same place satisfies the requirement to 238 | distribute the source code, even though third parties are not 239 | compelled to copy the source along with the object code. 240 | 241 | 5. A program that contains no derivative of any portion of the 242 | Library, but is designed to work with the Library by being compiled or 243 | linked with it, is called a "work that uses the Library". Such a 244 | work, in isolation, is not a derivative work of the Library, and 245 | therefore falls outside the scope of this License. 246 | 247 | However, linking a "work that uses the Library" with the Library 248 | creates an executable that is a derivative of the Library (because it 249 | contains portions of the Library), rather than a "work that uses the 250 | library". The executable is therefore covered by this License. 251 | Section 6 states terms for distribution of such executables. 252 | 253 | When a "work that uses the Library" uses material from a header file 254 | that is part of the Library, the object code for the work may be a 255 | derivative work of the Library even though the source code is not. 256 | Whether this is true is especially significant if the work can be 257 | linked without the Library, or if the work is itself a library. The 258 | threshold for this to be true is not precisely defined by law. 259 | 260 | If such an object file uses only numerical parameters, data 261 | structure layouts and accessors, and small macros and small inline 262 | functions (ten lines or less in length), then the use of the object 263 | file is unrestricted, regardless of whether it is legally a derivative 264 | work. (Executables containing this object code plus portions of the 265 | Library will still fall under Section 6.) 266 | 267 | Otherwise, if the work is a derivative of the Library, you may 268 | distribute the object code for the work under the terms of Section 6. 269 | Any executables containing that work also fall under Section 6, 270 | whether or not they are linked directly with the Library itself. 271 | 272 | 6. As an exception to the Sections above, you may also combine or 273 | link a "work that uses the Library" with the Library to produce a 274 | work containing portions of the Library, and distribute that work 275 | under terms of your choice, provided that the terms permit 276 | modification of the work for the customer's own use and reverse 277 | engineering for debugging such modifications. 278 | 279 | You must give prominent notice with each copy of the work that the 280 | Library is used in it and that the Library and its use are covered by 281 | this License. You must supply a copy of this License. If the work 282 | during execution displays copyright notices, you must include the 283 | copyright notice for the Library among them, as well as a reference 284 | directing the user to the copy of this License. Also, you must do one 285 | of these things: 286 | 287 | a) Accompany the work with the complete corresponding 288 | machine-readable source code for the Library including whatever 289 | changes were used in the work (which must be distributed under 290 | Sections 1 and 2 above); and, if the work is an executable linked 291 | with the Library, with the complete machine-readable "work that 292 | uses the Library", as object code and/or source code, so that the 293 | user can modify the Library and then relink to produce a modified 294 | executable containing the modified Library. (It is understood 295 | that the user who changes the contents of definitions files in the 296 | Library will not necessarily be able to recompile the application 297 | to use the modified definitions.) 298 | 299 | b) Use a suitable shared library mechanism for linking with the 300 | Library. A suitable mechanism is one that (1) uses at run time a 301 | copy of the library already present on the user's computer system, 302 | rather than copying library functions into the executable, and (2) 303 | will operate properly with a modified version of the library, if 304 | the user installs one, as long as the modified version is 305 | interface-compatible with the version that the work was made with. 306 | 307 | c) Accompany the work with a written offer, valid for at 308 | least three years, to give the same user the materials 309 | specified in Subsection 6a, above, for a charge no more 310 | than the cost of performing this distribution. 311 | 312 | d) If distribution of the work is made by offering access to copy 313 | from a designated place, offer equivalent access to copy the above 314 | specified materials from the same place. 315 | 316 | e) Verify that the user has already received a copy of these 317 | materials or that you have already sent this user a copy. 318 | 319 | For an executable, the required form of the "work that uses the 320 | Library" must include any data and utility programs needed for 321 | reproducing the executable from it. However, as a special exception, 322 | the materials to be distributed need not include anything that is 323 | normally distributed (in either source or binary form) with the major 324 | components (compiler, kernel, and so on) of the operating system on 325 | which the executable runs, unless that component itself accompanies 326 | the executable. 327 | 328 | It may happen that this requirement contradicts the license 329 | restrictions of other proprietary libraries that do not normally 330 | accompany the operating system. Such a contradiction means you cannot 331 | use both them and the Library together in an executable that you 332 | distribute. 333 | 334 | 7. You may place library facilities that are a work based on the 335 | Library side-by-side in a single library together with other library 336 | facilities not covered by this License, and distribute such a combined 337 | library, provided that the separate distribution of the work based on 338 | the Library and of the other library facilities is otherwise 339 | permitted, and provided that you do these two things: 340 | 341 | a) Accompany the combined library with a copy of the same work 342 | based on the Library, uncombined with any other library 343 | facilities. This must be distributed under the terms of the 344 | Sections above. 345 | 346 | b) Give prominent notice with the combined library of the fact 347 | that part of it is a work based on the Library, and explaining 348 | where to find the accompanying uncombined form of the same work. 349 | 350 | 8. You may not copy, modify, sublicense, link with, or distribute 351 | the Library except as expressly provided under this License. Any 352 | attempt otherwise to copy, modify, sublicense, link with, or 353 | distribute the Library is void, and will automatically terminate your 354 | rights under this License. However, parties who have received copies, 355 | or rights, from you under this License will not have their licenses 356 | terminated so long as such parties remain in full compliance. 357 | 358 | 9. You are not required to accept this License, since you have not 359 | signed it. However, nothing else grants you permission to modify or 360 | distribute the Library or its derivative works. These actions are 361 | prohibited by law if you do not accept this License. Therefore, by 362 | modifying or distributing the Library (or any work based on the 363 | Library), you indicate your acceptance of this License to do so, and 364 | all its terms and conditions for copying, distributing or modifying 365 | the Library or works based on it. 366 | 367 | 10. Each time you redistribute the Library (or any work based on the 368 | Library), the recipient automatically receives a license from the 369 | original licensor to copy, distribute, link with or modify the Library 370 | subject to these terms and conditions. You may not impose any further 371 | restrictions on the recipients' exercise of the rights granted herein. 372 | You are not responsible for enforcing compliance by third parties with 373 | this License. 374 | 375 | 11. If, as a consequence of a court judgment or allegation of patent 376 | infringement or for any other reason (not limited to patent issues), 377 | conditions are imposed on you (whether by court order, agreement or 378 | otherwise) that contradict the conditions of this License, they do not 379 | excuse you from the conditions of this License. If you cannot 380 | distribute so as to satisfy simultaneously your obligations under this 381 | License and any other pertinent obligations, then as a consequence you 382 | may not distribute the Library at all. For example, if a patent 383 | license would not permit royalty-free redistribution of the Library by 384 | all those who receive copies directly or indirectly through you, then 385 | the only way you could satisfy both it and this License would be to 386 | refrain entirely from distribution of the Library. 387 | 388 | If any portion of this section is held invalid or unenforceable under any 389 | particular circumstance, the balance of the section is intended to apply, 390 | and the section as a whole is intended to apply in other circumstances. 391 | 392 | It is not the purpose of this section to induce you to infringe any 393 | patents or other property right claims or to contest validity of any 394 | such claims; this section has the sole purpose of protecting the 395 | integrity of the free software distribution system which is 396 | implemented by public license practices. Many people have made 397 | generous contributions to the wide range of software distributed 398 | through that system in reliance on consistent application of that 399 | system; it is up to the author/donor to decide if he or she is willing 400 | to distribute software through any other system and a licensee cannot 401 | impose that choice. 402 | 403 | This section is intended to make thoroughly clear what is believed to 404 | be a consequence of the rest of this License. 405 | 406 | 12. If the distribution and/or use of the Library is restricted in 407 | certain countries either by patents or by copyrighted interfaces, the 408 | original copyright holder who places the Library under this License may add 409 | an explicit geographical distribution limitation excluding those countries, 410 | so that distribution is permitted only in or among countries not thus 411 | excluded. In such case, this License incorporates the limitation as if 412 | written in the body of this License. 413 | 414 | 13. The Free Software Foundation may publish revised and/or new 415 | versions of the Lesser General Public License from time to time. 416 | Such new versions will be similar in spirit to the present version, 417 | but may differ in detail to address new problems or concerns. 418 | 419 | Each version is given a distinguishing version number. If the Library 420 | specifies a version number of this License which applies to it and 421 | "any later version", you have the option of following the terms and 422 | conditions either of that version or of any later version published by 423 | the Free Software Foundation. If the Library does not specify a 424 | license version number, you may choose any version ever published by 425 | the Free Software Foundation. 426 | 427 | 14. If you wish to incorporate parts of the Library into other free 428 | programs whose distribution conditions are incompatible with these, 429 | write to the author to ask for permission. For software which is 430 | copyrighted by the Free Software Foundation, write to the Free 431 | Software Foundation; we sometimes make exceptions for this. Our 432 | decision will be guided by the two goals of preserving the free status 433 | of all derivatives of our free software and of promoting the sharing 434 | and reuse of software generally. 435 | 436 | NO WARRANTY 437 | 438 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 439 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 440 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 441 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 442 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 443 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 444 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 445 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 446 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 447 | 448 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 449 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 450 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 451 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 452 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 453 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 454 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 455 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 456 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 457 | DAMAGES. 458 | 459 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #Firmata 2 | 3 | Firmata is a protocol for communicating with microcontrollers from software on a host computer. The [protocol](http://firmata.org/wiki/Protocol) can be implemented in firmware on any microcontroller architecture as well as software on any host computer software package. The arduino repository described here is a Firmata library for Arduino and Arduino-compatible devices. See the [firmata wiki](http://firmata.org/wiki/Main_Page) for additional informataion. If you would like to contribute to Firmata, please see the [Contributing](#contributing) section below. 4 | 5 | ##Usage 6 | 7 | There are two main models of usage of Firmata. In one model, the author of the Arduino sketch uses the various methods provided by the Firmata library to selectively send and receive data between the Arduino device and the software running on the host computer. For example, a user can send analog data to the host using ``` Firmata.sendAnalog(analogPin, analogRead(analogPin)) ``` or send data packed in a string using ``` Firmata.sendString(stringToSend) ```. See File -> Examples -> Firmata -> AnalogFirmata & EchoString respectively for examples. 8 | 9 | The second and more common model is to load a general purpose sketch called StandardFirmata on the Arduino board and then use the host computer exclusively to interact with the Arduino board. StandardFirmata is located in the Arduino IDE in File -> Examples -> Firmata. 10 | 11 | ##Firmata Client Libraries 12 | Most of the time you will be interacting with arduino with a client library on the host computers. Several Firmata client libraries have been implemented in a variety of popular programming languages: 13 | 14 | * procesing 15 | * [https://github.com/firmata/processing] 16 | * [http://funnel.cc] 17 | * python 18 | * [https://github.com/firmata/pyduino] 19 | * [https://github.com/lupeke/python-firmata] 20 | * [https://github.com/tino/pyFirmata] 21 | * perl 22 | * [https://github.com/ntruchsess/perl-firmata] 23 | * [https://github.com/rcaputo/rx-firmata] 24 | * ruby 25 | * [https://github.com/hardbap/firmata] 26 | * [https://github.com/PlasticLizard/rufinol] 27 | * [http://funnel.cc] 28 | * clojure 29 | * [https://github.com/nakkaya/clodiuno] 30 | * javascript 31 | * [https://github.com/jgautier/firmata] 32 | * [http://breakoutjs.com] 33 | * [https://github.com/rwldrn/johnny-five] 34 | * java 35 | * [https://github.com/4ntoine/Firmata] 36 | * [https://github.com/shigeodayo/Javarduino] 37 | * .NET 38 | * [http://www.imagitronics.org/projects/firmatanet/] 39 | * Flash/AS3 40 | * [http://funnel.cc] 41 | * [http://code.google.com/p/as3glue/] 42 | * PHP 43 | * [https://bitbucket.org/ThomasWeinert/carica-firmata] 44 | 45 | Note: The above libraries may support various versions of the Firmata protocol and therefore may not support all features of the latest Firmata spec nor all arduino and arduino-compatible boards. Refer to the respective projects for details. 46 | 47 | ##Updating Firmata in the Arduino IDE (< Arduino 1.5) 48 | The version of firmata in the Arduino IDE contains an outdated version of Firmata. To update Firmata, clone the repo into the location of firmata in the arduino IDE or download the latest [tagged version](https://github.com/firmata/arduino/tags) (stable), rename the folder to "Firmata" and replace the existing Firmata folder in your Ardino application. 49 | 50 | **Mac OSX**: 51 | 52 | ```bash 53 | $ rm -r /Applications/Arduino.app/Contents/Resources/Java/libraries/Firmata 54 | $ git clone git@github.com:firmata/arduino.git /Applications/Arduino.app/Contents/Resources/Java/libraries/Firmata 55 | ``` 56 | 57 | If you are downloading the latest tagged version of Firmata, rename it to "Firmata" and copy to /Applications/Arduino.app/Contents/Resources/Java/libraries/ overwriting the existing Firmata directory. Right-click (or conrol + click) on the Arduino application and choose "Show Package Contents" and navigate to the libraries directory. 58 | 59 | **Windows**: 60 | 61 | Using the Git Shell application installed with [GitHub for Windows](http://windows.github.com/) (set default shell in options to Git Bash) or other command line based git tool: 62 | 63 | update the path and arduino version as necessary 64 | ```bash 65 | $ rm -r c:/Program\ Files/arduino-1.x/libraries/Firmata 66 | $ git clone git@github.com:firmata/arduino.git c:/Program\ Files/arduino-1.x/libraries/Firmata 67 | ``` 68 | 69 | Note: If you use GitHub for Windows, you must clone the firmata/arduino repository using the Git Shell application as described above. You can use the Github for Windows GUI only after you have cloned the repository. Drag the Firmata file into the Github for Windows GUI to track it. 70 | 71 | **Linux**: 72 | 73 | update the path and arduino version as necessary 74 | ```bash 75 | $ rm -r ~/arduino-1.x/libraries/Firmata 76 | $ git clone git@github.com:firmata/arduino.git ~/arduino-1.x/libraries/Firmata 77 | ``` 78 | 79 | ##Updating Firmata in the Arduino IDE (>= Arduino 1.5.2) 80 | As of Arduino 1.5.2 and there are separate library directories for the sam and 81 | avr architectures. To update Firmata in Arduino 1.5.2 or higher, follow the 82 | instructions above for pre Arduino 1.5 versions but update the path as follows: 83 | 84 | **Mac OSX**: 85 | ``` 86 | /Applications/Arduino.app/Contents/Resources/Java/hardware/arduino/avr/libraries/Firmata 87 | /Applications/Arduino.app/Contents/Resources/Java/hardware/arduino/sam/libraries/Firmata 88 | ``` 89 | 90 | **Windows**: 91 | ``` 92 | /Program\ Files/arduino-1.5.x/hardware/arduino/avr/libraries/Firmata 93 | /Program\ Files/arduino-1.5.x/hardware/arduino/sam/libraries/Firmata 94 | ``` 95 | 96 | **Linux** 97 | ``` 98 | ~/arduino-1.5.x/hardware/arduino/avr/libraries/Firmata 99 | ~/arduino-1.5.x/hardware/arduino/sam/libraries/Firmata 100 | ``` 101 | 102 | 103 | ##Contributing 104 | 105 | If you discover a bug or would like to propose a new feature, please open a new [issue](https://github.com/firmata/arduino/issues?sort=created&state=open). Due to the limited memory of standard Arduino boards we cannot add every requested feature to StandardFirmata. Requests to add new features to StandardFirmata will be evaluated by the Firmata developers. However it is still possible to add new features to other Firmata implementations (Firmata is a protocol whereas StandardFirmata is just one of many possible implementations). 106 | 107 | To contribute, fork this respository and create a new topic branch for the bug, feature or other existing issue you are addressing. Submit the pull request against the *dev* branch. 108 | 109 | If you would like to contribute but don't have a specific bugfix or new feature to contribute, you can take on an existing issue, see issues labeled "pull-request-encouraged". Add a comment to the issue to express your intent to begin work and/or to get any additional information about the issue. 110 | 111 | You must thorougly test your contributed code. In your pull request, describe tests performed to ensure that no existing code is broken and that any changes maintain backwards compatibility with the existing api. Test on multiple Arduino board variants if possible. We hope to enable some form of automated (or at least semi-automated) testing in the future, but for now any tests will need to be executed manually by the contributor and reviewsers. 112 | 113 | Maintain the existing code style: 114 | 115 | - Indentation is 2 spaces 116 | - Use spaces instead of tabs 117 | - Use camel case for both private and public properties and methods 118 | - Document functions (specific doc style is TBD... for now just be sure to document) 119 | - Insert first block bracket on line following the function definition: 120 | 121 |
void someFunction()
122 | {
123 |   // do something
124 | }
125 | 
126 | -------------------------------------------------------------------------------- /examples/BluefruitLE_nrf51822/BluefruitConfig.h: -------------------------------------------------------------------------------- 1 | // COMMON SETTINGS 2 | // ---------------------------------------------------------------------------------------------- 3 | // These settings are used in both SW UART, HW UART and SPI mode 4 | // ---------------------------------------------------------------------------------------------- 5 | #define BUFSIZE 128 // Size of the read buffer for incoming data 6 | #define VERBOSE_MODE true // If set to 'true' enables debug output 7 | 8 | 9 | // SOFTWARE UART SETTINGS 10 | // ---------------------------------------------------------------------------------------------- 11 | // The following macros declare the pins that will be used for 'SW' serial. 12 | // You should use this option if you are connecting the UART Friend to an UNO 13 | // ---------------------------------------------------------------------------------------------- 14 | #define BLUEFRUIT_SWUART_RXD_PIN 9 // Required for software serial! 15 | #define BLUEFRUIT_SWUART_TXD_PIN 10 // Required for software serial! 16 | #define BLUEFRUIT_UART_CTS_PIN 11 // Required for software serial! 17 | #define BLUEFRUIT_UART_RTS_PIN -1 // Optional, set to -1 if unused 18 | 19 | 20 | // HARDWARE UART SETTINGS 21 | // ---------------------------------------------------------------------------------------------- 22 | // The following macros declare the HW serial port you are using. Uncomment 23 | // this line if you are connecting the BLE to Leonardo/Micro or Flora 24 | // ---------------------------------------------------------------------------------------------- 25 | #ifdef Serial1 // this makes it not complain on compilation if there's no Serial1 26 | #define BLUEFRUIT_HWSERIAL_NAME Serial1 27 | #endif 28 | 29 | 30 | // SHARED UART SETTINGS 31 | // ---------------------------------------------------------------------------------------------- 32 | // The following sets the optional Mode pin, its recommended but not required 33 | // ---------------------------------------------------------------------------------------------- 34 | #define BLUEFRUIT_UART_MODE_PIN 12 // Set to -1 if unused 35 | 36 | 37 | // SHARED SPI SETTINGS 38 | // ---------------------------------------------------------------------------------------------- 39 | // The following macros declare the pins to use for HW and SW SPI communication. 40 | // SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when 41 | // using HW SPI. This should be used with nRF51822 based Bluefruit LE modules 42 | // that use SPI (Bluefruit LE SPI Friend). 43 | // ---------------------------------------------------------------------------------------------- 44 | #define BLUEFRUIT_SPI_CS 8 45 | #define BLUEFRUIT_SPI_IRQ 7 46 | #define BLUEFRUIT_SPI_RST 4 47 | 48 | // SOFTWARE SPI SETTINGS 49 | // ---------------------------------------------------------------------------------------------- 50 | // The following macros declare the pins to use for SW SPI communication. 51 | // This should be used with nRF51822 based Bluefruit LE modules that use SPI 52 | // (Bluefruit LE SPI Friend). 53 | // ---------------------------------------------------------------------------------------------- 54 | #define BLUEFRUIT_SPI_SCK 13 55 | #define BLUEFRUIT_SPI_MISO 12 56 | #define BLUEFRUIT_SPI_MOSI 11 57 | -------------------------------------------------------------------------------- /examples/BluefruitLE_nrf51822/BluefruitLE_nrf51822.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #if not defined (_VARIANT_ARDUINO_DUE_X_) && not defined (_VARIANT_ARDUINO_ZERO_) 6 | #include 7 | #endif 8 | 9 | // Change this to whatever is the Serial console you want, either Serial or SerialUSB 10 | #define FIRMATADEBUG Serial 11 | // Pause for Serial console before beginning? 12 | #define WAITFORSERIAL true 13 | // Print all BLE interactions? 14 | #define VERBOSE_MODE false 15 | 16 | 17 | /************************ CONFIGURATION SECTION ***********************************/ 18 | /* 19 | Don't forget to also change the BluefruitConfig.h for the SPI or UART connection 20 | and pinout you are using! 21 | 22 | Then below, you can edit the list of pins that are available. Remove any pins 23 | that are used for accessories or for talking to the BLE module! 24 | */ 25 | 26 | /************** For Bluefruit Micro or Feather 32u4 Bluefruit ************/ 27 | uint8_t boards_digitaliopins[] = {0,1,2,3,5,6,9,10,11,12,13,A0,A1,A2,A3,A4,A5}; 28 | 29 | /************** For UNO + nRF58122 SPI & shield ************/ 30 | //uint8_t boards_digitaliopins[] = {2, 3, 5, 6, 9, 10, A0, A1, A2, A3, A4, A5}; 31 | 32 | /************** For Bluefruit M0 Bluefruit ************/ 33 | //uint8_t boards_digitaliopins[] = {0,1,5,6,9,10,11,12,13,20,21,A0,A1,A2,A3,A4,A5}; 34 | 35 | #if defined(__AVR_ATmega328P__) 36 | // Standard setup for UNO, no need to tweak 37 | uint8_t boards_analogiopins[] = {A0, A1, A2, A3, A4, A5}; // A0 == digital 14, etc 38 | uint8_t boards_pwmpins[] = {3, 5, 6, 9, 10, 11}; 39 | uint8_t boards_servopins[] = {9, 10}; 40 | uint8_t boards_i2cpins[] = {SDA, SCL}; 41 | #elif defined(__AVR_ATmega32U4__) 42 | uint8_t boards_analogiopins[] = {A0, A1, A2, A3, A4, A5}; // A0 == digital 14, etc 43 | uint8_t boards_pwmpins[] = {3, 5, 6, 9, 10, 11, 13}; 44 | uint8_t boards_servopins[] = {3, 5, 6, 9, 10, 11, 13}; 45 | uint8_t boards_i2cpins[] = {SDA, SCL}; 46 | #elif defined(__SAMD21G18A__) 47 | #define SDA PIN_WIRE_SDA 48 | #define SCL PIN_WIRE_SCL 49 | uint8_t boards_analogiopins[] = {PIN_A0, PIN_A1, PIN_A2, PIN_A3, PIN_A4, PIN_A5,PIN_A6, PIN_A7}; // A0 == digital 14, etc 50 | uint8_t boards_pwmpins[] = {3,4,5,6,8,10,11,12,A0,A1,A2,A3,A4,A5}; 51 | uint8_t boards_servopins[] = {9, 10}; 52 | uint8_t boards_i2cpins[] = {SDA, SCL}; 53 | #define NUM_DIGITAL_PINS 26 54 | #endif 55 | 56 | 57 | #define TOTAL_PINS NUM_DIGITAL_PINS /* highest number in boards_digitaliopins MEMEFIXME:automate */ 58 | #define TOTAL_PORTS ((TOTAL_PINS + 7) / 8) 59 | 60 | 61 | /***********************************************************/ 62 | 63 | 64 | #include "Adafruit_BLE_Firmata_Boards.h" 65 | 66 | #include "Adafruit_BLE.h" 67 | #include "Adafruit_BluefruitLE_SPI.h" 68 | #include "Adafruit_BluefruitLE_UART.h" 69 | #include "BluefruitConfig.h" 70 | 71 | 72 | // Create the bluefruit object, either software serial...uncomment these lines 73 | /* 74 | SoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN); 75 | 76 | Adafruit_BluefruitLE_UART bluefruit(bluefruitSS, BLUEFRUIT_UART_MODE_PIN, 77 | BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN); 78 | */ 79 | 80 | /* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */ 81 | // Adafruit_BluefruitLE_UART bluefruit(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN); 82 | 83 | /* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */ 84 | Adafruit_BluefruitLE_SPI bluefruit(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST); 85 | 86 | /* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */ 87 | //Adafruit_BluefruitLE_SPI bluefruit(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO, 88 | // BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS, 89 | // BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST); 90 | 91 | 92 | #define AUTO_INPUT_PULLUPS true 93 | 94 | // our current connection status 95 | boolean lastBTLEstatus, BTLEstatus; 96 | 97 | // make one instance for the user to use 98 | Adafruit_BLE_FirmataClass BLE_Firmata = Adafruit_BLE_FirmataClass(bluefruit); 99 | 100 | // A small helper 101 | void error(const __FlashStringHelper*err) { 102 | FIRMATADEBUG.println(err); 103 | while (1); 104 | } 105 | 106 | /*============================================================================== 107 | * GLOBAL VARIABLES 108 | *============================================================================*/ 109 | 110 | /* analog inputs */ 111 | int analogInputsToReport = 0; // bitwise array to store pin reporting 112 | int lastAnalogReads[NUM_ANALOG_INPUTS]; 113 | 114 | /* digital input ports */ 115 | byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence 116 | byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent 117 | 118 | /* pins configuration */ 119 | byte pinConfig[TOTAL_PINS]; // configuration of every pin 120 | byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else 121 | int pinState[TOTAL_PINS]; // any value that has been written 122 | 123 | /* timer variables */ 124 | unsigned long currentMillis; // store the current value from millis() 125 | unsigned long previousMillis; // for comparison with currentMillis 126 | int samplingInterval = 200; // how often to run the main loop (in ms) 127 | #define MINIMUM_SAMPLE_DELAY 150 128 | #define ANALOG_SAMPLE_DELAY 50 129 | 130 | 131 | /* i2c data */ 132 | struct i2c_device_info { 133 | byte addr; 134 | byte reg; 135 | byte bytes; 136 | }; 137 | 138 | /* for i2c read continuous more */ 139 | i2c_device_info query[MAX_QUERIES]; 140 | 141 | byte i2cRxData[32]; 142 | boolean isI2CEnabled = false; 143 | signed char queryIndex = -1; 144 | unsigned int i2cReadDelayTime = 0; // default delay time between i2c read request and Wire.requestFrom() 145 | 146 | Servo servos[MAX_SERVOS]; 147 | /*============================================================================== 148 | * FUNCTIONS 149 | *============================================================================*/ 150 | 151 | void readAndReportData(byte address, int theRegister, byte numBytes) { 152 | // allow I2C requests that don't require a register read 153 | // for example, some devices using an interrupt pin to signify new data available 154 | // do not always require the register read so upon interrupt you call Wire.requestFrom() 155 | if (theRegister != REGISTER_NOT_SPECIFIED) { 156 | Wire.beginTransmission(address); 157 | #if ARDUINO >= 100 158 | Wire.write((byte)theRegister); 159 | #else 160 | Wire.send((byte)theRegister); 161 | #endif 162 | Wire.endTransmission(); 163 | delayMicroseconds(i2cReadDelayTime); // delay is necessary for some devices such as WiiNunchuck 164 | } else { 165 | theRegister = 0; // fill the register with a dummy value 166 | } 167 | 168 | Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom 169 | 170 | // check to be sure correct number of bytes were returned by slave 171 | if(numBytes == Wire.available()) { 172 | i2cRxData[0] = address; 173 | i2cRxData[1] = theRegister; 174 | for (int i = 0; i < numBytes; i++) { 175 | #if ARDUINO >= 100 176 | i2cRxData[2 + i] = Wire.read(); 177 | #else 178 | i2cRxData[2 + i] = Wire.receive(); 179 | #endif 180 | } 181 | } 182 | else { 183 | if(numBytes > Wire.available()) { 184 | BLE_Firmata.sendString("I2C Read Error: Too many bytes received"); 185 | } else { 186 | BLE_Firmata.sendString("I2C Read Error: Too few bytes received"); 187 | } 188 | } 189 | 190 | // send slave address, register and received bytes 191 | BLE_Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); 192 | } 193 | 194 | void outputPort(byte portNumber, byte portValue, byte forceSend) 195 | { 196 | // pins not configured as INPUT are cleared to zeros 197 | portValue = portValue & portConfigInputs[portNumber]; 198 | // only send if the value is different than previously sent 199 | if(forceSend || previousPINs[portNumber] != portValue) { 200 | //FIRMATADEBUG.print(F("Sending update for port ")); FIRMATADEBUG.print(portNumber); FIRMATADEBUG.print(" = 0x"); FIRMATADEBUG.println(portValue, HEX); 201 | BLE_Firmata.sendDigitalPort(portNumber, portValue); 202 | previousPINs[portNumber] = portValue; 203 | } 204 | } 205 | 206 | /* ----------------------------------------------------------------------------- 207 | * check all the active digital inputs for change of state, then add any events 208 | * to the Serial output queue using () */ 209 | void checkDigitalInputs(boolean forceSend = false) 210 | { 211 | /* Using non-looping code allows constants to be given to readPort(). 212 | * The compiler will apply substantial optimizations if the inputs 213 | * to readPort() are compile-time constants. */ 214 | for (uint8_t i=0; i TOTAL_PINS) lastPin = TOTAL_PINS; 344 | for (pin=port*8; pin < lastPin; pin++) { 345 | // do not disturb non-digital pins (eg, Rx & Tx) 346 | if (BLE_Firmata.IS_PIN_DIGITAL(pin)) { 347 | // only write to OUTPUT 348 | // do not touch pins in PWM, ANALOG, SERVO or other modes 349 | if (pinConfig[pin] == OUTPUT) { 350 | pinWriteMask |= mask; 351 | pinState[pin] = ((byte)value & mask) ? 1 : 0; 352 | } 353 | } 354 | mask = mask << 1; 355 | } 356 | FIRMATADEBUG.print(F("Write digital port #")); FIRMATADEBUG.print(port); 357 | FIRMATADEBUG.print(F(" = 0x")); FIRMATADEBUG.print(value, HEX); 358 | FIRMATADEBUG.print(F(" mask = 0x")); FIRMATADEBUG.println(pinWriteMask, HEX); 359 | BLE_Firmata.writePort(port, (byte)value, pinWriteMask); 360 | } 361 | } 362 | 363 | 364 | // ----------------------------------------------------------------------------- 365 | /* sets bits in a bit array (int) to toggle the reporting of the analogIns 366 | */ 367 | //void FirmataClass::setAnalogPinReporting(byte pin, byte state) { 368 | //} 369 | void reportAnalogCallback(byte analogPin, int value) 370 | { 371 | if (analogPin < BLE_Firmata._num_analogiopins) { 372 | if(value == 0) { 373 | analogInputsToReport = analogInputsToReport &~ (1 << analogPin); 374 | FIRMATADEBUG.print(F("Stop reporting analog pin #")); FIRMATADEBUG.println(analogPin); 375 | } else { 376 | analogInputsToReport |= (1 << analogPin); 377 | FIRMATADEBUG.print(F("Will report analog pin #")); FIRMATADEBUG.println(analogPin); 378 | } 379 | } 380 | // TODO: save status to EEPROM here, if changed 381 | } 382 | 383 | void reportDigitalCallback(byte port, int value) 384 | { 385 | if (port < TOTAL_PORTS) { 386 | //FIRMATADEBUG.print(F("Will report 0x")); FIRMATADEBUG.print(value, HEX); FIRMATADEBUG.print(F(" digital mask on port ")); FIRMATADEBUG.println(port); 387 | reportPINs[port] = (byte)value; 388 | } 389 | // do not disable analog reporting on these 8 pins, to allow some 390 | // pins used for digital, others analog. Instead, allow both types 391 | // of reporting to be enabled, but check if the pin is configured 392 | // as analog when sampling the analog inputs. Likewise, while 393 | // scanning digital pins, portConfigInputs will mask off values from any 394 | // pins configured as analog 395 | } 396 | 397 | /*============================================================================== 398 | * SYSEX-BASED commands 399 | *============================================================================*/ 400 | 401 | void sysexCallback(byte command, byte argc, byte *argv) 402 | { 403 | byte mode; 404 | byte slaveAddress; 405 | byte slaveRegister; 406 | byte data; 407 | unsigned int delayTime; 408 | 409 | FIRMATADEBUG.println("********** Sysex callback"); 410 | switch(command) { 411 | case I2C_REQUEST: 412 | mode = argv[1] & I2C_READ_WRITE_MODE_MASK; 413 | if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { 414 | //BLE_Firmata.sendString("10-bit addressing mode is not yet supported"); 415 | FIRMATADEBUG.println(F("10-bit addressing mode is not yet supported")); 416 | return; 417 | } 418 | else { 419 | slaveAddress = argv[0]; 420 | } 421 | 422 | switch(mode) { 423 | case I2C_WRITE: 424 | Wire.beginTransmission(slaveAddress); 425 | for (byte i = 2; i < argc; i += 2) { 426 | data = argv[i] + (argv[i + 1] << 7); 427 | #if ARDUINO >= 100 428 | Wire.write(data); 429 | #else 430 | Wire.send(data); 431 | #endif 432 | } 433 | Wire.endTransmission(); 434 | delayMicroseconds(70); 435 | break; 436 | case I2C_READ: 437 | if (argc == 6) { 438 | // a slave register is specified 439 | slaveRegister = argv[2] + (argv[3] << 7); 440 | data = argv[4] + (argv[5] << 7); // bytes to read 441 | readAndReportData(slaveAddress, (int)slaveRegister, data); 442 | } 443 | else { 444 | // a slave register is NOT specified 445 | data = argv[2] + (argv[3] << 7); // bytes to read 446 | readAndReportData(slaveAddress, (int)REGISTER_NOT_SPECIFIED, data); 447 | } 448 | break; 449 | case I2C_READ_CONTINUOUSLY: 450 | if ((queryIndex + 1) >= MAX_QUERIES) { 451 | // too many queries, just ignore 452 | BLE_Firmata.sendString("too many queries"); 453 | break; 454 | } 455 | queryIndex++; 456 | query[queryIndex].addr = slaveAddress; 457 | query[queryIndex].reg = argv[2] + (argv[3] << 7); 458 | query[queryIndex].bytes = argv[4] + (argv[5] << 7); 459 | break; 460 | case I2C_STOP_READING: 461 | byte queryIndexToSkip; 462 | // if read continuous mode is enabled for only 1 i2c device, disable 463 | // read continuous reporting for that device 464 | if (queryIndex <= 0) { 465 | queryIndex = -1; 466 | } else { 467 | // if read continuous mode is enabled for multiple devices, 468 | // determine which device to stop reading and remove it's data from 469 | // the array, shifiting other array data to fill the space 470 | for (byte i = 0; i < queryIndex + 1; i++) { 471 | if (query[i].addr = slaveAddress) { 472 | queryIndexToSkip = i; 473 | break; 474 | } 475 | } 476 | 477 | for (byte i = queryIndexToSkip; i 0) { 495 | i2cReadDelayTime = delayTime; 496 | } 497 | 498 | if (!isI2CEnabled) { 499 | enableI2CPins(); 500 | } 501 | 502 | break; 503 | case SERVO_CONFIG: 504 | if(argc > 4) { 505 | // these vars are here for clarity, they'll optimized away by the compiler 506 | byte pin = argv[0]; 507 | int minPulse = argv[1] + (argv[2] << 7); 508 | int maxPulse = argv[3] + (argv[4] << 7); 509 | 510 | if (BLE_Firmata.IS_PIN_SERVO(pin)) { 511 | if (servos[BLE_Firmata.PIN_TO_SERVO(pin)].attached()) 512 | servos[BLE_Firmata.PIN_TO_SERVO(pin)].detach(); 513 | servos[BLE_Firmata.PIN_TO_SERVO(pin)].attach(BLE_Firmata.PIN_TO_DIGITAL(pin), minPulse, maxPulse); 514 | setPinModeCallback(pin, SERVO); 515 | } 516 | } 517 | break; 518 | case SAMPLING_INTERVAL: 519 | if (argc > 1) { 520 | samplingInterval = argv[0] + (argv[1] << 7); 521 | if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { 522 | samplingInterval = MINIMUM_SAMPLING_INTERVAL; 523 | } 524 | } else { 525 | //BLE_Firmata.sendString("Not enough data"); 526 | } 527 | break; 528 | case EXTENDED_ANALOG: 529 | if (argc > 1) { 530 | int val = argv[1]; 531 | if (argc > 2) val |= (argv[2] << 7); 532 | if (argc > 3) val |= (argv[3] << 14); 533 | analogWriteCallback(argv[0], val); 534 | } 535 | break; 536 | case CAPABILITY_QUERY: 537 | bluefruit.write(START_SYSEX); 538 | bluefruit.write(CAPABILITY_RESPONSE); 539 | 540 | //FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.print(START_SYSEX, HEX); FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.println(CAPABILITY_RESPONSE, HEX); 541 | delay(10); 542 | for (byte pin=0; pin < TOTAL_PINS; pin++) { 543 | //FIRMATADEBUG.print("\t#"); FIRMATADEBUG.println(pin); 544 | if (BLE_Firmata.IS_PIN_DIGITAL(pin)) { 545 | bluefruit.write((byte)INPUT); 546 | bluefruit.write(1); 547 | bluefruit.write((byte)OUTPUT); 548 | bluefruit.write(1); 549 | 550 | /* 551 | FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.print(INPUT, HEX); 552 | FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.print(1, HEX); 553 | FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.print(OUTPUT, HEX); 554 | FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.println(1, HEX); 555 | */ 556 | delay(20); 557 | } else { 558 | bluefruit.write(127); 559 | //FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.println(127, HEX); 560 | delay(20); 561 | continue; 562 | } 563 | if (BLE_Firmata.IS_PIN_ANALOG(pin)) { 564 | bluefruit.write(ANALOG); 565 | bluefruit.write(10); 566 | 567 | //FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.print(ANALOG, HEX); FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.println(10, HEX); 568 | delay(20); 569 | } 570 | if (BLE_Firmata.IS_PIN_PWM(pin)) { 571 | bluefruit.write(PWM); 572 | bluefruit.write(8); 573 | 574 | //FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.print(PWM, HEX); FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.println(8, HEX); 575 | delay(20); 576 | } 577 | if (BLE_Firmata.IS_PIN_SERVO(pin)) { 578 | bluefruit.write(SERVO); 579 | bluefruit.write(14); 580 | 581 | //FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.print(SERVO, HEX);FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.println(14, HEX); 582 | delay(20); 583 | } 584 | if (BLE_Firmata.IS_PIN_I2C(pin)) { 585 | bluefruit.write(I2C); 586 | bluefruit.write(1); // to do: determine appropriate value 587 | delay(20); 588 | } 589 | bluefruit.write(127); 590 | //FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.println(127, HEX); 591 | } 592 | bluefruit.write(END_SYSEX); 593 | //FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.println(END_SYSEX, HEX); 594 | break; 595 | case PIN_STATE_QUERY: 596 | if (argc > 0) { 597 | byte pin=argv[0]; 598 | bluefruit.write(START_SYSEX); 599 | bluefruit.write(PIN_STATE_RESPONSE); 600 | bluefruit.write(pin); 601 | if (pin < TOTAL_PINS) { 602 | bluefruit.write((byte)pinConfig[pin]); 603 | bluefruit.write((byte)pinState[pin] & 0x7F); 604 | if (pinState[pin] & 0xFF80) bluefruit.write((byte)(pinState[pin] >> 7) & 0x7F); 605 | if (pinState[pin] & 0xC000) bluefruit.write((byte)(pinState[pin] >> 14) & 0x7F); 606 | } 607 | bluefruit.write(END_SYSEX); 608 | } 609 | break; 610 | case ANALOG_MAPPING_QUERY: 611 | FIRMATADEBUG.println("Analog mapping query"); 612 | bluefruit.write(START_SYSEX); 613 | bluefruit.write(ANALOG_MAPPING_RESPONSE); 614 | for (byte pin=0; pin < TOTAL_PINS; pin++) { 615 | bluefruit.write(BLE_Firmata.IS_PIN_ANALOG(pin) ? BLE_Firmata.PIN_TO_ANALOG(pin) : 127); 616 | } 617 | bluefruit.write(END_SYSEX); 618 | break; 619 | } 620 | } 621 | 622 | void enableI2CPins() 623 | { 624 | byte i; 625 | // is there a faster way to do this? would probaby require importing 626 | // Arduino.h to get SCL and SDA pins 627 | for (i=0; i < TOTAL_PINS; i++) { 628 | if(BLE_Firmata.IS_PIN_I2C(i)) { 629 | // mark pins as i2c so they are ignore in non i2c data requests 630 | setPinModeCallback(i, I2C); 631 | } 632 | } 633 | 634 | isI2CEnabled = true; 635 | 636 | // is there enough time before the first I2C request to call this here? 637 | Wire.begin(); 638 | } 639 | 640 | /* disable the i2c pins so they can be used for other functions */ 641 | void disableI2CPins() { 642 | isI2CEnabled = false; 643 | // disable read continuous mode for all devices 644 | queryIndex = -1; 645 | // uncomment the following if or when the end() method is added to Wire library 646 | // Wire.end(); 647 | } 648 | 649 | /*============================================================================== 650 | * SETUP() 651 | *============================================================================*/ 652 | 653 | void systemResetCallback() 654 | { 655 | // initialize a defalt state 656 | FIRMATADEBUG.println(F("***RESET***")); 657 | // TODO: option to load config from EEPROM instead of default 658 | if (isI2CEnabled) { 659 | disableI2CPins(); 660 | } 661 | for (byte i=0; i < TOTAL_PORTS; i++) { 662 | reportPINs[i] = false; // by default, reporting off 663 | portConfigInputs[i] = 0; // until activated 664 | previousPINs[i] = 0; 665 | } 666 | // pins with analog capability default to analog input 667 | // otherwise, pins default to digital output 668 | for (byte i=0; i < TOTAL_PINS; i++) { 669 | if (BLE_Firmata.IS_PIN_ANALOG(i)) { 670 | // turns off pullup, configures everything 671 | setPinModeCallback(i, ANALOG); 672 | } else { 673 | // sets the output to 0, configures portConfigInputs 674 | setPinModeCallback(i, INPUT); 675 | } 676 | } 677 | // by default, do not report any analog inputs 678 | analogInputsToReport = 0; 679 | 680 | /* send digital inputs to set the initial state on the host computer, 681 | * since once in the loop(), this firmware will only send on change */ 682 | /* 683 | TODO: this can never execute, since no pins default to digital input 684 | but it will be needed when/if we support EEPROM stored config 685 | for (byte i=0; i < TOTAL_PORTS; i++) { 686 | outputPort(i, readPort(i, portConfigInputs[i]), true); 687 | } 688 | */ 689 | } 690 | 691 | void setup() 692 | { 693 | if (WAITFORSERIAL) { 694 | while (!FIRMATADEBUG) delay(1); 695 | } 696 | 697 | FIRMATADEBUG.begin(9600); 698 | FIRMATADEBUG.println(F("Adafruit Bluefruit LE Firmata test")); 699 | 700 | FIRMATADEBUG.print("Total pins: "); FIRMATADEBUG.println(NUM_DIGITAL_PINS); 701 | FIRMATADEBUG.print("Analog pins: "); FIRMATADEBUG.println(sizeof(boards_analogiopins)); 702 | //for (uint8_t i=0; i samplingInterval) { 833 | previousMillis += samplingInterval; 834 | /* ANALOGREAD - do all analogReads() at the configured sampling interval */ 835 | 836 | for(pin=0; pin= 100 129 | Wire.write((byte)theRegister); 130 | #else 131 | Wire.send((byte)theRegister); 132 | #endif 133 | Wire.endTransmission(); 134 | delayMicroseconds(i2cReadDelayTime); // delay is necessary for some devices such as WiiNunchuck 135 | } else { 136 | theRegister = 0; // fill the register with a dummy value 137 | } 138 | 139 | Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom 140 | 141 | // check to be sure correct number of bytes were returned by slave 142 | if(numBytes == Wire.available()) { 143 | i2cRxData[0] = address; 144 | i2cRxData[1] = theRegister; 145 | for (int i = 0; i < numBytes; i++) { 146 | #if ARDUINO >= 100 147 | i2cRxData[2 + i] = Wire.read(); 148 | #else 149 | i2cRxData[2 + i] = Wire.receive(); 150 | #endif 151 | } 152 | } 153 | else { 154 | if(numBytes > Wire.available()) { 155 | BLE_Firmata.sendString("I2C Read Error: Too many bytes received"); 156 | } else { 157 | BLE_Firmata.sendString("I2C Read Error: Too few bytes received"); 158 | } 159 | } 160 | 161 | // send slave address, register and received bytes 162 | BLE_Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); 163 | } 164 | 165 | void outputPort(byte portNumber, byte portValue, byte forceSend) 166 | { 167 | // pins not configured as INPUT are cleared to zeros 168 | portValue = portValue & portConfigInputs[portNumber]; 169 | // only send if the value is different than previously sent 170 | if(forceSend || previousPINs[portNumber] != portValue) { 171 | //FIRMATADEBUG.print(F("Sending update for port ")); FIRMATADEBUG.print(portNumber); FIRMATADEBUG.print(" = 0x"); FIRMATADEBUG.println(portValue, HEX); 172 | BLE_Firmata.sendDigitalPort(portNumber, portValue); 173 | previousPINs[portNumber] = portValue; 174 | } 175 | } 176 | 177 | /* ----------------------------------------------------------------------------- 178 | * check all the active digital inputs for change of state, then add any events 179 | * to the Serial output queue using () */ 180 | void checkDigitalInputs(boolean forceSend = false) 181 | { 182 | /* Using non-looping code allows constants to be given to readPort(). 183 | * The compiler will apply substantial optimizations if the inputs 184 | * to readPort() are compile-time constants. */ 185 | for (uint8_t i=0; i TOTAL_PINS) lastPin = TOTAL_PINS; 315 | for (pin=port*8; pin < lastPin; pin++) { 316 | // do not disturb non-digital pins (eg, Rx & Tx) 317 | if (BLE_Firmata.IS_PIN_DIGITAL(pin)) { 318 | // only write to OUTPUT 319 | // do not touch pins in PWM, ANALOG, SERVO or other modes 320 | if (pinConfig[pin] == OUTPUT) { 321 | pinWriteMask |= mask; 322 | pinState[pin] = ((byte)value & mask) ? 1 : 0; 323 | } 324 | } 325 | mask = mask << 1; 326 | } 327 | //FIRMATADEBUG.print(F("Write digital port #")); FIRMATADEBUG.print(port); 328 | //FIRMATADEBUG.print(F(" = 0x")); FIRMATADEBUG.print(value, HEX); 329 | //FIRMATADEBUG.print(F(" mask = 0x")); FIRMATADEBUG.println(pinWriteMask, HEX); 330 | BLE_Firmata.writePort(port, (byte)value, pinWriteMask); 331 | } 332 | } 333 | 334 | 335 | // ----------------------------------------------------------------------------- 336 | /* sets bits in a bit array (int) to toggle the reporting of the analogIns 337 | */ 338 | //void FirmataClass::setAnalogPinReporting(byte pin, byte state) { 339 | //} 340 | void reportAnalogCallback(byte analogPin, int value) 341 | { 342 | if (analogPin < BLE_Firmata._num_analogiopins) { 343 | if(value == 0) { 344 | analogInputsToReport = analogInputsToReport &~ (1 << analogPin); 345 | //FIRMATADEBUG.print(F("Stop reporting analog pin #")); FIRMATADEBUG.println(analogPin); 346 | } else { 347 | analogInputsToReport |= (1 << analogPin); 348 | //FIRMATADEBUG.print(F("Will report analog pin #")); FIRMATADEBUG.println(analogPin); 349 | } 350 | } 351 | // TODO: save status to EEPROM here, if changed 352 | } 353 | 354 | void reportDigitalCallback(byte port, int value) 355 | { 356 | if (port < TOTAL_PORTS) { 357 | //FIRMATADEBUG.print(F("Will report 0x")); FIRMATADEBUG.print(value, HEX); FIRMATADEBUG.print(F(" digital mask on port ")); FIRMATADEBUG.println(port); 358 | reportPINs[port] = (byte)value; 359 | } 360 | // do not disable analog reporting on these 8 pins, to allow some 361 | // pins used for digital, others analog. Instead, allow both types 362 | // of reporting to be enabled, but check if the pin is configured 363 | // as analog when sampling the analog inputs. Likewise, while 364 | // scanning digital pins, portConfigInputs will mask off values from any 365 | // pins configured as analog 366 | } 367 | 368 | /*============================================================================== 369 | * SYSEX-BASED commands 370 | *============================================================================*/ 371 | 372 | void sysexCallback(byte command, byte argc, byte *argv) 373 | { 374 | byte mode; 375 | byte slaveAddress; 376 | byte slaveRegister; 377 | byte data; 378 | unsigned int delayTime; 379 | 380 | FIRMATADEBUG.println("********** Sysex callback"); 381 | 382 | switch(command) { 383 | case I2C_REQUEST: 384 | mode = argv[1] & I2C_READ_WRITE_MODE_MASK; 385 | if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { 386 | //BLE_Firmata.sendString("10-bit addressing mode is not yet supported"); 387 | //FIRMATADEBUG.println(F("10-bit addressing mode is not yet supported")); 388 | return; 389 | } 390 | else { 391 | slaveAddress = argv[0]; 392 | } 393 | 394 | switch(mode) { 395 | case I2C_WRITE: 396 | Wire.beginTransmission(slaveAddress); 397 | for (byte i = 2; i < argc; i += 2) { 398 | data = argv[i] + (argv[i + 1] << 7); 399 | #if ARDUINO >= 100 400 | Wire.write(data); 401 | #else 402 | Wire.send(data); 403 | #endif 404 | } 405 | Wire.endTransmission(); 406 | delayMicroseconds(70); 407 | break; 408 | case I2C_READ: 409 | if (argc == 6) { 410 | // a slave register is specified 411 | slaveRegister = argv[2] + (argv[3] << 7); 412 | data = argv[4] + (argv[5] << 7); // bytes to read 413 | readAndReportData(slaveAddress, (int)slaveRegister, data); 414 | } 415 | else { 416 | // a slave register is NOT specified 417 | data = argv[2] + (argv[3] << 7); // bytes to read 418 | readAndReportData(slaveAddress, (int)REGISTER_NOT_SPECIFIED, data); 419 | } 420 | break; 421 | case I2C_READ_CONTINUOUSLY: 422 | if ((queryIndex + 1) >= MAX_QUERIES) { 423 | // too many queries, just ignore 424 | BLE_Firmata.sendString("too many queries"); 425 | break; 426 | } 427 | queryIndex++; 428 | query[queryIndex].addr = slaveAddress; 429 | query[queryIndex].reg = argv[2] + (argv[3] << 7); 430 | query[queryIndex].bytes = argv[4] + (argv[5] << 7); 431 | break; 432 | case I2C_STOP_READING: 433 | byte queryIndexToSkip; 434 | // if read continuous mode is enabled for only 1 i2c device, disable 435 | // read continuous reporting for that device 436 | if (queryIndex <= 0) { 437 | queryIndex = -1; 438 | } else { 439 | // if read continuous mode is enabled for multiple devices, 440 | // determine which device to stop reading and remove it's data from 441 | // the array, shifiting other array data to fill the space 442 | for (byte i = 0; i < queryIndex + 1; i++) { 443 | if (query[i].addr = slaveAddress) { 444 | queryIndexToSkip = i; 445 | break; 446 | } 447 | } 448 | 449 | for (byte i = queryIndexToSkip; i 0) { 467 | i2cReadDelayTime = delayTime; 468 | } 469 | 470 | if (!isI2CEnabled) { 471 | enableI2CPins(); 472 | } 473 | 474 | break; 475 | case SERVO_CONFIG: 476 | if(argc > 4) { 477 | // these vars are here for clarity, they'll optimized away by the compiler 478 | byte pin = argv[0]; 479 | int minPulse = argv[1] + (argv[2] << 7); 480 | int maxPulse = argv[3] + (argv[4] << 7); 481 | 482 | if (BLE_Firmata.IS_PIN_SERVO(pin)) { 483 | if (servos[BLE_Firmata.PIN_TO_SERVO(pin)].attached()) 484 | servos[BLE_Firmata.PIN_TO_SERVO(pin)].detach(); 485 | servos[BLE_Firmata.PIN_TO_SERVO(pin)].attach(BLE_Firmata.PIN_TO_DIGITAL(pin), minPulse, maxPulse); 486 | setPinModeCallback(pin, SERVO); 487 | } 488 | } 489 | break; 490 | case SAMPLING_INTERVAL: 491 | if (argc > 1) { 492 | samplingInterval = argv[0] + (argv[1] << 7); 493 | if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { 494 | samplingInterval = MINIMUM_SAMPLING_INTERVAL; 495 | } 496 | } else { 497 | //BLE_Firmata.sendString("Not enough data"); 498 | } 499 | break; 500 | case EXTENDED_ANALOG: 501 | if (argc > 1) { 502 | int val = argv[1]; 503 | if (argc > 2) val |= (argv[2] << 7); 504 | if (argc > 3) val |= (argv[3] << 14); 505 | analogWriteCallback(argv[0], val); 506 | } 507 | break; 508 | case CAPABILITY_QUERY: 509 | bluefruit.write(START_SYSEX); 510 | bluefruit.write(CAPABILITY_RESPONSE); 511 | 512 | //FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.print(START_SYSEX, HEX); FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.println(CAPABILITY_RESPONSE, HEX); 513 | delay(10); 514 | for (byte pin=0; pin < TOTAL_PINS; pin++) { 515 | //FIRMATADEBUG.print("\t#"); FIRMATADEBUG.println(pin); 516 | if (BLE_Firmata.IS_PIN_DIGITAL(pin)) { 517 | bluefruit.write((byte)INPUT); 518 | bluefruit.write(1); 519 | bluefruit.write((byte)OUTPUT); 520 | bluefruit.write(1); 521 | 522 | /* 523 | FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.print(INPUT, HEX); 524 | FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.print(1, HEX); 525 | FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.print(OUTPUT, HEX); 526 | FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.println(1, HEX); 527 | */ 528 | delay(20); 529 | } else { 530 | bluefruit.write(127); 531 | //FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.println(127, HEX); 532 | delay(20); 533 | continue; 534 | } 535 | if (BLE_Firmata.IS_PIN_ANALOG(pin)) { 536 | bluefruit.write(ANALOG); 537 | bluefruit.write(10); 538 | 539 | //FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.print(ANALOG, HEX); FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.println(10, HEX); 540 | delay(20); 541 | } 542 | if (BLE_Firmata.IS_PIN_PWM(pin)) { 543 | bluefruit.write(PWM); 544 | bluefruit.write(8); 545 | 546 | //FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.print(PWM, HEX); FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.println(8, HEX); 547 | delay(20); 548 | } 549 | if (BLE_Firmata.IS_PIN_SERVO(pin)) { 550 | bluefruit.write(SERVO); 551 | bluefruit.write(14); 552 | 553 | //FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.print(SERVO, HEX);FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.println(14, HEX); 554 | delay(20); 555 | } 556 | if (BLE_Firmata.IS_PIN_I2C(pin)) { 557 | bluefruit.write(I2C); 558 | bluefruit.write(1); // to do: determine appropriate value 559 | delay(20); 560 | } 561 | bluefruit.write(127); 562 | //FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.println(127, HEX); 563 | } 564 | bluefruit.write(END_SYSEX); 565 | //FIRMATADEBUG.print(" 0x"); FIRMATADEBUG.println(END_SYSEX, HEX); 566 | break; 567 | case PIN_STATE_QUERY: 568 | if (argc > 0) { 569 | byte pin=argv[0]; 570 | bluefruit.write(START_SYSEX); 571 | bluefruit.write(PIN_STATE_RESPONSE); 572 | bluefruit.write(pin); 573 | if (pin < TOTAL_PINS) { 574 | bluefruit.write((byte)pinConfig[pin]); 575 | bluefruit.write((byte)pinState[pin] & 0x7F); 576 | if (pinState[pin] & 0xFF80) bluefruit.write((byte)(pinState[pin] >> 7) & 0x7F); 577 | if (pinState[pin] & 0xC000) bluefruit.write((byte)(pinState[pin] >> 14) & 0x7F); 578 | } 579 | bluefruit.write(END_SYSEX); 580 | } 581 | break; 582 | case ANALOG_MAPPING_QUERY: 583 | //FIRMATADEBUG.println("Analog mapping query"); 584 | bluefruit.write(START_SYSEX); 585 | bluefruit.write(ANALOG_MAPPING_RESPONSE); 586 | for (byte pin=0; pin < TOTAL_PINS; pin++) { 587 | bluefruit.write(BLE_Firmata.IS_PIN_ANALOG(pin) ? BLE_Firmata.PIN_TO_ANALOG(pin) : 127); 588 | } 589 | bluefruit.write(END_SYSEX); 590 | break; 591 | } 592 | } 593 | 594 | void enableI2CPins() 595 | { 596 | byte i; 597 | // is there a faster way to do this? would probaby require importing 598 | // Arduino.h to get SCL and SDA pins 599 | for (i=0; i < TOTAL_PINS; i++) { 600 | if(BLE_Firmata.IS_PIN_I2C(i)) { 601 | // mark pins as i2c so they are ignore in non i2c data requests 602 | setPinModeCallback(i, I2C); 603 | } 604 | } 605 | 606 | isI2CEnabled = true; 607 | 608 | // is there enough time before the first I2C request to call this here? 609 | Wire.begin(); 610 | } 611 | 612 | /* disable the i2c pins so they can be used for other functions */ 613 | void disableI2CPins() { 614 | isI2CEnabled = false; 615 | // disable read continuous mode for all devices 616 | queryIndex = -1; 617 | // uncomment the following if or when the end() method is added to Wire library 618 | // Wire.end(); 619 | } 620 | 621 | /*============================================================================== 622 | * SETUP() 623 | *============================================================================*/ 624 | 625 | void systemResetCallback() 626 | { 627 | // initialize a defalt state 628 | FIRMATADEBUG.println(F("***RESET***")); 629 | // TODO: option to load config from EEPROM instead of default 630 | if (isI2CEnabled) { 631 | disableI2CPins(); 632 | } 633 | for (byte i=0; i < TOTAL_PORTS; i++) { 634 | reportPINs[i] = false; // by default, reporting off 635 | portConfigInputs[i] = 0; // until activated 636 | previousPINs[i] = 0; 637 | } 638 | // pins with analog capability default to analog input 639 | // otherwise, pins default to digital output 640 | for (byte i=0; i < TOTAL_PINS; i++) { 641 | if (BLE_Firmata.IS_PIN_ANALOG(i)) { 642 | // turns off pullup, configures everything 643 | setPinModeCallback(i, ANALOG); 644 | } else { 645 | // sets the output to 0, configures portConfigInputs 646 | setPinModeCallback(i, INPUT); 647 | } 648 | } 649 | // by default, do not report any analog inputs 650 | analogInputsToReport = 0; 651 | 652 | /* send digital inputs to set the initial state on the host computer, 653 | * since once in the loop(), this firmware will only send on change */ 654 | /* 655 | TODO: this can never execute, since no pins default to digital input 656 | but it will be needed when/if we support EEPROM stored config 657 | for (byte i=0; i < TOTAL_PORTS; i++) { 658 | outputPort(i, readPort(i, portConfigInputs[i]), true); 659 | } 660 | */ 661 | } 662 | 663 | void setup() 664 | { 665 | if (WAITFORSERIAL) { 666 | while (!FIRMATADEBUG) delay(1); 667 | } 668 | 669 | FIRMATADEBUG.begin(9600); 670 | FIRMATADEBUG.println(F("Adafruit Bluefruit nRF8001 Firmata test")); 671 | 672 | FIRMATADEBUG.print("Total pins: "); FIRMATADEBUG.println(NUM_DIGITAL_PINS); 673 | FIRMATADEBUG.print("Analog pins: "); FIRMATADEBUG.println(sizeof(boards_analogiopins)); 674 | //for (uint8_t i=0; i samplingInterval) { 785 | previousMillis += samplingInterval; 786 | /* ANALOGREAD - do all analogReads() at the configured sampling interval */ 787 | 788 | for(pin=0; pin 13 | # 14 | # - Write prototypes for all your functions (or define them before you 15 | # call them). A prototype declares the types of parameters a 16 | # function will take and what type of value it will return. This 17 | # means that you can have a call to a function before the definition 18 | # of the function. A function prototype looks like the first line of 19 | # the function, with a semi-colon at the end. For example: 20 | # int digitalRead(int pin); 21 | # 22 | # Instructions for using the makefile: 23 | # 24 | # 1. Copy this file into the folder with your sketch. 25 | # 26 | # 2. Below, modify the line containing "TARGET" to refer to the name of 27 | # of your program's file without an extension (e.g. TARGET = foo). 28 | # 29 | # 3. Modify the line containg "ARDUINO" to point the directory that 30 | # contains the Arduino core (for normal Arduino installations, this 31 | # is the hardware/cores/arduino sub-directory). 32 | # 33 | # 4. Modify the line containing "PORT" to refer to the filename 34 | # representing the USB or serial connection to your Arduino board 35 | # (e.g. PORT = /dev/tty.USB0). If the exact name of this file 36 | # changes, you can use * as a wildcard (e.g. PORT = /dev/tty.USB*). 37 | # 38 | # 5. At the command line, change to the directory containing your 39 | # program's file and the makefile. 40 | # 41 | # 6. Type "make" and press enter to compile/verify your program. 42 | # 43 | # 7. Type "make upload", reset your Arduino board, and press enter to 44 | # upload your program to the Arduino board. 45 | # 46 | # $Id: Makefile,v 1.7 2007/04/13 05:28:23 eighthave Exp $ 47 | 48 | PORT = /dev/tty.usbserial-* 49 | TARGET := $(shell pwd | sed 's|.*/\(.*\)|\1|') 50 | ARDUINO = /Applications/arduino 51 | ARDUINO_SRC = $(ARDUINO)/hardware/cores/arduino 52 | ARDUINO_LIB_SRC = $(ARDUINO)/hardware/libraries 53 | ARDUINO_TOOLS = $(ARDUINO)/hardware/tools 54 | INCLUDE = -I$(ARDUINO_SRC) -I$(ARDUINO)/hardware/tools/avr/avr/include \ 55 | -I$(ARDUINO_LIB_SRC)/EEPROM \ 56 | -I$(ARDUINO_LIB_SRC)/Firmata \ 57 | -I$(ARDUINO_LIB_SRC)/Matrix \ 58 | -I$(ARDUINO_LIB_SRC)/Servo \ 59 | -I$(ARDUINO_LIB_SRC)/Wire \ 60 | -I$(ARDUINO_LIB_SRC) 61 | SRC = $(wildcard $(ARDUINO_SRC)/*.c) 62 | CXXSRC = applet/$(TARGET).cpp $(ARDUINO_SRC)/HardwareSerial.cpp \ 63 | $(ARDUINO_LIB_SRC)/EEPROM/EEPROM.cpp \ 64 | $(ARDUINO_LIB_SRC)/Firmata/Firmata.cpp \ 65 | $(ARDUINO_LIB_SRC)/Servo/Servo.cpp \ 66 | $(ARDUINO_SRC)/Print.cpp \ 67 | $(ARDUINO_SRC)/WMath.cpp 68 | HEADERS = $(wildcard $(ARDUINO_SRC)/*.h) $(wildcard $(ARDUINO_LIB_SRC)/*/*.h) 69 | 70 | MCU = atmega168 71 | #MCU = atmega8 72 | F_CPU = 16000000 73 | FORMAT = ihex 74 | UPLOAD_RATE = 19200 75 | 76 | # Name of this Makefile (used for "make depend"). 77 | MAKEFILE = Makefile 78 | 79 | # Debugging format. 80 | # Native formats for AVR-GCC's -g are stabs [default], or dwarf-2. 81 | # AVR (extended) COFF requires stabs, plus an avr-objcopy run. 82 | DEBUG = stabs 83 | 84 | OPT = s 85 | 86 | # Place -D or -U options here 87 | CDEFS = -DF_CPU=$(F_CPU) 88 | CXXDEFS = -DF_CPU=$(F_CPU) 89 | 90 | # Compiler flag to set the C Standard level. 91 | # c89 - "ANSI" C 92 | # gnu89 - c89 plus GCC extensions 93 | # c99 - ISO C99 standard (not yet fully implemented) 94 | # gnu99 - c99 plus GCC extensions 95 | CSTANDARD = -std=gnu99 96 | CDEBUG = -g$(DEBUG) 97 | CWARN = -Wall -Wstrict-prototypes 98 | CTUNING = -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums 99 | #CEXTRA = -Wa,-adhlns=$(<:.c=.lst) 100 | 101 | CFLAGS = $(CDEBUG) $(CDEFS) $(INCLUDE) -O$(OPT) $(CWARN) $(CSTANDARD) $(CEXTRA) 102 | CXXFLAGS = $(CDEFS) $(INCLUDE) -O$(OPT) 103 | #ASFLAGS = -Wa,-adhlns=$(<:.S=.lst),-gstabs 104 | LDFLAGS = 105 | 106 | 107 | # Programming support using avrdude. Settings and variables. 108 | AVRDUDE_PROGRAMMER = stk500 109 | AVRDUDE_PORT = $(PORT) 110 | AVRDUDE_WRITE_FLASH = -U flash:w:applet/$(TARGET).hex 111 | AVRDUDE_FLAGS = -F -p $(MCU) -P $(AVRDUDE_PORT) -c $(AVRDUDE_PROGRAMMER) \ 112 | -b $(UPLOAD_RATE) -q -V 113 | 114 | # Program settings 115 | ARDUINO_AVR_BIN = $(ARDUINO_TOOLS)/avr/bin 116 | CC = $(ARDUINO_AVR_BIN)/avr-gcc 117 | CXX = $(ARDUINO_AVR_BIN)/avr-g++ 118 | OBJCOPY = $(ARDUINO_AVR_BIN)/avr-objcopy 119 | OBJDUMP = $(ARDUINO_AVR_BIN)/avr-objdump 120 | SIZE = $(ARDUINO_AVR_BIN)/avr-size 121 | NM = $(ARDUINO_AVR_BIN)/avr-nm 122 | #AVRDUDE = $(ARDUINO_AVR_BIN)/avrdude 123 | AVRDUDE = avrdude 124 | REMOVE = rm -f 125 | MV = mv -f 126 | 127 | # Define all object files. 128 | OBJ = $(SRC:.c=.o) $(CXXSRC:.cpp=.o) $(ASRC:.S=.o) 129 | 130 | # Define all listing files. 131 | LST = $(ASRC:.S=.lst) $(CXXSRC:.cpp=.lst) $(SRC:.c=.lst) 132 | 133 | # Combine all necessary flags and optional flags. 134 | # Add target processor to flags. 135 | ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) 136 | ALL_CXXFLAGS = -mmcu=$(MCU) -I. $(CXXFLAGS) 137 | ALL_ASFLAGS = -mmcu=$(MCU) -I. -x assembler-with-cpp $(ASFLAGS) 138 | 139 | 140 | # Default target. 141 | all: build 142 | 143 | build: applet/$(TARGET).hex 144 | 145 | eep: applet/$(TARGET).eep 146 | lss: applet/$(TARGET).lss 147 | sym: applet/$(TARGET).sym 148 | 149 | 150 | # Convert ELF to COFF for use in debugging / simulating in AVR Studio or VMLAB. 151 | COFFCONVERT=$(OBJCOPY) --debugging \ 152 | --change-section-address .data-0x800000 \ 153 | --change-section-address .bss-0x800000 \ 154 | --change-section-address .noinit-0x800000 \ 155 | --change-section-address .eeprom-0x810000 156 | 157 | 158 | coff: applet/$(TARGET).elf 159 | $(COFFCONVERT) -O coff-avr applet/$(TARGET).elf applet/$(TARGET).cof 160 | 161 | 162 | extcoff: applet/$(TARGET).elf 163 | $(COFFCONVERT) -O coff-ext-avr applet/$(TARGET).elf applet/$(TARGET).cof 164 | 165 | 166 | .SUFFIXES: .elf .hex .eep .lss .sym .pde 167 | 168 | .elf.hex: 169 | $(OBJCOPY) -O $(FORMAT) -R .eeprom $< $@ 170 | 171 | .elf.eep: 172 | -$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \ 173 | --change-section-lma .eeprom=0 -O $(FORMAT) $< $@ 174 | 175 | # Create extended listing file from ELF output file. 176 | .elf.lss: 177 | $(OBJDUMP) -h -S $< > $@ 178 | 179 | # Create a symbol table from ELF output file. 180 | .elf.sym: 181 | $(NM) -n $< > $@ 182 | 183 | 184 | # Compile: create object files from C++ source files. 185 | .cpp.o: $(HEADERS) 186 | $(CXX) -c $(ALL_CXXFLAGS) $< -o $@ 187 | 188 | # Compile: create object files from C source files. 189 | .c.o: $(HEADERS) 190 | $(CC) -c $(ALL_CFLAGS) $< -o $@ 191 | 192 | 193 | # Compile: create assembler files from C source files. 194 | .c.s: 195 | $(CC) -S $(ALL_CFLAGS) $< -o $@ 196 | 197 | 198 | # Assemble: create object files from assembler source files. 199 | .S.o: 200 | $(CC) -c $(ALL_ASFLAGS) $< -o $@ 201 | 202 | 203 | 204 | applet/$(TARGET).cpp: $(TARGET).pde 205 | test -d applet || mkdir applet 206 | echo '#include "WProgram.h"' > applet/$(TARGET).cpp 207 | echo '#include "avr/interrupt.h"' >> applet/$(TARGET).cpp 208 | sed -n 's|^\(void .*)\).*|\1;|p' $(TARGET).pde | grep -v 'setup()' | \ 209 | grep -v 'loop()' >> applet/$(TARGET).cpp 210 | cat $(TARGET).pde >> applet/$(TARGET).cpp 211 | cat $(ARDUINO_SRC)/main.cxx >> applet/$(TARGET).cpp 212 | 213 | # Link: create ELF output file from object files. 214 | applet/$(TARGET).elf: applet/$(TARGET).cpp $(OBJ) 215 | $(CC) $(ALL_CFLAGS) $(OBJ) -lm --output $@ $(LDFLAGS) 216 | # $(CC) $(ALL_CFLAGS) $(OBJ) $(ARDUINO_TOOLS)/avr/avr/lib/avr5/crtm168.o --output $@ $(LDFLAGS) 217 | 218 | pd_close_serial: 219 | echo 'close;' | /Applications/Pd-extended.app/Contents/Resources/bin/pdsend 34567 || true 220 | 221 | # Program the device. 222 | upload: applet/$(TARGET).hex 223 | $(AVRDUDE) $(AVRDUDE_FLAGS) $(AVRDUDE_WRITE_FLASH) 224 | 225 | 226 | pd_test: build pd_close_serial upload 227 | 228 | # Target: clean project. 229 | clean: 230 | $(REMOVE) -- applet/$(TARGET).hex applet/$(TARGET).eep \ 231 | applet/$(TARGET).cof applet/$(TARGET).elf $(TARGET).map \ 232 | applet/$(TARGET).sym applet/$(TARGET).lss applet/$(TARGET).cpp \ 233 | $(OBJ) $(LST) $(SRC:.c=.s) $(SRC:.c=.d) $(CXXSRC:.cpp=.s) $(CXXSRC:.cpp=.d) 234 | rmdir -- applet 235 | 236 | depend: 237 | if grep '^# DO NOT DELETE' $(MAKEFILE) >/dev/null; \ 238 | then \ 239 | sed -e '/^# DO NOT DELETE/,$$d' $(MAKEFILE) > \ 240 | $(MAKEFILE).$$$$ && \ 241 | $(MV) $(MAKEFILE).$$$$ $(MAKEFILE); \ 242 | fi 243 | echo '# DO NOT DELETE THIS LINE -- make depend depends on it.' \ 244 | >> $(MAKEFILE); \ 245 | $(CC) -M -mmcu=$(MCU) $(CDEFS) $(INCLUDE) $(SRC) $(ASRC) >> $(MAKEFILE) 246 | 247 | .PHONY: all build eep lss sym coff extcoff clean depend pd_close_serial pd_test 248 | 249 | # for emacs 250 | etags: 251 | make etags_`uname -s` 252 | etags *.pde \ 253 | $(ARDUINO_SRC)/*.[ch] \ 254 | $(ARDUINO_SRC)/*.cpp \ 255 | $(ARDUINO_LIB_SRC)/*/*.[ch] \ 256 | $(ARDUINO_LIB_SRC)/*/*.cpp \ 257 | $(ARDUINO)/hardware/tools/avr/avr/include/avr/*.[ch] \ 258 | $(ARDUINO)/hardware/tools/avr/avr/include/*.[ch] 259 | 260 | etags_Darwin: 261 | # etags -a 262 | 263 | etags_Linux: 264 | # etags -a /usr/include/*.h linux/input.h /usr/include/sys/*.h 265 | 266 | etags_MINGW: 267 | # etags -a /usr/include/*.h /usr/include/sys/*.h 268 | 269 | 270 | path: 271 | echo $(PATH) 272 | echo $$PATH 273 | 274 | -------------------------------------------------------------------------------- /examples/StandardFirmata/StandardFirmata.ino: -------------------------------------------------------------------------------- 1 | /* 2 | * Firmata is a generic protocol for communicating with microcontrollers 3 | * from software on a host computer. It is intended to work with 4 | * any host computer software package. 5 | * 6 | * This version is modified to specifically work with Adafruit's BLE 7 | * library. It no longer works over the standard "USB" connection! 8 | */ 9 | 10 | /* 11 | Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. 12 | Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. 13 | Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. 14 | Copyright (C) 2009-2011 Jeff Hoefs. All rights reserved. 15 | Copyright (C) 2014 Limor Fried/Kevin Townsend All rights reserved. 16 | 17 | This library is free software; you can redistribute it and/or 18 | modify it under the terms of the GNU Lesser General Public 19 | License as published by the Free Software Foundation; either 20 | version 2.1 of the License, or (at your option) any later version. 21 | 22 | See file LICENSE.txt for further informations on licensing terms. 23 | 24 | formatted using the GNU C formatting and indenting 25 | */ 26 | 27 | /* 28 | * TODO: use Program Control to load stored profiles from EEPROM 29 | */ 30 | 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include "Adafruit_BLE_UART.h" 36 | 37 | #define AUTO_INPUT_PULLUPS true 38 | 39 | // Connect CLK/MISO/MOSI to hardware SPI 40 | // e.g. On UNO & compatible: CLK = 13, MISO = 12, MOSI = 11 41 | #define ADAFRUITBLE_REQ 10 42 | #define ADAFRUITBLE_RDY 2 // This should be an interrupt pin, on Uno thats #2 or #3 43 | #define ADAFRUITBLE_RST 9 44 | 45 | // so we have digital 3-8 and analog 0-6 46 | 47 | Adafruit_BLE_UART BLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST); 48 | 49 | 50 | // make one instance for the user to use 51 | Adafruit_BLE_FirmataClass BLE_Firmata(BLEserial); 52 | 53 | 54 | /*============================================================================== 55 | * GLOBAL VARIABLES 56 | *============================================================================*/ 57 | 58 | /* analog inputs */ 59 | int analogInputsToReport = 0; // bitwise array to store pin reporting 60 | int lastAnalogReads[NUM_ANALOG_INPUTS]; 61 | 62 | /* digital input ports */ 63 | byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence 64 | byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent 65 | 66 | /* pins configuration */ 67 | byte pinConfig[TOTAL_PINS]; // configuration of every pin 68 | byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else 69 | int pinState[TOTAL_PINS]; // any value that has been written 70 | 71 | /* timer variables */ 72 | unsigned long currentMillis; // store the current value from millis() 73 | unsigned long previousMillis; // for comparison with currentMillis 74 | int samplingInterval = 200; // how often to run the main loop (in ms) 75 | #define MINIMUM_SAMPLE_DELAY 150 76 | #define ANALOG_SAMPLE_DELAY 50 77 | 78 | 79 | /* i2c data */ 80 | struct i2c_device_info { 81 | byte addr; 82 | byte reg; 83 | byte bytes; 84 | }; 85 | 86 | /* for i2c read continuous more */ 87 | i2c_device_info query[MAX_QUERIES]; 88 | 89 | byte i2cRxData[32]; 90 | boolean isI2CEnabled = false; 91 | signed char queryIndex = -1; 92 | unsigned int i2cReadDelayTime = 0; // default delay time between i2c read request and Wire.requestFrom() 93 | 94 | Servo servos[MAX_SERVOS]; 95 | /*============================================================================== 96 | * FUNCTIONS 97 | *============================================================================*/ 98 | 99 | void readAndReportData(byte address, int theRegister, byte numBytes) { 100 | // allow I2C requests that don't require a register read 101 | // for example, some devices using an interrupt pin to signify new data available 102 | // do not always require the register read so upon interrupt you call Wire.requestFrom() 103 | if (theRegister != REGISTER_NOT_SPECIFIED) { 104 | Wire.beginTransmission(address); 105 | #if ARDUINO >= 100 106 | Wire.write((byte)theRegister); 107 | #else 108 | Wire.send((byte)theRegister); 109 | #endif 110 | Wire.endTransmission(); 111 | delayMicroseconds(i2cReadDelayTime); // delay is necessary for some devices such as WiiNunchuck 112 | } else { 113 | theRegister = 0; // fill the register with a dummy value 114 | } 115 | 116 | Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom 117 | 118 | // check to be sure correct number of bytes were returned by slave 119 | if(numBytes == Wire.available()) { 120 | i2cRxData[0] = address; 121 | i2cRxData[1] = theRegister; 122 | for (int i = 0; i < numBytes; i++) { 123 | #if ARDUINO >= 100 124 | i2cRxData[2 + i] = Wire.read(); 125 | #else 126 | i2cRxData[2 + i] = Wire.receive(); 127 | #endif 128 | } 129 | } 130 | else { 131 | if(numBytes > Wire.available()) { 132 | BLE_Firmata.sendString("I2C Read Error: Too many bytes received"); 133 | } else { 134 | BLE_Firmata.sendString("I2C Read Error: Too few bytes received"); 135 | } 136 | } 137 | 138 | // send slave address, register and received bytes 139 | BLE_Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); 140 | } 141 | 142 | void outputPort(byte portNumber, byte portValue, byte forceSend) 143 | { 144 | // pins not configured as INPUT are cleared to zeros 145 | portValue = portValue & portConfigInputs[portNumber]; 146 | // only send if the value is different than previously sent 147 | if(forceSend || previousPINs[portNumber] != portValue) { 148 | Serial.print(F("Sending update for port ")); Serial.print(portNumber); Serial.print(" = 0x"); Serial.println(portValue, HEX); 149 | BLE_Firmata.sendDigitalPort(portNumber, portValue); 150 | previousPINs[portNumber] = portValue; 151 | } 152 | } 153 | 154 | /* ----------------------------------------------------------------------------- 155 | * check all the active digital inputs for change of state, then add any events 156 | * to the Serial output queue using Serial.print() */ 157 | void checkDigitalInputs(boolean forceSend = false) 158 | { 159 | /* Using non-looping code allows constants to be given to readPort(). 160 | * The compiler will apply substantial optimizations if the inputs 161 | * to readPort() are compile-time constants. */ 162 | for (uint8_t i=0; i TOTAL_PINS) lastPin = TOTAL_PINS; 289 | for (pin=port*8; pin < lastPin; pin++) { 290 | // do not disturb non-digital pins (eg, Rx & Tx) 291 | if (IS_PIN_DIGITAL(pin)) { 292 | // only write to OUTPUT and INPUT (enables pullup) 293 | // do not touch pins in PWM, ANALOG, SERVO or other modes 294 | if (pinConfig[pin] == OUTPUT || pinConfig[pin] == INPUT) { 295 | pinWriteMask |= mask; 296 | pinState[pin] = ((byte)value & mask) ? 1 : 0; 297 | 298 | if (AUTO_INPUT_PULLUPS && ( pinConfig[pin] == INPUT)) { 299 | value |= mask; 300 | } 301 | } 302 | } 303 | mask = mask << 1; 304 | } 305 | Serial.print(F("Write digital port #")); Serial.print(port); 306 | Serial.print(F(" = 0x")); Serial.print(value, HEX); 307 | Serial.print(F(" mask = 0x")); Serial.println(pinWriteMask, HEX); 308 | writePort(port, (byte)value, pinWriteMask); 309 | } 310 | } 311 | 312 | 313 | // ----------------------------------------------------------------------------- 314 | /* sets bits in a bit array (int) to toggle the reporting of the analogIns 315 | */ 316 | //void FirmataClass::setAnalogPinReporting(byte pin, byte state) { 317 | //} 318 | void reportAnalogCallback(byte analogPin, int value) 319 | { 320 | if (analogPin < TOTAL_ANALOG_PINS) { 321 | if(value == 0) { 322 | analogInputsToReport = analogInputsToReport &~ (1 << analogPin); 323 | Serial.print(F("Stop reporting analog pin #")); Serial.println(analogPin); 324 | } else { 325 | analogInputsToReport |= (1 << analogPin); 326 | Serial.print(F("Will report analog pin #")); Serial.println(analogPin); 327 | } 328 | } 329 | // TODO: save status to EEPROM here, if changed 330 | } 331 | 332 | void reportDigitalCallback(byte port, int value) 333 | { 334 | if (port < TOTAL_PORTS) { 335 | Serial.print(F("Will report 0x")); Serial.print(value, HEX); Serial.print(F(" digital mask on port ")); Serial.println(port); 336 | reportPINs[port] = (byte)value; 337 | } 338 | // do not disable analog reporting on these 8 pins, to allow some 339 | // pins used for digital, others analog. Instead, allow both types 340 | // of reporting to be enabled, but check if the pin is configured 341 | // as analog when sampling the analog inputs. Likewise, while 342 | // scanning digital pins, portConfigInputs will mask off values from any 343 | // pins configured as analog 344 | } 345 | 346 | /*============================================================================== 347 | * SYSEX-BASED commands 348 | *============================================================================*/ 349 | 350 | void sysexCallback(byte command, byte argc, byte *argv) 351 | { 352 | byte mode; 353 | byte slaveAddress; 354 | byte slaveRegister; 355 | byte data; 356 | unsigned int delayTime; 357 | 358 | switch(command) { 359 | case I2C_REQUEST: 360 | mode = argv[1] & I2C_READ_WRITE_MODE_MASK; 361 | if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { 362 | //BLE_Firmata.sendString("10-bit addressing mode is not yet supported"); 363 | Serial.println(F("10-bit addressing mode is not yet supported")); 364 | return; 365 | } 366 | else { 367 | slaveAddress = argv[0]; 368 | } 369 | 370 | switch(mode) { 371 | case I2C_WRITE: 372 | Wire.beginTransmission(slaveAddress); 373 | for (byte i = 2; i < argc; i += 2) { 374 | data = argv[i] + (argv[i + 1] << 7); 375 | #if ARDUINO >= 100 376 | Wire.write(data); 377 | #else 378 | Wire.send(data); 379 | #endif 380 | } 381 | Wire.endTransmission(); 382 | delayMicroseconds(70); 383 | break; 384 | case I2C_READ: 385 | if (argc == 6) { 386 | // a slave register is specified 387 | slaveRegister = argv[2] + (argv[3] << 7); 388 | data = argv[4] + (argv[5] << 7); // bytes to read 389 | readAndReportData(slaveAddress, (int)slaveRegister, data); 390 | } 391 | else { 392 | // a slave register is NOT specified 393 | data = argv[2] + (argv[3] << 7); // bytes to read 394 | readAndReportData(slaveAddress, (int)REGISTER_NOT_SPECIFIED, data); 395 | } 396 | break; 397 | case I2C_READ_CONTINUOUSLY: 398 | if ((queryIndex + 1) >= MAX_QUERIES) { 399 | // too many queries, just ignore 400 | BLE_Firmata.sendString("too many queries"); 401 | break; 402 | } 403 | queryIndex++; 404 | query[queryIndex].addr = slaveAddress; 405 | query[queryIndex].reg = argv[2] + (argv[3] << 7); 406 | query[queryIndex].bytes = argv[4] + (argv[5] << 7); 407 | break; 408 | case I2C_STOP_READING: 409 | byte queryIndexToSkip; 410 | // if read continuous mode is enabled for only 1 i2c device, disable 411 | // read continuous reporting for that device 412 | if (queryIndex <= 0) { 413 | queryIndex = -1; 414 | } else { 415 | // if read continuous mode is enabled for multiple devices, 416 | // determine which device to stop reading and remove it's data from 417 | // the array, shifiting other array data to fill the space 418 | for (byte i = 0; i < queryIndex + 1; i++) { 419 | if (query[i].addr = slaveAddress) { 420 | queryIndexToSkip = i; 421 | break; 422 | } 423 | } 424 | 425 | for (byte i = queryIndexToSkip; i 0) { 443 | i2cReadDelayTime = delayTime; 444 | } 445 | 446 | if (!isI2CEnabled) { 447 | enableI2CPins(); 448 | } 449 | 450 | break; 451 | case SERVO_CONFIG: 452 | if(argc > 4) { 453 | // these vars are here for clarity, they'll optimized away by the compiler 454 | byte pin = argv[0]; 455 | int minPulse = argv[1] + (argv[2] << 7); 456 | int maxPulse = argv[3] + (argv[4] << 7); 457 | 458 | if (IS_PIN_SERVO(pin)) { 459 | if (servos[PIN_TO_SERVO(pin)].attached()) 460 | servos[PIN_TO_SERVO(pin)].detach(); 461 | servos[PIN_TO_SERVO(pin)].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse); 462 | setPinModeCallback(pin, SERVO); 463 | } 464 | } 465 | break; 466 | case SAMPLING_INTERVAL: 467 | if (argc > 1) { 468 | samplingInterval = argv[0] + (argv[1] << 7); 469 | if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { 470 | samplingInterval = MINIMUM_SAMPLING_INTERVAL; 471 | } 472 | } else { 473 | //BLE_Firmata.sendString("Not enough data"); 474 | } 475 | break; 476 | case EXTENDED_ANALOG: 477 | if (argc > 1) { 478 | int val = argv[1]; 479 | if (argc > 2) val |= (argv[2] << 7); 480 | if (argc > 3) val |= (argv[3] << 14); 481 | analogWriteCallback(argv[0], val); 482 | } 483 | break; 484 | case CAPABILITY_QUERY: 485 | Serial.write(START_SYSEX); 486 | Serial.write(CAPABILITY_RESPONSE); 487 | for (byte pin=0; pin < TOTAL_PINS; pin++) { 488 | if (IS_PIN_DIGITAL(pin)) { 489 | Serial.write((byte)INPUT); 490 | Serial.write(1); 491 | Serial.write((byte)OUTPUT); 492 | Serial.write(1); 493 | } 494 | if (IS_PIN_ANALOG(pin)) { 495 | Serial.write(ANALOG); 496 | Serial.write(10); 497 | } 498 | if (IS_PIN_PWM(pin)) { 499 | Serial.write(PWM); 500 | Serial.write(8); 501 | } 502 | if (IS_PIN_SERVO(pin)) { 503 | Serial.write(SERVO); 504 | Serial.write(14); 505 | } 506 | if (IS_PIN_I2C(pin)) { 507 | Serial.write(I2C); 508 | Serial.write(1); // to do: determine appropriate value 509 | } 510 | Serial.write(127); 511 | } 512 | Serial.write(END_SYSEX); 513 | break; 514 | case PIN_STATE_QUERY: 515 | if (argc > 0) { 516 | byte pin=argv[0]; 517 | Serial.write(START_SYSEX); 518 | Serial.write(PIN_STATE_RESPONSE); 519 | Serial.write(pin); 520 | if (pin < TOTAL_PINS) { 521 | Serial.write((byte)pinConfig[pin]); 522 | Serial.write((byte)pinState[pin] & 0x7F); 523 | if (pinState[pin] & 0xFF80) Serial.write((byte)(pinState[pin] >> 7) & 0x7F); 524 | if (pinState[pin] & 0xC000) Serial.write((byte)(pinState[pin] >> 14) & 0x7F); 525 | } 526 | Serial.write(END_SYSEX); 527 | } 528 | break; 529 | case ANALOG_MAPPING_QUERY: 530 | Serial.write(START_SYSEX); 531 | Serial.write(ANALOG_MAPPING_RESPONSE); 532 | for (byte pin=0; pin < TOTAL_PINS; pin++) { 533 | Serial.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127); 534 | } 535 | Serial.write(END_SYSEX); 536 | break; 537 | } 538 | } 539 | 540 | void enableI2CPins() 541 | { 542 | byte i; 543 | // is there a faster way to do this? would probaby require importing 544 | // Arduino.h to get SCL and SDA pins 545 | for (i=0; i < TOTAL_PINS; i++) { 546 | if(IS_PIN_I2C(i)) { 547 | // mark pins as i2c so they are ignore in non i2c data requests 548 | setPinModeCallback(i, I2C); 549 | } 550 | } 551 | 552 | isI2CEnabled = true; 553 | 554 | // is there enough time before the first I2C request to call this here? 555 | Wire.begin(); 556 | } 557 | 558 | /* disable the i2c pins so they can be used for other functions */ 559 | void disableI2CPins() { 560 | isI2CEnabled = false; 561 | // disable read continuous mode for all devices 562 | queryIndex = -1; 563 | // uncomment the following if or when the end() method is added to Wire library 564 | // Wire.end(); 565 | } 566 | 567 | /*============================================================================== 568 | * SETUP() 569 | *============================================================================*/ 570 | 571 | void systemResetCallback() 572 | { 573 | // initialize a defalt state 574 | Serial.println(F("***RESET***")); 575 | // TODO: option to load config from EEPROM instead of default 576 | if (isI2CEnabled) { 577 | disableI2CPins(); 578 | } 579 | for (byte i=0; i < TOTAL_PORTS; i++) { 580 | reportPINs[i] = false; // by default, reporting off 581 | portConfigInputs[i] = 0; // until activated 582 | previousPINs[i] = 0; 583 | } 584 | // pins with analog capability default to analog input 585 | // otherwise, pins default to digital output 586 | for (byte i=0; i < TOTAL_PINS; i++) { 587 | if (IS_PIN_ANALOG(i)) { 588 | // turns off pullup, configures everything 589 | setPinModeCallback(i, ANALOG); 590 | } else { 591 | // sets the output to 0, configures portConfigInputs 592 | setPinModeCallback(i, INPUT); 593 | } 594 | } 595 | // by default, do not report any analog inputs 596 | analogInputsToReport = 0; 597 | 598 | /* send digital inputs to set the initial state on the host computer, 599 | * since once in the loop(), this firmware will only send on change */ 600 | /* 601 | TODO: this can never execute, since no pins default to digital input 602 | but it will be needed when/if we support EEPROM stored config 603 | for (byte i=0; i < TOTAL_PORTS; i++) { 604 | outputPort(i, readPort(i, portConfigInputs[i]), true); 605 | } 606 | */ 607 | } 608 | 609 | 610 | aci_evt_opcode_t lastBTLEstatus, BTLEstatus; 611 | 612 | void setup() 613 | { 614 | Serial.begin(9600); 615 | Serial.println(F("Adafruit BTLE Firmata test")); 616 | 617 | BLEserial.begin(); 618 | 619 | BTLEstatus = lastBTLEstatus = ACI_EVT_DISCONNECTED; 620 | } 621 | 622 | void firmataInit() { 623 | Serial.println(F("Init firmata")); 624 | //BLE_Firmata.setFirmwareVersion(FIRMATA_MAJOR_VERSION, FIRMATA_MINOR_VERSION); 625 | //Serial.println(F("firmata analog")); 626 | BLE_Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); 627 | //Serial.println(F("firmata digital")); 628 | BLE_Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); 629 | //Serial.println(F("firmata analog report")); 630 | BLE_Firmata.attach(REPORT_ANALOG, reportAnalogCallback); 631 | //Serial.println(F("firmata digital report")); 632 | BLE_Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); 633 | //Serial.println(F("firmata pinmode")); 634 | BLE_Firmata.attach(SET_PIN_MODE, setPinModeCallback); 635 | //Serial.println(F("firmata sysex")); 636 | BLE_Firmata.attach(START_SYSEX, sysexCallback); 637 | //Serial.println(F("firmata reset")); 638 | BLE_Firmata.attach(SYSTEM_RESET, systemResetCallback); 639 | 640 | Serial.println(F("Begin firmata")); 641 | BLE_Firmata.begin(); 642 | systemResetCallback(); // reset to default config 643 | } 644 | /*============================================================================== 645 | * LOOP() 646 | *============================================================================*/ 647 | 648 | void loop() 649 | { 650 | // Check the BTLE link, how're we doing? 651 | BLEserial.pollACI(); 652 | // Link status check 653 | BTLEstatus = BLEserial.getState(); 654 | 655 | // Check if something has changed 656 | if (BTLEstatus != lastBTLEstatus) { 657 | // print it out! 658 | if (BTLEstatus == ACI_EVT_DEVICE_STARTED) { 659 | Serial.println(F("* Advertising started")); 660 | } 661 | if (BTLEstatus == ACI_EVT_CONNECTED) { 662 | Serial.println(F("* Connected!")); 663 | // initialize Firmata cleanly 664 | firmataInit(); 665 | } 666 | if (BTLEstatus == ACI_EVT_DISCONNECTED) { 667 | Serial.println(F("* Disconnected or advertising timed out")); 668 | } 669 | // OK set the last status change to this one 670 | lastBTLEstatus = BTLEstatus; 671 | } 672 | 673 | // if not connected... bail 674 | if (BTLEstatus != ACI_EVT_CONNECTED) { 675 | delay(100); 676 | return; 677 | } 678 | 679 | // For debugging, see if there's data on the serial console, we would forwad it to BTLE 680 | if (Serial.available()) { 681 | BLEserial.write(Serial.read()); 682 | } 683 | 684 | // Onto the Firmata main loop 685 | 686 | byte pin, analogPin; 687 | 688 | /* DIGITALREAD - as fast as possible, check for changes and output them to the 689 | * BTLE buffer using Serial.print() */ 690 | checkDigitalInputs(); 691 | 692 | /* SERIALREAD - processing incoming messagse as soon as possible, while still 693 | * checking digital inputs. */ 694 | while(BLE_Firmata.available()) { 695 | //Serial.println(F("*data available*")); 696 | BLE_Firmata.processInput(); 697 | } 698 | /* SEND FTDI WRITE BUFFER - make sure that the FTDI buffer doesn't go over 699 | * 60 bytes. use a timer to sending an event character every 4 ms to 700 | * trigger the buffer to dump. */ 701 | 702 | // make the sampling interval longer if we have more analog inputs! 703 | uint8_t analogreportnums = 0; 704 | for(uint8_t a=0; a<8; a++) { 705 | if (analogInputsToReport & (1 << a)) { 706 | analogreportnums++; 707 | } 708 | } 709 | 710 | samplingInterval = (uint16_t)MINIMUM_SAMPLE_DELAY + (uint16_t)ANALOG_SAMPLE_DELAY * (1+analogreportnums); 711 | 712 | currentMillis = millis(); 713 | if (currentMillis - previousMillis > samplingInterval) { 714 | previousMillis += samplingInterval; 715 | /* ANALOGREAD - do all analogReads() at the configured sampling interval */ 716 | for(pin=0; pin