authenticate on new sector skip trailing block

--- examples/WriteTag/WriteTag.ino
+++ examples/WriteTag/WriteTag.ino
@@ -60,6 +60,9 @@
       NdefMessage* m = new NdefMessage();
       m->addTextRecord("Hello, World");
       m->addUriRecord("http://arduino.cc");
+      m->addEmptyRecord();
+      m->addTextRecord("Goodbye, World");
+
       m->print();

       write(*m, uid, uidLength);
@@ -81,12 +84,23 @@
 // TODO return success / failure
 void write(NdefMessage& m, uint8_t * uid, int uidLength)
 {
+    int BLOCK_SIZE = 16;

     uint8_t encoded[m.getEncodedSize()];
     m.encode(encoded);

     // TLV wrapper
     // assuming short TLV  3 bytes type +  byte length of data + NDEF_DATA + 1 byte terminator
+    int buffer_size = sizeof(encoded) + 5;
+    Serial.print("buffer_size ");Serial.println(buffer_size);
+
+    // buffer_size needs to be a multiple of BLOCK_SIZE
+    if (buffer_size % BLOCK_SIZE != 0)
+    {
+      buffer_size = ((buffer_size / BLOCK_SIZE) + 1) * BLOCK_SIZE;
+      Serial.print("Adjusted buffer_size to ");Serial.println(buffer_size);
+    }
+
     uint8_t buffer[sizeof(encoded) + 5];
     buffer[0] = 0x0;
     buffer[1] = 0x0;
@@ -98,41 +112,39 @@
     // Write to tag
     int index = 0;
     int currentBlock = 4;
-    int BLOCK_SIZE = 16;
+    uint8_t key[6] = { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 }; // this is Sector 1 - 15 key

-    // lame check dues to bad implemenation
-    if (sizeof(buffer) > BLOCK_SIZE * 3) {
-      Serial.println();
-      Serial.println("ERROR: Message is too large.");
-      Serial.println("Message can not exceed 3 blocks or 48 bytes (with TLV)");
-      while(1); // halt
+    while (index < sizeof(buffer))
+    {
+
+      if (nfc.mifareclassic_IsFirstBlock(currentBlock))
+      {
+        int success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key);
+        if (!success)
+        {
+          Serial.print("Error. Block Authentication failed for ");Serial.println(currentBlock);
+          while (1); // halt
+        }
+      }
+
+      int write_success = nfc.mifareclassic_WriteDataBlock (currentBlock, &buffer[index]);
+      if (write_success) {
+          Serial.print("wrote block ");Serial.println(currentBlock);
+      } else {
+          Serial.println("write failed");
+          while (1); // halt
+      }
+      index += BLOCK_SIZE;
+      currentBlock++;
+
+      if (nfc.mifareclassic_IsTrailerBlock(currentBlock))
+      {
+        // can't write to trailer block
+        Serial.print("skipping block ");Serial.println(currentBlock);
+        currentBlock++;
+      }
+
     }
-
-    uint8_t key[6] = { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 }; // this is Sector 1 - 15 key
-
-    // Start with block 4, the first block of sector 1. Note sector 0 contains the manufacturer data.
-    uint8_t success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key);
-
-    if (success)
-    {
-      Serial.println("Sector 1 (Blocks 4..7) has been authenticated");
-
-      while (index < sizeof(buffer))
-      {
-        int write_success = nfc.mifareclassic_WriteDataBlock (currentBlock, &buffer[index]);
-        if (write_success) {
-            Serial.print("wrote block ");Serial.println(currentBlock);
-        } else {
-            Serial.println("write failed");
-        }
-        index += BLOCK_SIZE;
-        currentBlock++; // this will fail on block 7
-      }
-
-    }
-    else
-    {
-      Serial.println("Error. Block Authentication failed.");
-    }
+
 }


Does not queue up zones with no time value

Fixes open issue (enhancement) #17.  Added a strcmp to "toggleON" and to "allOn" logic to skip over commands to queue up zones set to run for 0 mins.

--- ArduinoSmartShieldIrrigationController.ino
+++ ArduinoSmartShieldIrrigationController.ino
@@ -1,7 +1,7 @@

 /**
  ****************************************************************************************************************************
- * Irrigation Controller v2.3
+ * Irrigation Controller v2.4
  * Simple, elegant irrigation controller that takes advantage of the cloud and SmartThings ecosystem
  * Arduino UNO with SmartThings Shield  and an 8 Relay Module
  * Works by receiving irrigation run times from the Cloud and then builds a queue to execute
@@ -169,7 +169,7 @@
     inValue [i] = strtok(NULL, delimiters); //remove remaining substrings as incoming values
     i++;
   }
-  if (strcmp(inValue[0],"on")==0) {   // add new station to queue
+  if (strcmp(inValue[0],"on")==0 && strcmp(inValue[2],"0")==1) {   // add new station to queue
     int addStation=atoi(inValue[1]);
     queue[addStation]=1;
     stationTime[addStation]=atol(inValue[2])*60L*1000L;
@@ -190,7 +190,7 @@
   if (strcmp(inValue[0],"allOn")==0) {
     int i=1;
     while (i<stations+1) {
-      if (i != trafficCop) {
+      if (i != trafficCop && (strcmp(inValue[i],"0")==1)) {
         queue[i]=1;
       }
       stationTime[i]=atoi(inValue[i])*60L*1000L;
@@ -272,4 +272,4 @@
   }
   smartthing.send(statusUpdate);
   statusUpdate = "";
-}+}


Add rotation for new package with matrix input at lower left

--- src/badge/badge.ino
+++ src/badge/badge.ino
@@ -30,9 +30,10 @@
 // to accomodate packaging of the LED matrix with different locations of the connector
 const int rotationZero = NEO_MATRIX_TOP + NEO_MATRIX_LEFT + NEO_MATRIX_ROWS;
 const int rotationNinety = NEO_MATRIX_TOP + NEO_MATRIX_RIGHT + NEO_MATRIX_COLUMNS;
+const int rotationOneEighty = NEO_MATRIX_BOTTOM + NEO_MATRIX_LEFT + NEO_MATRIX_COLUMNS;

 Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(8, 8, PIN,
-    rotationNinety + NEO_MATRIX_PROGRESSIVE,
+    rotationOneEighty + NEO_MATRIX_PROGRESSIVE,
     NEO_GRB + NEO_KHZ400);

 TickerAnimation ticker(matrix);


stairs: add gradient breathing mode

stairs: add gradient breathing mode

--- stairs/main.ino
+++ stairs/main.ino
@@ -37,6 +37,7 @@
 // All the different modes available.
 #define MAX_MODES 10
 void modeBreathe();
+void modeBreatheGradient();
 void modeEase();
 void modeGradient();
 void modeOff();
@@ -54,8 +55,8 @@
     &modeRainbow,
     &modeRainbowTrain,
     &modeBreathe,
+    &modeBreatheGradient,
     &modeSine,
-    &modeOff,
     &modeOff
 };

@@ -96,7 +97,7 @@
 #endif

 // animate returns true if the animation should be stepped.
-uint8_t animate() {
+uint8_t animate(uint8_t speed) {
     static uint32_t lastClock = 0;
     uint32_t diff;
     uint32_t clock;
@@ -110,7 +111,7 @@
     clock = millis();
     diff = clock - lastClock;

-    expectedDelay = map(pots.var, 1, 255, 250, 1);
+    expectedDelay = map(speed, 1, 255, 250, 1);
     if (diff >= expectedDelay) {
         lastClock = clock;
         return 1;
@@ -120,9 +121,9 @@
 }

 // animation animates from 0-255.
-uint8_t animation() {
+uint8_t animation(uint8_t speed) {
     static uint8_t an = 0;
-    an += animate();
+    an += animate(speed);
     return an;
 }

@@ -142,9 +143,9 @@
     if (analog < 508)   return 3;
     if (analog < 604)   return 4;
     if (analog < 694)   return 5;
-    if (analog < 765)   return 7;
+    if (analog < 764)   return 7;
     if (analog < 929)   return 6;
-    if (analog < 957)   return 8;
+    if (analog < 955)   return 8;
     return 9;
 }

@@ -177,7 +178,7 @@
 void modeRainbow() {
     uint8_t hue;
     for (uint8_t led = 0; led < NUM_LEDS; led++) {
-        hue = ledAngle(led) + animation() + pots.hue;
+        hue = ledAngle(led) + animation(pots.var) + pots.hue;
         leds[led] = CHSV(hue, pots.sat, pots.val);
     }
 }
@@ -188,12 +189,12 @@
     uint8_t sine;
     uint8_t value;

-    sine = cubicwave8(animation());
+    sine = cubicwave8(animation(pots.var));
     start = pots.val - 100;
     if (start > pots.val) {
         start = 0;
     }
-    value = map(sine, 0, 255, start, pots.val);
+    value = map8(sine, start, pots.val);

 #ifdef DEBUG_ANIMATION
     char buf[128];
@@ -205,11 +206,29 @@
     fill_solid(&leds[0], NUM_LEDS, CHSV(pots.hue, pots.sat, value));
 }

+// Fill all LEDs with a single color, animating between two hues in a cubic
+// ease in-out wave resembling a sine wave. The speed is calculated
+// automatically based on distance on the color wheel.
+void modeBreatheGradient() {
+    uint8_t angle;
+    uint8_t hue;
+    uint8_t distance;
+    uint8_t speed;
+
+    distance = pots.var - pots.hue;
+    speed = 255 - map8(distance, 15, 130);
+
+    angle = cubicwave8(animation(speed));
+    hue = map8(angle, pots.hue, pots.var);
+
+    fill_solid(&leds[0], NUM_LEDS, CHSV(hue, pots.sat, pots.val));
+}
+
 // Animate each LED's intensity according to a sine wave.
 void modeSine() {
     uint8_t angle;
     uint8_t value;
-    uint8_t an = animation();
+    uint8_t an = animation(pots.var);
     for (uint8_t led = 0; led < NUM_LEDS; led++) {
         angle = ledAngle(led);
         value = sin8(angle + an);
@@ -222,7 +241,7 @@
 void modeEase() {
     uint8_t angle;
     uint8_t value;
-    uint8_t an = animation();
+    uint8_t an = animation(pots.var);
     for (uint8_t led = 0; led < NUM_LEDS; led++) {
         angle = map(led, 0, NUM_LEDS-1, 0, 255);
         value = ease8InOutCubic(sin8(angle + an));
@@ -237,7 +256,7 @@
     uint8_t hue = 0;
     uint8_t angle;
     uint8_t value;
-    uint8_t an = animation();
+    uint8_t an = animation(pots.var);
     for (uint8_t led = 0; led < NUM_LEDS; led++) {
         angle = map(led, 0, NUM_LEDS-1, 0, 255);
         value = ease8InOutCubic(sin8(angle + an));


Moved api call into alpabetical order.

Moved api call into alpabetical order.

Removed some stale code.

--- webservertask.ino
+++ webservertask.ino
@@ -236,15 +236,6 @@
       return request->send( response );
     }

-    else if ( request->hasArg( "tftorientation" ) )
-    {
-      if ( !xTftTaskHandle )
-      {
-        return request->send( 501, textHtmlHeader, "Not present." );
-      }
-      return request->send( 200, textHtmlHeader, ( tftOrientation == TFT_ORIENTATION_NORMAL ) ? "normal" : "upsidedown" );
-    }
-
     else if ( request->hasArg( "sensor" ) )
     {
       if ( !numberOfFoundSensors )
@@ -322,6 +313,15 @@
       return request->send( response );
     }

+    else if ( request->hasArg( "tftorientation" ) )
+    {
+      if ( !xTftTaskHandle )
+      {
+        return request->send( 501, textHtmlHeader, "Not present." );
+      }
+      return request->send( 200, textHtmlHeader, ( tftOrientation == TFT_ORIENTATION_NORMAL ) ? "normal" : "upsidedown" );
+    }
+
     else if ( request->hasArg( "timezone" ) )
     {
       response = request->beginResponseStream( textHtmlHeader );
@@ -336,8 +336,6 @@

     else if ( request->hasArg( "wifissid" ) )
     {
-      //response = request->beginResponseStream( textHtmlHeader );
-      //response->printf( "%s", WiFi.SSID().c_str() );
       return request->send( 200, textHtmlHeader, WiFi.SSID().c_str() );
     }


added check if relay already set to requested state

--- src/sonoff-relay.ino
+++ src/sonoff-relay.ino
@@ -31,7 +31,7 @@

 /* Set relay to ON */
 void SonoffRelay::on() {
-  digitalWrite(RELAY, HIGH);
+  if (get()==RELAY_OFF) digitalWrite(RELAY, HIGH);
   publish();
   if (Configuration.debugger) Serial << "Relay set to ON" << endl;
   Eeprom.saveRelayState(RELAY_ON);
@@ -40,7 +40,7 @@

 /* Set relay to OFF */
 void SonoffRelay::off() {
-  digitalWrite(RELAY, LOW);
+  if (get()==RELAY_ON) digitalWrite(RELAY, LOW);
   publish();
   if (Configuration.debugger) Serial << "Relay set to OFF" << endl;
   Eeprom.saveRelayState(RELAY_OFF);


v6.0 Add theme to splash screen

v6.0 Add theme to splash screen

--- PictureViewer.ino
+++ PictureViewer.ino
@@ -307,6 +307,8 @@

 // Displays the splash screen
 void displaySplashScreen(displayModeEnum displayMode) {
+  byte maxLeghtOfTheme;
+
   tft.setTextWrap(false);
   tft.fillScreen(ST7735_BLACK);
   tft.setCursor(0, 5);
@@ -319,13 +321,18 @@
   tft.setCursor(20, 40);
   tft.print("Version ");
   tft.println(VERSION);
+  tft.setTextColor(ST7735_YELLOW);
+  maxLeghtOfTheme = min(themeField.length(), MAXTHEMELENGTH); // Limit characters
+  tft.setCursor((HALFTHEMELENGTH - (maxLeghtOfTheme / 2)) * LCDWIDTHOFFSET, 55);
+  tft.println(themeField);
   tft.setTextSize(2);
-  tft.println("");
+  tft.setCursor(0, 75);
   tft.setTextColor(ST7735_BLUE);
   tft.println("GK Grotsky");
-  tft.println("");
+  tft.setCursor(0, 100);
   tft.setTextColor(ST7735_GREEN);
   tft.println("Mode:");
+  tft.setCursor(0, 115);
   if (displayMode == NonTest) {
     tft.println((digitalRead(MODE_PIN)) ? "Random" : "Sequential");
   }
@@ -399,10 +406,9 @@
     tft.println("Test");
   }
   tft.setCursor(0, 15);
-  tft.println("Theme:");
   // Center the theme
   maxLeghtOfTheme = min(themeField.length(), MAXTHEMELENGTH); // Limit characters
-  tft.setCursor((HALFTHEMELENGTH - (maxLeghtOfTheme / 2)) * LCDWIDTHOFFSET, 25);
+  tft.setCursor((HALFTHEMELENGTH - (maxLeghtOfTheme / 2)) * LCDWIDTHOFFSET, 20);
   tft.println(themeField);
   tft.setTextSize(2);
   tft.setCursor(10, 50);


Adds code to generate the CDI.xml on the fly.

--- arduino/examples/ESP32IOBoard/ESP32IOBoard.ino
+++ arduino/examples/ESP32IOBoard/ESP32IOBoard.ino
@@ -34,11 +34,13 @@

 #include <Arduino.h>
 #include <WiFi.h>
+#include <SPIFFS.h>
 #include <ESPmDNS.h>
 #include <vector>

 #include <OpenMRN.h>
 #include <openlcb/TcpDefs.hxx>
+#include <utils/FileUtils.hxx>
 #include "config.h"

 constexpr uint16_t OPENMRN_TCP_PORT = 12021L;
@@ -116,7 +118,47 @@
     WiFiClient client_;
 };

+const char CDI_FILENAME[] = "/spiffs/cdi.xml";
+namespace openlcb {
+// This will stop openlcb from exporting the CDI memory space upon start.
+extern const char CDI_DATA[] = "";
+}
+
 void setup() {
+    SPIFFS.begin(true);
+    string cdi_string;
+    cfg.config_renderer().render_cdi(&cdi_string);
+
+    bool need_write = false;
+    FILE* ff = fopen(CDI_FILENAME, "rb");
+    if (!ff) {
+      need_write = true;
+    } else {
+      fclose(ff);
+      string current_str = read_file_to_string(CDI_FILENAME);
+      if (current_str != cdi_string) {
+        need_write = true;
+      }
+    }
+    if (need_write) {
+
+       int fd = ::open(CDI_FILENAME, O_CREAT|O_TRUNC|O_RDWR, S_IRUSR | S_IWUSR);
+        if (fd < 0)
+        {
+            printf("Failed to create config file: fd %d errno %d: %s\n",
+                   fd, errno, strerror(errno));
+            DIE();
+        }
+        close(fd);
+
+      printf("Updating CDI file %s (len %u)", CDI_FILENAME, cdi_string.size());
+      write_string_to_file(CDI_FILENAME, cdi_string);
+    }
+
+    openlcb::MemorySpace* space = new openlcb::ROFileMemorySpace(CDI_FILENAME);
+    openmrn.stack()->memory_config_handler()->registry()->insert(
+            openmrn.stack()->node(), openlcb::MemoryConfigDefs::SPACE_CDI, space);
+
     Serial.begin(115200L);

     printf("\nConnecting to: %s\n", ssid);


divide brightness to effect_brightness and instrument_brightness

--- ptw-wheel.ino
+++ ptw-wheel.ino
@@ -38,8 +38,9 @@
 int e_color_g = 0;
 int e_color_b = 255;

-float brightness_min = 0.5; // 平常時のBrightness
-float brightness = 1;
+float instrument_brightness_min = 0.5; // default brightness
+float instrument_brightness = 1;
+float effect_brightness = 0;

 int divide = 2; // LEDパターンの分割数
 float slit_position = 0.5; // 0~1 分割された区分の中のどこまでがinstrumentにするか。0だと全部effect color。1だと全部instrument color。
@@ -108,7 +109,7 @@
     // sound trigger
     // "s:;"
     else if(command=="s") {
-      brightness = 1.0;
+      instrument_brightness = 1.0;
       instrument_flag = !instrument_flag;
     }
     // set divide number
@@ -137,14 +138,14 @@
       Serial.println(slit_position);
       updateLED();
     }
-    // set brightness min value
+    // set instrument_brightness min value
     // "b:[0.0-1.0];"
     else if(command=="b") {
       // TODO argument check
       // argument is float
-      brightness_min = argument.toFloat();
-      Serial.print("set brightness min value: ");
-      Serial.println(brightness_min);
+      instrument_brightness_min = argument.toFloat();
+      Serial.print("set instrument_brightness min value: ");
+      Serial.println(instrument_brightness_min);
       updateLED();
     }
     else {
@@ -153,8 +154,8 @@
     }
   }
   else {
-    if(brightness_min+0.01 <= brightness) {
-      brightness -= 0.01;
+    if(instrument_brightness_min+0.01 <= instrument_brightness) {
+      instrument_brightness -= 0.01;
       updateLED();
     }
   }
@@ -181,8 +182,8 @@
 }

 void updateLED() {
-  uint32_t instrument_color = multiplicateBrightness(constrainValue(i_color_r), constrainValue(i_color_g), constrainValue(i_color_b));
-  uint32_t effect_color = multiplicateBrightness(constrainValue(e_color_r), constrainValue(e_color_g), constrainValue(e_color_b));
+  uint32_t instrument_color = multiplicateBrightness(constrainValue(i_color_r), constrainValue(i_color_g), constrainValue(i_color_b), instrument_brightness);
+  uint32_t effect_color = multiplicateBrightness(constrainValue(e_color_r), constrainValue(e_color_g), constrainValue(e_color_b), effect_brightness);

   switch (i_type) {

@@ -294,10 +295,10 @@
   strip.show();
 }

-uint32_t multiplicateBrightness(int _r, int _g, int _b) {
-  int r = (int) _r*brightness;
-  int g = (int) _g*brightness;
-  int b = (int) _b*brightness;
+uint32_t multiplicateBrightness(int _r, int _g, int _b, float _brightness) {
+  int r = (int) _r*_brightness;
+  int g = (int) _g*_brightness;
+  int b = (int) _b*_brightness;
   return strip.Color(r, g, b);
 }


Add debug mode

Add debug mode

--- ptw-wheel.ino
+++ ptw-wheel.ino
@@ -2,6 +2,13 @@
 #include <HSBColor.h>

 // Arduino Nano v2.x, v3.x
+
+// ----------------
+// LEDのテスト用に200個のLEDをレインボー表示させるモードにするフラグ
+// ここをtrueにするときは、その下のTOTAL_PIXELSも200にして、その後のTOTAL_PIXELSの定義をコメントアウトしておくこと
+bool debug = false;
+// #define TOTAL_PIXELS 200 // for debug mode
+// ----------------

 #define TOTAL_PIXELS 99 // 大人用バスケ（緑・シルバー・黄）, 展示大人用テニス
 // #define TOTAL_PIXELS 94 // 大人用バスケ（無塗装）
@@ -57,6 +64,11 @@
 void setup() {
   strip.begin();
   strip.show(); // Initialize all pixels to 'off'
+
+  if(debug){
+    return;
+  }
+
   Serial.begin(9600);
   randomSeed(analogRead(0));

@@ -101,6 +113,11 @@
 }

 void loop() {
+  if(debug){
+    rainbow(2);
+    return;
+  }
+
   if (0<Serial.available()) {
     String command = Serial.readStringUntil(':');
     String argument = Serial.readStringUntil(';');


Better place for endTransmission

Better place for endTransmission

--- RealTimeClock/RealTimeClock.ino
+++ RealTimeClock/RealTimeClock.ino
@@ -15,12 +15,12 @@
   // sekundy jsou ulozeny v 1 byte
   Wire.requestFrom(DS1307_CTRL_ID, 1);
   int s = Wire.read();
+  Wire.endTransmission();
+
   Serial.println(s);
   // desitky sekund jsou v bitech 4-6, je treba je posunout o 4 bity doprava
   Serial.print((s & 0b01110000) >> 4);
   // jednotky sekund jsou v bitech 0-3, proto pouzijeme masku
   Serial.println(s & 0b00001111);
-  Wire.endTransmission();
-
   delay(1000);
 }


Simplify check_radio

Simplify check_radio

--- Receiver_test/Receiver_test.ino
+++ Receiver_test/Receiver_test.ino
@@ -158,19 +158,11 @@
 bool check_radio(void){
   if (radio.available()){
     timeout = millis() + 10000;
-    if (msg[1] == 0){
+    if (msg[1] == 0 || msg[1] == addr){
       return true;
     }
-    else if (msg[1] == addr){
-      return true;
-    }
-    else
-    {
-      return false;
-    }
-  }
-  else
-  {
+    // for safety reset msg target to a value that matches no lantern
+    msg[1] = 255;
     return false;
   }
 }
@@ -201,4 +193,4 @@
 // eof

-
+


fix the gear numbering

fix the gear numbering

--- software/decision/decision.ino
+++ software/decision/decision.ino
@@ -7,6 +7,8 @@
 #define HALL P1_5

 #define SHIFT_OFFSET 10
+
+#define GEAR_COUNT 8

 // global variable declarations
 unsigned long oldtime;
@@ -97,7 +99,7 @@

     if (radio_data.header == SWITCHER_HEADER) {
       gear_data = radio_data.gear;
-      gear = gear_data.gear;
+      gear = GEAR_COUNT - gear_data.gear;
     }
     else if (radio_data.header == INTERFACE_HEADER) {
       target_data = radio_data.target;


update switcher

update switcher

--- software/switcher/switcher.ino
+++ software/switcher/switcher.ino
@@ -29,7 +29,7 @@
 bool down;

 // initalize gear count
-int gear = 7;
+int gear = 8;
 int gear_number = 8;

 // function


added explicit cast to satisfy permissive compiler settings (#22)

--- Arduino/adrilight/adrilight.ino
+++ Arduino/adrilight/adrilight.ino
@@ -61,7 +61,7 @@
 {
     if (waitForPreamble(TIMEOUT))
     {
-        Serial.readBytes(buffer, NUM_BYTES);
+        Serial.readBytes((char*)buffer, NUM_BYTES);

         while (byte_counter < NUM_BYTES)
         {


changed breathe from blue to red(thinking more movie theater like..)

--- Scripts/fourelevenseventeen.ino
+++ Scripts/fourelevenseventeen.ino
@@ -50,38 +50,38 @@
  void loop() {

     if (timeOut+15700 < millis()) {        // idle state - 'breathe' the top and bottom LED to show program is looping
-       uint32_t blue = (0, 0, breathe);
+       uint32_t red = (breathe, 0, 0);
        breathe = breathe + change;
-       strip.setPixelColor(0, blue);
-       strip.setPixelColor(27, blue);
-       strip.setPixelColor(28, blue);
-       strip.setPixelColor(57, blue);
-       strip.setPixelColor(58, blue);
-       strip.setPixelColor(87, blue);
-       strip.setPixelColor(88, blue);
-       strip.setPixelColor(117, blue);
-       strip.setPixelColor(118, blue);
-       strip.setPixelColor(147, blue);
-       strip.setPixelColor(148, blue);
-       strip.setPixelColor(177, blue);
-       strip.setPixelColor(178, blue);
-       strip.setPixelColor(207, blue);
-       strip.setPixelColor(208, blue);
-       strip.setPixelColor(237, blue);
-       strip.setPixelColor(238, blue);
-       strip.setPixelColor(267, blue);
-       strip.setPixelColor(268, blue);
-       strip.setPixelColor(297, blue);
-       strip.setPixelColor(298, blue);
-       strip.setPixelColor(327, blue);
-       strip.setPixelColor(328, blue);
-       strip.setPixelColor(357, blue);
-       strip.setPixelColor(358, blue);
-       strip.setPixelColor(387, blue);
-       strip.setPixelColor(388, blue);
-       strip.setPixelColor(417, blue);
-       strip.setPixelColor(418, blue);
-       strip.setPixelColor(446, blue);
+       strip.setPixelColor(0, red);
+       strip.setPixelColor(27, red);
+       strip.setPixelColor(28, red);
+       strip.setPixelColor(57, red);
+       strip.setPixelColor(58, red);
+       strip.setPixelColor(87, red);
+       strip.setPixelColor(88, red);
+       strip.setPixelColor(117, red);
+       strip.setPixelColor(118, red);
+       strip.setPixelColor(147, red);
+       strip.setPixelColor(148, red);
+       strip.setPixelColor(177, red);
+       strip.setPixelColor(178, red);
+       strip.setPixelColor(207, red);
+       strip.setPixelColor(208, red);
+       strip.setPixelColor(237, red);
+       strip.setPixelColor(238, red);
+       strip.setPixelColor(267, red);
+       strip.setPixelColor(268, red);
+       strip.setPixelColor(297, red);
+       strip.setPixelColor(298, red);
+       strip.setPixelColor(327, red);
+       strip.setPixelColor(328, red);
+       strip.setPixelColor(357, red);
+       strip.setPixelColor(358, red);
+       strip.setPixelColor(387, red);
+       strip.setPixelColor(388, red);
+       strip.setPixelColor(417, red);
+       strip.setPixelColor(418, red);
+       strip.setPixelColor(446, red);
        strip.show();
        if (breathe == 100 || breathe == 0) change = -change;      // breathe the LED from 0 = off to 100 = fairly bright
        if (breathe == 100 || breathe == 0); delay (100);           // Pause at beginning and end of each breath


Fix internal clock timer.

Fix internal clock timer.

--- examples/seq/seq.ino
+++ examples/seq/seq.ino
@@ -163,6 +163,7 @@
     if(retrigger)
     {
       retrigger = false;
+      clock_gate &= seq_values.clock_ext;
     }
   }

@@ -262,7 +263,8 @@
     }
     seq_values.clock_period = bpm_to_ms(params.vals.clock_bpm);
     seq_values.clock_ext = !(bool)params.vals.clock_bpm;
-    update_clock();
+    Timer1.initialize(seq_values.clock_period * 1000);
+    Timer1.attachInterrupt(clock_isr);

     // draw global elements
     display->draw_char(38, 2, '0' + params.vals.stage_count, DUINO_SSD1306::White);
@@ -517,10 +519,13 @@
  private:
   void update_clock()
   {
-    Timer1.detachInterrupt();
-    if(!seq_values.clock_ext)
-    {
-      Timer1.initialize(seq_values.clock_period * 1000);
+    if(seq_values.clock_ext)
+    {
+      Timer1.detachInterrupt();
+    }
+    else
+    {
+      Timer1.setPeriod(seq_values.clock_period * 1000);
       Timer1.attachInterrupt(clock_isr);
     }
   }
@@ -707,7 +712,8 @@

 void clock_isr()
 {
-  clock_gate = function->gt_read(GT3);
+  clock_gate = !seq_values.clock_ext || function->gt_read(GT3);
+
   if(clock_gate)
   {
     step++;


fix battery checker bug.

fix battery checker bug.

--- roof_sensor_serial/roof_sensor_serial.ino
+++ roof_sensor_serial/roof_sensor_serial.ino
@@ -110,6 +110,7 @@
 void updateVoltage() {
   Serial.print(TEXT_BATTERY);
   Serial.println( readVcc(), DEC );
+  batteryCounter = 1;
 }

 // gets the number of windTurns


NBand_Stereo: Update comments to reflect name "NBand"

--- examples/05-FullSystems/WDRC_NBand_Stereo_Earpiece_Prescrip_wApp/WDRC_NBand_Stereo_Earpiece_Prescrip_wApp.ino
+++ examples/05-FullSystems/WDRC_NBand_Stereo_Earpiece_Prescrip_wApp/WDRC_NBand_Stereo_Earpiece_Prescrip_wApp.ino
@@ -1,5 +1,5 @@
 /*
-  WDRC_12BandIIR_Stereo_Earpieces_Prescrip_wApp
+  WDRC_NBand_Stereo_Earpieces_Prescrip_wApp

   Created: Chip Audette (OpenAudio), Oct 2021
     Primarly built upon CHAPRO "Generic Hearing Aid" from
@@ -147,7 +147,7 @@
 void setup() {
   myTympan.beginBothSerial();
   if (Serial) Serial.print(CrashReport);
-  Serial.println("WDRC_XBand_Stereo_Earpiece_Prescrip_wApp: setup():...");
+  Serial.println("WDRC_NBand_Stereo_Earpiece_Prescrip_wApp: setup():...");
   Serial.print("Sample Rate (Hz): "); Serial.println(audio_settings.sample_rate_Hz);
   Serial.print("Audio Block Size (samples): "); Serial.println(audio_settings.audio_block_samples);


updates

updates

--- garden.ino
+++ garden.ino
@@ -59,6 +59,12 @@
     {
         zones_all_off("");
     }
+    else
+    {
+        dString = (currentTime - stopTime) + " seconds remaining";
+    }
+
+
 }
 int readZone(String command)
 {
@@ -85,13 +91,8 @@
 // *************** Particle Functions **********************************
 int runZone(String command) {

-    Serial.print("runZone...");
-    Serial.println(command);
-
     int zone_i = readZone(command);
     int zone_duration = readDuration(command);
-    Serial.println("zone: " + zone_i);
-    Serial.println("duration: " + zone_duration);

     if(zone_i > 0 && zone_duration > 0)
     {
@@ -116,11 +117,10 @@
     // set the stopTime
     stopTime = currentTime + duration;
     change_zone_valve(zone_number,true);
+    dString = duration + " seconds";

     char str[80];
     sprintf(str, "duration(%d):stopTime(%lu):currentTime(%lu)", duration, stopTime, currentTime);
-
-    Particle.publish("striide.garden.runzone.duration",str);
 }

 bool change_zone_valve(int zone_number, bool on_or_off){
@@ -135,8 +135,6 @@
         digitalWrite(zones[zone_number-1], HIGH);
         sString = zone_number + "is on";
 	}
-
-	//Particle.publish("striide.garden.runzone.valve", String(zone_number + ":" + status));

 	return on_or_off;
 }


eliminata riga

eliminata riga

--- provaESP/src/provaESP.ino
+++ provaESP/src/provaESP.ino
@@ -41,7 +41,7 @@

     printWEB();
     //delay(500);
-  Wire.begin(default_sda_pin, default_scl_pin);
+  //Wire.begin(default_sda_pin, default_scl_pin);
   Wire.beginTransmission (2);
   Wire.write (20);
   Wire.endTransmission(true);


Incorporated APRS readings into program. Preliminary updating of target parameters every second (needs work).

--- PortableAntennaRotorControl.ino
+++ PortableAntennaRotorControl.ino
@@ -19,11 +19,11 @@
 const int azDrvPin = 18;
 const int azSgnPin = 19;
 const int ppsPin = 6;
-const int updatePer = 1000;
 const float xtalTol = 20e-6;
 const float maxTimeTol = 0.5; // seconds
 const long maxTimeSyncAge = (long)( 0.5 + maxTimeTol / xtalTol );
-
+const long rotorUpdateInterval = 200000;
+const float deg2rad = 3.1415927 / 180.0;
 /*
  * Set addresses of EEPROM parameters
  */
@@ -34,7 +34,7 @@
 const int eeaddrAzPotMin = eeaddrAzPotWest + sizeof( int );
 const int eeaddrAzPotMax = eeaddrAzPotMin + sizeof( int );
 const int eeaddrElPot0 = eeaddrAzPotMax + sizeof( int );
-const int eeaddrElPot45 = eeaddrElPot0 + sizeof( int );
+const int eeaddrElPot90 = eeaddrElPot0 + sizeof( int );

  /*
  * Copernicus II configured for two NMEA sentences every 60 seconds:
@@ -45,6 +45,7 @@
  *      date/time. Also indicates whether time at last PPS is true
  *      UTC.
  */
+
 const String gpsConfStr = "$PTNLSNM,0220,60*50\r\n";

 const char* callSgns[] = { "KC9LHW", "KC9LIG", "WB9SKY" };
@@ -62,8 +63,10 @@
 char aprs[APRSLEN], aprsBuf[APRSLEN];
 int aprsIndex = 0;
 boolean aprsRdy, aprsChkFlg, aprsErrFlg, aprsBufCurrent, aprsValid;
-boolean aprsFlg;
+boolean aprsFlg, aprsNewFlg;
+long aprsTime, lastAprsTime; // standard time in seconds with decimal fraction to ms
 float aprsLat, aprsLon, aprsAlt, aprsVg, aprsHdg;
+float lastAprsAlt; // needed to keep track of prior value to calculate Vz

 char term[TERMLEN], aprsfiBuf[APRSFILEN], cmdBuf[CMDLEN];
 int termIndex = 0;
@@ -72,9 +75,16 @@
 boolean cmdRdy, aprsfiRdy;
 float apfiLat, apfiLon, apfiAlt, apfiVg, apfiHdg;

-boolean rotorUpdateFlg;
-
-IntervalTimer updateTimer;
+boolean targetValid;
+float target[6];
+
+Aprs aprsObj = Aprs( "WB9SKY,KC9LIG,KC9LHW" );
+
+long ppsMillis;
+
+int clockStatus;
+
+IntervalTimer rotorDriveUpdate;

 void setup() {
   pinMode( elDrvPin, OUTPUT );
@@ -85,7 +95,6 @@
   gpsMsgFlg = false;
   gpsRdy = true;
   aprsBufCurrent = true;
-  rotorUpdateFlg = false;
   cmdRdy = false;
   cmdBufCurrent = true;
   setSyncProvider( getTeensy3Time );
@@ -112,6 +121,8 @@
   setSyncInterval( 10 );

   attachInterrupt( ppsPin, ppsSvc, RISING );
+//  rotorDriveUpdate.priority( 64 ); // Default is 128, lower is higher
+//  rotorDriveUpdate.begin( rotorSvc, rotorUpdateInterval );
 }

 void loop() {
@@ -123,22 +134,17 @@
   if ( Serial.available() ) getTermByte();
   if ( Serial1.available() ) getAPRSByte();
   if ( Serial2.available() ) getGPSByte();
-
   if ( !aprsBufCurrent ) updateAPRSBuffer();
+  if ( aprsFlg ) {
+    if ( DEBUG ) Serial.print( "APRS msg rcvd" );
+    aprsFlg = false;
+    procAprs( );
+  }
 //  if ( !aprsfiBufCurrent ) updateAPRSfiBuffer();
 //  if ( cmdBufCurrent ) {
 //    cmdBufCurrent = false;
 //    Serial.println( "Command" );
 //  }
-  if ( aprsFlg ) {
-    if ( DEBUG ) Serial.print( "APRS msg rcvd" );
-    aprsFlg = false;
-    procAprs();
-  }
-  if ( rotorUpdateFlg ) updateRotors();
-//  if ( gpsRdy ) updateLocal();
-//  if ( aprsRdy ) updateRemote();
-
 }

 void getGPSByte() {
@@ -147,7 +153,7 @@
     gpsIndex = 0;
     gpsRdy = false;
     gpsChk = 0;
-    if ( DEBUG ) Serial.println( "GPS msg started..." );
+    if ( DEBUG ) Serial.println( "\nGPS msg started..." );
   }
   if ( c == '*' ) { // '*' indicates end of GPS sentence
     gpsChkFlg = true;
@@ -198,6 +204,7 @@
     Serial.print( "GPS Flags:" );Serial.print( gpsTFFlg );
     Serial.println( gpsZDAFlg );
   }
+  digitalClockDisplay();
 }

 void procZDAMsg() {
@@ -248,6 +255,7 @@
   Serial2.print( gpsConfStr );
 }

+
 void getAPRSByte() {
   char c = Serial1.read();
   if ( ( c == '\n' || c == '\r' ) ) { // End of APRS msg
@@ -255,12 +263,12 @@
       aprsIndex = 0;
       aprsRdy = true;
       aprsBufCurrent = false;
-      if ( DEBUG ) Serial.println( "APRS msg ended." );
+      if ( DEBUG ) Serial.println( "\nAPRS msg ended." );
       if ( DEBUG ) Serial.println( aprs );
     }
   } else {
     if ( aprsRdy ) {
-      if ( DEBUG ) Serial.println( "APRS msg started..." );
+      if ( DEBUG ) Serial.println( "\nAPRS msg started..." );
       aprsRdy = false;
     }
   }
@@ -348,7 +356,9 @@

 void digitalClockDisplay() {
   // digital clock display of the time
-  Serial.print(hour());
+  int hr = hour();
+  if ( hr < 10 ) Serial.print( '0' );
+  Serial.print(hr);
   printDigits(minute());
   printDigits(second());
   Serial.print(" ");
@@ -370,12 +380,11 @@

 void ppsSvc() {
   if ( DEBUG ) {
-    Serial.print( "." );
-  }
-  rotorUpdateFlg = true;
-
+    //Serial.print( "." );
+  }
+
   // Set clock(s) to UTC time if a valid fix came in since the last PPS
-  if ( DEBUG ) digitalClockDisplay();
+  //if ( DEBUG ) digitalClockDisplay();
   if ( gpsTimeValid && gpsTimeFlg ) {
     time_t oldTime = getTeensy3Time();
     setTime( gpsHr,gpsMin,gpsSec,gpsDay,gpsMon,gpsYr ); // "Library" time
@@ -399,20 +408,77 @@
   gpsTimeFlg = false;
   gpsZDAFlg = false;
   gpsTFFlg = false;
+
+  updateTarget();
+
 }

 void procAprs() {
   /* Check msg is proper APRS msg from a monitored call sign,
      not some other output from TNC */
-  /* Extract parameters and add timestamp it if time not available */
-}
-
-void estTargetPosition() {
-  // get last measured position and time
-  // extrapolate using velocity and possibly acceleration
-}
-
-void updateRotors() {
-
-}
-
+  aprsObj.putAprsString( aprsBuf );
+  String callSgn = aprsObj.getCallsign();
+  boolean callSgnFilt = false;
+  for ( int i = 0 ; i < numCallSgns ; i++ ) {
+    callSgnFilt |= ( (String)callSgns[i] == callSgn );
+  }
+  if ( DEBUG ) Serial.print( "\n" + callSgn + ' ');
+  if ( DEBUG ) if ( callSgnFilt ) {
+    Serial.println( "valid" );
+  } else {
+    Serial.println( "invalid" );
+  }
+  if ( callSgnFilt ) {
+    aprsTime = now();
+    aprsLat = aprsObj.getLatitude();
+    aprsLon = aprsObj.getLongitude();
+    aprsAlt = (float)aprsObj.getAltitude();
+    aprsVg = (float)aprsObj.getGroundspeed();
+    aprsHdg = (float)aprsObj.getCourse();
+    aprsNewFlg = true;
+  }
+
+}
+
+void updateTarget() {
+    // Time must be a long int, can't be float, so can't be part of target state
+    // array. Change this so that target state is just separate variables instead
+    // of an array.
+  if ( aprsNewFlg ) {
+    if ( DEBUG ) Serial.println( "APRS target update" );
+    // Set prior target state to new APRS data
+    target[0] = aprsTime;
+    // Initialization for computed derivatives on first valid APRS fix
+    if ( targetValid ) {
+      target[6] = ( aprsAlt - lastAprsAlt ) / ( aprsTime - lastAprsTime );
+    } else {
+      target[6] = 0.0;
+      targetValid = true;
+    }
+    target[1] = aprsLon;
+    target[2] = aprsLat;
+    target[3] = aprsAlt;
+    target[4] = aprsVg * cos( aprsHdg * deg2rad ) * cos( aprsLat * deg2rad );
+    target[5] = aprsVg * sin( aprsHdg * deg2rad );
+    lastAprsTime = aprsTime;
+    lastAprsAlt = aprsAlt;
+    aprsNewFlg = false;
+  }
+
+  // Update target state
+  if ( targetValid ) {
+    float temp = target[0]; // old time
+    target[0] = float(now());
+    temp = target[0] - temp; // delta t
+    target[1] += ( target[4] * temp );
+    target[2] += ( target[5] * temp );
+    target[3] += ( target[6] * temp );
+  }
+//  for ( int i = 0 ; i < 6 ; i++ ) {
+//    Serial.print( target[i] );
+//    Serial.print( ":" );
+//  }
+//  Serial.println( "" );
+}
+
+


Modificación serial-server

Modificación serial-server

--- ClienteServidor/espinoClient/espinoClient.ino
+++ ClienteServidor/espinoClient/espinoClient.ino
@@ -78,7 +78,6 @@

 //------------------------
-//------------------------
 // general callbacks
 void onDataCb(ESP8266Client& client, char *data, unsigned short length)
 {


Added some better comments

Added some better comments

--- src/CAN/CAN_receive_v2/CAN_receive_v2.ino
+++ src/CAN/CAN_receive_v2/CAN_receive_v2.ino
@@ -23,6 +23,8 @@
 // "Control Units" -- LED Lights to be controlled
 const int blueLED = 4;
 const int greenLED = 3;
+
+// For the RGB LED
 const int RED = 7;
 const int GREEN = 5;
 const int BLUE = 6;
@@ -39,8 +41,8 @@

 void setup()
 {
-    InitMessages();
-    Serial.begin(115200);             // serial interface baud rate (typical rate for CAN Bus)
+    InitMessages();     // Initialize valid CAN messages in can_constants.h
+    Serial.begin(115200);    // serial interface baud rate (typical rate for CAN Bus)

     while (CAN_OK != CAN.begin(CAN_500KBPS))              // init can bus : baudrate = 500k
     {
@@ -50,6 +52,7 @@
     }
     Serial.println("CAN BUS Shield init ok!");

+    // Initialize all the LEDs
     pinMode(blueLED, OUTPUT);
     pinMode(greenLED, OUTPUT);
     pinMode(RED, OUTPUT);
@@ -70,13 +73,18 @@
         id = CAN.getCanId(); // get CAN ID
         CAN.readMsgBufID(&id, &dlc, data);    // read data,  len: data length, buf: data buf
         Serial.println("\n------------------------------\n");
-        PrintMessage();
-
+
+        // Display the message
+        PrintMessage();
+
+        // Authenticate the message
         if (Authenticate())
           Serial.println("\tAuth Good");
         else
           Serial.println("\tFAILED AUTH");
-
+
+        // Once Authentication is finished, this will be moved
+        // inside the IF above. Acts based off the data sent
         TakeAction();
     }
 }


Refined the displays

Refined the displays

--- Robot_Lights_Display/Robot_Lights_Display.ino
+++ Robot_Lights_Display/Robot_Lights_Display.ino
@@ -35,32 +35,30 @@
 }

 void loop() {
-  for (int c = 2; c > 0; c--) {
+  rotatingCogs(YELLOW, BLUE);
+  displayColor(YELLOW);
+  for (int c = 4; c > 0; c--) {
     cylon(YELLOW, BLUE);
   }
-  displayRed();
-  for (int c = 20; c > 0; c--) {
+  for (int c = 50; c > 0; c--) {
     alternate(YELLOW, BLUE);
   }
-  displayRed();
-  rotatingCogs(YELLOW, BLUE);
-  displayRed();
 }

 void rotatingCogs(CRGB colorOne, CRGB colorTwo) {
   cogs(colorOne, colorTwo);
   FastLED.show();
-  for (int i = 0; i < 10; i++) {
+  for (int i = 0; i < 40; i++) {
     for (int c = 0; c < 4; c++) {
       moveCogsUp();
-      delay(30);
+      delay(75);
       FastLED.show();
     }
   }
 }

 void cylon(CRGB colorOne, CRGB colorTwo) {
-  for(int i = 0; i < NUM_LEDS; i++) {
+  for (int i = 0; i < NUM_LEDS; i++) {
 		// Set the i'th led to red
 		leds[i] = colorOne;
 		// Show the leds
@@ -114,12 +112,11 @@
   delay(200);
 }

-void displayRed() {
+void displayColor(CRGB color) {
   for (int i=0 ; i < NUM_LEDS; i++) {
-        leds[i] = CRGB::Red;
+        leds[i] = color;
   }
   FastLED.show();
-  delay(2000);
 }

 void cogs(CRGB colorOne, CRGB colorTwo) {


Delete ss963_test.ino

Delete ss963_test.ino

--- arduino-uno-test/ss963_test.ino
+++ arduino-uno-test/ss963_test.ino
@@ -1,113 +0,0 @@
-/*
-  ss963   Uno         Logic Analyzer
-  -----   ---         --------------
-  Latch   9           3
-  CLK     13  (SCL)   2
-  Data    11  (MOSI)  1
-  Reset   8           4
-  Gnd     Gnd         Gnd
-*/
-
-#include <SPI.h>
-
-byte ports[96];
-byte byte_array[12];
-
-int DATA_PIN = 11; /* MOSI */
-int LATCH_PIN = 9;
-int RESET_PIN = 8;
-int LATCH_DELAY_MS = 1;
-int i, j;
-
-void setup() {
-  pinMode(RESET_PIN, OUTPUT);
-  pinMode(LATCH_PIN, OUTPUT);
-  digitalWrite(RESET_PIN, HIGH);
-
-  SPI.begin();
-  SPI.setClockDivider(SPI_CLOCK_DIV2); /* 16MHz/2 = 8MHz hiza ayarla */
-
-  Serial.begin(115200);
-}
-
-/*
- * Converts 'ports' bit array to bytes array.
- * After, bytes array will transmit to SPI port.
- */
-void convert_bit_array_to_byte_array(byte *ports, byte *byte_array) {
-  int i, j;
-  for (i = 0; i < 12; i++)
-  {
-    byte_array[i] = 0;
-    for (j = 0; j < 8; j++)
-      byte_array[i] += ports[i * 8 + j] << j;
-  }
-}
-
-/*
- * Set all ports of card to LOW or HIGH.
- * Not critial.
- */
-void fill_ports(byte *ports, byte on_off)
-{
-  int i;
-  for (i = 0; i < 96; i++)
-    ports[i] = on_off;
-}
-
-/*
- * Store ports array data to card's buffer registers.
- */
-void write_ports(byte *ports)
-{
-  convert_bit_array_to_byte_array(ports, byte_array);
-
-  for (j = 11; j >= 0; j--) {
-    SPI.transfer(byte_array[j]);
-  }
-
-  latch();
-}
-
-
-/*
- * Do latch.
- * The latch function writes buffer registers to outs.
- */
-void latch() {
-  digitalWrite(LATCH_PIN, HIGH);
-  delay(LATCH_DELAY_MS);
-  digitalWrite(LATCH_PIN, LOW);
-}
-
-void loop() {
-
-  fill_ports(ports, 0);
-  for (i = 0; i < 96; i++)
-  {
-    ports[i] = HIGH;
-    write_ports(ports);
-    delay(20);
-  }
-
-  for (i = 0; i < 3; i++)
-  {
-    fill_ports(ports, 0);
-    write_ports(ports);
-    delay(500);
-    fill_ports(ports, 1);
-    write_ports(ports);
-    delay(500);
-  }
-
-  for (i = 95; i >= 0; i--)
-  {
-    ports[i] = LOW;
-    write_ports(ports);
-    delay(20);
-  }
-
-}
-
-
-


change timer

change timer

--- _66-slack-bot/_66-slack-bot.ino
+++ _66-slack-bot/_66-slack-bot.ino
@@ -56,8 +56,8 @@
 #define IR_TX_PIN 2
 #define AC_CONF_TYPE 1
 #define AC_CONF_HEATING 0
-#define AC_CONF_ON_MIN 5
-#define AC_CONF_OFF_MIN 3
+#define AC_CONF_ON_MIN 30
+#define AC_CONF_OFF_MIN 20

 volatile struct
 {
@@ -73,7 +73,7 @@
 } ir_data;

 IRrecv irrecv(IR_RX_PIN);
-lgWhisen lgWhisen(AC_CONF_TYPE, AC_CONF_HEATING);
+lgWhisen lgWhisen;

 void chane_ac_temp_flow()
 {
@@ -369,6 +369,8 @@
   ir_data.timerMillis = millis();;
   nextTimercheck = ir_data.intervalon;

+  lgWhisen.setActype(AC_CONF_TYPE);
+  lgWhisen.setHeating(AC_CONF_HEATING);
   lgWhisen.setTemp(ir_data.ac_temp);    // 18 ~ 30
   lgWhisen.setFlow(ir_data.ac_flow);    // 0 : low, 1 : mid, 2 : high, if setActype == 1, 3 : change
   lgWhisen.setIrpin(IR_TX_PIN);         // ir tx pin


fixing a bug

fixing a bug


Edit Blink6

Edit Blink6

--- blink6/blink6.ino
+++ blink6/blink6.ino
@@ -23,12 +23,14 @@

 void loop() {
   // put your main code here, to run repeatedly
-  // turn the lights on in order
-  for (counter=0; counter < 6; counter++) {
-    digitalWrite(ledArray[counter], HIGH);
-    delay(timer);
-    digitalWrite(ledArray[counter], LOW);
-    delay(timer);
+  // turn the lights on in order 2 times
+  for (countDown=2; countDown > 0; countDown--) {
+     for (counter=0; counter < 6; counter++) {
+       digitalWrite(ledArray[counter], HIGH);
+       delay(timer);
+       digitalWrite(ledArray[counter], LOW);
+       delay(timer);
+     }
   }
   // flash all lights 4 times
   for (countDown=4; countDown > 0; countDown--) {


Remove the unused skipHeaders function.

Remove the unused skipHeaders function.

The Stream methods seem reliable, although they do take up more memory. That said, they allow easy extraction of the Content-Length header, which is a definite advantage.

--- wee_printer.ino
+++ wee_printer.ino
@@ -69,17 +69,6 @@
 int failures = 0;
 int requests = 0;

-void skipHeaders(Stream *stream) {
-  unsigned int inByte = 0;
-  unsigned int lastByte = 0;
-  while (!(inByte == '\n' && lastByte == '\n')) {
-    if (inByte != '\r') {
-      lastByte = inByte;
-    }
-    inByte = stream->read();
-  }
-}
-
 void loop() {
   digitalWrite(greenPin, LOW);


Start in height only mode.

Start in height only mode.

--- 00_Firmware/Firmware/Firmware.ino
+++ 00_Firmware/Firmware/Firmware.ino
@@ -477,7 +477,7 @@
 	eClipMode = EEPROM.read(EEMODEADDR);
 	if (eClipMode != EEMODE_SYNCPULSE && eClipMode != EEMODE_HEIGHTONLY)
 	{
-		EEPROM.write(EEMODEADDR, EEMODE_SYNCPULSE);
+		EEPROM.write(EEMODEADDR, EEMODE_HEIGHTONLY);
 		eClipMode = EEMODE_HEIGHTONLY;
 	}


Add comments.

Add comments.

--- src/sketch.ino
+++ src/sketch.ino
@@ -11,6 +11,7 @@
     int status = LOW;
     int out = 0;

+    // Print the received timings to the console.
     for (i = 0; i < counter; i++) {
         out = message[i] * MULTIPLIER;
         Serial.print(out);
@@ -18,6 +19,7 @@
     }
     Serial.println("");

+    // Send the message.
     for (i = 0; i < counter; i++) {
         if (status == HIGH) {
             status = LOW;
@@ -28,6 +30,7 @@
         out = message[i] * MULTIPLIER;
         delayMicroseconds(out);
     }
+    // Reset, just in case.
     digitalWrite(OUT, LOW);
 }

@@ -47,12 +50,14 @@
         }
         character = Serial.read();
         if (character == 0) {
+            // Complete the message if we receive a null.
             digitalWrite(LED, HIGH);
             processMessage();
             digitalWrite(LED, LOW);
             Serial.println("Command sent.");
             counter = 0;
         } else {
+            // Append the received byte to the array.
             message[counter] = character;
             counter++;
         }


COH-80: all messages flowing, but lossy

COH-80: all messages flowing, but lossy

--- COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
+++ COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
@@ -1,6 +1,6 @@
 // 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.
+//#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
@@ -562,8 +562,7 @@
   {
   const uint8_t msglen = msg[-1];

-  // TODO: consider extracting hash of all message data (good/bad) and injecting into entropy pool.
-#if 1 && defined(DEBUG)
+#if 0 && defined(DEBUG)
   OTRadioLink::printRXMsg(p, msg-1, msglen+1); // Print len+frame.
 #endif


COH-77: WIP

COH-77: WIP

--- COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
+++ COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
@@ -1,6 +1,6 @@
 // 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.
+#define CONFIG_Trial2013Winter_Round2_CC1HUB // REV2 cut4 as CC1 hub.
+//#define CONFIG_REV9 // REV9 as CC1 relay, cut 2 of the board.

 #include <Arduino.h>
 #include <Wire.h>
@@ -857,13 +857,12 @@
   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(); }
+  // 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


Improving switch code generation benchmark.

--- examples/Sandbox/CosaSwitch/CosaSwitch.ino
+++ examples/Sandbox/CosaSwitch/CosaSwitch.ino
@@ -174,6 +174,8 @@
   TRACE(switch_fn_size);
   for (uint8_t op = OP_ADD; op <= OP_EXIT; op++)
     TRACE(switch_fn(op));
+  SLEEP(1);
+
   start = RTC::micros();
   res = 0;
   for (int i = 0; i < 1000; i++)
@@ -183,6 +185,8 @@
   us = stop - start;
   TRACE(res);
   TRACE(us);
+  SLEEP(1);
+
   start = RTC::micros();
   for (int i = 0; i < 10000; i++)
     for (uint8_t op = OP_LOAD; op <= OP_EXIT; op++)
@@ -191,12 +195,15 @@
   us = stop - start;
   TRACE(res);
   TRACE(us);
+  SLEEP(1);

   // Measure goto-label table version
   TRACE(goto_fn_addr);
   TRACE(goto_fn_size);
   for (uint8_t op = OP_ADD; op <= OP_EXIT; op++)
     TRACE(goto_fn(op));
+  SLEEP(1);
+
   start = RTC::micros();
   res = 0;
   for (int i = 0; i < 1000; i++)
@@ -206,6 +213,8 @@
   us = stop - start;
   TRACE(res);
   TRACE(us);
+  SLEEP(1);
+
   start = RTC::micros();
   for (int i = 0; i < 10000; i++)
     for (uint8_t op = OP_LOAD; op <= OP_EXIT; op++)
@@ -214,6 +223,7 @@
   us = stop - start;
   TRACE(res);
   TRACE(us);
+  SLEEP(1);

   ASSERT(true == false);
 }


Update SendGetRequest.ino

Update SendGetRequest.ino

Just some comments.

--- examples/SendGetRequest/SendGetRequest.ino
+++ examples/SendGetRequest/SendGetRequest.ino
@@ -13,6 +13,7 @@
   wifi.reset();
   wifi.setMode(1);
   wifi.connect("insert_ssid_here","insert_password_here");
+  //should check to see if connect failed; print error
   out.print("Connected in ");
   out.print((millis() - time));
   out.println("ms");
@@ -21,12 +22,14 @@
 int count = 0;
 void loop() {
   String get = "GET /update?key=INSERT_THINGSPEAK_KEY&field1=";
+  //make they Key and Field into variables
   get += count;

   unsigned long time = millis();
   wifi.start("TCP","184.106.153.149",80);  //connect to thingspeak
   wifi.sendPayload(get);
   wifi.close();
+  //how do we know the above was successful?
   out.print("Connected in ");
   out.print((millis() - time));
   out.println("ms");


Doc improvement

Doc improvement

--- examples/statsd_tagging/statsd_tagging.ino
+++ examples/statsd_tagging/statsd_tagging.ino
@@ -40,7 +40,7 @@
   // Emit a named metric with given value, some number of comma separated tags at a given sample rate.
   // metric: some.metric
   // value: val
-  // tags: sensor: basement (and host: speck, configured in the constant tags for the client)
+  // tags: sensor, location: basement (and host: speck, configured in the constant tags for the client)
   // sample rate: 0 -> 1.0 (100%)
   // Use tags when you have a metric that will benefit from being able to drill down by tags.
   // In this example we include the information that this datapoint comes from a sensor in


tidyup

tidyup

--- Arduino/V0p2_Main/V0p2_Main.ino
+++ Arduino/V0p2_Main/V0p2_Main.ino
@@ -143,15 +143,15 @@
   }
 #endif // ALT_MAIN_LOOP

-// Rearrange date into sensible most-significant-first order.  (Would like it also to be fully numeric, but whatever...)
-// FIXME: would be better to have this in PROGMEM (Flash) rather than RAM.
+// 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], __DATE__[5],
+  ((' ' == __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.
@@ -160,7 +160,7 @@
   {
   OTV0P2BASE::serialPrintAndFlush(F("board V0.2 REV"));
   OTV0P2BASE::serialPrintAndFlush(V0p2_REV);
-  OTV0P2BASE::serialPrintAndFlush(F(" "));
+  OTV0P2BASE::serialPrintAndFlush(' ');
   OTV0P2BASE::serialPrintAndFlush(_YYYYMmmDD);
   OTV0P2BASE::serialPrintlnAndFlush(F(" " __TIME__));
   }


Added rollover handling in sleep function

--- Pan_Tilt_laser/Pan_Tilt_laser.ino
+++ Pan_Tilt_laser/Pan_Tilt_laser.ino
@@ -206,7 +206,7 @@
     while(millis() - startTime < 60000){
       heartBeat();
       delay(10000);
-      if(startTime > millis){
+      if(startTime > millis){ //check for rollovers
         break;
       }
     }


Use 1/8th microstepping for MotorTest example

--- examples/MotorTest/MotorTest.ino
+++ examples/MotorTest/MotorTest.ino
@@ -653,10 +653,28 @@
 void setup(void)
 {

+    // initialize the kissStepper
+    mot.begin();
+
+    // set drive mode pins
+    // the kissStepper library does not do this for you!
+    pinMode(PIN_MS1, OUTPUT);
+    pinMode(PIN_MS2, OUTPUT);
+    digitalWrite(PIN_MS1, LOW);
+    digitalWrite(PIN_MS2, LOW);
+    switch (DRIVE_MODE)
+    {
+    case 2: // half-step
+        digitalWrite(PIN_MS1, HIGH);
+        break;
+    case 4: // quarter-step
+        digitalWrite(PIN_MS2, HIGH);
+        break;
+    case 8: // eighth-step
+        digitalWrite(PIN_MS1, HIGH);
+        digitalWrite(PIN_MS2, HIGH);
+        break;
+    }
+
     Serial.begin(9600);
-
-    // initialize the kissStepper
-    // use 1/8th drive mode, and set the maximum speed to 200 st/s
-    mot.begin();
-
-}
+}


added fully commented robot build code.

added fully commented robot build code.

--- robotBuild/robotController/robotController.ino
+++ robotBuild/robotController/robotController.ino
@@ -1,379 +1,690 @@
+/*
+|--------------------------------------------------------------------------
+|
+| Mini Warehouse Robot: Robot Controller
+| Author: MECN3012 Group A2 (2017)
+| University of the Witwatersrand - Copyright 2017
+| Objective: Detect colour sequence, Deliver cups to dispatch bay in
+|            presented sequence, return back to starting bay.
+|
+|--------------------------------------------------------------------------
+*/
+
+// Including motor pins and bttery voltage constants
 #include "Constants.h"
 #include "IOpins.h"

-// Colour sensor
+// Colour sensor
 const int s0 = 3, s1 = 4, s2 = 5, s3 = 6;  // Colour sensor pin connections
 const int colourPin = 2;
 int LED = 13;
 int instructionsArray[3];                  // Creating empty colour sequence array
+
 int colour = 0;                            // Colour varibale (1 = pink, 2 = Blue, 3 = Green)
 bool inArray = false;                      // Setting array checking boolean variable

 // Ultrasonic distance sensor
-const int trigPin = 12;                    // Ultrasonic sensor pin connections
+const int trigPin = 12;                    // Ultrasonic sensor pin connections
 const int echoPin = 11;

+// Coordinate Array
+;float cupPoints[3][6] =
+{
+  {27.0, 140.0, 27.0, 27.0, 30.0, 27.0},        // Pink
+  {27.0, 54.0, 70.0, 25.0, 30.0, 25.0},         // Blue
+  {27.0, 88.0, 70.0, 25.0, 30.0, 25.0}          // Green
+};
+
+// Motion
+float accuracyRange = 2.0;
+int turnIncrement = 0;
+
 // Servo motor
-const int srvoMotorPin = 18;               // Servo motor digital pin connection
+const int srvoMotorPin = 18;              // Servo motor digital pin connection

 // Battery
-int volts;                                 // battery voltage
-int pause = -1;                            // a value of -1 means the battery voltage is ok,
-                                           // 0 and 1 are used to flash LED on D13 when the battery is flat
-
-// ********************************************************************************
-// SETUP and LOOP FUNCTIONS
-// ********************************************************************************
+int volts;                                // battery voltage
+int pause = -1;                           // a value of -1 means the battery voltage is ok,
+                                          // 0 and 1 are used to flash LED on D13 when the battery is flat
+
+// -------------------------------------------------------------------------
+// SETUP and LOOP FUNCTIONS
+// -------------------------------------------------------------------------

 void setup()
-{
-  //Serial.begin(9600);                            // initialize serial communication
-
+{
   // Setup motor direction pins as outputs
-  pinMode(Ldirpin,OUTPUT);                       // set left  direction pin as an output pin
-  pinMode(Rdirpin,OUTPUT);                       // set right direction pin as an output pin
+  pinMode(Ldirpin, OUTPUT);                    // set left  direction pin as an output pin
+  pinMode(Rdirpin, OUTPUT);                    // set right direction pin as an output pin

   // Setup colour sensor pins as inputs and outputs
-  pinMode(s0,OUTPUT);
-  pinMode(s1,OUTPUT);
-  pinMode(s2,OUTPUT);
-  pinMode(s3,OUTPUT);
-  pinMode(colourPin,INPUT);
-
+  pinMode(s0, OUTPUT);
+  pinMode(s1, OUTPUT);
+  pinMode(s2, OUTPUT);
+  pinMode(s3, OUTPUT);
+  pinMode(colourPin, INPUT);
+
   // Set colour sensor output frequency to frequency-scaling of 2%
   digitalWrite(s0, LOW);
   digitalWrite(s1, HIGH);
-
+
   // Set servo control pin as an output pin
-  pinMode(srvoMotorPin,OUTPUT);
-
-  delay(1000);                              // Wait 1 second before starting the loop function.
+  pinMode(srvoMotorPin, OUTPUT);
+
+  delay(1000);                              // Wait 1 second before starting the loop function.
 }

 void loop()
-{
-  // -------------------------------------------------------------------------
-  /* Battery Check.
-  | !Low battery voltages will damage your controller!
-  | The robot will stop moving if the battery voltage is below a certain value.
-  | The LED on pin D13 will also flash on and off.
-  | !Do not tamper with this code!
+{
+  /*
+    | -------------------------------------------------------------------------
+    | Battery Check.
+    | -------------------------------------------------------------------------
+    | !Low battery voltages will damage your controller!
+    | The robot will stop moving if the battery voltage is below a certain value.
+    | The LED on pin D13 will also flash on and off.
+    | !Do not tamper with this code!
+    | This code is modified from:
+    | https://sites.google.com/site/daguproducts/home/Software/Doodle_Bot_Text_Demo.zip?attredirects=0
+    | -------------------------------------------------------------------------
   */
-  // This code is modified from:
-  // https://sites.google.com/site/daguproducts/home/Software/Doodle_Bot_Text_Demo.zip?attredirects=0
-  // -------------------------------------------------------------------------
-
-  volts = analogRead(Battery)/10;           // Battery voltage reading
-
-  if((volts < lowbat) || (pause != -1))     // once voltage falls below lowbat value
+
+  volts = analogRead(Battery) / 10;         // Battery voltage reading
+
+  if ((volts < lowbat) || (pause != -1))    // once voltage falls below lowbat value
   {
     // Stop the robot
-    digitalWrite(Ldirpin,0);                // set left direction
-    analogWrite (Lpwmpin,0);                // set left speed to zero
-    digitalWrite(Rdirpin,0);                // set right direction
-    analogWrite (Rpwmpin,0);                // set right speed to zero
+    digitalWrite(Ldirpin, 0);               // set left direction
+    analogWrite (Lpwmpin, 0);               // set left speed to zero
+    digitalWrite(Rdirpin, 0);               // set right direction
+    analogWrite (Rpwmpin, 0);               // set right speed to zero

     pause++;                                // increment pause
-    if(pause > 1)                           // toggle pause between 0 and 1 once battery is flat
-    {
-      pause = 0;
-    }
-
-    digitalWrite(13,pause);                 // flash LED on D13
+    if (pause > 1)                          // toggle pause between 0 and 1 once battery is flat
+    {
+      pause = 0;
+    }
+
+    digitalWrite(13, pause);                // flash LED on D13
     delay(200);                             // set flashing LED speed
     return;                                 // reset loop
-  }
-
+  }
+
   robotProject();                          // The robotProject function contains your project code
-  while(1);
-}
-
-// ********************************************************************************
-// ROBOTPROJECT FUNCTION
-// ********************************************************************************
+  exit(0);                                 // Ensuring code runs only once
+}
+// -------------------------------------------------------------------------
+// Voltage Stabilising function
+// -------------------------------------------------------------------------
+int voltageFunction(int mtrSpeed)
+{
+  int batteryLvl = analogRead(Battery);
+  int newSpeed = round(((7.5*mtrSpeed)/255)*(34782/batteryLvl));
+  return newSpeed;
+}
+
+// -------------------------------------------------------------------------
+// ROBOTPROJECT FUNCTION
+// -------------------------------------------------------------------------
 void robotProject()
 {
-  colourSequence();
-  goSomewhere(1, 1, 60, 90, 3);
-}
-
-// ********************************************************************************
-// FUNCTIONS
-// ********************************************************************************
-
-// ********************************************************************************
-// Robot speed and direction functions
-// ********************************************************************************
-
+  colourSequence();         // Check & Store colour sequence
+  openServo();              // Raise cup latching mechanism
+  getCup();                 // Get cups in array sequence
+  blinkLED(4);              // Blink LED to signal completion
+}
+
+// -------------------------------------------------------------------------
+// Robot speed and direction Functions                                     |
+// -------------------------------------------------------------------------
+
+// ------------------------------------
+// Setting motion (turning or moving) |
+// ------------------------------------
 void goSomewhere(int dirBinaryLeft, int dirBinaryRight, int leftSpeed, int rightSpeed, int delayTime)
 {
   /*
-  | -------------------------------------------------------------------------
-  | This function moves the robot in any desired direction based on user
-  | inputs. It can move: Forward, Backwards, Turn Left and Right, and
-  | Stop completely.
-  | -------------------------------------------------------------------------
+    | -------------------------------------------------------------------------
+    | This function moves the robot in any desired direction based on user
+    | inputs. It can move: Forward, Backwards, Turn Left and Right, and
+    | Stop completely.
+    | -------------------------------------------------------------------------
   */
-  if (leftSpeed > 255)                          // limit maximum motor speed value
+  if (leftSpeed > 255)                      // limit maximum left motor speed value
   {
     leftSpeed = 255;
   }
-  if (rightSpeed > 255)                         // limit maximum motor speed value
+  if (rightSpeed > 255)                     // limit maximum right motor speed value
   {
     rightSpeed = 255;
   }

-  digitalWrite(Ldirpin, dirBinaryLeft);          // set left direction
-  analogWrite (Lpwmpin, leftSpeed);              // set left speed
-  digitalWrite(Rdirpin, dirBinaryRight);         // set right direction
-  analogWrite (Rpwmpin, rightSpeed);             // set right speed
-  delay(delayTime*1000);
-}
-
-// ********************************************************************************
+  digitalWrite(Ldirpin, dirBinaryLeft);     // set left direction
+  digitalWrite(Rdirpin, dirBinaryRight);    // set right direction
+  analogWrite (Rpwmpin, rightSpeed);        // set right speed
+  analogWrite (Lpwmpin, leftSpeed);         // set left speed
+  delay(delayTime);                         // Hold desired motion for specific amount of time
+
+  // Stop wheels after moving
+  digitalWrite(Ldirpin, 0);                 // set left direction
+  digitalWrite(Rdirpin, 0);                 // set right direction
+  analogWrite (Rpwmpin, 0);                 // set right speed
+  analogWrite (Lpwmpin, 0);                 // set left speed
+}
+
+// --------------------------------
+// Keep motion in a straight line |
+// --------------------------------
+void straightLine(int leftMtr, int rightMtr, float desiredDist, float knownWall, bool BOF)
+{
+  if (knownWall == 0.0)
+  {
+    knownWall = ultraSensorDist();
+  }
+
+  bool distReached = true;
+  while (distReached)
+  {
+    if ( (BOF == true) && (infraDistance() <= desiredDist) )
+    {
+      distReached = false;
+    }
+
+    else if ( (BOF == false) && (infraDistance() >= desiredDist) )
+    {
+      distReached = false;
+    }
+
+    if (BOF == true)
+    {
+      obstructionStop();
+      break;
+    }
+
+    int mtrSpeed = voltageFunction(80);
+    goSomewhere(leftMtr, rightMtr, mtrSpeed, mtrSpeed, 100);
+    delay(300);
+
+    int rs = 0;
+    int ls = 0;
+    float ping = ultraSensorDist();
+    mtrSpeed = voltageFunction(60);
+    if (ping < knownWall)                 // Shifted Right
+    {
+      for (int rs=0; rs < 3; rs++)
+      {
+        if (BOF == true)
+        {
+          goSomewhere(0, 0, 0, mtrSpeed, 30);
+        }
+        else if (BOF == false)
+        {
+          goSomewhere(1, 1, mtrSpeed, 0, 30);
+        }
+
+        ping = ultraSensorDist();
+        if ( (knownWall < ping) && (ping < knownWall + accuracyRange) )
+        {
+          break;
+        }
+        delay(100);
+      }
+    }
+
+    else if ( ping > knownWall)           // Shifted left
+    {
+      for (int ls=0; ls < 3; ls++)
+      {
+        if (BOF == true)
+        {
+          goSomewhere(0, 0, mtrSpeed, 0, 30);
+        }
+        else if (BOF == false)
+        {
+          goSomewhere(1, 1, 0, mtrSpeed, 30);
+        }
+
+        ping = ultraSensorDist();
+        if ( (knownWall < ping) && (ping < knownWall + accuracyRange) )
+        {
+          break;
+        }
+        delay(100);
+      }
+    }
+
+    if (rs == 2)
+    {
+      for (int j=0; j < 6; j++)
+      {
+        if (BOF == true)
+        {
+          goSomewhere(0, 0, mtrSpeed, 0, 30);
+        }
+        else if (BOF == false)
+        {
+          goSomewhere(1, 1, 0, mtrSpeed, 30);
+        }
+        delay(100);
+      }
+    }
+    if (ls == 2)
+    {
+      for (int k=0; k < 6; k++)
+      {
+        if (BOF == true)
+        {
+          goSomewhere(0, 0, 0, mtrSpeed, 30);
+        }
+        else if (BOF == false)
+        {
+          goSomewhere(1, 1, mtrSpeed, 0, 50);
+        }
+        delay(100);
+      }
+    }
+    delay(100);
+  }
+  delay(1000);
+}
+
+// ---------
+// Reverse |
+// ---------
+void reverse()
+{
+  for (int k=0; k < 5; k++)
+  {
+    goSomewhere(1, 1, 80, 85, 90);
+  }
+  delay(1000);
+}
+
+// ---------
+// Get cup |
+// ---------
+void getCup()
+{
+  float cupGap = 0;
+  for (int i=0; i<3; i++)
+  {
+    turnIncrement = 0;
+
+    int mtrSpeed = voltageFunction(70);
+    straightLine(0, 0, cupPoints[instructionsArray[i]][0], 0.0, true);          // point 1
+    turnLR(0, 0, 0, mtrSpeed, cupPoints[instructionsArray[i]][0]);              // turn A
+
+    straightLine(0, 0, cupPoints[instructionsArray[i]][1], 0.0, true);          // point 2
+    turnLR(0, 0, 0, mtrSpeed, cupPoints[instructionsArray[i]][1]);              // turn B
+
+    straightLine(0, 0, cupPoints[instructionsArray[i]][2], 0.0, true);          // point 3
+    closeServo();                                                               // Grab cup
+    reverse();
+    reverse();
+    reverse();
+    reverse();
+    reverse();
+    turnLR(0, 0, mtrSpeed, 0, cupPoints[instructionsArray[i]][2]);              // turn C
+
+    mtrSpeed = voltageFunction(60);
+    straightLine(0, 0, cupPoints[instructionsArray[i]][3] + cupGap, 0.0, true); // point 5
+    openServo();                                                                // leave cup
+    reverse();                                                                  // point 6 (reverse)
+    turnLR(0, 0, 0, mtrSpeed, cupPoints[instructionsArray[i]][3] + 5.0);        // turn D
+    closeServo();
+
+    straightLine(0, 0, cupPoints[instructionsArray[i]][4], 0.0, true);          // point 7
+    turnLR(0, 0, 0, mtrSpeed, cupPoints[instructionsArray[i]][4]);              // turn E
+
+    straightLine(0, 0, cupPoints[instructionsArray[i]][5], 0.0, true);          // point 8
+    turnLR(0, 0, 0, mtrSpeed, cupPoints[ instructionsArray[i] ][5]);            // turn F
+
+    cupGap = cupGap + 10;
+    openServo();
+
+    delay(3000);
+  }
+
+}
+
+// ---------------------------------
+// Stop if obstructuction detected |
+// ---------------------------------
+bool obstructionStop()
+{
+  float ping = infraDistance();
+  if (ping < 22)
+  {
+    goSomewhere(0, 0, 0, 0, 0);
+  }
+}
+
+// --------------------
+// Turn left or right |
+// --------------------
+void turnLR(int leftDir, int RightDir, int leftSpeed, int rightSpeed, float wallDist)
+{
+  wallDist = infraDistance() - 3.0;
+  delay(1000);
+  goSomewhere(leftDir, RightDir, leftSpeed, rightSpeed, 480 + turnIncrement);
+  turnIncrement = turnIncrement + 15;
+  delay(2000);
+  for (int l=0; l < 15; l++)
+  {
+    goSomewhere(leftDir, RightDir, leftSpeed, rightSpeed, 60);
+    float wallPing = ultraSensorDist();
+    if( (wallPing > wallDist) && ( wallPing <= (wallDist + 3.0) ) )
+    {
+      break;
+    }
+    delay(300);
+  }
+  delay(1000);
+}
+
+// --------------------------------------------------------------------------
 // Infrared Distance Sensor Function
-// ********************************************************************************
+// --------------------------------------------------------------------------
 float infraDistance()
 {
   /*
-  |--------------------------------------------------------------------------
-  | Convert Analog Readings To Voltages:
-  |--------------------------------------------------------------------------
-  |
-  | Takes an anolog reading and uses a 10 bit scale to return a value
-  | between 0 - 5 Volts. Then takes the voltage value, and using the
-  | trendline equation found in sesorCalibration.numbers to return
-  | an approximate actual distance as is seen by the sensor.
-  |
+    |--------------------------------------------------------------------------
+    | Convert Analog Readings To Voltages:
+    |--------------------------------------------------------------------------
+    |
+    | Takes an anolog reading and uses a 10 bit scale to return a value
+    | between 0 - 5 Volts. Then takes the voltage value, and using the
+    | trendline equation found in sesorCalibration.numbers to return
+    | an approximate actual distance as is seen by the sensor.
+    |
   */
-  int sensorValue = analogRead(A0);
-  float voltage = sensorValue * (5.0 / 1024.0);
-  float actualDistance = pow((23.694 / voltage), (1 / 0.7478));
-  return actualDistance;
-}
-
-// ********************************************************************************
+
+  float tempArray[5];
+  for (int i=0; i<5; i++)
+  {
+    int sensorValue = analogRead(A0);
+    float voltage = sensorValue * (5.0 / 1024.0);                     // Get sensor voltage reading
+    float trendline1 = pow((23.669 / voltage), (1 / 0.749));          // Use calibration voltage to get distance reading
+    float trendline2 = ( (trendline1 + 11.588) / (1.4165) );          // Use trendline one to get distance reading
+    float tempDistance = pow(  (trendline2 / 0.7163), (1 / 1.089) );  // Use trendline two to get distance reading
+
+    tempArray[i] = tempDistance;
+    delay(5);
+  }
+
+  float sum = 0.0;
+  for (int j=0; j<5; j++)
+  {
+    sum = sum + tempArray[j];
+  }
+  sum = sum / 5;       // Ensure all readings are averages of at least 5 readings
+  return sum;
+}
+
+// -------------------------------------------------------------------------
 // Ultrasonic Distance Sensor Function
-// ********************************************************************************
-
-// This code is modified from:
-// https://gist.github.com/flakas/3294829#file-hc-sr04-ino
-
+// -------------------------------------------------------------------------
 float ultraSensorDist()
 {
   /*
-  | -------------------------------------------------------------------------
-  | This function obtains a reading in cm from the ultrasonic distance sensor
-  | The sensor is triggered by a HIGH pulse of 10 or more microseconds.
-  | Reading the signal from the sensor:
-  | a HIGH pulse whose duration is the time (in microseconds) from the sending
-  | of the ping to the reception of its echo off of an object.
-  | To convert the time into a distance:
-  | The speed of sound is 340 m/s or 29.4 microseconds per centimeter.
-  | The ping travels out and back, so to find the distance of the
-  | object we take half of the distance travelled.
-  | -------------------------------------------------------------------------
+    | -------------------------------------------------------------------------
+    | This function obtains a reading in cm from the ultrasonic distance sensor
+    | The sensor is triggered by a HIGH pulse of 10 or more microseconds.
+    |
+    | Reading the signal from the sensor:
+    | a HIGH pulse whose duration is the time (in microseconds) from the sending
+    | of the ping to the reception of its echo off of an object.
+    | To convert the time into a distance:
+    | The speed of sound is 340 m/s or 29.4 microseconds per centimeter.
+    | The ping travels out and back, so to find the distance of the
+    | object we take half of the distance travelled.
+    |
+    | This code is modified from:
+    | https://gist.github.com/flakas/3294829#file-hc-sr04-ino
+    | -------------------------------------------------------------------------
   */
-
-  long duration;
-  float cm;                           // variables for duration of the ping and the distance result in centimeters
-
-  pinMode(trigPin, OUTPUT);           // Set trigPin as output
-  digitalWrite(trigPin, LOW);         // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
-  delayMicroseconds(2);               // Duration of LOW pulse
-  digitalWrite(trigPin, HIGH);        // HIGH pulse to trigger sensor
-  delayMicroseconds(10);              // Duration of HIGH pulse
-  digitalWrite(trigPin, LOW);         // Turn HIGH pulse off
-
-  pinMode(echoPin, INPUT);            // Set echoPin as input
-  duration = pulseIn(echoPin, HIGH);  // Read the signal from the sensor:
-
-  cm = (duration / 29.4) / 2.0;         // convert the time into a distance
-
-  delay(30);
-  return cm;
-}
-
-
-// ********************************************************************************
+  float tempArray[5];
+  for (int i=0; i<5; i++)
+  {
+    pinMode(trigPin, OUTPUT);                               // Set trigPin as output
+    digitalWrite(trigPin, LOW);                             // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
+    delayMicroseconds(2);                                   // Duration of LOW pulse
+    digitalWrite(trigPin, HIGH);                            // HIGH pulse to trigger sensor
+    delayMicroseconds(10);                                  // Duration of HIGH pulse
+    digitalWrite(trigPin, LOW);                             // Turn HIGH pulse off
+
+    pinMode(echoPin, INPUT);                                // Set echoPin as input
+    long duration = pulseIn(echoPin, HIGH);                 // Read the signal from the sensor:
+
+    float cm = (duration / 29.4) / 2.0;                     // convert the time into a distance result in centimeters
+
+    float finalDist = pow( (cm / 1.0014), (1 / 1.0013) );   // Convert distance using trendline equation
+    tempArray[i] = finalDist;
+    delay(5);
+  }
+  float sum = 0.0;
+  for (int j=0; j<5; j++)
+  {
+    sum = sum + tempArray[j];
+  }
+  sum = sum / 5;
+  return sum;
+}
+
+// -------------------------------------------------------------------------
 // Colour Sensor Functions:
-// ********************************************************************************
-
-// ------------------------------------------------------
-// Checking  all colours and setting cup storage sequence
-// ------------------------------------------------------
+// -------------------------------------------------------------------------
+
+// -------------------------------------------------------
+// Checking all colours and setting cup storage sequence |
+// -------------------------------------------------------
 void colourSequence()
 {
   /*
-  |--------------------------------------------------------------------------
-  | Detect, append, and respond accordingly:
-  |--------------------------------------------------------------------------
-  | 1. Check if a known cup colour is detected i.e. colourDetected is not
-  |    equal to zero.
-  | 2. Set response for each possible colour detected i.e. for Pink = 1,
-  |    Blue = 2, Green = 3, and "Not cup colour" = 0.
-  | 3. For each response check if colour not already in array. If it is
-  |    not, append that colour into the corresponding array slot using
-  |    the count variable and increment the count variable by 1.
-  | 4. For each appended colour, blink LED a specific number of times
-  |    i.e. Pink = once, Blue = twice, Green = Thrice.
-  | 5. Once all three colours identified, blink four times.
-  |--------------------------------------------------------------------------
+    |--------------------------------------------------------------------------
+    | Detect, append, and respond accordingly:
+    |--------------------------------------------------------------------------
+    | 1. Check if a known cup colour is detected i.e. colourDetected is not
+    |    equal to zero.
+    | 2. Set response for each possible colour detected i.e. for Pink = 1,
+    |    Blue = 2, Green = 3, and "Not cup colour" = 0.
+    | 3. For each response check if colour not already in array. If it is
+    |    not, append that colour into the corresponding array slot using
+    |    the count variable and increment the count variable by 1.
+    | 4. For each appended colour, blink LED a specific number of times
+    |    i.e. Pink = once, Blue = twice, Green = Thrice.
+    | 5. Once all three colours identified, blink four times.
+    |--------------------------------------------------------------------------
   */
-  int count = 0;                          // Keep track of number of colours detected
+  int count = 0;                                                                // Keep track of number of colours detected
   while (count != 3)
   {
     inArray = false;
     int colourDetected = colourSensed();
-    if (colourDetected != 0)              // Check if colour identified
-    {
-      if (colourDetected == 1)            // If colour detected is Pink
+    if (colourDetected != 0)                                                    // Check if colour identified
+    {
+      if (colourDetected == 1)                                                  // If colour detected is Pink
       {
-        inArray = checkArray(colourDetected);  // Check if colour already in array
-        count = count + storageBlinker(inArray, count, 1, colourDetected);
+        inArray = checkArray(colourDetected);                                   // Check if colour already in array
+        count = count + storageBlinker(inArray, count, 1, colourDetected);      // Append or increment count if colour successfully stored in array
       }
-      else if (colourDetected == 2)       // If colour detected is Blue
+      else if (colourDetected == 2)                                             // If colour detected is Blue
       {
-        inArray = checkArray(colourDetected); // Check if colour already in array
-        count = count + storageBlinker(inArray, count, 2, colourDetected);
+        inArray = checkArray(colourDetected);                                   // Check if colour already in array
+        count = count + storageBlinker(inArray, count, 2, colourDetected);      // Append or increment count if colour successfully stored in array
       }
-      else if (colourDetected == 3)        // If colour detected is Green
+      else if (colourDetected == 3)                                             // If colour detected is Green
       {
-        inArray = checkArray(colourDetected); // Check if colour already in array
-        count = count + storageBlinker(inArray, count, 3, colourDetected);
+        inArray = checkArray(colourDetected);                                   // Check if colour already in array
+        count = count + storageBlinker(inArray, count, 3, colourDetected);      // Append or increment count if colour successfully stored in array
       }
     }
   }
   delay(3000);
-  blinkLED(4);       // Blink 4 times to signal colour sensing process complete
-}
-
-// -----------------------------------
-// Storing identified colours in array
-// -----------------------------------
+  blinkLED(4);                                                                  // Blink 4 times to signal colour sensing process complete
+}
+// -------------------------------------
+// Storing identified colours in array |
+// -------------------------------------
 int storageBlinker(bool inArray, int count, int blinkNumber, int colour)
 {
-  if (inArray == false)
-  {
-    instructionsArray[count] = colour;
-    delay(4000);
-    blinkLED(blinkNumber);
+  if (inArray == false)                   // If item not already in colour sequence array
+  {
+    instructionsArray[count] = colour;    // Append colour into current count slot in colour sequence array
+    delay(4000);                          // Because colour sensing process blinks continuously at 300 ms intervals,
+                                          // the delay allows for recognizable blinking once a colour is identified and stored
+    blinkLED(blinkNumber);                // Blink according to identified colour
     delay(3000);
-    return 1;
-  }
-  else
-  {
-    return 0;
-  }
-}
-// -------------------------------------
-// Checking if colour already identified
-// -------------------------------------
+    return 1;                             // Return integer to increase count by
+  }
+  else                                    // Else if item already in colour seequence array
+  {
+    return 0;                             // Return zero, so count value stays the same
+  }
+}
+// ---------------------------------------
+// Checking if colour already identified |
+// ---------------------------------------
 bool checkArray(int colourDetected)
 {
-  for (int i = 0; i < 3; i++)
-  {
-    if (instructionsArray[i] == colourDetected)
-    {
-      inArray = true;
-    }
-  }
-  return inArray;
-}
-// ------------------------------------------------
-// Making blue LED blink a specific number of times
-// ------------------------------------------------
+  for (int i = 0; i < 3; i++)                     // Iterate throughout entire array length
+  {
+    if (instructionsArray[i] == colourDetected)   // Check array slot for detected colour
+    {
+      inArray = true;                             // If detected colour already in array set inArray value to True
+    }
+  }
+  return inArray;                                 // Return inArray value,
+                                                  // which equals false if detected colour not in colour sequence array
+}
+// --------------------------------------------------
+// Making blue LED blink a specific number of times |
+// --------------------------------------------------
 int blinkLED(int blinkCount)
 {
-  for (int i = 0; i < blinkCount; i++)
-  {
-    digitalWrite(LED, HIGH);
-    delay(1000);
-    digitalWrite(LED, LOW);
-    delay(1000);
-  }
-}
-// ---------------------------------------
-// Detecting and returning colour detected
-// ---------------------------------------
-int colourSensed()
-{
+  for (int i = 0; i < blinkCount; i++)    // Iterate required number of blinks
+  {
+    digitalWrite(LED, HIGH);              // Turn LED on
+    delay(1000);                          // Keep on for 1 second
+    digitalWrite(LED, LOW);               // Turn LED off
+    delay(1000);                          // Keep off for 1 second
+  }
+}
+// -----------------------------------------
+// Detecting and returning colour detected |
+// -----------------------------------------
+int colourSensed()
+{
+  // Turning colour sensor LED on
   digitalWrite(LED, HIGH);
   delay(200);
+
   // Setting red filtered photodiodes to be read
-  digitalWrite(s2,LOW);
-  digitalWrite(s3,LOW);
+  digitalWrite(s2, LOW);
+  digitalWrite(s3, LOW);
   // Reading the output frequency
   int redCheck = pulseIn(colourPin, LOW);

   // Setting Green filtered photodiodes to be read
-  digitalWrite(s2,HIGH);
-  digitalWrite(s3,HIGH);
+  digitalWrite(s2, HIGH);
+  digitalWrite(s3, HIGH);
   // Reading the output frequency
   int greenCheck = pulseIn(colourPin, LOW);

   // Setting Blue filtered photodiodes to be read
-  digitalWrite(s2,LOW);
-  digitalWrite(s3,HIGH);
+  digitalWrite(s2, LOW);
+  digitalWrite(s3, HIGH);
   // Reading the output frequency
   int blueCheck = pulseIn(colourPin, LOW);
+
+  // Turning colour sensor LED on
   digitalWrite(LED, LOW);
   delay(100);

+  /*
+    |--------------------------------------------------------------------------
+    | Detect, append, and respond accordingly:
+    |--------------------------------------------------------------------------
+    |
+    | Detection values used are calibrated using ColourSensorCalibration.ino
+    | file found
+    |
+    |--------------------------------------------------------------------------
+  */
   if ( (redCheck < 600) && (redCheck < blueCheck) && (blueCheck < greenCheck) )
   {
-   colour = 1;
+    colour = 1;                   // Setting detected colour to Pink
   }
   else if ( (redCheck > 600) && (blueCheck < greenCheck) && (greenCheck < redCheck) )
   {
-   colour = 2;
-  }
-  else if ( (redCheck < 600) && (blueCheck < greenCheck) && (greenCheck < redCheck) )
-  {
-   colour = 3;
+    colour = 2;                   // Setting detected colour to Green
+  }
+  else if ( (redCheck < 600) && (blueCheck < greenCheck) && (greenCheck < redCheck) )
+  {
+    colour = 3;                   // Setting detected colour to Blue
   }
   else
   {
-    colour = 0;
+    colour = 0;                   // No colour detected
   }
   return colour;
 }

-// ********************************************************************************
+// -------------------------------------------------------------------------
 // Servomotor position function
-// ********************************************************************************
-
-// This code is modified from:
-// https://sites.google.com/site/daguproducts/home/download-page
-
-void setServoPos(int servoPin, int posMicro)
-{
-  // -------------------------------------------------------------------------
-  /* The angle of rotation of the servo motor is dependant on the length of the pulse sent to it
-   * A pulse of 1500uS corresponds to 90 degrees
-   * A pulse of 700uS corresponds roughly to 0 degrees
-   * A pulse of 2300uS corresponds roughly to 180 degrees
-   * Do not set your servo motor to the limits of its angular position range as this will damage the servo motor
-   * If your servo motor starts to vibrate, you have reached its position limit
-   */
-  // -------------------------------------------------------------------------
-
-  if(posMicro < 700)
-  {
-    posMicro = 700;                         // set minimum pulse width
-  }
-
-  if(posMicro > 2300)
-  {
-    posMicro = 2300;                        // set maximum pulse width
-  }
-
-  for(int i = 0; i < 20; i++)               // send 20 pulses to the servo to allow time for the servo to reach the new position
-  {
-    digitalWrite(servoPin,1);               // set servo control pin high to start pulse
+// -------------------------------------------------------------------------
+void setServoPos(int servoPin, int posMicro)
+{
+  /*
+    | -------------------------------------------------------------------------
+    |
+    | This code is modified from:
+    | https://sites.google.com/site/daguproducts/home/download-page
+    |
+    | The angle of rotation of the servo motor is dependant on the length of
+    | the pulse sent to it.
+    | A pulse of 1500uS corresponds to 90 degrees
+    | A pulse of 700uS corresponds roughly to 0 degrees
+    | A pulse of 2300uS corresponds roughly to 180 degrees
+    | Do not set your servo motor to the limits of its angular position
+    | range as this will damage the servo motor.
+    | If your servo motor starts to vibrate, you have reached its position limit
+    |
+    | -------------------------------------------------------------------------
+  */
+
+  if (posMicro < 700)
+  {
+    posMicro = 700;                         // set minimum pulse width
+  }
+
+  if (posMicro > 2300)
+  {
+    posMicro = 2300;                        // set maximum pulse width
+  }
+
+  for (int i = 0; i < 20; i++)              // send 20 pulses to the servo to allow time for the servo to reach the new position
+  {
+    digitalWrite(servoPin, 1);              // set servo control pin high to start pulse
     delayMicroseconds(posMicro);            // hold pulse high for 'posMicro'uS
-    digitalWrite(servoPin,0);               // set servo control pin low to finish pulse
-    int lenDelay = 20 - posMicro/1000;
+    digitalWrite(servoPin, 0);              // set servo control pin low to finish pulse
+    int lenDelay = 20 - posMicro / 1000;
     delay(lenDelay);                        // wait 20mS before repeating the pulse
-  }
+  }
+}
+// ------------------------------
+// Raise cup latching mechanism |
+// ------------------------------
+void openServo()
+{
+  setServoPos(18, 700);                     // Lift Cup latching Mechanism
+  delay(500);
+}
+// ------------------------------
+// Lower cup latching mechanism |
+// ------------------------------
+void closeServo()
+{
+  setServoPos(18, 1900);                    // Lower cup latching mechanism
+  delay(500);
 }


does almost nothing, but it compiles at least

--- Emp-Ctrl-Due.ino
+++ Emp-Ctrl-Due.ino
@@ -67,15 +67,22 @@
     // Buttons work.
     updateAll();
     digitalWrite(feeder.out, feeder.button.state());
-    if (general.button.status() == true) {
+    digitalWrite(general.out, general.button.state());
+    if (digitalRead(general.out) == ON) {
       modes.set(STARTING);
     }
   } else if (modes.status(STARTING)) {
-    digitalWrite(feeder.out, OFF);
-    digitalWrite(feeder.out, ON);
-
     // 3 empty cycles.
     updateAll();
+    if (digitalRead(feeder.out) == ON) {
+      feeder.button.next();
+      /*digitalWrite(feeder.out, OFF);*/
+      digitalWrite(general.out, general.button.state());
+    }
+    digitalWrite(general.out, general.button.state());
+    if (digitalRead(general.out) == OFF) {
+      modes.set(STANDBY);
+    }
   } else if (modes.status(PRODUCTION)) {
     // Normal production.
     updateAll();


Fix syntactic bug.

Fix syntactic bug.

--- examples/MS5837_Example/MS5837_Example.ino
+++ examples/MS5837_Example/MS5837_Example.ino
@@ -48,7 +48,7 @@
   Wire.begin();

   sensor.init();
-  sensor.setModel(MS5837::MS5837_30BA)
+  sensor.setModel(MS5837::MS5837_30BA);
   sensor.setFluidDensity(997); // kg/m^3 (freshwater, 1029 for seawater)
 }


comments updated

comments updated

--- jenny5-firmware.ino
+++ jenny5-firmware.ino
@@ -1,5 +1,3 @@
-// version 2015.11.07.0
-
 #include <AccelStepper.h>

 #define num_motors 4
@@ -11,6 +9,8 @@

 int default_motor_speed = 3200; //maximum steps per second
 int default_motor_acceleration = 800; //steps/second/second to accelerate
+
+char firmware_version[] = "2015.11.09.4";

 AccelStepper *steppers[num_motors];

@@ -29,16 +29,18 @@
   reset_pins();

   Serial.begin(9600); //Open Serial connection
-  Serial.println("jenny 5 firmaware version 2015.11.09.4");
+  Serial.print("jenny 5 firmaware version: ");
+  Serial.print(firmware_version);
   Serial.println();
   //Print function list for user selection5
   Serial.println("Commands are:");
-  Serial.println("motor index can be between 0 and num_motors - 1");
-  Serial.println("M1 100# // move motor 1 to 100 steps");
-  Serial.println("D1#  // Disable 1");
-  Serial.println("S1 100# // set speed of motor 1 to 100");
-  Serial.println("A1 100# // set acceleration of motor 1 to 100");
-
+  Serial.println("Mx y# // Moves motor x with y steps. If y is negative the motor runs in the opposite direction.");
+  Serial.println("Dx#  // Disables motor x.");
+  Serial.println("Sx y# // Sets speed of motor x to y");
+  Serial.println("Ax y# // Sets acceleration of motor x to y");
+  Serial.println("Motor index can be between 0 and num_motors - 1");
+  Serial.println("Each command is terminated with #.");
+
   Serial.println();

   current_buffer[0] = 0;
@@ -57,7 +59,6 @@
       strcat(current_buffer, arduino_buffer);
       // parse from the beginning until I find a M, D, S or A
       int buffer_length = strlen(current_buffer);
-      //Serial.write(current_buffer);
       for (int i = 0; i < buffer_length; i++)
         if (current_buffer[i] == 'M'){// move motor
           // find the terminal character #
@@ -65,17 +66,13 @@
           for (; j < buffer_length && current_buffer[j] != '#'; j++);// parse until I find the termination char
           if (j < buffer_length){
               char tmp_str[64];
-             // Serial.println(i);
-             // Serial.println(j);
               strncpy(tmp_str, current_buffer + i + 1, j - i - 1);
               tmp_str[j - i - 1] = 0;
               int motor_index, num_steps;
-        //      Serial.write(tmp_str);
               sscanf(tmp_str, "%d%d", &motor_index, &num_steps);
               move_motor(motor_index, num_steps);
               // remove the current executed command
               strcpy(current_buffer, current_buffer + j + 1);
-          //    Serial.write(current_buffer);
               break;
           }
           else{// the string is not completed ... so I must wait more...
@@ -83,23 +80,19 @@
           }
         }
         else
-        if (current_buffer[i] == 'D'){// disable motor
+        if (current_buffer[i] == 'D'){// Disables motor command.
           // find the terminal character #
           int j = i + 1;
           for (; j < buffer_length && current_buffer[j] != '#'; j++);// parse until I find the termination char
           if (j < buffer_length){
               char tmp_str[64];
-             // Serial.println(i);
-             // Serial.println(j);
               strncpy(tmp_str, current_buffer + i + 1, j - i - 1);
               tmp_str[j - i - 1] = 0;
               int motor_index;
-        //      Serial.write(tmp_str);
               sscanf(tmp_str, "%d", &motor_index);
               disable_motor(motor_index);
               // remove the current executed command
               strcpy(current_buffer, current_buffer + j + 1);
-          //    Serial.write(current_buffer);
               break;
           }
           else{// the string is not completed ... so I must wait more...
@@ -116,16 +109,6 @@
       steppers[m]->run();
     else
       steppers[m]->setCurrentPosition(0);
-}
-//--------------------------------------------------------------------------------------------
-//Reset pins to default states
-void reset_pins()
-{
-  for (int m = 0; m < num_motors; m++){
-    digitalWrite(step_pins[m], LOW);
-    digitalWrite(dir_pins[m], LOW);
-    digitalWrite(enable_pins[m], HIGH); // all motors are disabled now
-  }
 }
 //--------------------------------------------------------------------------------------------
 void move_motor(int motor_index, int num_steps)
@@ -153,4 +136,15 @@
   digitalWrite(enable_pins[motor_index], HIGH); // disable motor
 }
 //--------------------------------------------------------------------------------------------
+//Reset pins to default states
+void reset_pins()
+{
+  for (int m = 0; m < num_motors; m++){
+    digitalWrite(step_pins[m], LOW);
+    digitalWrite(dir_pins[m], LOW);
+    digitalWrite(enable_pins[m], HIGH); // all motors are disabled now
+  }
+}
+//--------------------------------------------------------------------------------------------

+


Fixed weird bug

Fixed weird bug

I don't why but it looks like if when there are too many 'else if()s' asking for the different commands, the arduino freezes.

--- firmware/malduino_elite/malduino_elite.ino
+++ firmware/malduino_elite/malduino_elite.ino
@@ -46,8 +46,8 @@
   return -1;
 }

-bool equals(int start, int end, String str){
-  int len = str.length();
+bool equals(int start, int end, char* str){
+  int len = sizeof(str);
   if(end-start != len) return false;
   for(int i=0;i<len;i++){
     if(buf[start+i] != str[i]) return false;
@@ -155,12 +155,13 @@
   else if(equals(s,e,"NUM_7")) KeyboardWrite(KEYPAD_7);
   else if(equals(s,e,"NUM_8")) KeyboardWrite(KEYPAD_8);
   else if(equals(s,e,"NUM_9")) KeyboardWrite(KEYPAD_9);
+  /*
   else if(equals(s,e,"NUM_ASTERIX")) KeyboardWrite(KEYPAD_ASTERIX);
   else if(equals(s,e,"NUM_ENTER")) KeyboardWrite(KEYPAD_ENTER);
   else if(equals(s,e,"NUM_Minus")) KeyboardWrite(KEYPAD_MINUS);
   else if(equals(s,e,"NUM_PERIOD")) KeyboardWrite(KEYPAD_PERIOD);
   else if(equals(s,e,"NUM_PLUS")) KeyboardWrite(KEYPAD_PLUS);
-  else if(equals(s,e,"NUM_SLASH")) KeyboardWrite(KEYPAD_SLASH);
+  else if(equals(s,e,"NUM_SLASH")) KeyboardWrite(KEYPAD_SLASH);*/

   //not implemented
   //else if(equals(s,e,"APP")) Keyboard.press();


use 57600 instead of 19200 for serial

use 57600 instead of 19200 for serial

--- playground/PulseCounting/Measure_pulse_frequency_using_interrupt_1/Measure_pulse_frequency_using_interrupt_1.ino
+++ playground/PulseCounting/Measure_pulse_frequency_using_interrupt_1/Measure_pulse_frequency_using_interrupt_1.ino
@@ -28,7 +28,7 @@

 void setup()
 {
-  Serial.begin(19200);    // this is here so that we can print the result
+  Serial.begin(57600);    // this is here so that we can print the result
   attachInterrupt(1, isr, RISING);    // enable the interrupt
 }