Added description, added door fail retry time, changed variables to underscore instead of camelCase.

--- chicken_door_timer_v2.ino
+++ chicken_door_timer_v2.ino
@@ -1,13 +1,26 @@
+/* Chicek door timer (v2)
+ *  By Leo Febey 2016
+ *  leofebey (at) gmail (dot) com
+ *
+ *  Program that automatically opens and closes a door on sunrise / sunset.
+ *  User can also set a delay before and after sunrise and sunset to
+ *  ensure chickens (or other animals) are very certainly inside.
+ *
+ *  Requires Button.h, TimeLord.h, RTClib.h (Adafruit), and included encoder.h
+ */
+
+// TODO: if door didn't close/open properly, get it to try again a few times.
+// TODO: thoroughly read through code to ensure it's all good.k
 #include <avr/sleep.h>
 #include <avr/power.h>
 #include <avr/wdt.h>

 #include <LiquidCrystal.h>
 #include <Wire.h>
+#include <EEPROM.h>
 #include <Button.h>
 #include <TimeLord.h>
 #include "RTClib.h"
-#include <EEPROM.h>
 #include "encoder.h"

 // Pins
@@ -50,8 +63,7 @@
 #define DEBOUNCE_MS 20
 #define PULLUP false
 #define INVERT false
-
-#define PZ_VOL 254
+#define DOOR_RETRY_SECONDS 10

 Button menuButton(PIN_ENC_BTN, PULLUP, INVERT, DEBOUNCE_MS);

@@ -63,8 +75,9 @@
 const int TIMEOUT_MAX = 220;
 const int DELAY_MS = 10;
 const int MAX_DELAY_MINUTES = 100;
-int menuPos = 0;
-int delayVal = 0;
+int menu_pos = 0;
+int delay_val = 0;
+int door_retry_seconds_c = 0;

 RTC_DS1307 rtc;

@@ -84,14 +97,16 @@
 byte sunset[6];

 // process logic booleans
-bool isDayTime = false;
-bool doorOpen = false;
-bool inSetupMenu = false;
-bool inPreDelayMenu = false;
-bool inPostDelayMenu = false;
-bool setDelayValue = false;
-bool hitBottom = false;
-bool hitTop = false;
+bool is_day_time = false;
+bool door_open = false;
+bool in_setup_menu = false;
+bool in_pre_delay_menu = false;
+bool in_post_delay_menu = false;
+bool set_delay_value = false;
+bool hit_bottom = false;
+bool hit_top = false;
+bool couldnt_close_door = false;
+bool couldnt_open_door = false;

 unsigned int delay_time_before_sunrise;
 unsigned int delay_time_after_sunset;
@@ -119,9 +134,7 @@
   byte sunrise_dt_c_calc = CKSUM_SECRET ^ sunrise_dt_v0;
   sunrise_dt_c_calc ^= sunrise_dt_v1;

-  int eepromSuccess = 0x00;
-
-  //int precalc_sunrise_c = sunrise_dt_c;
+  int eeprom_success = 0x00;

   // if checksum mismatch - something went wrong with EEPROM writing. Try to reset
   if(sunrise_dt_c_calc != sunrise_dt_c){
@@ -137,14 +150,12 @@
     delay_time_before_sunrise = (SUNRISE_DT_0_V << 4) + SUNRISE_DT_1_V;
   } else {
     delay_time_before_sunrise = (sunrise_dt_v0 << 4) + sunrise_dt_v1;
-    eepromSuccess += 0x01;
+    eeprom_success += 0x01;
   }

   // check checksum of sunset time from EEPROM
   byte sunset_dt_c_calc = CKSUM_SECRET ^ sunset_dt_v0;
   sunset_dt_c_calc ^= sunset_dt_v1;
-
-  //int precalc_sunset_c = (int)SUNSET_DT_C_V;

   if(sunset_dt_c_calc != sunset_dt_c){
     lcd.clear();
@@ -159,10 +170,10 @@
     delay_time_after_sunset = (SUNSET_DT_0_V << 4) + SUNSET_DT_1_V;
   } else {
     delay_time_after_sunset = (sunset_dt_v0 << 4) + sunset_dt_v1;
-    eepromSuccess += 0x10;
-  }
-
-  if(eepromSuccess == 0x11){
+    eeprom_success += 0x10;
+  }
+
+  if(eeprom_success == 0x11){
     Serial.println("EEPROM read successfully.");
   }
 }
@@ -317,6 +328,7 @@
   power_all_enable();
 }

+// Opens the door (with timeout)
 void openDoor(){
   lcd.clear();
   lcd.setCursor(0, 0);
@@ -336,11 +348,15 @@
     if(timeoutcount > TIMEOUT_MAX){
       Serial.print("\nERROR! door not closing properly. Check limit switch.\n");
       Serial.print("Pretending that it's closed for now..");
+      couldnt_open_door = true;
       break;
     }
     Serial.print(".");
   }
-  hitTop = true;
+  if(timeoutcount <= TIMEOUT_MAX){
+    couldnt_open_door = false;
+  }
+  hit_top = true;
   Serial.println();

   // send low to door open motor pin
@@ -348,10 +364,11 @@

   Serial.println("Door opened!!");
   // set door is open bool to true
-  doorOpen = true;
-
-}
-
+  door_open = true;
+
+}
+
+// Closes the door (with timeout)
 void closeDoor(){
   // send high to door close motor pin
   digitalWrite(PIN_DOOR_DN, HIGH);
@@ -369,29 +386,43 @@
     if(timeoutcount > TIMEOUT_MAX){
       Serial.print("\nERROR! door not opening properly. Check limit switch.\n");
       Serial.print("Pretending that it's open for now..");
+      couldnt_close_door = true;
       break;
     }
      Serial.print(".");
   }
-  hitBottom = true;
+  if(timeoutcount <= TIMEOUT_MAX){
+    couldnt_close_door = false;
+  }
+  hit_bottom = true;
   Serial.println();

   // send low to door close motor pin
   digitalWrite(PIN_DOOR_DN, LOW);
   Serial.println("Door closed!!");
   // set door is open bool to false
-  doorOpen = false;
+  door_open = false;

 }

 void updateDoor(){
-  if(isDayTime && !doorOpen){
+  if(is_day_time && !door_open){
     Serial.print("It's daytime and we are now opening the door!");
     openDoor();
-  } else if (!isDayTime && doorOpen){
+  } else if (!is_day_time && door_open){
     Serial.print("It's night time and we are now closing the door!");
     closeDoor();
   }
+  door_retry_seconds_c += 4;
+  if(door_retry_seconds_c >= DOOR_RETRY_SECONDS){
+    if(couldnt_open_door){
+      openDoor();
+    } else if (couldnt_close_door){
+      closeDoor();
+    }
+    door_retry_seconds_c = 0;
+  }
+
 }

 // Alert user to press a button, otherwise the system will try to open/close the door to the proper position
@@ -399,9 +430,9 @@
   lcd.clear();
   lcd.setCursor(0, 0);
   lcd.print("Door will ");
-  if(isDayTime && hitBottom){
+  if(is_day_time && hit_bottom){
     lcd.print("open");
-  } else if(!isDayTime && hitTop){
+  } else if(!is_day_time && hit_top){
     lcd.print("close");
   }
   lcd.setCursor(0, 1);
@@ -409,9 +440,9 @@

   DateTime stopTime = rtc.now();
   DateTime fixTime;
-  if(isDayTime && hitBottom){
+  if(is_day_time && hit_bottom){
     fixTime = stopTime + TimeSpan(0, 0, 0, 6);
-  } else if(!isDayTime && hitTop){
+  } else if(!is_day_time && hit_top){
     fixTime = stopTime + TimeSpan(0, 0, 0, 5);
   }

@@ -435,9 +466,9 @@
     lcd.setCursor(0, 0);
     lcd.print("Keeping door ");
     lcd.setCursor(0, 1);
-    if(isDayTime && hitBottom){
+    if(is_day_time && hit_bottom){
       lcd.print("open");
-    } else if(!isDayTime && hitTop){
+    } else if(!is_day_time && hit_top){
       lcd.print("close");
     }
     lcd.print("Press btn");
@@ -446,9 +477,9 @@
     stopTime = rtc.now();
     bool timeOut = false;

-    if(isDayTime && hitBottom){
+    if(is_day_time && hit_bottom){
       fixTime = stopTime + TimeSpan(0, 0, 50, 0);
-    } else if(!isDayTime && hitTop){
+    } else if(!is_day_time && hit_top){
       fixTime = stopTime + TimeSpan(0, 0, 30, 0);
     }

@@ -479,30 +510,30 @@
       lcd.setCursor(0, 0);
       lcd.print("Sorry! Have to");
       lcd.setCursor(0, 1);
-      if(isDayTime && hitBottom){
+      if(is_day_time && hit_bottom){
         lcd.print("open");
-      } else if(!isDayTime && hitTop){
+      } else if(!is_day_time && hit_top){
         lcd.print("close");
       }
       lcd.print(" Door.");
     } else {
       lcd.clear();
       lcd.setCursor(0, 0);
-      if(isDayTime && hitBottom){
+      if(is_day_time && hit_bottom){
         lcd.print("Opening");
-      } else if(!isDayTime && hitTop){
+      } else if(!is_day_time && hit_top){
         lcd.print("Closing");
       }
       lcd.print(" door");
     }
   }
   // finally, open or close the door
-  if(isDayTime && hitBottom){
+  if(is_day_time && hit_bottom){
     openDoor();
-    hitBottom = false;
-  } else if(!isDayTime && hitTop){
+    hit_bottom = false;
+  } else if(!is_day_time && hit_top){
     closeDoor();
-    hitTop = false;
+    hit_top = false;
   }

 }
@@ -510,21 +541,21 @@
 // check limit switches - if door is open when it should be closed
 void checkLimitSwitches(){
   // If daytime, only check if door has been manually or accidentally closed
-  if(isDayTime){
+  if(is_day_time){
     Serial.print("Checking if door closed at daytime.");
     // quickly power motor to check if door is hitting wrong limit switch
     // if down switch pressed and day time
     digitalWrite(PIN_DOOR_DN, HIGH);
     if(digitalRead(PIN_LIMSW_DN) == HIGH){
       Serial.print("Hit bottom!");
-      hitBottom = true;
+      hit_bottom = true;
     }
     delay(1);
     digitalWrite(PIN_DOOR_DN, LOW);
     digitalWrite(PIN_DOOR_UP, HIGH);
     delay(2);
     digitalWrite(PIN_DOOR_UP, LOW);
-    if(hitBottom){
+    if(hit_bottom){
       waitForUserResetOpen();
     }
   } else {
@@ -533,7 +564,7 @@
     // if up switch is pressed at day time
     digitalWrite(PIN_DOOR_UP, HIGH);
     if(digitalRead(PIN_LIMSW_UP) == LOW){
-      hitTop = true;
+      hit_top = true;
       Serial.print("Hit bottom!");
     }
     delay(1);
@@ -541,7 +572,7 @@
     digitalWrite(PIN_DOOR_DN, HIGH);
     delay(2);
     digitalWrite(PIN_DOOR_DN, LOW);
-    if(hitTop){
+    if(hit_top){
       waitForUserResetOpen();
     }
   }
@@ -578,17 +609,17 @@
       Serial.print((int)delta_mins / 60);
       Serial.print(":");
       Serial.println(delta_mins % 60);
-      isDayTime = false;
+      is_day_time = false;
     } else {
       Serial.print("Time until sunset: ");
       Serial.print(-delta_mins / 60);
       Serial.print(":");
       Serial.println(-delta_mins % 60);
-      isDayTime = true;
+      is_day_time = true;
     }
   }
   // get day for tomorrow if the sun has gone down already
-  if(!isDayTime){
+  if(!is_day_time){
     // If in the evening, before the next day
     if(now.hour() > sunset[tl_hour]){
       Serial.println("Checking sunrise for tomorrow..?");
@@ -615,7 +646,7 @@
     Serial.print(":");
     Serial.println((int) sunrise[tl_minute]);
     int delta_mins;
-    if(!isDayTime){
+    if(!is_day_time){
       if(evening){
         // get total mins including minutes before midnight
         delta_mins = (24 - now.hour() + sunrise[tl_hour]) * 60 + (sunrise[tl_minute] + (60-now.minute()));
@@ -662,7 +693,7 @@
  tensDigitLCD(now.hour());
  lcd.print(":");
  tensDigitLCD(now.minute());
-  if(isDayTime){
+  if(is_day_time){
     lcd.setCursor(0, 1);
     lcd.print("Sunset:  ");
     tensDigitLCD(sunset[tl_hour]);
@@ -681,35 +712,35 @@
 void drawDelaySetMenu(){
   lcd.clear();
   lcd.setCursor(0, 0);
-  if(inPreDelayMenu){
+  if(in_pre_delay_menu){
     lcd.print("Pre: ");
-  } else if(inPostDelayMenu){
+  } else if(in_post_delay_menu){
     lcd.print("Post: ");
   }
-  lcd.print(delayVal);
+  lcd.print(delay_val);
   lcd.print(" mins");
 }

 // update delay value loop - check encoder, if change, update lcd with new val
-void updateDelayValLoop(){
+void updatedelay_valLoop(){
   encState eState = encoder.read();
   if (eState == ENC_DEC) {
-    if (delayVal == 0) {
-      delayVal = MAX_DELAY_MINUTES - 1;
+    if (delay_val == 0) {
+      delay_val = MAX_DELAY_MINUTES - 1;
     } else {
-      delayVal = (delayVal - 1);
-    }
-    tone(PIN_PIEZO, 100 + delayVal * 12, 25);
+      delay_val = (delay_val - 1);
+    }
+    tone(PIN_PIEZO, 100 + delay_val * 12, 25);
     drawDelaySetMenu();
   } else if (eState == ENC_INC) {
-    delayVal = (delayVal + 1) % (MAX_DELAY_MINUTES);
-    tone(PIN_PIEZO, 100 + delayVal * 12, 25);
+    delay_val = (delay_val + 1) % (MAX_DELAY_MINUTES);
+    tone(PIN_PIEZO, 100 + delay_val * 12, 25);
     drawDelaySetMenu();
   }
 }

 // write new delay value to EEPROM (including checksum)
-void setDelayValEEPROM(bool sunrise, int val){
+void setdelay_valEEPROM(bool sunrise, int val){
   int val_l = (val & 0b11110000) >> 4;
   int val_r = val & 0b00001111;
   int checksum = CKSUM_SECRET ^ val_l;
@@ -729,24 +760,24 @@
 void updateDelaySettings(){
   // get latest EEPROM values..
   readEEPROM();
-  if(inPreDelayMenu){
-    delayVal = delay_time_before_sunrise;
-  } else if(inPostDelayMenu){
-    delayVal = delay_time_after_sunset;
+  if(in_pre_delay_menu){
+    delay_val = delay_time_before_sunrise;
+  } else if(in_post_delay_menu){
+    delay_val = delay_time_after_sunset;
   }
   drawDelaySetMenu();
-  while(!setDelayValue){
+  while(!set_delay_value){
     wdt_reset();
-    updateDelayValLoop();
+    updatedelay_valLoop();
     menuButton.read();
     if(menuButton.wasReleased()){
-      tone(PIN_PIEZO, 100 + delayVal * 12, 100);
+      tone(PIN_PIEZO, 100 + delay_val * 12, 100);
       delay(200);
-      tone(PIN_PIEZO, 100 + delayVal * 12, 100);
+      tone(PIN_PIEZO, 100 + delay_val * 12, 100);
       // TODO: set delay value in EEPROM
-      setDelayValue = true;
-      bool sunrise = inPreDelayMenu;
-      setDelayValEEPROM(sunrise, delayVal);
+      set_delay_value = true;
+      bool sunrise = in_pre_delay_menu;
+      setdelay_valEEPROM(sunrise, delay_val);
     }
   }
 }
@@ -757,8 +788,8 @@
   lcd.print("Set delay before");
   lcd.setCursor(0, 1);
   lcd.print("Sunrise. [1/2]");
-  inPreDelayMenu = true;
-  inPostDelayMenu = false;
+  in_pre_delay_menu = true;
+  in_post_delay_menu = false;
 }

 void drawPostDelayMenu(){
@@ -766,18 +797,18 @@
   lcd.print("Set delay after");
   lcd.setCursor(0, 1);
   lcd.print("sunset.  [2/2]");
-  inPreDelayMenu = false;
-  inPostDelayMenu = true;
+  in_pre_delay_menu = false;
+  in_post_delay_menu = true;
 }

 void drawSelectedMenu(){
   lcd.setCursor(0, 0);
-  if(menuPos == 0){
+  if(menu_pos == 0){
     drawPreDelayMenu();
-    inPreDelayMenu = true;
-  } else if (menuPos == 1){
+    in_pre_delay_menu = true;
+  } else if (menu_pos == 1){
     drawPostDelayMenu();
-    inPostDelayMenu = true;
+    in_post_delay_menu = true;
   }
 }

@@ -787,19 +818,19 @@
   encState eState = encoder.read();
   if (eState == ENC_DEC) {
     tone(PIN_PIEZO, 400, 25);
-    if (menuPos == 0) {
-      menuPos = MENU_COUNT - 1;
+    if (menu_pos == 0) {
+      menu_pos = MENU_COUNT - 1;
     } else {
-      menuPos = (menuPos - 1);
+      menu_pos = (menu_pos - 1);
     }
     drawSelectedMenu();
     Serial.print("Menu item: ");
-    Serial.println(menuPos);
+    Serial.println(menu_pos);
   } else if (eState == ENC_INC) {
     tone(PIN_PIEZO, 400, 25);
-    menuPos = (menuPos + 1) % (MENU_COUNT);
+    menu_pos = (menu_pos + 1) % (MENU_COUNT);
     Serial.print("Menu item: ");
-    Serial.println(menuPos);
+    Serial.println(menu_pos);
     drawSelectedMenu();
   }
 }
@@ -810,17 +841,17 @@
   if(menuButton.wasReleased()){
     tone(PIN_PIEZO, 1000, 50);
     // if in main menu (date/time)
-    if(!inSetupMenu){
+    if(!in_setup_menu){
       lcd.clear();
-      inSetupMenu = true;
-      inPreDelayMenu = true;
-      inPostDelayMenu = false;
+      in_setup_menu = true;
+      in_pre_delay_menu = true;
+      in_post_delay_menu = false;
       drawPreDelayMenu();
-    } else if (inPreDelayMenu || inPostDelayMenu){
+    } else if (in_pre_delay_menu || in_post_delay_menu){
       Serial.println("drawing menu screen to update delay value");
-      setDelayValue = false;
+      set_delay_value = false;
       updateDelaySettings();
-      inSetupMenu = false;
+      in_setup_menu = false;
     }
   }

@@ -832,7 +863,7 @@
   checkIfButtonPressed();

   // if in menu, update menu
-  if(inSetupMenu){
+  if(in_setup_menu){
     updateSetupMenu();
   } else {
     // main loop - sleep for about 4s (maximum for timer?) then check time and update door


Added Stiring Controls

Added Stiring Controls

--- BrewDuino.ino
+++ BrewDuino.ino
@@ -15,7 +15,7 @@
 #define PIN_ROTARY_2 3
 #define PIN_ROTARY_BUTTON 4
 #define PIN_BG_LIGHT A0
-#define PIN_RUEHRER 5
+#define PIN_STIRER 5
 #define PIN_HEATER 6
 #define PIN_THERMOMETER 7
 #define PIN_BUZZER 8
@@ -104,7 +104,7 @@
 unsigned long alertMillis = 0;

 bool first = false;
-bool isHeating;
+bool isHeating, isStiring = false;

 void setup()   {
   //LCD Setup
@@ -122,8 +122,12 @@

   pinMode(PIN_BG_LIGHT, OUTPUT);
   pinMode(PIN_HEATER, OUTPUT);
+  pinMode(PIN_STIRER, OUTPUT);
   digitalWrite(PIN_BG_LIGHT, LOW);
   digitalWrite(PIN_HEATER, HIGH);
+  digitalWrite(PIN_STIRER, HIGH);
+
+  isStiring = false;

   //Encoder und Interrupt Setup
   encoder = new ClickEncoder(PIN_ROTARY_1, PIN_ROTARY_2, PIN_ROTARY_BUTTON, 4);
@@ -404,6 +408,18 @@
   addTemperature(true);
 }

+void turnOffStiring() {
+  //Toggle Relais
+  isStiring = false;
+  digitalWrite(PIN_STIRER, HIGH);
+}
+
+void turnOnStiring() {
+  //Toggle Relais
+  isStiring = true;
+  digitalWrite(PIN_STIRER, LOW);
+}
+
 void addTemperature(boolean force) {
   //Wenn die aktuelle Temperatur nciht der angezeigten entspricht, aktualisieren.
   if (temp != lastTemp || force) {


fix description in arduino sample

fix description in arduino sample

--- arduino/sketch_sample.ino
+++ arduino/sketch_sample.ino
@@ -1,4 +1,4 @@
-/* Скетч выше, каждые 3 секунды будет присылать в серийный порт следующее:
+/* Данный скетч, каждые 3 секунды будет присылать в серийный порт следующее:
  * <testkey:0>
  * <testkey:1>
  * <testkey:2>


update Arduino glass code; packet transmit one more time


Update KP_Password.ino

Update KP_Password.ino

--- Examples/KP_Password/KP_Password.ino
+++ Examples/KP_Password/KP_Password.ino
@@ -1,3 +1,5 @@
+//Original Creator: Andrew Mascolo
+
 #include <OnewireKeypad.h>
 #include <Password.h>


Shortened heartbeat delay

Shortened heartbeat delay

--- Pan_Tilt_laser/Pan_Tilt_laser.ino
+++ Pan_Tilt_laser/Pan_Tilt_laser.ino
@@ -218,11 +218,11 @@
   uint8_t ledPin = 13;
   pinMode(ledPin, OUTPUT);
   digitalWrite(ledPin, HIGH);
-  delay(250);
+  delay(100);
   digitalWrite(ledPin, LOW);
-  delay(250);
+  delay(100);
   digitalWrite(ledPin, HIGH);
-  delay(250);
+  delay(100);
   digitalWrite(ledPin, LOW);

 }


Tweaks

Tweaks

--- Pan_Tilt_laser/Pan_Tilt_laser.ino
+++ Pan_Tilt_laser/Pan_Tilt_laser.ino
@@ -79,6 +79,7 @@
 void loop() {
   static unsigned long timePassed;
   static int changeVal;
+  static int markovShakeState;
   delay(10);

@@ -88,12 +89,14 @@

   panTilt.updateAngles();
+  if(markovShakeState == 2){
+    shake();
+  }
+
 if(millis() - timePassed >= 1000){
     changeVal = getMarkovSpeed(changeVal);
-
-    if(markovState(20, 70) == 2){
-      shake();
-    }
+    markovShakeState = markovState(10, 20);
+

     if(random(101) < 6){
       delay(markovPause());
@@ -101,12 +104,12 @@
     }

-    if(random(6001) < 2){
+    if(random(5001) < 1){
       sleep(5, 10);

     }

-    else if(random(100001) < 10){
+    else if(random(10001) < 10){
       sleep(1800, 2400); //sleep between 30 and 40 minutes
     }
     timePassed = millis();
@@ -147,12 +150,12 @@

 int getMarkovSpeed(int oldSpeed){
   int probability = random(101);
-  int lowVal = 2;
-  int midVal = 5;
-  int hiVal = 10;
+  int lowVal = 1;
+  int midVal = 2;
+  int hiVal = 3;

   if(oldSpeed == lowVal){
-    if(probability < 20){
+    if(probability < 60){
       return midVal;
     }
     else{
@@ -161,10 +164,10 @@
   }

   else if(oldSpeed == midVal){
-    if(probability < 20){
+    if(probability < 40){
       return hiVal;
     }
-    else if(probability < 70){
+    else if(probability < 90){
       return midVal;
     }
     else{
@@ -173,7 +176,7 @@
   }

   else if(oldSpeed == hiVal){
-    if(probability < 20){
+    if(probability < 50){
       return midVal;
     }
     else{


Update Addicore_RFID_Example.ino

Update Addicore_RFID_Example.ino

--- libraries/AddicoreRFID/examples/Addicore_RFID_Example/Addicore_RFID_Example.ino
+++ libraries/AddicoreRFID/examples/Addicore_RFID_Example/Addicore_RFID_Example.ino
@@ -1,115 +1,115 @@
-// Example sketch to read the ID from an Addicore 13.56MHz RFID tag
-// as found in the RFID AddiKit found at:
-// http://www.addicore.com/RFID-AddiKit-with-RC522-MIFARE-Module-RFID-Cards-p/126.htm
-
-#include <AddicoreRFID.h>
-#include <SPI.h>
-
-#define	uchar	unsigned char
-#define	uint	unsigned int
-
-uchar fifobytes;
-uchar fifoValue;
-
-AddicoreRFID myRFID; // create AddicoreRFID object to control the RFID module
-
-/////////////////////////////////////////////////////////////////////
-//set the pins
-/////////////////////////////////////////////////////////////////////
-const int chipSelectPin = 9;
-const int NRSTPD = 8;
-
-//Maximum length of the array
-#define MAX_LEN 16
-
-void setup() {
-   Serial.begin(9600);                        // RFID reader SOUT pin connected to Serial RX pin at 9600bps
-
-  // start the SPI library:
-  SPI.begin();
-
-  Serial.print("hello world");
-
-  pinMode(chipSelectPin,OUTPUT);              // Set digital pin 9 as OUTPUT to connect it to the RFID /ENABLE pin
-    digitalWrite(chipSelectPin, LOW);         // Activate the RFID reader
-  pinMode(NRSTPD,OUTPUT);                     // Set digital pin 9 , Not Reset and Power-down
-    digitalWrite(NRSTPD, HIGH);
-
-  myRFID.AddicoreRFID_Init();
-}
-
-void loop()
-{
-  	uchar i, tmp, checksum1;
-	uchar status;
-        uchar str[MAX_LEN];
-        uchar RC_size;
-        uchar blockAddr;	//Selection operation block address 0 to 63
-        String mynum = "";
-
-        str[1] = 0x4400;
-	//Find tags, return tag type
-	status = myRFID.AddicoreRFID_Request(PICC_REQIDL, str);
-  Serial.print(	status);
-	if (status == MI_OK)
-	{
-          Serial.println("RFID tag detected");
-          Serial.print("Tag Type:\t\t");
-          uint tagType = str[0] << 8;
-          tagType = tagType + str[1];
-          switch (tagType) {
-            case 0x4400:
-              Serial.println("Mifare UltraLight");
-              break;
-            case 0x400:
-              Serial.println("Mifare One (S50)");
-              break;
-            case 0x200:
-              Serial.println("Mifare One (S70)");
-              break;
-            case 0x800:
-              Serial.println("Mifare Pro (X)");
-              break;
-            case 0x4403:
-              Serial.println("Mifare DESFire");
-              break;
-            default:
-              Serial.println("Unknown");
-              break;
-          }
-	}
-
-	//Anti-collision, return tag serial number 4 bytes
-	status = myRFID.AddicoreRFID_Anticoll(str);
-	if (status == MI_OK)
-	{
-          checksum1 = str[0] ^ str[1] ^ str[2] ^ str[3];
-          Serial.print("The tag's number is:\t");
-    	    Serial.print(str[0]);
-            Serial.print(" , ");
-    	    Serial.print(str[1]);
-            Serial.print(" , ");
-    	    Serial.print(str[2]);
-            Serial.print(" , ");
-    	    Serial.println(str[3]);
-
-          Serial.print("Read Checksum:\t\t");
-    	      Serial.println(str[4]);
-          Serial.print("Calculated Checksum:\t");
-            Serial.println(checksum1);
-
-            // Should really check all pairs, but for now we'll just use the first
-            if(str[0] == 197)                      //You can change this to the first byte of your tag by finding the card's ID through the Serial Monitor
-            {
-                Serial.println("\nHello Craig!\n");
-            } else if(str[0] == 244) {             //You can change this to the first byte of your tag by finding the card's ID through the Serial Monitor
-                Serial.println("\nHello Erin!\n");
-            }
-            Serial.println();
-            delay(1000);
-	}
-
-        myRFID.AddicoreRFID_Halt();		   //Command tag into hibernation
-
-}
+// Example sketch to read the ID from an Addicore 13.56MHz RFID tag
+// as found in the RFID AddiKit found at:
+// http://www.addicore.com/RFID-AddiKit-with-RC522-MIFARE-Module-RFID-Cards-p/126.htm

+#include <AddicoreRFID.h>
+#include <SPI.h>
+
+#define	uchar	unsigned char
+#define	uint	unsigned int
+
+uchar fifobytes;
+uchar fifoValue;
+
+AddicoreRFID myRFID; // create AddicoreRFID object to control the RFID module
+
+/////////////////////////////////////////////////////////////////////
+//set the pins
+/////////////////////////////////////////////////////////////////////
+const int chipSelectPin = 10;
+const int NRSTPD = 5;
+
+//Maximum length of the array
+#define MAX_LEN 16
+
+void setup() {
+   Serial.begin(9600);                        // RFID reader SOUT pin connected to Serial RX pin at 9600bps
+
+  // start the SPI library:
+  SPI.begin();
+
+  Serial.print("hello world");
+
+  pinMode(chipSelectPin,OUTPUT);              // Set digital pin 10 as OUTPUT to connect it to the RFID /ENABLE pin
+    digitalWrite(chipSelectPin, LOW);         // Activate the RFID reader
+  pinMode(NRSTPD,OUTPUT);                     // Set digital pin 5, Not Reset and Power-down
+    digitalWrite(NRSTPD, HIGH);
+
+  myRFID.AddicoreRFID_Init();
+}
+
+void loop()
+{
+  	uchar i, tmp, checksum1;
+	uchar status;
+        uchar str[MAX_LEN];
+        uchar RC_size;
+        uchar blockAddr;	//Selection operation block address 0 to 63
+        String mynum = "";
+
+        str[1] = 0x4400;
+	//Find tags, return tag type
+	status = myRFID.AddicoreRFID_Request(PICC_REQIDL, str);
+  Serial.print(	status);
+	if (status == MI_OK)
+	{
+          Serial.println("RFID tag detected");
+          Serial.print("Tag Type:\t\t");
+          uint tagType = str[0] << 8;
+          tagType = tagType + str[1];
+          switch (tagType) {
+            case 0x4400:
+              Serial.println("Mifare UltraLight");
+              break;
+            case 0x400:
+              Serial.println("Mifare One (S50)");
+              break;
+            case 0x200:
+              Serial.println("Mifare One (S70)");
+              break;
+            case 0x800:
+              Serial.println("Mifare Pro (X)");
+              break;
+            case 0x4403:
+              Serial.println("Mifare DESFire");
+              break;
+            default:
+              Serial.println("Unknown");
+              break;
+          }
+	}
+
+	//Anti-collision, return tag serial number 4 bytes
+	status = myRFID.AddicoreRFID_Anticoll(str);
+	if (status == MI_OK)
+	{
+          checksum1 = str[0] ^ str[1] ^ str[2] ^ str[3];
+          Serial.print("The tag's number is:\t");
+    	    Serial.print(str[0]);
+            Serial.print(" , ");
+    	    Serial.print(str[1]);
+            Serial.print(" , ");
+    	    Serial.print(str[2]);
+            Serial.print(" , ");
+    	    Serial.println(str[3]);
+
+          Serial.print("Read Checksum:\t\t");
+    	      Serial.println(str[4]);
+          Serial.print("Calculated Checksum:\t");
+            Serial.println(checksum1);
+
+            // Should really check all pairs, but for now we'll just use the first
+            if(str[0] == 197)                      //You can change this to the first byte of your tag by finding the card's ID through the Serial Monitor
+            {
+                Serial.println("\nHello Craig!\n");
+            } else if(str[0] == 244) {             //You can change this to the first byte of your tag by finding the card's ID through the Serial Monitor
+                Serial.println("\nHello Erin!\n");
+            }
+            Serial.println();
+            delay(1000);
+	}
+
+        myRFID.AddicoreRFID_Halt();		   //Command tag into hibernation
+
+}
+


more debug commands

more debug commands

--- arduino/HandshakeInterface/HandshakeInterface.ino
+++ arduino/HandshakeInterface/HandshakeInterface.ino
@@ -12,7 +12,8 @@
 PANEL-SET 5 0 100 sculpture1 easein
 PANEL-SET 5 1 100 sculpture2 easein
 PANEL-SET 5 2 100 sculpture3 easein
-//PANEL-SET 5 3 100 white easein
+PANEL-SET 5 3 100 sculpture3 easein
+PANEL-SET 5 3 0 sculpture3 easein
 PANEL-PULSE 5 3 100 white sleep
 PANEL-SET 6 0 100 sculpture1
 PANEL-SET 6 1 100 sculpture1


Attempting to avoid time out problems.

Attempting to avoid time out problems.

--- WhereDial.ino
+++ WhereDial.ino
@@ -321,11 +321,38 @@
   if (err == 0)
   {

+    delay(1000);
+    Serial.print("millis()=");
+    Serial.println(millis());
+
     /* OK - TURN DOWN LED  02 */
     digitalWrite(errorLeds[3],LOW);
     Serial.println("Started request ok");
-
-    err = http.responseStatusCode();
+    if (!http.available()) {
+      digitalWrite(errorLeds[2],LOW);
+      digitalWrite(errorLeds[1],LOW);
+      digitalWrite(errorLeds[0],LOW);
+      while (!http.available() && http.connected()) {
+        delay(10);
+      }
+      // If we've disconnected with no data available,
+      // it's a connection problem not a status code problem
+      if (! http.available()) {
+        Serial.println("Disconnected");
+        digitalWrite(errorLeds[3],HIGH);
+      } else {
+        Serial.println("Turns out we have data");
+      }
+      digitalWrite(errorLeds[2],HIGH);
+      digitalWrite(errorLeds[1],HIGH);
+      digitalWrite(errorLeds[0],HIGH);
+    } else {
+      Serial.println("We have data straight away");
+    }
+
+    if (http.connected()||http.available()) {
+      err = http.responseStatusCode();
+    }
     if ((err >= 200) && (err < 300))
     {

@@ -343,6 +370,8 @@
     {
       Serial.print("Web request failed, got status code: ");
       Serial.println(err);
+      Serial.print("millis()=");
+      Serial.println(millis());
       digitalWrite(ledRed,HIGH);
     }
   }


Testing out integration with WIFI and LCD

--- WiFi/WiFi.ino
+++ WiFi/WiFi.ino
@@ -1,6 +1,8 @@
 #include <Adafruit_CC3000.h>
+#include <SoftwareSerial.h>
 #include <ccspi.h>
 #include <SPI.h>
+#include "utility/debug.h"

 #define CC3000_TINY_DRIVER
 // These are the interrupt and control pins
@@ -12,10 +14,188 @@
 // On an UNO, SCK = 13, MISO = 12, and MOSI = 11
 Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIV2);

+#define WLAN_SSID       "arduino"           // cannot be longer than 32 characters!
+#define WLAN_PASS       "testing123"
+// Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
+#define WLAN_SECURITY   WLAN_SEC_WPA2
+
+#define LISTEN_PORT           7    // What TCP port to listen on for connections.  The echo protocol uses port 7.
+
+Adafruit_CC3000_Server echoServer(LISTEN_PORT);
+
+#define rxPin 4  // rxPin is immaterial - not used - just make this an unused Arduino pin number
+#define txPin 14 // pin 14 is analog pin 0, on a BBB just use a servo cable :), see Reference pinMode
+SoftwareSerial mySerial =  SoftwareSerial(rxPin, txPin);
+
 void setup(void)
 {
+  pinMode(txPin, OUTPUT);
+   mySerial.begin(9600);      // 9600 baud is chip comm speed
+
+   mySerial.print("?G420");   // set display geometry,  2 x 16 characters in this case
+   delay(500);                // pause to allow LCD EEPROM to program
+
+   mySerial.print("?B77");    // set backlight to ff hex, maximum brightness
+   delay(1000);                // pause to allow LCD EEPROM to program
+
+   mySerial.print("?s6");     // set tabs to six spaces
+   delay(1000);               // pause to allow LCD EEPROM to program
+
+    mySerial.print("?D00000000000000000");       // define special characters
+   delay(300);                                  // delay to allow write to EEPROM
+                                                // see moderndevice.com for a handy custom char generator (software app)
+   mySerial.print("?f");                   // clear the LCD
+   delay(10);
+   mySerial.print("...");
+
+
+   //crashes LCD without delay
+   mySerial.print("?D11010101010101010");
+   delay(300);
+
+   mySerial.print("?D21818181818181818");
+   delay(300);
+
+   mySerial.print("?D31c1c1c1c1c1c1c1c");
+   delay(300);
+
+   mySerial.print("?D41e1e1e1e1e1e1e1e");
+   delay(300);
+
+   mySerial.print("?D51f1f1f1f1f1f1f1f");
+   delay(300);
+
+   mySerial.print("?D60000000000040E1F");
+   delay(300);
+
+   mySerial.print("?D70000000103070F1F");
+   delay(300);
+
+   mySerial.print("?c0");                  // turn cursor off
+   delay(300);
+
+   mySerial.print("?f");                   // clear the LCD
+
+   delay(1000);
+
+   mySerial.print("?f");                   // clear the LCD
+   delay(100);
+   delay(3000);
+
+   mySerial.print("?x00?y0");              // cursor to first character of line 0
+
+  mySerial.print(F("Hello, CC3000!\n"));
+
+  delay(1000);
+  mySerial.print("?f");                   // clear the LCD
+  mySerial.print("?x00?y0");              // cursor to first character of line 0
+  mySerial.print("Free RAM: "); mySerial.println(getFreeRam(), DEC);
+
+  delay(1000);
+  mySerial.print("?f");                   // clear the LCD
+  mySerial.print("?x00?y0");              // cursor to first character of line 0
+  mySerial.print("Initializing...");
+
+  /* Initialise the module */
+  if (!cc3000.begin())
+  {
+    mySerial.print("?x00?y1");           // locate cursor to beginning of line 1
+    mySerial.print("Couldn't begin()! Check your wiring?");
+    while(1);
+  }
+
+  mySerial.print("?x00?y1");              // cursor to first character of line 0
+  mySerial.print("Connecting...");
+
+  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
+    mySerial.print("?x00?y1");           // locate cursor to beginning of line 1
+    mySerial.print("Failed!");
+    while(1);
+  }
+
+  mySerial.print("?x00?y2");              // cursor to first character of line 2
+  mySerial.print("Connected!");
+
+  delay(1000);
+  mySerial.print("?f");                   // clear the LCD
+  mySerial.print("?x00?y0");              // cursor to first character of line 0
+
+  mySerial.print("Request DHCP");
+  while (!cc3000.checkDHCP())
+  {
+    delay(100); // ToDo: Insert a DHCP timeout!
+  }
+
+  delay(1000);
+  mySerial.print("?f");                   // clear the LCD
+  mySerial.print("?x00?y0");              // cursor to first character of line 0
+
+  /* Display the IP address DNS, Gateway, etc. */
+  while (! displayConnectionDetails()) {
+    delay(1000);
+  }
+
+  // Start listening for connections
+  echoServer.begin();
+
+  delay(3000);
+  mySerial.print("?f");                   // clear the LCD
+  mySerial.print("?x00?y0");              // cursor to first character of line 0
+
+  mySerial.print("Listening...");
 }

 void loop(void)
 {
-}
+  // Try to get a client which is connected.
+  Adafruit_CC3000_ClientRef client = echoServer.available();
+  if (client) {
+     // Check if there is data available to read.
+     if (client.available() > 0) {
+       // Read a byte and write it to all clients.
+       uint8_t ch = client.read();
+       mySerial.print((char) ch);
+       client.write(ch);
+     }
+  }
+}
+
+/**************************************************************************/
+/*!
+    @brief  Tries to read the IP address and other connection details
+*/
+/**************************************************************************/
+bool displayConnectionDetails(void)
+{
+  uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;
+
+  mySerial.print("?f");                   // clear the LCD
+  mySerial.print("?x00?y0");              // cursor to first character of line 0
+
+  if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
+  {
+    mySerial.print("Unable to retrieve the IP Address!");
+    return false;
+  }
+  else
+  {
+    mySerial.print("IP: "); printIPdots(ipAddress);
+    mySerial.print("?x00?y1");              // cursor to first character of line 1
+    mySerial.print("GW: "); printIPdots(gateway);
+    mySerial.print("?x00?y2");              // cursor to first character of line 2
+    mySerial.print("DHCP: "); printIPdots(dhcpserv);
+    mySerial.print("?x00?y3");              // cursor to first character of line 3
+    mySerial.print("DNS: "); printIPdots(dnsserv);
+    return true;
+  }
+}
+
+void printIPdots(uint32_t ip) {
+  mySerial.print((uint8_t)(ip >> 24));
+  mySerial.print('.');
+  mySerial.print((uint8_t)(ip >> 16));
+  mySerial.print('.');
+  mySerial.print((uint8_t)(ip >> 8));
+  mySerial.print('.');
+  mySerial.print((uint8_t)(ip));
+}


matrix read now debugged

matrix read now debugged

--- KSPboard.ino
+++ KSPboard.ino
@@ -152,40 +152,23 @@
   uint16_t matrix = 0;
   uint8_t row = 0, col = 0;

-#ifdef DEBUG
-  Serial.println(F(" => matrix"));
-#endif
-
   for (row = PIN_HELM_MAT_ROW; row < PIN_HELM_MAT_ROWS; row++)
   {
     digitalWrite(row, LOW); // turn on the active-low row

     for (col = PIN_HELM_MAT_COL; col < PIN_HELM_MAT_COLS; col++)
     {
-      boolean switchState = !digitalRead(col); // get inverted result
-      matrix <<= switchState; // and shift it onto the matrix
-
-#ifdef DEBUG
-      Serial.print(F("\t"));
-      Serial.print(switchState);
-#endif
+      // get inverted result and shift it onto the matrix
+      matrix = (matrix << 1) | !digitalRead(col); // wish there was <<=
     }

     digitalWrite(row, HIGH); // turn off the active-low row
-
-#ifdef DEBUG
-    Serial.println();
-#endif
-  }
-
-#ifdef DEBUG
-  Serial.println();
-#endif
+  }

   return (matrix);
 }

-int16_t helmGetAdjustment(uint8_t high, uint8_t low, int8_t adj) // get control input
+int16_t helmGetAdjustment(boolean high, boolean low, int8_t adj) // get control input
 {
   switch (high ? HIGH : (low ? LOW : NEUTRAL)) // high trumps low
   {
@@ -282,6 +265,7 @@

   for (index = PIN_HELM_MAT_ROW; index < PIN_HELM_MAT_ROWS; index++)
   {
+    pinMode(index, OUTPUT);
     digitalWrite(index, HIGH); // pull these up to 5V so current cannot flow
   }
 }
@@ -348,12 +332,7 @@
 {
   // get the matrix state used in the pitch/roll/yaw masks below
   uint16_t helm = helmReadMatrix();
-/*
-#ifdef DEBUG
-  Serial.print(F(" => maxtrix:\n\t"));
-  Serial.println(helm, BIN);
-#endif
-*/
+
   // update control surface inputs
   // the MASKED_ contants have "helm & DIR_MASK_x" format for convenience
   pitchAdjust = helmGetAdjustment(MASKED_PITCH_U, MASKED_PITCH_D, pitchAdjust);
@@ -453,6 +432,7 @@
   delay(DELAY_LOOP);
 #else
   delay(DELAY_DEBUG);
+  Serial.println(); // separates the data packets with a newline
 #endif

   Serial.flush();


fix chip type in comment

fix chip type in comment

--- arduino/libraries/examples/DG408_AnalogMUX8to1_test/DG408_AnalogMUX8to1_test.ino
+++ arduino/libraries/examples/DG408_AnalogMUX8to1_test/DG408_AnalogMUX8to1_test.ino
@@ -9,7 +9,7 @@
 #include <SPI.h>
 #include <DG408_AnalogMUX8to1.h>

-//configure the DAC chip - on OLM port 4
+//configure the MUX chip - on OLM port 4
 DG408_AnalogMUX8to1Class MUX(10,  //addr0
                              A3, //addr1
                              7   //addr2


- remove indicate property (so it can be used with Android)

--- examples/test/test.ino
+++ examples/test/test.ino
@@ -1,5 +1,5 @@

-#define SHOW_FREE_MEMORY
+//#define SHOW_FREE_MEMORY

 #ifdef SHOW_FREE_MEMORY
 #include <MemoryFree.h>
@@ -12,10 +12,10 @@
 #define BLE_RDY 2
 #define BLE_RST 9

-BLEPeripheral     blePeripheral                         = BLEPeripheral(BLE_REQ, BLE_RDY, BLE_RST);
+BLEPeripheral                      blePeripheral        = BLEPeripheral(BLE_REQ, BLE_RDY, BLE_RST);

 BLEService                         test1Service         = BLEService("fff0");
-BLECharacteristicT<unsigned short> test1Characteristic  = BLECharacteristicT<unsigned short>("fff1", BLEPropertyRead | BLEPropertyWrite | BLEPropertyWriteWithoutResponse | BLEPropertyNotify | BLEPropertyIndicate);
+BLECharacteristicT<unsigned short> test1Characteristic  = BLECharacteristicT<unsigned short>("fff1", BLEPropertyRead | BLEPropertyWrite | BLEPropertyWriteWithoutResponse | BLEPropertyNotify /*| BLEPropertyIndicate*/);
 BLEDescriptor                      test1Descriptor      = BLEDescriptor("2901", "counter");

 void setup() {


testing a different number for custom service id (***215)

--- angu/angu.ino
+++ angu/angu.ino
@@ -2,11 +2,11 @@

 const int ledPin = 13; // set ledPin to on-board LED

-BLEService ledService("19B10010-E8F2-537E-4F6C-D104768A1214"); // create service
+BLEService ledService("19B10010-E8F2-537E-4F6C-D104768A1215"); // create service

 // create switch characteristic and allow remote device to read and write
-BLECharCharacteristic ledCharacteristic("19B10011-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
+BLECharCharacteristic ledCharacteristic("19B10011-E8F2-537E-4F6C-D104768A1215", BLERead | BLEWrite);

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


Changed command z to command Z to be in-line with the other screen serial commands

--- 00_Firmware/Firmware/Firmware.ino
+++ 00_Firmware/Firmware/Firmware.ino
@@ -32,6 +32,7 @@
         [G][0-255][X] - Set green value
         [B][0-255][X] - Set blue value
         [H][0-255][X] - Set height value
+        [Z][any][X]   - Zero the actuator

         When in any mode:
         [M][H][X] - Change to height mode
@@ -1106,10 +1107,31 @@
 	}
 }

+#define SERIAL_WATCH_ERRORS
+
 void loopSerialMode()
 {
 	screenSerialRead();
-
+
+        #ifdef SERIAL_WATCH_ERRORS
+        static byte lastValue = 0;
+        if( cmdBuffer[0] == 0 )
+          lastValue = 0;
+
+        if( cmdBuffer[0] > lastValue )
+        {
+          if( cmdBuffer[0] != lastValue+1 )
+            Serial.print( "Err," );
+          else
+            Serial.print( "Ok," );
+          Serial.println( cmdBuffer[0] );
+
+          lastValue = cmdBuffer[0];
+        }
+
+
+        #else
+
 	if( cmdBuffer[2] == 'X' )
 	{
 		switch( cmdBuffer[0] )
@@ -1118,13 +1140,14 @@
 			case 'G': iTargetG = (unsigned)cmdBuffer[1]; eRGBMode = RGBMODE_SCREEN; break;
 			case 'B': iTargetB = (unsigned)cmdBuffer[1]; eRGBMode = RGBMODE_SCREEN; break;
 			case 'H': iTargetPos = map( (unsigned)cmdBuffer[1], 0, 0xFF, 0, MOTOR_TRAVEL ); break;
-			case 'z': zeroMotor(); break;
+			case 'Z': zeroMotor(); break;
 		}
 	}

 	// Move the motor and update the colour.
 	moveMotor();
 	updateColour();
+        #endif
 }

 /**


Get rid of PID library dependency (not necessary) Add time out

--- Arduino/Simple/src/src.ino
+++ Arduino/Simple/src/src.ino
@@ -19,17 +19,20 @@
 #include <SoftwareSerial.h>
 #include <SabertoothSimplified.h>
 #include <TinyGPS++.h>
-#include <PID_v1.h>

 const int ledPin = 13;

 String inputString = "";         // a string to hold incoming data
 boolean stringComplete = false;  // whether the string is complete
+boolean isTimeOut = false;

 //Note: NOT_A_PIN (0) was previously used for RX which is not used, but this was causing problems
 SoftwareSerial SWSerial(10, 8); // RX, TX. RX on no pin (unused), TX on pin 8 (to S1).
 SabertoothSimplified ST(SWSerial); // Use SWSerial as the serial port.
 int power1, power2;
+long lastSerialReception_ms;
+long last_order_ms = 0;
+#define ORDER_RATE_ms 100

 TinyGPSPlus nmea;
 // O stands for Opensource, R for Robokite
@@ -40,13 +43,6 @@
 TinyGPSCustom setpos1  (nmea, "ORSP1", 1);  // Position setpoint for Sabertooth output 1
 TinyGPSCustom setpos2  (nmea, "ORSP2", 1);  // Position setpoint for Sabertooth output 2
 boolean isFeedbackRequested = false;
-
-// Define Variables we'll be connecting to
-double Setpoint1, Input1, Output1;
-double Setpoint2, Input2, Output2;
-// Specify the links and initial tuning parameters (Kp, Ki, Kd)
-PID myPID1(&Input1, &Output1, &Setpoint1, 1, 0, 0, DIRECT);
-PID myPID2(&Input2, &Output2, &Setpoint2, 1, 0, 0, DIRECT);

 void setup()
 {
@@ -78,6 +74,8 @@
     if (inChar == '\n') {
       stringComplete = true;
     }
+    lastSerialReception_ms = millis();
+    isTimeOut = false;
   }
 }

@@ -93,9 +91,14 @@

 void processSerialInput()
 {
+  if (fabs(millis()-lastSerialReception_ms)>1000)
+  {
+    isTimeOut = true;
+  }
   // print the string when a newline arrives:
   if (stringComplete)
   {
+
     //Serial.println(inputString);
     char ctab[inputString.length()+1];
     inputString.toCharArray(ctab, sizeof(ctab));
@@ -107,11 +110,11 @@
       {
         if (pwm1.isUpdated())
         {
-          myPID1.SetMode(MANUAL);
+          pwm1.value();
         }
         if (pwm2.isUpdated())
         {
-          myPID2.SetMode(MANUAL);
+          pwm2.value();
         }
         if (feedback_request.isUpdated())
         {
@@ -144,21 +147,30 @@
 }

 void computeOrder()
-{
-  if (myPID1.GetMode() == MANUAL)
+{
+  if (isTimeOut)
+  {
+    power1 = 0;
+    power2 = 0;
+  }
+  else
   {
     power1 = atoi(pwm1.value());
-  }
-  if (myPID2.GetMode() == MANUAL)
-  {
     power2 = atoi(pwm2.value());
   }
+
 }

 void sendOrder()
 {
+  if (fabs(millis()-last_order_ms)>ORDER_RATE_ms)
+  {
+    last_order_ms = millis();
   // Order in the range -127/127
+    //SWSerial.println(127);
+      //Saturation based on posSat
    ST.motor(1, power1);
    ST.motor(2, power2);
 }
+}


Update McLighting.ino

Update McLighting.ino

- "/pixelconf" code to check for HTTP method code is commented but placed for the future

--- Arduino/McLighting/McLighting.ino
+++ Arduino/McLighting/McLighting.ino
@@ -773,6 +773,19 @@

   server.on("/pixelconf", []() {

+    /*
+
+    // This will be used later when web-interface is ready and HTTP_GET will not be allowed to update the Strip Settings
+
+    if(server.args() == 0 and server.method() != HTTP_POST)
+    {
+      server.sendHeader("Access-Control-Allow-Origin", "*");
+      server.send(200, "text/plain", "Only HTTP POST method is allowed and check the number of arguments!");
+      return;
+    }
+
+    */
+
     bool updateStrip = false;
     if(server.hasArg("ct")){
       uint16_t pixelCt = server.arg("ct").toInt();


fix: add termination character at the end of payload

--- VideoMicStatus/VideoMicStatus.ino
+++ VideoMicStatus/VideoMicStatus.ino
@@ -22,29 +22,29 @@

 // Radio pipe addresses for the 2 nodes to communicate.
 const uint64_t pipes[2] = {
-  0xF2F0F0F0D3LL, 0xF1F0F0F0C3LL
-};
-
-//Door Status
-typedef enum {
-  NOMEETING = 0, MIC = 1, CAMERA = 2, MICANDCAMERA = 3
-}
-SwitchStats;
+    0xF2F0F0F0D3LL, 0xF1F0F0F0C3LL};
+
+// Door Status
+typedef enum
+{
+  NOMEETING = 0,
+  MIC = 1,
+  CAMERA = 2,
+  MICANDCAMERA = 3
+} SwitchStats;

 // FriendlyName of the door state
-const char* switchStatsFriendlyName[] = {
-  "No meeting\n", "Mic on\n", "Video on\n", "Video and mic on\n"
-};
-
-//Status of the door currently
+const char *switchStatsFriendlyName[] = {
+    "No meeting\n", "Mic on\n", "Video on\n", "Video and mic on\n"};
+
+// Status of the door currently
 SwitchStats switchStats;
-

 const int maxPayloadSize = 255;
 const int minPayloadSize = 4;
 const int packageSize = 32;
 const int payloadIncrementBy = 2;
-const char* packetSizeCode = "packet-size";
+const char *packetSizeCode = "packet-size";
 int nextPayloadSize = minPayloadSize;

 void setup(void)
@@ -54,7 +54,8 @@
   configureRF();
 }

-void setInitialState() {
+void setInitialState()
+{
   pinMode(red, OUTPUT);
   pinMode(green, OUTPUT);
   pinMode(blue, OUTPUT);
@@ -66,7 +67,8 @@
   switchStats = NOMEETING;
 }

-void configureRF() {
+void configureRF()
+{
   Serial.begin(57600);
   printf_begin();

@@ -76,7 +78,7 @@
   // We will be using the Ack Payload feature, so please enable it
   radio.enableAckPayload();

-  //All other setup
+  // All other setup
   radio.setDataRate(RF24_250KBPS);
   radio.setPALevel(RF24_PA_MAX);
   radio.setChannel(90);
@@ -97,14 +99,14 @@

 void loop(void)
 {
-    // if there is data ready
+  // if there is data ready
   if (radio.available())
   {
     String payload = getPayload();
-
-    /*
-    * NOTE: stop listening and send ack payload back when necessary
-    */
+
+    /*
+     * NOTE: stop listening and send ack payload back when necessary
+     */

     decideSwitchMode(payload);
     delay(1000);
@@ -112,10 +114,11 @@
   runLightShow();
 }

-String getPayload(){
+String getPayload()
+{
   // Dump the payloads until we've gotten everything
   uint8_t len;
-
+
   //[maxPayloadSize + 1];
   String finalMessage;
   unsigned long started_waiting_at = millis();
@@ -126,56 +129,67 @@
   while (radio.available() || radioIterator < packetCount)
   {
     char receive_payload[50];
-    if(radio.available()) {
+    if (radio.available())
+    {
       // Fetch the payload, and see if this was the last one.
       len = radio.getDynamicPayloadSize();
       radio.read(receive_payload, len);
-       // Spew it
+
+      receive_payload[len] = '\0';
+
+      // Spew it
       printf("Got payload size=%i value=%s\n\r", len, receive_payload);
     }

-    if (millis() - started_waiting_at > 2500) {
+    if (millis() - started_waiting_at > 2500)
+    {
       radioIterator = packetCount;
       printf("timeout; payload is now: %s\n\r", receive_payload);
     }

     // sender is sending packet size information
-    if(radioIterator == 0 &&
-      strncmp(receive_payload, packetSizeCode, sizeof(packetSizeCode)) == 0) {
-        strtok(receive_payload, ":");
-        packetCount = atoi(strtok(NULL, ":"));
-        printf("number of packets changed to: %i\n\r", packetCount);
-
-        radioIterator++;
+    if (radioIterator == 0 &&
+        strncmp(receive_payload, packetSizeCode, sizeof(packetSizeCode)) == 0)
+    {
+      strtok(receive_payload, ":");
+      packetCount = atoi(strtok(NULL, ":"));
+      printf("number of packets changed to: %i\n\r", packetCount);
+
+      radioIterator++;
     }

     // only concatenate string when packet count is still as the sender says
-    if(strncmp(receive_payload, packetSizeCode, sizeof(packetSizeCode)) != 0) {
+    if (strncmp(receive_payload, packetSizeCode, sizeof(packetSizeCode)) != 0 && strcmp(receive_payload, "") != 0)
+    {
       finalMessage.concat(receive_payload);

       radioIterator++;
     }
+
+    memset(receive_payload, 0, sizeof(receive_payload));
   }
   printf("no more data\n\r");

   return finalMessage;
 }

-void decideSwitchMode(String jsonString) {
+void decideSwitchMode(String jsonString)
+{
   DynamicJsonDocument doc(350);
-  char* jsonChar = const_cast<char*>(jsonString.c_str());
-
+  char *jsonChar = const_cast<char *>(jsonString.c_str());
+
   printf("JSON covert: %s", jsonString.c_str());
   auto error = deserializeJson(doc, jsonChar);
-  if (error) {
-      Serial.print(F("deserializeJson() failed with code "));
-      Serial.println(error.c_str());
-      return;
+  if (error)
+  {
+    Serial.print(F("deserializeJson() failed with code "));
+    Serial.println(error.c_str());
+    return;
   }

   const int noMeetRed = doc["noMeeting"]["red"];
   const int micRed = doc["mic"]["red"];
-
+
   printf("nomeet: %i, mic: %i; camera: %s\n\r", noMeetRed, micRed, doc["camera"]);

   // if (jsonString == "green")
@@ -192,15 +206,15 @@
   // }
 }

-void runLightShow() {
-  switch(switchStats) {
-    case MIC:
-      analogWrite(red, 255);
-      delay(1000);
-      analogWrite(red, 0);
-      delay(1000);
-      break;
-    }
-}
-
-
+void runLightShow()
+{
+  switch (switchStats)
+  {
+  case MIC:
+    analogWrite(red, 255);
+    delay(1000);
+    analogWrite(red, 0);
+    delay(1000);
+    break;
+  }
+}


fixed int that should not have been int (it overflowed!)

--- arduino/motor_driver/motor_driver.ino
+++ arduino/motor_driver/motor_driver.ino
@@ -184,10 +184,9 @@
     else if (state==HOMINGBACKOFF) {
       return;
     }
-    else state=ENDSTOP;

+    state=ENDSTOP;
     goalSpeed = 0;
-
   }

@@ -446,7 +445,7 @@
   // /go/nwPos,nePos,sePos,swPos long ints
   if (state != OK) return;

-  int value = m.getFloat(MOTOR_ID);
+  double value = m.getFloat(MOTOR_ID);
   pidSetpoint = value;
 }


Delete K_Nearest_Boxes_Height_Weight.ino

--- K_Nearest_Boxes_Height_Weight.ino
+++ K_Nearest_Boxes_Height_Weight.ino
@@ -1,324 +0,0 @@
-//Distance Sensor   UPDATE
-//Feature is height
-//Pre-known object of different heights
-#include <Arduino.h>
-#include <NewPing.h>
-#include <HX711.h>
-#include <Wire.h>
-#include "Adafruit_TCS34725.h"
-
-#include <math.h>
-
-#include "Object.h"
-
-// Distance Sensor (Height)
-#define TRIGGER_PIN 12
-#define ECHO_PIN 11
-
-// Weight Sensor
-#define DOUT 3
-#define CLK 2
-
-int test = 0;
-
-const int DISTANCE_SENSOR_MAX_DISTANCE = 50;
-
-// HX711 Weight Sensor
-// Use HX711_Calibration sketch to define
-const float calibration_factor = 0;
-
-// K Nearest Neighbors
-const int K = 3;
-
-byte gammatable[256];
-Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_50MS, TCS34725_GAIN_4X);
-
-const size_t NUM_OF_KNOWN_OBJECTS = 9;
-const size_t NUM_OF_OBJECT_TYPES = 3;
-String Known_Object_Types[3] = {"Small", "Medium", "Large"};
-const int STRUCT_FIELDS = 5;
-
-const int HEIGHT_MAX = 50;
-const int HEIGHT_MIN = 0;
-const int WEIGHT_MAX = 6;
-const int WEIGHT_MIN = 0;
-const int RGB_MAX = 256;
-const int RGB_MIN = 0;
-
-NewPing sonar(TRIGGER_PIN, ECHO_PIN, DISTANCE_SENSOR_MAX_DISTANCE);
-HX711 scale(DOUT, CLK);
-
-//  Computes the euclidean distance between the known and the current object's features
-float ComputeDistanceofObjects(Object currObject, Object knownObject) {
-  float height = currObject.height - knownObject.height;
-  float weight = currObject.weight - knownObject.weight;
-  float red = currObject.red - knownObject.red;
-  float green = currObject.green - knownObject.green;
-  float blue = currObject.blue - knownObject.blue;
-  float dist = 0;
-  dist = pow(height, 2) + pow(weight, 2) + pow(red, 2) + pow(green, 2) + pow(blue, 2);
-  dist = sqrt(dist);
-  // Nearest 100ths place
-  dist = roundf(dist * 100.0) / 100.0;
-
-  return dist;
-}
-
-
-// Takes the features from the current object and converts them to strings and integers
-// **
-void ObjectFeatureExtraction(Object &currObject) {
-  // Pass in an object (Pass by pointer) (Maybe?)
-  int currDistance;
-  //Need a fourth value for getRawData()
-  uint16_t red, green, blue, clear_val;
-  uint32_t sum;
-  float r, g, b;
-
-  // Get height feature (in cm)
-  currDistance = sonar.ping_cm();
-  currObject.height = DISTANCE_SENSOR_MAX_DISTANCE - currDistance;
-
-  // Get weight feature (in lbs) to the nearest 100ths place
-  currObject.weight = roundf(scale.get_units() * 100.0) / 100.0;
-
-  // RGB VALUES
-  // turn on LED
-  tcs.setInterrupt(false);
-  // takes 60ms to read
-  delay(60);
-  tcs.getRawData(&red, &green, &blue, &clear_val);
-  //turn off LED
-  tcs.setInterrupt(true);
-  sum = clear_val;
-  r = red/sum;
-  g = green/sum;
-  b = blue/sum;
-  r *= 256;
-  g *= 256;
-  b *= 256;
-  currObject.red = (int)r;
-  currObject.green = (int)g;
-  currObject.blue = (int)b;
-}
-
-float Standardize(float original_value, float min_value, float max_value) {
-  float standardized;
-  standardized = (original_value - min_value)/(max_value - min_value);
-  return standardized;
-}
-
-void StandardizeObject(Object &currObject, Object (&knownObjects)[NUM_OF_KNOWN_OBJECTS]) {
-  currObject.height = Standardize(currObject.height, HEIGHT_MIN, HEIGHT_MAX);
-  currObject.weight = Standardize(currObject.weight, WEIGHT_MIN, WEIGHT_MAX);
-  currObject.red = Standardize(currObject.red, RGB_MIN, RGB_MAX);
-  currObject.green = Standardize(currObject.green, RGB_MIN, RGB_MAX);
-  currObject.blue = Standardize(currObject.blue, RGB_MIN, RGB_MAX);
-
-  for(int i = 0; i < NUM_OF_KNOWN_OBJECTS; ++i) {
-    knownObjects[i].height = Standardize(knownObjects[i].height, HEIGHT_MIN, HEIGHT_MAX);
-    knownObjects[i].weight = Standardize(knownObjects[i].weight, WEIGHT_MIN, WEIGHT_MAX);
-    knownObjects[i].red = Standardize(knownObjects[i].red, RGB_MIN, RGB_MAX);
-    knownObjects[i].green = Standardize(knownObjects[i].green, RGB_MIN, RGB_MAX);
-    knownObjects[i].blue = Standardize(knownObjects[i].blue, RGB_MIN, RGB_MAX);
-  }
-}
-
-// Finds the patterns from the current object and compares them to patterns from the given objects
-// **
-String PatternRecognition(Object currObject, Object knownObjects[]) {
-
-  Object kNearestObjects[K];
-  // For testing purposes
-  /*
-  Serial.print("Object standardized height: ");
-  Serial.println(currObject.height);
-  Serial.print("Object standardized weight: ");
-  Serial.println(currObject.weight);
-  Serial.print("Object standardized red: ");
-  Serial.println(currObject.red);
-  Serial.print("Object standardized green: ");
-  Serial.println(currObject.green);
-  Serial.print("Object standardized blue: ");
-  Serial.println(currObject.blue);
-  */
-
-  // For testing purposes
-  for(int i = 0; i < NUM_OF_KNOWN_OBJECTS; ++i) {
-    Serial.println(ComputeDistanceofObjects(currObject, knownObjects[i]));
-  }
-
-  for(int i = 0; i < K; ++i) {
-    kNearestObjects[i].height = abs(knownObjects[i].height - currObject.height);
-    kNearestObjects[i].weight = abs(knownObjects[i].weight - currObject.weight);
-    kNearestObjects[i].red = abs(knownObjects[i].red - currObject.red);
-    kNearestObjects[i].green = abs(knownObjects[i].green - currObject.green);
-    kNearestObjects[i].blue = abs(knownObjects[i].blue - currObject.blue);
-    kNearestObjects[i].type = knownObjects[i].type;
-  }
-
-  // Now, determine if each remaining object is among the K closest, and if so insert into array (thus dropping one obj)
-  for(int i = K; i < NUM_OF_KNOWN_OBJECTS; ++i) { // For each remaining known object
-
-    // Find the current max difference (CHANGE TO DISTANCE, EVERYWHERE) in the K nearest objects
-    float max_diff = 0;
-    int max_index = 0;
-    int temp_height = 0;
-    float temp_weight = 0;
-    float temp_red = 0;
-    float temp_green = 0;
-    float temp_blue = 0;
-    float temp_dist = 0;
-
-    for(int j = 0; j < K; ++j) {
-      /*
-      temp_height = kNearestObjects[j].height;
-      temp_weight = kNearestObjects[j].weight;
-      temp_red = kNearestObjects[j].red;
-      temp_green = kNearestObjects[j].green;
-      temp_blue = kNearestObjects[j].blue;
-      */
-      //temp_dist = ComputeDistanceofObjects(temp_height, temp_weight);
-
-      //ISSUE MIGHT BE HERE
-      temp_dist = ComputeDistanceofObjects(currObject, kNearestObjects[j]);
-
-      if(temp_dist > max_diff) { // Update max
-        max_diff = temp_dist;
-        max_index = j;
-      }
-    }
-
-    // If the current known object's difference < the max difference in the current K nearest neighbors
-    temp_height = abs(knownObjects[i].height - currObject.height);
-    temp_weight = abs(knownObjects[i].weight - currObject.weight);
-    temp_red = abs(knownObjects[i].red - currObject.red);
-    temp_green = abs(knownObjects[i].green - currObject.green);
-    temp_blue = abs(knownObjects[i].blue - currObject.blue);
-    //temp_dist = ComputeDistanceofObjects(temp_height, temp_weight);
-    temp_dist = ComputeDistanceofObjects(currObject, knownObjects[i]);
-
-    if(temp_dist < max_diff) {
-      // Replace the existing neighbor having max_diff, by the current known object, in the K nearest neighbors array
-      kNearestObjects[max_index].type = knownObjects[i].type;
-      kNearestObjects[max_index].height = temp_height;
-      kNearestObjects[max_index].weight = temp_weight;
-      kNearestObjects[max_index].red = temp_red;
-      kNearestObjects[max_index].green = temp_green;
-      kNearestObjects[max_index].blue = temp_blue;
-    }
-  }
-
-  // For testing purposes
-  /*
-  for(int i = 0; i < K; ++i) {
-    Serial.println(kNearestObjects[i].type);
-    Serial.println(ComputeDistanceofObjects(currObject, kNearestObjects[i]));
-  }
-  */
-
-  int count = 0;
-  int max_count = 0;
-  String max_type;
-  // Find out which object type occurs the most
-  for(int i = 0; i < NUM_OF_OBJECT_TYPES; ++i) {
-    count = 0;
-    for(int j = 0; j < K; ++j) {
-      if(kNearestObjects[j].type == Known_Object_Types[i]) {
-        count++;
-      }
-    }
-    if(count > max_count) {
-      max_count = count;
-      max_type = Known_Object_Types[i];
-    }
-  }
-
-  return max_type;
-}
-
-// Prints the type of object that is being passed through the project
-// **
-void Actuation(String object) {
-  if(object != "") {
-    Serial.print("\t");
-    Serial.println(object);
-  }
-}
-
-void setup() {
-  Serial.begin(9600);
-
-  // Weight sensor, found with calibration sketch
-  scale.set_scale(calibration_factor);
-  //Resets scale to 0
-  scale.tare();
-}
-
-void loop() {
-  // Turns both LEDs off before each reading
-
-  // Should put feature extraction and pattern recognition in one multi-second for loop to
-    //give the box time to go through the sensors.
-
-  // {Type, height (cm.), weight (lbs.)}
-  // Small is red, Medium is green, Large is blue
-  Object knownObjects[NUM_OF_KNOWN_OBJECTS] = { {"Small", 11, 1.2, 230, 54, 27},
-                                                {"Small", 15, 0.8, 205, 43, 18},
-                                                {"Small", 12, 1.6, 253, 40, 7},
-                                                {"Medium", 27, 2.5, 5, 253, 7},
-                                                {"Medium", 29, 3.2, 16, 196, 16},
-                                                {"Medium", 30, 4.1, 45, 246, 45},
-                                                {"Large", 40, 4.6, 30, 18, 191},
-                                                {"Large", 42, 4.2, 66, 53, 235},
-                                                {"Large", 42, 5.3, 17, 9, 134}};
-
-  Object testObjects[NUM_OF_KNOWN_OBJECTS] = {  {"", 11, 1.2, 230, 54, 27},
-                                                {"", 15, 0.8, 205, 43, 18},
-                                                {"", 12, 1.6, 253, 40, 7},
-                                                {"", 27, 2.5, 5, 253, 7},
-                                                {"", 29, 3.2, 16, 196, 16},
-                                                {"", 30, 4.1, 45, 246, 45},
-                                                {"", 40, 4.6, 30, 18, 191},
-                                                {"", 42, 4.2, 66, 53, 235},
-                                                {"", 42, 5.3, 17, 9, 134}};
-
-  Object currObject;
-  String closestObject;
-
-  // Removed for testing purposes
-  //ObjectFeatureExtraction(currObject);
-  Serial.print("Test: ");
-  Serial.println(test);
-  currObject = testObjects[test];
-  if(test == 9) {
-    test = 0;
-  }
-  else {
-    ++test;
-  }
-
-  StandardizeObject(currObject, knownObjects);
-  /*
-  Serial.println(currObject.type);
-  Serial.println(currObject.height);
-  Serial.println(currObject.weight);
-  Serial.println(currObject.red);
-  Serial.println(currObject.green);
-  Serial.println(currObject.blue);
-
-  for(int i = 0; i < NUM_OF_KNOWN_OBJECTS; ++i) {
-    Serial.println(knownObjects[i].type);
-    Serial.println(knownObjects[i].height);
-    Serial.println(knownObjects[i].weight);
-    Serial.println(knownObjects[i].red);
-    Serial.println(knownObjects[i].green);
-    Serial.println(knownObjects[i].blue);
-  }
-  */
-  closestObject = PatternRecognition(currObject, knownObjects);
-
-  Actuation(closestObject);
-
-  delay(1000);
-}


Implemented raw sleep mode

Implemented raw sleep mode

--- arduino/smartbuoy/smartbuoy.ino
+++ arduino/smartbuoy/smartbuoy.ino
@@ -35,7 +35,9 @@
 TinyGPSPlus gps;
 SoftwareSerial softwareSerial(7, 8);

+//Misc
 #include <MemoryFree.h>
+#include <LowPower.h>

 //Compass
 #define compassAddr 0x0D
@@ -93,15 +95,18 @@

   //Serial.print("freeMemory()=");
   //Serial.println(freeMemory());
-
+  pinMode(9, INPUT);
 }
 bool saveDataToSD = true;
-bool doInterval = false;
+bool doInterval = true;
+bool doSleepInterval = false;

 unsigned long lastTime = 0;
+unsigned long sleepingTime = 0;

 void loop() {
   // put your main code here, to run repeatedly:
+  doSleepInterval = digitalRead(9);
   if(Serial.available() > 0){
     char input = Serial.read();
     bufferString+=input;
@@ -110,9 +115,12 @@
       bufferString="";
     }
   }
-  if(doInterval && millis() - 20000 > lastTime){
+  if(doInterval && millis() - 20000 > lastTime && millis() > 20000){
     lastTime = millis();
     doMeasurements();
+    if(doSleepInterval==true){
+      sleepingTime = millis() + 5000;
+    }
   }
   //Light
   digitalWrite(LIGHT_PIN, analogRead(PHOTO_PIN)<LIGHT_TRESHHOLD);
@@ -122,6 +130,10 @@
     char c = softwareSerial.read();
     //Serial.print(c);
     gps.encode(c);
+  }
+  if(sleepingTime>0 && sleepingTime<millis()){
+    sleepingTime=0;
+    goToSleep();
   }
 }

@@ -138,6 +150,8 @@
     Serial.println(doInterval);
   }else if(bufferString=="logSD\r"){
     printSD();
+  }else if(bufferString=="sleep\r"){
+    goToSleep();
   }
 }

@@ -203,6 +217,8 @@
   result += String(gps.location.lat(), 6);
   result += ";";
   result += String(gps.location.lng(), 6);
+  result += ";";
+  result += String(gps.satellites.value());
   result += ";";
   if(saveDataToSD){
     saveValueToSD(result, false);
@@ -278,7 +294,7 @@
     Serial.println(F("BUOY-ID=001"));
     Serial.print(F("SIZE="));
     Serial.println(csvFile.size());
-    Serial.println(F("DATE;TIME;HUMIDITY;AIR-TEMPERATURE;WATER-TEMPERATURE;LAT;LONG;HEADING;"));
+    Serial.println(F("DATE;TIME;HUMIDITY;AIR-TEMPERATURE;WATER-TEMPERATURE;LAT;LONG;SATELLITES;HEADING;"));
     Serial.println(F("--BODY--"));
     while(csvFile.available()){
       Serial.write(csvFile.read());
@@ -290,3 +306,15 @@
   }
 }

+void goToSleep(){
+  softwareSerial.end();
+  Serial.println(F("Going to sleep mode..."));
+  delay(40);
+  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);//   8Sec
+  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);// + 8Sec
+  LowPower.powerDown(SLEEP_4S, ADC_OFF, BOD_OFF);// + 4Sec
+                                                 // = 20Sec
+  Serial.println(F("Woke up!"));
+  softwareSerial.begin(9600);
+}
+


bugfix

bugfix

--- controller/controller.ino
+++ controller/controller.ino
@@ -52,7 +52,7 @@
     initBH1750();
   #endif

-  #ifdef USE_SHumidity
+  #ifdef USE_SHUMIDITY
     #ifdef DEBUG
       Serial.println("Using SHumidity");
     #endif
@@ -199,4 +199,4 @@
     delay(SnoozingTimeMS);
   #endif
   delay(ADDRESS * 100);
-}
+}


Updated comments and improved ease of use for users

--- Embedded-Arduino/Testing/SystemID/Single_Wheel_System_ID/Single_Wheel_System_ID.ino
+++ Embedded-Arduino/Testing/SystemID/Single_Wheel_System_ID/Single_Wheel_System_ID.ino
@@ -2,6 +2,45 @@
 #include <Wire.h>
 #include <digitalWriteFast.h>
 #include <math.h>
+
+/*
+This sketch can be used to collect data to be used in the system ID of a wheel motor. Essentially
+it sends a series of random voltage commands to the wheel motor for random durations and then
+periodically measures the average angular velocity of the wheels over a period.
+
+Modify the parameters as desired below, upload the sketch, and place the robot on a clear space on
+the ground. Establish a terminal connection with the communication port of the XBEE and switch
+on the robot. The robot will turn in place (or more accurately, turn about one of its wheels)
+for a period of time. When the test is complete, the onboard XBEE will transmit the results.
+Note that all time measurements are in milliseconds and the transmitted velocity measurements
+are in encoder ticks per velocity interval, where the velocity interval is user-defined. One
+can easily convert this to radians per second using:
+
+  w = 1000 * 2 * PI * MEASURED_TICKS / TOTAL_TICKS
+
+where TOTAL_TICKS is the number of ticks per revolution, which is approximately 3000.
+
+Author: Ryan J. Marcotte
+Date: 15 March 2014
+*/
+
+//#####SYSTEM ID PARAMETERS#######
+//#####MODIFY THESE FIELDS########
+#define TEST_PIN FORWARD_LEFT //the pin of the motor you are working with (options: FORWARD_RIGHT,
+                                  //FORWARD_LEFT, REVERSE_RIGHT, REVERSE_LEFT)
+const int TOTAL_VOL_COMS = 20; //the total number of voltage commands to be executed by the robot
+                               //if this is set too high, memory can become an issue
+                               //if the board runs out of memory, it resets itself which can be
+                               //a challenging bug to diagnose
+const int MIN_COM_DUR = 5; //the minimum duration a command could be executed for
+const int MAX_COM_DUR = 2000; //the maximum duration a command could be executed for
+const int COM_DUR_RESOLUTION = 5; //command durations can take on values as multiples of
+                                          //this parameter; 5 ms recommended
+const int VELOCITY_INTERVAL = 20; //length of interval (in ms) velocity measurements are taken over
+                                 //20 ms is probably optimal for most situations
+
+//##########END PARAMETERS###########
+//###NO MODIFICATIONS NEEDED BELOW###

 //######ENCODERS######
 //Left Encoder
@@ -24,39 +63,54 @@

 //######MOTORS#########
 //Left Motor
-const int reverseLeftMotorPin = 11;
-const int forwardLeftMotorPin = 10;
+const int REVERSE_LEFT = 11;
+const int FORWARD_LEFT = 10;

 //Right Motor
-const int reverseRightMotorPin = 9;
-const int forwardRightMotorPin = 8;
-
-//######SYSTEM ID#######
-//Modify these fields
-const int totalVolComs = 20; //the total number of voltage commands to be executed by the robot
-const int testPin1 = forwardLeftMotorPin;
-const int testPin2 = forwardRightMotorPin;
-
-int volComs[totalVolComs]; //the voltage commands to be executed by robot
-int volComsIndex = 0; //keeps track of which voltage command the robot is current executing
-unsigned long volComTimes[totalVolComs]; //the lengths of time each voltage command is executed
-
-const int totalTime = 20000; //the total amount of time the robot should measure angular velocity of the wheels
-const int velsSize = totalTime / 20;
-int vels[velsSize]; //the velocities of the wheels, measured every 20 ms
-int velsIndex = 0; //keeps track of which measurement is currently being executed
-int velsTimes[velsSize];
-int velsCommandIndex[velsSize];
-
-unsigned long currentTime;
-unsigned long lastMeasureTime;
-unsigned long lastCommandTime;
-boolean commandNow = false;
-boolean measureNow = false;
-
+const int REVERSE_RIGHT = 9;
+const int FORWARD_RIGHT = 8;
+
+/*
+ * Drives the execution of the system ID routine. Initializes the pins to be used. Generates
+ * the arrays of voltage commands (magnitude & duration). Determines the total runtime based
+ * on the generated command durations. Performs the system ID test. Outputs a summary of the
+ * parameters of the test as well as the velocity results.
+ */
 void setup(){
   Serial.begin(9600);
-
+  long runtime;
+  int velsSize;
+
+  initializePins();
+
+  Prev_RightEncoderTicks = _RightEncoderTicks;
+  Prev_LeftEncoderTicks = _LeftEncoderTicks;
+
+  int volComs[TOTAL_VOL_COMS];
+  unsigned long volComTimes[TOTAL_VOL_COMS];
+  generateCommandArrays(volComs, volComTimes);
+
+  runtime = determineRuntime(volComTimes);
+  velsSize = runtime / VELOCITY_INTERVAL;
+  int vels[velsSize];
+  int velsTimes[velsSize];
+  int velsCommandIndexes[velsSize];
+
+  performTest(runtime, velsSize, vels, velsTimes, velsCommandIndexes, volComs, volComTimes);
+  outputSummary(runtime, volComs, volComTimes);
+  outputResults(velsSize, vels, velsTimes, velsCommandIndexes);
+}
+
+/*
+ * Intentionally left empty. Robot simply idles upon completion of setup routine.
+ */
+void loop(){
+}
+
+/*
+ * Sets up encoder pins and attaches interrupts. Sets all motor pins to output mode.
+ */
+void initializePins(){
   //Left Encoder
   pinMode(c_LeftEncoderPinA, INPUT);     //sets pin A as input
   digitalWrite(c_LeftEncoderPinA, LOW);  //turns on pullup resistors
@@ -71,88 +125,188 @@
   digitalWrite(c_RightEncoderPinB, LOW); //turns on pullupresistors
   attachInterrupt(c_RightEncoderInterrupt, HandleRightMotorInterruptA, RISING);

-  Prev_RightEncoderTicks = _RightEncoderTicks;
-  Prev_LeftEncoderTicks = _LeftEncoderTicks;
-
   //Motors
-  pinMode(reverseLeftMotorPin, OUTPUT);
-  pinMode(forwardLeftMotorPin, OUTPUT);
-  pinMode(reverseRightMotorPin, OUTPUT);
-  pinMode(forwardRightMotorPin, OUTPUT);
-
-  generateCommandArrays();
-
-  outputResults();
-
-  performTest();
-}
-
-void loop(){
-}
-
-void generateCommandArrays(){
-  randomSeed(analogRead(0));
-
-  for(int i = 0; i < totalVolComs; i++){
+  pinMode(FORWARD_RIGHT, OUTPUT);
+  pinMode(FORWARD_LEFT, OUTPUT);
+  pinMode(REVERSE_RIGHT, OUTPUT);
+  pinMode(REVERSE_LEFT, OUTPUT);
+}
+
+/*
+ * Randomly generates the lists of command magnitudes and durations based
+ * on the user's desired parameters of the minimum and maximum command times
+ * as well as the command time resolution. If identical command lists are
+ * desired repeatedly for test purposes, comment out the fist line that seeds
+ * the random number generator.
+ */
+void generateCommandArrays(int volComs[], unsigned long volComTimes[]){
+  //randomSeed(analogRead(0));
+  unsigned long min;
+  unsigned long max;
+
+  for(int i = 0; i < TOTAL_VOL_COMS; i++){
     volComs[i] = random(256);
-    volComTimes[i] = 5*random(1,400);
+    min = COM_DUR_RESOLUTION * MIN_COM_DUR;
+    max = COM_DUR_RESOLUTION * MAX_COM_DUR;
+    volComTimes[i] = COM_DUR_RESOLUTION * random(min, max);
   }
 }

-void performTest(){
-  const unsigned long baseTime = millis();
-  currentTime = baseTime;
-  analogWrite(reverseLeftMotorPin, volComs[volComsIndex]);
-  lastCommandTime = currentTime;
-  lastMeasureTime = currentTime;
-
-  while(currentTime - baseTime < totalTime){
+/*
+ * Determines the total runtime of the test, calculated as the sum of
+ * the voltage command durations.
+ */
+long determineRuntime(unsigned long volComTimes[]){
+  unsigned long runtime = 0;
+
+  for(int i = 0; i < TOTAL_VOL_COMS; i++) {
+    runtime += volComTimes[i];
+  }
+
+  runtime += (VELOCITY_INTERVAL - runtime % VELOCITY_INTERVAL);
+
+  return runtime;
+}
+
+/*
+ * Measures repeated step responses on the motor being tested. Each time the main loop iterates, the
+ * function checks to see if the current time dictates that a measurement should be taken or a new
+ * command should be executed.
+ *
+ * Note: An unresolved issue remains with utilizing the millis timing. This code is written under the
+ * assumption that the main while loop iterates many times each millisecond. Microsecond timing tests
+ * showed that it executed in approximately 50-100 us, which supports this assumption. However, repeated
+ * tests of the code also showed that the while loop appears to "skip over" certain millisecond times.
+ * For example, if voltage command or velocity measurement is supposed to be sent or taken at a time
+ * 80 ms after the base time, the loop skips over that time and does not take the appropriate action.
+ * As a result, a command or measurement may be delayed by up to a millisecond. This is reported in the
+ * final results that are output to the user, so it is not terribly significant. However, this is an
+ * issue to be explored.
+ */
+void performTest(const unsigned long RUNTIME, const int VELS_SIZE, int vels[], int velsTimes[],
+                   int velsCommandIndexes[], const int VOL_COMS[], const unsigned long VOL_COM_TIMES[]){
+  int velsIndex = 0;
+  int volComsIndex = 0;
+  boolean commandNow = false;
+  boolean measureNow = false;
+
+  const unsigned long BASE_TIME = millis();
+  unsigned long currentTime = BASE_TIME;
+  unsigned long lastCommandTime = currentTime;
+  unsigned long  lastMeasureTime = currentTime;
+
+  analogWrite(TEST_PIN, VOL_COMS[volComsIndex]);
+
+  while(currentTime - BASE_TIME < RUNTIME){
     currentTime = millis();
-    commandNow = (currentTime - lastCommandTime >= volComTimes[volComsIndex] && lastCommandTime != currentTime) ? true : false;
-    measureNow = (currentTime - lastMeasureTime >= 20 && lastMeasureTime != currentTime) ? true : false;
+    commandNow = (currentTime - lastCommandTime >= VOL_COM_TIMES[volComsIndex] && lastCommandTime != currentTime) ? true : false;
+    measureNow = (currentTime - lastMeasureTime >= VELOCITY_INTERVAL && lastMeasureTime != currentTime) ? true : false;

     if(commandNow || measureNow){
       if(commandNow){
-        analogWrite(reverseLeftMotorPin, volComs[++volComsIndex]);
+        analogWrite(TEST_PIN, VOL_COMS[++volComsIndex]);
         lastCommandTime = currentTime;
       }

       if(measureNow){
-        vels[velsIndex] = _LeftEncoderTicks - Prev_LeftEncoderTicks;
+        if(TEST_PIN == FORWARD_RIGHT || TEST_PIN == REVERSE_RIGHT) {
+          vels[velsIndex] = _RightEncoderTicks - Prev_RightEncoderTicks;
+          Prev_RightEncoderTicks = _RightEncoderTicks;
+        } else {
+          vels[velsIndex] = _LeftEncoderTicks - Prev_LeftEncoderTicks;
+          Prev_LeftEncoderTicks = _LeftEncoderTicks;
+        }
+
         lastMeasureTime = currentTime;
-        Prev_LeftEncoderTicks = _LeftEncoderTicks;
-        velsTimes[velsIndex] = currentTime - baseTime;
-        velsCommandIndex[velsIndex++] = volComsIndex;
+        velsTimes[velsIndex] = currentTime - BASE_TIME;
+        velsCommandIndexes[velsIndex++] = volComsIndex;
       }
     }
   }

-  digitalWrite(reverseLeftMotorPin, LOW);
-}
-
-void outputResults(){
-  for(int i = 0; i < totalVolComs; i++){
-    Serial.print(volComs[i]);
+  digitalWrite(TEST_PIN, LOW);
+}
+
+/*
+ * Outputs a summary of the test, including the user-selected parameters and the generated list
+ * of voltage command magnitudes and durations.
+ */
+void outputSummary(const long RUNTIME, const int VOL_COMS[], const unsigned long VOL_COM_TIMES[]){
+  Serial.println("System ID Summary");
+  delay(20);
+  Serial.print("Motor tested: ");
+  delay(20);
+  Serial.println(getPinName());
+  delay(20);
+  Serial.print("Total commands executed: ");
+  delay(20);
+  Serial.println(TOTAL_VOL_COMS);
+  delay(20);
+  Serial.print("Total run time: ");
+  delay(20);
+  Serial.println(RUNTIME);
+  delay(20);
+  Serial.print("Velocity interval: ");
+  delay(20);
+  Serial.println(VELOCITY_INTERVAL);
+  delay(20);
+  Serial.println("\n\nVoltage Commands");
+  delay(20);
+  Serial.println("Magnitude   Duration");
+  delay(20);
+
+  for(int i = 0; i < TOTAL_VOL_COMS; i++){
+    Serial.print(VOL_COMS[i]);
+    delay(5);
+    Serial.print("   ");
+    delay(5);
+    Serial.println(VOL_COM_TIMES[i]);
+    delay(5);
+  }
+
+  Serial.println("End Summary");
+}
+
+/*
+ * Returns the name of the pin being tested as a string.
+ */
+String getPinName() {
+  switch(TEST_PIN) {
+    case FORWARD_RIGHT:
+      return "Forward Right";
+    case FORWARD_LEFT:
+      return "Forward Left";
+    case REVERSE_RIGHT:
+      return "Reverse Right";
+    case REVERSE_LEFT:
+      return "Reverse Left";
+  }
+}
+
+/*
+ * Outputs the results of the measurements, including the time of the measurements and the index of the voltage
+ * command being executed during that measurement.
+ */
+void outputResults(const int VELS_SIZE, const int VELS[], const int VELS_TIMES[], const int VELS_COMMAND_INDEXES[]){
+  Serial.println("\n\nVelocity Measurements");
+  delay(20);
+  Serial.print("Elapsed Time   ");
+  delay(20);
+  Serial.print("Command Index   ");
+  delay(20);
+  Serial.print("Measurement");
+  delay(20);
+
+  for(int i = 0; i < VELS_SIZE; i++){
+    Serial.print(VELS_TIMES[i]);
     delay(5);
     Serial.print(" ");
     delay(5);
-    Serial.println(volComTimes[i]);
-    delay(5);
-  }
-
-  Serial.println("End Commands\n\nStart Measurements");
-  delay(20);
-
-  for(int i = 0; i < velsSize; i++){
-    Serial.print(velsTimes[i]);
+    Serial.print(VELS_COMMAND_INDEXES[i]);
     delay(5);
     Serial.print(" ");
     delay(5);
-    Serial.print(velsCommandIndex[i]);
-    delay(5);
-    Serial.print(" ");
-    delay(5);
-    Serial.println(vels[i]);
+    Serial.println(VELS[i]);
     delay(5);
   }


Fix example fs api usage

Fix example fs api usage

--- libraries/ESP8266WebServer/examples/FSBrowser/FSBrowser.ino
+++ libraries/ESP8266WebServer/examples/FSBrowser/FSBrowser.ino
@@ -168,8 +168,8 @@
   {
     Dir dir = SPIFFS.openDir("/");
     while (dir.next()) {
-      String fileName = dir.fileName();
-      size_t fileSize = dir.fileSize();
+      String fileName = dir.entryName();
+      size_t fileSize = dir.entrySize();
       DBG_OUTPUT_PORT.printf("FS File: %s, size: %s\n", fileName.c_str(), formatBytes(fileSize).c_str());
     }
     DBG_OUTPUT_PORT.printf("\n");


ip address is shown after start

ip address is shown after start

--- esp8266_NeoPixelLightStick.ino
+++ esp8266_NeoPixelLightStick.ino
@@ -68,6 +68,8 @@
 #define STAT_ENDED 2
 #define STAT_DELAY 3

+#define BUTTONPIN 0
+

 int height;
 int width;
@@ -116,6 +118,27 @@
   tcp.begin();

   NeoPixelLightStick.black(NeoPixelLightStick._maxPixelCount);
+  delay(500);
+
+  for (int i = 0; i < 4; i++) {
+    byte octet = WiFi.localIP()[i];
+    Serial.println(octet);
+    if (octet / 100 > 0) {
+      NeoPixelLightStick.setColor(i * 9, 255, 0, 0);
+    } else {
+      NeoPixelLightStick.setColor(i * 9, 255 / 127, 0, 0);
+    }
+    octet = octet % 100;
+    showDigit(0, 255, 0, octet / 10, i * 9 + 1);
+    octet = octet % 10;
+    showDigit(0, 0, 255, octet, i * 9 + 5);
+  }
+  NeoPixelLightStick.setColor(4 * 9 + 1, 255/ 6, 0, 0);
+  NeoPixelLightStick.setColor(4 * 9 + 2, 0, 255/ 6, 0);
+  NeoPixelLightStick.setColor(4 * 9 + 3, 0, 0, 255/ 6);
+  NeoPixelLightStick.show();
+
+  pinMode(BUTTONPIN, INPUT_PULLUP);

   Serial.println(F("initialized"));
 }
@@ -134,6 +157,10 @@
       mode = MODE_TCP;
       break;
   }
+  if (!digitalRead(BUTTONPIN)) {
+    NeoPixelLightStick.black(NeoPixelLightStick._maxPixelCount);
+    delay(500);
+  }
 }

@@ -141,6 +168,34 @@
   NeoPixelLightStick.setColor(value % maxValue, r, g, b);
   NeoPixelLightStick.setColor((value + maxValue - 1) % maxValue, 0x00, 0x00, 0x00);
   NeoPixelLightStick.show();
+}
+
+
+void showDigit(byte r, byte g, byte b, int value, int pos) {
+  byte hr, hg, hb, lr, lg, lb;
+  if (value <= 5) {
+    hr = r / 6;
+    hg = g / 6;
+    hb = b / 6;
+    lr = r / 127;
+    lg = g / 127;
+    lb = b / 127;
+  } else {
+    hr = r;
+    hg = g;
+    hb = b;
+    lr = r / 6;
+    lg = g / 6;
+    lb = b / 6;
+    value = value - 5;
+  }
+  for (int i = 0; i < 4; i++) {
+    if (i < value) {
+      NeoPixelLightStick.setColor(pos + i, hr, hg, hb);
+    } else {
+      NeoPixelLightStick.setColor(pos + i, lr, lg, lb);
+    }
+  }
 }


Fixup the FastLED single string example.

--- examples/fastled_candle/fastled_candle.ino
+++ examples/fastled_candle/fastled_candle.ino
@@ -16,7 +16,10 @@

 // Define the array of leds
 CRGB leds[NUM_LEDS];
-candle::Candle *candles[NUM_LEDS], *saturation[NUM_LEDS];
+
+candle::Candle candles[NUM_LEDS];
+candle::Candle saturation[NUM_LEDS];
+
 byte hues[NUM_LEDS];

 #define CANDLE_TICK_TIME 20
@@ -47,11 +50,12 @@
         leds[i] = CRGB::Black;

         // Initialize candles
-        candles[i] = new Candle(random8(16, 96), 255, random8(3, 8), random8(6, 22));
+        candles[i].init(random8(16, 96), 255, random8(3, 8), random8(6, 22));

         // Initialize random hues and saturation
         hues[i] = random8(24, 32);
-        saturation[i] = new Candle(random8(112, 240), random8(241, 255), random8(10, 20), random8(22, 62));
+        saturation[i].init(random8(112, 240), random8(241, 255), random8(10, 20), random8(22, 62));
+
     }

     FastLED.show();
@@ -68,7 +72,7 @@
 void candleLoop() {
     if (candle_timer.check() == 1) {
         for (size_t i=0; i<NUM_LEDS; i++) {
-            leds[i] = CHSV(hues[i], saturation[i]->get_next_brightness(), candles[i]->get_next_brightness());
+            leds[i] = CHSV(hues[i], saturation[i].get_next_brightness(), candles[i].get_next_brightness());
         }

         FastLED.show();


defect #44

defect #44

https://github.com/tschaban/AFE-Firmware/issues/44

--- src/AFE-MQTT-listener.ino
+++ src/AFE-MQTT-listener.ino
@@ -16,14 +16,14 @@

   char _mqttTopic[50];
   Led.on();
-  //  Serial << endl << "INFO: MQTT message recieved: " << topic << " \\ ";
+  // Serial << endl << "INFO: MQTT message recieved: " << topic << " \\ ";

   if (length >= 1) { // command arrived
-                     /*
-                         for (uint8_t i = 0; i < length; i++) {
-                           Serial << (char)payload[i];
-                         }
-                     */
+
+    for (uint8_t i = 0; i < length; i++) {
+      Serial << (char)payload[i];
+    }
+
     sprintf(_mqttTopic, "%scmd", Relay.getMQTTTopic());
     /*
         Serial << endl
@@ -33,13 +33,13 @@
     if (String(topic) == String(_mqttTopic)) {
       if ((char)payload[1] == 'N') {
         Relay.on();
-        Mqtt.publish("state", "ON");
+        Mqtt.publish(Relay.getMQTTTopic(), "state", "ON");
       } else if ((char)payload[1] == 'F') {
         Relay.off();
-        Mqtt.publish("state", "OFF");
+        Mqtt.publish(Relay.getMQTTTopic(), "state", "OFF");
       } else if ((char)payload[2] == 'p') { // reportState
-        Relay.get() ? Mqtt.publish("state", "ON")
-                    : Mqtt.publish("state", "OFF");
+        Mqtt.publish(Relay.getMQTTTopic(), "state",
+                     Relay.get() == RELAY_ON ? "ON" : "OFF");
       }
     }


Add validation of node id

Add validation of node id

--- arduino/rflink/rflink.ino
+++ arduino/rflink/rflink.ino
@@ -38,6 +38,8 @@
     uint8_t slot_size;
 } beacon_t;

+// whether radio initialisation was successful
+static boolean radio_ok = false;
 // our node id
 static uint8_t node_id;
 // the current time offset between our clock and the master (milliseconds)
@@ -77,6 +79,11 @@
     }
 }

+static bool node_valid(uint8_t id)
+{
+    return (id < NUM_SLOTS);
+}
+
 static void fill_buffer(uint8_t to, uint8_t flags, uint8_t len, uint8_t *data)
 {
     // select our own node buffer as send buffer
@@ -94,11 +101,15 @@

 static int do_id(int argc, char *argv[])
 {
-    uint8_t node_id = id_read();
-    if (argc >= 2) {
-        node_id = atoi(argv[1]);
-        id_write(node_id);
-        radio_init(node_id);
+    uint8_t node = id_read();
+    if (argc == 2) {
+        node = atoi(argv[1]);
+        if (!node_valid(node)) {
+            return ERR_PARAM;
+        }
+        id_write(node);
+        radio_init(node);
+        node_id = node;
     }
     print("00 %02X\n", node_id);
     return 0;
@@ -109,6 +120,9 @@
     uint8_t node = 0xFF;
     if (argc > 1) {
         node = atoi(argv[1]);
+    }
+    if (!node_valid(node)) {
+        return ERR_PARAM;
     }

     // prepare ping message
@@ -151,6 +165,9 @@
         return ERR_PARAM;
     }
     uint8_t node = atoi(argv[1]);
+    if (!node_valid(node)) {
+        return ERR_PARAM;
+    }
     uint8_t type = atoi(argv[2]);
     uint8_t buf[64];
     int len = decode_hex(argv[3], buf, sizeof(buf));
@@ -177,6 +194,9 @@
         return ERR_PARAM;
     }
     uint8_t node = atoi(argv[1]);
+    if (!node_valid(node)) {
+        return ERR_PARAM;
+    }
     buffer_t *buf = &buffers[node];
     if (buf->len == 0) {
         // nothing to read
@@ -258,8 +278,8 @@
     // SPI init
     spi_init(1000000L, 0);

-    bool ok = radio_init(node_id);
-    print("#RFLINK,id=%d,init=%s\n", node_id, ok ? "OK" : "FAIL");
+    radio_ok = radio_init(node_id);
+    print("#RFLINK,id=%d,init=%s\n", node_id, radio_ok ? "OK" : "FAIL");
 }

 void loop(void)
@@ -281,6 +301,11 @@
                 print("%02X\n", res);
             }
         }
+    }
+
+    // verify conditions for doing any radio processing
+    if (!radio_ok || !node_valid(node_id)) {
+        return;
     }

     // radio processing
@@ -352,13 +377,15 @@

         default:
             // copy data into buffer and indicate reception
-            buffer_t *buf = &buffers[node];  // TODO BSI check node in range
-            if (buf->len == 0) {
-                // only indicate when buffer status changes (empty->full)
-                print("!r %02X\n", node);
+            if (node_valid(node)) {
+                buffer_t *buf = &buffers[node];
+                if (buf->len == 0) {
+                    // only indicate when buffer status changes (empty->full)
+                    print("!r %02X\n", node);
+                }
+                memcpy(&buf->data, rcv, len);
+                buf->len = len;
             }
-            memcpy(&buf->data, rcv, len);
-            buf->len = len;
             break;
         }
     }


fix toInt conversion

fix toInt conversion

--- arduino/scetch/scetch.ino
+++ arduino/scetch/scetch.ino
@@ -57,8 +57,7 @@
     String message = buffer;
     if (message.charAt(0) == powerKey && laserEnabled == true) {
       String powerLvlString = String(message);
-      powerLvlString.remove(0);
-      long lvl = powerLvlString.toInt();
+      long lvl = powerLvlString.substring(1, len).toInt();
       if (lvl >= 0 && lvl <= 100) {
         submitPower((byte) lvl);
       } else {


update to use current libraries; fix tmp275 error messaging;

--- examples/Mux_and_Temps/Mux_and_Temps.ino
+++ examples/Mux_and_Temps/Mux_and_Temps.ino
@@ -43,15 +43,16 @@
 uint8_t config_tmp275;

-Systronix_PCA9548A PCA9548A_70(PCA9548A_SLAVE_ADDR_0);
-
-Systronix_TMP275 Mux0Temp1(TMP275_SLAVE_ADDR_1);
-Systronix_TMP275 Mux1Temp1(TMP275_SLAVE_ADDR_1);
-Systronix_TMP275 Mux2Temp1(TMP275_SLAVE_ADDR_1);
+Systronix_PCA9548A PCA9548A_70;
+
+Systronix_TMP275 Mux0Temp0;
+Systronix_TMP275 Mux1Temp0;
+Systronix_TMP275 Mux2Temp0;

 const char * text_ptr;

 uint32_t startuptime = 0;
+uint32_t iter = 0;

 /* ========== SETUP ========== */
 void setup(void)
@@ -90,8 +91,23 @@
 #endif

-  // start PCA9548A library
-  PCA9548A_70.begin();
+// start PCA9548A library
+	PCA9548A_70.setup (PCA9548A_SLAVE_ADDR_0, Wire1, (char*)"Wire1");
+	PCA9548A_70.begin (I2C_PINS_29_30, I2C_RATE_100);
+	PCA9548A_70.init ();
+
+// start TMP275 libraries
+	Mux0Temp0.setup(TMP275_SLAVE_ADDR_0, Wire1, (char*)"Wire1");
+	Mux0Temp0.begin (I2C_PINS_29_30, I2C_RATE_100);
+	Mux0Temp0.init (TMP275_CFG_RES12);
+
+	Mux1Temp0.setup(TMP275_SLAVE_ADDR_0, Wire1, (char*)"Wire1");
+	Mux1Temp0.begin (I2C_PINS_29_30, I2C_RATE_100);
+	Mux1Temp0.init (TMP275_CFG_RES12);
+
+	Mux2Temp0.setup(TMP275_SLAVE_ADDR_0, Wire1, (char*)"Wire1");
+	Mux2Temp0.begin (I2C_PINS_29_30, I2C_RATE_100);
+	Mux2Temp0.init (TMP275_CFG_RES12);

   config_value = PCA9548A_PORT_0_ENABLE;  //

@@ -103,8 +119,8 @@
     Serial.printf(" Attempt #%u: Init control reg to 0x%.2X - ", iter, config_value);
     if (SUCCESS != stat)
     {
-      text_ptr = (PCA9548A_70.status_text[PCA9548A_70.error.ret_val]);
-      Serial.printf("failed - returned 0x%.2X: %s\r\n", PCA9548A_70.error.ret_val, text_ptr);
+      text_ptr = (PCA9548A_70.status_text[PCA9548A_70.error.error_val]);
+      Serial.printf("failed - returned 0x%.2X: %s\r\n", PCA9548A_70.error.error_val, text_ptr);
 #if defined I2C_T3_H
     // reset I2C just to be safe
     // we may have interrupted a message in process of loading new code or Teensy reset
@@ -180,94 +196,94 @@
   if (verbose) Serial.printf("@%.4u  ", millis());

   // Enable Mux Channel 0
-  stat = PCA9548A_70.controlWrite(PCA9548A_PORT_0_ENABLE);
+  stat = PCA9548A_70.control_write(PCA9548A_PORT_0_ENABLE);
   if (SUCCESS != stat)
   {
-    text_ptr = (PCA9548A_70.status_text[PCA9548A_70.error.ret_val]);
-    Serial.printf("mux0 control write failed with return of 0x%.2X: %s\r\n", PCA9548A_70.error.ret_val, text_ptr);
-    text_ptr = (PCA9548A_70.status_text[PCA9548A_70.error.ret_val]);
+    text_ptr = (PCA9548A_70.status_text[PCA9548A_70.error.error_val]);
+    Serial.printf("mux0 control write failed with return of 0x%.2X: %s\r\n", PCA9548A_70.error.error_val, text_ptr);
+    text_ptr = (PCA9548A_70.status_text[PCA9548A_70.error.error_val]);
     delay(dtime/2); // don't blast repeat failures too quickly
   }
   else
   {
-    stat = PCA9548A_70.controlRead(&control_read_val);
+    stat = PCA9548A_70.control_read(&control_read_val);
     if (verbose) Serial.printf("OK control=0x%.2X\r\n", control_read_val);
   }

-  // Init Mux0Temp1 Sensors
-  stat = Mux0Temp1.init(TMP275_CFG_RES12);
-  if (SUCCESS != stat) Serial.printf(" Mux0Temp1 init failed with return of 0x%.2X: %s\r\n", Mux0Temp1.error.ret_val);
+  // Init Mux0Temp0 Sensors
+  stat = Mux0Temp0.init(TMP275_CFG_RES12);
+  if (SUCCESS != stat) Serial.printf(" Mux0Temp0 init failed with return of 0x%.2X: %s\r\n", Mux0Temp0.error.error_val, Mux0Temp0.status_text[Mux0Temp0.error.error_val]);

   // leave the pointer set to read temperature
-  stat = Mux0Temp1.pointerWrite(TMP275_TEMP_REG_PTR);
+  stat = Mux0Temp0.pointer_write(TMP275_TEMP_REG_PTR);

   // Read Temp on sensors Mux Channel 0
   rawtemp=0;
   temp=0.0;
-  stat = Mux0Temp1.register16Read (&rawtemp);
-  if (stat != SUCCESS) Serial.printf("Mux0Temp1 error, stat=%u\r\n", stat);
-  temp = Mux0Temp1.raw12_to_c(rawtemp);
-  Serial.printf ("Mux0Temp1 %6.4f C\r\n", temp);
+  stat = Mux0Temp0.register16_read (&rawtemp);
+  if (stat != SUCCESS) Serial.printf("Mux0Temp0 error, stat=%u\r\n", stat);
+  temp = Mux0Temp0.raw12_to_c(rawtemp);
+  Serial.printf ("Mux0Temp0 %6.4f C\r\n", temp);

   // Enable Mux Channel 1
-  stat = PCA9548A_70.controlWrite(PCA9548A_PORT_1_ENABLE);
+  stat = PCA9548A_70.control_write(PCA9548A_PORT_1_ENABLE);
   if (SUCCESS != stat)
   {
-    text_ptr = (PCA9548A_70.status_text[PCA9548A_70.error.ret_val]);
-    Serial.printf("mux1 control write failed with return of 0x%.2X: %s\r\n", PCA9548A_70.error.ret_val, text_ptr);
-    text_ptr = (PCA9548A_70.status_text[PCA9548A_70.error.ret_val]);
+    text_ptr = (PCA9548A_70.status_text[PCA9548A_70.error.error_val]);
+    Serial.printf("mux1 control write failed with return of 0x%.2X: %s\r\n", PCA9548A_70.error.error_val, text_ptr);
+    text_ptr = (PCA9548A_70.status_text[PCA9548A_70.error.error_val]);
     delay(dtime/2); // don't blast repeat failures too quickly
   }
   else
   {
-    stat = PCA9548A_70.controlRead(&control_read_val);
+    stat = PCA9548A_70.control_read(&control_read_val);
     if (verbose) Serial.printf("OK control=0x%.2X\r\n", control_read_val);
   }

-  // Init Mux1Temp1 Sensors
-  stat = Mux1Temp1.init(TMP275_CFG_RES12);
-  if (SUCCESS != stat) Serial.printf(" Mux1Temp1 init failed with return of 0x%.2X: %s\r\n", Mux0Temp1.error.ret_val);
+  // Init Mux1Temp0 Sensors
+  stat = Mux1Temp0.init(TMP275_CFG_RES12);
+  if (SUCCESS != stat) Serial.printf(" Mux1Temp0 init failed with return of 0x%.2X: %s\r\n", Mux1Temp0.error.error_val, Mux1Temp0.status_text[Mux1Temp0.error.error_val]);

   // leave the pointer set to read temperature
-  stat = Mux1Temp1.pointerWrite(TMP275_TEMP_REG_PTR);
+  stat = Mux1Temp0.pointer_write(TMP275_TEMP_REG_PTR);

   // Read Temp on sensors Mux Channel 1
   rawtemp=0;
   temp=0.0;
-  stat = Mux1Temp1.register16Read (&rawtemp);
-  if (stat != SUCCESS) Serial.printf("Mux1Temp1 error, stat=%u\r\n", stat);
-  temp = Mux1Temp1.raw12_to_c(rawtemp);
-  Serial.printf ("Mux1Temp1 %6.4f C\r\n", temp);
+  stat = Mux1Temp0.register16_read (&rawtemp);
+  if (stat != SUCCESS) Serial.printf("Mux1Temp0 error, stat=%u\r\n", stat);
+  temp = Mux1Temp0.raw12_to_c(rawtemp);
+  Serial.printf ("Mux1Temp0 %6.4f C\r\n", temp);

   // Enable Mux Channel 2
-  stat = PCA9548A_70.controlWrite(PCA9548A_PORT_2_ENABLE);
+  stat = PCA9548A_70.control_write(PCA9548A_PORT_2_ENABLE);
   if (SUCCESS != stat)
   {
-    text_ptr = (PCA9548A_70.status_text[PCA9548A_70.error.ret_val]);
-    Serial.printf("mux2 control write failed with return of 0x%.2X: %s\r\n", PCA9548A_70.error.ret_val, text_ptr);
-    text_ptr = (PCA9548A_70.status_text[PCA9548A_70.error.ret_val]);
+    text_ptr = (PCA9548A_70.status_text[PCA9548A_70.error.error_val]);
+    Serial.printf("mux2 control write failed with return of 0x%.2X: %s\r\n", PCA9548A_70.error.error_val, text_ptr);
+    text_ptr = (PCA9548A_70.status_text[PCA9548A_70.error.error_val]);
     delay(dtime/2); // don't blast repeat failures too quickly
   }
   else
   {
-    stat = PCA9548A_70.controlRead(&control_read_val);
+    stat = PCA9548A_70.control_read(&control_read_val);
     if (verbose) Serial.printf("OK control=0x%.2X\r\n", control_read_val);
   }

-  // Init Mux2Temp1 Sensors
-  stat = Mux2Temp1.init(TMP275_CFG_RES12);
-  if (SUCCESS != stat) Serial.printf(" Mux2Temp1 init failed with return of 0x%.2X: %s\r\n", Mux0Temp1.error.ret_val);
+  // Init Mux2Temp0 Sensors
+  stat = Mux2Temp0.init(TMP275_CFG_RES12);
+  if (SUCCESS != stat) Serial.printf(" Mux2Temp0 init failed with return of 0x%.2X: %s\r\n", Mux2Temp0.error.error_val, Mux2Temp0.status_text[Mux2Temp0.error.error_val]);

   // leave the pointer set to read temperature
-  stat = Mux2Temp1.pointerWrite(TMP275_TEMP_REG_PTR);
+  stat = Mux2Temp0.pointer_write(TMP275_TEMP_REG_PTR);

   // Read Temp on sensors Mux Channel 1
   rawtemp=0;
   temp=0.0;
-  stat = Mux2Temp1.register16Read (&rawtemp);
-  if (stat != SUCCESS) Serial.printf("Mux2Temp1 error, stat=%u\r\n", stat);
-  temp = Mux2Temp1.raw12_to_c(rawtemp);
-  Serial.printf ("Mux2Temp1 %6.4f C\r\n", temp);
+  stat = Mux2Temp0.register16_read (&rawtemp);
+  if (stat != SUCCESS) Serial.printf("Mux2Temp0 error, stat=%u\r\n", stat);
+  temp = Mux2Temp0.raw12_to_c(rawtemp);
+  Serial.printf ("Mux2Temp0 %6.4f C\r\n", temp);

   Serial.println();


Sets valid i2c slave address of Arduino

Sets valid i2c slave address of Arduino

--- booth_controller/booth_controller.ino
+++ booth_controller/booth_controller.ino
@@ -5,8 +5,8 @@
 */
 #include <LiquidCrystal.h>

-// after bit shifting will be converted to I2C slave address 8
-#define SLAVE_ADDRESS 0x02
+// after bit shifting will be converted to I2C slave address 16
+#define SLAVE_ADDRESS 0x04

 /*
 * temporary - initialize lcd object and set I2C simulating arming button


311Khz

--- mega6502.ino
+++ mega6502.ino
@@ -21,8 +21,7 @@
 byte ram[0x1000];
 byte pia[0x14];

-void printAddr(uint16_t addr, uint8_t col, uint8_t row) {
-
+void printAddr(const uint16_t addr, const uint8_t col, const uint8_t row) {
   lcd.setCursor(col, row);
   lcd.print((addr >> 12) & 0x0f, HEX);
   lcd.print((addr >> 8) & 0x0f, HEX);
@@ -31,8 +30,7 @@

 }

-void printByte(uint8_t val, uint8_t col, uint8_t row) {
-
+void printByte(const uint8_t val, const uint8_t col, const uint8_t row) {
   lcd.setCursor(col, row);
   //char buf[2];
   //sprintf(&buf, "%2x", val);
@@ -48,7 +46,10 @@
 extern byte ram[];
 extern byte pia[];

-uint8_t memRead(uint16_t addr) {
+#define ADDR ((addrh << 8) | addrl)
+
+uint8_t memRead(const uint8_t addrh, const uint8_t addrl) {
+  const uint16_t addr = ADDR;
   uint8_t val;
   switch (addr >> 12) {
     default:
@@ -84,17 +85,10 @@
       if (LCD) printAddr(addr, 8, 0);
       if (LCD) printByte(val, 14, 0);
       return val;
-    /*
-    case 0xf:
-      printAddr(addr, 8, 0);
-      val = rom[addr & 0xff];
-      printByte(val, 14, 0);
-      return val;
-    */
   }
 }

-void memWrite(uint16_t addr, uint8_t val) {
+void memWrite(const uint16_t addr, const uint8_t val) {
   switch (addr >> 12) {
     default:
       // nothing in the address space ignore the write;
@@ -174,12 +168,12 @@
     if (PINB & _BV(PB2)) {
       // read cycle
       DDRL = 0xff;
-      PORTL = memRead((addrh << 8) | addrl);
+      PORTL = memRead(addrh, addrl);
     } else {
       // write cycle
       DDRL = 0x00;
       PORTL = 0;
-      memWrite((addrh << 8) | addrl, PINL);
+      memWrite(ADDR, PINL);
     }
   }
 }