Fix #97

Fix #97

--- examples/Widgets/LED/LED.ino
+++ examples/Widgets/LED/LED.ino
@@ -18,7 +18,7 @@
  * App project setup:
  *   LED widget on V1
  *   LED widget on V2
- *
+ *   LED widget on V3
  *
  * WARNING :
  * For this example you'll need SimpleTimer library:
@@ -38,8 +38,12 @@
 // Go to the Project Settings (nut icon).
 char auth[] = "YourAuthToken";

+// Select your pin with physical button
+const int btnPin = 7;
+
 WidgetLED led1(V1);
 WidgetLED led2(V2);
+WidgetLED led3(V3);

 SimpleTimer timer;

@@ -48,14 +52,19 @@
   Serial.begin(9600); // See the connection status in Serial Monitor
   Blynk.begin(auth);

+  // Setup physical button pin (active low)
+  pinMode(btnPin, INPUT_PULLUP);
+
   while (Blynk.connect() == false) {
     // Wait until connected
   }

   timer.setInterval(1000L, blinkLedWidget);
-  timer.setInterval(200L, fadeLedWidget);
+  timer.setInterval(300L, fadeLedWidget);
+  timer.setInterval(500L, buttonLedWidget);
 }

+// V1 LED Widget is blinking
 void blinkLedWidget()
 {
   if (led1.getValue()) {
@@ -67,10 +76,11 @@
   }
 }

+// V2 LED Widget is fading
 void fadeLedWidget()
 {
   static int value = 0;
-  static int delta = 20;
+  static int delta = 30;
   value += delta;
   if (value > 255 || value < 0) {
     delta = -delta;
@@ -80,8 +90,27 @@
   }
 }

+// V3 LED Widget represents the physical button state
+boolean btnState = false;
+void buttonLedWidget()
+{
+  // Read button
+  boolean isPressed = (digitalRead(btnPin) == LOW);
+
+  // If state has changed...
+  if (isPressed != btnState) {
+    if (isPressed) {
+      led3.on();
+    } else {
+      led3.off();
+    }
+    btnState = isPressed;
+  }
+}
+
 void loop()
 {
   Blynk.run();
   timer.run();
 }
+


Main program limit pins configured

Main program limit pins configured

--- src/TenazAyuda.ino
+++ src/TenazAyuda.ino
@@ -46,15 +46,15 @@
  *                                    LIMITES DE CARRERA                                 *
  * ***************************************************************************************/

-DigitalInput limitASoftStopBase(UP_BUTTON, BUTTON_INTERRUPTS_COOLDOWN);
-DigitalInput limitAHardStopBase(UP_BUTTON, BUTTON_INTERRUPTS_COOLDOWN);
-DigitalInput limitBSoftStopBase(UP_BUTTON, BUTTON_INTERRUPTS_COOLDOWN);
-DigitalInput limitBHardStopBase(UP_BUTTON, BUTTON_INTERRUPTS_COOLDOWN);
+DigitalInput limitASoftStopBase(MOTOR_BASE_LIMIT_A_SOFT_STOP, BUTTON_INTERRUPTS_COOLDOWN);
+DigitalInput limitAHardStopBase(MOTOR_BASE_LIMIT_A_HARD_STOP, BUTTON_INTERRUPTS_COOLDOWN);
+DigitalInput limitBSoftStopBase(MOTOR_BASE_LIMIT_B_SOFT_STOP, BUTTON_INTERRUPTS_COOLDOWN);
+DigitalInput limitBHardStopBase(MOTOR_BASE_LIMIT_B_HARD_STOP, BUTTON_INTERRUPTS_COOLDOWN);

-DigitalInput limitASoftStopRotador(UP_BUTTON, BUTTON_INTERRUPTS_COOLDOWN);
-DigitalInput limitAHardStopRotador(UP_BUTTON, BUTTON_INTERRUPTS_COOLDOWN);
-DigitalInput limitBSoftStopRotador(UP_BUTTON, BUTTON_INTERRUPTS_COOLDOWN);
-DigitalInput limitBHardStopRotador(UP_BUTTON, BUTTON_INTERRUPTS_COOLDOWN);
+DigitalInput limitASoftStopRotador(MOTOR_ROTADOR_LIMIT_A_SOFT_STOP, BUTTON_INTERRUPTS_COOLDOWN);
+DigitalInput limitAHardStopRotador(MOTOR_ROTADOR_LIMIT_A_HARD_STOP, BUTTON_INTERRUPTS_COOLDOWN);
+DigitalInput limitBSoftStopRotador(MOTOR_ROTADOR_LIMIT_B_SOFT_STOP, BUTTON_INTERRUPTS_COOLDOWN);
+DigitalInput limitBHardStopRotador(MOTOR_ROTADOR_LIMIT_B_HARD_STOP, BUTTON_INTERRUPTS_COOLDOWN);

 /* ***************************************************************************************
  *                                        ACTIONS                                        *
@@ -143,12 +143,12 @@

 void loop() {
   // temporal
-  if (cyclesCount % 100 == 0) {
+  //if (cyclesCount % 100 == 0) {
     statedChanged = true;
-    cyclesCount = 0;
-  } else {
-    cyclesCount++;
-  }
+  //  cyclesCount = 0;
+  //} else {
+  //  cyclesCount++;
+  //}
   // -----------

   if (statedChanged) {


use the pin definition, not hard coded.

use the pin definition, not hard coded.

--- Grove_Dust_Sensor.ino
+++ Grove_Dust_Sensor.ino
@@ -23,7 +23,7 @@
 void setup()
 {
     Serial.begin(9600);
-    pinMode(8,INPUT);
+    pinMode(pin,INPUT);
     starttime = millis();//get the current time;
 }


Change LCD pins to not conflict with the can bus

--- Event_Printer/Event_Printer.ino
+++ Event_Printer/Event_Printer.ino
@@ -29,8 +29,8 @@

 /* TFT Pin Defines */
 #define TFT_CS     10
-#define TFT_RST    9
-#define TFT_DC     8
+#define TFT_RST    7
+#define TFT_DC     4

 /* Globals */
 MCP_CAN CAN(9);


This commit fixes where the AM/PM wouldn't show

--- TinyScreenClockAndDisplay/TinyScreenClockAndDisplay.ino
+++ TinyScreenClockAndDisplay/TinyScreenClockAndDisplay.ino
@@ -192,12 +192,11 @@
     display.print("0");
   }
   display.print(minute);
+  display.setFont(liberationSans_12ptFontInfo);
   if (hour > 12) {
-  display.fontColor(WHITE,BLACK);
   display.print(" AM");
   }
   else {
-    display.fontColor(WHITE,BLACK);
     display.print(" PM");
   }
 }


Swapped servo increment/decment functions

--- ir_control_trinket/ir_control_trinket.ino
+++ ir_control_trinket/ir_control_trinket.ino
@@ -116,12 +116,12 @@

 void fullLeft(){
       pf.single_pwm(TURN,PWM_REV6);
-      pf.single_increment(TURN,false);
+      pf.single_decrement(TURN);
 }

 void fullRight(){
       pf.single_pwm(TURN,PWM_FWD6);
-      pf.single_increment(TURN,true);
+      pf.single_increment(TURN);
 }

 unsigned long LapCompensate(unsigned long time){


COH-78: WIP

COH-78: WIP

--- COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
+++ COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
@@ -1,6 +1,9 @@
 // Uncomment exactly one of the following CONFIG_... lines to select which board is being built for.
 #define CONFIG_Trial2013Winter_Round2_CC1HUB // REV2 cut4 as CC1 hub.
 //#define CONFIG_REV9 // REV9 as CC1 relay, cut 2 of the board.
+
+// IF DEFINED: entire comms model switches to secure.
+//#define ENABLE_OTSECUREFRAME_ENCODING_SUPPORT

 #define DEBUG // Uncomment for debug output.

@@ -870,18 +873,32 @@
 // With care (not accessing EEPROM for example) this could also reject anything with wrong house code.
 static bool FilterRXISR(const volatile uint8_t *buf, volatile uint8_t &buflen)
   {
+#ifndef ENABLE_OTSECUREFRAME_ENCODING_SUPPORT
   if((buflen < 8) || (OTRadioLink::FTp2_CC1PollAndCmd != buf[0])) { return(false); }
   // TODO: filter for only this unit address/housecode as FHT8V.getHC{1,2}() are thread-safe.
+#else
+  // Expect secure frame with 2-byte ID and empty body.
+  if((buflen < 29) || ((0x80|OTRadioLink::FTp2_CC1PollAndCmd) != buf[0])) { return(false); }
+  // TODO: filter for only this unit address/housecode as FHT8V.getHC{1,2}() are thread-safe.
+#endif // ENABLE_OTSECUREFRAME_ENCODING_SUPPORT
   return(true); // Accept message.
   }
 #elif defined(ALLOW_CC1_SUPPORT_HUB)
 // For a CC1 hub, ignore everything except FTp2_CC1Alert and FTp2_CC1PollResponse messages.
 static bool FilterRXISR(const volatile uint8_t *buf, volatile uint8_t &buflen)
   {
+#ifndef ENABLE_OTSECUREFRAME_ENCODING_SUPPORT
   if(buflen < 8) { return(false); }
   const uint8_t t = buf[0];
   if((OTRadioLink::FTp2_CC1Alert != t) && (OTRadioLink::FTp2_CC1PollResponse != t)) { return(false); }
   // TODO: filter for only associated relay address/housecodes.
+#else
+  // Expect secure frame with 2-byte ID and 32-byte encrypted body.
+  if(buflen < 63) { return(false); }
+  const uint8_t t = buf[0];
+  if(((0x80|OTRadioLink::FTp2_CC1Alert) != t) && ((0x80|OTRadioLink::FTp2_CC1PollResponse) != t)) { return(false); }
+  // TODO: filter for only associated relay address/housecodes.
+#endif // ENABLE_OTSECUREFRAME_ENCODING_SUPPORT
   return(true); // Accept message.
   }
 #endif


Minor comments added

Minor comments added

--- VernierMousetrap/VernierMousetrap.ino
+++ VernierMousetrap/VernierMousetrap.ino
@@ -7,8 +7,9 @@
 connector.

 This sketch will continuously check the photogate and start the stepper
-motor rotating when the photogate is blocked.
-
+motor rotating when the photogate is blocked. External power must be supplied
+to the DCU to drive the stepper motor.
+
 See www.vernier.com/arduino for more information.
  */

@@ -88,7 +89,7 @@
     } ;//end of for
 };// end of Step

-void DCU (int output)
+void DCU (int output) //DCU segment
 {
   switch (output)
   {


atduino code done!

atduino code done!

--- WeMos/httpConnector/httpConnector.ino
+++ WeMos/httpConnector/httpConnector.ino
@@ -34,7 +34,7 @@
 typedef struct {
     String identifier;
     float value;
-    String databaseId;
+    int databaseId;
 } Sensor;

 // This is for the ESP8266 processor on ESP-01
@@ -59,8 +59,10 @@
   dht.begin();

   for (index = 0; index < MAX_SENSOR_COUNT; index++){
+      char sensorId[2];
       Sensor sensor;
-      sensor.identifier = "S" + index;
+      sprintf(sensorId, "S%i",index);
+      sensor.identifier = sensorId;
       // initalise to -1 to give it a value which will never succeed
       sensor.databaseId = -1;

@@ -112,7 +114,8 @@
         Serial.print("IP Addr:  ");
         Serial.println(WiFi.localIP());

-        ip = ""+WiFi.localIP();
+        char buffer[16];
+        ip = WiFi.localIP().toString();

         Serial.print("Status: ");
         Serial.println(WiFi.status());
@@ -184,7 +187,7 @@
  * @return body: the filled/generated json body
  */
 String generateBody(float value){
-  StaticJsonBuffer<200> jsonBuffer;
+  StaticJsonBuffer<400> jsonBuffer;
   JsonObject& root = jsonBuffer.createObject();

   root["value"] = value;
@@ -198,28 +201,28 @@
 String generateRegister(String ip, String identifier){
     int index;

-  StaticJsonBuffer<200> jsonBuffer;
-  JsonObject& root = jsonBuffer.createObject();
-
-  JsonArray& sensors = root.createNestedArray("sensors");
-  for(index = 0; index < MAX_SENSOR_COUNT; index++){
-      sensors.add(sensorsList[index].identifier);
-  }
-
-  root["sensors"] = sensors;
-  root["ip"] = ip;
-
-  char buffer[256];
-  root.printTo(buffer);
-
-  return buffer;
+    StaticJsonBuffer<400> jsonBuffer;
+    JsonObject& root = jsonBuffer.createObject();
+
+    JsonArray& sensors = root.createNestedArray("sensors");
+    for(index = 0; index < MAX_SENSOR_COUNT; index++){
+        sensors.add(sensorsList[index].identifier);
+    }
+
+    root["sensors"] = sensors;
+    root["ip"] = ip;
+
+    char buffer[256];
+    root.printTo(buffer);
+
+    return buffer;
 }

 /*
  * Check if response is valid and no errors are returned (like device blocked)
  */
 boolean errorInResponse(String response){
-  StaticJsonBuffer<200> jsonBuffer;
+  StaticJsonBuffer<400> jsonBuffer;
   JsonObject& root = jsonBuffer.parseObject(response);
   if (!root.success()){
     return true;
@@ -233,34 +236,48 @@
 /*
  * Register device at server
  */
-boolean registerDevice(){
-    Serial.println(generateRegister(ip, identifier));
-    String response = httpRequestPost(server + "/register", generateRegister(ip, identifier));
-
+boolean registerDevice(String body){
+
+    // char buffer[100];
+    // sprintf(buffer, "http://192.168.42.1:3000/register", server);
+
+    String response = httpRequestPost(server + "/register", body);
+
+    Serial.println("Checking register response");
     if(response != HTTP_ERROR_RESPONSE && !errorInResponse(response)){
+        Serial.println("Parsing response");
+
         // Set the databaseid's for the sensors
-        StaticJsonBuffer<200> jsonBuffer;
+        StaticJsonBuffer<400> jsonBuffer;
         JsonObject& root = jsonBuffer.parseObject(response);

+        Serial.println("Response size:");
+        Serial.println(response.length());
+
+        if(root.success()){
+            Serial.println("It's not the json");
+        } else{
+            Serial.println("It might be the json");
+        }
         if(root.success() && root.containsKey("found")){
             int index;

-            Serial.println("REGISTER:\n" + response);
-
-            char buffer[256];
-            root["found"].printTo(buffer);
-            JsonArray& jsonArray = jsonBuffer.parseArray(buffer);
+            // Serial.println("REGISTER:\n" + response);
+            Serial.println("REGISTERED succesfully!");
+            Serial.println(response);

             for(index = 0; index < MAX_SENSOR_COUNT; index++){
-                const char* jsonId = jsonArray[index]["ID"];
-                sensorsList[index].databaseId = jsonId;
+                // JsonArray& array = root['found'];
+                sensorsList[index].databaseId = root["found"][index]["database_id"];
             }

             return true;
         }
     }
+    Serial.println("Delay");
     delay(1000);
-    return registerDevice();   //retry recursive
+    Serial.println("Retrying register, recursively");
+    return registerDevice(body);   //retry recursive
 }

 /*
@@ -269,12 +286,14 @@
  * @return response: the response from the server or HTTP_ERROR_RESPONSE when failed! (REQUEST_FAILED)
 */
 String sendSensorData(Sensor sensor){
-    String sensorName = "/sensor/" + sensor.databaseId;
+    char buffer[100];
+    sprintf(buffer, "/sensor/%i", sensor.databaseId);
+    // Serial.println(buffer);

     if(isnan(sensor.value)){
       return "NAN value";
     }
-    return httpRequestPost(server + sensorName, generateBody(sensor.value));
+    return httpRequestPost(server + buffer, generateBody(sensor.value));
 }

 void setup() {
@@ -285,10 +304,12 @@
         Serial.println("Retrying connecion...");
     }
     initSensors();
-    registerDevice();
+    registerDevice(generateRegister(ip, identifier));
+    Serial.println("Done registering!");
 }

 void loop() {
+    Serial.println("loop!");
     int index;

     // Update the value in the sensors


moved some pins around for simplicity, new startup/shutdown animations, initial crack at cyclotron animation

see https://www.youtube.com/watch?v=2o-0Lq8c1x0 for demo of current
code. This is initial still and has not been optimized

--- Arduino/Neutrino_Wand/Neutrino_Wand.ino
+++ Arduino/Neutrino_Wand/Neutrino_Wand.ino
@@ -11,18 +11,19 @@
 #define LOW  0x0

 // neopixel pins
-#define NEO_NOSE 9 // for nose of wand
+#define NEO_NOSE 3 // for nose of wand
 Adafruit_NeoPixel noseJewel = Adafruit_NeoPixel(7, NEO_NOSE, NEO_GRB + NEO_KHZ800);

-#define NEO_POWER 10 // for cyclotron and powercell
-Adafruit_NeoPixel powerStick = Adafruit_NeoPixel(16, NEO_POWER, NEO_GRB + NEO_KHZ800);
+#define NEO_POWER 2 // for cyclotron and powercell
+Adafruit_NeoPixel powerStick = Adafruit_NeoPixel(44, NEO_POWER, NEO_GRB + NEO_KHZ800);

 bool powerBooted = false; // has the pack booted up
+bool poweredDown = true;

 // soundboard pins
-#define SFX_RST 2
-#define SFX_RX 3
-#define SFX_TX 4
+#define SFX_RST 10
+#define SFX_RX 11
+#define SFX_TX 12

 // setup the board with the pins
 SoftwareSerial ss = SoftwareSerial(SFX_TX, SFX_RX);
@@ -85,11 +86,12 @@

   // configure nose jewel
   noseJewel.begin();
+  powerStick.setBrightness(80);
   noseJewel.show(); // Initialize all pixels to 'off'

   // configure powercell/cyclotron
   powerStick.begin();
-  powerStick.setBrightness(10);
+  powerStick.setBrightness(20);
   powerStick.show(); // Initialize all pixels to 'off'

   // set the modes for the switches/buttons
@@ -133,9 +135,10 @@
 }

 /* ************* Main Loop ************* */
-int pwr_interval = 60;     // interval at which to cycle lights for the powercell. We update this in the loop to speed up the animation so must be declared here (milliseconds)
+int pwr_interval = 60;       // interval at which to cycle lights for the powercell. We update this in the loop to speed up the animation so must be declared here (milliseconds)
+int cyc_interval = 1000;      // interval at which to cycle lights for the cyclotron.
 int firing_interval = 40;    // interval at which to cycle firing lights on the bargraph. We update this in the loop to speed up the animation so must be declared here (milliseconds).
-
+bool shuttingDown = false;
 void loop() {
   // get the current time
   int currentMillis = millis();
@@ -170,7 +173,9 @@

     // choose the right powercell animation sequence for booted/on
     if ( powerBooted == true ) {
-      powerSequenceOne(currentMillis, pwr_interval);
+      poweredDown = false;
+      shuttingDown = false;
+      powerSequenceOne(currentMillis, pwr_interval, cyc_interval);
     } else {
       powerSequenceBoot(currentMillis);
     }
@@ -232,6 +237,7 @@
           if ( diff > warnWaitTime) {
             pwr_interval = 20; // speed up the powercell animation
             firing_interval = 20; // speed up the bar graph animation
+            cyc_interval = 100; // really speed up cyclotron
             if (playing == 1 || shouldWarn == false ) {
               shouldWarn = true;
               playTrack(warnTrack); // play the firing track with the warning
@@ -239,6 +245,7 @@
           } else if ( diff > dialogWaitTime) { // if we are in the dialog playing interval
             pwr_interval = 40; // speed up the powercell animation
             firing_interval = 30; // speed up the bar graph animation
+            cyc_interval = 500; // speed up cyclotron
             if (playing == 1) {
               playTrack(blastTrack); // play the normal blast track
             }
@@ -249,6 +256,7 @@
           clearFireStrobe();
           pwr_interval = 60;
           firing_interval = 40;
+          cyc_interval = 1000;
           fire = false;

           // see if we've been firing long enough to get the dialog or vent sounds
@@ -305,15 +313,20 @@
       }
     }
   } else { // if we are powering down
-    clearPowerStrip(); // clear all led's
-    shutdown_leds();
-
-    if (startup == true) { // if started reset the variables
-      startup = false;
-      safety = false;
-      fire = false;
-
-      playTrack(shutdownTrack); // play the pack shutdown track
+    if( poweredDown == false ){
+      if( shuttingDown == false ){
+        playTrack(shutdownTrack); // play the pack shutdown track
+        shuttingDown = true;
+      }
+      powerSequenceShutdown(currentMillis);
+    }else{
+      if (startup == true) { // if started reset the variables
+        clearPowerStrip(); // clear all led's
+        shutdown_leds();
+        startup = false;
+        safety = false;
+        fire = false;
+      }
     }
   }
   delay(1);
@@ -361,68 +374,238 @@
 }

 /*************** Powercell Animations *********************/
-unsigned long prevPwrBootMillis = 0;    // the last time we changed a light in the boot sequence
-const int pwr_boot_interval = 400;      // interval at which to cycle lights (milliseconds).
-unsigned long prevPwrMillis = 0;        // last time we changed a light in the idle sequence
-
-int powerSeqTotal = 16;     // total number of led's for power
-int powerBootSeqNum = 16;   // boot sequence counts down from 16
-int powerSeqNum = 0;
+int c1Start = 16;
+int c1End = 22;
+int c2Start = 23;
+int c2End = 29;
+int c3Start = 30;
+int c3End = 36;
+int c4Start = 37;
+int c4End = 44;
+
+unsigned long prevPwrBootMillis = 0;    // the last time we changed a powercell light in the boot sequence
+const int pwr_boot_interval = 41;       // interval at which to cycle lights (milliseconds).
+unsigned long prevCycBootMillis = 0;    // the last time we changed a cyclotron light in the boot sequence
+const int cyc_boot_interval = 400;      // interval at which to cycle lights (milliseconds).
+
+unsigned long prevShtdMillis = 0;       // last time we changed a light in the idle sequence
+const int pwr_shutdown_interval = 200;  // interval at which to cycle lights (milliseconds).
+
+unsigned long prevPwrMillis = 0;        // last time we changed a powercell light in the idle sequence
+unsigned long prevCycMillis = 0;        // last time we changed a cyclotron light in the idle sequence
+
+int powerSeqTotal = 15;       // total number of led's for powercell 0 based
+int currentBootLevel = -1;    // current powercell boot sequence led
+int currentLightLevel = 15;   // current powercell shutdown sequence led
+int powerSeqNum = 0;          // current running powercell sequence led
+int powerShutdownSeqNum = 15; // shutdown sequence counts down from 16

 // clears out and resets the power cell neopixel
 void clearPowerStrip() {
+  // reset vars
   powerBooted = false;
-  for ( int i = 0; i < powerSeqTotal; i++) {
+  poweredDown = true;
+  powerSeqNum = 0;
+  powerShutdownSeqNum = 15;
+  currentLightLevel = 15;
+  currentBootLevel = -1;
+
+  // shutoff the leds
+  for ( int i = 0; i <= c4End; i++) {
     powerStick.setPixelColor(i, 0);
   }
   powerStick.show();
-  powerSeqNum = 0;
-  powerBootSeqNum = 16;
-}
-
-// boot animation on the bar graph
+}
+
+bool reverseBootCyclotron = false;
+// boot animation on the powercell
 void powerSequenceBoot(int currentMillis) {
+  bool doUpdate = false;
+
+  if (currentMillis - prevCycBootMillis > cyc_boot_interval) {
+    prevCycBootMillis = currentMillis;
+
+    // START CYCLOTRON
+    if( reverseBootCyclotron == false ){
+      setCyclotronLightState(c1Start, c1End, 1);
+      setCyclotronLightState(c2Start, c2End, 2);
+      setCyclotronLightState(c3Start, c3End, 1);
+      setCyclotronLightState(c4Start, c4End, 2);
+
+      doUpdate = true;
+      reverseBootCyclotron = true;
+    }else{
+      setCyclotronLightState(c1Start, c1End, 2);
+      setCyclotronLightState(c2Start, c2End, 1);
+      setCyclotronLightState(c3Start, c3End, 2);
+      setCyclotronLightState(c4Start, c4End, 1);
+
+      doUpdate = true;
+      reverseBootCyclotron = false;
+    }
+    // END CYCLOTRON
+  }
+
   if (currentMillis - prevPwrBootMillis > pwr_boot_interval) {
     // save the last time you blinked the LED
     prevPwrBootMillis = currentMillis;

-    for ( int i = powerSeqTotal; i > 0; i--) {
-      if ( i <= powerBootSeqNum ) {
+    // START POWERCELL
+    if( currentBootLevel != powerSeqTotal ){
+      if( currentBootLevel == currentLightLevel){
+        powerStick.setPixelColor(currentBootLevel, powerStick.Color(0, 0, 150));
+        currentLightLevel = powerSeqTotal;
+        currentBootLevel++;
+      }else{
+        if(currentLightLevel+1 <= powerSeqTotal){
+          powerStick.setPixelColor(currentLightLevel+1, 0);
+        }
+        powerStick.setPixelColor(currentLightLevel, powerStick.Color(0, 0, 150));
+        currentLightLevel--;
+      }
+      doUpdate = true;
+    }else{
+      powerBooted = true;
+      currentBootLevel = -1;
+      currentLightLevel = 15;
+    }
+    // END POWERCELL
+  }
+
+  // if we have changed an led
+  if( doUpdate == true ){
+    powerStick.show(); // commit all of the changes
+  }
+}
+
+void setCyclotronLightState(int startLed, int endLed, int state ){
+  switch ( state ) {
+    case 0:
+      for(int i=startLed; i <= endLed; i++) { // red
+        powerStick.setPixelColor(i, powerStick.Color(150, 0, 0));
+      }
+      break;
+    case 1:
+      for(int i=startLed; i <= endLed; i++) { // orange
+        powerStick.setPixelColor(i, powerStick.Color(255, 106, 0));
+      }
+      break;
+    case 2:
+      for(int i=startLed; i <= endLed; i++) { // off
+        powerStick.setPixelColor(i, 0);
+      }
+      break;
+  }
+}
+
+int cyclotronFadeOut = 255;
+// shutdown animation on the powercell
+void powerSequenceShutdown(int currentMillis) {
+  if (currentMillis - prevShtdMillis > pwr_shutdown_interval) {
+    prevShtdMillis = currentMillis;
+
+    // START CYCLOTRON
+    for(int i=c1Start; i <= c4End; i++) {
+      if( cyclotronFadeOut >= 0 ){
+        powerStick.setPixelColor(i, 255 * cyclotronFadeOut/255, 0, 0);
+        cyclotronFadeOut--;
+      }else{
+        powerStick.setPixelColor(i, 0);
+      }
+    }
+    // END CYCLOTRON
+
+    // START POWERCELL
+    for ( int i = powerSeqTotal; i >= 0; i--) {
+      if ( i <= powerShutdownSeqNum ) {
         powerStick.setPixelColor(i, powerStick.Color(0, 0, 150));
       } else {
         powerStick.setPixelColor(i, 0);
       }
     }
+
     powerStick.show();
-    if ( powerBootSeqNum > 0) {
-      powerBootSeqNum--;
+
+    if ( powerShutdownSeqNum >= 0) {
+      powerShutdownSeqNum--;
     } else {
-      powerBooted = true;
-      powerBootSeqNum = 16;
-    }
-  }
-}
-
+      poweredDown = true;
+      powerShutdownSeqNum = 15;
+      cyclotronFadeOut = 255;
+    }
+    // END POWERCELL
+  }
+}
+
+int cycOrder = 0;
 // normal animation on the bar graph
-void powerSequenceOne(int currentMillis, int anispeed) {
-  powerBootSeqNum = 16;
+void powerSequenceOne(int currentMillis, int anispeed, int cycspeed) {
+  bool doUpdate = false;
+
+  if (currentMillis - prevCycMillis > cycspeed) {
+    prevCycMillis = currentMillis;
+
+    // START CYCLOTRON
+    switch ( cycOrder ) {
+      case 0:
+        setCyclotronLightState(c1Start, c1End, 0);
+        setCyclotronLightState(c2Start, c2End, 2);
+        setCyclotronLightState(c3Start, c3End, 2);
+        setCyclotronLightState(c4Start, c4End, 2);
+        cycOrder = 1;
+        break;
+      case 1:
+        setCyclotronLightState(c1Start, c1End, 2);
+        setCyclotronLightState(c2Start, c2End, 0);
+        setCyclotronLightState(c3Start, c3End, 2);
+        setCyclotronLightState(c4Start, c4End, 2);
+        cycOrder = 2;
+        break;
+      case 2:
+        setCyclotronLightState(c1Start, c1End, 2);
+        setCyclotronLightState(c2Start, c2End, 2);
+        setCyclotronLightState(c3Start, c3End, 0);
+        setCyclotronLightState(c4Start, c4End, 2);
+        cycOrder = 3;
+        break;
+      case 3:
+        setCyclotronLightState(c1Start, c1End, 2);
+        setCyclotronLightState(c2Start, c2End, 2);
+        setCyclotronLightState(c3Start, c3End, 2);
+        setCyclotronLightState(c4Start, c4End, 0);
+        cycOrder = 0;
+        break;
+    }
+
+    doUpdate = true;
+    // END CYCLOTRON
+  }
+
   if (currentMillis - prevPwrMillis > anispeed) {
     // save the last time you blinked the LED
     prevPwrMillis = currentMillis;

-    for ( int i = 0; i < powerSeqTotal; i++) {
+    // START POWERCELL
+    for ( int i = 0; i <= powerSeqTotal; i++) {
       if ( i <= powerSeqNum ) {
         powerStick.setPixelColor(i, powerStick.Color(0, 0, 150));
       } else {
         powerStick.setPixelColor(i, 0);
       }
     }
-    powerStick.show();
-    if ( powerSeqNum < powerSeqTotal) {
+
+    if ( powerSeqNum <= powerSeqTotal) {
       powerSeqNum++;
     } else {
       powerSeqNum = 0;
     }
+
+    doUpdate = true;
+    // END POWERCELL
+  }
+
+  if( doUpdate == true ){
+    powerStick.show();
   }
 }


New version of the panel

New version of the panel

--- Arduino/sketch_mar14b/sketch_mar14b.ino
+++ Arduino/sketch_mar14b/sketch_mar14b.ino
@@ -118,6 +118,67 @@

 bool debug = false;

+String getTD(String id, String value){
+return (""+value+"	");
+}
+
+void printCSS(WiFiClient client){
+client.println("");
+}
+
+void printJavascript(WiFiClient client){
+client.println("");
+}
+
+void printPanelTable(WiFiClient client) {
+  client.println("");
+  printCSS(client);
+  printJavascript(client);
+  client.println("

"+getTD("*.*","&#x21D8"));
+  for (int i=0; i<8; i++)
+    client.println(getTD("*."+i, "&#x21D3"));
+  client.println(getTD("?.7","&#x25A7"));
+  client.println("

");
+  client.println("
");
+  for (int i=0; i<8; i++) {
+    client.println("
"+getTD(i+".*","&#x21D2"));
+    for (int j=0; j<8; j++) {
+      client.println(getTD(i+"."+j,"&#x25C9"));
+    }
+    client.println(getTD("i.-","&#x25A5"));
+    client.println("
");
+  }
+  client.println("

");
+  client.println("

"+getTD("-.-","&#x25A9"));
+  for (int i=0; i<8; i++) {
+    client.println(getTD("-."+i, "&#x25A4"));
+  }
+  client.println(getTD("-?","&#x25A8"));
+  client.println("

");
+  client.println("");
+}
+
 void blink(byte n){
   for (byte i=0; i<n; i++) {
   digitalWrite(LEDPIN, LOW);    // turn the LED off by making the voltage LOW
@@ -195,7 +256,7 @@
 void handleHexaStringRequest(String req, int waitms) {
   printDebug("req="+req);

-  RgbColor white = RgbColor(128,128,128);
+  RgbColor white = RgbColor(255,255,255);
   RgbColor black = RgbColor(0,0,0);
   int off = 0;
   int pixelNumber= 0;
@@ -427,9 +488,9 @@

 void handleDefault(WiFiClient client){
 blink(1);
-
+printPanelTable(client);

-
+  /*
   client.println("<title>aMaker club - CE aMaDEUS</title>\r\n


G92 support

G92 support

--- src/miscr.ino
+++ src/miscr.ino
@@ -472,6 +472,28 @@
     return true;
   } else if(gindex == 90) {
     return true; // Not implemented, yet needed to test support for G-Code senders
+  } else if(gindex == 92) {
+    in = trim(in);
+
+    float xindex = getIndex('X', in);
+
+    if(xindex != INT_MIN) {
+      sX.pos = xindex;
+      in = trim(in);
+    }
+
+    float yindex = getIndex('Y', in);
+
+    if(yindex != INT_MIN)
+      sY.pos = yindex;
+
+    if(xindex == INT_MIN && yindex == INT_MIN) {
+      sX.pos = 0;
+      sY.pos = 0;
+      sZ.pos = 0;
+    }
+
+    return true;
   }

   int mindex = getIndex('M', in);


M115 and partial G28 support

M115 and partial G28 support

--- src/miscr.ino
+++ src/miscr.ino
@@ -186,12 +186,13 @@
   }
   //void step(double times) {}
   void testSpin(int amount) {
+    amount *= 80;
     if(amount > 0)
       dw(dirPin, LOW);
     else
       dw(dirPin, HIGH);
     prevpos = pos;
-    pos += (amount / 80);
+    pos += amount / 80;
     update = true;
     command.pin = stepPin;
     command.times = abs(amount);
@@ -285,8 +286,8 @@
     in = trim(in);
     int yindex = getIndex('Y', in);

-    if(xindex != INT_MIN) sX.testSpin(xindex * 80);
-    if(yindex != INT_MIN) sY.testSpin(yindex * 80);
+    if(xindex != INT_MIN) sX.testSpin(xindex);
+    if(yindex != INT_MIN) sY.testSpin(yindex);

     if(xindex == INT_MIN && yindex == INT_MIN) {
       out.msg(1, "No parameters/Invalid values for G0/G1");
@@ -294,12 +295,23 @@
     }

     return true;
+  } else if(gindex == 28) {
+    if(globalPos.x != 0)
+      sX.testSpin(globalPos.x - (globalPos.x * 2));
+    if(globalPos.y != 0)
+      sY.testSpin(globalPos.y - (globalPos.y * 2));
+
+    return true;
   }

   int mindex = getIndex('M', in);

   if(mindex == 114) {
     out.pos(0);
+    return false;
+  } else if(mindex == 115) {
+    Serial.println("ok PROTOCOL_VERSION:0.11 FIRMWARE_NAME:miscr FIRMWARE_URL:github.com/argarak/miscr MACHINE_TYPE:N/A EXTRUDER_COUNT:0");
+    Serial.println("");
     return false;
   }


Award Day version

Award Day version

--- app/inTheDuck/LoverDuck/LoverDuck.ino
+++ app/inTheDuck/LoverDuck/LoverDuck.ino
@@ -17,9 +17,9 @@
 Adafruit_NeoPixel pixelsA = Adafruit_NeoPixel(ledNumA, ledPinA, NEO_GRB + NEO_KHZ800);
 Adafruit_NeoPixel pixelsB = Adafruit_NeoPixel(ledNumB, ledPinB, NEO_GRB + NEO_KHZ800);
 int color[]={0,250,50};
-int startColor[]={0, 0, 200};
-int endColor[]={0, 200, 0};
-unsigned long mode1Duration=4*60*1000;
+int startColor[]={0, 0, 250};
+int endColor[]={0, 250, 0};
+unsigned long mode1Duration=20000;

 boolean notFirst=true;

@@ -131,7 +131,9 @@
 unsigned long sendInterval=50;
 void processData(){
   if(mode==0){
-    return;
+//    return;
+//    IRL, it's not desirable to send BT even when it's supposed to be on
+//    demo-wise, only the LED changes when on and off
   }
   if((millis()-previousProcess)>sendInterval){
     float data[6];
@@ -259,13 +261,13 @@
 //        }
 //        color[i]=(a/mode1Duration+startColor[i])%256;
 //      }
-
+      float ratio= 0.7+ 0.3 * sin(((millis()/10)%360)*3.14/180);
       float ratio_general=(float)(millis()-startCurrentMode)/mode1Duration;
 //      Serial.print(ratio_general);
 //     for debug

       for(int i=0; i<3 ; i++){
-        color[i]=(int)(ratio_general*(endColor[i]-startColor[i])) + startColor;
+        color[i]=(int)(ratio*((ratio_general*(endColor[i]-startColor[i])) + startColor[i]));
       }
       if(!isBT){
         Serial.println((String)color[0]+","+(String)color[1]+","+(String)color[2]);


Add commands to turn left or right for a brief amount of time.

--- arduino/tank_control/tank_control.ino
+++ arduino/tank_control/tank_control.ino
@@ -69,6 +69,12 @@
   Serial.println("left");
 }

+void left (char a,char b, int ms) {
+  left(a,b);
+  delay(ms);
+  stop();
+}
+
 void right (char a,char b)
 {
   analogWrite (E1,a);
@@ -76,6 +82,12 @@
   analogWrite (E2,b);
   digitalWrite(M2,HIGH);
   Serial.println("right");
+}
+
+void right (char a,char b, int ms) {
+  right(a,b);
+  delay(ms);
+  stop();
 }

 void moveServoUp(int amount) {
@@ -90,7 +102,7 @@

 void handleSerial(char command) {
   int leftspeed = 255;   // 255 is maximum speed
-  int rightspeed = 240;  // Adjust for skew
+  int rightspeed = 255;
   switch(command) // Perform an action depending on the command
   {
     case 'w'://Move Forward
@@ -109,13 +121,21 @@
     case 'D':
       right (leftspeed,rightspeed);
       break;
-    case 'r': //Tilt UP
-    case 'R':
+    case 'u': //Tilt UP
+    case 'U':
       moveServoUp(SERVO_MOVE_INCREMENT);
       break;
-    case 'f':
-    case 'F':
+    case 'j':
+    case 'J':
       moveServoDown(SERVO_MOVE_INCREMENT);
+      break;
+    case 'h':
+    case 'H':
+      left(leftspeed,rightspeed,100);
+      break;
+    case 'k':
+    case 'K':
+      right(leftspeed, rightspeed, 100);
       break;
     default:
       stop();


Updated code

Updated code

There was an error with new versions of Arduino IDE, this code must work.

--- pairing/pairing/pairing.ino
+++ pairing/pairing/pairing.ino
@@ -13,24 +13,20 @@
   *
   *   Lozano Ramirez Angel Ivan
   *   02.07.2018
+  *   NOTE: Set the Serial monitor with NL&CR and 9600 baud
 */

 #include <SoftwareSerial.h>
-SoftwareSerial BT(10,11);
+SoftwareSerial BT(11,10);

 void setup(){
   BT.begin(38400);
-  Serial.begin(38400);
+  Serial.begin(9600);
 }

 void loop(){
-  if( BT.available() ){
-    Serial.write( BT.read() );
-  }
-
-  if( Serial.available() ){
-     BT.write( Serial.read() );
-  }
+  if( BT.available() ) Serial.write( BT.read() );
+  if( Serial.available() ) BT.write(Serial.read());
 }


extract constant for easier tweaks

extract constant for easier tweaks

--- status.ino
+++ status.ino
@@ -10,6 +10,8 @@
 #define RESPONSE_SCALE_UP 2
 #define RESPONSE_SCALE_DOWN 3
 #define RESPONSE_RESTART 4
+
+#define LIGHT_INTENSITY 10 // how bright – 1 to 255

 SparkButton strip = SparkButton();

@@ -60,23 +62,23 @@
             strip.ledOff(i);
             break;
         case GREEN:
-            strip.ledOn(i, 0, 10, 0);
+            strip.ledOn(i, 0, LIGHT_INTENSITY, 0);
             break;
         case YELLOW:
-            strip.ledOn(i, 10, 10, 0);
+            strip.ledOn(i, LIGHT_INTENSITY, LIGHT_INTENSITY, 0);
             break;
         case RED:
-            strip.ledOn(i, 10, 0, 0);
+            strip.ledOn(i, LIGHT_INTENSITY, 0, 0);
             break;
         case BLUE:
-            strip.ledOn(i, 0, 0, 10);
+            strip.ledOn(i, 0, 0, LIGHT_INTENSITY);
             break;
     }
 }

 void processButton(int response) {
     drainResponse = response;
-    strip.allLedsOn(10, 10, 10);
+    strip.allLedsOn(LIGHT_INTENSITY, LIGHT_INTENSITY, LIGHT_INTENSITY);
     for(int i=0; i<12; i++) {
         // flag as dirty so it will go back to whatever color it was
         current[i] = 99;


Check HTTP response code, and flash out error codes on the LED

--- client_arduino/arduino_client.ino
+++ client_arduino/arduino_client.ino
@@ -32,8 +32,62 @@
 TelegramReader telegramReader;
 WiFiClientSecure httpsClient;

+enum ErrorCode {
+  NO_ERROR = 0,
+  WIFI_CONNECT_ERROR = 1,
+  NTP_ERROR = 2,
+  TELEGRAM_READ_ERROR = 3,
+  TELEGRAM_CHECKSUM_ERROR = 4,
+  SERVER_CONNECT_ERROR = 5,
+  SERVER_SSL_ERROR = 6,
+  SERVER_READ_ERROR = 7,
+  SERVER_PROTOCOL_ERROR = 8,
+  SERVER_RESPONSE_ERROR = 9,
+};
+
 void setLed(bool on) {
   digitalWrite(LED_PIN, on ? LOW : HIGH);
+}
+
+void blinkLed(int ms) {
+  setLed(true);
+  delay(ms);
+  setLed(false);
+}
+
+/**
+ * Flashes out an error in a kind of "decimal morse code", for example:
+ * 502 = ..... _ ..
+ */
+void flashNumber(uint16 number) {
+  byte digits[5]; // Maximum 65535.
+  byte numDigits = 0;
+  while (number) {
+    digits[numDigits] = number % 10;
+    numDigits++;
+    number /= 10;
+  }
+  if (numDigits == 0) {
+    digits[0] = 0;
+    numDigits = 1;
+  }
+  while (numDigits) {
+    numDigits--;
+    setLed(false);
+    delay(500);
+
+    byte digit = digits[numDigits];
+    if (digit) {
+      while (digit) {
+        digit--;
+        blinkLed(150);
+        delay(150);
+      }
+    } else {
+      blinkLed(500);
+      delay(150);
+    }
+  }
 }

 /**
@@ -45,13 +99,14 @@
     Serial.print("Failed to connect to " SERVER_HOST ":");
     Serial.print(SERVER_PORT);
     Serial.println();
+    flashNumber(SERVER_CONNECT_ERROR);
     return false;
   }
-
-  setLed(true);

   if (!httpsClient.verify(SERVER_CERTIFICATE_FINGERPRINT, SERVER_HOST)) {
     Serial.println("Certificate verification failed");
+    httpsClient.stop();
+    flashNumber(SERVER_SSL_ERROR);
     return false;
   }

@@ -68,9 +123,71 @@
       "\r\n");
   httpsClient.write(buffer, size);

+  // "HTTPS/1.1 ", we stop reading after the space.
+  while (true) {
+    byte b = httpsClient.read();
+    if (b < 0) {
+      httpsClient.stop();
+      flashNumber(SERVER_READ_ERROR);
+      return false;
+    }
+    if (b == ' ') {
+      break;
+    }
+  }
+  // "200 ", we stop reading after the space.
+  int statusCode = 0;
+  while (true) {
+    byte b = httpsClient.read();
+    if (b < 0) {
+      httpsClient.stop();
+      flashNumber(SERVER_READ_ERROR);
+      return false;
+    }
+    if (!isDigit(b)) {
+      break;
+    }
+    statusCode = (statusCode * 10) + (b - '0');
+    if (statusCode > 999) {
+      httpsClient.stop();
+      flashNumber(SERVER_PROTOCOL_ERROR);
+      return false;
+    }
+  }
+  if (statusCode != 200) {
+    Serial.print("Non-success HTTP response code from server: ");
+    Serial.print(statusCode);
+    Serial.print(" ");
+    // "OK" or whatever descriptive message there is.
+    while (true) {
+      int b = httpsClient.read();
+      if (b < 0) {
+        httpsClient.stop();
+        flashNumber(SERVER_READ_ERROR);
+        return false;
+      }
+      if (b == '\r') {
+        break;
+      }
+      Serial.write((byte) b);
+    }
+    Serial.println();
+    httpsClient.stop();
+    if (statusCode == 400) {
+      flashNumber(TELEGRAM_CHECKSUM_ERROR);
+      return false;
+    } else {
+      flashNumber(SERVER_RESPONSE_ERROR);
+      delay(500);
+      flashNumber(statusCode);
+      return false;
+    }
+  }
+
   Serial.print("Uploaded telegram of ");
   Serial.print(size);
   Serial.println(" bytes");
+  flashNumber(NO_ERROR);

   return true;
 }
@@ -129,7 +246,7 @@
     Serial.print(READ_TIMEOUT_MILLIS);
     Serial.println(" ms");
     telegramReader.reset();
-    setLed(false);
+    flashNumber(TELEGRAM_READ_ERROR);
   }

   int b = P1_INPUT.read();
@@ -149,10 +266,7 @@
       Serial.print(size);
       Serial.println(" bytes");

-      bool success = uploadTelegram(telegramReader.getBuffer(), size);
-      if (success) {
-        setLed(false);
-      }
+      uploadTelegram(telegramReader.getBuffer(), size);

       telegramReader.reset();
     }


Increased the delay time

Increased the delay time

--- src/LCDPrint/LCDPrint.ino
+++ src/LCDPrint/LCDPrint.ino
@@ -12,7 +12,7 @@

 LiquidCrystal_I2C lcd(0x27, 16, 2);

-const int delayTime = 500;
+const int delayTime = 1000;
 const String topLine = "Derby Grammar";

 void setup() {


Fixed 'Content-Length mismatch' error when uploading.

--- webserver.ino
+++ webserver.ino
@@ -152,13 +152,13 @@
   webServer.on( "/api/upload", HTTP_POST, []() {
     webServer.sendHeader("Connection", "close");
     webServer.sendHeader("Access-Control-Allow-Origin", "*");
+    webServer.send( 200, "text/plain", "" );
   }, []() {
     HTTPUpload& upload = webServer.upload();
     if ( upload.status == UPLOAD_FILE_START ) {
       String filename = upload.filename;
       if ( !filename.startsWith("/") ) filename = "/" + filename;
       fsUploadFile = SPIFFS.open( filename, "w");
-      //filename = String();
     } else if ( upload.status == UPLOAD_FILE_WRITE ) {
       if ( fsUploadFile )
         fsUploadFile.write( upload.buf, upload.currentSize );
@@ -166,7 +166,6 @@
       if ( fsUploadFile ) {
         fsUploadFile.close();
       }
-      webServer.send( 200, "text/plain", formatBytes( upload.totalSize ) + " written in '" + upload.filename + "'" );
     }
   });


SwSerial.ino edited online with Bitbucket

--- examples/Transports/Advanced/SwSerial/SwSerial.ino
+++ examples/Transports/Advanced/SwSerial/SwSerial.ino
@@ -1,3 +1,8 @@
+
+
+//   Please rename sketch to SoftwareSerial.ino
+
+
 #define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
 #include <SoftwareSerial.h>
 #include <BlynkSerial.h>


7 segment display function in test sketch

--- firmware/old/_7SegmentOutTest/_7SegmentOutTest.ino
+++ firmware/old/_7SegmentOutTest/_7SegmentOutTest.ino
@@ -5,7 +5,7 @@

 //This is the hex value of each number stored in an array by index num
-byte digitOne[10]= {0x3F, 0x06, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
+byte digitOne[10]= {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f};

 int i;

@@ -20,13 +20,19 @@

 void loop(){

-  for(int i=0; i<10; i++){
-    for(int j=0; j<10; j++){
-      digitalWrite(LATCH, LOW);
-      shiftOut(DATA, CLK, LSBFIRST, ~digitOne[i]); // digitTwo
-      shiftOut(DATA, CLK, LSBFIRST, ~digitOne[j]); // digitOne
-      digitalWrite(LATCH, HIGH);
-      delay(500);
-    }
+  for(int i=0; i<100; i++){
+    showNumber(i);
+    delay(100);
   }
 }
+
+
+void showNumber(byte num) {
+  byte i = num % 10;
+  byte j = (num - i) / 10;
+      digitalWrite(LATCH, LOW);
+      shiftOut(DATA, CLK, MSBFIRST, digitOne[i]); // digitTwo
+      shiftOut(DATA, CLK, MSBFIRST, digitOne[j]); // digitOne
+      digitalWrite(LATCH, HIGH);
+
+}


Update i2c_datatest.ino

Update i2c_datatest.ino

--- code/i2c_datatest.ino
+++ code/i2c_datatest.ino
@@ -1,6 +1,8 @@
 #include <Wire.h>

 #define SENSOR_ADDR 0x68;
+
+unsigned char bytes[14];

 void setup(){
   Wire.begin();
@@ -22,6 +24,10 @@
   Wire.requestFrom(SENSOR_ADDR, 14, true);

   // read 14 DATAbytes here
+  for (int i = 0; i < 14; i++)
+      bytes[i] = Wire.read();
+
+  // convert into ints
   // ...

   delay(30);


mem buttons start with #1

mem buttons start with #1

--- vfobox.ino
+++ vfobox.ino
@@ -169,13 +169,13 @@
       // long push = commit to memory
       EEPROM.put(eeAddressStart+buttons*sizeof(double),freq);
       lcd.print("m");
-      lcd.print(buttons);
+      lcd.print(buttons+1); // first button is referred to as "m1"
       lcd.print(" stored");
       } else {
       // short push = qsy to memory frequency
       EEPROM.get(eeAddressStart+buttons*sizeof(double),freq);
       lcd.print("recall m");
-      lcd.print(buttons);
+      lcd.print(buttons+1);
       send_frequency(freq);
       display_frequency(freq);
       }


Removed delay in sketch

Removed delay in sketch

--- panasonic_raw/panasonic_raw_send/panasonic_raw_send.ino
+++ panasonic_raw/panasonic_raw_send/panasonic_raw_send.ino
@@ -53,7 +53,7 @@
       // altered the code just to send/test my raw code
       irsend.sendRaw(raw,105,40);
       Serial.println("IR raw sent");
-      delay(2000);
+//      delay(2000);
     }
     else {
     // do nothing
@@ -70,7 +70,7 @@
       // altered the code just to send/test my raw code
       irsend.sendRaw(raw,69,40);
       Serial.println("IR raw sent");
-      delay(2000);;
+//      delay(2000);;
     }
     else {
     // do nothing
@@ -87,7 +87,7 @@
       // altered the code just to send/test my raw code
       irsend.sendRaw(raw,531,40);
       Serial.println("IR raw sent");
-      delay(2000);
+//      delay(2000);
     }
     else {
     // do nothing
@@ -103,7 +103,7 @@
       // altered the code just to send/test my raw code
       irsend.sendRaw(raw,465,40);
       Serial.println("IR raw sent");
-      delay(2000);
+//      delay(2000);
     }
     else {
     // do nothing


Properly display p2 score

Properly display p2 score

--- Pingduino/Pingduino.ino
+++ Pingduino/Pingduino.ino
@@ -2,11 +2,11 @@
 #define P2PIN           1
 #define BUTTONLIGHTPIN  4
 #define SPEAKERPIN      9
-#define LONGPRESS_TIME 25
+#define LONGPRESS_TIME  1000
 #define LATCH           7
 #define CLK             6
 #define DATA            5
-#define INACTIVEMILLIS 1200000 // 20 minutes
+#define INACTIVEMILLIS  1200000 // 20 minutes

 // Seven Segment Display Handling
 byte DigitBytes[10]= {0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x67};
@@ -127,7 +127,7 @@
   if (trackP1Button == 1) {
     trackP1Button = 0;
     unsigned long now = millis();
-    if ((now - p1ButtonChangeMillis) <= 500) {
+    if ((now - p1ButtonChangeMillis) <= LONGPRESS_TIME) {
       // Short press, score
       if (gameOver)
         return;
@@ -159,7 +159,7 @@
   if (trackP2Button == 1) {
     trackP2Button = 0;
     unsigned long now = millis();
-    if ((now - p2ButtonChangeMillis) <= 500) {
+    if ((now - p2ButtonChangeMillis) <= LONGPRESS_TIME) {
       // Short press, score
       if (gameOver)
         return;
@@ -167,7 +167,7 @@
       numServes++;
     } else {
       // Long press, reset
-      currentServe = 0;
+      currentServe = 1;
       requestReset = 1;
     }
   }
@@ -242,11 +242,28 @@
     currentServe = currentServe == 0 ? 1 : 0;
   }

+  int p1OnesIndex = p1Score % 10;
+  int p1TensIndex = p1Score / 10;
+  int p1Ones = DigitBytes[p1OnesIndex];
+  int p1Tens = DigitBytes[p1TensIndex];
+
+  int p2OnesIndex = p2Score % 10;
+  int p2TensIndex = p2Score / 10;
+  int p2Ones = DigitBytes[p2OnesIndex];
+  int p2Tens = DigitBytes[p2TensIndex];
+
   if (currentServe == 0) {
-    showP1Score(p1Score, true);
+    p1Tens |= 0x80;
   } else {
-    showP1Score(p1Score, false);
-  }
+    p2Tens |= 0x80;
+  }
+
+  digitalWrite(LATCH, LOW);
+  shiftOut(DATA, CLK, MSBFIRST, p2Ones);
+  shiftOut(DATA, CLK, MSBFIRST, p2Tens);
+  shiftOut(DATA, CLK, MSBFIRST, p1Ones);
+  shiftOut(DATA, CLK, MSBFIRST, p1Tens);
+  digitalWrite(LATCH, HIGH);
 }

 void goToSleep()


refactor checkOutputLevel

refactor checkOutputLevel

--- vfobox.ino
+++ vfobox.ino
@@ -66,7 +66,6 @@
 long lastClick = 0;
 long lastBlink = 0;
 long lastStatus = 0;
-long lastTrigger = 0;
 long last_mem[NUMBER_MEM_BUTTONS];

 boolean blinkState = false;
@@ -166,6 +165,19 @@
    spinDirection = 2;
    encval = 0;
   }
+}
+
+void checkOutputLevel() {
+  static long lastTrigger = 0;
+
+  if(millis() - lastTrigger > 100) {
+    if(analogRead(RF_V) > threshold) {
+      digitalWrite(WARN_LED, HIGH);
+    } else {
+      digitalWrite(WARN_LED, LOW);
+    }
+    lastTrigger = millis();
+  }
 }

 void setup() {
@@ -293,15 +305,8 @@
     }
   }

-  if(millis() - lastTrigger > 100) {
-    if(analogRead(RF_V) > threshold) {
-      digitalWrite(WARN_LED, HIGH);
-    } else {
-      digitalWrite(WARN_LED, LOW);
-    }
-    lastTrigger = millis();
-  }
-
+  checkOutputLevel();
+
   //wipe stale status
   if (statusDisplayed && millis() - lastStatus > 2000) {
     clear_line(1);


Update GAC.ino

Update GAC.ino

--- GAC/GAC.ino
+++ GAC/GAC.ino
@@ -17,16 +17,23 @@
 #include <SD.h>
 #include <Wire.h>
 #include "RTClib.h"
-#include <SoftwareSerial.h>      //we have to include the SoftwareSerial library, or else we can't use it.
-
+#include <Adafruit_RGBLCDShield.h>
+#include <utility/Adafruit_MCP23017.h>
+Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
+#define RED 0x1
+#define YELLOW 0x3
+#define GREEN 0x2
+#define TEAL 0x6
+#define BLUE 0x4
+#define VIOLET 0x5
+#define WHITE 0x7
 const int chipSelect = 10;

-unsigned long LOG_INTERVAL = 60000;
+unsigned long LOG_INTERVAL = 25000;
 unsigned long previousMillis = 0;

-
 // The analog pins that connect to the sensors
-#define PressureAnalog A1      // analog 1
+#define PressureAnalog A0      // analog 1

 // define the Real Time Clock object
 RTC_PCF8523 RTC;
@@ -39,21 +46,39 @@
 float f;
 char *flotot;

-int PressureAnalogReading = 0;
-unsigned long PressureReadingSUM = 0;
+float PressureAnalogReading = 0;
+float PressureReadingSUM = 0;
 unsigned long readingCount = 0;

 void setup() {
+    lcd.begin(16, 2);
+  /* if (! rtc.begin()) {
+    lcd.print("Couldn't find RTC");
+    while (1);
+  }
+
+  if (rtc.lostPower()) {
+    lcd.print("RTC lost power, lets set the time!");
+    // following line sets the RTC to the date & time this sketch was compiled
+    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
+    // This line sets the RTC with an explicit date & time, for example to set
+    // January 21, 2014 at 3am you would call:
+    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
+  }
+  // Print a message to the LCD. We track how long it takes since
+  // this library has been optimized a bit and we're proud of it :)*/
+  lcd.print("start!");
+  lcd.setBacklight(WHITE);
+  delay(5000);
+
+uint8_t i=0;
   // Open serial communications and wait for port to open:

   Serial.begin(9600);
-  while (!Serial) {
+  /*while (!Serial) {
     ; // wait for serial port to connect. Needed for native USB port only
   }
-
-
   Serial.print("Initializing SD card...");
-
   // see if the card is present and can be initialized:
   if (!SD.begin(chipSelect)) {
     Serial.println("Card failed, or not present");
@@ -62,13 +87,23 @@
   }
   Serial.println("card initialized.");
   // connect to RTC
-  Wire.begin();
+  Wire.begin();  */
 }

 void loop() {
-  analogRead(PressureAnalog);
+  float t=millis();
+  float number= (analogRead(PressureAnalog)*.7018-52)*.868;
+  PressureReadingSUM = PressureReadingSUM + number;
+  lcd.clear();
+  lcd.setCursor(0,0);
+  lcd.print("GAC ");
+  lcd.setCursor(0,1);
+  lcd.print(number);//lcd.print(PressureAnalogReading);
+  lcd.setCursor(6,1);
+  lcd.print(t);
+  lcd.setBacklight(TEAL);
   delay(10);
-
+  readingCount=readingCount+1;
   delay(990);

   unsigned long currentMillis = millis();
@@ -77,7 +112,7 @@
     previousMillis = currentMillis;

     // create a filename
-
+    /*
     DateTime now;
     now = RTC.now();
     int YR = now.year();
@@ -89,19 +124,21 @@
     String DYs = String(DY,DEC);
     String DATE = YRs + MOs + DYs;
     String filename = DATE + ".CSV";
-
+  */
     //collect data
     //Average repetative current and voltage readings between sampling interval
     PressureAnalogReading = PressureReadingSUM / readingCount;
-    float P = PressureAnalogReading / 102.94;
-
-    delay(10);
-
+    float P = PressureAnalogReading;
+    lcd.clear();
+    lcd.setCursor(0,0);
+    lcd.print(P);
+    delay(10000);
+    Serial.println(P);
     //read total flow once per sampling interval

     delay(200);

-    // make a string for assembling the data to log:
+    /*/ make a string for assembling the data to log:
     String dataString = "";
     dataString += String(now.unixtime());dataString += ",";
     dataString += String(P);
@@ -117,14 +154,17 @@
       dataFile.close();
       // print to the serial port too:
       Serial.println(dataString);
+      lcd.setCursor(0,1);
+    lcd.print("it works");
     }
     // if the file isn't open, pop up an error:
     else {
       Serial.print("error opening ");Serial.print(filename);Serial.println("!");
     }
-
+  */
+    delay(10000);
     //reset averaging tools if interval is met
     readingCount=0;
-    PressureAnalogReading = 0;
+    PressureReadingSUM = 0;
   }
 }


background and foreground colors alternate with each letter

--- baby_alphabet/baby_alphabet.ino
+++ baby_alphabet/baby_alphabet.ino
@@ -12,6 +12,12 @@
   'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
 };

+int colorState = 0;
+
+const uint8_t colorMap[2][2] = {
+  {BLACK, WHITE},
+  {WHITE, BLACK}
+};

 const uint16_t alphabetSong[] = {
   NOTE_C4, NOTE_C4, NOTE_G4, NOTE_G4, NOTE_A4, NOTE_A4, NOTE_G4,
@@ -45,7 +51,7 @@
   NOTE_E4, 500, //T
   NOTE_E4, 500, //U
   NOTE_D4, 500, //V
-  NOTE_G4, 250, NOTE_G4, 250, NOTE_G4, 500,//W
+  NOTE_G4, 250, NOTE_G4, 250, NOTE_G4, 500,//W
   NOTE_F4, 500, //X
   NOTE_E4, 500, //Y
   NOTE_E4, 500, //Z
@@ -80,12 +86,27 @@
   return false;
 }

+void nextLetter(int letterIndex) {
+  colorState = !colorState;
+  int colorScheme[] = {colorMap[colorState][0], colorMap[colorState][1]};
+
+  arduboy.fillScreen(colorMap[colorState][0]);
+  arduboy.drawChar(50, 10, alphabet[letterIndex], colorScheme[1], colorScheme[0], 6);
+
+  //TODO make a lookup table with the note and how many times/how long to play it
+  sound.tone(alphabetSong[letterIndex], 500);
+  arduboy.setCursor(0, 0);
+  arduboy.display();
+}
+
 void setup() {
   // put your setup code here, to run once:
   arduboy.begin();
   arduboy.clear();
-  playSong();
+//  playSong();
   counter = 0;
+  nextLetter(counter);
+  arduboy.display();
 }

 void loop() {
@@ -100,7 +121,7 @@
     else {
       counter = 0;
     }
-    sound.tone(alphabetSong[counter], 500);
+    nextLetter(counter);
   }
   //Check if the DOWN_BUTTON is being pressed
   if ( buttonJustPressed(LEFT_BUTTON ) || buttonJustPressed( DOWN_BUTTON ) == true ) {
@@ -111,14 +132,10 @@
     else {
       counter = 25;
     }
-    sound.tone(alphabetSong[counter], 500);
+    nextLetter(counter);
   }

   if (buttonJustPressed(A_BUTTON) || buttonJustPressed(B_BUTTON) == true) {
     playSong();
   }
-
-  arduboy.setCursor(0, 0);
-  arduboy.drawChar(50, 10, alphabet[counter], WHITE, BLACK, 6);
-  arduboy.display();
 }


Small refactoring

Small refactoring

--- xtrm-arduino-client/xtrm-arduino-client.ino
+++ xtrm-arduino-client/xtrm-arduino-client.ino
@@ -15,7 +15,7 @@
 #include <Ethernet.h>

 byte macAddress[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x23, 0x58 };
-IPAddress server(192, 168, 1, 50); // Server IP address
+IPAddress serverAddress(192, 168, 1, 50); // Server IP address
 int serverPort = 3001; // Server port

 // Ethernet TCP client
@@ -30,7 +30,7 @@
   Serial.println("Device connected: " + Ethernet.localIP());

   // Attempt server connection
-  if (client.connect(server, serverPort)) {
+  if (client.connect(serverAddress, serverPort)) {
       Serial.println("Connected to the server!");
   }
   else {


Replace hard coded level with configuration value

--- src/cyclop_plus/cyclop_plus.ino
+++ src/cyclop_plus/cyclop_plus.ino
@@ -267,7 +267,7 @@
     if (millis() > alarmTimer) {
       alarmSoundOn = !alarmSoundOn;
       if (alarmSoundOn) {
-        analogWrite( ALARM_PIN, 32 );
+        analogWrite( ALARM_PIN, options[ALARM_LEVEL_OPTION] );
         alarmTimer = millis() + alarmOnPeriod;
       }
       else {


Clean up.

Clean up.

--- examples/Analyzer/CosaAnalyzserGPIO/CosaAnalizerGPIO.ino
+++ examples/Analyzer/CosaAnalyzserGPIO/CosaAnalizerGPIO.ino
@@ -17,7 +17,7 @@
  *
  * @section Description
  * Logic Analyzer Cosa GPIO; trigger on rising edge transition
- * on ledPin. Measurement values are for Arduino Uno
+ * on ledPin. Measurement values are for Arduino Uno/Nano.
  *
  * This file is part of the Arduino Che Cosa project.
  */
@@ -55,7 +55,9 @@
 void loop()
 {
   // Measure overhead in test case marker;
-  // 0.5 us
+  // 1.5 us (0.5 us per pulse)
+  ~ledPin;
+  ~ledPin;
   ~ledPin;
   ~ledPin;
   DELAY(10);
@@ -242,10 +244,7 @@
   // 8.375 us (0.98 us per bit)
   ~ledPin;
   for(uint8_t bit = 0x80; bit != 0; bit >>= 1) {
-    if (data & bit)
-      GPIO::write(Board::D9, 1);
-    else
-      GPIO::write(Board::D9, 0);
+    if (data & bit) GPIO::write(Board::D9, 1); else GPIO::write(Board::D9, 0);
     GPIO::write(Board::D10, 1);
     GPIO::write(Board::D10, 0);
   }
@@ -269,10 +268,7 @@
   // 7.750 us (0.91 us per bit)
   ~ledPin;
   for(uint8_t bit = 0x80; bit != 0; bit >>= 1) {
-    if (data & bit)
-      GPIO::write(Board::D9, 1);
-    else
-      GPIO::write(Board::D9, 0);
+    if (data & bit) GPIO::write(Board::D9, 1); else GPIO::write(Board::D9, 0);
     GPIO::toggle(Board::D10);
     GPIO::toggle(Board::D10);
   }
@@ -314,52 +310,28 @@
   // and toggle member functions fully unrolled
   // 5.250 us (0.59 us per bit)
   ~ledPin;
-  if (data & 0x80)
-    GPIO::write(Board::D9, 1);
-  else
-    GPIO::write(Board::D9, 0);
-  GPIO::toggle(Board::D10);
-  GPIO::toggle(Board::D10);
-  if (data & 0x40)
-    GPIO::write(Board::D9, 1);
-  else
-    GPIO::write(Board::D9, 0);
-  GPIO::toggle(Board::D10);
-  GPIO::toggle(Board::D10);
-  if (data & 0x20)
-    GPIO::write(Board::D9, 1);
-  else
-    GPIO::write(Board::D9, 0);
-  GPIO::toggle(Board::D10);
-  GPIO::toggle(Board::D10);
-  if (data & 0x10)
-    GPIO::write(Board::D9, 1);
-  else
-    GPIO::write(Board::D9, 0);
-  GPIO::toggle(Board::D10);
-  GPIO::toggle(Board::D10);
-  if (data & 0x08)
-    GPIO::write(Board::D9, 1);
-  else
-    GPIO::write(Board::D9, 0);
-  GPIO::toggle(Board::D10);
-  GPIO::toggle(Board::D10);
-  if (data & 0x04)
-    GPIO::write(Board::D9, 1);
-  else
-    GPIO::write(Board::D9, 0);
-  GPIO::toggle(Board::D10);
-  GPIO::toggle(Board::D10);
-  if (data & 0x02)
-    GPIO::write(Board::D9, 1);
-  else
-    GPIO::write(Board::D9, 0);
-  GPIO::toggle(Board::D10);
-  GPIO::toggle(Board::D10);
-  if (data & 0x01)
-    GPIO::write(Board::D9, 1);
-  else
-    GPIO::write(Board::D9, 0);
+  if (data & 0x80) GPIO::write(Board::D9, 1); else GPIO::write(Board::D9, 0);
+  GPIO::toggle(Board::D10);
+  GPIO::toggle(Board::D10);
+  if (data & 0x40) GPIO::write(Board::D9, 1); else GPIO::write(Board::D9, 0);
+  GPIO::toggle(Board::D10);
+  GPIO::toggle(Board::D10);
+  if (data & 0x20) GPIO::write(Board::D9, 1); else GPIO::write(Board::D9, 0);
+  GPIO::toggle(Board::D10);
+  GPIO::toggle(Board::D10);
+  if (data & 0x10) GPIO::write(Board::D9, 1); else GPIO::write(Board::D9, 0);
+  GPIO::toggle(Board::D10);
+  GPIO::toggle(Board::D10);
+  if (data & 0x08) GPIO::write(Board::D9, 1); else GPIO::write(Board::D9, 0);
+  GPIO::toggle(Board::D10);
+  GPIO::toggle(Board::D10);
+  if (data & 0x04) GPIO::write(Board::D9, 1); else GPIO::write(Board::D9, 0);
+  GPIO::toggle(Board::D10);
+  GPIO::toggle(Board::D10);
+  if (data & 0x02) GPIO::write(Board::D9, 1); else GPIO::write(Board::D9, 0);
+  GPIO::toggle(Board::D10);
+  GPIO::toggle(Board::D10);
+  if (data & 0x01) GPIO::write(Board::D9, 1); else GPIO::write(Board::D9, 0);
   GPIO::toggle(Board::D10);
   GPIO::toggle(Board::D10);
   ~ledPin;


change write to motor params

change write to motor params

--- StartUp.ino
+++ StartUp.ino
@@ -36,9 +36,7 @@
   delay(500);

   engineArm();
-  delay(1000);
   engineStart();
-  delay(1000);

@@ -198,29 +196,33 @@

   //digitalWrite(13, HIGH);

-  writeToMotor(14);
+  writeToMotor(14,14,14,14);
 }

 void engineStart()
 {
   Serial.println("Engine Starting... ");
   // Write to Servo
-  writeToMotor(startup);
+  writeToMotor(startup,startup,startup,startup);
 }

 void engineLock()
 {
   Serial.println("Engine Locked...");
   //void writeToMotor(int param);
-  writeToMotor(lock);
-}
-
-void writeToMotor(int param)
-{
-  moto1.write(param);
-  moto2.write(param);
-  moto3.write(param);
-  moto4.write(param);
-}
-
-
+  writeToMotor(lock, lock, lock, lock);
+}
+
+void writeToMotor(int moto1, int moto2, int moto3, int moto4)
+{
+  moto1.write(moto1);
+  delay(200);
+  moto2.write(moto2);
+    delay(200);
+  moto3.write(moto3);
+    delay(200);
+      delay(200);
+  moto4.write(moto4);
+}
+
+


Digital Sensor RPM

Digital Sensor RPM

--- Hall_Sense/Hall_Sense.ino
+++ Hall_Sense/Hall_Sense.ino
@@ -1,28 +1,26 @@
 #define LINE_COUNT 50
-#define HALL_SENSOR A4
+#define HALL_SENSOR 2
+#define HALL_SENSOR_INT 0

-int oldPinValue;
-int nowPinValue;
-long oldTimeStamp;
-long nowTimeStamp;
+volatile long oldTimeStamp;
+
+void Int_Hall()
+{
+  int currTimeStamp = millis();
+  Serial.println((float)60000 / (currTimeStamp - oldTimeStamp));
+  oldTimeStamp = currTimeStamp;
+}

 void setup()
 {
+  digitalWrite(HALL_SENSOR, HIGH);
+  attachInterrupt(HALL_SENSOR_INT, Int_Hall, RISING);
   Serial.begin(115200);
-  oldTimeStamp = millis();
-  oldPinValue = returnLineCount(analogRead(HALL_SENSOR));
 }

 void loop()
 {
-  nowPinValue = returnLineCount(analogRead(HALL_SENSOR));
-  if (nowPinValue - oldPinValue >= 2)
-  {
-    nowTimeStamp = millis();
-    Serial.println(nowTimeStamp - oldTimeStamp);
-    oldTimeStamp = nowTimeStamp;
-  }
-  oldPinValue = nowPinValue;
+
 }

 int returnLineCount(int value)


stop network monitor on restarting state machine

This commit avoid the state machine from being restarted in a deadly
fast loop if the new connection is not established quickly enough
(>100ms, ticker_mon interval).

--- src/neurite.ino
+++ src/neurite.ino
@@ -1080,6 +1080,7 @@
 	struct neurite_data_s *nd = &g_nd;
 	switch (worker_st) {
 		case WORKER_ST_0:
+			stop_ticker_mon(nd);
 			start_ticker_led_blink(nd);
 			wifi_connect(nd);
 			update_worker_state(WORKER_ST_1);


fix the worst..

fix the worst..

--- coni/arduino/test/big/big.ino
+++ coni/arduino/test/big/big.ino
@@ -27,7 +27,6 @@
 #define MAXSPEED 6000
 #define MAXACC 4000

-SoftwareSerial mySerial(pinRX, pinTX);
 AccelStepper stepper_C(1, pinStep_C, pinDirection_C);
 AccelStepper stepper_D(1, pinStep_D, pinDirection_D);
 AccelStepper stepper_E(1, pinStep_E, pinDirection_E);
@@ -113,9 +112,9 @@
   if (arg != NULL)
   {
     aNumber=atoi(arg);    // Converts a char string to an integer
-    stepper_A.setMaxSpeed(aNumber);
-    stepper_B.setMaxSpeed(aNumber);
     stepper_C.setMaxSpeed(aNumber);
+    stepper_D.setMaxSpeed(aNumber);
+    stepper_E.setMaxSpeed(aNumber);
   }

 }


remove assignment error in define

remove assignment error in define

--- hardware/src/base-station-sketch/base-station-sketch.ino
+++ hardware/src/base-station-sketch/base-station-sketch.ino
@@ -2,7 +2,7 @@
 #include "CmdMessenger.h"

 // Defines
-#define BAUD_RATE = 9600;
+#define BAUD_RATE 9600;

 // Define list of possible commands
 enum {


COH-71: WIP

COH-71: WIP

--- COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
+++ COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
@@ -1,9 +1,456 @@
+// Uncomment exactly one of the following CONFIG_ lines to select which board is being built for.
+#define CONFIG_Trial2013Winter_Round2_CC1HUB // REV2 cut4 as CC1 hub.
+//#define CONFIG_REV9 // REV9 as CC1 relay, cut 2 of the board.
+
+//#ifndef BAUD
+//#define BAUD 4800 // Ensure that OpenTRV 'standard' UART speed is set unless explicitly overridden.
+//#endif
+
+#include <Arduino.h>
+#include <Wire.h>
+#include <OTV0p2Base.h>
+#include <OTRadioLink.h>
+#include <OTRadValve.h>
+#include <OTProtocolCC.h>
+#include <OTV0p2_CONFIG_REV2.h>
+#include <OTV0p2_CONFIG_REV9.h>
+//#if defined(ENABLE_OTSECUREFRAME_ENCODING_SUPPORT) || defined(ENABLE_SECURE_RADIO_BEACON)
+//#include <OTAESGCM.h>
+//#endif
+#include <OTV0p2_Board_IO_Config.h> // I/O pin allocation and setup: include ahead of I/O module headers.
+
+// Indicate that the system is broken in an obvious way (distress flashing of the main UI LED).
+// DOES NOT RETURN.
+// Tries to turn off most stuff safely that will benefit from doing so, but nothing too complex.
+// Tries not to use lots of energy so as to keep the distress beacon running for a while.
+void panic();
+// Panic with fixed message.
+void panic(const __FlashStringHelper *s);
+
+// Version (code/board) information printed as one line to serial (with line-end, and flushed); machine- and human- parseable.
+// Format: "board VXXXX REVY; code YYYY/Mmm/DD HH:MM:SS".
+void serialPrintlnBuildVersion();
+
+// Call this to do an I/O poll if needed; returns true if something useful happened.
+// This call should typically take << 1ms at 1MHz CPU.
+// Does not change CPU clock speeds, mess with interrupts (other than possible brief blocking), or sleep.
+// Should also do nothing that interacts with Serial.
+// Limits actual poll rate to something like once every 8ms, unless force is true.
+//   * force if true then force full poll on every call (ie do not internally rate-limit)
+// Not thread-safe, eg not to be called from within an ISR.
+// NOTE: implementation may not be in power-management module.
+bool pollIO(bool force = false);
+
+// Call this to productively burn tens to hundreds of CPU cycles, and poll I/O, eg in a busy-wait loop.
+// This may churn PRNGs or gather entropy for example.
+// This call should typically take << 1ms at 1MHz CPU.
+// Does not change CPU clock speeds, mess with interrupts (other than possible brief blocking), or sleep.
+// May capture some entropy in secure and non-secure PRNGs.
+inline void burnHundredsOfCyclesProductivelyAndPoll()
+  {
+  if(pollIO()) { OTV0P2BASE::seedRNG8(OTV0P2BASE::getCPUCycleCount(), 37 /* _watchdogFired */, OTV0P2BASE::_getSubCycleTime()); }
+  else { OTV0P2BASE::captureEntropy1(); }
+  }
+
+#ifndef DEBUG
+#define DEBUG_SERIAL_PRINT(s) // Do nothing.
+#define DEBUG_SERIAL_PRINTFMT(s, format) // Do nothing.
+#define DEBUG_SERIAL_PRINT_FLASHSTRING(fs) // Do nothing.
+#define DEBUG_SERIAL_PRINTLN_FLASHSTRING(fs) // Do nothing.
+#define DEBUG_SERIAL_PRINTLN() // Do nothing.
+#define DEBUG_SERIAL_TIMESTAMP() // Do nothing.
+#else
+// Send simple string or numeric to serial port and wait for it to have been sent.
+// Make sure that Serial.begin() has been invoked, etc.
+#define DEBUG_SERIAL_PRINT(s) { OTV0P2BASE::serialPrintAndFlush(s); }
+#define DEBUG_SERIAL_PRINTFMT(s, fmt) { OTV0P2BASE::serialPrintAndFlush((s), (fmt)); }
+#define DEBUG_SERIAL_PRINT_FLASHSTRING(fs) { OTV0P2BASE::serialPrintAndFlush(F(fs)); }
+#define DEBUG_SERIAL_PRINTLN_FLASHSTRING(fs) { OTV0P2BASE::serialPrintlnAndFlush(F(fs)); }
+#define DEBUG_SERIAL_PRINTLN() { OTV0P2BASE::serialPrintlnAndFlush(); }
+// Print timestamp with no newline in format: MinutesSinceMidnight:Seconds:SubCycleTime
+extern void _debug_serial_timestamp();
+#define DEBUG_SERIAL_TIMESTAMP() _debug_serial_timestamp()
+#endif // DEBUG
+
+// Use WDT-based timer for xxxPause() routines.
+// Very tiny low-power sleep to approximately match the PICAXE V0.09 routine of the same name.
+#define VERYTINY_PAUSE_MS 5
+static void inline veryTinyPause() { OTV0P2BASE::sleepLowPowerMs(VERYTINY_PAUSE_MS); }
+// Tiny low-power sleep to approximately match the PICAXE V0.09 routine of the same name.
+#define TINY_PAUSE_MS 15
+static void inline tinyPause() { OTV0P2BASE::nap(WDTO_15MS); } // 15ms vs 18ms nominal for PICAXE V0.09 impl.
+// Small low-power sleep.
+#define SMALL_PAUSE_MS 30
+static void inline smallPause() { OTV0P2BASE::nap(WDTO_30MS); }
+// Medium low-power sleep to approximately match the PICAXE V0.09 routine of the same name.
+// Premature wakeups MAY be allowed to avoid blocking I/O polling for too long.
+#define MEDIUM_PAUSE_MS 60
+static void inline mediumPause() { OTV0P2BASE::nap(WDTO_60MS); } // 60ms vs 144ms nominal for PICAXE V0.09 impl.
+// Big low-power sleep to approximately match the PICAXE V0.09 routine of the same name.
+// Premature wakeups MAY be allowed to avoid blocking I/O polling for too long.
+#define BIG_PAUSE_MS 120
+static void inline bigPause() { OTV0P2BASE::nap(WDTO_120MS); } // 120ms vs 288ms nominal for PICAXE V0.09 impl.
+
+#ifdef ALLOW_CC1_SUPPORT_RELAY_IO // REV9 CC1 relay...
+// Call this on even numbered seconds (with current time in seconds) to allow the CO UI to operate.
+// Should never be skipped, so as to allow the UI to remain responsive.
+bool tickUICO(uint_fast8_t sec);
+// Directly adjust LEDs.
+//   * light-colour         [0,3] bit flags 1==red 2==green (lc) 0 => stop everything
+//   * light-on-time        [1,15] (0 not allowed) 30-450s in units of 30s (lt) ???
+//   * light-flash          [1,3] (0 not allowed) 1==single 2==double 3==on (lf)
+// If fromPollAndCmd is true then this is being called from an incoming Poll/Cms message receipt.
+// Not ISR- safe.
+void setLEDsCO(uint8_t lc, uint8_t lt, uint8_t lf, bool fromPollAndCmd);
+
+// Get the switch toggle state.
+// The hub should monitor this changing,
+// taking the change as indication of a boost request.
+// This is allowed to toggle only much slower than the hub should poll,
+// thus ensuring that the hub doesn't miss a boost request.
+// Safe to call from an ISR (though this would be unexpected).
+bool getSwitchToggleStateCO();
+#endif
+
+
+
+
+
+
+
+
+
+// Indicate that the system is broken in an obvious way (distress flashing the main LED).
+// DOES NOT RETURN.
+// Tries to turn off most stuff safely that will benefit from doing so, but nothing too complex.
+// Tries not to use lots of energy so as to keep distress beacon running for a while.
+void panic()
+  {
+#ifdef ENABLE_RADIO_PRIMARY_MODULE
+  // Reset radio and go into low-power mode.
+  PrimaryRadio.panicShutdown();
+#endif
+#ifdef ENABLE_RADIO_SECONDARY_MODULE
+  // Reset radio and go into low-power mode.
+  SecondaryRadio.panicShutdown();
+#endif
+  // Power down almost everything else...
+  OTV0P2BASE::minimisePowerWithoutSleep();
+#ifdef LED_HEATCALL
+  pinMode(LED_HEATCALL, OUTPUT);
+#else
+  pinMode(LED_HEATCALL_L, OUTPUT);
+#endif
+  for( ; ; )
+    {
+    LED_HEATCALL_ON();
+    tinyPause();
+    LED_HEATCALL_OFF();
+    bigPause();
+    }
+  }
+
+// Panic with fixed message.
+void panic(const __FlashStringHelper *s)
+  {
+  OTV0P2BASE::serialPrintlnAndFlush(); // Start new line to highlight error.  // May fail.
+  OTV0P2BASE::serialPrintAndFlush('!'); // Indicate error with leading '!' // May fail.
+  OTV0P2BASE::serialPrintlnAndFlush(s); // Print supplied detail text. // May fail.
+  panic();
+  }
+
+// Rearrange date into sensible most-significant-first order, and make it fully numeric.
+// FIXME: would be better to have this in PROGMEM (Flash) rather than RAM, eg as F() constant.
+static const char _YYYYMmmDD[] =
+  {
+  __DATE__[7], __DATE__[8], __DATE__[9], __DATE__[10],
+  '/',
+  __DATE__[0], __DATE__[1], __DATE__[2],
+  '/',
+  ((' ' == __DATE__[4]) ? '0' : __DATE__[4]), __DATE__[5],
+  '\0'
+  };
+// Version (code/board) information printed as one line to serial (with line-end, and flushed); machine- and human- parseable.
+// Format: "board VX.X REVY YYYY/Mmm/DD HH:MM:SS".
+void serialPrintlnBuildVersion()
+  {
+  OTV0P2BASE::serialPrintAndFlush(F("board V0.2 REV"));
+  OTV0P2BASE::serialPrintAndFlush(V0p2_REV);
+  OTV0P2BASE::serialPrintAndFlush(' ');
+  OTV0P2BASE::serialPrintAndFlush(_YYYYMmmDD);
+  OTV0P2BASE::serialPrintlnAndFlush(F(" " __TIME__));
+  }
+
+
+
+
+
+
+// Controller's view of Least Significant Digits of the current (local) time, in this case whole seconds.
+// See PICAXE V0.1/V0.09/DHD201302L0 code.
+#define TIME_LSD_IS_BINARY // TIME_LSD is in binary (cf BCD).
+#define TIME_CYCLE_S 60 // TIME_LSD ranges from 0 to TIME_CYCLE_S-1, also major cycle length.
+static uint_fast8_t TIME_LSD; // Controller's notion of seconds within major cycle.
+
+// 'Elapsed minutes' count of minute/major cycles; cheaper than accessing RTC and not tied to real time.
+// Starts at or just above zero (within the first 4-minute cycle) to help avoid collisions between units after mass power-up.
+// Wraps at its maximum (0xff) value.
+static uint8_t minuteCount;
+
+// Mask for Port B input change interrupts.
+#define MASK_PB_BASIC 0b00000000 // Nothing.
+#if defined(PIN_RFM_NIRQ) && defined(ENABLE_RADIO_RX) // RFM23B IRQ only used for RX.
+  #if (PIN_RFM_NIRQ < 8) || (PIN_RFM_NIRQ > 15)
+    #error PIN_RFM_NIRQ expected to be on port B
+  #endif
+  #define RFM23B_INT_MASK (1 << (PIN_RFM_NIRQ&7))
+  #define MASK_PB (MASK_PB_BASIC | RFM23B_INT_MASK)
+#else
+  #define MASK_PB MASK_PB_BASIC
+#endif
+
+// Mask for Port C input change interrupts.
+#define MASK_PC_BASIC 0b00000000 // Nothing.
+
+// Mask for Port D input change interrupts.
+#define MASK_PD_BASIC 0b00000001 // Serial RX by default.
+#if defined(ENABLE_VOICE_SENSOR)
+  #if VOICE_NIRQ > 7
+    #error VOICE_NIRQ expected to be on port D
+  #endif
+  #define VOICE_INT_MASK (1 << (VOICE_NIRQ&7))
+  #define MASK_PD1 (MASK_PD_BASIC | VOICE_INT_MASK)
+#else
+  #define MASK_PD1 MASK_PD_BASIC // Just serial RX, no voice.
+#endif
+#if defined(ENABLE_SIMPLIFIED_MODE_BAKE)
+#if BUTTON_MODE_L > 7
+  #error BUTTON_MODE_L expected to be on port D
+#endif
+  #define MODE_INT_MASK (1 << (BUTTON_MODE_L&7))
+  #define MASK_PD (MASK_PD1 | MODE_INT_MASK) // MODE button interrupt (et al).
+#else
+  #define MASK_PD MASK_PD1 // No MODE button interrupt.
+#endif
+
+#if defined(MASK_PB) && (MASK_PB != 0) // If PB interrupts required.
+//// Interrupt count.  Marked volatile so safe to read without a lock as is a single byte.
+//static volatile uint8_t intCountPB;
+// Previous state of port B pins to help detect changes.
+static volatile uint8_t prevStatePB;
+// Interrupt service routine for PB I/O port transition changes.
+ISR(PCINT0_vect)
+  {
+//  ++intCountPB;
+  const uint8_t pins = PINB;
+  const uint8_t changes = pins ^ prevStatePB;
+  prevStatePB = pins;
+
+// FIXME FIXME FIXME
+//#if defined(RFM23B_INT_MASK)
+//  // RFM23B nIRQ falling edge is of interest.
+//  // Handler routine not required/expected to 'clear' this interrupt.
+//  // TODO: try to ensure that OTRFM23BLink.handleInterruptSimple() is inlineable to minimise ISR prologue/epilogue time and space.
+//  if((changes & RFM23B_INT_MASK) && !(pins & RFM23B_INT_MASK))
+//    { PrimaryRadio.handleInterruptSimple(); }
+//#endif
+  }
+#endif
+
+#if defined(MASK_PC) && (MASK_PC != 0) // If PC interrupts required.
+// Previous state of port C pins to help detect changes.
+static volatile uint8_t prevStatePC;
+// Interrupt service routine for PC I/O port transition changes.
+ISR(PCINT1_vect)
+  {
+//  const uint8_t pins = PINC;
+//  const uint8_t changes = pins ^ prevStatePC;
+//  prevStatePC = pins;
+//
+// ...
+  }
+#endif
+
+#if defined(MASK_PD) && (MASK_PD != 0) // If PD interrupts required.
+// Previous state of port D pins to help detect changes.
+static volatile uint8_t prevStatePD;
+// Interrupt service routine for PD I/O port transition changes (including RX).
+ISR(PCINT2_vect)
+  {
+  const uint8_t pins = PIND;
+  const uint8_t changes = pins ^ prevStatePD;
+  prevStatePD = pins;
+
+// FIXME FIXME FIXME
+//  // If an interrupt arrived from no other masked source then wake the CLI.
+//  // The will ensure that the CLI is active, eg from RX activity,
+//  // eg it is possible to wake the CLI subsystem with an extra CR or LF.
+//  // It is OK to trigger this from other things such as button presses.
+//  // FIXME: ensure that resetCLIActiveTimer() is inlineable to minimise ISR prologue/epilogue time and space.
+//  if(!(changes & MASK_PD & ~1)) { resetCLIActiveTimer(); }
+  }
+#endif
+
+
 void setup() {
-  // put your setup code here, to run once:
-
+  // Set appropriate low-power states, interrupts, etc, ASAP.
+  OTV0P2BASE::powerSetup();
+  // IO setup for safety, and to avoid pins floating.
+  IOSetup();
+  // Restore previous RTC state if available.
+  OTV0P2BASE::restoreRTC();
+#if defined(LED_UI2_EXISTS) && defined(ENABLE_UI_LED_2_IF_AVAILABLE)
+  LED_UI2_ON();
+#endif
+  OTV0P2BASE::serialPrintAndFlush(F("\r\nOpenTRV: ")); // Leading CRLF to clear leading junk, eg from bootloader.
+    serialPrintlnBuildVersion();
+#if defined(LED_UI2_EXISTS) && defined(ENABLE_UI_LED_2_IF_AVAILABLE)
+  OTV0P2BASE::nap(WDTO_120MS); // Sleep to let UI2 LED be seen.
+  LED_UI2_OFF();
+#endif
+
+  // Count resets to detect unexpected crashes/restarts.
+  const uint8_t oldResetCount = eeprom_read_byte((uint8_t *)V0P2BASE_EE_START_RESET_COUNT);
+  eeprom_write_byte((uint8_t *)V0P2BASE_EE_START_RESET_COUNT, 1 + oldResetCount);
+
+#if defined(DEBUG) && !defined(ENABLE_MIN_ENERGY_BOOT)
+  DEBUG_SERIAL_PRINTLN_FLASHSTRING("DEBUG");
+#endif
+
+  DEBUG_SERIAL_PRINT_FLASHSTRING("Resets: ");
+  DEBUG_SERIAL_PRINT(oldResetCount);
+  DEBUG_SERIAL_PRINTLN();
+#if !defined(ALT_MAIN_LOOP) && !defined(UNIT_TESTS)
+  const uint8_t overruns = (~eeprom_read_byte((uint8_t *)V0P2BASE_EE_START_OVERRUN_COUNTER)) & 0xff;
+  if(0 != overruns)
+    {
+    DEBUG_SERIAL_PRINT_FLASHSTRING("Overruns: ");
+    DEBUG_SERIAL_PRINT(overruns);
+    DEBUG_SERIAL_PRINTLN();
+    }
+#endif
+
+  // Have 32678Hz clock at least running before going any further.
+#if defined(ENABLE_WAKEUP_32768HZ_XTAL)
+  if(!::OTV0P2BASE::HWTEST::check32768HzOsc()) { panic(F("xtal")); } // Async clock not running correctly.
+#else
+  DEBUG_SERIAL_PRINTLN_FLASHSTRING("(No xtal.)");
+#endif
+
+//  // Signal that xtal is running AND give it time to settle.
+//  posPOST(0 /*, F("about to test radio module") */);
+
+// FIXME FIXME FIXME
+//  // Initialise the radio, if configured, ASAP because it can suck a lot of power until properly initialised.
+//  PrimaryRadio.preinit(NULL);
+//  // Check that the radio is correctly connected; panic if not...
+//  if(!PrimaryRadio.configure(nPrimaryRadioChannels, RFM23BConfigs) || !PrimaryRadio.begin()) { panic(F("r1")); }
+//  // Apply filtering, if any, while we're having fun...
+//#ifndef NO_RX_FILTER
+//  PrimaryRadio.setFilterRXISR(FilterRXISR);
+//#endif // NO_RX_FILTER
+
+//  posPOST(1, F("Radio OK, checking buttons/sensors and xtal"));
+
+// FIXME FIXME FIXME
+//  // Collect full set of environmental values before entering loop() in normal mode.
+//  // This should also help ensure that sensors are properly initialised.
+//  const int heat = TemperatureC16.read();
+//#if defined(ENABLE_AMBLIGHT_SENSOR)
+//  const int light = AmbLight.read();
+//#endif
+//#if defined(HUMIDITY_SENSOR_SUPPORT)
+//  const uint8_t rh = RelHumidity.read();
+//#endif
+
+  // Seed RNGs, after having gathered some sensor values in RAM...
+  OTV0P2BASE::seedPRNGs();
+
+//#if defined(ENABLE_NOMINAL_RAD_VALVE)
+//  // Update targets, output to TRV and boiler, etc, to be sensible before main loop starts.
+//  NominalRadValve.read();
+//#endif
+
+  // Ensure that the unique node ID is set up (mainly on first use).
+  // Have one attempt (don't want to stress an already failing EEPROM) to force-reset if not good, then panic.
+  // Needs to have had entropy gathered, etc.
+  if(!OTV0P2BASE::ensureIDCreated())
+    {
+    if(!OTV0P2BASE::ensureIDCreated(true)) // Force reset.
+      { panic(F("ID")); }
+    }
+
+  // Initialised: turn main/heatcall UI LED off.
+  LED_HEATCALL_OFF();
+
+  // Help user get to CLI.
+  OTV0P2BASE::serialPrintlnAndFlush(F("At CLI > prompt enter ? for help"));
+
+// FIXME FIXME FIXME
+//  // Report initial status.
+//  serialStatusReport();
+
+// FIXME FIXME FIXME
+//  // Radio not listening to start with.
+//  // Ignore any initial spurious RX interrupts for example.
+//  PrimaryRadio.listen(false);
+
+  // Set up async edge interrupts.
+  ATOMIC_BLOCK (ATOMIC_RESTORESTATE)
+    {
+    //PCMSK0 = PB; PCINT  0--7    (LEARN1 and Radio)
+    //PCMSK1 = PC; PCINT  8--15
+    //PCMSK2 = PD; PCINT 16--24   (Serial RX and LEARN2 and MODE and Voice)
+
+    PCICR =
+#if defined(MASK_PB) && (MASK_PB != 0) // If PB interrupts required.
+        1 | // 0x1 enables PB/PCMSK0.
+#endif
+#if defined(MASK_PC) && (MASK_PC != 0) // If PC interrupts required.
+        2 | // 0x2 enables PC/PCMSK1.
+#endif
+#if defined(MASK_PD) && (MASK_PD != 0) // If PD interrupts required.
+        4 | // 0x4 enables PD/PCMSK2.
+#endif
+        0;
+
+#if defined(MASK_PB) && (MASK_PB != 0) // If PB interrupts required.
+    PCMSK0 = MASK_PB;
+#endif
+#if defined(MASK_PC) && (MASK_PC != 0) // If PC interrupts required.
+    PCMSK1 = MASK_PC;
+#endif
+#if defined(MASK_PD) && (MASK_PD != 0) // If PD interrupts required.
+    PCMSK2 = MASK_PD;
+#endif
+    }
+
+  // Start local counters in randomised positions to help avoid inter-unit collisions,
+  // eg for mains-powered units starting up together after a power cut,
+  // but without (eg) breaking any of the logic about what order things will be run first time through.
+  // Uses some decent noise to try to start the units separated.
+  const uint8_t b = OTV0P2BASE::getSecureRandomByte(); // randRNG8();
+  // Start within bottom half of minute (or close to); sensor readings happen in second half.
+  OTV0P2BASE::setSeconds(b >> 2);
+  // Start anywhere in first 4 minute cycle.
+  minuteCount = b & 3;
+
+  // Set appropriate loop() values just before entering it.
+  TIME_LSD = OTV0P2BASE::getSecondsLT();
 }

 void loop() {
   // put your main code here, to run repeatedly:

 }
+
+
+
+
+
+
+
+
+
+
+


change args to pass color

change args to pass color

--- src/traffic.ino
+++ src/traffic.ino
@@ -9,21 +9,13 @@
 //
 // curl https://api.spark.io/v1/devices/{DEVICE_ID}/build \
 // -d access_token={ACCESS_TOKEN} \
-// -d "args=PASSED"
-
-// curl https://api.spark.io/v1/devices/{DEVICE_ID}/build \
-// -d access_token={ACCESS_TOKEN} \
-// -d "args=BUILDING"
-
-// curl https://api.spark.io/v1/devices/{DEVICE_ID}/build \
-// -d access_token={ACCESS_TOKEN} \
-// -d "args=FAILED"
-int build(String status) {
-  if (status == "PASSED"){
+// -d "args=green"
+int build(String color) {
+  if (color == "green"){
       digitalWrite(red, LOW);
       digitalWrite(yellow, LOW);
       digitalWrite(green, HIGH);
-  } else if (status == "FAILED") {
+  } else if (color == "red") {
       digitalWrite(red, HIGH);
       digitalWrite(yellow, LOW);
       digitalWrite(green, LOW);
@@ -32,6 +24,7 @@
   }
   return 1;
 }
+

 // Turn off the lights and set up the Spark.function usage.
 void setup() {


VERY slow progress debugging zmodem.

VERY slow progress debugging zmodem.

git-svn-id: d8bfcd070c2c81762cca1b3912331324182919ba@16154 0d6f1817-ed0e-0410-87c9-987e46238f29

--- zimodem/proto_zmodem.ino
+++ zimodem/proto_zmodem.ino
@@ -181,7 +181,7 @@
       act = ZACTION_CANCEL;
     }
   }
-debugPrintf("RACT0 %d\n",act);
+  //debugPrintf("RACT0 %d\n",act);
   switch(act)
   {
   case ZACTION_HEADER:
@@ -228,12 +228,12 @@
       hcrc = updateZCrc(b, hcrcBits, hcrc);
       buf[x+1]=b;
     }
-debugPrintf("RH-BUF: ");
-for(int x=0;x<5;x++)
-  debugPrintf("%s ",TOHEX(buf[x]));
-debugPrintf("CHK: %s ",TOHEX(buf[i]));
-debugPrintf("%s ",TOHEX(buf[i+1]));
-debugPrintf("\n");
+    //debugPrintf("RH-BUF: ");
+    //for(int x=0;x<5;x++)
+    //  debugPrintf("%s ",TOHEX(buf[x]));
+    //debugPrintf("CHK: %s ",TOHEX(buf[i]));
+    //debugPrintf("%s ",TOHEX(buf[i+1]));
+    //debugPrintf("\n");

     if(hcrcBits == 16)
       hcrc = updateZCrc(0, hcrcBits, updateZCrc(0, hcrcBits, hcrc)) & 0xffff;
@@ -255,7 +255,7 @@
     if(htyp==ZMOCHAR_ZDATA || htyp==ZMOCHAR_ZFILE)
       acceptsHeader = false;
     *bufSize = 5;
-    break;
+    return ZSTATUS_HEADER;
   }
   case ZACTION_DATA:
   {
@@ -264,7 +264,17 @@
       crc = updateZCrc(0, crcBits, updateZCrc(0, crcBits, crc)) & 0xffff;
     else
       crc = ~crc;
-debugPrintf("RA-CRCCHK of data type %d\n",dtyp);
+    /*
+    debugPrintf("RA-BUF: ");
+    int x=0;
+    for(x=0;x<(*bufSize)-(crcBits/8);x++)
+      debugPrintf("%s ",TOHEX(buf[x]));
+    debugPrintf("CHK: %s ",TOHEX(buf[x++]));
+    for(;x<(*bufSize);x++)
+      debugPrintf("%s ",TOHEX(buf[x]));
+    debugPrintf("\n");
+    debugPrintf("RA-CRCCHK of data type %d\n",dtyp);
+    */
     uint8_t dcrcBits = crcBits;
     int i=(*bufSize - (dcrcBits/8));
     if(i < 0)
@@ -279,21 +289,20 @@
         return ZSTATUS_INVALIDCHECKSUM;
     }
     *bufSize = *bufSize - (crcBits / 8);
-debugPrintf("RA-SUCCESS! %d\n",*bufSize);
     crc = (crcBits == 16) ? 0 : 0xffffffff;
     if(dtyp==ZMOCHAR_ZCRCG)
       acceptsHeader = false;
     else
       acceptsHeader = true;
-    break;
+    return ZSTATUS_DATA;
   }
   case ZACTION_ESCAPE:
-debugPrintf("RESC TIMEOUT\n");
     return ZSTATUS_TIMEOUT;
   case ZACTION_CANCEL:
-debugPrintf("RCANCEL\n");
     crc = (crcBits == 16) ? 0 : 0xffffffff;
     return ZSTATUS_CANCEL;
+  default:
+    return ZSTATUS_INVALIDCHECKSUM;
   }
 }

@@ -350,7 +359,7 @@

 void ZModem::sendDataPacket(uint8_t type, uint8_t* data, int dataSize)
 {
-  debugPrintf("Send data packet: %d\n",type);
+  //debugPrintf("Send data packet: %d\n",type);
   uint8_t *hbuf = (uint8_t *)malloc((dataSize*2)+64);
   uint8_t hbufIndex=0;
   const uint8_t hcrcBits = 16; // because bin, but not bin32
@@ -398,7 +407,7 @@

 void ZModem::sendBinHeader(uint8_t type, uint8_t* flags)
 {
-  debugPrintf("Send bin header: %d\n",type);
+  //debugPrintf("Send bin header: %d\n",type);
   uint8_t hbuf[15];
   uint8_t hbufIndex=0;
   const uint8_t hcrcBits = 16; // because bin, but not bin32
@@ -437,7 +446,7 @@

 void ZModem::sendHexHeader(uint8_t type, uint8_t* flags)
 {
-  debugPrintf("Send hex header: %d\n",type);
+  //debugPrintf("Send hex header: %d\n",type);
   uint8_t hbuf[15]; // because flags is always 4, so 2 + (4*2) + (2*2) = 14 +0
   uint8_t hbufIndex=0;
   const uint8_t hcrcBits = 16; // because always hex
@@ -500,12 +509,11 @@
   while(lastStatus == ZSTATUS_CONTINUE)
   {
     uint16_t bufSize = 0;
-    debugPrintf("Wait for packet...\n");
     ZStatus packetStatus = readZModemPacket(buf,&bufSize);
-    debugPrintf("Got packet status %d\n",packetStatus);
     if(packetStatus == ZSTATUS_TIMEOUT)
     {
       ++timeouts;
+      debugPrintf("RCV: TIMEOUT %d\n",timeouts);
       if(timeouts>=10)
       {
         sendCancel();
@@ -518,6 +526,7 @@
     if(packetStatus == ZSTATUS_INVALIDCHECKSUM)
     {
       ++errorCount;
+      debugPrintf("RCV: INVALIDCHECKSUM %d\n",errorCount);
       if(errorCount>=3)
       {
         sendCancel();
@@ -529,6 +538,7 @@
     else
     if((packetStatus == ZSTATUS_CANCEL)||(packetStatus == ZSTATUS_FINISH))
     {
+      debugPrintf("RCV: CANCEL/FINISH \n");
       lastStatus = packetStatus;
       break;
     }
@@ -536,20 +546,27 @@
     if(packetStatus == ZSTATUS_HEADER)
     {
       lastStatus = ZSTATUS_CONTINUE;
+      errorCount=0;
+      timeouts=7;
       switch(buf[0])
       {
       case ZMOCHAR_ZRQINIT:
       {
+        debugPrintf("RCV: ZRQINIT\n");
         uint8_t recvOpt[4] ={0,4,0,ZMOPT_ESCCTL|ZMOPT_ESC8};
+        debugPrintf("SND: ZRINIT \n");
         sendHexHeader(ZMOCHAR_ZRINIT, recvOpt);
         break;
       }
       case ZMOCHAR_ZFILE:
+        debugPrintf("RCV: ZFILE\n");
         expect = ZEXPECT_FILENAME;
         break;
       case ZMOCHAR_ZEOF:
       {
+        debugPrintf("RCV: ZEOF\n");
         uint8_t recvOpt[4] ={0,4,0,ZMOPT_ESCCTL|ZMOPT_ESC8};
+        debugPrintf("SND: ZRINIT \n");
         sendHexHeader(ZMOCHAR_ZRINIT, recvOpt);
         expect = ZEXPECT_NOTHING;
         filename = "";
@@ -562,6 +579,19 @@
       case ZMOCHAR_ZDATA:
       {
         uint32_t pos=(buf[1]) | ((uint32_t)buf[2] << 8) | ((uint32_t)buf[2] << 16) | ((uint32_t)buf[2] << 24);
+        debugPrintf("RCV: ZDATA %d\n",pos);
+        if(fileOpen)
+        {
+          if(pos != Foffset)
+          {
+            uint8_t byts[4]={(pos & 0xff),((pos >> 8)&0xff),((pos >> 16)&0xff),((pos >> 24)&0xff)};
+            debugPrintf("SND: ZRPOS %d!=%d \n",pos,Foffset);
+            sendHexHeader(ZMOCHAR_ZRPOS, byts);
+          }
+          else
+            expect = ZEXPECT_DATA;
+        }
+        else
         if(filename.length() > 0)
         {
           Foffset=0;
@@ -585,12 +615,15 @@
       }
       case ZMOCHAR_ZFIN:
       {
+        debugPrintf("RCV: ZFIN\n");
         uint8_t finOpt[4] ={0,0,0,0};
+        debugPrintf("SND: ZFIN\n");
         sendHexHeader(ZMOCHAR_ZFIN, finOpt);
         lastStatus = ZSTATUS_FINISH;
         break;
       }
       default:
+        debugPrintf("RCV: **UNKNOWN**\n");
         sendCancel();
         lastStatus = ZSTATUS_CANCEL;
         break;
@@ -604,13 +637,23 @@
       {
       case ZEXPECT_NOTHING:
       {
+        debugPrintf("RCV: DATAxNOTHING\n");
         uint8_t recvOpt[4] ={0,4,0,ZMOPT_ESCCTL|ZMOPT_ESC8};
+        debugPrintf("SND: ZRINIT\n");
         sendHexHeader(ZMOCHAR_ZRINIT, recvOpt);
         break;
       }
       case ZEXPECT_FILENAME:
       {
+        debugPrintf("RCV: DATAxFILENAME\n");
         filename = "";
+        debugPrintf("RCV: DEBUG:FILENAME:\n");
+        for(int i=0;i<bufSize;i++)
+          if(buf[i]<32)
+            debugPrintf("$%s",TOHEX(buf[i]));
+          else
+            debugPrintf("%c",buf[i]);
+        debugPrintf("\n");
         for(int i=0;i<bufSize && buf[i]!=0;i++)
           if(buf[i] >= 32)
             filename += (char)buf[i];
@@ -622,6 +665,7 @@
           fchk.close();
         }
         uint8_t byts[4]={(pos & 0xff),((pos >> 8)&0xff),((pos >> 16)&0xff),((pos >> 24)&0xff)};
+        debugPrintf("SND: ZRPOS %d\n",pos);
         sendHexHeader(ZMOCHAR_ZRPOS, byts);
         expect = ZEXPECT_NOTHING;
         break;
@@ -635,14 +679,22 @@
         switch(buf[0])
         {
         case ZMOCHAR_ZCRCW:
+          debugPrintf("RCV: DATAxDATA:ZCRCW %d\n",bufSize);
           expect = ZEXPECT_NOTHING;
         case ZMOCHAR_ZCRCQ:
         {
+          debugPrintf("RCV: DATAxDATA:ZCRCW %d\n",bufSize);
           uint8_t byts[4]={(Foffset & 0xff),((Foffset >> 8)&0xff),((Foffset >> 16)&0xff),((Foffset >> 24)&0xff)};
+          debugPrintf("SBD: ZACK %d\n",Foffset);
           sendHexHeader(ZMOCHAR_ZACK, byts);
           break;
         }
         case ZMOCHAR_ZCRCE:
+          debugPrintf("RCV: DATAxDATA:ZCRCE %d\n",bufSize);
+          expect = ZEXPECT_NOTHING;
+          break;
+        default:
+          debugPrintf("RCV: DATAxDATA:UNKNOWN %d, %d\n",buf[0],bufSize);
           expect = ZEXPECT_NOTHING;
           break;
         }
@@ -664,12 +716,11 @@
   while(lastStatus == ZSTATUS_CONTINUE)
   {
     uint16_t bufSize = 0;
-    debugPrintf("Wait for packet...\n");
     ZStatus packetStatus = readZModemPacket(buf,&bufSize);
-    debugPrintf("Got packet status %d\n",packetStatus);
     if(packetStatus == ZSTATUS_TIMEOUT)
     {
       ++timeouts;
+      debugPrintf("RCV: TIMEOUT %d\n",timeouts);
       if(timeouts>=10)
       {
         sendCancel();
@@ -684,6 +735,7 @@
     if(packetStatus == ZSTATUS_INVALIDCHECKSUM)
     {
       ++errorCount;
+      debugPrintf("RCV: INVALIDCHECKSUM %d\n",errorCount);
       if(errorCount>=3)
       {
         sendCancel();
@@ -695,6 +747,7 @@
     else
     if((packetStatus == ZSTATUS_CANCEL)||(packetStatus == ZSTATUS_FINISH))
     {
+      debugPrintf("RCV: CANCEL/FINISH\n");
       lastStatus = packetStatus;
       break;
     }
@@ -702,27 +755,47 @@
     if(packetStatus == ZSTATUS_HEADER)
     {
       lastStatus = ZSTATUS_CONTINUE;
+      errorCount=0;
+      timeouts=7;
       switch(buf[0])
       {
       case ZMOCHAR_ZRINIT:
+        debugPrintf("RCV: ZRINIT\n");
         if(atEOF) // nextFile would go here!
         {
           uint8_t byts[4]={0,0,0,0};
+          debugPrintf("SND: ZFIN\n");
           sendBinHeader(ZMOCHAR_ZFIN, byts);
         }
         else
         {
           uint8_t byts[4] ={0,0,0,ZMOPT_ZCBIN};
           sendBinHeader(ZMOCHAR_ZFILE, byts);
-          String packet="";
+          String rfileSzStr="";
+          rfileSzStr += rfile.size();
           String p=rfile.name();
           int x=p.lastIndexOf("/");
           if((x>=0)&&(x<p.length()-1))
-            packet += p.substring(x+1);
-          packet += '\0';
-          packet += rfile.size();
-          packet += " 0 777 0 0 00";
-          sendDataPacket(ZMOCHAR_ZCRCW, (uint8_t *)packet.c_str(), packet.length());
+            p = p.substring(x+1);
+          uint8_t *pbuf = (uint8_t *)malloc(p.length() + (rfileSzStr.length()*2) + 25);
+          uint16_t pbuflen=0;
+          for(int i=0;i<p.length();i++)
+            pbuf[pbuflen++] = p[i];
+          pbuf[pbuflen++] = 0;
+          for(int i=0;i<rfileSzStr.length();i++)
+            pbuf[pbuflen++] = rfileSzStr[i];
+          //String nums=" 0 0 0 1 ";
+          String nums=" 13207776736 100644";
+          for(int i=0;i<nums.length();i++)
+            pbuf[pbuflen++] = nums[i];
+          //for(int i=0;i<rfileSzStr.length();i++)
+          //  pbuf[pbuflen++] = rfileSzStr[i];
+          //pbuf[pbuflen++] = 0x18;
+          pbuf[pbuflen++] = 0;
+          pbuf[pbuflen++] = 'k';
+          debugPrintf("SND: ZCRCW of len %d\n",pbuflen);
+          sendDataPacket(ZMOCHAR_ZCRCW, pbuf, pbuflen);
+          free(pbuf);
         }
         break;
       case ZMOCHAR_ZRPOS:
@@ -730,18 +803,25 @@
         if(!atEOF)
         {
           uint32_t pos=(buf[1]) | ((uint32_t)buf[2] << 8) | ((uint32_t)buf[2] << 16) | ((uint32_t)buf[2] << 24);
+          debugPrintf("RCV: ZRPOS %d==%d\n",pos,Foffset);
           if(pos!=Foffset)
           {
             rfile.seek(pos);
             Foffset = pos;
           }
         }
+        else
+          debugPrintf("RCV: ZRPOS ??\n");
       }
       //FALLTHROUGH OK!
       case ZMOCHAR_ZACK:
       {
+        if(buf[0] == ZMOCHAR_ZACK)
+          debugPrintf("RCV: ZACK\n");
+
         {
           uint8_t byts[4]={(Foffset & 0xff),((Foffset >> 8)&0xff),((Foffset >> 16)&0xff),((Foffset >> 24)&0xff)};
+          debugPrintf("SND: ZDATA: %d\n",Foffset);
           sendBinHeader(ZMOCHAR_ZDATA, byts);
           uint8_t data[1024];
           int len = rfile.read(data, 1024);
@@ -752,21 +832,25 @@
             type=ZMOCHAR_ZCRCE;
           }
           Foffset += len;
+          debugPrintf("SND: ZDATA: DATA LEN=%d\n",len);
           sendDataPacket(type, data, len);
         }
         if(atEOF)
         {
           uint8_t byts[4]={(Foffset & 0xff),((Foffset >> 8)&0xff),((Foffset >> 16)&0xff),((Foffset >> 24)&0xff)};
+          debugPrintf("SND: ZEOF\n");
           sendHexHeader(ZMOCHAR_ZEOF, byts);
         }
         break;
       }
       case ZMOCHAR_ZFIN:
+        debugPrintf("RCV: ZFIN\n");
         for(int i=0;i<2;i++)
           mdmOt->printb('O');
         lastStatus = ZSTATUS_FINISH;
         break;
       default:
+        debugPrintf("RCV: %d??!! CANCELLING!\n",buf[0]);
         sendCancel();
         lastStatus = ZSTATUS_CANCEL;
         break;


Fixed issue where title song played into the 1st stage

--- arduboy-game/arduboy-game.ino
+++ arduboy-game/arduboy-game.ino
@@ -15,7 +15,6 @@
 #include <inttypes.h>
 #include <Arduino.h>
 #include <avr/pgmspace.h>
-#include <avr/pgmspace.h>

 #define DEBOUNCE_DELAY 100
 #define MAX_LIVES 4
@@ -30,7 +29,7 @@
 byte starWidth[NUM_STARS];

 bool musicOn = true;
-byte currentSong = 0;
+byte currentSong = 255;

 // Bullet arrays
 Bullet playerBullets[MAX_PLAYER_BULLETS];
@@ -398,7 +397,8 @@
   score = 0;
   livesRemaining = MAX_LIVES;
   spaceShip.reset();
-
+  stopMusic();
+
   while (livesRemaining > 0) {
     arduboy.clear();
     inGameFrame++;


Removing comments

Removing comments

--- arduboy-game/arduboy-game.ino
+++ arduboy-game/arduboy-game.ino
@@ -145,21 +145,6 @@
   }

   if (delayTimer) {
-      // There is still an overflow here that needs to be dealt with:
-      //     /Users/richard/Documents/arduboy-game/arduboy-game/arduboy-game.ino: In function 'void drawChrs(byte, byte, const uint8_t*, long unsigned int)':
-      //     /Users/richard/Documents/arduboy-game/arduboy-game/arduboy-game.ino:150:23: warning: large integer implicitly truncated to unsigned type [-Woverflow]
-      //       playTone(800, 15);
-      //                       ^
-      ///Users/richard/Documents/arduboy-game/arduboy-game/arduboy-game.ino:152:24: warning: large integer implicitly truncated to unsigned type [-Woverflow]
-      //       playTone(1200, 30);
-      //                        ^
-      //
-      // Changing the signature of playTone to playTone(unsigned long, byte) would resolve it but we don't
-      // have space for that.
-      // The behavior currently is undefined.
-      //
-      // We should probably pick 2 values that are in the range 0-255 for the first parameter
-      // of these functions if we can't squeeze
       playTone(800, 15);
       delay(15);
       playTone(1200, 30);


Light all if no audio connected

Light all if no audio connected

--- arduino/fasnacht/fasnacht.ino
+++ arduino/fasnacht/fasnacht.ino
@@ -112,7 +112,7 @@
       digitalWrite(3, 0); //B
       digitalWrite(5, 0); //D
       //Serial.println("B ON  D OFF ");
-    } else if( (ValueFrq >= 300) && (ValueFrq <= 399) ) {
+    } else if(((ValueFrq >= 300) && (ValueFrq <= 399)) || ValueFrq > 499) {
       digitalWrite(3, 1); //B
       digitalWrite(5, 1); //D
       //Serial.println("B OFF D ON  ");
@@ -133,7 +133,7 @@
       digitalWrite(6, 0); //E
       digitalWrite(9, 0); //H
       //Serial.println("E ON  H OFF ");
-    } else if( (ChannelFrq >= 300) && (ChannelFrq <= 399) ) {
+    } else if(((ChannelFrq >= 300) && (ChannelFrq <= 399)) || ChannelFrq > 499) {
       digitalWrite(6, 1); //E
       digitalWrite(9, 1); //H
       //Serial.println("E OFF H ON  ");