source: trunk/Arduino/libraries/Adafruit_Circuit_Playground/examples/CircuitPlaygroundFirmata/CircuitPlaygroundFirmata.ino @ 7

Last change on this file since 7 was 3, checked in by markus, 7 years ago

Setup project structure

File size: 43.5 KB
Line 
1/*
2  Circuit Playground Firmata Firmware
3
4  Special version of the Firmata firmware for Adafruit's Circuit Playground
5  physical computing board.  Based on the StandardFirmata firmware but
6  with extensions for the components and sensors on the Circuit Playground
7  board (NeoPixels, LIS3DH accelerometer, etc).
8
9  Firmata is a generic protocol for communicating with microcontrollers
10  from software on a host computer. It is intended to work with
11  any host computer software package.
12
13  To download a host software package, please clink on the following link
14  to open the list of Firmata client libraries your default browser.
15
16  https://github.com/firmata/arduino#firmata-client-libraries
17
18  Copyright (C) 2006-2008 Hans-Christoph Steiner.  All rights reserved.
19  Copyright (C) 2010-2011 Paul Stoffregen.  All rights reserved.
20  Copyright (C) 2009 Shigeru Kobayashi.  All rights reserved.
21  Copyright (C) 2009-2015 Jeff Hoefs.  All rights reserved.
22  Copyright (C) 2016 Tony DiCola.  All rights reservered.
23
24  This library is free software; you can redistribute it and/or
25  modify it under the terms of the GNU Lesser General Public
26  License as published by the Free Software Foundation; either
27  version 2.1 of the License, or (at your option) any later version.
28
29  See file LICENSE.txt for further informations on licensing terms.
30*/
31
32#include <SPI.h>
33#include <Servo.h>
34#include <Wire.h>
35#include <Adafruit_CircuitPlayground.h>
36
37// Uncomment below to enable debug output.
38//#define DEBUG_MODE
39
40// Uncomment below to add a demo mode before USB connect
41#define DEMO_MODE
42
43// These defines setup debug output if enabled above (otherwise it
44// turns into no-ops that compile out).
45#define DEBUG_OUTPUT Serial1
46#define DEBUG_BAUD   9600
47
48#ifdef DEBUG_MODE
49  #define DEBUG_PRINT(...) { DEBUG_OUTPUT.print(__VA_ARGS__); }
50  #define DEBUG_PRINTLN(...) { DEBUG_OUTPUT.println(__VA_ARGS__); }
51#else
52  #define DEBUG_PRINT(...) {}
53  #define DEBUG_PRINTLN(...) {}
54#endif
55
56#define I2C_WRITE                   B00000000
57#define I2C_READ                    B00001000
58#define I2C_READ_CONTINUOUSLY       B00010000
59#define I2C_STOP_READING            B00011000
60#define I2C_READ_WRITE_MODE_MASK    B00011000
61#define I2C_10BIT_ADDRESS_MODE_MASK B00100000
62#define I2C_MAX_QUERIES             8
63#define I2C_REGISTER_NOT_SPECIFIED  -1
64
65// Circuit playground configuration:
66#define PIXEL_COUNT    10     // Number of NeoPixels on the board.
67#define PIXEL_PIN      17     // Digital pin connected to the NeoPixel signal line.
68#define PIXEL_TYPE     NEO_GRB + NEO_KHZ800  // NeoPixel type.
69#define SPEAKER_PIN    5      // Digital pin connected to the speaker.
70#define LIS3DH_ADDR    0x18   // LIS3DH I2C address (not used).
71#define LIS3DH_CS      8      // LIS3DH chip select line.
72#define CAP_COUNT      8      // Number of cap touch inputs.
73#define CAP_COMMON     30     // Digital input as the common cap touch pin.
74#define CAP_SAMPLES    30     // Number of samples to take for a cap touch input.
75
76// Circuit playground-specific Firmata SysEx commands:
77#define CP_COMMAND              0x40  // Byte that identifies all Circuit Playground commands.
78#define CP_PIXEL_SET            0x10  // Set NeoPixel, expects the following bytes as data:
79                                      //  - Pixel ID (0-9)
80                                      //  - Pixel RGB color data as 4 7-bit bytes.  The upper
81                                      //    24 bits will be mapped to the R, G, B bytes.
82#define CP_PIXEL_SHOW           0x11  // Update NeoPixels with their current color values.
83#define CP_PIXEL_CLEAR          0x12  // Clear all NeoPixels to black/off.  Must call show pixels after this to see the change!
84#define CP_PIXEL_BRIGHTNESS     0x13  // Set the brightness of the NeoPixels, just like calling the
85                                      // NeoPixel library setBrightness function.  Takes one parameter
86                                      // which is a single byte with a value 0-100.
87#define CP_TONE                 0x20  // Play a tone on the speaker, expects the following bytes as data:
88                                      //  - Frequency (hz) as 2 7-bit bytes (up to 2^14 hz, or about 16khz)
89                                      //  - Duration (ms) as 2 7-bit bytes.
90#define CP_NO_TONE              0x21  // Stop playing anything on the speaker.
91#define CP_ACCEL_READ           0x30  // Return the current x, y, z accelerometer values.
92#define CP_ACCEL_TAP            0x31  // Return the current accelerometer tap state.
93#define CP_ACCEL_READ_REPLY     0x36  // Result of an acceleromete read.  Includes 3 floating point values (4 bytes each) with x, y, z
94                                      // acceleration in meters/second^2.
95#define CP_ACCEL_TAP_REPLY      0x37  // Result of the tap sensor read.  Includes a byte with the tap register value.
96#define CP_ACCEL_TAP_STREAM_ON  0x38  // Turn on continuous streaming of tap data.
97#define CP_ACCEL_TAP_STREAM_OFF 0x39  // Turn off streaming of tap data.
98#define CP_ACCEL_STREAM_ON      0x3A  // Turn on continuous streaming of accelerometer data.
99#define CP_ACCEL_STREAM_OFF     0x3B  // Turn off streaming of accelerometer data.
100#define CP_ACCEL_RANGE          0x3C  // Set the range of the accelerometer, takes one byte as a parameter.
101                                      // Use a value 0=+/-2G, 1=+/-4G, 2=+/-8G, 3=+/-16G
102#define CP_ACCEL_TAP_CONFIG     0x3D  // Set the sensitivity of the tap detection, takes 4 bytes of 7-bit firmata
103                                      // data as parameters which expand to 2 unsigned 8-bit bytes value to set:
104                                      //   - Type of click: 0 = no click detection, 1 = single click, 2 = single & double click (default)
105                                      //   - Click threshold: 0-255, the higher the value the less sensitive.  Depends on the accelerometer
106                                      //     range, good values are: +/-16G = 5-10, +/-8G = 10-20, +/-4G = 20-40, +/-2G = 40-80
107                                      //     80 is the default value (goes well with default of +/-2G)
108#define CP_CAP_READ             0x40  // Read a single capacitive input.  Expects a byte as a parameter with the
109                                      // cap touch input to read (0, 1, 2, 3, 6, 9, 10, 12).  Will respond with a
110                                      // CP_CAP_REPLY message.
111#define CP_CAP_ON               0x41  // Turn on continuous cap touch reads for the specified input (sent as a byte parameter).
112#define CP_CAP_OFF              0x42  // Turn off continuous cap touch reads for the specified input (sent as a byte parameter).
113#define CP_CAP_REPLY            0x43  // Capacitive input read response.  Includes a byte with the pin # of the cap input, then
114                                      // four bytes of data which represent an int32_t value read from the cap input.
115#define CP_SENSECOLOR           0x50  // Perform a color sense using the NeoPixel and light sensor.
116#define CP_SENSECOLOR_REPLY     0x51  // Result of a color sense, will return the red, green, blue color
117                                      // values that were read from the light sensor.  This will return
118                                      // 6 bytes of data:
119                                      //  - red color (unsigned 8 bit value, split across 2 7-bit bytes)
120                                      //  - green color (unsigned 8 bit value, split across 2 7-bit bytes)
121                                      //  - blue color (unsigned 8 bit value, split across 2 7-bit bytes)
122
123
124// the minimum interval for sampling analog input
125#define MINIMUM_SAMPLING_INTERVAL   1
126
127
128/*==============================================================================
129 * GLOBAL VARIABLES
130 *============================================================================*/
131
132// Circuit playground globals:
133bool streamTap = false;
134bool streamAccel = false;
135// Define type for the cap touch sensor state of each cap touch input.
136typedef struct {
137  bool streaming;
138  uint8_t pin;
139} cap_state_type;
140
141cap_state_type cap_state[CAP_COUNT] = {
142  {
143    .streaming = false,
144    .pin       = 0
145  },
146  {
147    .streaming = false,
148    .pin       = 1
149  },
150  {
151    .streaming = false,
152    .pin       = 2
153  },
154  {
155    .streaming = false,
156    .pin       = 3
157  },
158  {
159    .streaming = false,
160    .pin       = 6
161  },
162  {
163    .streaming = false,
164    .pin       = 9
165  },
166  {
167    .streaming = false,
168    .pin       = 10
169  },
170  {
171    .streaming = false,
172    .pin       = 12
173  }
174};
175
176
177/* analog inputs */
178int analogInputsToReport = 0; // bitwise array to store pin reporting
179
180/* digital input ports */
181byte reportPINs[TOTAL_PORTS];       // 1 = report this port, 0 = silence
182byte previousPINs[TOTAL_PORTS];     // previous 8 bits sent
183
184/* pins configuration */
185byte pinConfig[TOTAL_PINS];         // configuration of every pin
186byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else
187int pinState[TOTAL_PINS];           // any value that has been written
188
189/* timer variables */
190unsigned long currentMillis;        // store the current value from millis()
191unsigned long previousMillis;       // for comparison with currentMillis
192unsigned int samplingInterval = 19; // how often to run the main loop (in ms)
193
194/* i2c data */
195struct i2c_device_info {
196  byte addr;
197  int reg;
198  byte bytes;
199};
200
201/* for i2c read continuous more */
202i2c_device_info query[I2C_MAX_QUERIES];
203
204byte i2cRxData[64];
205boolean isI2CEnabled = false;
206signed char queryIndex = -1;
207// default delay time between i2c read request and Wire.requestFrom()
208unsigned int i2cReadDelayTime = 0;
209
210Servo servos[MAX_SERVOS];
211byte servoPinMap[TOTAL_PINS];
212byte detachedServos[MAX_SERVOS];
213byte detachedServoCount = 0;
214byte servoCount = 0;
215
216boolean isResetting = false;
217
218/* utility functions */
219void wireWrite(byte data)
220{
221#if ARDUINO >= 100
222  Wire.write((byte)data);
223#else
224  Wire.send(data);
225#endif
226}
227
228byte wireRead(void)
229{
230#if ARDUINO >= 100
231  return Wire.read();
232#else
233  return Wire.receive();
234#endif
235}
236
237/*==============================================================================
238 * FUNCTIONS
239 *============================================================================*/
240
241void attachServo(byte pin, int minPulse, int maxPulse)
242{
243  if (servoCount < MAX_SERVOS) {
244    // reuse indexes of detached servos until all have been reallocated
245    if (detachedServoCount > 0) {
246      servoPinMap[pin] = detachedServos[detachedServoCount - 1];
247      if (detachedServoCount > 0) detachedServoCount--;
248    } else {
249      servoPinMap[pin] = servoCount;
250      servoCount++;
251    }
252    if (minPulse > 0 && maxPulse > 0) {
253      servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse);
254    } else {
255      servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin));
256    }
257  } else {
258    Firmata.sendString("Max servos attached");
259  }
260}
261
262void detachServo(byte pin)
263{
264  servos[servoPinMap[pin]].detach();
265  // if we're detaching the last servo, decrement the count
266  // otherwise store the index of the detached servo
267  if (servoPinMap[pin] == servoCount && servoCount > 0) {
268    servoCount--;
269  } else if (servoCount > 0) {
270    // keep track of detached servos because we want to reuse their indexes
271    // before incrementing the count of attached servos
272    detachedServoCount++;
273    detachedServos[detachedServoCount - 1] = servoPinMap[pin];
274  }
275
276  servoPinMap[pin] = 255;
277}
278
279void readAndReportData(byte address, int theRegister, byte numBytes) {
280  // allow I2C requests that don't require a register read
281  // for example, some devices using an interrupt pin to signify new data available
282  // do not always require the register read so upon interrupt you call Wire.requestFrom()
283  if (theRegister != I2C_REGISTER_NOT_SPECIFIED) {
284    Wire.beginTransmission(address);
285    wireWrite((byte)theRegister);
286    Wire.endTransmission();
287    // do not set a value of 0
288    if (i2cReadDelayTime > 0) {
289      // delay is necessary for some devices such as WiiNunchuck
290      delayMicroseconds(i2cReadDelayTime);
291    }
292  } else {
293    theRegister = 0;  // fill the register with a dummy value
294  }
295
296  Wire.requestFrom(address, numBytes);  // all bytes are returned in requestFrom
297
298  // check to be sure correct number of bytes were returned by slave
299  if (numBytes < Wire.available()) {
300    Firmata.sendString("I2C: Too many bytes received");
301  } else if (numBytes > Wire.available()) {
302    Firmata.sendString("I2C: Too few bytes received");
303  }
304
305  i2cRxData[0] = address;
306  i2cRxData[1] = theRegister;
307
308  for (int i = 0; i < numBytes && Wire.available(); i++) {
309    i2cRxData[2 + i] = wireRead();
310  }
311
312  // send slave address, register and received bytes
313  Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData);
314}
315
316void outputPort(byte portNumber, byte portValue, byte forceSend)
317{
318  // pins not configured as INPUT are cleared to zeros
319  portValue = portValue & portConfigInputs[portNumber];
320  // only send if the value is different than previously sent
321  if (forceSend || previousPINs[portNumber] != portValue) {
322    Firmata.sendDigitalPort(portNumber, portValue);
323    previousPINs[portNumber] = portValue;
324  }
325}
326
327/* -----------------------------------------------------------------------------
328 * check all the active digital inputs for change of state, then add any events
329 * to the Serial output queue using Serial.print() */
330void checkDigitalInputs(void)
331{
332  /* Using non-looping code allows constants to be given to readPort().
333   * The compiler will apply substantial optimizations if the inputs
334   * to readPort() are compile-time constants. */
335  if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false);
336  if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false);
337  if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false);
338  if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false);
339  if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false);
340  if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false);
341  if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false);
342  if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false);
343  if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false);
344  if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false);
345  if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false);
346  if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false);
347  if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false);
348  if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false);
349  if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false);
350  if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false);
351}
352
353// -----------------------------------------------------------------------------
354/* sets the pin mode to the correct state and sets the relevant bits in the
355 * two bit-arrays that track Digital I/O and PWM status
356 */
357void setPinModeCallback(byte pin, int mode)
358{
359  if (pinConfig[pin] == PIN_MODE_IGNORE)
360    return;
361
362  if (pinConfig[pin] == PIN_MODE_I2C && isI2CEnabled && mode != PIN_MODE_I2C) {
363    // disable i2c so pins can be used for other functions
364    // the following if statements should reconfigure the pins properly
365    disableI2CPins();
366  }
367  if (IS_PIN_DIGITAL(pin) && mode != PIN_MODE_SERVO) {
368    if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) {
369      detachServo(pin);
370    }
371  }
372  if (IS_PIN_ANALOG(pin)) {
373    reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); // turn on/off reporting
374  }
375  if (IS_PIN_DIGITAL(pin)) {
376    if (mode == INPUT || mode == PIN_MODE_PULLUP) {
377      portConfigInputs[pin / 8] |= (1 << (pin & 7));
378    } else {
379      portConfigInputs[pin / 8] &= ~(1 << (pin & 7));
380    }
381  }
382  pinState[pin] = 0;
383  switch (mode) {
384    case PIN_MODE_ANALOG:
385      if (IS_PIN_ANALOG(pin)) {
386        if (IS_PIN_DIGITAL(pin)) {
387          pinMode(PIN_TO_DIGITAL(pin), INPUT);    // disable output driver
388#if ARDUINO <= 100
389          // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6
390          digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups
391#endif
392        }
393        pinConfig[pin] = PIN_MODE_ANALOG;
394      }
395      break;
396    case INPUT:
397      if (IS_PIN_DIGITAL(pin)) {
398        pinMode(PIN_TO_DIGITAL(pin), INPUT);    // disable output driver
399#if ARDUINO <= 100
400        // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6
401        digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups
402#endif
403        pinConfig[pin] = INPUT;
404      }
405      break;
406    case PIN_MODE_PULLUP:
407      if (IS_PIN_DIGITAL(pin)) {
408        pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP);
409        pinConfig[pin] = PIN_MODE_PULLUP;
410        pinState[pin] = 1;
411      }
412      break;
413    case OUTPUT:
414      if (IS_PIN_DIGITAL(pin)) {
415        digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable PWM
416        pinMode(PIN_TO_DIGITAL(pin), OUTPUT);
417        pinConfig[pin] = OUTPUT;
418      }
419      break;
420    case PIN_MODE_PWM:
421      if (IS_PIN_PWM(pin)) {
422        pinMode(PIN_TO_PWM(pin), OUTPUT);
423        analogWrite(PIN_TO_PWM(pin), 0);
424        pinConfig[pin] = PIN_MODE_PWM;
425      }
426      break;
427    case PIN_MODE_SERVO:
428      if (IS_PIN_DIGITAL(pin)) {
429        pinConfig[pin] = PIN_MODE_SERVO;
430        if (servoPinMap[pin] == 255 || !servos[servoPinMap[pin]].attached()) {
431          // pass -1 for min and max pulse values to use default values set
432          // by Servo library
433          attachServo(pin, -1, -1);
434        }
435      }
436      break;
437    case PIN_MODE_I2C:
438      if (IS_PIN_I2C(pin)) {
439        // mark the pin as i2c
440        // the user must call I2C_CONFIG to enable I2C for a device
441        pinConfig[pin] = PIN_MODE_I2C;
442      }
443      break;
444    default:
445      Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM
446  }
447  // TODO: save status to EEPROM here, if changed
448}
449
450/*
451 * Sets the value of an individual pin. Useful if you want to set a pin value but
452 * are not tracking the digital port state.
453 * Can only be used on pins configured as OUTPUT.
454 * Cannot be used to enable pull-ups on Digital INPUT pins.
455 */
456void setPinValueCallback(byte pin, int value)
457{
458  if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) {
459    if (pinConfig[pin] == OUTPUT) {
460      pinState[pin] = value;
461      digitalWrite(PIN_TO_DIGITAL(pin), value);
462    }
463  }
464}
465
466void analogWriteCallback(byte pin, int value)
467{
468  if (pin < TOTAL_PINS) {
469    switch (pinConfig[pin]) {
470      case PIN_MODE_SERVO:
471        if (IS_PIN_DIGITAL(pin))
472          servos[servoPinMap[pin]].write(value);
473        pinState[pin] = value;
474        break;
475      case PIN_MODE_PWM:
476        if (IS_PIN_PWM(pin))
477          analogWrite(PIN_TO_PWM(pin), value);
478        pinState[pin] = value;
479        break;
480    }
481  }
482}
483
484void digitalWriteCallback(byte port, int value)
485{
486  byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0;
487
488  if (port < TOTAL_PORTS) {
489    // create a mask of the pins on this port that are writable.
490    lastPin = port * 8 + 8;
491    if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS;
492    for (pin = port * 8; pin < lastPin; pin++) {
493      // do not disturb non-digital pins (eg, Rx & Tx)
494      if (IS_PIN_DIGITAL(pin)) {
495        // do not touch pins in PWM, ANALOG, SERVO or other modes
496        if (pinConfig[pin] == OUTPUT || pinConfig[pin] == INPUT) {
497          pinValue = ((byte)value & mask) ? 1 : 0;
498          if (pinConfig[pin] == OUTPUT) {
499            pinWriteMask |= mask;
500          } else if (pinConfig[pin] == INPUT && pinValue == 1 && pinState[pin] != 1) {
501            // only handle INPUT here for backwards compatibility
502#if ARDUINO > 100
503            pinMode(pin, INPUT_PULLUP);
504#else
505            // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier
506            pinWriteMask |= mask;
507#endif
508          }
509          pinState[pin] = pinValue;
510        }
511      }
512      mask = mask << 1;
513    }
514    writePort(port, (byte)value, pinWriteMask);
515  }
516}
517
518
519// -----------------------------------------------------------------------------
520/* sets bits in a bit array (int) to toggle the reporting of the analogIns
521 */
522//void FirmataClass::setAnalogPinReporting(byte pin, byte state) {
523//}
524void reportAnalogCallback(byte analogPin, int value)
525{
526  if (analogPin < TOTAL_ANALOG_PINS) {
527    if (value == 0) {
528      analogInputsToReport = analogInputsToReport & ~ (1 << analogPin);
529    } else {
530      analogInputsToReport = analogInputsToReport | (1 << analogPin);
531      // prevent during system reset or all analog pin values will be reported
532      // which may report noise for unconnected analog pins
533      if (!isResetting) {
534        // Send pin value immediately. This is helpful when connected via
535        // ethernet, wi-fi or bluetooth so pin states can be known upon
536        // reconnecting.
537        Firmata.sendAnalog(analogPin, analogRead(analogPin));
538      }
539    }
540  }
541  // TODO: save status to EEPROM here, if changed
542}
543
544void reportDigitalCallback(byte port, int value)
545{
546  if (port < TOTAL_PORTS) {
547    reportPINs[port] = (byte)value;
548    // Send port value immediately. This is helpful when connected via
549    // ethernet, wi-fi or bluetooth so pin states can be known upon
550    // reconnecting.
551    if (value) outputPort(port, readPort(port, portConfigInputs[port]), true);
552  }
553  // do not disable analog reporting on these 8 pins, to allow some
554  // pins used for digital, others analog.  Instead, allow both types
555  // of reporting to be enabled, but check if the pin is configured
556  // as analog when sampling the analog inputs.  Likewise, while
557  // scanning digital pins, portConfigInputs will mask off values from any
558  // pins configured as analog
559}
560
561
562/*==============================================================================
563 * Circuit Playground commands
564 *============================================================================*/
565
566void circuitPlaygroundCommand(byte command, byte argc, byte* argv) {
567  switch (command) {
568    case CP_PIXEL_SET:
569      // Set a NeoPixel to the specified RGB color.
570      // Expect: 1 byte pixel number, 4 bytes pixel RGB value (as 7-bit bytes)
571      if (argc >= 5) {
572        // Parse out the pixel number and R, G, B bytes.
573        uint8_t pixel = argv[0] & 0x7F;
574        uint8_t r = (argv[1] << 1) | ((argv[2] & 0x7F) >> 6);  // Red = 7 bits from byte 4 and 1 bit from byte 5
575        uint8_t g = ((argv[2] & 0x3F) << 2) | (((argv[3]) & 0x7F) >> 5);  // Green = 6 bits from byte 5 and 2 bits from byte 6
576        uint8_t b = ((argv[3] & 0x1F) << 3) | (((argv[4]) & 0x7F) >> 4);  // Blue = 5 bits from byte 6 and 3 bits from byte 7
577        CircuitPlayground.strip.setPixelColor(pixel, r, g, b);
578      }
579      break;
580    case CP_PIXEL_SHOW:
581      // Light up the neopixels with their current buffer values.
582      CircuitPlayground.strip.show();
583      break;
584    case CP_PIXEL_CLEAR:
585      // Clear all the pixel color values.
586      CircuitPlayground.strip.clear();
587      break;
588    case CP_PIXEL_BRIGHTNESS:
589      // Set pixel brightness.
590      // Expects 1 byte with the brightness as a value 0-100.
591      if (argc >= 1) {
592        uint8_t brightness = argv[0];
593        if (brightness > 100) {
594          return;
595        }
596        CircuitPlayground.strip.setBrightness(brightness);
597      }
598    case CP_TONE:
599      // Play a tone on the speaker.
600      // Expect: 2 bytes tone frequency, 2 bytes tone duration
601      if (argc >= 4) {
602        uint16_t frequency = ((argv[1] & 0x7F) << 7) | (argv[0] & 0x7F);
603        uint16_t duration = ((argv[3] & 0x7F) << 7) | (argv[2] & 0x7F);
604        // If duration is zero then interpret that as continuous tone playback.
605        if (duration == 0) {
606          tone(SPEAKER_PIN, frequency);
607        }
608        else {
609          tone(SPEAKER_PIN, frequency, duration);
610        }
611      }
612      break;
613    case CP_NO_TONE:
614      // Stop tone playback.
615      noTone(SPEAKER_PIN);
616      break;
617    case CP_ACCEL_READ:
618      sendAccelResponse();
619      break;
620    case CP_ACCEL_TAP:
621      sendTapResponse();
622      break;
623    case CP_ACCEL_TAP_STREAM_ON:
624      streamTap = true;
625      break;
626    case CP_ACCEL_TAP_STREAM_OFF:
627      streamTap = false;
628      break;
629    case CP_ACCEL_STREAM_ON:
630      streamAccel = true;
631      break;
632    case CP_ACCEL_STREAM_OFF:
633      streamAccel = false;
634      break;
635    case CP_CAP_READ:
636      // Flip the streaming bool on for the specified input.
637      // First check we have enough parameters and grab the input from the first byte.
638      if (argc >= 1) {
639        uint8_t input = argv[0] & 0x7F;
640        // Now find the specified cap input and send a response with its current cap touch value.
641        for (int i=0; i<CAP_COUNT; ++i) {
642          if (cap_state[i].pin == input) {
643            sendCapResponse(input);
644          }
645        }
646      }
647      break;
648    case CP_CAP_ON:
649      // Flip the streaming bool on for the specified input.
650      // First check we have enough parameters and grab the input from the first byte.
651      if (argc >= 1) {
652        uint8_t input = argv[0] & 0x7F;
653        // Now find the specified cap input and flip on its streaming bit.
654        for (int i=0; i<CAP_COUNT; ++i) {
655          if (cap_state[i].pin == input) {
656            cap_state[i].streaming = true;
657          }
658        }
659      }
660      break;
661    case CP_CAP_OFF:
662      // Flip the streaming bool off for the specified input.
663      // First check we have enough parameters and grab the input from the first byte.
664      if (argc >= 1) {
665        uint8_t input = argv[0] & 0x7F;
666        // Now find the specified cap input and flip on its streaming bit.
667        for (int i=0; i<CAP_COUNT; ++i) {
668          if (cap_state[i].pin == input) {
669            cap_state[i].streaming = false;
670          }
671        }
672      }
673      break;
674    case CP_ACCEL_RANGE:
675      // Set the range of the accelerometer based on the passed in value.
676      // First check we have enough parameters and grab the input from the first byte.
677      if (argc >= 1) {
678        uint8_t range = argv[0] & 0x7F;
679        // Check the range is an allowed value (0, 1, 2, 3).
680        if (range > 3) {
681          // Unknown range value, stop processing!
682          return;
683        }
684        // Set the range of the accelerometer.
685        CircuitPlayground.lis.setRange((lis3dh_range_t)range);
686      }
687      break;
688    case CP_ACCEL_TAP_CONFIG:
689      // Set the sensitivity of tap detection.
690      // Expects 4 7-bit firmata bytes as input, which expand to 2 bytes of 8-bit unsigned data.
691      // First check we have enough parameters.
692      if (argc >= 4) {
693        // Parse out paramemters.
694        uint8_t type = ((argv[1] & 0x01) << 7) | (argv[0] & 0x7F);
695        uint8_t threshold = ((argv[3] & 0x01) << 7) | (argv[2] & 0x7F);
696        // Set the click threshold values.
697        CircuitPlayground.lis.setClick(type, threshold);
698      }
699    case CP_SENSECOLOR:
700      // Sense the color of an object over the light sensor and send back
701      // a CP_SENSECOLOR_REPLY response.
702      sendColorSenseResponse();
703  }
704}
705
706// Send a color sense response back to the host computer.
707void sendColorSenseResponse() {
708  // Perform a color sense with NeoPixel #1 and the light sensor.
709  uint8_t red, green, blue;
710  CircuitPlayground.senseColor(red, green, blue);
711  // Construct a response data packet and send it.
712  uint8_t data[4] = {0};
713  data[0] = CP_SENSECOLOR_REPLY;
714  data[1] = red;
715  data[2] = green;
716  data[3] = blue;
717  // Send the response.
718  Firmata.sendSysex(CP_COMMAND, 4, data);
719}
720
721// Read the accelerometer and send a response packet.
722void sendAccelResponse() {
723  // Get an accelerometer X, Y, Z reading.
724  sensors_event_t event;
725  CircuitPlayground.lis.getEvent(&event);
726  // Construct a response data packet.
727  uint8_t data[13] = {0};
728  data[0] = CP_ACCEL_READ_REPLY;
729  // Put the three 32-bit float X,Y,Z reading into the packet.
730  // Note that Firmata.sendSysex will automatically convert bytes into
731  // two 7-bit bytes that are Firmata/MIDI compatible.
732  // Use a union to easily grab the bytes of the float.
733  union {
734    float value;
735    uint8_t bytes[4];
736  } reading;
737  // Grab each X, Y, Z float byte value and copy it into the response.
738  reading.value = event.acceleration.x;
739  memcpy(data+1, reading.bytes, 4);
740  reading.value = event.acceleration.y;
741  memcpy(data+5, reading.bytes, 4);
742  reading.value = event.acceleration.z;
743  memcpy(data+9, reading.bytes, 4);
744  // Send the response.
745  Firmata.sendSysex(CP_COMMAND, 13, data);
746}
747
748// Read the accelerometer tap detection and send a response packet.
749void sendTapResponse() {
750  // Get the accelerometer tap detection state.
751  uint8_t click = CircuitPlayground.lis.getClick();
752  // Construct a response data packet and send it.
753  uint8_t data[2] = {0};
754  data[0] = CP_ACCEL_TAP_REPLY;
755  data[1] = click;
756  // Send the response.
757  Firmata.sendSysex(CP_COMMAND, 2, data);
758}
759
760// Read the capacitive sensor state and send a response packet.
761void sendCapResponse(uint8_t pin) {
762  // Get the cap sense value for the provided input pin.
763  int32_t value = CircuitPlayground.readCap(pin, CAP_SAMPLES);
764  // Build a response data packet and send it.  The response includes:
765  // - uint8_t: CP_CAP_REPLY value
766  // - uint8_t: pin number of the read input
767  // - int32_t: cap sensor value, large values mean the input was touched
768  union {
769    struct {
770      uint8_t type;
771      uint8_t pin;
772      int32_t value;
773    } data;
774    uint8_t bytes[6];
775  } response;
776  response.data.type = CP_CAP_REPLY;
777  response.data.pin = pin;
778  response.data.value = value;
779  // Send the response, this will expand each byte into 2 bytes of 7-bit data.
780  Firmata.sendSysex(CP_COMMAND, 6, response.bytes);
781}
782
783/*==============================================================================
784 * SYSEX-BASED commands
785 *============================================================================*/
786
787void sysexCallback(byte command, byte argc, byte *argv)
788{
789  byte mode;
790  byte slaveAddress;
791  byte data;
792  int slaveRegister;
793  unsigned int delayTime;
794
795  switch (command) {
796    // Circuit playground command processing:
797    case CP_COMMAND:
798      if (argc < 1) return;
799      circuitPlaygroundCommand(argv[0], argc-1, argv+1);
800      break;
801    case I2C_REQUEST:
802      mode = argv[1] & I2C_READ_WRITE_MODE_MASK;
803      if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) {
804        Firmata.sendString("10-bit addressing not supported");
805        return;
806      }
807      else {
808        slaveAddress = argv[0];
809      }
810
811      switch (mode) {
812        case I2C_WRITE:
813          Wire.beginTransmission(slaveAddress);
814          for (byte i = 2; i < argc; i += 2) {
815            data = argv[i] + (argv[i + 1] << 7);
816            wireWrite(data);
817          }
818          Wire.endTransmission();
819          delayMicroseconds(70);
820          break;
821        case I2C_READ:
822          if (argc == 6) {
823            // a slave register is specified
824            slaveRegister = argv[2] + (argv[3] << 7);
825            data = argv[4] + (argv[5] << 7);  // bytes to read
826          }
827          else {
828            // a slave register is NOT specified
829            slaveRegister = I2C_REGISTER_NOT_SPECIFIED;
830            data = argv[2] + (argv[3] << 7);  // bytes to read
831          }
832          readAndReportData(slaveAddress, (int)slaveRegister, data);
833          break;
834        case I2C_READ_CONTINUOUSLY:
835          if ((queryIndex + 1) >= I2C_MAX_QUERIES) {
836            // too many queries, just ignore
837            Firmata.sendString("too many queries");
838            break;
839          }
840          if (argc == 6) {
841            // a slave register is specified
842            slaveRegister = argv[2] + (argv[3] << 7);
843            data = argv[4] + (argv[5] << 7);  // bytes to read
844          }
845          else {
846            // a slave register is NOT specified
847            slaveRegister = (int)I2C_REGISTER_NOT_SPECIFIED;
848            data = argv[2] + (argv[3] << 7);  // bytes to read
849          }
850          queryIndex++;
851          query[queryIndex].addr = slaveAddress;
852          query[queryIndex].reg = slaveRegister;
853          query[queryIndex].bytes = data;
854          break;
855        case I2C_STOP_READING:
856          byte queryIndexToSkip;
857          // if read continuous mode is enabled for only 1 i2c device, disable
858          // read continuous reporting for that device
859          if (queryIndex <= 0) {
860            queryIndex = -1;
861          } else {
862            // if read continuous mode is enabled for multiple devices,
863            // determine which device to stop reading and remove it's data from
864            // the array, shifiting other array data to fill the space
865            for (byte i = 0; i < queryIndex + 1; i++) {
866              if (query[i].addr == slaveAddress) {
867                queryIndexToSkip = i;
868                break;
869              }
870            }
871
872            for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) {
873              if (i < I2C_MAX_QUERIES) {
874                query[i].addr = query[i + 1].addr;
875                query[i].reg = query[i + 1].reg;
876                query[i].bytes = query[i + 1].bytes;
877              }
878            }
879            queryIndex--;
880          }
881          break;
882        default:
883          break;
884      }
885      break;
886    case I2C_CONFIG:
887      delayTime = (argv[0] + (argv[1] << 7));
888
889      if (delayTime > 0) {
890        i2cReadDelayTime = delayTime;
891      }
892
893      if (!isI2CEnabled) {
894        enableI2CPins();
895      }
896
897      break;
898    case SERVO_CONFIG:
899      if (argc > 4) {
900        // these vars are here for clarity, they'll optimized away by the compiler
901        byte pin = argv[0];
902        int minPulse = argv[1] + (argv[2] << 7);
903        int maxPulse = argv[3] + (argv[4] << 7);
904
905        if (IS_PIN_DIGITAL(pin)) {
906          if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) {
907            detachServo(pin);
908          }
909          attachServo(pin, minPulse, maxPulse);
910          setPinModeCallback(pin, PIN_MODE_SERVO);
911        }
912      }
913      break;
914    case SAMPLING_INTERVAL:
915      if (argc > 1) {
916        samplingInterval = argv[0] + (argv[1] << 7);
917        if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) {
918          samplingInterval = MINIMUM_SAMPLING_INTERVAL;
919        }
920      } else {
921        //Firmata.sendString("Not enough data");
922      }
923      break;
924    case EXTENDED_ANALOG:
925      if (argc > 1) {
926        int val = argv[1];
927        if (argc > 2) val |= (argv[2] << 7);
928        if (argc > 3) val |= (argv[3] << 14);
929        analogWriteCallback(argv[0], val);
930      }
931      break;
932    case CAPABILITY_QUERY:
933      Firmata.write(START_SYSEX);
934      Firmata.write(CAPABILITY_RESPONSE);
935      for (byte pin = 0; pin < TOTAL_PINS; pin++) {
936        if (IS_PIN_DIGITAL(pin)) {
937          Firmata.write((byte)INPUT);
938          Firmata.write(1);
939          Firmata.write((byte)PIN_MODE_PULLUP);
940          Firmata.write(1);
941          Firmata.write((byte)OUTPUT);
942          Firmata.write(1);
943        }
944        if (IS_PIN_ANALOG(pin)) {
945          Firmata.write(PIN_MODE_ANALOG);
946          Firmata.write(10); // 10 = 10-bit resolution
947        }
948        if (IS_PIN_PWM(pin)) {
949          Firmata.write(PIN_MODE_PWM);
950          Firmata.write(8); // 8 = 8-bit resolution
951        }
952        if (IS_PIN_DIGITAL(pin)) {
953          Firmata.write(PIN_MODE_SERVO);
954          Firmata.write(14);
955        }
956        if (IS_PIN_I2C(pin)) {
957          Firmata.write(PIN_MODE_I2C);
958          Firmata.write(1);  // TODO: could assign a number to map to SCL or SDA
959        }
960        Firmata.write(127);
961      }
962      Firmata.write(END_SYSEX);
963      break;
964    case PIN_STATE_QUERY:
965      if (argc > 0) {
966        byte pin = argv[0];
967        Firmata.write(START_SYSEX);
968        Firmata.write(PIN_STATE_RESPONSE);
969        Firmata.write(pin);
970        if (pin < TOTAL_PINS) {
971          Firmata.write((byte)pinConfig[pin]);
972          Firmata.write((byte)pinState[pin] & 0x7F);
973          if (pinState[pin] & 0xFF80) Firmata.write((byte)(pinState[pin] >> 7) & 0x7F);
974          if (pinState[pin] & 0xC000) Firmata.write((byte)(pinState[pin] >> 14) & 0x7F);
975        }
976        Firmata.write(END_SYSEX);
977      }
978      break;
979    case ANALOG_MAPPING_QUERY:
980      Firmata.write(START_SYSEX);
981      Firmata.write(ANALOG_MAPPING_RESPONSE);
982      for (byte pin = 0; pin < TOTAL_PINS; pin++) {
983        Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127);
984      }
985      Firmata.write(END_SYSEX);
986      break;
987  }
988}
989
990void enableI2CPins()
991{
992  byte i;
993  // is there a faster way to do this? would probaby require importing
994  // Arduino.h to get SCL and SDA pins
995  for (i = 0; i < TOTAL_PINS; i++) {
996    if (IS_PIN_I2C(i)) {
997      // mark pins as i2c so they are ignore in non i2c data requests
998      setPinModeCallback(i, PIN_MODE_I2C);
999    }
1000  }
1001
1002  isI2CEnabled = true;
1003
1004  Wire.begin();
1005}
1006
1007/* disable the i2c pins so they can be used for other functions */
1008void disableI2CPins() {
1009  isI2CEnabled = false;
1010  // disable read continuous mode for all devices
1011  queryIndex = -1;
1012}
1013
1014/*==============================================================================
1015 * SETUP()
1016 *============================================================================*/
1017
1018void systemResetCallback()
1019{
1020  isResetting = true;
1021
1022  // initialize a defalt state
1023  // TODO: option to load config from EEPROM instead of default
1024
1025  // Reset circuit playground components to a default state with nothing running.
1026  // (i.e. no pixels lit, no sound, no data streaming back)
1027  circuitPlaygroundReset();
1028
1029  if (isI2CEnabled) {
1030    disableI2CPins();
1031  }
1032
1033  for (byte i = 0; i < TOTAL_PORTS; i++) {
1034    reportPINs[i] = false;    // by default, reporting off
1035    portConfigInputs[i] = 0;  // until activated
1036    previousPINs[i] = 0;
1037  }
1038
1039  for (byte i = 0; i < TOTAL_PINS; i++) {
1040    // pins with analog capability default to analog input
1041    // otherwise, pins default to digital output
1042    if (IS_PIN_ANALOG(i)) {
1043      // turns off pullup, configures everything
1044      setPinModeCallback(i, PIN_MODE_ANALOG);
1045    } else if (IS_PIN_DIGITAL(i)) {
1046      // sets the output to 0, configures portConfigInputs
1047      setPinModeCallback(i, OUTPUT);
1048    }
1049
1050    servoPinMap[i] = 255;
1051  }
1052  // by default, do not report any analog inputs
1053  analogInputsToReport = 0;
1054
1055  detachedServoCount = 0;
1056  servoCount = 0;
1057
1058  /* send digital inputs to set the initial state on the host computer,
1059   * since once in the loop(), this firmware will only send on change */
1060  /*
1061  TODO: this can never execute, since no pins default to digital input
1062        but it will be needed when/if we support EEPROM stored config
1063  for (byte i=0; i < TOTAL_PORTS; i++) {
1064    outputPort(i, readPort(i, portConfigInputs[i]), true);
1065  }
1066  */
1067  isResetting = false;
1068}
1069
1070void circuitPlaygroundReset() {
1071  // Reset the circuit playground components into a default state
1072  // with none of the pixels lit, no tones playing, and no cap touch
1073  // or accelerometer data streaming back.
1074
1075  // Turn off all the NeoPixels.
1076  CircuitPlayground.strip.clear();
1077  CircuitPlayground.strip.show();
1078
1079  // Reset the accelerometer to a default range.
1080  CircuitPlayground.lis.setRange(LIS3DH_RANGE_2_G);
1081  delay(100);
1082  CircuitPlayground.lis.setClick(2, 80);
1083  delay(100);
1084
1085  // Turn off streaming of tap, accel, and cap touch data.
1086  streamTap = false;
1087  streamAccel = false;
1088  for (int i=0; i<CAP_COUNT; ++i) {
1089    cap_state[i].streaming = false;
1090  }
1091
1092  // Stop any tones on the speaker.
1093  noTone(SPEAKER_PIN);
1094}
1095
1096void setup()
1097{
1098  // Circuit playground debug setup
1099  #ifdef DEBUG_MODE
1100    DEBUG_OUTPUT.begin(DEBUG_BAUD);
1101    DEBUG_PRINTLN("Circuit Playground Firmata starting up!");
1102  #endif
1103
1104  // Circuit playground setup:
1105  if (!CircuitPlayground.begin()) {
1106    // Failed to initialize circuit playground, fast blink the red LED on the board.
1107    DEBUG_PRINTLN("Failed to initialize circuit playground!");
1108    pinMode(13, OUTPUT);
1109    while (1) {
1110      digitalWrite(13, LOW);
1111      delay(100);
1112      digitalWrite(13, HIGH);
1113      delay(100);
1114    }
1115  }
1116
1117  Firmata.setFirmwareVersion(FIRMATA_MAJOR_VERSION, FIRMATA_MINOR_VERSION);
1118
1119  Firmata.attach(ANALOG_MESSAGE, analogWriteCallback);
1120  Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback);
1121  Firmata.attach(REPORT_ANALOG, reportAnalogCallback);
1122  Firmata.attach(REPORT_DIGITAL, reportDigitalCallback);
1123  Firmata.attach(SET_PIN_MODE, setPinModeCallback);
1124  Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback);
1125  Firmata.attach(START_SYSEX, sysexCallback);
1126  Firmata.attach(SYSTEM_RESET, systemResetCallback);
1127
1128  // to use a port other than Serial, such as Serial1 on an Arduino Leonardo or Mega,
1129  // Call begin(baud) on the alternate serial port and pass it to Firmata to begin like this:
1130  // Serial1.begin(57600);
1131  // Firmata.begin(Serial1);
1132  // then comment out or remove lines 701 - 704 below
1133  Firmata.begin(57600);
1134
1135  // Tell Firmata to ignore pins that are used by the Circuit Playground hardware.
1136  // This MUST be called or else Firmata will 'clobber' pins like the SPI CS!
1137  pinConfig[28] = PIN_MODE_IGNORE;   // Pin 28 = D8 = LIS3DH CS
1138  pinConfig[26] = PIN_MODE_IGNORE;   // Messes with CS too?
1139
1140#if defined(DEMO_MODE)
1141  while (!Serial) {
1142     runDemo();   // this will 'demo' the board off, so you know its working, until the serial port is opened
1143  }
1144#endif
1145
1146  systemResetCallback();  // reset to default config
1147}
1148
1149/*==============================================================================
1150 * LOOP()
1151 *============================================================================*/
1152void loop()
1153{
1154  byte pin, analogPin;
1155
1156  /* DIGITALREAD - as fast as possible, check for changes and output them to the
1157   * FTDI buffer using Serial.print()  */
1158  checkDigitalInputs();
1159
1160  /* STREAMREAD - processing incoming messagse as soon as possible, while still
1161   * checking digital inputs.  */
1162  while (Firmata.available())
1163    Firmata.processInput();
1164
1165  // TODO - ensure that Stream buffer doesn't go over 60 bytes
1166
1167  currentMillis = millis();
1168  if (currentMillis - previousMillis > samplingInterval) {
1169    previousMillis += samplingInterval;
1170    /* ANALOGREAD - do all analogReads() at the configured sampling interval */
1171    for (pin = 0; pin < TOTAL_PINS; pin++) {
1172      if (IS_PIN_ANALOG(pin) && pinConfig[pin] == PIN_MODE_ANALOG) {
1173        analogPin = PIN_TO_ANALOG(pin);
1174        if (analogInputsToReport & (1 << analogPin)) {
1175          Firmata.sendAnalog(analogPin, analogRead(analogPin));
1176        }
1177      }
1178    }
1179    // report i2c data for all device with read continuous mode enabled
1180    if (queryIndex > -1) {
1181      for (byte i = 0; i < queryIndex + 1; i++) {
1182        readAndReportData(query[i].addr, query[i].reg, query[i].bytes);
1183      }
1184    }
1185    // Check if a tap event should be streamed to the firmata client.
1186    if (streamTap) {
1187      sendTapResponse();
1188    }
1189    // Check if an accelerometer event should be streamed to the firmata client.
1190    if (streamAccel) {
1191      sendAccelResponse();
1192    }
1193    // Check if any cap touch inputs should be streamed to the firmata client.
1194    for (int i=0; i<CAP_COUNT; ++i) {
1195      if (cap_state[i].streaming) {
1196        sendCapResponse(cap_state[i].pin);
1197      }
1198    }
1199  }
1200}
1201
1202
1203/*==============================================================================
1204 * RUN_DEMO()
1205 *============================================================================*/
1206
1207// we light one pixel at a time, this is our counter
1208uint8_t pixeln = 0;
1209void runDemo(void) {
1210  // test Red #13 LED
1211  CircuitPlayground.redLED(pixeln % 1);
1212
1213  /************* TEST SLIDE SWITCH */
1214  if (CircuitPlayground.slideSwitch()) {
1215    pixeln++;
1216    if (pixeln == 11) {
1217      pixeln = 0;
1218      CircuitPlayground.clearPixels();
1219    }
1220  } else {
1221    if (pixeln == 0) {
1222      pixeln = 10;
1223      CircuitPlayground.clearPixels();
1224    }
1225    pixeln--;
1226  }
1227
1228
1229  /************* TEST 10 NEOPIXELS */
1230  CircuitPlayground.setPixelColor(pixeln, CircuitPlayground.colorWheel(25 * pixeln));
1231
1232
1233  /************* TEST BOTH BUTTONS */
1234  if (CircuitPlayground.leftButton()) {
1235    CircuitPlayground.playTone(500 + pixeln * 500, 100, false);
1236  }
1237  if (CircuitPlayground.rightButton()) {
1238    CircuitPlayground.setBrightness(60);
1239  } else {
1240    CircuitPlayground.setBrightness(20);
1241  }
1242
1243  delay(100);
1244
1245}
Note: See TracBrowser for help on using the repository browser.