Use strtok_r like a good human

Use strtok_r like a good human

--- battlestation/arduino/arduino.ino
+++ battlestation/arduino/arduino.ino
@@ -34,7 +34,7 @@
   Serial.begin(115200);

   for (byte i = 0; i < 4; i++) {
-    strips[i] = &Adafruit_NeoPixel(strip_leds[i], strip_pins[i], NEO_GRB + NEO_KHZ800);
+    strips[i] = new Adafruit_NeoPixel(strip_leds[i], strip_pins[i], NEO_GRB + NEO_KHZ800);
     strips[i]->begin();
     strips[i]->show();
   }
@@ -74,33 +74,28 @@
     // Done executing or buffer is full before newline
     memset(cmd, 0, sizeof(cmd));
     cmd_idx = 0;
-    Serial.print("\n> ");
-  }
-}
-
-static const char cmd_teams[] = "teams";
-static const char cmd_team[] = "team t rrr ggg bbb";
-static const char cmd_strip[] = "strip s t 11 t 22 t 33";
-static const char cmd_help[] = "help";
+    Serial.print("> ");
+  }
+}

 void exec_cmd() {
-  if (strncmp(cmd, "teams", 5) == 0) {
-    exec_teams();
-  } else if (strncmp(cmd, "team", 4) == 0) {
-    exec_team();
-  } else if (strncmp(cmd, "strip", 5) == 0) {
-    exec_strip();
-  } else if (strncmp(cmd, "help", 4) == 0) {
-    Serial.println(cmd_teams);
-    Serial.println(cmd_team);
-    Serial.println(cmd_help);
-    return;
+  char * tok = NULL;
+  const char * cmd_name = strtok_r(cmd, " ", &tok);
+  if (strcmp(cmd_name, "teams") == 0) {
+    exec_teams(tok);
+  } else if (strcmp(cmd, "team") == 0) {
+    exec_team(tok);
+  } else if (strcmp(cmd, "strip") == 0) {
+    exec_strip(tok);
+  } else if (strcmp(cmd, "help") == 0) {
+    Serial.println("teams");
+    Serial.println("team <team_num> <r> <g> <b>");
+    Serial.println("strip <strip_num> <team_num> <leds> <team_num> <leds> <team_num> <leds>");
+    Serial.println("help");
   } else {
     Serial.print("unknown command: ");
     Serial.println(cmd);
-    return;
   }
-  Serial.println("ok");
 }

 void usage(const char * usage) {
@@ -118,7 +113,7 @@
   return atoi(s);
 }

-void exec_teams(){
+void exec_teams(char * tok){
   for (byte i = 0; i < 3; i++) {
     Serial.print(i);
     Serial.print(": ");
@@ -131,43 +126,65 @@
   }
 }

-void exec_team() {
-  if (strlen(cmd) < strlen(cmd_team)) {
-    usage(cmd_team);
-    return;
-  }
-  int t = read_int(&cmd[5], 1);
-  if (t > 2) {
-    Serial.println("Invalid team number");
-    return;
-  }
-  int r = read_int(&cmd[7], 3);
-  int g = read_int(&cmd[11], 3);
-  int b = read_int(&cmd[15], 3);
-  team_colors[t] = Adafruit_NeoPixel::Color(r, g, b);
-}
-
-void exec_strip() {
-  if (strlen(cmd) < strlen(cmd_strip)) {
-    usage(cmd_strip);
-    return;
-  }
-  int strip = read_int(&cmd[6], 1);
-  if (strip > 3) {
-    Serial.println("Invalid strip number");
-    return;
-  }
-
-  byte led = 0;
-
-  // Read the three "t 11" parts
-  for (byte i = 8; i < 19; i += 5) {
-    int team = read_int(&cmd[i], 1);
-    if (team > 3) {
-      Serial.println("Invalid team number");
+void exec_team(char * tok) {
+  // Read team number
+  char * arg = strtok_r(NULL, " ", &tok);
+  if (arg == NULL) {
+    Serial.println("team number is required");
+    return;
+  }
+  int team = atoi(arg);
+  if (team > 2) {
+    Serial.println("team number is one of 0,1,2");
+    return;
+  }
+  // Read colors
+  arg = strtok_r(NULL, " ", &tok);
+  int r = atoi(arg);
+  arg = strtok_r(NULL, " ", &tok);
+  int g = atoi(arg);
+  arg = strtok_r(NULL, " ", &tok);
+  int b = atoi(arg);
+  team_colors[team] = Adafruit_NeoPixel::Color(r, g, b);
+}
+
+void exec_strip(char * tok) {
+  // Read strip number
+  char * arg = strtok_r(NULL, " ", &tok);
+  if (arg == NULL) {
+    Serial.println("strip number is required");
+    return;
+  }
+  int strip = atoi(arg);
+  if (strip > 2) {
+    Serial.println("strip number is one of 0,1,2");
+    return;
+  }
+
+  byte led = 0;
+  // Read the three groups of "teamNumber ledCount"
+  for (byte i = 0; i < 3; i++) {
+    // Read the team
+    arg = strtok_r(NULL, " ", &tok);
+    if (arg == NULL) {
+      Serial.println("team number is required");
       return;
     }
-    int team_leds = read_int(&cmd[i + 2], 2);
+    int team = atoi(arg);
+    if (team > 2) {
+      Serial.println("team number is one of 0,1,2");
+      return;
+    }
+
+    // Read the LED count
+    arg = strtok_r(NULL, " ", &tok);
+    if (arg == NULL) {
+      Serial.println("led count is required");
+      return;
+    }
+    int team_leds = atoi(arg);
+
+    // Enable the LEDs
     for (byte l = 0; l < team_leds; l++) {
       strips[strip]->setPixelColor(led + l, team_colors[team]);
     }
@@ -180,3 +197,5 @@
   }
   strips[strip]->show();
 }
+
+


addd printing pixel order

addd printing pixel order

--- arduino/libraries/ledtable/examples/hpi_logo/hpi_logo.ino
+++ arduino/libraries/ledtable/examples/hpi_logo/hpi_logo.ino
@@ -5,26 +5,28 @@
 #include <Adafruit_NeoPixel.h>
 #include <ledtable.h>

-LEDTable ledtable = LEDTable(6, 20, 15, PIXELORDER<flip_xy, rotate_180, snake>);
+LEDTable ledtable = LEDTable(6, 20, 15, PIXELORDER<rotate_180, snake>);

 //    1   1   1 1   1
 //    1 1 1   1 1   1
 //    1   1   1     1
-const uint32_t HPIbits[3] = {0b10101101,
-                             0b11101101,
-                             0b10101001};
-Stamp HPI = Stamp(HPIbits, 8, 3);
+Stamp HPI = Stamp(0b10101101,
+                  0b11101101,
+                  0b10101001);

 void setup() {
+  Serial.begin(9600);
   ledtable.begin();
-  ledtable.brightness(20);
+  ledtable.brightness(50);
   ledtable.fill(color_black);
   ledtable.fill(0, 12, 10, 2, RGB(177, 7, 10));
   ledtable.fill(2, 10, 12, 0, RGB(247, 169, 0));
   ledtable.fill(2, 10, 10, 2, RGB(222, 98, 7));
   HPI.stamp(&ledtable, 2, 3);
   ledtable.show();
+  ledtable.printToSerial();
+  ledtable.printPixelOrderToSerial();
 }

 void loop() {
-}
+}


delete isPortWriteable

delete isPortWriteable

--- app/firmware/entry/entry.ino
+++ app/firmware/entry/entry.ino
@@ -63,8 +63,7 @@
     sendAnalogValue(pinNumber);
   }
   for (pinNumber = 0; pinNumber < 14; pinNumber++) {
-    if (!isPortWritable(pinNumber))
-      sendDigitalValue(pinNumber);
+    sendDigitalValue(pinNumber);
   }
 }


change "server" to "data sharing" in line with discussion about associating sensors with users

--- ardesp/waterelf/waterelf.ino
+++ ardesp/waterelf/waterelf.ino
@@ -49,7 +49,7 @@
   "
Control
\n"
   "

\n"
   "
Join a wifi network
\n"
-  "
Configure server location
\n"
+  "
Configure data sharing
\n"
   "
\n"
     "<form method='POST' action='actuate'>\n"
     "External power: "
@@ -387,7 +387,7 @@
   String f = pageTop;
   f += ": Server Config";
   f += pageTop2;
-  f += "
Configure a server

\n";
+  f += "
Configure data sharing

\n";

   f += "<form method='POST' action='svrchz'> ";
   f += "
Local server IP address: ";
@@ -409,7 +409,7 @@
 void handle_svrchz() {
   Serial.println("serving page at /svrchz");
   String toSend = pageTop;
-  toSend += ": server configured";
+  toSend += ": data sharing configured";
   toSend += pageTop2;

   boolean cloudShare = false;


added data collection for the analog sensor

--- ardesp/waterelf/waterelf.ino
+++ ardesp/waterelf/waterelf.ino
@@ -101,8 +101,7 @@
   long waterLevel1; // TODO should be an array
   long waterLevel2;
   long waterLevel3;
-  // TODO add last reboot
-  // TODO add free memory?
+  float analog;
 } monitor_t;
 monitor_t monitorData[MONITOR_POINTS];
 int monitorCursor = 0;
@@ -392,6 +391,7 @@
       dbg(valveDBG, "; wL2: "); dbg(valveDBG, now->waterLevel2);
       dbg(valveDBG, "; wL3: "); dln(valveDBG, now->waterLevel3);
     }
+    if(GOT_ANALOG_SENSOR) { getAnalog(&now->analog);    yield(); }

     flowController.step(now); yield();  // set valves on and off etc.
     if(SEND_DATA) {                     // push data to the cloud
@@ -935,6 +935,11 @@
     buf->concat("^ ~waterLevel3~+ "); buf->concat(m->waterLevel3);
     if(! JSON) buf->concat("\tcm");
   }
+  if(GOT_ANALOG_SENSOR){
+    buf->concat("^ ~analog~+ ");
+    buf->concat(m->analog);
+    if(! JSON) buf->concat("\tanalog");
+  }
   if(JSON) {
     buf->concat(" }");
     buf->replace('~', '"');
@@ -1017,6 +1022,17 @@
   dln(monitorDBG, " cm, ");
   return;
 }
+void getAnalog(float* a) {
+  if(! GOT_ANALOG_SENSOR) {
+    (*a) = 0.0;
+  } else if(analogSensor == "analog_mains") {
+    (*a) = 1.0;
+  } else if(analogSensor == "analog_pressure") {
+    (*a) = -1.0;
+  }
+
+  return;
+}

 /////////////////////////////////////////////////////////////////////////////
 // config utils /////////////////////////////////////////////////////////////


create dfrdb

create dfrdb


Changed thrust smoothing code to instantly drop to target thrust when that is a reduction in power.

--- arduino/OpenROV/OpenROV.ino
+++ arduino/OpenROV/OpenROV.ino
@@ -59,6 +59,23 @@
     readings[thisReading] = 0;
 }

+int smoothAdjustedServoPosition(int target, int current){
+  // if the MIDPOINT is betwen the change requested in velocity we want to go to MIDPOINT first, and right away.
+  if (((current < MIDPOINT) && (MIDPOINT < target)) || ((target < MIDPOINT) && (MIDPOINT < current))){
+    return MIDPOINT;
+  }
+  // if the change is moving us closer to MIDPOINT it is a reduction of power and we can move all the way to the target
+  // in one command
+  if (abs(MIDPOINT-target) < abs(MIDPOINT-current)){
+    return target;
+  }
+  // else, we need to smooth out amp spikes by making a series of incrimental changes in the motors, so only move part of
+  // the way to the target this time.
+  double x = target - current;
+  int sign = (x>0) - (x<0);
+  return(current + sign * (min(abs(target - current), smoothingIncriment)));
+}
+
 void loop(){

   if (Serial.available()) {
@@ -98,14 +115,10 @@
   //to their new positions in increments.  The incriment should eventually be adjustable from the cockpit so that
   //the pilot could have more aggressive response profiles for the ROV.
   if (controltime.elapsed (50)) {
-    if (p<new_p) new_p -= min(smoothingIncriment,new_p-p);
-    if (p>new_p) new_p += min(smoothingIncriment,p-new_p);
-    if (v<new_v) new_v -= min(smoothingIncriment,new_v-v);
-    if (v>new_v) new_v += min(smoothingIncriment,v-new_v);
-    if (s<new_s) new_s -= min(smoothingIncriment,new_s-s);
-    if (s>new_s) new_s += min(smoothingIncriment,s-new_s);
-    if (tilt_val<new_tilt) new_tilt -= min(smoothingIncriment,new_tilt-tilt_val);
-    if (tilt_val>new_tilt) new_tilt += min(smoothingIncriment,tilt_val-new_tilt);
+    new_p = smoothAdjustedServoPosition(p,new_p);
+    new_v = smoothAdjustedServoPosition(v,new_v);
+    new_s = smoothAdjustedServoPosition(s,new_s);
+    new_tilt = smoothAdjustedServoPosition(tilt_val,new_tilt);
     tilt.writeMicroseconds(new_tilt);
     motors.go(new_p, new_v, new_s);
   }


Added hack to allow direct arduino firmware upload from the src folder instead of having to upload via browser by simply selecting upload firmware in browser without selecting a file. Increased default video to 1920x1080.

--- arduino/OpenROV/OpenROV.ino
+++ arduino/OpenROV/OpenROV.ino
@@ -40,7 +40,7 @@

 void setup(){

-  delay(5000); //wait 5 seconds before starting to give time for programming pin sets
+  //delay(10000); //wait 5 seconds before starting to give time for programming pin sets

   Serial.begin(115200);


dont power down gps

dont power down gps

--- arduino/car-mon/car-mon.ino
+++ arduino/car-mon/car-mon.ino
@@ -100,7 +100,7 @@
   boolean postedLocation = false;

   // each 'attempt' should take around a second...
-  const int maxFixAttempts = 60 * 3;
+  const int maxFixAttempts = 60 * 5;
   int fixAttemptCount = 0;

   gpsSerial.enableRx(true);
@@ -169,10 +169,10 @@
   if (stillCycleCount >= numStillCyclesForDeepSleep) {
     Serial.println("we've been stationary for a while");

-    Serial.println("power down GPS");
+    Serial.println("power down GPS, (skipping)");

     // stop the GPS
-    digitalWrite(gpsPowerPin, LOW);
+    //digitalWrite(gpsPowerPin, LOW);

     // stop the sim900
     powerDownSim();


Add warning message to OutputToneWithSteppedAmplitude example

--- examples/02-Utility/OutputToneWithSteppedAmplitude/OutputToneWithSteppedAmplitude.ino
+++ examples/02-Utility/OutputToneWithSteppedAmplitude/OutputToneWithSteppedAmplitude.ino
@@ -5,6 +5,7 @@

   Plays a single tone followed by silence.  Repeats the tone+silence at increasing amplitude.
   The last tone should definitely distort.  The 2nd-to-last tone should be on the edge of distorting.
+  WARNING: DO NOT LISTEN TO THIS WITH HEADPHONES ON

   MIT License, Use at your own risk.
 */


Document code

Document code

--- teensy_octo.ino
+++ teensy_octo.ino
@@ -1,8 +1,11 @@
 /**
  * Teensy Octo v1.0
  *
- * Custom-built USB peripheral with eight buttons, two PWM RGB LEDs and a Piezo buzzer.
- * Based on the Teensy 2 microcontroller - http://www.pjrc.com/teensy
+ * This is the C / Arduino firmware for the Teensy Octo,
+ * a custom-built USB peripheral with eight buttons, two
+ * PWM RGB LEDs and a Piezo buzzer.
+ *
+ * The microcontroller in use is Teensy 2.0 - http://www.pjrc.com/teensy
  *
  * Created as a birthday present to Waher (http://waher.net/about-waher-net)
  *
@@ -13,27 +16,28 @@
  * http://www.pjrc.com/teensy/td_libs_Bounce.html - About button bouncing
  * http://www.pjrc.com/teensy/pinout.html - Teensy pinout diagram
  * http://www.pjrc.com/teensy/td_usage.html - Reprogramming
+ * https://github.com/anroots/teensy-octo - Repository for the firmware / wrapper
  **/

 #include <Bounce.h>

 #define DEBOUNCE 10  // Number of ms to debounce
 #define NUMBER_OF_BUTTONS 8
-#define NUMBER_OF_LEDS 6 // 2 RGB LEDs
+#define NUMBER_OF_LEDS 6 // 2 RGB LEDs, 3 * 2

 // Define digital pins for the buttons
-const byte BUTTON_PINS[] = {
-  0, 1, 2, 3, 7, 8, 20, 21};
+const byte BUTTON_PINS[] = { 0, 1, 2, 3, 7, 8, 20, 21 };

 // Define PWM pins for the RGB LED
-// LED0-R, LED0-G, LED0-B; LED1-R, LED1-G, LED1-B
-const byte LED_PINS[] = {
-  9, 5, 10, 14, 12, 15};
+// Order: LED0-R, LED0-G, LED0-B; LED1-R, LED1-G, LED1-B
+const byte LED_PINS[] = { 9, 5, 10, 14, 12, 15 };

 // The Piezo buzzer sits in this PWM pin
 const byte BUZZER_PIN = 4;

 // Initialize button objects
+// We access the buttons through these Bounce objects
+// instead of directly reading them (see: debouncing)
 Bounce buttons[NUMBER_OF_BUTTONS] = {
   Bounce( BUTTON_PINS[0], DEBOUNCE),
   Bounce( BUTTON_PINS[1], DEBOUNCE),
@@ -49,14 +53,18 @@
    * Setup function - run once on power-on
    **/
   void setup() {
+
+    // The baud rate is ignored and communication always occurs at full USB speed.
+    // http://www.pjrc.com/teensy/td_serial.html
     Serial.begin(9600);

-    // Initialize pushbutton pins as inputs with the internal pullup resistor enabled
+    // Initialize pushbutton pins as inputs with the internal pullup resistor enabled.
+    // http://www.pjrc.com/teensy/tutorial3.html
     for (byte i = 0; i < NUMBER_OF_BUTTONS; i++) {
       pinMode(BUTTON_PINS[i], INPUT_PULLUP);
     }

-    // Initialize LED pins
+    // Initialize LED pins as output
     for (byte i = 0; i < NUMBER_OF_LEDS; i++) {
       pinMode(LED_PINS[i], OUTPUT);
       analogWrite(LED_PINS[i], 255);
@@ -67,6 +75,7 @@
     Serial.print(millis());
     Serial.println("ms - which is amazingly fast.");

+    Serial.println();
     printHelp();
     Serial.println("");
     Serial.println("Waiting for button presses or serial commands.");
@@ -82,7 +91,7 @@
   // Detect and handle button presses
   processButtonPress();

-  // Receive and proccess commands sent from the PC over serial
+  // Receive and process commands sent from the PC over serial
   processSerialCommand();

   delay(5);
@@ -158,19 +167,18 @@
 {
   char separator = ' ';
   int found = 0;
-  int strIndex[] = {
-    0, -1  };
-  int maxIndex = data.length()-1;
-
-  for(int i=0; i<=maxIndex && found<=index; i++){
-    if(data.charAt(i)==separator || i==maxIndex){
+  int strIndex[] = { 0, -1  };
+  int maxIndex = data.length() - 1;
+
+  for(int i = 0; i <= maxIndex && found <= index; i++){
+    if(data.charAt(i) == separator || i == maxIndex){
       found++;
       strIndex[0] = strIndex[1]+1;
-      strIndex[1] = (i == maxIndex) ? i+1 : i;
+      strIndex[1] = (i == maxIndex) ? i + 1 : i;
     }
   }

-  return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
+  return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
 }

 /**
@@ -213,7 +221,7 @@
     buzz(param1, param2);
     endWork();
   }
-  else if (command == "nobuzz") {
+  else if (command == "nobuzz") { // Stop the buzzer
     startWork();
     noBuzz();
     endWork();
@@ -331,4 +339,3 @@
     delay(duration*1.2);
   }
 }
-


Calibration light, red button, debug state

--- crypt-gears/gear_arduino/gear_arduino.ino
+++ crypt-gears/gear_arduino/gear_arduino.ino
@@ -2,6 +2,8 @@
 int output_lights[7] = {38, 39, 40, 41, 42, 43, 44};

 int red_button = 30;
+
+int calibration_light = 31;

 int pot = A0;

@@ -28,7 +30,7 @@

 // photoresistor_history[i][j] is the state of the photoresistor i when we were
 // at selector position j.  Only meaningful in state 1, and then only for
-// 0 <= j < the current selector gear position.  When we transition to state 2
+// 0 <= j <= the current selector gear position.  When we transition to state 2
 // we use this to populate gear_types and gear_orientations.
 // NOTE: The photoresistor is positioned down.
 boolean photoresistor_history[3][7];
@@ -48,6 +50,11 @@
 // Note they get filled in in reverse order (see note by selector pos).
 boolean correct_positions[7];

+// -1 if not blinking, 0..19 when blinking (0..9 = on, 10..19 = off)
+boolean calibration_state = -1;
+
+// 0..9 or -1 to disable debug; only show state on 0
+int debug_state = 0;

 // CONSTANTS DEFINING THE PUZZLE

@@ -87,9 +94,16 @@
 void loop()
 {
   delay(50);
+  if (debug_state == 0)
+  {
+    printState();
+  }
+  if (debug_state >= 0)
+  {
+    debug_state = (debug_state + 1) % 10;
+  }
+
   int selector_pos = getSelectorGearPosition();
-  Serial.println(selector_pos);
-  return;
   if (selector_pos == -2)
   {
     sendCastleErrorMessage();
@@ -106,9 +120,10 @@
   // position we immediately do what we would have done there.
   if (state == 0)
   {
+    setCalibration(false);
     // TODO(benkraft): Should we only be starting here when the red button is
     // pressed?
-    if (selector_pos == 0)
+    if (selector_pos == 0 && buttonPressed())
     {
       // We have started calibrating!
       state = 1;
@@ -117,6 +132,7 @@

   if (state == 1)
   {
+    stepCalibration();
     if (selector_pos < last_selector_pos
         || selector_pos > last_selector_pos + 1)
     {
@@ -185,6 +201,7 @@

   if (state == 2)
   {
+    setCalibration(true);
     if (selector_pos > last_selector_pos
         || selector_pos < last_selector_pos - 1)
     {
@@ -224,10 +241,14 @@
     }
   }

+  if (state == 3 && buttonPressed())
+  {
+    state = 0;
+  }
+
   // TODO(benkraft): How do we exit state 3?  When the button is pressed?

   last_selector_pos = selector_pos;
-  delay(50);
 }

@@ -484,6 +505,33 @@
   }

   // TODO(bhomberg): close all solenoids (??)
+  digitalWrite(calibration_light, LOW);
+}
+
+void setCalibration(boolean on)
+{
+  calibration_state = -1;
+  if (on)
+  {
+    digitalWrite(calibration_light, LOW);
+  }
+  else
+  {
+    digitalWrite(calibration_light, HIGH);
+  }
+}
+
+void stepCalibration()
+{
+  calibration_state = (calibration_state + 1) % 20;
+  if (calibration_state < 10)
+  {
+    digitalWrite(calibration_light, LOW);
+  }
+  else
+  {
+    digitalWrite(calibration_light, HIGH);
+  }
 }

 // Tell the user they have won!
@@ -507,13 +555,52 @@
 {
   // TODO(benkraft): internal state too?
   // print out position of the pot
-  Serial.print(getSelectorGearPosition());
+  Serial.print("pot: ");
+  Serial.println(getSelectorGearPosition());
   // print out the three photoresistors.
+  Serial.print("photoresistors:");
   for (int i=0; i<3; i++)
   {
     Serial.print(" ");
     Serial.print(getPhotoresistor(i));
   }
+  Serial.println("");
+
+  Serial.print("state: ");
+  Serial.println(state);
+  Serial.print("last selector pos: ");
+  Serial.println(last_selector_pos);
+
+  if (state == 1)
+  {
+    for (int i=0; i<3; i++)
+    {
+      Serial.print("history ");
+      Serial.print(i);
+      Serial.print(":");
+      for (int j=0; j<=last_selector_pos; j++)
+      {
+        Serial.print(" ");
+        Serial.print(photoresistor_history[i][j]);
+      }
+      Serial.println("");
+    }
+  }
+
+  if (state == 2)
+  {
+    for (int i=0; i<3; i++)
+    {
+      Serial.print("gear ");
+      Serial.print(i);
+      Serial.print("type: ");
+      Serial.print(gear_types[i]);
+      Serial.print(", orientation: ");
+      Serial.print(gear_orientations[i]);
+      Serial.println("");
+    }
+  }
+
   Serial.println("");
 }

@@ -538,8 +625,6 @@
 int getSelectorGearPosition()
 {
   int val = analogRead(pot);
-  Serial.print(val);
-  Serial.print(" ");

   if (val > pot_locs[0])
   {
@@ -560,3 +645,9 @@

   return -2;
 }
+
+// True if the button is pressed.
+boolean buttonPressed()
+{
+  return digitalRead(red_button);
+}


added note on tmp112

added note on tmp112

--- Arduino/hardware/REV2/REV2ElectricHeating/REV2ElectricHeating.ino
+++ Arduino/hardware/REV2/REV2ElectricHeating/REV2ElectricHeating.ino
@@ -195,14 +195,10 @@
 typedef OTV0P2BASE::SensorAmbientLight AmbientLight;
 AmbientLight AmbLight;

-// Singleton implementation/instance.   FIXME what is correct temp sensor type for REV2?
-typedef OTV0P2BASE::HumiditySensorSHT21 RelHumidity_t;
-// Singleton implementation/instance.
-OTV0P2BASE::HumiditySensorSHT21 RelHumidity;
-
+// FIXME Dummy humidity sensor

 // Ambient/room temperature sensor, usually on main board.
-OTV0P2BASE::RoomTemperatureC16_SHT21 TemperatureC16; // SHT21 impl.
+OTV0P2BASE::RoomTemperatureC16_SHT21 TemperatureC16; // SHT21 impl. // FIXME this should be TMP112

 ////// ACTUATORS


Use actual Morse code for error blinking

--- client_arduino/arduino_client.ino
+++ client_arduino/arduino_client.ino
@@ -56,11 +56,24 @@
 }

 /**
- * Flashes out an error in a kind of "decimal morse code", for example:
- * 502 = ..... _ ..
+ * Flashes out a decimal number in Morse code:
+ * 0 -----
+ * 1 .----
+ * 2 ..---
+ * 3 ...--
+ * 4 ....-
+ * 5 .....
+ * 6 -....
+ * 7 --...
+ * 8 ---..
+ * 9 ----.
  */
 void flashNumber(uint16 number) {
-  byte digits[5]; // Maximum 65535.
+  unsigned int const DOT_DURATION = 100;
+  unsigned int const DASH_DURATION = 3 * DOT_DURATION;
+  unsigned int const INTERVAL_DURATION = DOT_DURATION;
+  unsigned int const CHARACTER_SEPARATOR_DURATION = 3 * DOT_DURATION;
+  byte digits[5]; // Maximum is 65535, which is 5 digits long.
   byte numDigits = 0;
   while (number) {
     digits[numDigits] = number % 10;
@@ -74,18 +87,19 @@
   while (numDigits) {
     numDigits--;
     setLed(false);
-    delay(500);
+    delay(CHARACTER_SEPARATOR_DURATION);

     byte digit = digits[numDigits];
-    if (digit) {
-      while (digit) {
-        digit--;
-        blinkLed(150);
-        delay(150);
-      }
-    } else {
-      blinkLed(500);
-      delay(150);
+    for (byte i = 0; i < 5; i++) {
+      // In case of underflow, this wraps and becomes greater than 5.
+      if (static_cast<byte>(digit - 1 - i) < 5) {
+        blinkLed(DOT_DURATION);
+      } else {
+        blinkLed(DASH_DURATION);
+      }
+      if (i < 4) {
+        delay(INTERVAL_DURATION);
+      }
     }
   }
 }


Delete K_Nearest_Neighbors_Boxes.ino

Delete K_Nearest_Neighbors_Boxes.ino

--- K_Nearest_Neighbors_Boxes.ino
+++ K_Nearest_Neighbors_Boxes.ino
@@ -1,139 +0,0 @@
-// Distance Sensor
-// Feature is height
-// Pre-known object of different heights
-// Pattern is see what the object is closest to.
-#include <Arduino.h>
-#include <NewPing.h>
-
-#include "Object.h"
-
-#define TRIGGER_PIN 12
-#define ECHO_PIN 11
-
-const int DISTANCE_SENSOR_MAX_DISTANCE = 50;
-
-// K Nearest Neighbors
-const int K = 3;
-
-const size_t NUM_OF_KNOWN_OBJECTS = 9;
-const size_t NUM_OF_OBJECT_TYPES = 3;
-String Known_Object_Types[3] = {"Small", "Medium", "Large"};
-
-NewPing sonar(TRIGGER_PIN, ECHO_PIN, DISTANCE_SENSOR_MAX_DISTANCE);
-
-// Takes the features from the current object and converts them to strings and integers
-// **
-void ObjectFeatureExtraction(Object &currObject) {
-  // Pass in an object (Pass by pointer)
-  int currDistance;
-
-  // Get height feature
-  currDistance = sonar.ping_cm();
-
-  currObject.height = DISTANCE_SENSOR_MAX_DISTANCE - currDistance;
-
-}
-
-// Finds the patterns from the current object and compares them to patterns from the given objects
-// **
-String PatternRecognition(Object currObject, Object knownObjects[]) {
-  Object kNearestObjects[K];
-
-  Serial.print("Object height: ");
-  Serial.println(currObject.height);
-
-
-  // First K known objects are the closest K, obviously, so just fill array
-  for(int i = 0; i < K; ++i) {
-    kNearestObjects[i].height = abs(knownObjects[i].height - currObject.height);
-    kNearestObjects[i].type = knownObjects[i].type;
-  }
-
-  // Now, determine if each remaining object is among the K closest, and if so insert into array (thus dropping one obj)
-  for(int i = K; i < NUM_OF_KNOWN_OBJECTS; ++i) { // For each remaining known object
-
-    // Find the current max difference in the K nearest objects
-    int max_diff = 0;
-    int max_index = 0;
-    for(int j = 0; j < K; ++j) {
-      if(kNearestObjects[j].height > max_diff) {
-        max_diff = kNearestObjects[j].height;
-        max_index = j;
-      }
-    }
-
-    // If the current known object's difference < the max difference in the current K nearest neighbors
-    if(abs(knownObjects[i].height - currObject.height) < max_diff) {
-      // Replace the existing neighbor having max_diff, by the current known object, in the K nearest neighbors array
-      kNearestObjects[max_index].type = knownObjects[i].type;
-      kNearestObjects[max_index].height = abs(knownObjects[i].height - currObject.height);
-    }
-  }
-
-  // For testing purposes
-  for(int i = 0; i < K; ++i) {
-    Serial.println(kNearestObjects[i].type);
-    Serial.println(kNearestObjects[i].height);
-  }
-
-  int count = 0;
-  int max_count = 0;
-  String max_type;
-  // Find out which object type occurs the most
-  for(int i = 0; i < NUM_OF_OBJECT_TYPES; ++i) {
-    count = 0;
-    for(int j = 0; j < K; ++j) {
-      if(kNearestObjects[j].type == Known_Object_Types[i]) {
-        count++;
-      }
-    }
-    if(count > max_count) {
-      max_count = count;
-      max_type = Known_Object_Types[i];
-    }
-  }
-
-  return max_type;
-}
-
-// Prints the type of object that is being passed through the project
-// **
-void Actuation(String object) {
-  if(object != "") {
-    Serial.print("\t");
-    Serial.println(object);
-  }
-}
-
-void setup() {
-  Serial.begin(9600);
-}
-
-void loop() {
-  // Turns both LEDs off before each reading
-
-  // Should put feature extraction and pattern recognition in one multi-second for loop to
-    // give the box time to go through the sensors.
-
-  Object knownObjects[NUM_OF_KNOWN_OBJECTS] = {{"Small", 11},
-                        {"Small", 15},
-                        {"Small", 12},
-                        {"Medium", 27},
-                        {"Medium", 29},
-                        {"Medium", 30},
-                        {"Large", 40},
-                        {"Large", 42},
-                        {"Large", 42}};
-
-  Object currObject;
-  String closestObject;
-
-  ObjectFeatureExtraction(currObject);
-
-  closestObject = PatternRecognition(currObject, knownObjects);
-
-  Actuation(closestObject);
-
-  delay(1000);
-}
-


updated Wed 10/04/2017 14:35:15.93

updated Wed 10/04/2017 14:35:15.93

--- glowing-pumpkin-feather-timer/glowing-pumpkin-feather-timer.ino
+++ glowing-pumpkin-feather-timer/glowing-pumpkin-feather-timer.ino
@@ -41,13 +41,13 @@
 //time during the summer if you live in an area that observes daylight time.
 const int timeZone = EDT;

-//Wi-Fi settings are in an external file: **wifi-config.h**
+//Wi-Fi settings are in an external file: wifi-config.h
 //Set your Wi-Fi SSID and password there.

 //Populate the following variable with the number of rows in the slots array
 //I'm doing this way because Arduino doesn't have an easy way to determine
 //the size of an array at runtime, especially multidimensional arrays.
-#define NUMSLOTS 2
+#define NUMSLOTS 8
 //Use the Slots array to define when the relay(s) go on and off
 //Slots array values: {onTime, offTime };
 // Examples:
@@ -58,8 +58,14 @@
 // Turn the relay on at 5:30 AM, turn the relay off at 7:00 AM.
 // {530, 700}
 int slots[NUMSLOTS][2] = {
-  {600, 800},
-  {1900, 2100}
+  {600, 700},
+  {800, 900},
+  {1000, 1100},
+  {1200, 1300},
+  {1400, 1500},
+  {1600, 1700},
+  {1800, 1900},
+  {2000, 2100}
   //BE SURE TO UPDATE THE NUMSLOTS CONSTANT IF YOU ADD/REMOVE
   //ROWS FROM THIS ARRAY
 };
@@ -216,6 +222,7 @@
   //Start trying to connect to the local Wi-Fi network
   WiFi.begin(wifi_ssid, wifi_pass);
   //Loop until connected
+  // todo: add a loop counter, and drop out after 10 tries or so
   while (WiFi.status() != WL_CONNECTED) {
     delay(500);
     Serial.print(".");
@@ -237,7 +244,7 @@
   //on or off.
   wasOn = false;

-  Serial.println("Exiting setup()");
+  Serial.println("Exiting setup");
 }

 void loop() {
@@ -252,7 +259,9 @@
     } else {
       //otherwise, pick a random color and set each pixel individually to that color
       //with a random time delay between setting each pixel
-      stepLights(colors[(int)random(1, numColors + 1)], (int)random(50, 500));
+      //stepLights(colors[(int)random(1, numColors + 1)], (int)random(50, 500));
+      //For a smoother color transition, use the following:
+      swapColor(colors[(int)random(1, numColors + 1)], (int)random(25, 200));
     }
   } else {
     //Use wasOn to make sure we only turn the lights off once (after they've
@@ -307,6 +316,18 @@
     //wait for the specified period of time (in milliseconds)
     delay(delayVal);
   }  //for i
+}
+
+//Set a single color one column at a time across the array.
+//Used to 'fade' into a new color
+void swapColor(uint32_t c, int delayVal) {
+  for (uint16_t i = 0; i < pixels.numPixels(); i++) {
+    pixels.setPixelColor(i, c);
+    //Display the new row color
+    pixels.show();
+    //wait for the specified period of time (in milliseconds)
+    delay(delayVal);
+  }
 }

 int getTime24() {


make LED blink when face is detected

make LED blink when face is detected

Change-Id: I9611d82df1b856a72bf1133b401c54ac8dba0a7f
GitOrigin-RevId: a15551939514ed531d16eb3eb0f8a99a21e33c4b

--- arduino/libraries/TensorFlow/examples/DetectFaces/DetectFaces.ino
+++ arduino/libraries/TensorFlow/examples/DetectFaces/DetectFaces.ino
@@ -50,6 +50,8 @@
   pinMode(PIN_LED_STATUS, OUTPUT);
   digitalWrite(PIN_LED_STATUS, HIGH);
   Serial.println("Arduino Face Detection!");
+
+  pinMode(PIN_LED_USER, OUTPUT);

   SD.begin();

@@ -112,7 +114,6 @@
 }
 void loop() {
   input_tensor = interpreter->input_tensor(0);
-  delay(1000);
   if (Camera.grab(tflite::GetTensorData<uint8_t>(input_tensor)) !=
       CameraStatus::SUCCESS) {
     Serial.println("cannot invoke because camera failed to grab frame");
@@ -130,18 +131,24 @@

   auto results =
       coralmicro::tensorflow::GetDetectionResults(interpreter.get(), 0.6, 3);
-  Serial.print("Face count: ");
-  Serial.println(results.size());
-  for (auto result : results) {
-    Serial.print(" score: ");
-    Serial.print(result.score);
-    Serial.print(" xmin: ");
-    Serial.print(result.bbox.xmin);
-    Serial.print(" ymin: ");
-    Serial.print(result.bbox.ymin);
-    Serial.print(" xmax: ");
-    Serial.print(result.bbox.xmax);
-    Serial.print(" ymax: ");
-    Serial.println(result.bbox.ymax);
+  if (!results.empty()) {
+    digitalWrite(PIN_LED_USER, HIGH);
+    Serial.print("Face count: ");
+    Serial.println(results.size());
+    for (auto result : results) {
+      Serial.print(" score: ");
+      Serial.print(result.score);
+      Serial.print(" xmin: ");
+      Serial.print(result.bbox.xmin);
+      Serial.print(" ymin: ");
+      Serial.print(result.bbox.ymin);
+      Serial.print(" xmax: ");
+      Serial.print(result.bbox.xmax);
+      Serial.print(" ymax: ");
+      Serial.println(result.bbox.ymax);
+    }
+  } else {
+    digitalWrite(PIN_LED_USER, LOW);
+    Serial.println("No faces found");
   }
 }


Added code to process JSON pin data.

Added code to process JSON pin data.

--- ServerSketch/ServerSketch.ino
+++ ServerSketch/ServerSketch.ino
@@ -49,8 +49,8 @@

 typedef struct Pin {
   char label[PIN_LABEL_SIZE];
-  boolean is_analog;
-  boolean is_input;
+  int is_analog;
+  int is_input;
   float value;
   boolean connections[TOTAL_NUM_OF_PINS];
 }
@@ -72,7 +72,7 @@
 static struct option options[] = {

   {
-    NULL, 0, 0, 0                                     }
+    NULL, 0, 0, 0                                           }
 };

 /*
@@ -96,39 +96,39 @@

 static const struct serveable whitelist[] = {
   {
-    "/favicon.ico", "image/x-icon"                                     }
+    "/favicon.ico", "image/x-icon"                                           }
   ,
   {
-    "/static/css/app.css", "text/css"                                     }
+    "/static/css/app.css", "text/css"                                           }
   ,
   {
-    "/static/css/jquery.mobile-1.4.1.min.css", "text/css"                                     }
+    "/static/css/jquery.mobile-1.4.1.min.css", "text/css"                                           }
   ,
   {
-    "/static/js/app.js", "application/javascript"                                     }
+    "/static/js/app.js", "application/javascript"                                           }
   ,
   {
-    "/static/js/jquery.jsPlumb-1.4.1-all.js", "application/javascript"                                     }
+    "/static/js/jquery.jsPlumb-1.4.1-all.js", "application/javascript"                                           }
   ,
   {
-    "/static/js/jquery.mobile-1.4.1.js", "application/javascript"                                     }
+    "/static/js/jquery.mobile-1.4.1.js", "application/javascript"                                           }
   ,
   {
-    "/static/js/angular.min.js", "application/javascript"                                     }
+    "/static/js/angular.min.js", "application/javascript"                                           }
   ,
   {
-    "/static/js/jquery.min.js", "application/javascript"                                     }
+    "/static/js/jquery.min.js", "application/javascript"                                           }
   ,
   {
-    "/static/js/jquery-ui.min.js", "application/javascript"                                     }
+    "/static/js/jquery-ui.min.js", "application/javascript"                                           }
   ,
   {
-    "/static/js/underscore-min.js", "application/javascript"                                     }
+    "/static/js/underscore-min.js", "application/javascript"                                           }
   ,

   /* last one is the default served if no match */
   {
-    "/index.html", "text/html"                                     }
+    "/index.html", "text/html"                                           }
   ,
 };

@@ -566,7 +566,7 @@
   ,

   {
-    NULL, NULL, 0, 0                                     } /* terminator */
+    NULL, NULL, 0, 0                                           } /* terminator */
 };

 void sighandler(int sig)
@@ -1037,9 +1037,9 @@
     {
       /*
       Serial.print("Pin ");
-      Serial.print(pinstr);
-      Serial.println(" found");
-*/
+       Serial.print(pinstr);
+       Serial.println(" found");
+       */

       char sPinState[128];
       Serial.println("Pin Data: ");
@@ -1048,39 +1048,56 @@
       aJsonObject *poLabel = aJson.getObjectItem(poPinVals, "label");
       if (poLabel)
       {
-        snprintf(sPinState, sizeof(sPinState), "%s", poLabel->valuestring);
-        Serial.println(sPinState);
+        //snprintf(sPinState, sizeof(sPinState), "%s", poLabel->valuestring);
+        //Serial.println(sPinState);
+        snprintf(g_aPins[i].label, PIN_LABEL_SIZE, "%s", poLabel->valuestring);
+        //       Serial.println(g_aPins[i].label);
+        //        g_aPins[i].label[PIN_LABEL_SIZE]
       }

       aJsonObject *poIsAnalog = aJson.getObjectItem(poPinVals, "is_analog");
       if (poIsAnalog)
       {
-        snprintf(sPinState, sizeof(sPinState), "%i", poIsAnalog->valuebool);
-        Serial.println(sPinState);
+        //        snprintf(sPinState, sizeof(sPinState), "%s", poIsAnalog->valuestring);
+        //       Serial.println(sPinState);
+        if( 0 == strcmp(poIsAnalog->valuestring,"true") )
+          g_aPins[i].is_analog = 1;
+        else if( 0 == strcmp(poIsAnalog->valuestring,"false") )
+          g_aPins[i].is_analog = 0;
+        else
+          g_aPins[i].is_analog = -1;
       }
-
+
       aJsonObject *poIsInput = aJson.getObjectItem(poPinVals, "is_input");
       if (poIsInput)
       {
-        snprintf(sPinState, sizeof(sPinState), "%i", poIsInput->valuebool);
-        Serial.println(sPinState);
+        // snprintf(sPinState, sizeof(sPinState), "%s", poIsInput->valuestring);
+        // Serial.println(sPinState);
+        //  g_aPins[i].is_input =
+        if( 0 == strcmp(poIsInput->valuestring,"true") )
+          g_aPins[i].is_input = 1;
+        else if( 0 == strcmp(poIsInput->valuestring,"false") )
+          g_aPins[i].is_input = 0;
+        else
+          g_aPins[i].is_input = -1;
       }
-
+
       aJsonObject *poValue = aJson.getObjectItem(poPinVals, "value");
       if (poValue)
       {
-        snprintf(sPinState, sizeof(sPinState), "%f", poValue->valuefloat);
-        Serial.println(sPinState);
+        //snprintf(sPinState, sizeof(sPinState), "%s", poValue->valuestring);
+        //Serial.println(sPinState);
+        g_aPins[i].value = atof(poValue->valuestring);
       }
+
+      /*
+       //        g_aPins[i].is_analog = poLabel->valuebool;
+       // g_aPins[i].label[PIN_LABEL_SIZE] =

-       /*
-//        g_aPins[i].is_analog = poLabel->valuebool;
-      // g_aPins[i].label[PIN_LABEL_SIZE] =
-
-      aJsonObject *poIsAnalog = aJson.getObjectItem(poPinVals, "is_analog");
-      if (poPinVals)
-        g_aPins[i].is_analog = poIsAnalog->valuebool;
-*/
+       aJsonObject *poIsAnalog = aJson.getObjectItem(poPinVals, "is_analog");
+       if (poPinVals)
+       g_aPins[i].is_analog = poIsAnalog->valuebool;
+       */

       // g_aPins[i].is_input =

@@ -1088,11 +1105,11 @@
       // g_aPins[i].value =

       // Print pin value after assigment
-//      char sPinState[128];
-//      snprintf(sPinState, sizeof(sPinState), "%s,%i,%i,%f", g_aPins[i].label, g_aPins[i].is_analog, g_aPins[i].is_input, g_aPins[i].value);
-//      snprintf(sPinState, sizeof(sPinState), "%s,%i,%i,%f", g_aPins[i].label, poIsAnalog->valuebool, g_aPins[i].is_input, g_aPins[i].value);
- //     Serial.println("Pin Data: ");
-  //    Serial.println(sPinState);
+      //      char sPinState[128];
+      snprintf(sPinState, sizeof(sPinState), "%s,%i,%i,%f", g_aPins[i].label, g_aPins[i].is_analog, g_aPins[i].is_input, g_aPins[i].value);
+      //snprintf(sPinState, sizeof(sPinState), "%s,%i,%i,%f", g_aPins[i].label, poIsAnalog->valuebool, g_aPins[i].is_input, g_aPins[i].value);
+      //Serial.println("Pin Data: ");
+      Serial.println(sPinState);

     }
@@ -1215,3 +1232,6 @@

+
+
+


fixed missing ;

fixed missing ;

--- code/ESP8266_OSCExample/ESP8266_OSCExample/ESP8266_OSCExample.ino
+++ code/ESP8266_OSCExample/ESP8266_OSCExample/ESP8266_OSCExample.ino
@@ -133,7 +133,7 @@
   else
   {
     if (msg.isInt(0))
-      pxl = msg.getInt(0)
+      pxl = msg.getInt(0);
     if (msg.isInt(1))
       r = msg.getInt(1);
     if (msg.isInt(2))


fixed merge conflicts

fixed merge conflicts

--- Teensy-Reactor-Controller.ino
+++ Teensy-Reactor-Controller.ino
@@ -161,7 +161,7 @@
   // and if the argument isn't 0 or 1, return an error.
   else Serial.println("ERROR: Purge valve state invalid (must be 0 or 1).");
 }
-<<<<<<< HEAD
+

 command(setAutoPurge) {
   // A quick check that the number of arguments received is correct.
@@ -187,5 +187,4 @@
     Serial.println("AutoPurge is set to ON.")
   }
 }
-=======
->>>>>>> 1fdf74254066e9e834ee2515e74e69a88fe11104
+


Hardware tests, timing tweaks, future features

Hardware tests revealed a lot of problems, mostly relating to buffer
management.  Some serial processing functions were refactored for
readability.  Timing has been changed to "real" values for debugging
purposes - but since I haven't tested output visually, expect choppy
gradients.  Function organization still to-do.

Feature goals added: blinking lights and looping blinking lights.

--- csarc/csarc.ino
+++ csarc/csarc.ino
@@ -2,11 +2,16 @@
  *
  *  set a constant color value: "V#FFFFFF"
  *  make gradient pulses between two colors: "G#000000:#FFFFFF:pulseTime"
- *    \--loop between two colors: "L##000000:#FFFFFF:pulseTime"
+ *    \--loop between two colors: "L#000000:#FFFFFF:pulseTime"
+ *    \--smooth loop between two colors: "S#000000:#FFFFFF:pulseTime
+ *  start flashing between two colors:     "F#000000:#FFFFFF:pulseTime"
+ *  lock for a period of time: "DIS:waitTime"
  *
  *  Change SINGLE_LED and the color pins to match your hardware.
  *  You can toggle a handy debug mode with "d".
  */
+// TO DO: implement start/stop flashing
+// TO DO: implement smooth gradients

 #include <stdarg.h>

@@ -37,16 +42,16 @@
 char inputBuffer[SERIAL_BUFFER_LENGTH];
 float gradPerc, gradPercPerTick, gradDelayPerTick;
 int gradcol1[3], gradcol2[3];
-boolean gradientLoop, recentActivity = false;
+boolean gradientLoop = false, recentActivity = false;

 int red,green,blue;
 int* rgb[4] = {&red, &green, &blue, 0};

 // -------------- THREADS ---------------
 #include <TimedAction.h>
-TimedAction   serialThread = TimedAction(1000, &processSerial);
+TimedAction   serialThread = TimedAction(2000, 70, &processSerial);
 TimedAction gradientThread = TimedAction(0,  &gradientStep); // initially disabled in setup()
-TimedAction  timeoutThread = TimedAction(TIMEOUT*1000,  &timeoutAction);
+TimedAction  timeoutThread = TimedAction(TIMEOUT*1000, TIMEOUT*1000,  &timeoutAction);

 void setup() {
   if (SINGLE_LED) {
@@ -56,9 +61,9 @@
     pinMode(GND,OUTPUT);
   }
   gradientThread.disable();
+  Serial.setTimeout(10); //must be substantially less than serialThread's execution window
   Serial.begin(BAUDRATE);
-  // power-up notification
-  quickCycle(25);
+  quickCycle(25); // power-up notification
 }

 void loop() {
@@ -70,29 +75,33 @@
 void processSerial() {
   Serial.readBytesUntil('\n',inputBuffer,SERIAL_BUFFER_LENGTH);
   if (inputBuffer!="") { // if connected
-    recentActivity = true;
+//    if (debugMode) { Serial.print("|");
+//                     for (int x=0; x<10; x++) { Serial.print(inputBuffer[x]); }
+//                     Serial.print("|"); }
+    recentActivity = true;
     switch (inputBuffer[0]) {
-      case 'd': {
-        toggleDebug();
-        break;
-      }
-      case 'V': { // set value specified in V#FFFFFF input
-        processColor(inputBuffer);
-        break;
-      }
-
-      case 'G' : {
-        processGradient(inputBuffer);
-        break;
-      }
-
-      case 'L' : {
-        gradientLoop = true;
-        processGradient(inputBuffer);
-        break;
-      }
+      case 'd': { toggleDebug(); break; }
+      case 'V': { processColor(); break; } // set value specified in V#FFFFFF input
+      case 'L' : { gradientLoop = true; processGradient(); break;}
+      case 'G' : { gradientLoop = false; processGradient(); break;}
     }
     if (debugMode) {
+      processDebug();
+    }
+    clearBuffer();
+  } else if (debugMode) { Serial.println("No serial input."); }
+}
+
+void toggleDebug() {
+  debugMode = !debugMode;
+  Serial.print("Debug mode ");
+  if(debugMode) {
+    Serial.println("ON" );  }
+  else {
+    Serial.println("OFF");  }
+}
+
+void processDebug() {
       switch(inputBuffer[0]) {
         case '0' : {
           setValue(0,0,0);
@@ -120,26 +129,24 @@
         case '?' : { // display contents of *rgb: three colors and a null pointer
           Serial.println("Current color values:");
           for (int i=0; i<3; i++) {
-            Serial.print(*rgb[i]); Serial.print(',');
+            Serial.print(*rgb[i]);
+            Serial.print(',');
           }
           Serial.println(*rgb[3]);
-        }
+        }
       }
-    }
-  }
-}
-
-void toggleDebug() {
-  debugMode=!debugMode;
-  Serial.print("Debug mode ");
-  if(debugMode) {
-    Serial.println( "ON");  }
-  else {
-    Serial.println("OFF");  }
-}
-
-void processColor(char input[]) {
-  char colorInput[] = {input[1],input[2],input[3],input[4],input[5],input[6],input[7],'\0'}; // who needs loops
+}
+
+void processColor() {
+  gradientThread.disable(); // cut off anything else
+  gradientLoop = false;
+  char colorInput[] = {inputBuffer[1], //premature
+                       inputBuffer[2], //optimization
+                       inputBuffer[3], //but also
+                       inputBuffer[4], //laziness
+                       inputBuffer[5],
+                       inputBuffer[6],
+                       inputBuffer[7],'\0'};
   if (debugMode) {
     Serial.print("Serial input:");
     Serial.println(colorInput);  }
@@ -155,37 +162,50 @@
   }
 }

-void processGradient(char input[]) {
+void processGradient() {
 // run gradient pulse between a and b over a length of time; "G#000000:#123456:time" input
-        if ((input[1]!='#' || input[9]!='#')) {
-          Serial.println("Error: invalid gradient request");
-          Serial.println(input);
-        } else {
-          char hex1[8], hex2[8];
-          char timev[8]; //well our buffer is 7 chars now.
-          for (int x=0; x<7; x++) {
-            hex1[x]=input[x+1];
-            hex2[x]=input[x+9];
-            timev[x]=input[x+16];
-          }
-        int col1[4],col2[4];
-        int *col1p[4] = {&col1[0],&col1[1],&col1[2],0};
-        int *col2p[4] = {&col2[0],&col2[1],&col2[2],0};
-
-        decodeHex(hex1,col1p);
-        decodeHex(hex2,col2p);
-        float timeVal = atol(timev); //use strtol or sscanf instead
-        gradientPulseSetup(col1,col2,timeVal);
-
-        if (debugMode) {
-          Serial.println(hex1);
-          Serial.println(hex2);
-          Serial.println(timev); }
-        }
+  if ((inputBuffer[1]!='#' || inputBuffer[9]!='#')) {
+    Serial.println("Error: invalid gradient request");
+    Serial.println(inputBuffer);
+  } else {
+    char hex1[8], hex2[8];
+    char timev[8];
+    for (int x = 0; x<7; x++) {
+      hex1[x] = inputBuffer[1+x];
+      hex2[x] = inputBuffer[9+x];
+      timev[x] = inputBuffer[17+x];
+    }
+    int col1[4],col2[4];
+    int *col1p[4] = {&col1[0],&col1[1],&col1[2],0};
+    int *col2p[4] = {&col2[0],&col2[1],&col2[2],0};
+
+    if (debugMode) {
+      Serial.println("input char[]s");
+      Serial.println(hex1);
+      Serial.println(hex2);
+      Serial.println(timev); }
+
+
+    decodeHex(hex1,col1p);
+    decodeHex(hex2,col2p);
+    float timeVal = atol(timev); //use strtol or sscanf instead
+    gradientPulseSetup(col1,col2,timeVal);
+
+    if (debugMode) {
+      Serial.println("col1: ");
+      Serial.print(col1[0]); Serial.print(" "); Serial.print(col1[1]); Serial.print(" "); Serial.println(col1[2]);
+      Serial.println("col2: ");
+      Serial.print(col2[0]); Serial.print(" "); Serial.print(col2[1]); Serial.print(" "); Serial.println(col2[2]);
+      Serial.print("timeVal: ");
+      Serial.println(timeVal);
+    }
+  }
 }

 void timeoutAction() {
+
+  if (debugMode) { Serial.println("Processing timeout."); }
   if (!recentActivity) {
     // maybe timeout and timeout behavior should be configurable over serial.
     // low priority, bc this will mostly be running before serial comms have
@@ -195,34 +215,74 @@
   }
 }

-
-void setOutput( int r, int g, int b) {
-
-  if (!SINGLE_LED) {
-    Driver.begin();
-    Driver.SetColor(r, g, b);
-    Driver.end();
-  } else {
-    analogWrite(R_PIN,r);
-    analogWrite(G_PIN,g);
-    analogWrite(B_PIN,b);
-  }
-}
-
-void setOutput( int *color[]) {
+void gradientPulseSetup (const int col1[3],const int col2[3], float timev) { // timev is now in seconds
+  gradDelayPerTick = (float) timev*1000/numdivs;
+  gradPercPerTick = (float) 1/numdivs;
+  gradPerc = 0;
+  if (debugMode) {
+    Serial.println("---gradientPulse---");
+    Serial.println("col1,col2:");
+    for (int i=0; i<3;i++) {
+      Serial.print(col1[i]);
+      Serial.print(' ');
+    }
+    Serial.println();
+    for (int i=0; i<3;i++) {
+      Serial.print(col2[i]);
+      Serial.print(' ');
+    }
+    Serial.print("timev = ");
+    Serial.println(timev);
+    Serial.print("numdivs = ");
+    Serial.println(numdivs);
+    Serial.print("gradDelayPerTick = ");
+    Serial.println(gradDelayPerTick);
+    Serial.print("gradPercPerTick = ");
+    Serial.println(gradPercPerTick);
+    Serial.println();
+  }
+
+  for (int x=0; x<3; x++) {
+    gradcol1[x]=col1[x];
+    gradcol2[x]=col2[x];
+  }

-  if (debugMode) {
-    Serial.println(); // for some reason a lot of this output
-    Serial.println("---Setting output:---"); // doesn't show up
-    Serial.println(*color[0]);
-    Serial.println(*color[1]);
-    Serial.println(*color[2]);
-    Serial.println(*color[3]);
-    Serial.println("---------------------");
-  }
-    setOutput(*color[0],*color[1],*color[2]);
-
-}
+  gradientThread.setInterval(gradDelayPerTick);
+  gradientThread.reset();
+  gradientThread.enable();
+  if (debugMode) {
+    Serial.println("Gradient setup done, gradient thread enabled.");
+  }
+}
+
+
+
+void gradientStep() {
+  if (debugMode) { Serial.println("Gradient processing."); }
+  if (gradPerc <= 1.0) {
+    Serial.print(gradPerc);
+    Serial.println("/1");
+    gradientValue(gradcol1, gradcol2, gradPerc, rgb);
+    setOutput(rgb);
+    gradPerc+=gradPercPerTick;
+  }
+  else {
+    if (gradientLoop) {
+      gradPerc = 0;
+      if (debugMode) { Serial.println("Looping gradient."); }
+    } else {
+      if (debugMode) { Serial.println("Halting gradient."); }
+      gradientThread.disable();
+    }
+  }
+}
+
+void gradientValue(int col0[3], int col1[3], float percentage, int *output[3]) {
+  *output[0] = col1[0]*percentage + col0[0]*(1-percentage);
+  *output[1] = col1[1]*percentage + col0[1]*(1-percentage);
+  *output[2] = col1[2]*percentage + col0[2]*(1-percentage);
+}
+

 void decodeHex( char hexColor[], int * output[] ) { //in: #FFFFFF\0
   unsigned long number = strtol( &hexColor[1], NULL, 16);
@@ -245,65 +305,6 @@
   }
 }

-
-
-
-void gradientPulseSetup (const int col1[3],const int col2[3], float timev) { // timev is now in seconds
-  // in this initial version, gradient pulses are going to be locking.
-  // This is obviously a problem - add an interrupt when you have time.
-
-  gradDelayPerTick = (float) timev*1000/numdivs;
-  gradPercPerTick = (float) 1/numdivs;
-  if (debugMode) {
-    Serial.println("---gradientPulse---");
-    Serial.println("col1,col2:");
-    for (int i=0; i<3;i++) {
-      Serial.print(col1[i]);
-      Serial.print(' ');
-    }
-    Serial.println();
-    for (int i=0; i<3;i++) {
-      Serial.print(col2[i]);
-      Serial.print(' ');
-    }
-    Serial.print("gradDelayPerTick = ");
-    Serial.println(gradDelayPerTick);
-    Serial.print("gradPercPerTick = ");
-    Serial.println(gradPercPerTick);
-    Serial.println();
-  }
-  colorCopy(gradcol1,col1);
-  colorCopy(gradcol2,col2);
-  gradientThread.setInterval(gradDelayPerTick);
-  gradientThread.reset();
-  gradientThread.enable();
-}
-
-
-
-void gradientStep() {
-  if (gradPerc < 1.0) {
-    Serial.print(gradPerc);
-    Serial.println("/1");
-    gradientValue(gradcol1, gradcol2, gradPerc, rgb);
-    setOutput(rgb);
-    gradPerc+=gradPercPerTick;
-  }
-  else {
-    if (gradientLoop = true) {
-      gradPerc = 0;
-    } else {
-      gradientThread.disable();
-    }
-  }
-}
-
-void gradientValue(int col0[3], int col1[3], float percentage, int *output[3]) {
-  *output[0] = col1[0]*percentage + col0[0]*(1-percentage);
-  *output[1] = col1[1]*percentage + col0[1]*(1-percentage);
-  *output[2] = col1[2]*percentage + col0[2]*(1-percentage);
-}
-
 void printColors() {
   Serial.print('#');
   if (red<=16) {Serial.print('0');}
@@ -314,16 +315,13 @@
   Serial.println(blue, HEX);
 }

-void setValue ( int r, int g, int b) {
-  red=r; green=g; blue=b;
-  setOutput(rgb);
-}
-
-void colorCopy( int recipient[3], const int donor[3] ) {
-  recipient[0] = donor[0];
-  recipient[1] = donor[1];
-  recipient[2] = donor[2];
-}
+
+//void arrayCopy( int *recipient, const int *donor, int len ) { // make this more generic - should work on ints and chars
+//  //be very careful with len
+//  for (int x = 0; x<len; x++) {
+//    recipient[x] = donor[x];
+//  }
+//}

 void quickCycle(int baseTime) {
   setValue(255,0,0);
@@ -336,3 +334,61 @@
   delay(baseTime);
   setValue(0,0,0);
 }
+
+
+void setOutput( int r, int g, int b) {
+
+  if (!SINGLE_LED) {
+    Driver.begin();
+    Driver.SetColor(r, g, b);
+    Driver.end();
+  } else {
+    analogWrite(R_PIN,r);
+    analogWrite(G_PIN,g);
+    analogWrite(B_PIN,b);
+  }
+}
+
+
+
+void setOutput( int *color[]) {
+  if (debugMode) {
+    Serial.println(); // for some reason a lot of this output
+    Serial.println("---Setting output:---"); // doesn't show up
+    Serial.println(*color[0]);
+    Serial.println(*color[1]);
+    Serial.println(*color[2]);
+    Serial.println(*color[3]);
+    Serial.println("---------------------");
+  }
+    setOutput(*color[0],*color[1],*color[2]);
+}
+
+void setValue ( int r, int g, int b) {
+  gradientThread.disable(); // cut off anything else
+  gradientLoop = false;
+  red=r; green=g; blue=b;
+  setOutput(rgb);
+}
+
+void clearBuffer() {
+  //optimized for a mostly empty buffer
+  char *ptr = &inputBuffer[0];
+  if(debugMode) {
+    Serial.print("Buffer: [");
+    while (ptr<&inputBuffer[0]+SERIAL_BUFFER_LENGTH && *ptr!=0) {
+      Serial.print(*ptr);
+      *ptr = 0;
+      ptr++;
+    }
+    Serial.print(*ptr);
+    Serial.println( "] wiped.");
+  } else {
+    while (ptr<&inputBuffer[0]+SERIAL_BUFFER_LENGTH && *ptr!=0) {
+      *ptr = 0;
+      ptr++;
+    }
+  }
+  *ptr = 0;
+}
+


some trigerrs

some trigerrs

--- f-preform-02/f-preform-02.ino
+++ f-preform-02/f-preform-02.ino
@@ -180,7 +180,7 @@
 }

 LiquidCrystal_I2C lcd(0x27, 16, 2); // set the LCD address to 0x27 for a 16 chars and 2 line display
-//LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, 1);
+// LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, 1);
 const int b11 = B11_PIN, b12 = B12_PIN, b13 = B13_PIN, b14 = B14_PIN, b15 = B15_PIN, b21 = B21_PIN, b22 = B22_PIN, b23 = B23_PIN, // buttons
 b24 = B24_PIN, b25 = B25_PIN,
 l101 = L101_PIN, l102 = L102_PIN, l103 = L103_PIN, l104 = L104_PIN, l105 = L105_PIN, l106 = L106_PIN, l107 = L107_PIN, // leds
@@ -283,8 +283,26 @@
     currentMillis = millis();
     previousMillis = currentMillis;
     reset_buttons_flagClick();
-    digitalWrite(field[x][y], HIGH);
+    if (field[x][y] != -1)
+    {
+        digitalWrite(field[x][y], HIGH); // проверка наличия светодиода в новой координате
+    }
     digitalWrite(field[xPrev][yPrev], LOW);
+    if (y == 0 || y == 4)
+    {
+        game = GAME_SIDE_OUT;
+        return;
+    }
+    if (y == 2 && (x == 0 || x == 11))
+    {
+        game = GAME_GOAL;
+        return;
+    }
+    if (y == 2 && (x == 0 || x == 11))
+    {
+        game = GAME_END_OUT;
+        return;
+    }
 }

 void start_game()


Removes calibration code

Removes calibration code

Calibration will be done via the serial, since there is now only one
button and one led it is much harder to calibrate the device with out
more input. So the device will be calibrated over serial then a top
board can calibrate the base over serial as it will have much greater
input.

--- src/drifter.ino
+++ src/drifter.ino
@@ -2,164 +2,54 @@
 #include <Motor.h>
 #include <Button.h>
 #include <LED.h>
-#include <Potentiometer.h>
 #include <EEPROM.h>

-Potentiometer pot(0);
-Button switch1(4, PULLUP);
-Button switch2(8, PULLUP);
-LED led1(9);  // PWM pin
-LED led2(13); // Non PWM pin
+Button button(A0, PULLUP);
+LED led(13);
 Motor left_motor;
 Motor right_motor;
 static const int LEFT_MIN_POWER_ADDRESS = 0;
 static const int RIGHT_MIN_POWER_ADDRESS = 1;

 bool running = false;
-int speed = 0;
+int speed = 5;

 void setup()
 {
     Serial.begin(9600);
-    left_motor.attach(10, 11, 12);
-    right_motor.attach(5, 6, 7);
-    Serial.println("Press switch1 to start calibration");
-    led1.fadeIn(250);
-    led1.fadeOut(250);
-    if (switch1.isPressed()) {
-        calibrateMotors();
+    left_motor.attach(9, 8, 7);
+    right_motor.attach(6, 5, 4);
+    Serial.println("Loading EEPROM values");
+    byte left_min = EEPROM.read(LEFT_MIN_POWER_ADDRESS);
+    byte right_min = EEPROM.read(RIGHT_MIN_POWER_ADDRESS);
+
+    if (right_min > 100 || left_min > 100) {
+        Serial.println("Values uninitlised, initlising");
+        left_min = 50;
+        right_min = 50;
     } else {
-        Serial.println("Loading EEPROM values");
-        byte left_min = EEPROM.read(LEFT_MIN_POWER_ADDRESS);
-        byte right_min = EEPROM.read(RIGHT_MIN_POWER_ADDRESS);
-        Serial.print("Left motor min power: ");
-        Serial.println(left_min);
-        Serial.print("Right motor min power: ");
-        Serial.println(right_min);
-
-        if (right_min > 100 || left_min > 100) {
-            Serial.println("Bad values detected in EEPROM, running calibration");
-            calibrateMotors();
-        } else {
-            left_motor.setMinPower(left_min);
-            right_motor.setMinPower(right_min);
-        }
+        left_motor.setMinPower(left_min);
+        right_motor.setMinPower(right_min);
     }
+    Serial.print("Left motor min power: ");
+    Serial.println(left_min);
+    Serial.print("Right motor min power: ");
+    Serial.println(right_min);
     Serial.println("Started");
 }

 void loop()
 {
-    // Stop if the user has pressed the second switch
-    if (switch2.uniquePress()) {
-        running = false;
-        speed = 0;
-        left_motor.stop();
-        right_motor.stop();
-        return;
+    if (button.uniquePress()) {
+        if (running) {
+            left_motor.stop();
+            right_motor.stop();
+            running = false;
+        } else {
+            left_motor.forward(speed);
+            right_motor.forward(speed);
+            running = true;
+        }
     }
-
-    // Incroment speed if the first switch is pressed
-    if (switch1.uniquePress()) {
-        speed++;
-        if (speed > 10) {
-            speed = 1;
-        }
-        left_motor.forward(speed);
-        right_motor.forward(speed);
-    }
-
 }

-void calibrateMotors() {
-    byte min_power;
-    int offset_power;
-
-    Serial.println("Entering configure mode");
-    led1.on();
-    led2.on();
-    delay(500);
-    led1.off();
-    led2.off();
-    delay(500);
-    led1.on();
-    led2.on();
-
-    Serial.println("Calibrating Motor Min Power");
-    Serial.println("Turn pot to the minimum position then up until the rover starts moving, then press switch1 to continue");
-
-    while (pot.getValue()) {
-        delay(100);
-    }
-
-    left_motor.forward(1);
-    right_motor.forward(1);
-
-    // Find base min power
-    while (true) {
-        min_power = map(pot.getValue(), 0, 1023, 0, 255);
-        Serial.println(min_power);
-        left_motor.setMinPower(min_power);
-        right_motor.setMinPower(min_power);
-
-        if (switch1.uniquePress()) {
-            left_motor.stop();
-            right_motor.stop();
-            break;
-        }
-
-        delay(100);
-    }
-
-    Serial.println("Balancing the motors");
-    Serial.println("Adjust the pot to the center position, the rover will then start to move forward at the minimum speed, adjust the pot left or right to until the rover drives stright, then press switch1 to continue");
-
-    while (abs(map(pot.getValue(), 0, 1023, -50, 50)) > 2) {
-        if (offset_power > 0) {
-            led1.on();
-            led2.off();
-        } else if (offset_power < 0 ) {
-            led1.off();
-            led2.on();
-        }
-        led1.on();
-        led2.on();
-        delay(100);
-    }
-    delay(1000);
-
-    left_motor.forward(1);
-    right_motor.forward(1);
-
-
-    // Find the offset of the two motors
-    while (true) {
-        offset_power = map(pot.getValue(), 0, 1023, -50, 50);
-        Serial.println(offset_power);
-
-        if (offset_power > 0) {
-            Serial.print("Adjusting left");
-            Serial.println(min_power + offset_power);
-            left_motor.setMinPower(min_power + offset_power);
-        } else if (offset_power < 0 ) {
-            Serial.print("Adjusting right ");
-            Serial.println(min_power + abs(offset_power));
-            right_motor.setMinPower(min_power + abs(offset_power));
-        }
-
-        if (switch1.uniquePress()) {
-            left_motor.stop();
-            right_motor.stop();
-            break;
-        }
-
-        delay(100);
-    }
-
-    Serial.print("Final values, left min power: ");
-    Serial.print(left_motor.minPower());
-    Serial.print(" right min power: ");
-    Serial.print(right_motor.minPower());
-    EEPROM.write(LEFT_MIN_POWER_ADDRESS, left_motor.minPower());
-    EEPROM.write(RIGHT_MIN_POWER_ADDRESS, right_motor.minPower());
-}


fix consitancy issues with white space

fix consitancy issues with white space

--- bot_base.ino
+++ bot_base.ino
@@ -3,7 +3,7 @@
  * Compiled with Arduino IDE 1.6.5
  * The goal of this project is to provide remote control and some autonomous
  * program modes for a 2 wheeled robot driven by the 2x12 Sabertooth motor controller
- * !! no ramping assumes your motor controllor does it !!
+ * NOTICE!! no ramping, assumes your motor controllor does it !!
  * This robot also has a IR long range distance sensor panned by a servo
  * in order to cover a range of posible obstacles
  * The readme will include details of remote control via serial port
@@ -18,14 +18,14 @@

 // direction constants
 #define BACK_LEFT  '1'
-#define BACK		   '2'
+#define BACK       '2'
 #define BACK_RIGHT '3'
-#define SPIN_LEFT	 '4'
-#define STOP		   '5'
+#define SPIN_LEFT  '4'
+#define STOP       '5'
 #define SPIN_RIGHT '6'
-#define FWD_LEFT	 '7'
-#define FWD		     '8'
-#define FWD_RIGHT	 '9'
+#define FWD_LEFT   '7'
+#define FWD        '8'
+#define FWD_RIGHT  '9'
 // command types
 #define MOVEMENT   'M'
 #define SPEED      'S'
@@ -66,7 +66,7 @@

 //-------------- Main supporting functions ------------

-char* commandListen(char incoming){  // returns if a command has been called
+char* commandListen(char incoming){  // returns if a command has been recieved
   static char packet[2] = { 0, 0 }; // store potential incoming command packet
   // reset if a full packet has been recieved
   if(packet[0] && packet[1]){packet[0] = 0; packet[1] = 0;}
@@ -128,18 +128,17 @@
   int finalSpeedLeft = 0;
   int finalSpeedRight = 0;

-	if (speed == 0 && direction) {
-		finalSpeedLeft = direction;
-		finalSpeedRight = -direction;
+	if(speed == 0 && direction) {
+    finalSpeedLeft = direction;
+    finalSpeedRight = -direction;
 	} else {
-		finalSpeedLeft = speed * ((-255 - direction) / -255.0);
-		finalSpeedRight = speed * ((255 - direction) / 255.0);
-
-		if (speed > 0 && finalSpeedLeft > speed){finalSpeedLeft = speed;}
-		if (speed > 0 && finalSpeedRight > speed){finalSpeedRight = speed;}
-		if (speed < 0 && finalSpeedLeft < speed){finalSpeedLeft = speed;}
-		if (speed < 0 && finalSpeedRight < speed){finalSpeedRight = speed;}
-
+    finalSpeedLeft = speed * ((-255 - direction) / -255.0);
+    finalSpeedRight = speed * ((255 - direction) / 255.0);
+
+    if (speed > 0 && finalSpeedLeft > speed){finalSpeedLeft = speed;}
+    if (speed > 0 && finalSpeedRight > speed){finalSpeedRight = speed;}
+    if (speed < 0 && finalSpeedLeft < speed){finalSpeedLeft = speed;}
+    if (speed < 0 && finalSpeedRight < speed){finalSpeedRight = speed;}
 	}
   // !! no ramping assumes your motor controllor does it !!
   leftWheel.writeMicroseconds(map(finalSpeedLeft,-255,255,1000,2000));


Updated MidiKeyboard example to use OctaveKeyboard

--- arduino/libraries/BuildingBlocks/examples/MidiKeyboard/MidiKeyboard.ino
+++ arduino/libraries/BuildingBlocks/examples/MidiKeyboard/MidiKeyboard.ino
@@ -4,7 +4,7 @@
 #include <BuildingBlocks.h>

 // Define an instance of Keyboard module.
-Keyboard keyboard;
+OctaveKeyboard keyboard;

 // Define an instance of the Mainboard module.
 Mainboard mainboard(keyboard);
@@ -17,7 +17,7 @@
 	mainboard.init();

 	// Set the function which will get called when keyboard events are detected.
-	keyboard.setCallback(&onKeyEvent);
+	keyboard.setCallback(&onNoteEvent);
 }

 // Just update the Mainboard in order to receive the events that are happening in the attached modules.
@@ -26,8 +26,8 @@
 }

 // This will get called while executing mainboard.update(), if events were detected.
-void onKeyEvent(void *userdata, uint8_t key, bool isDown) {
-	sendMidiNote(0, 60 + key, isDown ? 100 : 0);
+void onNoteEvent(void *userdata, uint8_t note, bool isDown) {
+	sendMidiNote(0, note, isDown ? 100 : 0);
 }

 // Send the 3 byte MIDI Note On / Off message through the Serial port.


Resolve some compiler warnings when using the Makefile.

--- firmware.ino
+++ firmware.ino
@@ -84,7 +84,7 @@

 void getRGB(int hue, int sat, int val, int colors[3]) {
   // hue: 0-259, sat: 0-255, val (lightness): 0-255
-  int r, g, b, base;
+  int r = 0, g = 0, b = 0, base = 0;

   if (sat == 0) { // Achromatic color (gray).
     colors[0]=val;
@@ -145,7 +145,7 @@
 }

 void parse_message(String message) {
-  for (int i = 0; i <= message.length(); i++) {
+  for (unsigned int i = 0; i <= message.length(); i++) {
     time = millis();
     if (message[i] == '(') {
       motorVal = 10*(message[i+1]-'0') + (message[i+2]-'0');


Wrote code that actually does something. To be improved!

--- Safety_System_Integration/Safety_System_Integration.ino
+++ Safety_System_Integration/Safety_System_Integration.ino
@@ -1,9 +1,49 @@
+/*
+ * Safety System Integration
+ * YCP FSAE Formula Electric Car Team 2017
+ * Patrick Hock
+ * July 30 2017
+ *
+ * For now, this is mostly test code.
+ * Getting familiar with Arduino.
+ * This program will blink an LED external to the Teensy.
+ */
+
+#define BSPD_ERR_LED  33
+#define BSPD_IN 23
+uint8_t interruptTracker = 0;
+
 void setup() {
-  // put your setup code here, to run once:
-  // Patrick's new Project
+
+  pinMode(BSPD_ERR_LED, OUTPUT);  // Sets pin 33 as an output
+  pinMode(BSPD_IN, INPUT);  // Sets pin 23 as input
+
+  attachInterrupt(digitalPinToInterrupt(BSPD_IN), BSPD_Fault, RISING);
+
 }

 void loop() {
-  // put your main code here, to run repeatedly:
+
+// Check for BSPD Error
+if(bitRead(interruptTracker, 0))
+{
+  digitalWrite(BSPD_ERR_LED, HIGH);
+  bitWrite(interruptTracker, 0, 0);    // Resets the "interrupt flag" for BSPD Error
+}

 }
+
+void BSPD_Fault()
+{
+  noInterrupts();
+
+  // changes bit 0 to a one so that Loop() can handle the error
+
+  bitWrite(interruptTracker, 0, 1); // Sets "interrupt flag" for BSPD error
+
+  interrupts();
+
+  return;
+}
+
+


removed global file

removed global file

--- exhaust_sensor_array.ino
+++ exhaust_sensor_array.ino
@@ -30,11 +30,10 @@
 #endif

 int sensor_array[6];
-File log_file;

 void print_log() {

-  log_file = SD.open("log.csv", FILE_WRITE);
+  File log_file = SD.open("log.csv", FILE_WRITE);

   print(gps.location.lat(), 6);
   print(',');


Refactored example with a validated setup and program halt if something's wrong.

--- examples/DemoArcRPM/DemoArcRPM.ino
+++ examples/DemoArcRPM/DemoArcRPM.ino
@@ -92,6 +92,15 @@

 		AnimationStep = ((ANIMATION_STEPS*(now - AnimationStart)) / ANIMATION_DURATION);

+		if (AnimationStep < ANIMATION_STEPS / 2)
+		{
+			DemoRPM = AnimationStep * 2 * ((uint32_t)DEMO_RPM_RANGE / (uint32_t)ANIMATION_STEPS);
+		}
+		else
+		{
+			DemoRPM = (ANIMATION_STEPS - AnimationStep) * 2 * ((uint32_t)DEMO_RPM_RANGE / ANIMATION_STEPS);
+		}
+
 		if (now - AnimationStart > ANIMATION_DURATION - 1)
 		{
 			AnimationStep = 0;
@@ -152,19 +161,26 @@

 	Serial.println();
 	Serial.println();
+
 	Serial.println(F("RPM setup..."));
-	SetupRPMDriver();
+	if (!SetupRPMDriver())
+	{
+		Serial.println(F(" failed"));
+		Halt();
+	}
 	Serial.println(F(" complete"));

 	SetupDemo();
 }

+
+
 bool SetupRPMDriver()
 {
-
+	bool Success = false;
 	//RPMDriver.AddLogger(&Serial);
-	RPMDriver.Begin();
-	RPMDriver.SetDesignModel(SUB_PIXEL_ENABLED);// | SUB_PIXEL_HIGH_RANGE_ENABLED | BACKGROUND_ENABLED);
+	Success = RPMDriver.Begin();
+	RPMDriver.SetDesignModel(SUB_PIXEL_ENABLED | BACKGROUND_ENABLED);// | SUB_PIXEL_HIGH_RANGE_ENABLED | BACKGROUND_ENABLED);
 	RPMDriver.SetBrightness(GlobalBrightness);
 	RPMDriver.SetRangeRPM(600, 15000);
 	RPMDriver.ClearSections();
@@ -185,16 +201,6 @@
 {
 	Now = millis();

-	if (Now - LastBrightnessUpdate > BRIGHTNESS_UPDATE_INTERVAL - 1)
-	{
-
-		LastBrightnessUpdate += BRIGHTNESS_UPDATE_INTERVAL;
-
-		UpdateBrightness();
-		/*Serial.print("GlobalBrightness: ");
-		Serial.println(GlobalBrightness);*/
-	}
-
 	if (Now - LastLEDUpdate > DEMO_LED_UPDATE_INTERVAL - 1)
 	{
 		LastLEDUpdate += DEMO_LED_UPDATE_INTERVAL;
@@ -211,17 +217,10 @@
 	{
 		LastRPMUpdate += DEMO_RPM_UPDATE_INTERVAL;

-		if (AnimationStep < ANIMATION_STEPS / 2)
-		{
-			DemoRPM = AnimationStep * 2 * ((uint32_t)DEMO_RPM_RANGE / (uint32_t)ANIMATION_STEPS);
-		}
-		else
-		{
-			DemoRPM = (ANIMATION_STEPS - AnimationStep) * 2 * ((uint32_t)DEMO_RPM_RANGE / ANIMATION_STEPS);
-		}
+

 		//RPMStart = micros();
-		RPMDriver.UpdateRPM(DemoRPM, Now, true);
+		RPMDriver.UpdateRPM(DemoRPM, Now);
 		//Serial.println(RPMDriver.Debug());
 		//RPMEnd = micros();
 		//Serial.print("Update RPM took: ");
@@ -229,6 +228,16 @@
 		//Serial.println(" us");
 	}

+	if (Now - LastBrightnessUpdate > BRIGHTNESS_UPDATE_INTERVAL - 1)
+	{
+
+		LastBrightnessUpdate += BRIGHTNESS_UPDATE_INTERVAL;
+
+		UpdateBrightness();
+		/*Serial.print("GlobalBrightness: ");
+		Serial.println(GlobalBrightness);*/
+	}
+
 	Demo(Now);

 	if (Now - LastSerialUpdate > SERIAL_POLL_INTERVAL - 1)
@@ -243,4 +252,9 @@
 		//Serial.print("GlobalBrightness: ");
 		//Serial.println(GlobalBrightness);
 	}
+}
+
+void Halt()
+{
+	while (true);;
 }


Fixings

Fixings

--- Ned.ino
+++ Ned.ino
@@ -67,7 +67,9 @@
   {
     timer = millis(); //Keep timer up with millis().
     if (isItAutoMode) CalculateSunTimes(); //Do IT!
+    #ifdef DEBUG
     else MeasureTime();
+    #endif
   }
 }

@@ -108,6 +110,7 @@
     #endif
 }

+#ifdef DEBUG
 void MeasureTime()
 {
   int reading = analogRead(5);
@@ -117,6 +120,7 @@
   isItDayTime = analogRead(5) > 511;
   WriteOutput(!isItDayTime); //Make changes if needed.
 }
+#endif

 void WriteOutput(int level)
 {
@@ -129,4 +133,4 @@
     digitalWrite(i, level);
     i += i == 9 ? 4 : 1; //Skip the RTC Pins (10, 11, 12).
   }
-}
+}


ArduinoOTA.handle();

ArduinoOTA.handle();

--- _70-homekit-accessories-light/_70-homekit-accessories-light.ino
+++ _70-homekit-accessories-light/_70-homekit-accessories-light.ino
@@ -7,7 +7,6 @@
 #include <PubSubClient.h>
 #include <ArduinoJson.h>
 #include <Ticker.h>
-
 #include "/usr/local/src/rpi2_setting.h"

 #define BUTTON_PIN 0
@@ -174,14 +173,24 @@
 {
   digitalWrite(RELAY_PIN, bRelayState);
   bUpdated = false;
-  attachInterrupt(BUTTON_PIN, run_lightcmd_isr, FALLING);
 }

 void run_lightcmd_isr()
 {
-  detachInterrupt(BUTTON_PIN);
   bRelayState = !bRelayState;
   bUpdated = true;
+}
+
+String macToStr(const uint8_t* mac)
+{
+  String result;
+  for (int i = 0; i < 6; ++i)
+  {
+    result += String(mac[i], 16);
+    if (i < 5)
+      result += ':';
+  }
+  return result;
 }

 void ArduinoOTA_config()
@@ -273,6 +282,7 @@
     {
       client.loop();
     }
+    ArduinoOTA.handle();
   }
   else
   {
@@ -280,18 +290,4 @@
     wifi_connect();
   }
 }
-
-
-String macToStr(const uint8_t* mac)
-{
-  String result;
-  for (int i = 0; i < 6; ++i)
-  {
-    result += String(mac[i], 16);
-    if (i < 5)
-      result += ':';
-  }
-  return result;
-}
-
 // end of file


Update non_blocking_multiple.ino

Update non_blocking_multiple.ino

--- Arduino/MAX31850/non_blocking_multiple.ino
+++ Arduino/MAX31850/non_blocking_multiple.ino
@@ -48,7 +48,6 @@
   if (!sensors.getAddress(ambientTemperature, 0)) Serial.println("Unable to find address for Device 0");
   if (!sensors.getAddress(casingTemperature, 1)) Serial.println("Unable to find address for Device 1");

-
   // show the addresses we found on the bus
   Serial.print("Device 0 Address: ");
   printAddress(ambientTemperature);
@@ -69,11 +68,8 @@
   Serial.print(sensors.getResolution(casingTemperature), DEC);
   Serial.println();

+  sensors.setWaitForConversion(false);

-
-
-
-  sensors.setWaitForConversion(false);
   sensors.requestTemperatures();
   delayInMillis = 750 / (1 << (3));
   lastTempRequest = millis();
@@ -128,21 +124,17 @@
     digitalWrite(13, LOW);
     Serial.print("Ambient temperature: ");
     ambient_temperature = sensors.getTempCByIndex(0);
-	Serial.println(ambient_temperature, 1);
+    Serial.println(ambient_temperature, 1);

-	Serial.print("Casing temperature: ");
+    Serial.print("Casing temperature: ");
     casing_temperature = sensors.getTempCByIndex(1);
-	Serial.println(casing_temperature, 1);
-
-
-
-
-	Serial.print("Idle counter: ");
+    Serial.println(casing_temperature, 1);
+    Serial.print("Idle counter: ");

     Serial.println(idle);
     Serial.println();
     idle = 0;
-	sensors.requestTemperatures();
+    sensors.requestTemperatures();
     delayInMillis = 750 / (1 << (3));
     lastTempRequest = millis();
   }
@@ -152,6 +144,4 @@
   // for the demo we just count the idle time in millis
   delay(1);
   idle++;
-
-
-}+}


Invert the door logic to match the electronics. Oops.

--- test/PoE-test/tussendeur-asis-2017/tussendeur-asis-2017.ino
+++ test/PoE-test/tussendeur-asis-2017/tussendeur-asis-2017.ino
@@ -23,7 +23,10 @@
 #define MFRC522_RSTO    (32)
 #define MFRC522_3V3     /* 3v3 */

-#define SOLENOID_GPIO     (14)
+#define SOLENOID_GPIO     (4)
+#define SOLENOID_OFF      (LOW)
+#define SOLENOID_ENGAGED  (HIGH)
+#define AARTLED_GPIO     (16)

 #define DOOR_OPEN_DELAY         (10*1000)   //  10 seconds -- how long to hold the relay engaged; in milli seconds.
 #define CACHE_FALLBACK_TIMEOUT  (500)       // 0.5 second  -- how long to wait for a reply before checking the cache.
@@ -283,7 +286,7 @@
   Serial.println(" -- buuld: " __DATE__ " " __TIME__ );

   pinMode(SOLENOID_GPIO, OUTPUT);
-  digitalWrite(SOLENOID_GPIO, 1);
+  digitalWrite(SOLENOID_GPIO, SOLENOID_OFF);

   WiFi.onEvent(WiFiEvent);

@@ -409,7 +412,7 @@

 void closeDoor() {
   doorstate = CLOSED;
-  digitalWrite(SOLENOID_GPIO, HIGH);
+  digitalWrite(SOLENOID_GPIO, SOLENOID_OFF);
 }

 void openDoor() {
@@ -417,7 +420,7 @@
   client.publish(log_topic, "Engaging solenoid");

   // Engage solenoid.
-  digitalWrite(SOLENOID_GPIO, LOW);
+  digitalWrite(SOLENOID_GPIO, SOLENOID_ENGAGED);

   // according to Ticker examples - this will reset/overwrite
   // any already running tickers.
@@ -426,7 +429,7 @@
 };

 bool isOpen() {
-  return digitalRead(SOLENOID_GPIO) == LOW;
+  return digitalRead(SOLENOID_GPIO) == SOLENOID_ENGAGED;
 }

 bool isClosed() {


Update Arduino_16_Zone_Irrigation_Controller.ino

Updates the irrigation controller sketch to work properly with the ST_Anything library.  Now uses Hardware Serial 3 to communicate with the ThingShield.  You must connect jumpers from the RX/TX of Hardware Serial 3 to the Pin2/Pin3 of the ThingShield.  See diagram in the header.

--- 16_Zone_Controller/Arduino_16_Zone_Irrigation_Controller.ino
+++ 16_Zone_Controller/Arduino_16_Zone_Irrigation_Controller.ino
@@ -2,7 +2,7 @@
 /**
 *
  ****************************************************************************************************************************
- * Irrigation Controller 16 Zones With Options for Master Valve and Pump  v1
+ * Irrigation Controller 16 Zones With Options for Master Valve and Pump  v3_0
  * Simple, elegant irrigation controller that takes advantage of the cloud and SmartThings ecosystem
  * Arduino MEGA with SmartThings Shield  and 16 relay modules
  * Works by receiving irrigation run times from the Cloud and then builds a queue to execute
@@ -53,19 +53,19 @@
 ///               |           13 |--
 ///               |           12 |--
 ///               |           11 |--
-///             --| 3.3V      10 |----|  Run jumper from pin10 to pin3
-/// Relay VCC   --| 5V         9 |--  |
-/// Relay Ground--| GND        8 |--  |
-///             --| GND          |    |
-///             --| Vin        7 |--  |
-///               |            6 |--  |
-///             --| A0         5 |--  |
-///             --| A1    ( )  4 |--  |  pin4 Optional Pump/Master Valve
-///             --| A2         3 |----|  pin3 THING_RX
-///             --| A3         2 |--     pin2 THING_TX
-///             --| A4         1 |--
-///             --| A5        14 |--
-///             --| A6        15 |--
+///             --| 3.3V      10 |----
+/// Relay VCC   --| 5V         9 |--
+/// Relay Ground--| GND        8 |--
+///             --| GND          |
+///             --| Vin        7 |--
+///               |            6 |--
+///             --| A0         5 |--
+///             --| A1    ( )  4 |--       pin4 Optional Pump/Master Valve
+///             --| A2         3 |------|  pin3 connect to pin14 TX3
+///             --| A3         2 |--|   |  pin2 connect to pin15 RX3
+///             --| A4         1 |--|   |
+///             --| A5        14 |--]---|  TX3 Hardware Serial 3
+///             --| A6        15 |--|      RX3 Hardware Serial 3
 ///             --| A7        16 |--
 ///             --| A8        17 |--
 ///             --| A9        18 |--
@@ -213,11 +213,8 @@
 #include <SmartThings.h>  //be sure you are using the library from ST_ANYTHING which has support for the Arduino Mega
 #include <Event.h>
 #include <Timer.h>
-#define PIN_THING_RX    10
-#define PIN_THING_TX    2
-#define PIN_THING_LED  13
 SmartThingsCallout_t messageCallout;    // call out function forward decalaration
-SmartThings smartthing(PIN_THING_RX, PIN_THING_TX, messageCallout);  // constructor
+SmartThings smartthing(HW_SERIAL3, messageCallout);  // constructor

 //user configurable global variables to set before loading to Arduino
 int relays = 16;  //set up before loading to Arduino (max = 16 with current code and assumes last relay is a master valve/pump actuator)
@@ -240,8 +237,8 @@
 //initialize pump related variables.
 int pin4Relay = 4;  //pin4 reserved for optional additional relay to control a pump or master valve
 boolean isConfigPump = false; // if true, relay16 is used as the pump/master valve switch.  Can be toggled by device tye v2.7 and later
-char* configPumpStatus = "off";
-char* pin4PumpStatus= "off";
+const char* configPumpStatus = "off";
+const char* pin4PumpStatus= "off";
 boolean doUpdate = false;
 boolean doPumpUpdate = false;


Testing blinking LED at polling

Testing blinking LED at polling

--- module/module.ino
+++ module/module.ino
@@ -170,8 +170,9 @@
 	while (1) {
 		// Polling logic (approximately every second)
 		sendCommand(CMD_GET_SNR, blockID, machineID, keyA, NULL);
-		// if card is missing, increment a counter
+		// if card is missing, increment a counter and blink LED
 		if (!getResponse(serialNumber)) {
+			digitalWrite(ledPin, (digitalRead(ledPin) == HIGH ? LOW : HIGH));
 			pollCounter += 1;
 			// if the counter reaches a specified timeout, return
 			if (pollCounter == pollTimeout) {
@@ -190,6 +191,7 @@
 			}
 		}
 		else {
+			digitalWrite(ledPin, HIGH);
 			pollCounter = 0;
 		}
 		// End Polling Logic


Motor speed tweaks

Motor speed tweaks

--- fed-arduino/fed-arduino.ino
+++ fed-arduino/fed-arduino.ino
@@ -37,7 +37,7 @@
 File dataFile;

 const int MOTOR_STEPS_PER_REVOLUTION = 513;
-const int STEPS_TO_INCREMENT = 64;
+const int STEPS_TO_INCREMENT = 32;
 Adafruit_MotorShield gMotorShield = Adafruit_MotorShield();
 Adafruit_StepperMotor *motor1 = gMotorShield.getStepper(MOTOR_STEPS_PER_REVOLUTION,1);
 Adafruit_StepperMotor *motor2 = gMotorShield.getStepper(MOTOR_STEPS_PER_REVOLUTION,2);
@@ -67,8 +67,8 @@

   //motor shield stuff
   gMotorShield.begin();
-  motor1->setSpeed(20);
-  motor2->setSpeed(20);
+  motor1->setSpeed(12);
+  motor2->setSpeed(2);

   //SD card init stuff
   Wire.begin();
@@ -160,7 +160,7 @@
     Serial.print(String(inputNum + 1));
     Serial.println(F("..."));
     moveMotor(inputNum);
-    delay(350);
+    delay(500);
   }

   else if (PIStates[inputNum] == 0 & PIStates[inputNum] != lastStates[inputNum]) {
@@ -256,13 +256,13 @@
     power_twi_enable();
     if (motorNum == 0)
     {
-      motor1->step(STEPS_TO_INCREMENT/2,BACKWARD,DOUBLE);
+      motor1->step(STEPS_TO_INCREMENT/3,BACKWARD,DOUBLE);
       motor1->step(STEPS_TO_INCREMENT,FORWARD,DOUBLE);
       motor1->release();
     }
     else if (motorNum == 1)
     {
-      motor2->step(STEPS_TO_INCREMENT/2,BACKWARD,DOUBLE);
+      motor2->step(STEPS_TO_INCREMENT/3,BACKWARD,DOUBLE);
       motor2->step(STEPS_TO_INCREMENT,FORWARD,DOUBLE);
       motor2->release();
     }


define to const; organize

define to const; organize

--- computer_box/computer_box.ino
+++ computer_box/computer_box.ino
@@ -3,19 +3,18 @@

 #include <DHT.h>

-#define DHTPIN 3 // DHT Temp & Humidity Pin
 #define DHTTYPE DHT22   // DHT 22  (AM2302)

-int ac_probe = 0;
-int dc_probe = 1;
+const int dht_pin = 3; // DHT Temp & Humidity Pin
+const int ac_probe = 0;
+const int dc_probe = 1;
+const int fan_pin = 4;
+const int ds18_01_pin = 2;

-int led_pin = 13;
+const int num_ds18 = 3; // Number of DS18B20 Sensors
+
 int led_value = LOW;

-int fan_pin = 4;
-
-int ds18_01_pin = 2;
-const int num_ds18 = 3; // Number of DS18B20 Sensors
 uint8_t sensors_address[num_ds18][8]; //here will store the sensors addresses for later use

 // Temperature chip I/O
@@ -23,13 +22,13 @@
 float get_ds18b20_temp (uint8_t *address);

 // Setup DHT22
-DHT dht(DHTPIN, DHTTYPE);
+DHT dht(dht_pin, DHTTYPE);

 void setup() {
   Serial.begin(9600);
   Serial.flush();

-  pinMode(led_pin, OUTPUT);
+  pinMode(LED_BUILTIN, OUTPUT);
   pinMode(ds18_01_pin, OUTPUT);
   pinMode(fan_pin, OUTPUT);

@@ -62,7 +61,7 @@

       switch(pin_num){
         case fan_pin:
-        case led_pin:
+        case LED_BUILTIN:
           digitalWrite(pin_num, pin_status);
           break;
       }
@@ -133,8 +132,8 @@
   }
 }

-void read_fan_status(4) {
-  int fan_status digitalRead(fan_pin);
+void read_fan_status() {
+  int fan_status = digitalRead(fan_pin);

   Serial.print("\"fan\":"); Serial.print(fan_status); Serial.print(',');
 }
@@ -170,7 +169,7 @@

 void toggle_led() {
   led_value = ! led_value;
-  digitalWrite(led_pin, led_value);
+  digitalWrite(LED_BUILTIN, led_value);
 }

 void turn_fan_on() {


swag drag and droop

swag drag and droop

--- mouse/mouse.ino
+++ mouse/mouse.ino
@@ -1,22 +1,50 @@
 #include <Mouse.h>

-boolean click = false;
+enum states {
+  NO_CLICK,
+  CLICK,
+  HOLD,
+  DRAG,
+  RELEASE,
+};
+
+enum states state = NO_CLICK;

 void setup() {
   Serial.begin(9600);
+  Mouse.begin();
   attachInterrupt(digitalPinToInterrupt(2), interrupt, RISING);
 }

 void loop() {
-  if (click) {
-    Mouse.click();
-    click = false;
+  switch(state) {
+    case CLICK:
+      Mouse.click();
+      state = NO_CLICK;
+      break;
+    case HOLD:
+      Mouse.press();
+      state = DRAG;
+      break;
+    case RELEASE:
+      Mouse.release();
+      state = NO_CLICK;
+      break;
   }
 }

 void interrupt() {
   detachInterrupt(digitalPinToInterrupt(2));
-  click = true;
+  switch(state) {
+    case NO_CLICK:
+      state = CLICK;
+      break;
+    case CLICK:
+      state = HOLD;
+      break;
+    case DRAG:
+      state = RELEASE;
+  }
   attachInterrupt(digitalPinToInterrupt(2), interrupt, RISING);
 }


implementa método para tratar callback da mudança de status do ar

--- arduino/casa_inteligente/casa_inteligente.ino
+++ arduino/casa_inteligente/casa_inteligente.ino
@@ -27,7 +27,7 @@
 #define USUARIO_MQTT "mdzjtvif"
 #define SENHA_MQTT "snX5gG5TJs8P"

-void callback(char* topic, byte* payload, unsigned int length) {}
+void callback(char* topic, byte* payload, unsigned int length);

 PubSubClient client(server, PORTA_MQTT, callback, ethClient);

@@ -78,8 +78,19 @@
   {
     conectar_mosquitto();
   }
+  client.loop();
   ler_temperatura();
   Narcoleptic.delay(5000);
+}
+
+void callback(char* topic, byte* payload, unsigned int length) {
+  Serial.print("Message arrived [");
+  Serial.print(topic);
+  Serial.print("] ");
+  for (int i=0;i<length;i++) {
+    Serial.print((char)payload[i]);
+  }
+  Serial.println();
 }

@@ -129,20 +140,19 @@

 // Métodos auxiliares
-
+
 void conectar_mosquitto() {
-//  client.setServer(server, PORTA_MQTT);

   while (!client.connected()) {
     Serial.print("Conectando com mosquitto broker...");
-    if (client.connect("casa", "mdzjtvif", "snX5gG5TJs8P")) {
-//    if (client.connect("casa")) {
+    if (client.connect("casa", USUARIO_MQTT, SENHA_MQTT)) {
       Serial.println(" conectado!");
+      client.subscribe("casa/ar/status");
     } else {
       Serial.print("falha, rc=");
       Serial.println(client.state());
+      delay(TEMPO_NOVA_TENTATIVA);
     }
-    delay(TEMPO_NOVA_TENTATIVA);
   }
 }


Turn of flashing light once game starts

Turn of flashing light once game starts

--- bolt-arduino.ino
+++ bolt-arduino.ino
@@ -28,12 +28,10 @@

   led_setState(0, LED_STATE_FLASHING);
   button_wait(0);
+  led_setState(0, LED_STATE_OFF);

   game_start();
   logger(LOGGER_TYPE_INFO, "main", "Program done");
-
 }

-void loop() {
-
-}
+void loop() {}


Move procedure to setup

Move procedure to setup

--- bolt-arduino.ino
+++ bolt-arduino.ino
@@ -22,13 +22,18 @@
   flasher_setup();
   clock_setup();
   logger(LOGGER_TYPE_INFO, "main", "Setup done");
-}

-void loop() {
+  //Starting procedure
   screen_display("READY");

   led_setState(0, LED_STATE_FLASHING);
   button_wait(0);

   game_start();
+  logger(LOGGER_TYPE_INFO, "main", "Program done");
+
 }
+
+void loop() {
+
+}


WIP. added methods for firing timed events

--- src/kite_flag/kite_flag.ino
+++ src/kite_flag/kite_flag.ino
@@ -46,6 +46,36 @@
 }

+
+int getTimeout(long timestamp, int timeout_ms) {
+  return ! (timestamp % timeout_ms);
+}
+
+void fireTimedEvents(long timestamp) {
+
+  static long lastTimestamp = 0;
+  // run the countdown
+  if(lastTimestamp != timestamp) {
+    lastTimestamp = timestamp;
+
+    if(getTimeout(timestamp, 1000)){
+      Serial.println("1 second timeout");
+    }
+
+    if(getTimeout(timestamp, 3000)){
+      Serial.println("3 second timeout");
+    }
+
+    if(getTimeout(timestamp, 5000)){
+      Serial.println("5 second timeout");
+    }
+
+  }
+}
+
+
+
+
 /*
   on startup:
   run motor until the red flag is showing
@@ -57,6 +87,8 @@
 */
 void loop()
 {
+  fireTimedEvents(millis());
+  return;
   horn_demo();
   long cycle_time_ms = getCycleTime();


Now using writeMicroseconds

Now using writeMicroseconds

--- craniosacral/craniosacral.ino
+++ craniosacral/craniosacral.ino
@@ -10,21 +10,21 @@

 // 2 - 2.5 cycles per minute
 unsigned long midtide_last = 0;
-unsigned long midtide_interval = 150; //135000;
+unsigned long midtide_interval = 28;
 byte midtide_direction = 1;
-byte midtide_pos = 45;
+long midtide_pos = 1750;

 // 100 secs per cycle
 unsigned long longtide_last = 0;
-unsigned long longtide_interval = 500;
+unsigned long longtide_interval = 50;
 byte longtide_direction = 1;
-byte longtide_pos = 45;
+long longtide_pos = 1750;

 // 8 - 14 cycles per minute
 unsigned long cri_last = 0;
-unsigned long cri_interval = 26; //600000;
+unsigned long cri_interval = 4;
 byte cri_direction = 1;
-byte cri_pos = 45;
+long cri_pos = 1750;

 void setup()
 {
@@ -37,7 +37,7 @@

 void loop()
 {
-
+  //midtide.writeMicroseconds(1250);
   unsigned long now = millis();

   // mid tide
@@ -45,16 +45,16 @@
     midtide_last = now;
     if (midtide_direction) {
       midtide_pos++;
-      if (midtide_pos <= 135) {
-        midtide.write(midtide_pos);
+      if (midtide_pos <= 1750) {
+        midtide.writeMicroseconds(midtide_pos);
       } else {
         midtide_direction = !midtide_direction;
       }
     }
     if (!midtide_direction) {
       midtide_pos--;
-      if (midtide_pos >= 45) {
-        midtide.write(midtide_pos);
+      if (midtide_pos >= 1250) {
+        midtide.writeMicroseconds(midtide_pos);
       } else {
         midtide_direction = !midtide_direction;
       }
@@ -66,16 +66,16 @@
     longtide_last = now;
     if (longtide_direction) {
       longtide_pos++;
-      if (longtide_pos <= 135) {
-        longtide.write(longtide_pos);
+      if (longtide_pos <= 1750) {
+        longtide.writeMicroseconds(longtide_pos);
       } else {
         longtide_direction = !longtide_direction;
       }
     }
     if (!longtide_direction) {
       longtide_pos--;
-      if (longtide_pos >= 45) {
-        longtide.write(longtide_pos);
+      if (longtide_pos >= 1250) {
+        longtide.writeMicroseconds(longtide_pos);
       } else {
         longtide_direction = !longtide_direction;
       }
@@ -87,16 +87,16 @@
     cri_last = now;
     if (cri_direction) {
       cri_pos++;
-      if (cri_pos <= 135) {
-        cri.write(cri_pos);
+      if (cri_pos <= 1750) {
+        cri.writeMicroseconds(cri_pos);
       } else {
         cri_direction = !cri_direction;
       }
     }
     if (!cri_direction) {
       cri_pos--;
-      if (cri_pos >= 45) {
-        cri.write(cri_pos);
+      if (cri_pos >= 1250) {
+        cri.writeMicroseconds(cri_pos);
       } else {
         cri_direction = !cri_direction;
       }


Added motor control

Added motor control

Minor issues with lcd in this version

--- fed-arduino_V3/fed-arduino_V3.ino
+++ fed-arduino_V3/fed-arduino_V3.ino
@@ -10,6 +10,7 @@
 #include <avr/io.h>
 #include <SoftwareSerial.h>
 #include <Adafruit_MotorShield.h>
+#include <Stepper.h>

 #define PHOTO_INTERRUPTER_PIN_1 2
 #define PHOTO_INTERRUPTER_PIN_2 3
@@ -160,9 +161,8 @@
     Serial.print(F("Replacing pellet #"));
     Serial.print(String(inputNum + 1));
     Serial.println(F("..."));
-    //moveMotor(inputNum);
-    //motor1->step(99900,FORWARD,DOUBLE);
-    delay(200);
+    moveMotor(inputNum);
+    delay(500);
   }

   else if (PIStates[inputNum] == 0 & PIStates[inputNum] != lastStates[inputNum]) {
@@ -210,6 +210,7 @@

 void updateDisplay()
 {
+  Serial.println("aaa");
   clearDisplay();
   delay(2);
   if (pelletCount[0] % 100 < 10)
@@ -256,11 +257,17 @@
 void moveMotor(int motorNum)
 {
     power_twi_enable();
-    Adafruit_StepperMotor *motor;
-    if (motorNum = 0) { motor = motor1; }
-    else if (motorNum = 1) { motor = motor2; }
-    motor->step(STEPS_TO_INCREMENT/2,FORWARD,DOUBLE);
-    motor->step(STEPS_TO_INCREMENT,BACKWARD,DOUBLE);
-    motor->release();
+    if (motorNum == 0)
+    {
+      motor1->step(STEPS_TO_INCREMENT/2,FORWARD,DOUBLE);
+      motor1->step(STEPS_TO_INCREMENT,BACKWARD,DOUBLE);
+      motor1->release();
+    }
+    else if (motorNum == 1)
+    {
+      motor2->step(STEPS_TO_INCREMENT/2,FORWARD,DOUBLE);
+      motor2->step(STEPS_TO_INCREMENT,BACKWARD,DOUBLE);
+      motor2->release();
+    }
     power_twi_disable();
-} //*/
+}


Fixed syntax error

Fixed syntax error

Added missing parenthesis

--- bundles/binding/org.openhab.binding.nibeheatpump/NibeGW/NibeGW.ino
+++ bundles/binding/org.openhab.binding.nibeheatpump/NibeGW/NibeGW.ino
@@ -302,7 +302,7 @@

               // check special case, if checksum is 0x5C (start character),
               // heat pump seems to send 0xC5 checksum
-              if (checksum != 0x5C && msg_checksum != 0xC5
+              if (checksum != 0x5C && msg_checksum != 0xC5)
                 return -2;
             }


[Firmware] Better log messages

[Firmware] Better log messages

--- firmware/lm-wifilamp/x10_wifi.ino
+++ firmware/lm-wifilamp/x10_wifi.ino
@@ -45,7 +45,7 @@
   if (WiFi.getAutoConnect()) WiFi.setAutoConnect(false);
   if (WiFi.getMode() != WIFI_STA) WiFi.mode(WIFI_STA);

-  logInfo("Connecting...");
+  logInfo("Connecting to WiFi...");
   blinkerStart(BLINKER_STATE_CONNECTING);
   wifiGotIpFlag = false;

@@ -53,7 +53,7 @@
     // this executes when module reconnects and gets IP from DHCP
     // can be called multiple times
     wifiGotIpFlag = true;
-    logInfo("Connected successfuly");
+    logInfo("WiFi connected successfuly");
     logValue("Got IP: ", evt.ip);
   });


use ascii 10 instead of 255 as separator

--- Deploy/rootfolder/sketches/SimpleProtocol/SimpleProtocol.ino
+++ Deploy/rootfolder/sketches/SimpleProtocol/SimpleProtocol.ino
@@ -54,7 +54,7 @@
     if (Serial.available()) {
       // something to read
       lastRead = Serial.read();
-      if (lastRead == 255) {
+      if (lastRead == '\r') {
         break; // when we get a divider message, break out of loop
       } else {
         // add it to the inputString:


Update PulseSensorAmped_Arduino_1dot4.ino

--- PulseSensorAmped_Arduino_1dot4/PulseSensorAmped_Arduino_1dot4.ino
+++ PulseSensorAmped_Arduino_1dot4/PulseSensorAmped_Arduino_1dot4.ino
@@ -49,7 +49,6 @@
   if (QS == true){     // A Heartbeat Was Found
                        // BPM and IBI have been Determined
                        // Quantified Self "QS" true when arduino finds a heartbeat
-        digitalWrite(blinkPin,HIGH);     // Blink LED, we got a beat.
         fadeRate = 255;         // Makes the LED Fade Effect Happen
                                 // Set 'fadeRate' Variable to 255 to fade LED with pulse
         serialOutputWhenBeatHappens();   // A Beat Happened, Output that to serial.


Update RemoteControl.ino

Update RemoteControl.ino

--- remote-control-by-phone/RemoteControl.ino
+++ remote-control-by-phone/RemoteControl.ino
@@ -20,7 +20,7 @@
 // Note that for additional security and reusability, you could
 // use #define statements to specify these values in a .h file.

-// you NEXMO API key & secret
+// your NEXMO API key & secret
 const String NEXMO_API_KEY = "xxxxxxxxx";
 const String NEXMO_API_SECRET = "xxxxxxxxx";


ReadSensors now reads all data pins and crossbar's the ones needed. It is currently configured as a 1 bit reader. Comments in code show how to turn it into an 8 bit reader.

--- ReadSensors/ReadSensors.ino
+++ ReadSensors/ReadSensors.ino
@@ -139,10 +139,9 @@
 {
   //readPins
   byte freg = (digitalRead(REG) ? REG_PAPER : REG_HOLE);
-  //TODO: read from PORTB as a single byte
-  //TODO: run through crossbar if pins need remapping
-  byte now  = (digitalRead(D7)  ? ALL_PAPER : ALL_HOLES);
-
+  //byte now  = (digitalRead(D7)  ? ALL_PAPER : ALL_HOLES);
+  byte now = crossbar(readdata());
+
   // Show live diagnostics on LEDs
   writeLEDs(freg, now);

@@ -329,6 +328,24 @@

 //------------------------------------------------------------------------------------------------
+// Read data from the data pins
+
+byte readdata(void)
+{
+  byte data = 0;
+  if (digitalRead(D7)) data |= 1<<7;
+  if (digitalRead(D6)) data |= 1<<6;
+  if (digitalRead(D5)) data |= 1<<5;
+  if (digitalRead(D4)) data |= 1<<4;
+  if (digitalRead(D3)) data |= 1<<3;
+  if (digitalRead(D2)) data |= 1<<2;
+  if (digitalRead(D1)) data |= 1<<1;
+  if (digitalRead(D0)) data |= 1<<0;
+  return data;
+}
+
+
+//------------------------------------------------------------------------------------------------

 byte crossbar(byte xin) //TODO pass in cross bar config to allow more than one?? pgmspace??
 {