Delete FirmataPlusStepper.ino

Delete FirmataPlusStepper.ino

--- ArduinoSketch/FirmataPlusStepper/examples/FirmataPlusStepper/FirmataPlusStepper.ino
+++ ArduinoSketch/FirmataPlusStepper/examples/FirmataPlusStepper/FirmataPlusStepper.ino
@@ -1,905 +0,0 @@
-
-/*
- * Firmata is a generic protocol for communicating with microcontrollers
- * from software on a host computer. It is intended to work with
- * any host computer software package.
- *
- * To download a host software package, please clink on the following link
- * to open the download page in your default browser.ser
- *
- * http://firmata.org/wiki/Download
- */
-
-/*
- Copyright (C) 2006-2008 Hans-Christoph Steiner.  All rights reserved.
- Copyright (C) 2010-2011 Paul Stoffregen.  All rights reserved.
- Copyright (C) 2009 Shigeru Kobayashi.  All rights reserved.
- Copyright (C) 2009-2011 Jeff Hoefs.  All rights reserved.
- Copyright (C) 2013-2014 Alan Yorinks. All rights reserved.
-
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) any later version.
-
- See file LICENSE.txt for further informations on licensing terms.
-
- formatted using the GNU C formatting and indenting
- */
-
-/*
- * TODO: use Program Control to load stored profiles from EEPROM
- */
-
-#include <Servo.h>
-#include <Wire.h>
-#include <Firmata.h>
-#include <NewPing.h>
-#include <Stepper.h>
-
-// move the following defines to Firmata.h?
-#define I2C_WRITE B00000000
-#define I2C_READ B00001000
-#define I2C_READ_CONTINUOUSLY B00010000
-#define I2C_STOP_READING B00011000
-#define I2C_READ_WRITE_MODE_MASK B00011000
-#define I2C_10BIT_ADDRESS_MODE_MASK B00100000
-
-#define MAX_QUERIES 8
-#define MINIMUM_SAMPLING_INTERVAL 10
-
-#define REGISTER_NOT_SPECIFIED -1
-
-#define MAX_SONARS     6          // Maximum Number of sensors. - front, back, left, right, up, down
-#define SONAR_MAX_DISTANCE 200    // Maximum distance (in cm) to ping.
-
-#define INTER_PING_INTERVAL 40 // 40 ms.
-
-#define MAX_NUM_STEPPERS    4  // maximum number of stepper motors
-
-// SYSEX command sub specifiers
-#define TONE_TONE 0
-#define TONE_NO_TONE 1
-
-#define STEPPER_CONFIGURE 0
-#define STEPPER_STEP 1
-
-
-/*==============================================================================
- * GLOBAL VARIABLES
- *============================================================================*/
-
-/* analog inputs */
-int analogInputsToReport = 0; // bitwise array to store pin reporting
-
-/* digital input ports */
-byte reportPINs[TOTAL_PORTS];       // 1 = report this port, 0 = silence
-byte previousPINs[TOTAL_PORTS];     // previous 8 bits sent
-
-/* pins configuration */
-byte pinConfig[TOTAL_PINS];         // configuration of every pin
-byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else
-int pinState[TOTAL_PINS];           // any value that has been written
-
-/* timer variables */
-unsigned long currentMillis;        // store the current value from millis()
-unsigned long previousMillis;       // for comparison with currentMillis
-int samplingInterval = 19;          // how often to run the main loop (in ms)
-
-/* i2c data */
-struct i2c_device_info {
-  byte addr;
-  byte reg;
-  byte bytes;
-};
-
-/* for i2c read continuous more */
-i2c_device_info query[MAX_QUERIES];
-
-byte i2cRxData[32];
-boolean isI2CEnabled = false;
-signed char queryIndex = -1;
-unsigned int i2cReadDelayTime = 0;  // default delay time between i2c read request and Wire.requestFrom()
-
-
-// Servos
-Servo servos[MAX_SERVOS];
-
-// Ping variables
-
-int numLoops = 0 ;
-int pingLoopCounter = 0 ;
-
-int numActiveSonars = 0 ; // number of sonars attached
-uint8_t sonarPinNumbers[MAX_SONARS] ;
-int nextSonar = 0 ; // index into sonars[] for next device
-
-// array to hold up to 6 instances of sonar devices
-NewPing *sonars[MAX_SONARS] ;
-
-uint8_t sonarTriggerPin;
-uint8_t sonarEchoPin ;
-uint8_t currentSonar = 0;            // Keeps track of which sensor is active.
-
-uint8_t pingInterval = 33 ;  // Milliseconds between sensor pings (29ms is about the min to avoid
-                             // cross- sensor echo).
-byte sonarMSB, sonarLSB ;
-
-
-// Stepper Motor
-
-// Array of pointers to stepper motors
-Stepper *steppers[MAX_NUM_STEPPERS] ;
-
-
-
-/*==============================================================================
- * FUNCTIONS
- *============================================================================*/
-
-void readAndReportData(byte address, int theRegister, byte numBytes) {
-  // allow I2C requests that don't require a register read
-  // for example, some devices using an interrupt pin to signify new data available
-  // do not always require the register read so upon interrupt you call Wire.requestFrom()
-  if (theRegister != REGISTER_NOT_SPECIFIED) {
-    Wire.beginTransmission(address);
-#if ARDUINO >= 100
-    Wire.write((byte)theRegister);
-#else
-    Wire.send((byte)theRegister);
-#endif
-    Wire.endTransmission();
-    // do not set a value of 0
-    if (i2cReadDelayTime > 0) {
-      // delay is necessary for some devices such as WiiNunchuck
-      delayMicroseconds(i2cReadDelayTime);
-    }
-  }
-  else {
-    theRegister = 0;  // fill the register with a dummy value
-  }
-
-  Wire.requestFrom(address, numBytes);  // all bytes are returned in requestFrom
-
-  // check to be sure correct number of bytes were returned by slave
-  if (numBytes == Wire.available()) {
-    i2cRxData[0] = address;
-    i2cRxData[1] = theRegister;
-    for (int i = 0; i < numBytes; i++) {
-#if ARDUINO >= 100
-      i2cRxData[2 + i] = Wire.read();
-#else
-      i2cRxData[2 + i] = Wire.receive();
-#endif
-    }
-  }
-  else {
-    if (numBytes > Wire.available()) {
-      Firmata.sendString("I2C Read Error: Too many bytes received");
-    }
-    else {
-      Firmata.sendString("I2C Read Error: Too few bytes received");
-    }
-  }
-
-  // send slave address, register and received bytes
-  Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData);
-}
-
-void outputPort(byte portNumber, byte portValue, byte forceSend)
-{
-  // pins not configured as INPUT are cleared to zeros
-  portValue = portValue & portConfigInputs[portNumber];
-  // only send if the value is different than previously sent
-  if (forceSend || previousPINs[portNumber] != portValue) {
-    Firmata.sendDigitalPort(portNumber, portValue);
-    previousPINs[portNumber] = portValue;
-  }
-}
-
-/* -----------------------------------------------------------------------------
- * check all the active digital inputs for change of state, then add any events
- * to the Serial output queue using Serial.print() */
-void checkDigitalInputs(void)
-{
-  /* Using non-looping code allows constants to be given to readPort().
-   * The compiler will apply substantial optimizations if the inputs
-   * to readPort() are compile-time constants. */
-  if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false);
-  if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false);
-  if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false);
-  if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false);
-  if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false);
-  if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false);
-  if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false);
-  if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false);
-  if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false);
-  if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false);
-  if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false);
-  if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false);
-  if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false);
-  if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false);
-  if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false);
-  if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false);
-}
-
-// -----------------------------------------------------------------------------
-/* sets the pin mode to the correct state and sets the relevant bits in the
- * two bit-arrays that track Digital I/O and PWM status
- */
-void setPinModeCallback(byte pin, int mode)
-{
-  if (pinConfig[pin] == I2C && isI2CEnabled && mode != I2C) {
-    // disable i2c so pins can be used for other functions
-    // the following if statements should reconfigure the pins properly
-    disableI2CPins();
-  }
-  if (IS_PIN_SERVO(pin) && mode != SERVO && servos[PIN_TO_SERVO(pin)].attached()) {
-    servos[PIN_TO_SERVO(pin)].detach();
-  }
-  if (IS_PIN_ANALOG(pin)) {
-    reportAnalogCallback(PIN_TO_ANALOG(pin), mode == ANALOG ? 1 : 0); // turn on/off reporting
-  }
-  if (IS_PIN_DIGITAL(pin)) {
-    if (mode == INPUT) {
-      portConfigInputs[pin / 8] |= (1 << (pin & 7));
-    }
-    else {
-      portConfigInputs[pin / 8] &= ~(1 << (pin & 7));
-    }
-  }
-  pinState[pin] = 0;
-  switch (mode) {
-    case ANALOG:
-      if (IS_PIN_ANALOG(pin)) {
-        if (IS_PIN_DIGITAL(pin)) {
-          pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver
-          digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups
-        }
-        pinConfig[pin] = ANALOG;
-      }
-      break;
-    case INPUT:
-      if (IS_PIN_DIGITAL(pin)) {
-        pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver
-        digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups
-        pinConfig[pin] = INPUT;
-      }
-      break;
-    case OUTPUT:
-      if (IS_PIN_DIGITAL(pin)) {
-        digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable PWM
-        pinMode(PIN_TO_DIGITAL(pin), OUTPUT);
-        pinConfig[pin] = OUTPUT;
-      }
-      break;
-    case PWM:
-      if (IS_PIN_PWM(pin)) {
-        pinMode(PIN_TO_PWM(pin), OUTPUT);
-        analogWrite(PIN_TO_PWM(pin), 0);
-        pinConfig[pin] = PWM;
-      }
-      break;
-    case SERVO:
-      if (IS_PIN_SERVO(pin)) {
-        pinConfig[pin] = SERVO;
-        if (!servos[PIN_TO_SERVO(pin)].attached()) {
-          servos[PIN_TO_SERVO(pin)].attach(PIN_TO_DIGITAL(pin));
-        }
-      }
-      break;
-    case I2C:
-      if (IS_PIN_I2C(pin)) {
-        // mark the pin as i2c
-        // the user must call I2C_CONFIG to enable I2C for a device
-        pinConfig[pin] = I2C;
-      }
-      break;
-    case TONE:
-      pinConfig[pin] = TONE ;
-      break ;
-    case SONAR:
-      pinConfig[pin] = SONAR ;
-      break ;
-    case STEPPER:
-      pinConfig[pin] = STEPPER ;
-      break ;
-    default:
-      Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM
-      break ;
-  }
-  // TODO: save status to EEPROM here, if changed
-}
-
-void analogWriteCallback(byte pin, int value)
-{
-  if (pin < TOTAL_PINS) {
-    switch (pinConfig[pin]) {
-      case SERVO:
-        if (IS_PIN_SERVO(pin))
-          servos[PIN_TO_SERVO(pin)].write(value);
-        pinState[pin] = value;
-        break;
-      case PWM:
-        if (IS_PIN_PWM(pin))
-          analogWrite(PIN_TO_PWM(pin), value);
-        pinState[pin] = value;
-        break;
-    }
-  }
-}
-
-void digitalWriteCallback(byte port, int value)
-{
-  byte pin, lastPin, mask = 1, pinWriteMask = 0;
-
-  if (port < TOTAL_PORTS) {
-    // create a mask of the pins on this port that are writable.
-    lastPin = port * 8 + 8;
-    if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS;
-    for (pin = port * 8; pin < lastPin; pin++) {
-      // do not disturb non-digital pins (eg, Rx & Tx)
-      if (IS_PIN_DIGITAL(pin)) {
-        // only write to OUTPUT and INPUT (enables pullup)
-        // do not touch pins in PWM, ANALOG, SERVO or other modes
-        if (pinConfig[pin] == OUTPUT || pinConfig[pin] == INPUT) {
-          pinWriteMask |= mask;
-          pinState[pin] = ((byte)value & mask) ? 1 : 0;
-        }
-      }
-      mask = mask << 1;
-    }
-    writePort(port, (byte)value, pinWriteMask);
-  }
-}
-
-
-// -----------------------------------------------------------------------------
-/* sets bits in a bit array (int) to toggle the reporting of the analogIns
- */
-//void FirmataClass::setAnalogPinReporting(byte pin, byte state) {
-//}
-void reportAnalogCallback(byte analogPin, int value)
-{
-  if (analogPin < TOTAL_ANALOG_PINS) {
-    if (value == 0) {
-      analogInputsToReport = analogInputsToReport &~ (1 << analogPin);
-    }
-    else {
-      analogInputsToReport = analogInputsToReport | (1 << analogPin);
-    }
-  }
-  // TODO: save status to EEPROM here, if changed
-}
-
-void reportDigitalCallback(byte port, int value)
-{
-  if (port < TOTAL_PORTS) {
-    reportPINs[port] = (byte)value;
-  }
-  // do not disable analog reporting on these 8 pins, to allow some
-  // pins used for digital, others analog.  Instead, allow both types
-  // of reporting to be enabled, but check if the pin is configured
-  // as analog when sampling the analog inputs.  Likewise, while
-  // scanning digital pins, portConfigInputs will mask off values from any
-  // pins configured as analog
-}
-
-/*==============================================================================
- * SYSEX-BASED commands
- *============================================================================*/
-
-void sysexCallback(byte command, byte argc, byte *argv)
-{
-  byte mode;
-  byte slaveAddress;
-  byte slaveRegister;
-  byte data;
-  unsigned int delayTime;
-  byte pin ;// used for tone
-  int frequency ;
-  int duration ;
-
-  switch (command) {
-    case I2C_REQUEST:
-      mode = argv[1] & I2C_READ_WRITE_MODE_MASK;
-      if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) {
-        Firmata.sendString("10-bit addressing mode is not yet supported");
-        return;
-      }
-      else {
-        slaveAddress = argv[0];
-      }
-
-      switch (mode) {
-        case I2C_WRITE:
-          Wire.beginTransmission(slaveAddress);
-          for (byte i = 2; i < argc; i += 2) {
-            data = argv[i] + (argv[i + 1] << 7);
-#if ARDUINO >= 100
-            Wire.write(data);
-#else
-            Wire.send(data);
-#endif
-          }
-          Wire.endTransmission();
-          delayMicroseconds(70);
-          break;
-        case I2C_READ:
-          if (argc == 6) {
-            // a slave register is specified
-            slaveRegister = argv[2] + (argv[3] << 7);
-            data = argv[4] + (argv[5] << 7);  // bytes to read
-            readAndReportData(slaveAddress, (int)slaveRegister, data);
-          }
-          else {
-            // a slave register is NOT specified
-            data = argv[2] + (argv[3] << 7);  // bytes to read
-            readAndReportData(slaveAddress, (int)REGISTER_NOT_SPECIFIED, data);
-          }
-          break;
-        case I2C_READ_CONTINUOUSLY:
-          if ((queryIndex + 1) >= MAX_QUERIES) {
-            // too many queries, just ignore
-            Firmata.sendString("too many queries");
-            break;
-          }
-          queryIndex++;
-          query[queryIndex].addr = slaveAddress;
-          query[queryIndex].reg = argv[2] + (argv[3] << 7);
-          query[queryIndex].bytes = argv[4] + (argv[5] << 7);
-          break;
-        case I2C_STOP_READING:
-          byte queryIndexToSkip;
-          // if read continuous mode is enabled for only 1 i2c device, disable
-          // read continuous reporting for that device
-          if (queryIndex <= 0) {
-            queryIndex = -1;
-          }
-          else {
-            // if read continuous mode is enabled for multiple devices,
-            // determine which device to stop reading and remove it's data from
-            // the array, shifiting other array data to fill the space
-            for (byte i = 0; i < queryIndex + 1; i++) {
-              if (query[i].addr = slaveAddress) {
-                queryIndexToSkip = i;
-                break;
-              }
-            }
-
-            for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) {
-              if (i < MAX_QUERIES) {
-                query[i].addr = query[i + 1].addr;
-                query[i].reg = query[i + 1].addr;
-                query[i].bytes = query[i + 1].bytes;
-              }
-            }
-            queryIndex--;
-          }
-          break;
-        default:
-          break;
-      }
-      break;
-    case I2C_CONFIG:
-      delayTime = (argv[0] + (argv[1] << 7));
-
-      if (delayTime > 0) {
-        i2cReadDelayTime = delayTime;
-      }
-
-      if (!isI2CEnabled) {
-        enableI2CPins();
-      }
-
-      break;
-    case SERVO_CONFIG:
-      if (argc > 4) {
-        // these vars are here for clarity, they'll optimized away by the compiler
-        byte pin = argv[0];
-        int minPulse = argv[1] + (argv[2] << 7);
-        int maxPulse = argv[3] + (argv[4] << 7);
-
-        if (IS_PIN_SERVO(pin)) {
-          if (servos[PIN_TO_SERVO(pin)].attached())
-            servos[PIN_TO_SERVO(pin)].detach();
-          servos[PIN_TO_SERVO(pin)].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse);
-          setPinModeCallback(pin, SERVO);
-        }
-      }
-      break;
-    case SAMPLING_INTERVAL:
-      if (argc > 1) {
-        samplingInterval = argv[0] + (argv[1] << 7);
-        if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) {
-          samplingInterval = MINIMUM_SAMPLING_INTERVAL;
-        }
-        /* calculate number of loops per ping */
-        numLoops = INTER_PING_INTERVAL / samplingInterval ;
-        //numLoops = 1 ;
-      }
-      else {
-        //Firmata.sendString("Not enough data");
-      }
-      break;
-    case EXTENDED_ANALOG:
-      if (argc > 1) {
-        int val = argv[1];
-        if (argc > 2) val |= (argv[2] << 7);
-        if (argc > 3) val |= (argv[3] << 14);
-        analogWriteCallback(argv[0], val);
-      }
-      break;
-    case CAPABILITY_QUERY:
-      Firmata.write(START_SYSEX);
-      Firmata.write(CAPABILITY_RESPONSE);
-      for (byte pin = 0; pin < TOTAL_PINS; pin++) {
-        if (IS_PIN_DIGITAL(pin)) {
-          Firmata.write((byte)INPUT);
-          Firmata.write(1);
-          Firmata.write((byte)OUTPUT);
-          Firmata.write(1);
-        }
-        if (IS_PIN_ANALOG(pin)) {
-          Firmata.write(ANALOG);
-          Firmata.write(10);
-        }
-        if (IS_PIN_PWM(pin)) {
-          Firmata.write(PWM);
-          Firmata.write(8);
-        }
-        if (IS_PIN_SERVO(pin)) {
-          Firmata.write(SERVO);
-          Firmata.write(14);
-        }
-        if (IS_PIN_I2C(pin)) {
-          Firmata.write(I2C);
-          Firmata.write(1);  // to do: determine appropriate value
-        }
-        Firmata.write(127);
-      }
-      Firmata.write(END_SYSEX);
-      break;
-    case PIN_STATE_QUERY:
-      if (argc > 0) {
-        byte pin = argv[0];
-        Firmata.write(START_SYSEX);
-        Firmata.write(PIN_STATE_RESPONSE);
-        Firmata.write(pin);
-        if (pin < TOTAL_PINS) {
-          Firmata.write((byte)pinConfig[pin]);
-          Firmata.write((byte)pinState[pin] & 0x7F);
-          if (pinState[pin] & 0xFF80) Firmata.write((byte)(pinState[pin] >> 7) & 0x7F);
-          if (pinState[pin] & 0xC000) Firmata.write((byte)(pinState[pin] >> 14) & 0x7F);
-        }
-        Firmata.write(END_SYSEX);
-      }
-      break;
-    case ANALOG_MAPPING_QUERY:
-      Firmata.write(START_SYSEX);
-      Firmata.write(ANALOG_MAPPING_RESPONSE);
-      for (byte pin = 0; pin < TOTAL_PINS; pin++) {
-        Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127);
-      }
-      Firmata.write(END_SYSEX);
-      break;
-
-
-    case TONE_DATA:
-      byte toneCommand, pin;
-      int frequency, duration;
-
-      toneCommand = argv[0];
-      pin = argv[1];
-
-      if (toneCommand == TONE_TONE) {
-        frequency = argv[2] + (argv[3] << 7);
-        // duration is currently limited to 16,383 ms
-        duration = argv[4] + (argv[5] << 7);
-        tone(pin, frequency, duration);
-      }
-      else if (toneCommand == TONE_NO_TONE) {
-        noTone(pin);
-      }
-      break ;
-
-      // arg0 = trigger pin
-      // arg1 = echo pin
-      // arg2 = ping interval in milliseconds if 0, then set to 33
-      // arg3 = maxdistance lsb
-      // arg4 = maxdistance msb
-    case SONAR_CONFIG :
-      int max_distance ;
-      if ( numActiveSonars < MAX_SONARS)
-      {
-        sonarTriggerPin = argv[0] ;
-        sonarEchoPin = argv[1] ;
-        // set interval to a minium of 33 ms.
-        if ( argv[2] >= 33 ) {
-          pingInterval = argv[2] ;
-        }
-        else {
-          pingInterval = 33 ;
-        }
-        max_distance = argv[3] + (argv[4] << 7 ) ;
-        sonarPinNumbers[numActiveSonars] = sonarTriggerPin ;
-
-        setPinModeCallback(sonarTriggerPin, SONAR);
-        setPinModeCallback(sonarEchoPin, SONAR);
-        sonars[numActiveSonars] = new NewPing(sonarTriggerPin, sonarEchoPin, max_distance) ;
-        numActiveSonars++ ;
-      }
-      else {
-        Firmata.sendString("PING_CONFIG Error: Exceeded number of supported ping devices");
-      }
-      break ;
-
-    case STEPPER_DATA:
-      int motorID = -1 ;
-      // determine if this a STEPPER_CONFIGURE command or STEPPER_OPERATE command
-      if (argv[0] == STEPPER_CONFIGURE)
-      {
-        int motorID = argv[1] ;
-
-        if ( motorID < 0 || motorID > 3)
-        {
-          Firmata.sendString("STEPPER CONFIG Error: MOTOR ID is from 0-3");
-        }
-        if ( steppers[motorID] != NULL )
-        {
-          Firmata.sendString("STEPPER CONFIG Error: MOTOR ALREADY ASSIGNED");
-        }
-        else
-        {
-
-          int numSteps = argv[2] + (argv[3] << 7);
-          int pin1 = argv[4] ;
-          int pin2 = argv[5] ;
-          if ( argc == 6 )
-          {
-            // two pin motor
-            steppers[motorID] = new Stepper(numSteps, pin1, pin2) ;
-          }
-          else if (argc == 8 ) // 4 wire motor
-          {
-            int pin3 = argv[6] ;
-            int pin4 = argv[7] ;
-            steppers[motorID] =  new Stepper(numSteps, pin1, pin2, pin3, pin4) ;
-          }
-          else
-          {
-            Firmata.sendString("STEPPER CONFIG Error: Wrong Number of arguments");
-            printData("argc = ", argc) ;
-          }
-        }
-      }
-      else if ( argv[0] == STEPPER_STEP )
-      {
-        int motorID = argv[1] ;
-        long speed = (long)argv[2] | ((long)argv[3] << 7) | ((long)argv[4] << 14);
-        int numSteps = argv[5] + (argv[6] << 7);
-        int direction = argv[7] ;
-        if (steppers[motorID] != NULL )
-        {
-          steppers[motorID]->setSpeed(speed) ;
-          if (direction == 0 )
-          {
-            numSteps *= -1 ;
-          }
-          steppers[motorID]->step(numSteps) ;
-        }
-        else
-        {
-          Firmata.sendString("STEPPER OPERATE Error: MOTOR NOT CONFIGURED");
-        }
-      }
-      else
-      {
-        Firmata.sendString("STEPPER CONFIG Error: UNKNOWN STEPPER COMMAND");
-      }
-      break ;
-  }
-}
-
-void enableI2CPins()
-{
-  byte i;
-  // is there a faster way to do this? would probaby require importing
-  // Arduino.h to get SCL and SDA pins
-  for (i = 0; i < TOTAL_PINS; i++) {
-    if (IS_PIN_I2C(i)) {
-      // mark pins as i2c so they are ignore in non i2c data requests
-      setPinModeCallback(i, I2C);
-    }
-  }
-
-  isI2CEnabled = true;
-
-  // is there enough time before the first I2C request to call this here?
-  Wire.begin();
-}
-
-/* disable the i2c pins so they can be used for other functions */
-void disableI2CPins() {
-  isI2CEnabled = false;
-  // disable read continuous mode for all devices
-  queryIndex = -1;
-  // uncomment the following if or when the end() method is added to Wire library
-  // Wire.end();
-}
-
-/*==============================================================================
- * SETUP()
- *============================================================================*/
-
-void systemResetCallback()
-{
-  // initialize a defalt state
-  // TODO: option to load config from EEPROM instead of default
-  if (isI2CEnabled) {
-    disableI2CPins();
-  }
-  for (byte i = 0; i < TOTAL_PORTS; i++) {
-    reportPINs[i] = false;      // by default, reporting off
-    portConfigInputs[i] = 0;	// until activated
-    previousPINs[i] = 0;
-  }
-  // pins with analog capability default to analog input
-  // otherwise, pins default to digital output
-  for (byte i = 0; i < TOTAL_PINS; i++) {
-    if (IS_PIN_ANALOG(i)) {
-      // turns off pullup, configures everything
-      setPinModeCallback(i, ANALOG);
-    }
-    else if ( IS_PIN_TONE(i)) {
-      noTone(i) ;
-    }
-    else {
-      // sets the output to 0, configures portConfigInputs
-      setPinModeCallback(i, OUTPUT);
-    }
-  }
-  // stop pinging
-  numActiveSonars = 0 ;
-  for (int i = 0; i < MAX_SONARS; i++) {
-    sonarPinNumbers[i] = IGNORE ;
-    if ( sonars[i] ) {
-      sonars[i] = NULL ;
-    }
-  }
-  numActiveSonars = 0 ;
-
-  // by default, do not report any analog inputs
-  analogInputsToReport = 0;
-
-  // clear out array of steppers
-  for ( int i = 0 ; i < MAX_NUM_STEPPERS ; i++)
-    steppers[i] = NULL ;
-
-  /* send digital inputs to set the initial state on the host computer,
-   * since once in the loop(), this firmware will only send on change */
-  /*
-  TODO: this can never execute, since no pins default to digital input
-   but it will be needed when/if we support EEPROM stored config
-   for (byte i=0; i < TOTAL_PORTS; i++) {
-   outputPort(i, readPort(i, portConfigInputs[i]), true);
-   }
-   */
-}
-
-void setup()
-{
-
-
-  Firmata.setFirmwareVersion(FIRMATA_MAJOR_VERSION, FIRMATA_MINOR_VERSION);
-
-  Firmata.attach(ANALOG_MESSAGE, analogWriteCallback);
-  Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback);
-  Firmata.attach(REPORT_ANALOG, reportAnalogCallback);
-  Firmata.attach(REPORT_DIGITAL, reportDigitalCallback);
-  Firmata.attach(SET_PIN_MODE, setPinModeCallback);
-  Firmata.attach(START_SYSEX, sysexCallback);
-  Firmata.attach(SYSTEM_RESET, systemResetCallback);
-
-  numActiveSonars = 0 ;
-  pingLoopCounter = 0 ;
-  for (uint8_t i = 1; i < MAX_SONARS; i++) // Set the starting time for each sensor.
-  {
-    sonarPinNumbers[i] = IGNORE ;
-    if ( sonars[i] ) {
-      sonars[i] = NULL ;
-    }
-  }
-
-  /* calculate number of loops per ping */
-  numLoops = INTER_PING_INTERVAL / samplingInterval ;
-
-  Firmata.begin(57600);
-  systemResetCallback();  // reset to default config
-
-}
-
-/*==============================================================================
- * LOOP()
- *============================================================================*/
-void loop()
-{
-  byte pin, analogPin;
-  int pingResult = 0;
-
-  /* DIGITALREAD - as fast as possible, check for changes and output them to the
-   * FTDI buffer using Serial.print()  */
-  checkDigitalInputs();
-
-  /* SERIALREAD - processing incoming messagse as soon as possible, while still
-   * checking digital inputs.  */
-  while (Firmata.available())
-    Firmata.processInput();
-
-  /* SEND FTDI WRITE BUFFER - make sure that the FTDI buffer doesn't go over
-   * 60 bytes. use a timer to sending an event character every 4 ms to
-   * trigger the buffer to dump. */
-
-  currentMillis = millis();
-  if (currentMillis - previousMillis > samplingInterval) {
-    previousMillis += samplingInterval;
-
-    if ( pingLoopCounter++ > numLoops)
-    {
-      pingLoopCounter = 0 ;
-      if (numActiveSonars)
-      {
-        unsigned int uS = sonars[nextSonar]->ping();
-        // Convert ping time to distance in cm and print
-        pingResult = uS / US_ROUNDTRIP_CM ;
-        currentSonar = nextSonar ;
-        if ( nextSonar++ >= numActiveSonars - 1)
-        {
-          nextSonar = 0 ;
-        }
-        sonarLSB = pingResult & 0x7f ;
-        sonarMSB = pingResult >> 7 & 0x7f ;
-
-        Firmata.write(START_SYSEX);
-        Firmata.write(SONAR_DATA) ;
-        Firmata.write(sonarPinNumbers[currentSonar]) ;
-        Firmata.write(sonarLSB) ;
-        Firmata.write(sonarMSB) ;
-        Firmata.write(END_SYSEX);
-      }
-    }
-
-
-    /* ANALOGREAD - do all analogReads() at the configured sampling interval */
-    for (pin = 0; pin < TOTAL_PINS; pin++) {
-      if (IS_PIN_ANALOG(pin) && pinConfig[pin] == ANALOG) {
-        analogPin = PIN_TO_ANALOG(pin);
-        if (analogInputsToReport & (1 << analogPin)) {
-          Firmata.sendAnalog(analogPin, analogRead(analogPin));
-        }
-      }
-    }
-    // report i2c data for all device with read continuous mode enabled
-    if (queryIndex > -1) {
-      for (byte i = 0; i < queryIndex + 1; i++) {
-        readAndReportData(query[i].addr, query[i].reg, query[i].bytes);
-      }
-    }
-  }
-}
-
-
-
-void printData(char * id,  long data)
-{
-  char myArray[64] ;
-
-  String myString = String(data);
-  myString.toCharArray(myArray, 64) ;
-  Firmata.sendString(id) ;
-  Firmata.sendString(myArray);
-}
-
-
-


payloads per second to the monitor

payloads per second to the monitor

--- transmitter/TX/TX.ino
+++ transmitter/TX/TX.ino
@@ -191,9 +191,11 @@
       printf("pps: %d, lost: %d \n\r", pps, ppsLost);
     }
     ack_payload.key = 255;
-    ack_payload.val = pps;
+    ack_payload.val = (pps << 2); // Multiply by 4 (fast)
     monitor_sendData();
-  } else if (now - vcc_last > 3000) {
+  }
+
+  if (now - vcc_last > 3000) {
     vcc_last = now;
     ack_payload.key = 253;
     ack_payload.val = 4000; //@todo tx battery level


Remove unused servo lib. Localize some vars and pass pointers for others.

--- src/du.ino
+++ src/du.ino
@@ -1,17 +1,7 @@
-#include <Servo.h>
-Servo servo;
-
-bool debug = false;
-
 char request[7];
 int index = 0;
-char cmd[3];
-char pin[3];
-char val[4];
-
 String response = "";
-
-
+bool debug = false;

 void setup() {
   Serial.begin(115200);
@@ -29,7 +19,7 @@

     // Catch the request's ending delimiter and process the request.
     else if (c == '.') {
-      process();
+      process(request);
       if(response != "") Serial.println(response);
     }

@@ -42,24 +32,24 @@
 /*
  * Deal with a full request and determine function to call
  */
-void process() {
-  strncpy(cmd, request, 2);      cmd[2] = '\0';
-  strncpy(pin, request + 2, 2);  pin[2] = '\0';
-  strncpy(val, request + 4, 3);  val[3] = '\0';
-
+void process(char *request) {
+   char cmd[3];  strncpy(cmd, request, 2);      cmd[2] = '\0';
+   char pin[3];  strncpy(pin, request + 2, 2);  pin[2] = '\0';
+   char val[4];  strncpy(val, request + 4, 3);  val[3] = '\0';
+
   // if (debug) Serial.println(request);
-  int p = getPin(pin);
-  if (p == -1) return; // Should raise some kind of "bad pin" error.
+  int rawPin = getPin(pin);
+  if (rawPin == -1) return; // Should raise some kind of "bad pin" error.

   int cmdid = atoi(cmd);
   switch(cmdid) {
-    case 0:  setMode    (p, val);       break;
-    case 1:  dWrite     (p, val);       break;
-    case 2:  dRead      (p);            break;
-    case 3:  aWrite     (p, val);       break;
-    case 4:  aRead      (p);            break;
-    case 99: toggleDebug(val);          break;
-    default:                            break;
+    case 0:  setMode    (rawPin, val);             break;
+    case 1:  dWrite     (rawPin, val);             break;
+    case 2:  dRead      (rawPin, &response);       break;
+    case 3:  aWrite     (rawPin, val);             break;
+    case 4:  aRead      (rawPin, &response, pin);  break;
+    case 99: toggleDebug(val);                     break;
+    default:                                       break;
   }
 }

@@ -89,24 +79,25 @@
     digitalWrite(p, HIGH);
   }
 }
-void dRead(int p) {
+void dRead(int p, String *response) {
   pinMode(p, INPUT);
   int oraw = digitalRead(p);
   char m[7];
   sprintf(m, "%02d::%02d", p, oraw);
-  response = m;
-}
-void aRead(int p) {
-  pinMode(p, INPUT);
-  int rval = analogRead(p);
-  char m[8];
-  sprintf(m, "%s::%03d", pin, rval);
-  response = m;
+  *response = m;
 }
 void aWrite(int p, char *val) {
   pinMode(p, OUTPUT);
   analogWrite(p,atoi(val));
 }
+void aRead(int p, String *response, char *pin) {
+  pinMode(p, INPUT);
+  int rval = analogRead(p);
+  char m[8];
+  sprintf(m, "%s::%03d", pin, rval);
+  *response = m;
+}
+


TODO-632: WIP

TODO-632: WIP

--- test_SECFRAME/test_SECFRAME.ino
+++ test_SECFRAME/test_SECFRAME.ino
@@ -622,7 +622,7 @@
   AssertIsEqual(0, memcmp(input, inputDecoded, 32));
   }

-// Test encoding of entire secure frame for TX.
+// Test encoding/encryption then decoding/decryption of entire secure frame.
 static void testSecureSmallFrameEncoding()
   {
   Serial.println("SecureSmallFrameEncoding");
@@ -655,14 +655,15 @@
   const uint8_t id[] = { 0xaa, 0xaa, 0xaa, 0xaa };
   const uint8_t iv[] = { 0xaa, 0xaa, 0xaa, 0xaa, 0x55, 0x55, 0x00, 0x00, 0x2a, 0x00, 0x03, 0x19 };
   const uint8_t body[] = { 0x7f, 0x11, 0x7b, 0x22, 0x62, 0x22, 0x3a, 0x31 };
-  AssertIsEqual(63, OTRadioLink::encodeSecureSmallFrameRaw(buf, sizeof(buf),
+  const uint8_t encodedLength = OTRadioLink::encodeSecureSmallFrameRaw(buf, sizeof(buf),
                                     OTRadioLink::FTS_BasicSensorOrValve,
                                     0,
                                     id, 4,
                                     body, sizeof(body),
                                     iv,
                                     OTAESGCM::fixed32BTextSize12BNonce16BTagSimpleEnc_DEFAULT_STATELESS,
-                                    NULL, zeroKey));
+                                    NULL, zeroKey);
+  AssertIsEqual(63, encodedLength);
   //3f cf 04 aa aa aa aa 20 | ...
   AssertIsEqual(0x3e, buf[0]);
   AssertIsEqual(0xcf, buf[1]);
@@ -685,6 +686,9 @@
   AssertIsEqual(0x97, buf[46]); // 1st byte of tag.
   AssertIsEqual(0x8d, buf[61]); // 16th/last byte of tag.
   AssertIsEqual(0x80, buf[62]); // enc format.
+  // To decode, first unpick the header.
+  OTRadioLink::SecurableFrameHeader sfhRX;
+//  AssertIsTrue(0 != sfhRX.checkAndDecodeSmallFrameHeader(buf, encodedLength));
   }


Some clean-ups in firmware. Make ROW_LATCH toggle time longer.

--- avr/avr.ino
+++ avr/avr.ino
@@ -1,8 +1,6 @@
 /* -*- mode: c++; c-file-style: "linux" -*-
   Telepulssi TP-KN10 slave LED screen driver
 */
-
-#include <SPI.h>

 // Helper functions. NB! ARRAY_SIZE doesn't check if it's an array.
 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
@@ -70,20 +68,20 @@
 unsigned int byte_i;
 uint8_t bit_i;

+inline static void try_buf_swap(void);
 inline static void frame_store(uint8_t intensity);
 inline static void set_pixel(uint8_t *plane);
 static void screen_on(void);
 inline static void pick_column(void);
 static void try_drive_screen(void);

-void buf_swap(void) {
+inline static void try_buf_swap(void) {
+	if (!may_flip) return;
 	uint8_t (*tmp)[56] = buf_front;
 	buf_front = buf_back;
 	buf_back = tmp;
-	if (may_flip) {
-		Serial.write('S');
-		may_flip = 0;
-	}
+	Serial.write('S');
+	may_flip = 0;
 }

 void setup() {
@@ -289,15 +287,15 @@
 	if (pwm_i >= ARRAY_SIZE(pwm_lengths)) {
 		pwm_i = 0;
 		col_i++;
-		if (col_i > 7) {
+		if (col_i >= 8) {
 			col_i = 0;
 			row_i++;
-			if (row_i > 6) {
+			if (row_i >= 7) {
 				row_i = 0;
-				if (may_flip) {
-					buf_swap();
-				}
+				try_buf_swap();
 			}
+			// We can already pull the row latch down
+			digitalWrite(PIN_ROW_LATCH, LOW);
 		}
 	}

@@ -305,8 +303,7 @@
 	// it down.
 	digitalWrite(PIN_COL_LATCH, LOW);

-	// Send new data via SPI. Don't need to wait it to complete
-	// because it completes before the next timer interrupt.
+	// Send new data via SPI. Completion is monitored in SPI_STC_vect.
 	SPDR = buf_front[pwm_i][8*row_i+col_i];
 }

@@ -316,7 +313,6 @@
 {
 	if (spi_row_change) {
 		// Latch the written row info
-		digitalWrite(PIN_ROW_LATCH, LOW);
 		digitalWrite(PIN_ROW_LATCH, HIGH);
 		spi_row_change = false;
 		screen_on();


cleaned embedded a little bit

cleaned embedded a little bit

--- embedded/pca_9685/pca_9685.ino
+++ embedded/pca_9685/pca_9685.ino
@@ -1,113 +0,0 @@
-/*
- Code to talk to our PCA9685 PWM multiplexer using our arduino via I2c
-
-
-//sgillen - stole a lot of this code from this adafruit repo https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library for a board they sell with this chip on it.
-//had to change the mode flags to get it to work using the internal oscilator
-
-*/
-
-#include <Wire.h>
-
-
-#define PCA9685_MODE1 0x0
-#define PCA9685_PRESCALE 0xFE
-
-#define PCA9Address 0xFF // Device address in which is also included the 8th bit for selecting the mode, read in this case.
-#define allCall 0xE0 //address for "all call" which should turn all LEDs on
-
-
-#define LED0_ON_L 0x6
-#define LED0_ON_H 0x7
-#define LED0_OFF_L 0x8
-#define LED0_OFF_H 0x9
-
-
-int freq = 1400; //pretty arbitrary, max is 1600
-
-
-uint8_t read8(uint8_t addr) {
-  Wire.beginTransmission(PCA9Address);
-  Wire.write(addr);
-  Wire.endTransmission();
-
-  Wire.requestFrom((uint8_t)PCA9Address, (uint8_t)1);
-  return Wire.read();
-}
-
-void write8(uint8_t addr, uint8_t d) {
-  Wire.beginTransmission(PCA9Address);
-  Wire.write(addr);
-  Wire.write(d);
-  Wire.endTransmission();
-}
-
-
-void setup() {
-  Wire.begin(); // Initiate th1e Wire library
-  Serial.begin(9600);
-  delay(100);
-
-
-
-  Serial.print("Attempting to set freq ");
-  Serial.println(freq);
-  freq *= 0.9;  // Correct for overshoot in the frequency setting (see issue #11).
-  float prescaleval = 25000000;
-  prescaleval /= 4096;
-  prescaleval /= freq;
-  prescaleval -= 1;
-
-  uint8_t prescale = floor(prescaleval + 0.5);
-
-  uint8_t oldmode = read8(PCA9685_MODE1);
-  uint8_t oldmode2 = read8(PCA9685_MODE1 + 1);
-
-  Serial.println("old mode was");
-  Serial.println(oldmode);
-  Serial.println(oldmode2);
-
-  uint8_t newmode = 0x21;
-  write8(PCA9685_MODE1, newmode); // go to sleep
-  write8(PCA9685_PRESCALE, prescale); // set the prescaler
-  //write8(PCA9685_MODE1, oldmode);
-  //delay(5);
-  //write8(PCA9685_MODE1, oldmode | 0xa1);
-
-
-  oldmode = read8(PCA9685_MODE1);
-  oldmode2 = read8(PCA9685_MODE1 + 1);
-
-  Serial.println("new mode is");
-  Serial.println(oldmode);
-  Serial.println(oldmode2);
-
-
-
-
-}
-void loop() {
-
-
-  uint16_t on = 1;
-  uint16_t off = 2000;
-
-  Wire.beginTransmission(PCA9Address);
-  Wire.write(LED0_ON_L+4);
-  Wire.write(on);
-  Wire.write(on>>8);
-  Wire.write(off);
-  Wire.write(off>>8);
-  Wire.endTransmission();
-
-  delay(1000);
-
-  Serial.println(read8(LED0_ON_L +4));
-  Serial.println(read8(LED0_ON_H+4));
-
-  Serial.println();
-
-  Serial.println(read8(LED0_OFF_L+4));
-  Serial.println(read8(LED0_OFF_H+4));
-
-}


reset game with long press

reset game with long press

--- pingpong/pingpong.ino
+++ pingpong/pingpong.ino
@@ -32,7 +32,7 @@
 int Button::handle()
 {
   int event;
-  int now_pressed = digitalRead(pin);
+  int now_pressed = !digitalRead(pin);

   if (!now_pressed && pressed) {
     if (counter < longpress_time)
@@ -48,7 +48,7 @@
   } else {
     counter = 0;
   }
-
+
   pressed = now_pressed;
   return event;
 }
@@ -58,38 +58,49 @@
 int p1Score = 0;
 int p2Score = 0;

+int gameOver = 0;
+
 Button p1Button(P1PIN);
 Button p2Button(P2PIN);

 void setup()
 {
-  pinMode(p1Pin, INPUT);
-  pinMode(p2Pin, INPUT);
   Serial.begin(9600);
   showScore();

   p1Button.init();
+  p2Button.init();
 }

 void loop()
 {
   int p1Event, p2Event;
-
+
   p1Event = p1Button.handle();
-  if (p1Event) {
+  if (!gameOver && p1Event == BUTTON_SHORT) {
     p1Score++;
     showScore();
     checkForWinner();
   }

+  if (gameOver && p1Event == BUTTON_LONG) {
+    resetGame();
+    showScore();
+  }
+
   p2Event = p2Button.handle();
-  if (p2Event) {
+  if (!gameOver && p2Event == BUTTON_SHORT) {
     p2Score++;
     showScore();
     checkForWinner();
   }
-
-  delay(100);
+
+  if (gameOver && p2Event == BUTTON_LONG) {
+    resetGame();
+    showScore();
+  }
+
+  delay(20);
 }

 void showScore()
@@ -112,8 +123,7 @@
     }
     Serial.println("   *** WINNER ***");

-    resetGame();
-    showScore();
+    gameOver = 1;
   }
 }

@@ -121,6 +131,7 @@
 {
   p1Score = 0;
   p2Score = 0;
+  gameOver = 0;
 }


Ik ben een bout

Ik ben een bout

--- LightTrain.ino
+++ LightTrain.ino
@@ -10,7 +10,7 @@
 #define NUMPIXELS      10
 #define SENSOR_THRESHOLD 400

-#define IDLE_TIME 15*1000
+#define IDLE_TIME 300*1000
 #define WIT pixels.Color(255,255,255)
 #define UIT pixels.Color(0,0,0)

@@ -32,7 +32,7 @@
 int sensor1;
 int delayval = 200; // delay for half a second
 int ms = 0;         // Aantal milliseconden dat de trein erover doet om sensor 1 te passeren.
-int laatste_trein;   // Aantal milliseconden sinds de laatste keer dat de trein langskwam.
+unsigned long laatste_trein;   // Aantal milliseconden sinds de laatste keer dat de trein langskwam.
 int aantal_leds;
 boolean trein_langs;


Debugging

Debugging

--- receiver_analog/receiver_analog.ino
+++ receiver_analog/receiver_analog.ino
@@ -27,7 +27,7 @@

-
+int parsed_val = 0;
 byte solar_val = 64; // Temporary half value
 volatile byte wd_isr = WD_DO_STUFF;

@@ -104,6 +104,7 @@
         // comma 6 = battery reading

         if (comma == 5) {
+          parsed_val = val;
           solar_val = map(val, 0, 10000, 0, 128);

@@ -153,6 +154,10 @@
     // Ofcourse this is rather pointless a sleep will kill the pwm (replacing with digital pot)
     //analogWrite(PWM_PIN, solar_val);

+    Serial.print(parsed_val);
+    Serial.print(" -> ");
+    Serial.println(solar_val);
+
     digitalPotWrite(POT_ADDRESS, solar_val);

     // Turn off message indicator


Much nicer array building now

Much nicer array building now

--- Synthduino.ino
+++ Synthduino.ino
@@ -1,43 +1,26 @@
 #include "note.h"
 #include "pitches.h"
-#define LENGTH 32

-/*
-// Alberti Baseline
-int notes[] = {NOTE_C4, NOTE_G4, NOTE_E4, NOTE_G4,
-							 NOTE_C4, NOTE_G4, NOTE_E4, NOTE_G4,
-							 NOTE_B3, NOTE_G4, NOTE_F4, NOTE_G4,
-							 NOTE_C4, NOTE_G4, NOTE_E4, NOTE_G4,
-							 NOTE_C4, NOTE_A4, NOTE_F4, NOTE_A4,
-							 NOTE_C4, NOTE_G4, NOTE_E4, NOTE_G4,
-							 NOTE_B3, NOTE_G4, NOTE_F4, NOTE_G4,
-							 NOTE_C4, NOTE_G4, NOTE_E4, NOTE_G4
-							};
-int durations[] = { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
-										4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4
-									};
+#define BASS 12
+
+/* HEADER SECTION
+ * Declare your tempo and parts.
+ * Examples:
+ * TEMPO = 120 // in bpm (beats per minute) - how many quarter notes per minute
+ * Note bassline[] = { {NOTE_C3, 2}, {NOTE_DS3, 2}, {NOTE_F3, 1} };
  */

-Note melody[LENGTH];
-Note theNote(NOTE_A4, 2);
-
+Note bassLine[] = { {NOTE_C3, 2}, {NOTE_DS3, 2}, {NOTE_F3, 1} };
+
+#define TEMPO 120
+
 void setup(){
-  pinMode(12, OUTPUT);
-  for(int i=0; i<LENGTH; i++){
-    Note temp(notes[i], durations[i]);
-    melody[i] = temp;
-  }
+	pinMode(BASS, OUTPUT);
 }

 void loop() {
-  for(int i=0; i<LENGTH; i++){
-    melody[i].play(12);
+  for(int i=0; i<3; i++){
+    bassLine[i].play(12);
   }
  // delay(10000);
- //theNote.play(12);
-}
-
-// 120 bmp = 120 qNotes/60 seconds = 2 Hz freq, period = .5 sec = 500k millis
-// 8 = 4hz = .25 * 1,000,000 = 250,000
-
-// whole note  = .5 Hz+}


Added arduino sketch for lightstrip pollution meter

--- arduino/aqi_lightstrip.ino
+++ arduino/aqi_lightstrip.ino
@@ -3,3 +3,261 @@
 # receives an INT and displays that value onto the LED Strip
 # In my case the LED Strip has 60 LEDs attached to it, and i
 # allow the Pollution index to be from 0 to 200;
+#include "LPD8806.h"
+#include "SPI.h"
+
+int dataPin = 11;
+int clockPin = 13;
+
+unsigned long timeout = 60000*2;
+unsigned long timestamp = millis();
+
+LPD8806 strip = LPD8806(60, dataPin, clockPin);
+
+void setup() {
+	strip.begin();
+	strip.show();
+
+	Serial.begin(9600);
+	delay(100);
+	Serial.println("Reset");
+
+	/*
+		strip.setPixelColor(6,strip.Color(3,2,0)); // yellow
+		strip.setPixelColor(7,strip.Color(4,1,0)); // orange
+		strip.setPixelColor(8,strip.Color(5,0,0)); // red
+		strip.setPixelColor(9,strip.Color(5,0,2)); // magenta
+		strip.show();
+		while(1){}
+	*/
+}
+
+
+void loop() {
+	while(Serial.available()>0){
+		int data = Serial.parseInt();
+
+		if(data > 239){
+			data = 239;
+		}
+		if(data < 0){
+			data = 0;
+		}
+
+		int data_mapped = map(data, 0, 239, 0, 59);
+
+		Serial.print(data);
+		Serial.print(" = ");
+		Serial.println(data_mapped);
+
+		if (Serial.read() == '\n') {
+			timestamp = millis();
+			for (int i = strip.numPixels(); i >= data_mapped; i--) {
+				strip.setPixelColor(i,strip.Color(0,0,0));
+				strip.show();
+			}
+
+			for (int i=0; i <= data_mapped; i++){
+				switch(i){
+					case 0:
+						strip.setPixelColor(i,strip.Color(0,5,0));
+						break;
+					case 1:
+						strip.setPixelColor(i,strip.Color(0,5,0));
+						break;
+					case 2:
+						strip.setPixelColor(i,strip.Color(0,5,0));
+						break;
+					case 3:
+						strip.setPixelColor(i,strip.Color(0,5,0));
+						break;
+					case 4:
+						strip.setPixelColor(i,strip.Color(0,5,0));
+						break;
+					case 5:
+						strip.setPixelColor(i,strip.Color(0,5,0));
+						break;
+					case 6:
+						strip.setPixelColor(i,strip.Color(0,5,0));
+						break;
+					case 7:
+						strip.setPixelColor(i,strip.Color(0,5,0));
+						break;
+					case 8:
+						strip.setPixelColor(i,strip.Color(0,5,0));
+						break;
+					case 9:
+						strip.setPixelColor(i,strip.Color(0,5,0));
+						break;
+					case 10:
+						strip.setPixelColor(i,strip.Color(1,4,0));
+						break;
+					case 11:
+						strip.setPixelColor(i,strip.Color(2,3,0));
+						break;
+					case 12:
+						strip.setPixelColor(i,strip.Color(3,2,0));
+						break;
+					case 13:
+						strip.setPixelColor(i,strip.Color(3,2,0));
+						break;
+					case 14:
+						strip.setPixelColor(i,strip.Color(3,2,0));
+						break;
+					case 15:
+						strip.setPixelColor(i,strip.Color(3,2,0));
+						break;
+					case 16:
+						strip.setPixelColor(i,strip.Color(3,2,0));
+						break;
+					case 17:
+						strip.setPixelColor(i,strip.Color(3,2,0));
+						break;
+					case 18:
+						strip.setPixelColor(i,strip.Color(3,2,0));
+						break;
+					case 19:
+						strip.setPixelColor(i,strip.Color(3,2,0));
+						break;
+					case 20:
+						strip.setPixelColor(i,strip.Color(3,2,0));
+						break;
+					case 21:
+						strip.setPixelColor(i,strip.Color(3,2,0));
+						break;
+					case 22:
+						strip.setPixelColor(i,strip.Color(3,2,0));
+						break;
+					case 23:
+						strip.setPixelColor(i,strip.Color(3,1,0));
+						break;
+					case 24:
+						strip.setPixelColor(i,strip.Color(4,1,0));
+						break;
+					case 25:
+						strip.setPixelColor(i,strip.Color(4,1,0));
+						break;
+					case 26:
+						strip.setPixelColor(i,strip.Color(4,1,0));
+						break;
+					case 27:
+						strip.setPixelColor(i,strip.Color(4,1,0));
+						break;
+					case 28:
+						strip.setPixelColor(i,strip.Color(4,1,0));
+						break;
+					case 29:
+						strip.setPixelColor(i,strip.Color(4,1,0));
+						break;
+					case 30:
+						strip.setPixelColor(i,strip.Color(4,1,0));
+						break;
+					case 31:
+						strip.setPixelColor(i,strip.Color(4,1,0));
+						break;
+					case 32:
+						strip.setPixelColor(i,strip.Color(4,1,0));
+						break;
+					case 33:
+						strip.setPixelColor(i,strip.Color(4,1,0));
+						break;
+					case 34:
+						strip.setPixelColor(i,strip.Color(4,1,0));
+						break;
+					case 35:
+						strip.setPixelColor(i,strip.Color(5,1,0));
+						break;
+					case 36:
+						strip.setPixelColor(i,strip.Color(5,0,0));
+						break;
+					case 37:
+						strip.setPixelColor(i,strip.Color(5,0,0));
+						break;
+					case 38:
+						strip.setPixelColor(i,strip.Color(5,0,0));
+						break;
+					case 39:
+						strip.setPixelColor(i,strip.Color(5,0,0));
+						break;
+					case 40:
+						strip.setPixelColor(i,strip.Color(5,0,0));
+						break;
+					case 41:
+						strip.setPixelColor(i,strip.Color(5,0,0));
+						break;
+					case 42:
+						strip.setPixelColor(i,strip.Color(5,0,0));
+						break;
+					case 43:
+						strip.setPixelColor(i,strip.Color(5,0,0));
+						break;
+					case 44:
+						strip.setPixelColor(i,strip.Color(5,0,0));
+						break;
+					case 45:
+						strip.setPixelColor(i,strip.Color(5,0,0));
+						break;
+					case 46:
+						strip.setPixelColor(i,strip.Color(5,0,0));
+						break;
+					case 47:
+						strip.setPixelColor(i,strip.Color(5,0,0));
+						break;
+					case 48:
+						strip.setPixelColor(i,strip.Color(4,0,2));
+						break;
+					case 49:
+						strip.setPixelColor(i,strip.Color(5,0,2));
+						break;
+					case 50:
+						strip.setPixelColor(i,strip.Color(5,0,2));
+						break;
+					case 51:
+						strip.setPixelColor(i,strip.Color(5,0,2));
+						break;
+					case 52:
+						strip.setPixelColor(i,strip.Color(5,0,2));
+						break;
+					case 53:
+						strip.setPixelColor(i,strip.Color(5,0,2));
+						break;
+					case 54:
+						strip.setPixelColor(i,strip.Color(5,0,2));
+						break;
+					case 55:
+						strip.setPixelColor(i,strip.Color(5,0,2));
+						break;
+					case 56:
+						strip.setPixelColor(i,strip.Color(5,0,2));
+						break;
+					case 57:
+						strip.setPixelColor(i,strip.Color(5,0,2));
+						break;
+					case 58:
+						strip.setPixelColor(i,strip.Color(5,0,3));
+						break;
+					case 59:
+						strip.setPixelColor(i,strip.Color(5,0,4));
+						break;
+					default:
+					strip.setPixelColor(i,strip.Color(0,0,0));
+					break;
+				}
+				strip.show();
+			}
+		}
+	}
+
+	if(millis() - timestamp > timeout){
+		strip.setPixelColor(59,strip.Color(3,0,0));
+		delay(1000);
+		strip.show();
+
+		strip.setPixelColor(59,strip.Color(0,0,0));
+		delay(1000);
+		strip.show();
+	} else {
+		strip.setPixelColor(59,strip.Color(0,3,0));
+		strip.show();
+	}
+}


Update ZstabalizationTest1.ino

Update ZstabalizationTest1.ino

--- ZstabalizationTest1/ZstabalizationTest1.ino
+++ ZstabalizationTest1/ZstabalizationTest1.ino
@@ -56,10 +56,12 @@
     // if ROV is above saved state
       if(sensor.depth() > depthSavedState){
           // Move ROV DOWN
+          // Insert MOTOR CODE here
       }
     // if ROV is below saved state
       if(sensor.depth() < depthSavedState){
-          // Move ROV UP
+          // Move ROV UP
+          // Insert MOTOR CODE here
       }

     }


power_all_enable()

--- receiver_analog/receiver_analog.ino
+++ receiver_analog/receiver_analog.ino
@@ -336,7 +336,7 @@
   power_usart0_enable();
   power_twi_enable();
   */
-  power_all_disable();
+  power_all_enable();

   // Turn on the nrf24 radio
   radio.powerUp();


Optimalisatie

Optimalisatie

Optimaliseer onnodig gebruik van globale variabelen

--- LightTrain.ino
+++ LightTrain.ino
@@ -9,19 +9,19 @@

 #define PIN            4
 #define NUMPIXELS      10
-#define SENSOR_THRESHOLD 400
+#define SENSOR_THRESHOLD 400

-#define IDLE_TIME 300*1000
+#define IDLE_TIME 300L*1000L
 #define WIT kleur(255,255,255)
 #define UIT kleur(0,0,0)

 #if (delayval >= 200)
-#define KLEUR kleur(0, 150, 0) // Groen de trein gaat langzaam
-#elif (delayval < 200)
+#define KLEUR kleur(0, 200, 0) // Groen de trein gaat langzaam
+#elif (delayval < 200)
 #define KLEUR kleur(200, 200, 0) // Geel de trein gaat niet snel
-#elif (delayval < 150)
+#elif (delayval < 150)
 #define KLEUR kleur(200, 120, 0) // Oranje de trein gaat vrij snel
-#else
+#else
 #define KLEUR kleur(200, 0, 0)   // Rood de trein gaat vol gas
 #endif

@@ -30,50 +30,50 @@
 // example for more information on possible values.
 Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

-int sensor1;
-int delayval = 200; // delay for half a second
-int ms = 0;         // Aantal milliseconden dat de trein erover doet om sensor 1 te passeren.
+const int delayval = 200; // delay for half a second
 unsigned long laatste_trein;   // Aantal milliseconden sinds de laatste keer dat de trein langskwam.
-int aantal_leds;
-boolean trein_langs;
+

 void setup() {
   pixels.begin(); // This initializes the NeoPixel library.
-  for(int i=0;i<NUMPIXELS;i++){
+  for (int i = 0; i < NUMPIXELS; i++) {
     // Zet de beginkleur op wit
     pixels.setPixelColor(i, WIT);
   }
-  pixels.show();
+  pixels.show();
+  laatste_trein = millis();
 }

 void loop() {
-  sensor1 = analogRead(A0);
+  int sensor1 = analogRead(A0);
+  int aantal_leds;
+  boolean trein_aangekomen = false;
+  int ms = 0;         // Aantal milliseconden dat de trein erover doet om sensor 1 te passeren.
+
   while (sensor1 < SENSOR_THRESHOLD) { // Sensor is laag, de trein komt langs
     ms++;
     delay(1);
-    trein_langs = true;
+    trein_aangekomen = true;  // Er is een trein aangekomen
     sensor1 = analogRead(A0); // Herhaal deze loop totdat de waarde waar hoog is, dus totdat de trein voorbij is
   }
-  aantal_leds = ms/delayval;  // Het aantal ledjes dat de trein breedt is hoelang de trein overover doet gedeeld door hoelang een ledje duurt
-  if(trein_langs) {           // Als er een trein langsgekomen is doe het volgende:
-    for(int i=0;i<NUMPIXELS+aantal_leds;i++){ // Beetje ingewikkeld, tel tot het aantal ledjes + het aantal ledjes dat de trein lang is
+  aantal_leds = ms / delayval; // Het aantal ledjes dat de trein breedt is hoelang de trein overover doet gedeeld door hoelang een ledje duurt
+  if (trein_aangekomen) {          // Als er een trein langsgekomen is doe het volgende:
+    for (int i = 0; i < NUMPIXELS + aantal_leds; i++) { // Beetje ingewikkeld, tel tot het aantal ledjes + het aantal ledjes dat de trein lang is
       int achterste_led = i - aantal_leds;    // Dit doe ik zo om ook het terugschakelen van de ledjes te regelen
-      if(achterste_led >= 0) {                // Als de trein helemaal op de ledstrip is moeten er weer lampjes op de rust kleur worden gezet
+      if (achterste_led >= 0) {               // Als de trein helemaal op de ledstrip is moeten er weer lampjes op de rust kleur worden gezet
         pixels.setPixelColor(achterste_led, WIT);
       }
       if (i < NUMPIXELS) {                    // Zet de lampjes die met de trein meegaan op de kleur aangeven door de snelheid, zie bovenin
         pixels.setPixelColor(i, KLEUR);
-      }
+      }
       pixels.show();
       delay(delayval);                        // Wacht delayval milliseconden
     }
-    trein_langs = false;                      // Trein is langs dus doe dit niet weer opnieuw
-    ms = 0;
     laatste_trein = millis();                 // Reset als het ware de timer die het uitschakelen van de ledjes regelt, zie hieronder
   }
-  if((millis() - laatste_trein) > IDLE_TIME) {  // Als de trein IDLE_TIME milliseconden niet is langsgeweest, zet de lampjes uit
-    for(int i=0;i<NUMPIXELS;i++){
+  if ((millis() - laatste_trein) > IDLE_TIME) { // Als de trein IDLE_TIME milliseconden niet is langsgeweest, zet de lampjes uit
+    for (int i = 0; i < NUMPIXELS; i++) {
       // Zet de lampjes uit
       pixels.setPixelColor(i, UIT);
     }


Fixed example StringStartsWithEndsWith.ino

--- build/shared/examples/08.Strings/StringStartsWithEndsWith/StringStartsWithEndsWith.ino
+++ build/shared/examples/08.Strings/StringStartsWithEndsWith/StringStartsWithEndsWith.ino
@@ -42,12 +42,11 @@
   String sensorReading = "sensor = ";
   sensorReading += analogRead(A0);
   Serial.print (sensorReading);
-  if (sensorReading.endsWith(0)) {
+  if (sensorReading.endsWith("0")) {
     Serial.println(". This reading is divisible by ten");
   }
   else {
     Serial.println(". This reading is not divisible by ten");
-
   }

   // do nothing while true:


Get device id from light script .h

Get device id from light script .h

--- sketches/utils/blinkm_wrt_scr2/blinkm_wrt_scr2.ino
+++ sketches/utils/blinkm_wrt_scr2/blinkm_wrt_scr2.ino
@@ -15,8 +15,8 @@
 // #include "light_script_ss.h"
 #include "light_script_sr.h"

-// I2C device id for MaxM being programmed
-const byte maxmDev = 12;
+// I2C device id for MaxM being programmed; set in light script header
+byte maxmDev = BlinkM_devid;

 // MaxMs on port 2
 PortI2C MaxMbus (2);


Corrected comments of rx and tx for SoftwareSerial example.

--- hardware/arduino/avr/libraries/SoftwareSerial/examples/TwoPortReceive/TwoPortReceive.ino
+++ hardware/arduino/avr/libraries/SoftwareSerial/examples/TwoPortReceive/TwoPortReceive.ino
@@ -13,8 +13,8 @@

  The circuit:
  Two devices which communicate serially are needed.
- * First serial device's TX attached to digital pin 2, RX to pin 3
- * Second serial device's TX attached to digital pin 4, RX to pin 5
+ * First serial device's TX attached to digital pin 10(RX), RX to pin 11(TX)
+ * Second serial device's TX attached to digital pin 8(RX), RX to pin 9(TX)

  Note:
  Not all pins on the Mega and Mega 2560 support change interrupts,
@@ -26,7 +26,7 @@
  8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).

  created 18 Apr. 2011
- modified 25 May 2012
+ modified 19 March 2016
  by Tom Igoe
  based on Mikal Hart's twoPortRXExample

@@ -35,10 +35,10 @@
  */

 #include <SoftwareSerial.h>
-// software serial #1: TX = digital pin 10, RX = digital pin 11
+// software serial #1: RX = digital pin 10, TX = digital pin 11
 SoftwareSerial portOne(10, 11);

-// software serial #2: TX = digital pin 8, RX = digital pin 9
+// software serial #2: RX = digital pin 8, TX = digital pin 9
 // on the Mega, use other pins instead, since 8 and 9 don't work on the Mega
 SoftwareSerial portTwo(8, 9);


Improved roundtrip measurement.

Improved roundtrip measurement.

--- examples/Ethernet/CosaICMPping/CosaICMPping.ino
+++ examples/Ethernet/CosaICMPping/CosaICMPping.ino
@@ -78,7 +78,7 @@
       uint16_t	mtu;
     } frag;			/* path mtu discovery */
   };
-  uint8_t     payload[64];	/* added to simulate echo data */
+  uint32_t    timestamp;
 };

 #define ICMP_ECHOREPLY		0	/* Echo Reply			*/
@@ -153,13 +153,13 @@

   INFO("Build ICMP echo request block", 0);
   icmphdr req;
+  static uint16_t seq = 0;
   req.type = ICMP_ECHO;
   req.code = 0;
   req.checksum = 0;
   req.echo.id = 0xC05A;
-  for (uint8_t i = 0; i < sizeof(req.payload); i++)
-    req.payload[i] = i;
-  req.echo.seq = RTC::millis();
+  req.echo.seq = ++seq;
+  req.timestamp = RTC::micros();
   req.checksum = hton(INET::checksum(&req, sizeof(req)));
   ASSERT(INET::checksum(&req, sizeof(req)) == 0);

@@ -169,7 +169,7 @@
   if (res < 0) goto error;

   INFO("Receive the reply", 0);
-  uint16_t roundtrip;
+  uint32_t roundtrip;
   icmphdr reply;
   uint8_t src[4];
   uint16_t port;
@@ -179,17 +179,18 @@
   }
   if (res != sizeof(reply) + sizeof(IPRAW_HEADER)) goto error;
   res = sock->recv(&reply, sizeof(reply), src, port);
-  roundtrip = RTC::millis();
+  roundtrip = RTC::micros();

   // Sanity check the reply; right size, checksum, id
   if (res != sizeof(reply)) goto error;
   if (reply.type != ICMP_ECHOREPLY) goto error;
+  if (req.echo.id != 0xC05A) goto error;
+  if (req.echo.seq != seq) goto error;
   if (INET::checksum(&reply, sizeof(reply)) != 0) goto error;
-  if (req.echo.id != 0xC05A) goto error;

   // Calculate the time for the ping roundtrip
-  roundtrip -= reply.echo.seq;
-  INFO("roundtrip=%ud ms", roundtrip);
+  roundtrip -= reply.timestamp;
+  INFO("Roundtrip: %ul us", roundtrip);

  error:
   sock->close();


updating test sketch to try and replicate some grbl behavior I saw

--- testing/arduino/gcode_test_sketch/gcode_test_sketch.ino
+++ testing/arduino/gcode_test_sketch/gcode_test_sketch.ino
@@ -10,14 +10,17 @@
     char c = Serial.read();
     if (c == '\n') {
       delay(500);
-      Serial.write("ok\n");
+      Serial.write("ok\n\n");
+      Serial.flush();
+      Serial.write("ok\n\n");
     } else if (c == '$') {
        Serial.write("helpful output\n");
        Serial.write("--------------\n");
        Serial.write("$  - this output\n");
        Serial.write("\\n - prints 'ok'\n");
     }
-
+    Serial.flush();
+
     // TODO: validate gcode commands?
   }
 }


Added reset functionality

Added reset functionality

--- firmware/firmware.ino
+++ firmware/firmware.ino
@@ -24,6 +24,7 @@
  */

+#include <avr/wdt.h>
 #include <Bridge.h>
 #include <YunServer.h>
 #include <YunClient.h>
@@ -46,6 +47,7 @@

 void eventCallback(StatusEvent event);
 void sendEvent(StatusEvent event);
+void hardwareReset();

 /*
  * /arduino/start
@@ -85,9 +87,17 @@
 // will forward there all the HTTP requests for us.
 YunServer server;
 Process eventProcess;
+bool resetFlag;
+
+#define RESET_PIN 12

 void setup() {
-
+  digitalWrite(RESET_PIN, HIGH);
+  delay(40);
+  pinMode(RESET_PIN,OUTPUT);
+  digitalWrite(RESET_PIN, HIGH);
+
+  resetFlag = false;
   Serial.begin(115200);

   Serial.println(F("Initializing..."));
@@ -103,6 +113,7 @@

   sendEvent(EVENT_POWERED_ON);
   Serial.println(F("Starting main loop."));
+
 }

 void loop() {
@@ -118,6 +129,10 @@
     process(client);
     // Close connection and free resources.
     client.stop();
+  }
+
+  if(resetFlag){
+    hardwareReset();
   }

   delay(50); // Poll every 50ms
@@ -227,6 +242,8 @@
 void handle_reset(YunClient& client) {
   HTTP_STATUS(200);
   client.println(F("{}"));
+
+  resetFlag = true;
 }

 void handle_set_time(YunClient& client) {
@@ -270,3 +287,11 @@
   client.println(F("}"));
 }

+void hardwareReset(){
+  Process p;
+  p.begin("reboot");
+  p.run();
+  delay(500);
+  digitalWrite(RESET_PIN, LOW);
+}
+


Correct maximum size of snprintf (use same size as the buffer ;)

--- examples/mqtt_esp8266/mqtt_esp8266.ino
+++ examples/mqtt_esp8266/mqtt_esp8266.ino
@@ -124,7 +124,7 @@
   if (now - lastMsg > 2000) {
     lastMsg = now;
     ++value;
-    snprintf (msg, 75, "hello world #%ld", value);
+    snprintf (msg, 50, "hello world #%ld", value);
     Serial.print("Publish message: ");
     Serial.println(msg);
     client.publish("outTopic", msg);


Added startup delay

Added startup delay

RX5808 needs delay on start for proper config

--- OpenPRO58/OpenPRO58.ino
+++ OpenPRO58/OpenPRO58.ino
@@ -11,105 +11,101 @@

 #include "buttons.h"
 #include "state.h"
-
+#include "state_search.h"
 #include "ui.h"
 #include "Eeprom24C01_02.h"

 static void globalMenuButtonHandler(
-    Button button,
-    Buttons::PressType pressType
+  Button button,
+  Buttons::PressType pressType
 );

 void setup() {
   // init pins
   setupPins();
-
   EepromSettings.init();
   EepromSettings.load();
-  Receiver::setChannel(EepromSettings.startChannel);
+  Receiver::setChannel(EepromSettings.startChannel);
+
   StateMachine::setup();
   Ui::setup();
-
-

   Receiver::setActiveReceiver(Receiver::ReceiverId::A);

+  Buttons::registerChangeFunc(globalMenuButtonHandler);
+  // Switch to initial state.
+  StateMachine::switchState(StateMachine::State::SEARCH);

-
-  Buttons::registerChangeFunc(globalMenuButtonHandler);
- // Switch to initial state.
- StateMachine::switchState(StateMachine::State::SEARCH);
-
 }

 void setupPins() {

-    pinMode(PIN_BUZZER, OUTPUT);
-    pinMode(PIN_BUTTON_UP, INPUT_PULLUP);
-    pinMode(PIN_BUTTON_MODE, INPUT_PULLUP);
-    pinMode(PIN_BUTTON_DOWN, INPUT_PULLUP);
-    pinMode(PIN_BUTTON_EB0, INPUT_PULLUP);
-    pinMode(PIN_BUTTON_EB1, INPUT_PULLUP);
-    pinMode(PIN_BUTTON_EB2, INPUT_PULLUP);
+  pinMode(PIN_BUZZER, OUTPUT);
+  pinMode(PIN_BUTTON_UP, INPUT_PULLUP);
+  pinMode(PIN_BUTTON_MODE, INPUT_PULLUP);
+  pinMode(PIN_BUTTON_DOWN, INPUT_PULLUP);
+  pinMode(PIN_BUTTON_EB0, INPUT_PULLUP);
+  pinMode(PIN_BUTTON_EB1, INPUT_PULLUP);
+  pinMode(PIN_BUTTON_EB2, INPUT_PULLUP);

-    pinMode(PIN_LED_A,OUTPUT);
-    #ifdef USE_DIVERSITY
-        pinMode(PIN_LED_B,OUTPUT);
-    #endif
+  pinMode(PIN_LED_A, OUTPUT);
+#ifdef USE_DIVERSITY
+  pinMode(PIN_LED_B, OUTPUT);
+#endif

-    pinMode(PIN_RSSI_A, INPUT_ANALOG);
-    #ifdef USE_DIVERSITY
-        pinMode(PIN_RSSI_B, INPUT_ANALOG);
-    #endif
+  pinMode(PIN_RSSI_A, INPUT_ANALOG);
+#ifdef USE_DIVERSITY
+  pinMode(PIN_RSSI_B, INPUT_ANALOG);
+#endif

-    pinMode(PIN_SW, OUTPUT);
-    digitalWrite(PIN_SW, HIGH);
+  pinMode(PIN_SW, OUTPUT);
+  digitalWrite(PIN_SW, HIGH);

-    pinMode(PIN_SPI_DATA, OUTPUT);
-    pinMode(PIN_SPI_SLAVE_SELECT_A, OUTPUT);
-    pinMode(PIN_SPI_SLAVE_SELECT_B, OUTPUT);
-
-    pinMode(PIN_SPI_CLOCK, OUTPUT);
-
-    digitalWrite(PIN_SPI_SLAVE_SELECT_A, HIGH);
-    digitalWrite(PIN_SPI_SLAVE_SELECT_B, HIGH);
-    digitalWrite(PIN_SPI_CLOCK, LOW);
-    digitalWrite(PIN_SPI_DATA, LOW);
+  pinMode(PIN_SPI_DATA, OUTPUT);
+  pinMode(PIN_SPI_SLAVE_SELECT_A, OUTPUT);
+  pinMode(PIN_SPI_SLAVE_SELECT_B, OUTPUT);
+
+  pinMode(PIN_SPI_CLOCK, OUTPUT);
+
+  digitalWrite(PIN_SPI_SLAVE_SELECT_A, HIGH);
+  digitalWrite(PIN_SPI_SLAVE_SELECT_B, HIGH);
+  digitalWrite(PIN_SPI_CLOCK, LOW);
+  digitalWrite(PIN_SPI_DATA, LOW);
 }

 void loop() {
   // put your main code here, to run repeatedly:
-    EepromSettings.update();
-    Receiver::update();
-    Buttons::update();
-    StateMachine::update();
-    Ui::update();

+  Receiver::update();
+  Buttons::update();
+  StateMachine::update();
+  Ui::update();
+  EepromSettings.update();

-    if (
-        StateMachine::currentState != StateMachine::State::SCREENSAVER
-        && StateMachine::currentState != StateMachine::State::BANDSCAN
-        && (millis() - Buttons::lastChangeTime) >
-            (SCREENSAVER_TIMEOUT * 1000)
-    ) {
-        StateMachine::switchState(StateMachine::State::SCREENSAVER);
-    }
+  if (
+    StateMachine::currentState != StateMachine::State::SCREENSAVER
+    && StateMachine::currentState != StateMachine::State::BANDSCAN
+    && (millis() - Buttons::lastChangeTime) >
+    (SCREENSAVER_TIMEOUT * 1000)
+  ) {
+    StateMachine::switchState(StateMachine::State::SCREENSAVER);
+  }
 }

 static void globalMenuButtonHandler(
-    Button button,
-    Buttons::PressType pressType
+  Button button,
+  Buttons::PressType pressType
 ) {
-    if (
-        StateMachine::currentState != StateMachine::State::MENU &&
-        button == Button::MODE &&
-        pressType == Buttons::PressType::HOLDING
-    ) {
-        StateMachine::switchState(StateMachine::State::MENU);
-    }
-
+  if (
+    StateMachine::currentState != StateMachine::State::MENU &&
+    button == Button::MODE &&
+    pressType == Buttons::PressType::HOLDING
+  ) {
+    StateMachine::switchState(StateMachine::State::MENU);
+  }
+
 }