More tests

More tests

--- modbusiptest/modbusiptest.ino
+++ modbusiptest/modbusiptest.ino
@@ -9,13 +9,15 @@
 ModbusIP mb;

 #define COIL1    10
-#define COIL2    20
+#define COIL2    11
 #define LAMP     30
 #define TESTREG 100
+#define TESTREG2 101
 #define DISCINP 200
 #define INPREG  300

 const int ledPin = 9;
+

 long t1, t2;

@@ -32,17 +34,18 @@
     byte subnet[] = { 255, 255, 255, 0 };

     mb.config(mac, ip, dns, gateway, subnet);
-
     pinMode(ledPin, OUTPUT);

     mb.addCoil(COIL1);
     mb.addCoil(COIL2);
     mb.addCoil(LAMP);
     mb.addHreg(TESTREG);
+    mb.addHreg(TESTREG2);
     mb.addDimp(DISCINP);
     mb.addIreg(INPREG);

     mb.Hreg(TESTREG, 314);
+    mb.Hreg(TESTREG2, 159);
     mb.Dimp(DISCINP, true);
     mb.Ireg(INPREG, 0);
     mb.Coil(COIL1, false);


removing debug

removing debug

--- src/nest-rest.ino
+++ src/nest-rest.ino
@@ -13,32 +13,36 @@

 byte Ethernet::buffer[700];

-//const char skydome[] PROGMEM = "api.skydome.io";
-const char skydome[] PROGMEM = "192.168.2.120";
+const char skydome[] PROGMEM = "api.skydome.io";
+//const char skydome[] PROGMEM = "192.168.2.20";'

 void setup() {
   Serial.begin(9600);
-  if (manager.init())
-    Serial.println(F("init success"));
-  else
-    Serial.println(F("init failed"));
+  if (manager.init()){
+  //  Serial.println(F("init success"));
+  }
+  else {
+   // Serial.println(F("init failed"));
+  }
+
+  if (ether.begin(sizeof Ethernet::buffer, mymac, 10) == 0) {
+ //   Serial.println(F("Failed to access Ethernet controller"));
+}
+  if (!ether.dhcpSetup()){
+ //   Serial.println(F("DHCP failed"));
+}

-  if (ether.begin(sizeof Ethernet::buffer, mymac, 10) == 0)
-    Serial.println(F("Failed to access Ethernet controller"));
-  if (!ether.dhcpSetup())
-    Serial.println(F("DHCP failed"));
-
-  if (!ether.dnsLookup(skydome))
-    Serial.println(F("DNS failed"));
-
+  if (!ether.dnsLookup(skydome)){
+ //   Serial.println(F("DNS failed"));
+}
   ether.hisport = 8080;

-  Serial.println(F("setup() done"));
+//  Serial.println(F("setup() done"));
 }

 static void responseCallback (byte statusCode, word off, word len) {
   Ethernet::buffer[off + 300] = 0;
-  Serial.println((const char*) Ethernet::buffer + off);
+ // Serial.println((const char*) Ethernet::buffer + off);
 }

 const uint8_t charOffset PROGMEM = 48;
@@ -57,12 +61,15 @@

       Serial.print("got data[1]:");
       Serial.println(data[1]);
-      const char message[] PROGMEM = {'{','"', 'a', 'n', 't',            '"', ':', '"', (from + charOffset),   '"', ',',
-                                          '"', 't', 'y', 'p', 'e',       '"', ':', '"', (data[0] + charOffset), '"', ',',
-                                          '"', 'v', 'a', 'l', 'u', 'e',  '"', ':', '"', (data[1] + charOffset), '"', '}'
-                                     };
-
-      ether.httpPost(PSTR("/telemetry/plant/id/abcdefg"), skydome, PSTR("Authorization: Token asdaasd"), message, responseCallback);
+    char fromChar = from;
+    char data0 = data[0];
+    char data1 = data[1];
+       const char *message = '1323';
+    //  char message[] PROGMEM = {'{','"','a','"',':','"',from+charOffset,'"',',','"','t','"',':','"',data[0]+charOffset,'"',',',
+    //                                '"', 'v', '"',':','"',data[1]+charOffset,'"', '}'
+    //                           };
+
+      ether.httpPost(PSTR("/telemetry/plant/id/yaman"), skydome, PSTR("Authorization: Token asdaasd"), message, NULL);
     }
   }
 }


Reduced delay to 10ms

Reduced delay to 10ms

--- Musical_Instruments_2017_2018/Dance_Pads/Pad_B_Drums.ino
+++ Musical_Instruments_2017_2018/Dance_Pads/Pad_B_Drums.ino
@@ -113,6 +113,6 @@
     Keyboard.release('j');
   }

-  delay(100);
+  delay(10);

 }


Update from Tuesday

Update from Tuesday

--- src/sketch_jan20a/sketch_jan20a.ino
+++ src/sketch_jan20a/sketch_jan20a.ino
@@ -1,7 +1,8 @@
 int lastInterruptIndex = -1;
+int headIntIndex = -1;
 char InterruptLog[256] = {0};
 unsigned long TimeLog[256] = {0};
-
+bool ramOverflow = false;

 void setup()
 {
@@ -9,31 +10,49 @@
   Serial.println("i am 12 and wat is this");
   InitialiseIO();
   InitialiseInterrupt();
-  Serial.println("Jonathan is blind");
 }

 void loop() {
-  /* Nothing to do: the program jumps automatically to Interrupt Service Routine "blink"
-   in case of a hardware interrupt  */
-   int wut = 0;
-
-   delay(1000);
-   for( int i = 0; i < lastInterruptIndex; i++){
-    Serial.println(InterruptLog[i], HEX);
+   delay(500);
+   int kek = analogRead(A0);
+   Serial.println(kek);
+   Serial.println("oh shit");
+   if (ramOverflow){
+    Serial.println("Overflowed SRAM buffer!");
+    ramOverflow = false; //reset, this is not strictly unrecoverable.
    }
-
-   wut = analogRead(A0);
-   Serial.println(A0);
+   if (lastInterruptIndex < 0){
+    return; //restart the loop don't do unneccessary work
+   }
+   int A0 = 0;
+   int A1 = 0;
+   int A2 = 0;
+   for( int i = headIntIndex; i < lastInterruptIndex; i++){
+    char toTwiddle = InterruptLog[i];
+    char temp0 = toTwiddle & 0x1;
+    char temp1 = (toTwiddle & 0x2) >> 1;
+    char temp2 = (toTwiddle & 0x4) >> 2;
+    A0 += temp0;
+    A1 += temp1;
+    A2 += temp2;
+   }
+   unsigned long timeElapsed = (TimeLog[lastInterruptIndex] - TimeLog[0])/(10^6);
+   float avg0 = A0/timeElapsed;
+   float avg1 = A1/timeElapsed;
+   float avg2 = A2/timeElapsed;
+   Serial.println(avg0, 2);
+   Serial.println(avg1, 2);
+   Serial.println(avg2, 2);
+   return;
 }

 void InitialiseIO(){
-  /*pinMode(A0, INPUT);     // Pin A0 is input to which a switch is connected
+  pinMode(A0, INPUT);     // Pin A0 is input to which a switch is connected
   digitalWrite(A0, HIGH);   // Configure internal pull-up resistor
   pinMode(A1, INPUT);    // Pin A1 is input to which a switch is connected
   digitalWrite(A1, HIGH);   // Configure internal pull-up resistor
   pinMode(A2, INPUT);    // Pin A2 is input to which a switch is connected
   digitalWrite(A2, HIGH);      // Configure internal pull-up resistor
-  */
 }

 void InitialiseInterrupt(){
@@ -48,21 +67,25 @@
   volatile char store = 0x0;

   if (digitalRead(A0)==0){
-    store += 0x1;
+    store |= 0x1;
     Serial.println("A0");
   }

   if (digitalRead(A1)==0){
-    store += 0x2;;
+    store |= 0x2;;
     Serial.println("A1");
   }

   if (digitalRead(A2)==0) {
-    store += 0x4;
+    store |= 0x4;
     Serial.println("A2");
   }

   if (store > 0x0){
+    if (lastInterruptIndex >= 255){
+       lastInterruptIndex = -1; //if we are about to overflow buffer, overwrite oldest.
+       ramOverflow = true;
+    }
     lastInterruptIndex++;
     InterruptLog[lastInterruptIndex] = store;
     TimeLog[lastInterruptIndex] = micros();


Update Encoder.ino

Update Encoder.ino

--- Testbench/Encoder_TestBench/Software/Encoder/Encoder.ino
+++ Testbench/Encoder_TestBench/Software/Encoder/Encoder.ino
@@ -86,6 +86,11 @@
   }
   }
   angle = 0.015707*encoderCount/pi*90; //Unit is radian
+  //CPR = 100. Dependson encoder type
+  //100 * 4 = 400
+  //400/(2*pi) = counts/angle
+  //angle = counts*(2*pi/400)
+  //angle = 0.015707 * counts.
 }

 void doEncoderB(){    //Pin1 interrupt.


Fixes debounce issue with hi score table after new hi score.

--- arduboy-game/arduboy-game.ino
+++ arduboy-game/arduboy-game.ino
@@ -264,7 +264,6 @@
 }

 void highScoreScreen() {
-  long lastDebounceTime = millis();
   unsigned short totalDelay = 0;
   char hiInitials[4];
   char hiScore[7];
@@ -282,6 +281,9 @@
   }

   arduboy.display();
+
+  unsigned long lastDebounceTime = millis();
+
   while (totalDelay < 4000) {
     unsigned long currentMilliseconds = millis();


Fixed origin/destination swap. Saved a little RAM to improve stability.

--- examples/AFSK_PacketTester/AFSK_PacketTester.ino
+++ examples/AFSK_PacketTester/AFSK_PacketTester.ino
@@ -57,7 +57,6 @@
 }

 void loop() {
-  messagebuff = "KC7IBT,KC7IBT,:HAMSHIELD TEST";
   prepMessage();
   delay(10000);
 }
@@ -65,17 +64,17 @@
 void prepMessage() {
   radio.setModeTransmit();
   delay(500);
-  origin_call = messagebuff.substring(0,messagebuff.indexOf(','));                                          // get originating callsign
-  destination_call = messagebuff.substring(messagebuff.indexOf(',')+1,messagebuff.indexOf(',',messagebuff.indexOf(',')+1)); // get the destination call
-  textmessage = messagebuff.substring(messagebuff.indexOf(":")+1);
+  origin_call = "KC7IBT"; // get originating callsign
+  destination_call = "KC7IBT"; // get the destination call
+  textmessage = ":HAMSHIELD TEST";

-  Serial.print("From: "); Serial.print(origin_call); Serial.print(" To: "); Serial.println(destination_call); Serial.println("Text: "); Serial.println(textmessage);
+  Serial.print("From: "); Serial.print(origin_call); Serial.print(" To: "); Serial.println(destination_call); Serial.println("Text: "); Serial.print(textmessage);

   AFSK::Packet *packet = AFSK::PacketBuffer::makePacket(22 + 32);

   packet->start();
-  packet->appendCallsign(origin_call.c_str(),0);
-  packet->appendCallsign(destination_call.c_str(),15,true);
+  packet->appendCallsign(destination_call.c_str(),0);
+  packet->appendCallsign(origin_call.c_str(),15,true);
   packet->appendFCS(0x03);
   packet->appendFCS(0xf0);
   packet->print(textmessage);
@@ -84,17 +83,15 @@
   bool ret = afsk.putTXPacket(packet);

   if(afsk.txReady()) {
-    Serial.println(F("txReady"));
+    Serial.println(F("TX"));
     radio.setModeTransmit();
     //delay(100);
     if(afsk.txStart()) {
-      Serial.println(F("txStart"));
     } else {
       radio.setModeReceive();
     }
   }
   // Wait 2 seconds before we send our beacon again.
-  Serial.println("tick");
   // Wait up to 2.5 seconds to finish sending, and stop transmitter.
   // TODO: This is hackery.
   for(int i = 0; i < 500; i++) {
@@ -102,7 +99,7 @@
        break;
     delay(50);
   }
-  Serial.println("Done sending");
+  Serial.println("RX");
   radio.setModeReceive();
 }


erase default speed

erase default speed

--- examples/GPRS_OutgoingCall/GPRS_OutgoingCall.ino
+++ examples/GPRS_OutgoingCall/GPRS_OutgoingCall.ino
@@ -8,9 +8,9 @@
 // номер на который будем звонить
 #define PHONE_NUMBER  "+79263995140"

-// создаём объект класса GPRS и передаём ему скорость 9600 бод
+// создаём объект класса GPRS
 // с помощью него будем давать команды GPRS шилду
-GPRS gprs(9600);
+GPRS gprs();

 void setup()
 {


Fix examples - #123

Fix examples - #123

--- examples/TemperatureSensor/TemperatureSensor.ino
+++ examples/TemperatureSensor/TemperatureSensor.ino
@@ -16,11 +16,8 @@
     Serial.print("Temperature: ");
     Serial.print(temperature);
     Serial.println(" °C");
-    if (Homie.setNodeProperty(temperatureNode, "degrees", String(temperature), true)) {
-      lastTemperatureSent = millis();
-    } else {
-      Serial.println("Temperature sending failed");
-    }
+    Homie.setNodeProperty(temperatureNode, "degrees", String(temperature), true);
+    lastTemperatureSent = millis();
   }
 }


Rotating Camera demo works.

Rotating Camera demo works.

--- src/RotatingCamera/RotatingCamera.ino
+++ src/RotatingCamera/RotatingCamera.ino
@@ -34,7 +34,7 @@
 double stepDegree = 0.094;
 int desiredStep = 0;
 // In testing it seems this is unecessary.
-int DELAY = 0;
+int DELAY = 10;

 int CLOCKWISE = HIGH;
 int COUNTERCLOCKWISE = LOW;
@@ -54,20 +54,31 @@
   digitalWrite(ENABLE, HIGH); //the motor should not make loud screeching
   nh.initNode();
   nh.subscribe(cvDegreeReader);
+  //Serial.begin(9600);
 }

 void loop()
 {
 	nh.spinOnce();
+        //if(Serial.available())
+        //{
+        //  rotateToFaceAngle(Serial.parseInt());
+        //}
+
 	delayMicroseconds(1000);
 }

-void desiredCameraPosChanged( const std_msgs::Int32& newPos){
-    desiredDegrees = newPos.data;
-	// Step = Degrees / steps per degree * gear ratio
+void rotateToFaceAngle(int angle)
+{
+    desiredDegrees = angle % 360;
+    // Step = Degrees / steps per degree * gear ratio
     desiredStep = int(desiredDegrees/stepDegree)*19;
     Serial.print("Going to degree: ");
-    Serial.println(desiredDegrees);
+    Serial.print(desiredDegrees);
+    Serial.print(" (Desired step: ");
+    Serial.print(desiredStep);
+    Serial.print("; current step: ");
+    Serial.println(stepCount);
   if(stepCount == desiredStep)
   {
 	  return;
@@ -81,6 +92,13 @@
 	  driveDown();
   }
 }
+
+void desiredCameraPosChanged( const std_msgs::Int32& newPos){
+    desiredDegrees = newPos.data;
+    rotateToFaceAngle(desiredDegrees);
+}
+
+

   // increasing the count means we want to move clockwise (right)
   void driveUp()


Added de-bounce, tidied up some code, added dummy menu items

--- arduboy-game/arduboy-game.ino
+++ arduboy-game/arduboy-game.ino
@@ -36,6 +36,8 @@
 byte titleScreen() {
   byte selectedItem = TITLE_PLAY_GAME;
   unsigned short totalDelay = 0;
+  long lastDebounceTime = 0;  // the last time the button was pressed
+  long debounceDelay = 100;

   arduboy.clear();
   printText("TITLE", 25, 20, 2);
@@ -47,45 +49,83 @@
   arduboy.display();

   while(totalDelay < ATTRACT_MODE_TIMEOUT) {
+
     // TODO This needs a debounced button press routine... arduboy.pressed isn't doing it
     if (arduboy.pressed(A_BUTTON) || arduboy.pressed(B_BUTTON)) {
       break;
-    } else if (arduboy.pressed(LEFT_BUTTON)) {
-      if (selectedItem == TITLE_CREDITS) {
-        // Highlight play option
-        selectedItem = TITLE_PLAY_GAME;
-        arduboy.drawRect(30, 47, 45, 13, 0);
-        arduboy.drawRect(2, 47, 26, 13, 1);
-        arduboy.display();
-      } else if (selectedItem == TITLE_SETTINGS) {
-        // TODO move to credits
-        selectedItem = TITLE_CREDITS;
-        // TODO clear settings
-        arduboy.drawRect(76, 47, 51, 13, 0);
-        arduboy.drawRect(30, 47, 45, 13, 1);
-        arduboy.display();
-      }
-    } else if (arduboy.pressed(RIGHT_BUTTON)) {
-      if (selectedItem == TITLE_PLAY_GAME) {
-        // Highlight credits option
-        selectedItem = TITLE_CREDITS;
-        arduboy.drawRect(2, 47, 26, 13, 0);
-        arduboy.drawRect(30, 47, 45, 13, 1);
-        arduboy.display();
-      } else if (selectedItem == TITLE_CREDITS) {
-        selectedItem = TITLE_SETTINGS;
-        // TODO draw settings
-        arduboy.drawRect(30, 47, 45, 13, 0);
-        arduboy.drawRect(76, 47, 51, 13, 1);
-        arduboy.display();
+    }
+
+    if (arduboy.pressed(LEFT_BUTTON)) {
+      if ( (millis() - lastDebounceTime) > debounceDelay) {
+        selectedItem = titleMenuLeftButton(selectedItem);
+        lastDebounceTime = millis(); //set the current time
+      }
+    }
+
+    if (arduboy.pressed(RIGHT_BUTTON)) {
+      if ( (millis() - lastDebounceTime) > debounceDelay) {
+        selectedItem = titleMenuRightButton(selectedItem);
+        lastDebounceTime = millis(); //set the current time
       }
     }

     delay(15);
     totalDelay += 15;
   }
-
   return(totalDelay >= ATTRACT_MODE_TIMEOUT ? TITLE_TIMEOUT : selectedItem);
+}
+
+byte titleMenuLeftButton(byte selectedItem) {
+  /**
+   * Handle clicks on the left button
+   * to navigate through main menu
+   * items.
+   */
+  switch (selectedItem) {
+
+    case TITLE_SETTINGS:
+         arduboy.drawRect(76, 47, 51, 13, 0);
+         arduboy.drawRect(30, 47, 45, 13, 1);
+         arduboy.display();
+         return TITLE_CREDITS;
+         break;
+
+    case TITLE_CREDITS:
+         arduboy.drawRect(30, 47, 45, 13, 0);
+         arduboy.drawRect(2, 47, 26, 13, 1);
+         arduboy.display();
+         return  TITLE_PLAY_GAME;
+         break;
+
+    default: break;
+  }
+}
+
+
+byte titleMenuRightButton(byte selectedItem){
+  /**
+   * Handle clicks on the right button
+   * to navigate through main menu
+   * items.
+   */
+  switch (selectedItem) {
+
+    case TITLE_PLAY_GAME:
+         arduboy.drawRect(2, 47, 26, 13, 0);
+         arduboy.drawRect(30, 47, 45, 13, 1);
+         arduboy.display();
+         return TITLE_CREDITS;
+         break;
+
+    case TITLE_CREDITS:
+         arduboy.drawRect(30, 47, 45, 13, 0);
+         arduboy.drawRect(76, 47, 51, 13, 1);
+         arduboy.display();
+         return TITLE_SETTINGS;
+         break;
+
+    default: break;
+  }
 }

 void highScoreScreen() {
@@ -107,7 +147,9 @@
 void settingsScreen() {
   // TODO, this is a placeholder
   arduboy.clear();
-  printText("SETTINGS", 20, 25, 2);
+  printText("SETTINGS", 20, 5, 2);
+  printText("SOUND", 20, 25, 1);
+  printText("RESET HIGHSCORE", 20, 35, 1);
   arduboy.display();
   delay(5000);
 }


Simple cleanup things. Comments removed, etc...

--- arduboy-game/arduboy-game.ino
+++ arduboy-game/arduboy-game.ino
@@ -768,13 +768,8 @@
   drawBitmap(0, 8, gameOver, 0);
   arduboy.display();

-//  delay(100);
-  // play game over tune
-  playMusic(4);
-
+  playMusic(4);
   delay(4500);
-//  arduboy.tunes.stopScore();
-//  delay(2000);
 }

 void drawHighScoreEntryCursor(byte pos) {
@@ -799,7 +794,7 @@
   long lastDebounceTime = millis();
   bool allDone = false;
   unsigned short currPos = 0;
-  byte currInitials[] = { 65, 65, 65};
+  byte currInitials[] = {65, 65, 65};

   arduboy.clear();
   printText("NEW HI!", 24, 1, 2);
@@ -821,7 +816,6 @@
           if (currPos < 2) {
             currPos++;
             drawHighScoreEntryCursor(currPos);
-//            arduboy.display();
           }
           else {
             allDone = true;
@@ -834,7 +828,6 @@
         if (currPos > 0) {
           currPos--;
           drawHighScoreEntryCursor(currPos);
-//          arduboy.display();
         }
         lastDebounceTime = currentMilliseconds;
       }
@@ -844,7 +837,6 @@
         if (currPos < 2) {
           currPos++;
           drawHighScoreEntryCursor(currPos);
-//          arduboy.display();
         }
         lastDebounceTime = currentMilliseconds;
       }
@@ -858,7 +850,6 @@

           sprintf(textBuf, "%c%c%c", currInitials[0], currInitials[1], currInitials[2]);
           printText(textBuf, 44, 45, 2);
-//          arduboy.display();
           lastDebounceTime = currentMilliseconds;
        }

@@ -870,7 +861,6 @@
           }
           sprintf(textBuf, "%c%c%c", currInitials[0], currInitials[1], currInitials[2]);
           printText(textBuf, 44, 45, 2);
-//          arduboy.display();
           lastDebounceTime = currentMilliseconds;
        }
        arduboy.display();


Setting motor acceleration

Setting motor acceleration

--- arduino/autofowl/autofowl.ino
+++ arduino/autofowl/autofowl.ino
@@ -5,17 +5,19 @@
 #include <Wire.h>
 #include <RTClib.h>

+#define DEBUG 1
+
 // --------------------------------------
 // -- Constants
 // --------------------------------------

-const int INT_MAX               = 32767;
-const int NONE                  = -1;
-const int TICK                  = 150; // microseconds
-const byte EEPROM_UNINIT_VALUE  = -1;
-
-const int BUTTON_UP   = LOW;
-const int BUTTON_DOWN = HIGH;
+const int INT_MAX                           = 32767;
+const int NONE                              = -1;
+const int TICK                              = 150; // microseconds
+const byte EEPROM_UNINIT_VALUE              = -1;
+
+const int BUTTON_UP                         = LOW;
+const int BUTTON_DOWN                       = HIGH;

 // Run modes
 const int MODE_DISABLED                     = 0;
@@ -31,43 +33,45 @@
 const int MODE_MAX                          = MODE_SET_CLOCK_OPEN_MIN_THRESH;

 // Door positions
-const int DOOR_POSITION_UNKNOWN = 0;
-const int DOOR_POSITION_UP      = 1;
-const int DOOR_POSITION_DOWN    = 2;
-const int DOOR_POSITION_MAX     = DOOR_POSITION_DOWN;
-const int DOOR_POSITION_MIN     = DOOR_POSITION_UNKNOWN;
+const int DOOR_POSITION_UNKNOWN             = 0;
+const int DOOR_POSITION_UP                  = 1;
+const int DOOR_POSITION_DOWN                = 2;
+const int DOOR_POSITION_MAX                 = DOOR_POSITION_DOWN;
+const int DOOR_POSITION_MIN                 = DOOR_POSITION_UNKNOWN;

 // Door motion directions
-const int DOOR_STATIONARY       = 0;
-const int DOOR_MOVING_UP        = 1;
-const int DOOR_MOVING_DOWN      = 2;
+const int DOOR_STATIONARY                   = 0;
+const int DOOR_MOVING_UP                    = 1;
+const int DOOR_MOVING_DOWN                  = 2;

 // EEPROM addresses
-const int DOOR_POSITION_ADDRESS           = 0;
-const int CURRENT_MODE_ADDRESS            = 1;
-const int LIGHT_THRESH_DOWN_ADDRESS       = 3;
-const int LIGHT_THRESH_UP_ADDRESS         = 4;
-const int CLOCK_HOUR_THRESH_UP_ADDRESS    = 5;
-const int CLOCK_MIN_THRESH_UP_ADDRESS     = 6;
-const int CLOCK_HOUR_THRESH_DOWN_ADDRESS  = 7;
-const int CLOCK_MIN_THRESH_DOWN_ADDRESS   = 8;
-const int EEPROM_UNSET                    = 255;
+const int DOOR_POSITION_ADDRESS             = 0;
+const int CURRENT_MODE_ADDRESS              = 1;
+const int LIGHT_THRESH_DOWN_ADDRESS         = 3;
+const int LIGHT_THRESH_UP_ADDRESS           = 4;
+const int CLOCK_HOUR_THRESH_UP_ADDRESS      = 5;
+const int CLOCK_MIN_THRESH_UP_ADDRESS       = 6;
+const int CLOCK_HOUR_THRESH_DOWN_ADDRESS    = 7;
+const int CLOCK_MIN_THRESH_DOWN_ADDRESS     = 8;
+const int EEPROM_UNSET                      = 255;

 // Motor constants
-const int MOTOR_RPMS            = 60;
-const int STEPS_PER_REVOLUTION  = 200;
+const int MOTOR_MAX_RPMS                    = 60;
+const int STEPS_PER_REVOLUTION              = 200;
+const int MOTOR_SPEED_STEPS_PER_SECOND      = ( MOTOR_MAX_RPMS / 60 ) * STEPS_PER_REVOLUTION;
+const int MOTOR_ACCEL_STEPS_PER_SEC_PER_SEC = 50;

 // Number of ticks beyond threshold to wait before changing door position
-const int LIGHT_THRESH_TICKS_TO_CHANGE = 100;
+const int LIGHT_THRESH_TICKS_TO_CHANGE      = 100;
 // Number to change the light threshold by per button press
-const int LIGHT_THRESH_CHANGE_INCREMENT = 20;
+const int LIGHT_THRESH_CHANGE_INCREMENT     = 20;

 // Number of minutes to increment per click
-const int CLOCK_MIN_INCREMENT = 15;
+const int CLOCK_MIN_INCREMENT               = 15;

 // Door-specific constants
 // Number of revolutions to fully change door position
-const int REVOLUTIONS_TO_CHANGE = 100;
+const int REVOLUTIONS_TO_CHANGE             = 100;

 // Pins
 // Arduino Uno / Buttons
@@ -179,8 +183,10 @@
     0 // seconds
   );

-  // Set up the motor
-  Motor.setSpeed( ( MOTOR_RPMS / 60 ) * STEPS_PER_REVOLUTION );
+  // Set the motors desired constant speed in steps per second
+  Motor.setSpeed( MOTOR_SPEED_STEPS_PER_SECOND );
+  // Set the motors desired acceleration in steps per second per second
+  Motor.setAcceleration(MOTOR_ACCEL_STEPS_PER_SEC_PER_SEC);

   // Read door position from eeprom
   DoorPosition = EEPROM.read(DOOR_POSITION_ADDRESS);
@@ -214,7 +220,9 @@
   handleTriggers();

   // Write debug info to terminal
+  #if DEBUG
   debug();
+  #endif

   // Sleep to avoid busy wait
   delay(TICK);
@@ -437,7 +445,6 @@
   Motor.move(revolutions * (long) STEPS_PER_REVOLUTION);

   // Start stepping motor
-  // for (int rev = 1; rev <= revolutions; rev++) {
   while (true) {

     // Handle buttons to allow abort
@@ -586,6 +593,7 @@
 /**
  * Writes debug info to serial
  */
+#if DEBUG
 void debug() {
   Serial.print('[');
   Serial.print(Now.hour(), DEC);
@@ -617,3 +625,4 @@

   Serial.println();
 }
+#endif


implemented matrix scanning on helm switches

There were nine helm switches for use with the joystick, pedals and finally for the 'sticky' mode each input axis has.  If using long cables for the pedals a delay may be required if 62.5 nanoseconds is not long enough to loop through the pedal wire.

--- KSPboard.ino
+++ KSPboard.ino
@@ -6,6 +6,7 @@
 // for more information.

+
 /////////////
 /// libraries
 //
@@ -31,16 +32,23 @@
 #define PIN_LED 13 // status
 #define PIN_ENABLE A1 // this should be high to run

-// helm pins
-#define PIN_PITCH_U 12
-#define PIN_PITCH_D 11
-#define PIN_PITCH_S 5 // axis stick flag
-#define PIN_ROLL_R 9
-#define PIN_ROLL_L 10
-#define PIN_ROLL_S 4 // axis stick flag
-#define PIN_YAW_R 7
-#define PIN_YAW_L 8
-#define PIN_YAW_S 3 // axis stick flag
+// helm pins, matrix pins, and shorthand for helm masks
+#define PIN_HELM_MAT_DIM  3
+#define PIN_HELM_MAT_ROW  4
+#define PIN_HELM_MAT_ROWS (PIN_HELM_MAT_ROW + PIN_HELM_MAT_DIM)
+#define PIN_HELM_MAT_COL  7
+#define PIN_HELM_MAT_COLS (PIN_HELM_MAT_COL + PIN_HELM_MAT_DIM)
+
+
+#define MASKED_PITCH_U helm | 0b100000000
+#define MASKED_PITCH_D helm | 0b010000000
+#define MASKED_PITCH_S helm | 0b001000000
+#define MASKED_ROLL_R  helm | 0b000100000
+#define MASKED_ROLL_L  helm | 0b000010000
+#define MASKED_ROLL_S  helm | 0b000001000
+#define MASKED_YAW_R   helm | 0b000000100
+#define MASKED_YAW_L   helm | 0b000000010
+#define MASKED_YAW_S   helm | 0b000000001

 #define PIN_THROTTLE A0 // analog read

@@ -61,7 +69,6 @@
 #define DELAY_START 30
 #define DELAY_OP 100
 #define DELAY_CTRL 100
-#define DELAY_MATRIX 3 // this is in microseconds

 // misc
 #define OPS 16 // Action 1-10, stage, gear, light, rcs, brake, abort
@@ -71,15 +78,6 @@
 #define RAMP_MIN -RAMP_MAX
 #define DIR_MAX 2000
 #define DIR_MIN -DIR_MAX
-
-// helper stuff for helm / shorthand
-#define PITCH_STICK digitalRead(PIN_PITCH_S)
-#define ROLL_STICK digitalRead(PIN_ROLL_S)
-#define YAW_STICK digitalRead(PIN_YAW_S)
-
-#define PITCH_PINS PIN_PITCH_U, PIN_PITCH_D
-#define ROLL_PINS PIN_ROLL_R, PIN_ROLL_L
-#define YAW_PINS PIN_YAW_R, PIN_YAW_L

@@ -147,10 +145,29 @@
 }

 // direction helpers
-//convert to matrix
-int16_t getAdjustment(uint8_t pinH, uint8_t pinL, int8_t adj) // get control input
-{
-  switch (digitalRead(pinH) ? HIGH : (digitalRead(pinL) ? LOW : NEUTRAL))
+uint16_t helmReadMatrix()
+{
+  uint16_t matrix = 0;
+  uint8_t row = 0, col = 0;
+
+  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++)
+    {
+      matrix <<= digitalRead(col); // shift in the next column bit
+    }
+
+    digitalWrite(row, HIGH); // turn off the active-low row
+  }
+
+  return (matrix);
+}
+
+int16_t helmGetAdjustment(uint8_t high, uint8_t low, int8_t adj) // get control input
+{
+  switch (high ? HIGH : (low ? LOW : NEUTRAL)) // high trumps low
   {
     case HIGH: // pitch up / roll right / yaw right
       if (adj++ > RAMP_MAX)
@@ -170,7 +187,7 @@
   return (adj);
 }

-int16_t getDirection(int16_t dir, int8_t adj, boolean stick)
+int16_t helmGetDirection(int16_t dir, int8_t adj, boolean stick)
 {
   // reset current if no adj&stick flag or if adj and current are opposite signs
   if (!(adj || stick) || (dir > 0 && adj < 0) || (dir < 0 && adj > 0))
@@ -233,16 +250,15 @@

 void setupHelm()
 {
-  //convert to matrix
-  pinMode(PIN_PITCH_U, INPUT_PULLUP);
-  pinMode(PIN_PITCH_D, INPUT_PULLUP);
-  pinMode(PIN_PITCH_S, INPUT_PULLUP);
-  pinMode(PIN_ROLL_L, INPUT_PULLUP);
-  pinMode(PIN_ROLL_R, INPUT_PULLUP);
-  pinMode(PIN_ROLL_S, INPUT_PULLUP);
-  pinMode(PIN_YAW_L, INPUT_PULLUP);
-  pinMode(PIN_YAW_R, INPUT_PULLUP);
-  pinMode(PIN_YAW_S, INPUT_PULLUP);
+  // rows are output, and cols are input
+  // here we setup the input_pullup pinMode for the cols
+
+  uint8_t index = 0;
+
+  for (index = PIN_HELM_MAT_COL; index < PIN_HELM_MAT_COLS; index++)
+  {
+    pinMode(index, INPUT_PULLUP); // active low matrix
+  }
 }

 void setupOps()
@@ -274,7 +290,7 @@
     // do hiligting stuff //
   }

-  if (controlDebounce > 0) //
+  if (controlDebounce > 0) //
   {
     controlDebounce--; // do dat sweet digi debounce
   }
@@ -284,7 +300,7 @@
     {
       controlLocked = controlState; // update locked variable

-      Serial.println("this is where the good stuff goes, fuck yeah");
+      Serial.println("this is the krpc call to change sas state");

       controlDebounce = DELAY_CTRL; // reset delay
     }
@@ -303,18 +319,20 @@

 void updateHelm()
 {
-  //convert to matrix
+  // get the matrix state used in the pitch/roll/yaw masks below
+  uint16_t helm = helmReadMatrix();
+
   // update control surface inputs
-  pitchAdjust = getAdjustment(PITCH_PINS, pitchAdjust);
-  pitch = getDirection(pitch, pitchAdjust, PITCH_STICK);
+  pitchAdjust = helmGetAdjustment(MASKED_PITCH_U, MASKED_PITCH_D, pitchAdjust);
+  pitch = helmGetDirection(pitch, pitchAdjust, MASKED_PITCH_S);
   Serial.println(pitch);

-  rollAdjust = getAdjustment(ROLL_PINS, rollAdjust);
-  roll = getDirection(roll, rollAdjust, ROLL_STICK);
+  rollAdjust = helmGetAdjustment(MASKED_ROLL_R, MASKED_ROLL_L, rollAdjust);
+  roll = helmGetDirection(roll, rollAdjust, MASKED_ROLL_S);
   Serial.println(roll);

-  yawAdjust = getAdjustment(YAW_PINS, yawAdjust);
-  yaw = getDirection(yaw, yawAdjust, YAW_STICK);
+  yawAdjust = helmGetAdjustment(MASKED_YAW_R, MASKED_YAW_L, yawAdjust);
+  yaw = helmGetDirection(yaw, yawAdjust, MASKED_YAW_S);
   Serial.println(yaw);

   // update our current throttle input level
@@ -346,8 +364,8 @@
           // it to be sent out over serial, otherwise set it to zero
           opState[index] =  ((1 << index) & data) ? DELAY_OP : 0;

-          // increase the operations counter
-          ops++;
+          // increase the operations counter
+          ops++;
         }
       }
     }


Updated source code

Updated source code

--- Motor_v2.ino
+++ Motor_v2.ino
@@ -5,18 +5,18 @@
 BLEService motorService = BLEService("FFF1");

 // switchCharacteristic controls motor's on/off state
-BLECharCharacteristic switchCharacteristic =
+BLECharCharacteristic switchCharacteristic =
   BLECharCharacteristic("FFF2", BLERead | BLEWrite);
 BLEDescriptor switchDescriptor = BLEDescriptor("2901", "Switch");

 // speedCharacteristic controls the motor's speed
-BLEIntCharacteristic speedCharacteristic =
+BLEIntCharacteristic speedCharacteristic =
   BLEIntCharacteristic("FFF3", BLERead | BLEWrite);
 BLEDescriptor speedDescriptor = BLEDescriptor("2901", "Speed");

 void setup() {
   Serial.begin(9600);
-
+
   pinMode(MOTOR_PIN, OUTPUT);

   blePeripheral.setLocalName("Bluetooth Motor");
@@ -24,10 +24,10 @@
   blePeripheral.setAdvertisedServiceUuid(motorService.uuid());

   blePeripheral.addAttribute(motorService);
-
+
   blePeripheral.addAttribute(switchCharacteristic);
   blePeripheral.addAttribute(switchDescriptor);
-
+
   blePeripheral.addAttribute(speedCharacteristic);
   blePeripheral.addAttribute(speedDescriptor);


cleanup

cleanup

--- src/pirNet.ino
+++ src/pirNet.ino
@@ -236,35 +236,31 @@
   timerMgr.add(testUDPSendInterval, testUDPSend);
 }

-void setup() {
-  SetRandomSeed();
-  Serial.begin(115200);
+void reportStatus(void) {
   Serial.printf("Software version: %s\r\n", software_version.c_str());
-
-  wiFiMgr.joinNetwork();
   Serial.print("Local IP: ");
   Serial.println(wiFiMgr.ipAddress());
   Serial.print("Status: ");
   Serial.println(wiFiMgr.statusString());
   Serial.print("Mode: ");
   Serial.println(wiFiMgr.modeString());
-
+  Serial.printf("ESP8266 Location: floor=%u, room=%u, color=0x%08x\r\n",
+                loc.floor, loc.room, loc.color);
+  Serial.print("UDP Local port: ");
+  Serial.println(udpMgr.localPort());
+}
+
+void setup() {
+  SetRandomSeed();
+  Serial.begin(115200);
+
+  wiFiMgr.joinNetwork();
   enableTimers();
   enableOTAUpdates();

-  bool readLoc = configMgr.readLocation(&loc);
-  if (!readLoc) {
-    Serial.println("Failed to read location. Using defaults.");
-  }
-  Serial.printf("ESP8266 Location: floor=%u, room=%u, color=0x%08x\r\n",
-                loc.floor, loc.room, loc.color);
+  configMgr.readLocation(&loc);

   serverMgr.startConfigServer(configMgr, software_version, &loc);
-
-  // TODO(Gary): Move these.
-  // set UDP port for listen
-  Serial.print("UDP Local port: ");
-  Serial.println(udpMgr.localPort());

   // LEDs
   pinMode(LED_BLUE, OUTPUT);
@@ -281,6 +277,8 @@

   // PIR sensor
   pinMode(pirInputPin, INPUT);  // declare sensor as input
+
+  reportStatus();
 }

 void loop() {


Set CPU frequency to 160 Mhz.

Set CPU frequency to 160 Mhz.

--- aquacontrol2.ino
+++ aquacontrol2.ino
@@ -5,12 +5,9 @@
 #include <EEPROM.h>
 #include <FS.h>

-
-/*
   extern "C" {
   #include "user_interface.h"
   }
-*/

 //https://gist.github.com/dogrocker/f998dde4dbac923c47c1

@@ -68,7 +65,8 @@

 ESP8266WebServer webServer ( 80 );

-void setup() {
+void setup() {\
+  system_update_cpu_freq( 160 );
   WiFi.persistent( false );

   //setup channel names and set OUTPUT pinModes


fix a very small typo in http client tests (#4633)

--- tests/device/test_http_client/test_http_client.ino
+++ tests/device/test_http_client/test_http_client.ino
@@ -75,7 +75,7 @@
         REQUIRE(payload == "hello!!!");
     }
     {
-        // request which returns 8000 bytes
+        // request which returns 4000 bytes
         HTTPClient http;
         http.begin(getenv("SERVER_IP"), 8088, "/data?size=4000", fp);
         auto httpCode = http.GET();


added light calibration via gui

added light calibration via gui

--- master/master.ino
+++ master/master.ino
@@ -233,6 +233,137 @@
 	Slave1.requestPacket(SLAVE1_COMMANDS::CALIB_OFFSET);
 }

+void calibLight(){
+	// stop moving
+	Slave3.moveRobot(0, 0, 0);
+	Slave3.moveMotorE(0);
+
+	tftEnableBtn.erase();
+	ltBtn.erase();
+	magBtn.erase();
+	kickBtn.erase();
+	spinBtn.erase();
+
+	tft.fillRect(0, 32, 320, 145, ILI9341_BLACK);
+
+	BUTTON exitBtn(&tft, &touchedPoint);
+	BUTTON greenBtn(&tft, &touchedPoint);
+	BUTTON whiteBtn(&tft, &touchedPoint);
+	BUTTON endBtn(&tft, &touchedPoint);
+
+	greenBtn.setText("GREEN", 3, ILI9341_GREEN);
+	whiteBtn.setText("WHITE", 3, ILI9341_GREEN);
+	endBtn.setText("END", 3, ILI9341_GREEN);
+
+	exitBtn.setBounds(360 - 80, 0, 360, 32);
+	greenBtn.setBounds(0, 180, 107, 240);
+	whiteBtn.setBounds(107, 180, 214, 240);
+	endBtn.setBounds(214, 180, 320, 240);
+
+	exitBtn.setColour(ILI9341_RED);
+	greenBtn.setColour(tft.color565(50,50,50));
+	whiteBtn.setColour(tft.color565(100,100,100));
+	endBtn.setColour(tft.color565(150,150,150));
+
+	exitBtn.draw();
+	greenBtn.draw();
+	whiteBtn.draw();
+	endBtn.draw();
+
+	tft.setTextSize(1);
+	tft.setTextColor(ILI9341_WHITE);
+	tft.setCursor(0, 40);
+
+	delay(300);
+
+	int greens = 0, whites = 0;
+
+	do{
+		getTouch();
+		exitBtn.checkTouch();
+		greenBtn.checkTouch();
+		whiteBtn.checkTouch();
+		endBtn.checkTouch();
+
+		if (greenBtn.released){
+			tft.print("g ");
+			Slave1.requestPacket(SLAVE1_COMMANDS::CALIB_GREEN);
+			greens++;
+			delay(2);
+			Slave1.requestPacket(SLAVE1_COMMANDS::LIGHT_DATA_GREEN);
+			Slave1.receivePacket(inBuffer, 16, true);
+
+			for (int i = 0; i < 16; i++){
+				if (inBuffer[i] < 10){
+					tft.print("  ");
+				}
+				else if (inBuffer[i] <= 100){
+					tft.print(" ");
+				}
+				tft.print(inBuffer[i]);
+				tft.print(" ");
+			}
+			tft.println();
+		}
+		else if (whiteBtn.released){
+			tft.print("w ");
+			Slave1.requestPacket(SLAVE1_COMMANDS::CALIB_WHITE);
+			whites++;
+			delay(2);
+			Slave1.requestPacket(SLAVE1_COMMANDS::LIGHT_DATA_WHITE);
+			Slave1.receivePacket(inBuffer, 16, true);
+			for (int i = 0; i < 16; i++){
+				if (inBuffer[i] < 10){
+					tft.print("  ");
+				}
+				else if (inBuffer[i] <= 100){
+					tft.print(" ");
+				}
+				tft.print(inBuffer[i]);
+				tft.print(" ");
+			}
+			tft.println();
+		}
+		else if (endBtn.released){
+			if (greens && whites){
+				Slave1.requestPacket(SLAVE1_COMMANDS::END_CALIB_LIGHT);
+				tft.println();
+				tft.println("FINISHED CALIB");
+				tft.print("  ");
+				delay(2);
+				Slave1.requestPacket(SLAVE1_COMMANDS::LIGHT_DATA_REFS);
+				Slave1.receivePacket(inBuffer, 16, true);
+				for (int i = 0; i < 16; i++){
+					if (inBuffer[i] < 10){
+						tft.print("  ");
+					}
+					else if (inBuffer[i] <= 100){
+						tft.print(" ");
+					}
+					if (inBuffer[i] == 255){
+						tft.setTextColor(ILI9341_RED);
+					}
+					else{
+						tft.setTextColor(ILI9341_WHITE);
+					}
+					tft.print(inBuffer[i]);
+					tft.print(" ");
+				}
+				tft.println();
+			}
+			else{
+				if (!greens){
+					tft.println("NEED GREEN");
+				}
+				if (!whites){
+					tft.println("NEED WHITE");
+				}
+			}
+		}
+	} while(!exitBtn.released);
+	initDebugTFT();
+	drawButtons();
+}

 void calibMag(){
 	// stop moving


Update CardinalSerialInputDegrees.ino

Update CardinalSerialInputDegrees.ino

--- examples/CardinalSerialInputDegrees/CardinalSerialInputDegrees.ino
+++ examples/CardinalSerialInputDegrees/CardinalSerialInputDegrees.ino
@@ -27,50 +27,65 @@

 #include <Cardinal.h>    // Include the library

-int type = 3; // Type of precision
 /*
-Precision types:
+Precision types (see https://github.com/DaAwesomeP/arduino-cardinal/wiki/Types for mroe info):
  - 0: N, S, E, W
  - 1: N, NE, E, SE, S, SW, W, NW
  - 2: N, NNE, NE, ENE, E, ESE, SE, SSE, S, SSW, SW, WSW, W, WNW, NW, NNW
  - 3: all 32 headings (N, NbE, NNE, NEbN, NE, NEbE, etc.)
 */
+int type = 3; // Type of precision

+// Vars for grabbing the serial input
 String inputString = "";
 float inputFloat;
 boolean stringComplete = false;

+// Vars for string the converted headings
 String stringOut;
 int intOut;

 Cardinal cardinal;   // init the library to "cardnial"

 void setup() {
+  // Initialize serial
   Serial.begin(9600);
+  Serial.println("Cardinal example by DaAwesomeP");
+  Serial.println("-------------------------------------------------------------------------------------------");
+  // More environment variables can be found in Cardinal.h  or at https://github.com/DaAwesomeP/arduino-cardinal/wiki/Environment-Variables
+  Serial.println("Did you know that lots of new environment variables are available now?");
+  Serial.println("Here's a few (you can find them in the header file or in the Wiki):");
+  Serial.print("CARDINAL_NEbN_MIDAZ: "); Serial.print(CARDINAL_NEbN_MIDAZ); Serial.println(" (the middle azimuth of Northeast by North)");
+  Serial.print("CARDINAL_E_MIN: "); Serial.print(CARDINAL_E_MIN); Serial.println(" (the minimum degrees of East)");
+  Serial.print("CARDINAL_ESE: "); Serial.print(CARDINAL_ESE); Serial.println(" (the integer ID of East-southeast)");
+  Serial.println("-------------------------------------------------------------------------------------------");
   Serial.println("Type a number from 0 to 360 (including decimals) and see the output!");
-  Serial.println("--------------------------------------------------------------------");
+  Serial.println("-------------------------------------------------------------------------------------------");
 }

 void loop() {
-  if (stringComplete) {
+  if (stringComplete) {                                // If something has been entered in serial
     inputFloat = inputString.toFloat();                // Convert the inputted number to a float
     intOut = cardinal.integer(type, inputFloat);       // Use that float to get the heading number
     stringOut = cardinal.string(type, inputFloat);     // Use that float to get the heading in text format
-    Serial.print("in: ");
+    Serial.print("in: ");                              // Print the data to serial
     Serial.print(inputString);
     Serial.print("int: ");
     Serial.print(intOut);
     Serial.print(" str: ");
     Serial.println(stringOut);
     // clear the string:
-    inputString = "";
-    stringComplete = false;
+    inputString = "";                                  // Clear the input string
+    stringComplete = false;                            // Clear the input boolean
   }
 }

+// For compatibility with some Arduinos that lack this event (like the Pro Mini)
 void serialEventRun(void) {
   if (Serial.available()) serialEvent();
 }
+
+// Catch
 void serialEvent() {
   while (Serial.available()) {
     // get the new byte:


Preparing for an Arduino with motor shield and multiple motors

--- src/main.ino
+++ src/main.ino
@@ -19,9 +19,11 @@
 // step_mode let us use halfsteps (but we prolly don't need that)
 int step_mode = 8; // 4 = full, 8 = half

+// number of steps it takes to turn 360º
 #define fullRev 2048 * (step_mode/4)

-#define ledPin 13       // define test LED
+// setup LED at pin 13
+#define ledPin 13

 ////////////////////////
 // STEPPER INITIALIZE //
@@ -55,6 +57,8 @@
   delay(100);
   Serial.println("Backward");
   Stepper1.step(-fullRev);
+
+  partRev(1, 1.0);
 }

@@ -71,16 +75,29 @@
   }
 }

-void fullBendFinger(int finger) {
-  switch (finger) {
-    case 1:
-      Stepper1.step(500);
-      break;
-    case 2:
-      break;
-    case 3:
-      break;
-    case 4:
-      break;
+void partRev(int finger, float frac) {
+  if (frac > 0) {
+    switch (finger) {
+      case 1:
+        Stepper1.step(fullRev);
+        break;
+      case 2:
+        Stepper1.step(fullRev);
+        break;
+      case 3:
+        Stepper1.step(fullRev);
+        break;
+      case 4:
+        Stepper1.step(fullRev);
+        break;
+      case 5:
+        Stepper1.step(fullRev);
+        break;
+    }
+  }
+  else {
+    Serial.println("Fraction of rotation can't be negative or 0.");
+    float frac = 1.0;
+    partRev(finger, frac);
   }
 }


Bug fixes in v1 Code

Bug fixes in v1 Code


moyenne sur mesure ref fait...meme si c'est pas ce qu'il fallait faire

--- calibrateur.ino
+++ calibrateur.ino
@@ -30,7 +30,7 @@
 #define DELTA 150
 #define TEMPOSLEEP 1000 //en ms le temps pour le servo de bouger d'un increment quand on fait les mesure à la roue codeuse
 #define ERREURCOMPTAGE 7 //la tolérance de comptage avant que l'on estime que le servo est arrivé au bout
-#define NBRCYCLE_AR 5 //nbre de cycle d'aller et retour pour la fin des mesure de caractérisation
+#define NBRCYCLE_AR 5 //nbre de cycle d'aller et retour pour la fin des mesure de caractérisation et nbr de cycle pour la mesure des PWMIN et PWMMAX
 #define TEMPO_STAT 200 // tempo pour laisser le servo avancr lors des mesures statistique à la fin de la calibration
 #define ADRESSE_EEPROM 42//position de leeprom ou la valeur de reglage de l potence est stocké

@@ -46,7 +46,7 @@
 		WAITCLIC = 15,
 		DISPRESULT = 16,
 		WAITCLIC2 = 17,
-                LECTURE_OU_ECRITURE_EEEPROM=18,
+    LECTURE_OU_ECRITURE_EEEPROM=18,
 		SWEEPTOMIN = 2,
 		SWEPPTOMAX = 20
 };
@@ -65,9 +65,25 @@
 int compteurRef(0);
 int resultatImpulsion[NBRCYCLE_AR*2];
 long resultatTemps[NBRCYCLE_AR*2];
+int mesureRef[NBRCYCLE_AR];
+int PWMMin[NBRCYCLE_AR];
+int PWMMax[NBRCYCLE_AR];
+
+
 int objTest (0); // varaible temporaire pour ...peut sans doute etre supprimé en faisant apelle aux bnnes méthode pour connaitre etat courrant du servo

-
+int moyenne (int tailleTab, int tab [])
+
+{
+  byte j;
+  long moyenne (0);
+  for (j=0;j<tailleTab;j++)
+         {
+              moyenne=moyenne+tab[j];
+          }
+   moyenne=moyenne/(tailleTab);
+
+}

 defineTimerRun(rafraichirAffichage,800)
@@ -111,6 +127,7 @@
 	{
     //Serial.println("proute");
     //Serial.println("reflechi");
+    byte i;
 		if (boutonP.hasBeenLongClicked())
 			{
 				dateChangeServo=(millis());
@@ -159,7 +176,12 @@
 					if (boutonP.hasBeenDoubleClicked())
 					{
 						boutonP.acquit();
-						leServo.setVitesse(4000);
+            leServo.setVitesse(4000);
+            leServo.setObjectif(leServo.getMilieu());
+         // pour etre certain qu'on aprt du milieu et que le servo
+          //n'est pas n'importe ou suite à des manip de type sweep
+          //ou potar par ex
+
 						Serial.println(F("si lecture EEPROM pour potence Simple clic, si reglage potence double clic"));
 						etatCalibrateur=LECTURE_OU_ECRITURE_EEEPROM;
 					}
@@ -170,10 +192,10 @@
 						{
 							boutonP.acquit();
 							EEPROM.get(ADRESSE_EEPROM, bonnePositionPotence); //lire la prom
-                                                        Serial.println("j'ai lu");
-                                                        Serial.println(bonnePositionPotence);
-                                                        potence.setObjectif(bonnePositionPotence);
-                                                        etatCalibrateur=MESREFPULSE;
+              Serial.println("j'ai lu");
+              Serial.println(bonnePositionPotence);
+              potence.setObjectif(bonnePositionPotence);
+              etatCalibrateur=MESREFPULSE;
 						}

 					if (boutonP.hasBeenDoubleClicked())
@@ -186,11 +208,8 @@
 					break;

-                                case REGPOTENCINVIT :
-					leServo.setObjectif(leServo.getMilieu());
-					// pour etre certain qu'on aprt du milieu et que le servo
-					//n'est pas n'importe ou suite à des manip de type sweep
-					//ou potar par ex
+          case REGPOTENCINVIT :
+
 					if (lePotar.getValue()>1000)
 					{
 						etatCalibrateur=REGLPOTENC;
@@ -217,35 +236,33 @@
 						}
 					break;

-				case MESREFPULSE: //mesure des impulsion de reference sur une rotation de delta
-					Serial.println("ICI");
-					compteur=0;
-					compteurRef=0;
-//                                        Serial.print("En Cours=");
-//                                        Serial.print(leServo.getEnCours());
-//                                        Serial.print(" Objectif =");
-//                                        Serial.println(leServo.getObjectif());
-					//objTest=leServo.getMilieu()+DELTA;
-					leServo.setObjectif(leServo.getMilieu()+DELTA);
-//                                        Serial.println("Envoi incrément Servo");
-//                                        Serial.println("En Cours=");
-//                                        Serial.print(leServo.getEnCours());
-//                                        Serial.print(" Objectif =");
-//                                        Serial.println(leServo.getObjectif());
-					sleep(TEMPOSLEEP);
-//                                        Serial.println("Fin attente");
-//                                        Serial.println("En Cours=");
-//                                        Serial.print(leServo.getEnCours());
-//                                        Serial.print(" Objectif =");
-//                                        Serial.println(leServo.getObjectif());
+				case MESREFPULSE: //mesure des impulsion de reference sur une rotation de delta faite X fois pour plus de certitude
+
+          compteurRef=0;
+          for (i=0;i<NBRCYCLE_AR;i=i+1)
+          {
+    					Serial.print(F("iteration de mesure de ref="));
+    					compteur=0;
+
+    					leServo.setObjectif(leServo.getMilieu()+DELTA);
+    					sleep(TEMPOSLEEP);
+              mesureRef[i]=compteur;
+              leServo.setObjectif(leServo.getMilieu());
+              sleep(TEMPOSLEEP);
+              Serial.println(mesureRef[i]);
+          }
+
+
+
+
 					etatCalibrateur=FINDMINMAX;
-					//Serial.println("la");
-					compteurRef=compteur;
-                                        Serial.print(" SUPERcmpteurRef=");
-                                        Serial.println(compteurRef);
-//                                        Serial.print(" OBJTEST=");
-//                                        Serial.println(leServo.getObjectif());
-
+					compteurRef=moyenne(NBRCYCLE_AR,mesureRef);
+          Serial.print(" SUPERcmpteurRef=");
+          Serial.println(compteurRef);
+
+
+
+
 					if (compteurRef==0)
 						{
 							Serial.println(F("PB : compteur Ref=0 aucune impulsion fourche optique détecté"));
@@ -311,7 +328,7 @@

 					//séquence pour mesurer une vitesse et amplitude moyenne
 					//(10 cycle d'aller et retour et enregistrement systématique des mesures)
-					byte i;
+
 					for (i=0;i<NBRCYCLE_AR*2;i=i+2)
 						{
 							compteur=0;
@@ -537,6 +554,9 @@
 {
 	compteur++;
 }
+
+
+

 void loop ()
 {


qq correction dont notamment boucle for qui couvre amplitude min et max en même temps

--- calibrateur.ino
+++ calibrateur.ino
@@ -342,8 +342,9 @@
                     for (i=0;i<NBRCYCLE_AR;i=i+1){
                         compteur=compteurRef;
                         amplitude=0;
+						Serial.print(F("Cycle recherche MAX n ") );Serial.println(1+i);
                         while (abs(compteurRef-compteur)<ERREURCOMPTAGE) {
-                            Serial.print(F("Cycle recherche MAX n°") );Serial.println(i);
+
                             Serial.print(F("M+....."));
                             compteur=0;
                             //objTest=objTest+DELTA;
@@ -354,10 +355,10 @@
                             Serial.print(F(" amplitude="));Serial.println(amplitude);
                         }
                         amplitude=amplitude-abs(compteur)	;
-                        resultatAmplitudeMax[i] = amplitude ;
+                        //resultatAmplitudeMax[i] = amplitude ;
                         resultatMaxServo[i]= leServo.getObjectif()-DELTA;
-                        Serial.print(F(", amplitude retenue =") );Serial.println(amplitude);
-                    }
+                        Serial.print(F(", amplitude en cours retenue =") );Serial.println(amplitude);
+                    //}
 					//Serial.print(" amplitude retenue=");Serial.println(amplitude);
                     //leServo.setMax(leServo.getObjectif()-DELTA);
                     leServo.setMax( (int) moyenne( NBRCYCLE_AR, resultatMaxServo ) );
@@ -367,12 +368,13 @@
                     sleep(TEMPOSLEEP);
                     //----------------------------------------------------------
                     //find mmin
-                    for (i=0;i<NBRCYCLE_AR;i=i+1){
+                   // for (i=0;i<NBRCYCLE_AR;i=i+1){
                         compteur=-compteurRef;
+						Serial.print(F("Cycle recherche MIN n ") );Serial.println(i+1);
                         while (abs(-compteurRef-compteur)<ERREURCOMPTAGE){
                         // inversion du signe de compteur ref car on change de sens
                         // de rotation (par rapport au sens de recherche de compteur ref)
-                            Serial.print(F("Cycle recherche MIN n°") );Serial.println(i);
+
                             Serial.print(F("M-......"));
                             compteur=0;
                             //objTest=objTest-DELTA;
@@ -386,6 +388,11 @@
                         resultatAmplitudeMin[i] = amplitude ;
                         resultatMinServo[i]= leServo.getObjectif()+DELTA;
                         Serial.print(F(", amplitude retenue =") );Serial.println(amplitude);
+						leServo.setObjectif(leServo.getMilieu());
+
+						Serial.println("retourneMilieu");
+						sleep(TEMPOSLEEP);
+						Serial.println(F("*************************************") );
                     }
                     //leServo.setMin(leServo.getObjectif()+DELTA);
                     leServo.setMin((int) moyenne( NBRCYCLE_AR, resultatMinServo ));
@@ -396,9 +403,12 @@
                     leServo.setObjectif(leServo.getMin());
                     //----------------------------------------------------------
                     //Amplitude angulaire exprimee en unite de roue codeuse
-					amplitude = moyenne( NBRCYCLE_AR, resultatAmplitudeMax );
-                    amplitude += moyenne( NBRCYCLE_AR, resultatAmplitudeMin );
-                    //----------------------------------------------------------
+					//amplitude = moyenne( NBRCYCLE_AR, resultatAmplitudeMax );
+                    amplitude = moyenne( NBRCYCLE_AR, resultatAmplitudeMin );
+					Serial.println(F("=============") );
+					Serial.print(F("amplitude moyenne retenue =") );Serial.println(amplitude);
+                    Serial.println(F("=============") );
+					//----------------------------------------------------------
                     //séquence pour mesurer une vitesse et amplitude moyenne
                     //(10 cycles d'aller et retour de min à max
                     //et enregistrement systématique des mesures)


use byte and word iso uint*{8,16}_t to be consistent

… although the better option would probably be to use uint*_t
everywhere, and lose the byte/word stuff

--- examples/RF12/RF12demo/RF12demo.ino
+++ examples/RF12/RF12demo/RF12demo.ino
@@ -60,7 +60,7 @@
 #define _receivePin 8
 static int _bitDelay;
 static char _receive_buffer;
-static uint8_t _receive_buffer_index;
+static byte _receive_buffer_index;

 ISR (PCINT0_vect) {
     char i, d = 0;
@@ -81,8 +81,8 @@

 // TODO: replace with code from the std avr libc library:
 //  http://www.nongnu.org/avr-libc/user-manual/group__util__delay__basic.html
-void whackDelay (uint16_t delay) {
-    uint8_t tmp=0;
+void whackDelay (word delay) {
+    byte tmp=0;

     asm volatile("sbiw      %0, 0x01 \n\t"
                  "ldi %1, 0xFF \n\t"
@@ -95,7 +95,7 @@
 }

 static byte inChar () {
-    uint8_t d;
+    byte d;
     if (! _receive_buffer_index)
         return -1;
     d = _receive_buffer; // grab first and only byte
@@ -160,8 +160,8 @@
         Serial.print(value);
 }

-static uint16_t calcCrc (const void* ptr, uint8_t len) {
-    uint16_t crc = ~0;
+static word calcCrc (const void* ptr, byte len) {
+    word crc = ~0;
     for (byte i = 0; i < len; ++i)
         crc = _crc16_update(crc, ((const byte*) ptr)[i]);
     return crc;
@@ -383,7 +383,7 @@
 #if !TINY
             // this code adds about 400 bytes to flash memory use
             // display the exact frequency associated with this setting
-            uint8_t freq = 0, band = config.nodeId >> 6;
+            byte freq = 0, band = config.nodeId >> 6;
             switch (band) {
                 case RF12_433MHZ: freq = 43; break;
                 case RF12_868MHZ: freq = 86; break;
@@ -392,7 +392,7 @@
             uint32_t f1 = freq * 100000L + band * 25L * config.frequency_offset;
             Serial.print((word) (f1 / 10000));
             printOneChar('.');
-            uint16_t f2 = f1 % 10000;
+            word f2 = f1 % 10000;
             // tedious, but this avoids introducing floating point
             printOneChar('0' + f2 / 1000);
             printOneChar('0' + (f2 / 100) % 10);
@@ -518,7 +518,7 @@
     memset(stack, 0, sizeof stack);
 }

-static void displayASCII (const uint8_t* data, byte count) {
+static void displayASCII (const byte* data, byte count) {
     for (byte i = 0; i < count; ++i) {
         printOneChar(' ');
         char c = (char) data[i];
@@ -620,7 +620,7 @@
             }
             printOneChar(rf12_hdr & RF12_HDR_DST ? '>' : '<');
             printOneChar('@' + (rf12_hdr & RF12_HDR_MASK));
-            displayASCII((const uint8_t*) rf12_data, n);
+            displayASCII((const byte*) rf12_data, n);
         }

         if (rf12_crc == 0) {


Add serial commands

Add serial commands

--- arduino/arduino_md03_v_5_0/arduino_md03_v_5_0.ino
+++ arduino/arduino_md03_v_5_0/arduino_md03_v_5_0.ino
@@ -47,7 +47,18 @@
   int lid_pos;
 };

+// 0..255
+struct Command {
+  int yaw_pwm;
+  boolean yaw_direction;
+  int pitch_pwm;
+  boolean pitch_direction;
+  int lid_pwm;
+  boolean lid_direction;
+};
+
 Status stat = { 0, 0, 0 };
+Command cmd = { 0, true, 0, true, 0, true };

 //serial
 String inputString = "";         // a string to hold incoming data
@@ -75,7 +86,6 @@
   delay(30);
   //lcd.clear();

-
   //serial
   Serial.begin(9600);
   // reserve 200 bytes for the inputString:
@@ -85,21 +95,18 @@

 void loop(){
   static unsigned long send_time = millis();
-  stat.pitch_pos = analogRead(potPin1);
-  stat.yaw_pos = analogRead(potPin2);
-  stat.lid_pos = analogRead(potPin3);
-
+  read_status();
+
+  // read commands when we get a full line
+  if (stringComplete) {
+    read_command();
+    lcd_command();
+    do_command();
+  }
+
   //direct1 = manualSpeedControl(motorPinSpeed1, potPin1, rlyPin1, motorPinDir1, direct1, speedControl1);
   //direct2 = manualSpeedControl(motorPinSpeed2, potPin2, rlyPin2, motorPinDir2, direct2, speedControl2);
   //direct3 = manualSpeedControl(motorPinSpeed3, potPin3, rlyPin3, motorPinDir3, direct3, speedControl3);
-
-    // print the string when a newline arrives:
-  if (stringComplete) {
-    Serial.println(inputString);
-    // clear the string:
-    inputString = "";
-    stringComplete = false;
-  }

   if (millis() - send_time >= 10) {
     send_time = millis();
@@ -107,11 +114,78 @@
   }
 }

+void read_status() {
+  stat.pitch_pos = analogRead(potPin1);
+  stat.yaw_pos = analogRead(potPin2);
+  stat.lid_pos = analogRead(potPin3);
+}
+
+void read_command() {
+  String  message = inputString; // holds text not yet split
+  int     delimPosition;  // the position of the next delim in the string
+  inputString = "";
+  stringComplete = false;
+  int i = 0;
+  do
+  {
+      String value;
+      delimPosition = message.indexOf(',');
+      if(delimPosition != -1)
+      {
+          value = message.substring(0,delimPosition);
+          message = message.substring(delimPosition+1, message.length());
+      }
+      else
+      {  // here after the last comma is found
+         if(message.length() > 0)
+           value = message;  // if there is text after the last comma
+      }
+      switch (i) {
+        case 0:
+          cmd.yaw_pwm = value.toInt();
+          break;
+        case 1:
+          cmd.yaw_direction = (value == "1" ? HIGH : LOW);
+          break;
+        case 2:
+          cmd.pitch_pwm = value.toInt();
+          break;
+        case 3:
+          cmd.pitch_direction = (value == "1" ? HIGH : LOW);
+          break;
+        case 4:
+          cmd.lid_pwm = value.toInt();
+          break;
+        case 5:
+          cmd.lid_direction = (value == "1" ? HIGH : LOW);
+          break;
+        default:
+          break;
+      }
+      i++;
+   }
+   while(delimPosition >=0);
+}
+
+void lcd_command() {
+  lcd.clear();
+  lcd.setCursor(0,0);
+  lcd.print("Y"+String(cmd.yaw_pwm)+" "+String(cmd.yaw_direction));
+}
+
+// Send command to the motors
+void do_command() {
+  analogWrite(motorPinSpeed1, cmd.pitch_pwm);
+  digitalWrite(motorPinDir1, cmd.pitch_direction);
+  analogWrite(motorPinSpeed2, cmd.yaw_pwm);
+  digitalWrite(motorPinDir2, cmd.yaw_direction);
+}
+
 void send_status() {
   statusString = "";
   statusString += "yaw_pos=" + String(stat.yaw_pos) + ";";
   statusString += "pitch_pos=" + String(stat.pitch_pos) + ";";
-  statusString += "lid_pos=" + String(stat.lid_pos) + ";";
+  statusString += "lid_pos=" + String(stat.lid_pos);
   Serial.println(statusString);
 }


cleanup

cleanup

--- firmware/beer/beersensor.ino
+++ firmware/beer/beersensor.ino
@@ -129,14 +129,11 @@
 {
 //   pinVal(pin0, &pin0Value, pin0Name);
 //   pinVal(pin1, &pin1Value, pin1Name);
-//   analogVal(pin2, &pin2Value, pin2Name);
 //   pinVal(pin3, &pin3Value, pin3Name);
 //   pinVal(pin4, &pin4Value, pin4Name);
-//   analogVal(pin4, &pin4Value, pin4Name);
 //   pinVal(pin5, &pin5Value, pin5Name);
   pinVal(pin6, &pin6Value, pin6Name);
-    //  analogVal(pin6, &pin6Value, pin6Name);
-//   delay(100);
+
   EEPROM.update(EEPROM_ADDR_PULSE_COUNT, pulseCount);
   float percent = (float)pulseCount / (float)maxPulseCount;
   percentFull = (int)(percent * 100.0f);
@@ -159,13 +156,6 @@
 {
   maxPulseCount = val;
   EEPROM.update(EEPROM_ADDR_MAX_PULSE_COUNT, maxPulseCount);
-}
-
-void analogVal(int pin, int* pinValue, String pinName)
-{
-    *pinValue = analogRead(pin);  // read the input pin
-    // Serial.println(pinName + ":" + String(*pinValue));
-    digitalWrite(ledPin, *pinValue/16);
 }

 void pinVal(int pin, int* pinValue, String pinName)
@@ -200,6 +190,13 @@
   }

 //   Serial.println(pinName + ":" + String(*pinValue));
+}
+
+void analogVal(int pin, int* pinValue, String pinName)
+{
+    *pinValue = analogRead(pin);  // read the input pin
+    // Serial.println(pinName + ":" + String(*pinValue));
+    digitalWrite(ledPin, *pinValue/16);
 }

 void setPixels(int instantPulseCount)


simplified the algorithm

simplified the algorithm

--- examples/Sequencer_example/Sequencer_example.ino
+++ examples/Sequencer_example/Sequencer_example.ino
@@ -6,13 +6,14 @@
 byte bpm = 120;
 int stepTime;
 byte curStep = 0;
-int playhead = 1;
+int playhead = 0;
 byte dur[] = {50, 50, 50, 50};
 byte numSteps = 4;

 void setup(){
   pinMode(LED, OUTPUT);
   pinMode(13, OUTPUT);
+  stepTime = 60000.f / bpm;
 }

 void loop(){
@@ -23,20 +24,22 @@

 void runSequence(){
   playhead++;
-  if(playhead > numSteps * stepTime) playhead = 1; // reset playhead
-  curStep = playhead / stepTime; // increment current step
+  if(playhead > stepTime){
+    playhead = 0;
+    curStep++;
+    if(curStep == numSteps) {curStep = 0;}
+  }
   // Gate CV output
- if(playhead % stepTime < stepTime * dur[curStep] / 100.f){
-   digitalWrite(GATEOUT, HIGH);
-   analogWrite(curStep+LED, 255-V);
- }
- else{
-   digitalWrite(GATEOUT, LOW);
-   analogWrite(curStep+LED, 255-LOW);
+  if(playhead < stepTime * dur[curStep] / 100.f){
+    digitalWrite(GATEOUT, HIGH);
+    analogWrite(curStep+LED, 255-V);
+  }
+  else{
+    digitalWrite(GATEOUT, LOW);
+    analogWrite(curStep+LED, 255-LOW);
  }

  dur[0] = analogRead(0) / 1024.f * 100;
  bpm = (analogRead(8) >> 3) + 30; // from 30 to 157 bpm
  stepTime = 60000.f / bpm;
-
 }


Improve formatting and layout

Improve formatting and layout

--- Sensors/GreenhouseSensor/greenhouse/greenhouse.ino
+++ Sensors/GreenhouseSensor/greenhouse/greenhouse.ino
@@ -1,23 +1,5 @@
+// The DHT library for the temp sensor (I used V 1.2.3 by adafruit)
 #include <DHT.h>
-
-/*
-  Web Server
-
- A simple web server that shows the value of the analog input pins.
- using an Arduino Wiznet Ethernet shield.
-
- Circuit:
- * Ethernet shield attached to pins 10, 11, 12, 13
- * Analog inputs attached to pins A0 through A5 (optional)
-
- created 18 Dec 2009
- by David A. Mellis
- modified 9 Apr 2012
- by Tom Igoe
- modified 02 Sept 2015
- by Arturo Guadalupi
-
- */

 #include <SPI.h>
 #include <Ethernet.h>
@@ -26,13 +8,17 @@
 // Data wire is plugged into port 7 on the Arduino
 // Connect a 4.7K resistor between VCC and the data pin (strong pullup)
 #define DHT22_PIN 7
-const int analogInPin = A1;  // LDR Pin

+// LDR Pin
+const int ldrInPin = A1;
+
+// Reseviour level pin
 const int switchPin = 8;

-int sensorValue = 0;        // value read from the pot
+// value for the temp sensor
+int rawLightValue = 0;        // value read from the pot

-int outputValue = 0;        // value output to the PWM (analog out)
+int outputLightValue = 0;        // value output to the PWM (analog out)

 int switchValue = LOW;
 // Setup a DHT22 instance
@@ -43,6 +29,7 @@
 byte mac[] = {
   0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
 };
+
 IPAddress ip(192, 168, 1, 44);

 // Initialize the Ethernet server library
@@ -63,11 +50,6 @@

 void loop() {
-    // The sensor can only be read from every 1-2s, and requires a minimum
-  // 2s warm-up after power-on.
-  delay(2000);
-
-
   // listen for incoming clients
   EthernetClient client = server.available();
   if (client) {
@@ -83,55 +65,7 @@
         // character) and the line is blank, the http request has ended,
         // so you can send a reply
         if (c == '\n' && currentLineIsBlank) {
-
-            // send a standard http response header
-            client.println("HTTP/1.1 200 OK");
-            client.println("Content-Type: application/xml");
-            client.println("Connection: close");  // the connection will be closed after completion of the response
-            client.println();
-            client.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
-            client.println("<prtg>");
-
-            switchValue = digitalRead(switchPin);
-
-
-            // read the analog in value:
-            sensorValue = analogRead(analogInPin);
-
-
-            // map it to the range of the analog out:
-            outputValue = map(sensorValue, 0, 800, 0, 100);
-            if(outputValue >100)
-            {
-              outputValue = 100;
-            }
-            client.print("<result><channel>Light</channel><unit>Percent</unit><float>1</float><value>");
-            client.print(outputValue);
-            client.println("</value></result>");
-
-               client.print("<result><channel>Reservoir</channel><valueLookup>developingtrends.greenhouse.reservoir</valueLookup><value>");
-            client.print(switchValue);
-            client.println("</value></result>");
-
-                client.print("<result><channel>Temperature</channel><unit>Custom</unit><customUnit>°C</customUnit><float>1</float><value>");
-                client.print(myDHT22.readTemperature());
-                client.print("</value></result><result><channel>Humidity</channel><unit>Percent</unit><float>1</float><value>");
-                client.print(myDHT22.readHumidity());
-                client.println("</value></result>");
-                // Alternately, with integer formatting which is clumsier but more compact to store and
-             // can be compared reliably for equality:
-              //
-          //      char buf[128];
-           //     sprintf(buf, "Integer-only reading: Temperature %hi.%01hi C, Humidity %i.%01i %% RH",
-           //                  myDHT22.getTemperatureCInt()/10, abs(myDHT22.getTemperatureCInt()%10),
-           //                  myDHT22.getHumidityInt()/10, myDHT22.getHumidityInt()%10);
-            //    client.println(buf);
-
-
-
-
-
-          client.println("</prtg>");
+          sendResponse(client);
           break;
         }
         if (c == '\n') {
@@ -151,3 +85,55 @@
   }
 }

+void sendResponse(EthernetClient client)
+{
+   // send a standard http response header
+  sendHeader(client);
+  client.println("<prtg>");
+  sendLightData(client);
+  sendResevoirData(client);
+  sendTempData(client);
+  client.println("</prtg>");
+}
+void sendHeader(EthernetClient client)
+{
+  client.println("HTTP/1.1 200 OK");
+  client.println("Content-Type: application/xml");
+  client.println("Connection: close");  // the connection will be closed after completion of the response
+  client.println();
+  client.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
+}
+
+void sendLightData(EthernetClient client)
+{
+    // read the analog in value:
+    rawLightValue = analogRead(ldrInPin);
+
+    // map it to the range of the analog out:
+    outputLightValue = map(rawLightValue, 0, 800, 0, 100);
+    // Cap it at 100%
+    if(outputLightValue >100)
+    {
+      outputLightValue = 100;
+    }
+
+    client.print("<result><channel>Light</channel><unit>Percent</unit><float>1</float><value>");
+    client.print(outputLightValue);
+    client.println("</value></result>");
+}
+
+void sendTempData(EthernetClient client)
+{
+    client.print("<result><channel>Temperature</channel><unit>Custom</unit><customUnit>°C</customUnit><float>1</float><value>");
+    client.print(myDHT22.readTemperature());
+    client.print("</value></result><result><channel>Humidity</channel><unit>Percent</unit><float>1</float><value>");
+    client.print(myDHT22.readHumidity());
+    client.println("</value></result>");
+}
+void sendResevoirData(EthernetClient client)
+{
+  switchValue = digitalRead(switchPin);
+  client.print("<result><channel>Reservoir</channel><valueLookup>developingtrends.greenhouse.reservoir</valueLookup><value>");
+  client.print(switchValue);
+  client.println("</value></result>");
+}


Added Lucas' latest damping code.

Added Lucas' latest damping code.

--- src/MonsterSketch/MonsterSketch.ino
+++ src/MonsterSketch/MonsterSketch.ino
@@ -87,7 +87,7 @@

   ///  will need to move these to the update loop once they're inputing values dynamically
   /////////////////////////////springValue (usually small- (0.001-.1)
-  springValue = 0.01;
+  springValue = 0.03;
   /////////////////////////////////////////////////////////////////////

   ////////////////////////////dampening value (1= no dampening, 0 = full dampening (no movement)) Usually .9 or so.
@@ -270,7 +270,15 @@
   for (int i=0; i<5; i++){
     location[i] = location[i] + velocity[i];
   }
-
+
+ ///// Set Dampening couter/reset
+dampening = (dampening - 0.0005);
+if (dampening < 0.6){
+  dampening = 0.6;
+}
+if (g_bGotTweet == true){
+ dampening = 1.0;
+}

   // Orient the robot towards the object


Publish state on startup/reconnect

Publish state on startup/reconnect

--- arduinoHouse/mqttRelayWithState/mqttRelayWithState.ino
+++ arduinoHouse/mqttRelayWithState/mqttRelayWithState.ino
@@ -1,16 +1,16 @@

 /*
- * MQTT 32 output pins for driving 2 16-channel relay boards on an arduino mega with ethernet shield.
- *
- * NOTE: the topic is hardcoded: domogik/in/relay/r + relay number : e.g
- *
- * mosquitto_pub -t domogik/in/relay/r1 -m 1  -> turn on
- * mosquitto_pub -t domogik/in/relay/r1 -m 0  -> turn off
- * mosquitto_pub -t domogik/in/relay/r1 -m 2  -> toggle; so turn on again
- *
+   MQTT 32 output pins for driving 2 16-channel relay boards on an arduino mega with ethernet shield.
+
+   NOTE: the topic is hardcoded: domogik/in/relay/r + relay number : e.g
+
+   mosquitto_pub -t domogik/in/relay/r1 -m 1  -> turn on
+   mosquitto_pub -t domogik/in/relay/r1 -m 0  -> turn off
+   mosquitto_pub -t domogik/in/relay/r1 -m 2  -> toggle; so turn on again
+
   By Jeroen Schaeken
   Derived from http://www.esp8266.com/viewtopic.php?f=29&t=8746
-
+
   It connects to an MQTT server then:
   - on 0 switches off relay
   - on 1 switches on relay
@@ -75,41 +75,40 @@
 void switchRelay(char* switchState, int pos) {
   // Switch on the LED if an 1 was received as first character
   if (switchState == '0') {
-    digitalWrite(relayPins[pos], HIGH);
+    digitalWrite(relayPins[pos], HIGH);
     relayStates[pos] = HIGH;
     EEPROM.update(pos, relayStates[pos]);    // Write state to EEPROM
   } else if (switchState == '1') {
-    digitalWrite(relayPins[pos], LOW);
+    digitalWrite(relayPins[pos], LOW);
     relayStates[pos] = LOW;
     EEPROM.update(pos, relayStates[pos]);    // Write state to EEPROM
-  }
-}
-
-void mutuallyExcludePair(char* switchState, int pos){
+  }
+}
+
+void publishRelayState(int relayNbr, char* state) {
+  char outputTopicBuff[100];
+  strcpy(outputTopicBuff, outRelayTopic);
+  char relaybuffer[5];
+  sprintf(relaybuffer, "%d", relayNbr);
+  strcat(outputTopicBuff, relaybuffer);
+  client.publish(outputTopicBuff, state);
+}
+
+void mutuallyExcludePair(char* switchState, int pos) {
   if (pos % 2 == 0 && switchState == '1') //even
-   {
-     if (pinCount > (pos + 1) && relayStates[pos + 1] == LOW){
+  {
+    if (pinCount > (pos + 1) && relayStates[pos + 1] == LOW) {
       switchRelay('0', pos + 1);
-      char outputTopicBuff[100];
-      strcpy(outputTopicBuff,outRelayTopic);
-      char relaybuffer[5];
-      sprintf(relaybuffer, "%d", pos + 2);
-      strcat(outputTopicBuff,relaybuffer);
-      client.publish(outputTopicBuff, "0");
-     }
-   }
+      publishRelayState(pos + 2, "0");
+    }
+  }
   else if (pos % 2 == 1 && switchState == '1') //odd
-   {
-     if ((pos - 1) >= 0 && relayStates[pos - 1] == LOW){
+  {
+    if ((pos - 1) >= 0 && relayStates[pos - 1] == LOW) {
       switchRelay('0', pos - 1);
-      char outputTopicBuff[100];
-      strcpy(outputTopicBuff,outRelayTopic);
-      char relaybuffer[5];
-      sprintf(relaybuffer, "%d", pos);
-      strcat(outputTopicBuff,relaybuffer);
-      client.publish(outputTopicBuff, "0");
-     }
-   }
+      publishRelayState(pos, "0");
+    }
+  }
 }

 void callback(char* topic, byte* payload, unsigned int length) {
@@ -127,7 +126,7 @@
   char* switchState = (char)payload[0];

   if (switchState == '2') {
-    if (relayStates[posInArray] == HIGH){
+    if (relayStates[posInArray] == HIGH) {
       switchState = '1';
     }
     else {
@@ -135,8 +134,8 @@
     }
   }

-  if (isMutuallyExclude){
-   mutuallyExcludePair(switchState, posInArray);
+  if (isMutuallyExclude) {
+    mutuallyExcludePair(switchState, posInArray);
   }
   switchRelay(switchState, posInArray);

@@ -147,6 +146,10 @@
     if (client.connect("RelayboardClient")) {
       Serial.println("connected");
       client.publish(outTopic, "RelayBoard booted");
+      for (int thisPin = 0; thisPin < pinCount; thisPin++) {
+        char* state = relayStates[thisPin] == HIGH ? "0" : "1";
+        publishRelayState(thisPin + 1, state);
+      }
       client.subscribe(inTopic);
     } else {
       Serial.print("failed, rc=");
@@ -176,13 +179,13 @@
     digitalWrite(relayPins[thisPin], relayStates[thisPin]);
   }

-  digitalWrite(13, LOW);
+  digitalWrite(13, LOW);
   delay(500);
   digitalWrite(13, HIGH);
   delay(500);

   Serial.begin(115200);
-  setup_ethernet();
+  setup_ethernet();
   client.setServer(server, 1883);
   client.setCallback(callback);
 }


Expand NTP-TZ-DST example to list SNTP servers (#6611)

This change expands the NTP-TZ-DST example to list the active
SNTP servers. It lists the IP address server name (if used) and
reachability in ntpq style octal format.

Tests:
 - Build against all LwIP stack configurations and correct
   operation with a single SNTP server
 - Vary connectivity to an SNTP server and check reachability
   updates
 - Configure 3 SNTP servers by name
 - With a patched LwIP stack that supports simultaneous DHCP
   and DHCPv6 SNTP servers check that all server details are
   listed and update correctly during operation

--- libraries/esp8266/examples/NTP-TZ-DST/NTP-TZ-DST.ino
+++ libraries/esp8266/examples/NTP-TZ-DST/NTP-TZ-DST.ino
@@ -129,6 +129,25 @@
   // human readable
   Serial.print("ctime:     ");
   Serial.print(ctime(&now));
+
+#if LWIP_VERSION_MAJOR > 1
+  // LwIP v2 is able to list more details about the currently configured SNTP servers
+  for (int i = 0; i < SNTP_MAX_SERVERS; i++) {
+    IPAddress sntp = *sntp_getserver(i);
+    const char* name = sntp_getservername(i);
+    if (sntp.isSet()) {
+      Serial.printf("sntp%d:     ", i);
+      if (name) {
+        Serial.printf("%s (%s) ", name, sntp.toString().c_str());
+      } else {
+        Serial.printf("%s ", sntp.toString().c_str());
+      }
+      Serial.printf("IPv6: %s Reachability: %o\n",
+                    sntp.isV6() ? "Yes" : "No",
+                    sntp_getreachability(i));
+    }
+  }
+#endif

   Serial.println();
 }


added LED signal to HTTP request

added LED signal to HTTP request

--- T0/src/AFE-HTTP-API-listener.ino
+++ T0/src/AFE-HTTP-API-listener.ino
@@ -39,6 +39,7 @@
 /* Method processes HTTP API request */
 void processHTTPAPIRequest(HTTPCOMMAND request) {

+  Led.on();
   /* Checking of request is about a relay */
   if (strcmp(request.device, "relay") == 0) {
     /* Checking Relay #0 */
@@ -91,4 +92,5 @@
   } else {
     sendHTTPAPIRequestStatus(request, false);
   }
+  Led.off();
 }


added random distribution test

added random distribution test


Just save a snap

Just save a snap

--- sketch_yunba/sketch_yunba.ino
+++ sketch_yunba/sketch_yunba.ino
@@ -6,43 +6,43 @@
 const char *g_topic = "office";
 const char *g_devid = "plug_plc";

-#define BUFSIZE 192
-#define JSON_BUFSIZE 96
+#define BUFSIZE 128
+#define JSON_BUFSIZE 168
 #define PIN_CONTROL 4

 uint8_t mac[] = {0xb0, 0x5a, 0xda, 0x3a, 0x2e, 0x7e};

-boolean g_net_status = false;
-char url[24];
-
-char broker_addr[24];
-uint16_t port;
-
-unsigned int g_last_check_ms = 0;
+bool g_net_status = false;
+char g_url[32];
+
+char g_addr[32];
+uint16_t g_port;
+
+unsigned long g_last_check_ms = 0;
 char client_id[32];
 char username[24];
 char password[16];

-EthernetClient net;
+EthernetClient *mqtt_net_client;
 MQTTClient *mqtt_client;

 uint8_t g_status = 0;

-bool get_ip_port(const char *url, char *addr, uint16_t *port) {
-  char *p = strstr(url, "tcp://");
+bool get_ip_port() {
+  char *p = strstr(g_url, "tcp://");
   if (p) {
     p += 6;
     char *q = strchr(p, ':');
     if (q) {
       int len = strlen(p) - strlen(q);
       if (len > 0) {
-        memcpy(addr, p, len);
-        *port = atoi(q + 1);
+        memcpy(g_addr, p, len);
+        g_port = (uint16_t)atoi(q + 1);
 #if 0
         Serial.print("i:");
-        Serial.println(addr);
+        Serial.println(g_addr);
         Serial.print("p:");
-        Serial.println(*port);
+        Serial.println(g_port);
 #endif
         return true;
       }
@@ -78,19 +78,16 @@
   net_client.stop();
 }

-bool get_host_v2(const char *appkey, char *url) {
-  uint8_t buf[BUFSIZE] = {0};
-
-  String data("{\"a\":\"");
-  data += String(appkey);
-  data += String("\",\"n\":\"1\",\"v\":\"v1.0\",\"o\":\"1\"}");
-  uint16_t len = data.length();
+bool get_host_v2() {
+  uint8_t buf[BUFSIZE];
+  uint16_t len;
+
+  len = snprintf((char *)buf + 3, BUFSIZE - 3, "{\"a\":\"%s\",\"n\":\"1\",\"v\":\"v1.0\",\"o\":\"1\"}", g_appkey);

   buf[0] = 1;
   buf[1] = (uint8_t)((len >> 8) & 0xff);
   buf[2] = (uint8_t)(len & 0xff);

-  memcpy(buf + 3, data.c_str(), len);
   len += 3;

   buf[len] = 0;
@@ -105,7 +102,7 @@
       StaticJsonBuffer<JSON_BUFSIZE> jsonBuffer;
       JsonObject& root = jsonBuffer.parseObject(p);
       if (root.success()) {
-        strcpy(url, root["c"]);
+        strcpy(g_url, root["c"]);
         return true;
       }
     }
@@ -114,28 +111,16 @@
   return false;
 }

-bool setup_with_appkey_and_devid(const char *appkey, const char *devid) {
+bool setup_with_appkey_and_devid() {
   uint8_t buf[BUFSIZE];
-
-  if (appkey == NULL) return false;
-
-  String data("{\"a\": \"");
-  data += String(appkey);
-
-  if (devid == NULL) {
-    data += String("\", \"p\":4}");
-  } else {
-    data += String("\", \"p\":4, \"d\": \"");
-    data += String(devid);
-    data += String("\"}");
-  }
-  uint16_t len = data.length();
+  uint16_t len;
+
+  len = snprintf((char *)buf + 3, BUFSIZE - 3, "{\"a\":\"%s\",\"p\":4,\"d\":\"%s\"}", g_appkey, g_devid);

   buf[0] = 1;
   buf[1] = (uint8_t)((len >> 8) & 0xff);
   buf[2] = (uint8_t)(len & 0xff);

-  memcpy(buf + 3, data.c_str(), len);
   len += 3;

   buf[len] = 0;
@@ -162,37 +147,28 @@
   return false;
 }

-void set_alias(const char *alias) {
-  mqtt_client->publish(",yali", alias);
-}
-
-void mqtt_connect() {
-  Serial.println("cn.."); // connecting
-  while (!mqtt_client->connect(client_id, username, password)) {
-    Serial.println("..");
-    delay(1000);
-  }
-
-  Serial.println("co"); // connect ok
-
-//  mqtt_client->subscribe(g_topic);
-  set_alias(g_devid);
+void mqtt_init() {
+
 }

 void check_connect() {
   if (millis() - g_last_check_ms > 2000) {
-    boolean st = mqtt_client->connected();
-//    Serial.println(st);
+    bool st = mqtt_client->connected();
+    Serial.print("cs:");
+    Serial.println(st);
+
     if (st != g_net_status) {
-      Serial.print("cs:");
       g_net_status = st;
-      Serial.println(g_net_status);
     }

     if (!st) {
-      mqtt_client->disconnect();
-      delete(mqtt_client);
-      init_network();
+ //     mqtt_client->disconnect();
+ //     delete(mqtt_client);
+ //     delete(mqtt_net_client);
+ //     mqtt_client = 0;
+ //     mqtt_net_client = 0;
+      init_ethernet();
+      connect_yunba();
     }
     g_last_check_ms = millis();
   }
@@ -217,17 +193,15 @@
 }

 void report_status() {
-  String data("{\"status\":");
-  data += String(g_status);
-  data += String(",\"devid\":\"");
-  data += String(g_devid);
-  data += String("\"}");
-
-  Serial.println(data);
-  mqtt_client->publish(g_topic, data.c_str());
+  uint8_t buf[BUFSIZE];
+
+  snprintf((char *)buf, BUFSIZE, "{\"status\":%d,\"devid\":\"%s\"}", g_status, g_devid);
+  Serial.println((char *)buf);
+  mqtt_client->publish(g_topic, (char *)buf);
 }

 void messageReceived(String topic, String payload, char *bytes, unsigned int length) {
+  #if 0
   StaticJsonBuffer<JSON_BUFSIZE> jsonBuffer;

   bytes[length] = 0;
@@ -250,6 +224,7 @@
   } else if (strcmp(root["cmd"], "plug_get") == 0) {
     report_status();
   }
+  #endif
 }

 void extMessageReceived(EXTED_CMD cmd, int status, String payload, unsigned int length) {
@@ -278,31 +253,57 @@
 #endif
 }

-void init_network() {
-  init_ethernet();
-
-  //TODO: if we can't get reg info and tick info
-  get_host_v2(g_appkey, url);
-  get_ip_port(url, broker_addr, &port);
-
-  setup_with_appkey_and_devid(g_appkey, g_devid);
-
-  mqtt_client->begin(broker_addr, port, net);
-  mqtt_connect();
+void init_yunba() {
+  get_host_v2();
+  get_ip_port();
+  setup_with_appkey_and_devid();
+
+  mqtt_net_client = new EthernetClient();
+  mqtt_client = new MQTTClient();
+  mqtt_client->begin(g_addr, g_port, *mqtt_net_client);
+
+#if 1
+  Serial.println(g_addr);
+  Serial.println(g_port);
+#endif
+
+  Serial.println("=1");
+  Serial.println("=2");
+}
+
+void connect_yunba() {
+    Serial.println("cn.."); // connecting
+#if 1
+  Serial.println(client_id);
+  Serial.println(username);
+  Serial.println(password);
+#endif
+  while (!mqtt_client->connect(client_id, username, password)) {
+    Serial.println("..");
+    delay(1000);
+  }
+
+  g_last_check_ms = millis();
+  Serial.println("co"); // connect ok
+
+//  mqtt_client->subscribe(g_topic);
+  mqtt_client->publish(",yali", g_devid); // set alias
+  Serial.println("=3");
 }

 void setup() {

   Serial.begin(57600);
-  Serial.println("in.."); // init
+  Serial.println("st.."); // setup

   pinMode(PIN_CONTROL, OUTPUT);
   digitalWrite(PIN_CONTROL, LOW);

-  mqtt_client = new MQTTClient();
-  init_network();
-
-  Serial.println("io"); // init ok
+  init_ethernet();
+
+  init_yunba();
+
+  Serial.println("so"); // init ok
 }

 void loop() {


Update Firmware.ino

Update Firmware.ino

--- src/piggy_back_loggers/SD_prototype_Firmware/Firmware/Firmware.ino
+++ src/piggy_back_loggers/SD_prototype_Firmware/Firmware/Firmware.ino
@@ -62,6 +62,16 @@
 #include "powerSleep.h"
 #include "state.h"
 #include "RTC_PCF8523.h"
+#include "storeNewRecord.h"
+
+// These six macros below are the ten's place mask for the various real time clock registers
+#define SECONDS_REG_MASK 0x7                            // keep lower 3 bits
+#define MINUTES_REG_MASK 0x7
+#define HOURS_REG_MASK   0x3                            // keep lower 2 bits
+#define DAYS_REG_MASK    0x3
+#define MONTHS_REG_MASK  0x1                            // keep lower 1 bit
+#define YEARS_REG_MASK   0xF                            // keep all four bits
+

 /*********************************************************************************\
  * Setup:
@@ -131,17 +141,10 @@
   /*****************************************\
   * 4-second update: Update at 4 seconds
   * If 4-second flag is set:
-  *   <Pseudocode> (I would recommend
-  *                 putting this in a
-  *                 function)
+  *   Store a new record
   \*****************************************/
   if(State.flag4)
-  {
-    State.flag4 = false;
-    rtcTransfer(reg_Control_2, WRITE, 0x02);
-  }
-    // Daniel's function
-      // Don't forget to clear flag on RTC!
+    storeNewRecord();

   // JOSH
   /*****************************************\
@@ -180,3 +183,173 @@
 {
   State.flag4 = true;     // sets the "four second flag" to true
 }
+
+/* Function: storeNewRecord
+ *
+ * Author: Daniel Henshaw
+ * Date: 11/10/18
+ *
+ * Description: This function gets the current time from the Real Time Clock, and then
+ *              carries out the communication to write a new record to the SD card and
+ *              then turns off the I2C and SD card.
+ *
+ * Pseudocode:
+ *
+ * Begin
+ *   Reset flag4 to zero
+ *   Reset real time clock interrupt flag
+ *   Declare variables
+ *   Store pulse count to a variable named final count
+ *   Set pulseCount to zero
+ *   Read current time from the Real Time Clock and update the Date struct with the current time
+ *     turn on the I2C interface (function rtcTransfer does this for us)
+ *       read the year and store into temp variable
+ *       convert from binary-coded decimal into binary, and store into years field of Date struct
+ *       read the month and store into temp variable
+ *       convert from binary-coded decimal into binary, and store into months field of Date struct
+ *       read the day and store into temp variable
+ *       convert from binary-coded decimal into binary, and store into days field of Date struct
+ *       read the hour and store into temp variable
+ *       convert from binary-coded decimal into binary, and store into hours field of Date struct
+ *       read the minutes and store into temp variable
+ *       convert from binary-coded decimal into binary, and store into minutes field of Date struct
+ *       read the seconds and store into temp variable
+ *       convert from binary-coded decimal into binary, and store into seconds field of Date struct
+ *     turn off the I2C interface (function rtcTransfer does this for us)
+ *   Write the new record to the SD card
+ *     power on SD card
+ *       write new record to SD card
+ *         open the date-time string by writing a double quotation mark
+ *           write year, month, day, hours,
+ *           if minutes is less than ten
+ *           then
+ *             write a leading zero (the minutes value will be appended to it by the next statement)
+ *           endIf
+ *           write the minutes
+ *           if seconds is less than ten
+ *           then
+ *             write a leading zero (the seconds value will be appended to it by the next statement)
+ *           endIf
+ *           write the seconds
+ *         close the date-time string by writing a double quotation mark
+ *         write a comma to begin a new field (CSV file format)
+ *         write the record number
+ *         write a comma to begin a new field (CSV file format)
+ *         write the number of pulses counted when function was called (finalCount)
+ *       end of writing the record to SD card
+ *     power down SD card
+ * End of function storeNewRecord()
+ */
+
+
+
+void storeNewRecord()
+{                                                       // Begin
+    State.flag4 = 0;                                    //     Reset flag4 to zero
+    rtcTransfer(reg_Control_2, WRITE, 0x02);            //     Reset real time clock interrupt flag
+    byte finalCount;                                    //     Declare variables
+    byte temp;
+    finalCount = State.pulseCount;                      //     Store pulse count to a variable named final count
+    State.pulseCount = 0;                               //     Set pulseCount to zero
+                                                        //     Read current time from the Real Time Clock and update the Date struct with the current time
+      temp         = rtcTransfer(reg_Years,  READ, 0);  //         read the Years and store into temp variable
+      Date.years   = bcdtobin(temp, YEARS_REG_MASK);    //         convert from binary-coded decimal into binary, and store into years field of Date struct
+      temp         = rtcTransfer(reg_Months, READ, 0);  //         read the Months and store into temp variable
+      Date.months  = bcdtobin(temp, MONTHS_REG_MASK);   //         convert from binary-coded decimal into binary, and store into months field of Date struct
+      temp         = rtcTransfer(reg_Days,   READ, 0);  //         read the Days and store into temp variable
+      Date.days    = bcdtobin(temp, DAYS_REG_MASK);     //         convert from binary-coded decimal into binary, and store into days field of Date struct
+      temp         = rtcTransfer(reg_Hours,  READ, 0);  //         read the Hours and store into temp variable
+      Date.hours   = bcdtobin(temp, HOURS_REG_MASK);    //         convert from binary-coded decimal into binary, and store into hours field of Date struct
+      temp         = rtcTransfer(reg_Minutes,READ, 0);  //         read the Minutes and store into temp variable
+      Date.minutes = bcdtobin(temp, MINUTES_REG_MASK);  //         convert from binary-coded decimal into binary, and store into minutes field of Date struct
+      temp         = rtcTransfer(reg_Seconds,READ, 0);  //         read the Seconds and store into temp variable
+      Date.seconds = bcdtobin(temp, SECONDS_REG_MASK);  //         convert from binary-coded decimal into binary, and store into seconds field of Date struct
+                                                        //     Write the new record to the SD card
+      SDPowerUp();                                      //         power on SD card
+                                                        //         Write new record to SD card
+        dataFile.print('\"'));                          //           open the date-time string by writing a double quotation mark
+        dataFile.print(Date.years);                     //             write year, month, day, hours
+        dataFile.print('-');
+        dataFile.print(Date.months);
+        dataFile.print('-');
+        dataFile.print(Date.days);
+        dataFile.print(' ');
+        dataFile.print(Date.hours);
+        dataFile.print(':');
+        if(Date.minutes < 10)                           //             if minutes is less than ten
+        {                                               //             then
+          dataFile.print('0');                         //               write a leading zero (the minutes value will be appended to it by the next statement)
+        }                                               //             endIf
+        dataFile.print(Date.minutes);                   //             write the minutes
+        if(Date.seconds < 10)                           //             if seconds is less than ten
+        {                                               //             then
+          dataFile.print('0');                         //               write a leading zero (the seconds value will be appended to it by the next statement)
+        }                                               //             endIf
+        dataFile.print(':');                            //             write a colon to separate minutes from seconds
+        dataFile.print(Date.seconds);                   //             write the seconds
+        dataFile.print('\"');                           //           close date-time string by writing a double quotation mark
+        dataFile.print(',');                            //           write a comma to begin a new field (CSV file format)
+        dataFile.print(State.recordNum);                //           write the record number
+        dataFile.print(',');                            //           write a comma to begin a new field (CSV file format)
+        dataFile.println(finalCount);                   //           write the number of pulses counted when function was called (finalCount) and then print a new line
+                                                        //         end of writing the record to SD card
+      SDPowerDown();                                    //       power down SD card
+}                                                       // End of function storeNewRecord()
+
+
+
+
+
+
+/* Function: bcdtobin
+ *
+ * Author: Daniel Henshaw
+ * Date: 11/17/18
+ *
+ * Description: This function converts Binary Coded Decimal (BCD) numbers to
+ *              standard binary format. This is particularly useful when working
+ *              with the real time clock, which stores time data in BCD format
+ *              in its registers. The function takes in the value to convert, and
+ *              the source register the value is coming from. The source register
+ *              is required so that the conversion will be compatible with the
+ *              number of bits into which the BCD value is stored into the RTC's
+ *              registers.
+ *
+ * Optional dependencies: set of macro definitions, included below, improve
+ *              this function's usability or user friendliness. These make it
+ *              straightforward for the user to specify from which register
+ *              the data is coming from. These also do double duty as masks for the
+ *              value, as not all 8 bits in the register are for the BCD value; some
+ *              of the upper bits serve other purposes or are "unused"
+ *              (see datasheet for PCF8523 by NXP).
+ *
+ *              #define SECONDS_REG_MASK 0x7
+ *              #define MINUTES_REG_MASK 0x7
+ *              #define HOURS_REG_MASK   0x3
+ *              #define DAYS_REG_MASK    0x3
+ *              #define MONTHS_REG_MASK  0x1
+ *              #define YEARS_REG_MASK   0xF
+ *
+ * Pseudocode:
+ *
+ * Begin
+ *   Declare variable
+ *   shift right by four the bcdValue (Puts upper 4 bits at the bottom)
+ *   tensPlace is tensPlace ANDed with the provided bit mask a.k.a. conversion constant (hexadecimal value)
+ *   Return the binary value result (the unit's place plus tensPlace times ten)
+ * End
+ */
+
+byte bcdtobin(byte bcdValue, byte sourceReg)
+{
+  byte tensPlace;
+
+  tensPlace  = bcdValue >> 4;
+  tensPlace &= sourceReg;         /* NOTE: sourceReg is actually a bit mask */
+
+  return (bcdValue & 0x0F) + (tensPlace * 10); // return the binary value result:
+                                               //   step 1) First parenthesis: bcdValue ANDed with mask 0xF gives us the one's place,
+                                               //   step 2) Second parenthesis: move the ten's place value over by multiplying by ten
+                                               //   step 3) Add the first parenthesis group to the second parenthesis group
+}
+


Update Firmware.ino

Update Firmware.ino

--- src/piggy_back_loggers/SD_prototype_Firmware/Firmware/Firmware.ino
+++ src/piggy_back_loggers/SD_prototype_Firmware/Firmware/Firmware.ino
@@ -50,9 +50,9 @@
 *      Repeat Loop
 *
 * Interrupts:
-*   1. INT0 ()
+*   1. INT0_ISR()
 *
-*   2. INT1 ()
+*   2. INT1_ISR()
 *
 \*********************************************************/

@@ -61,11 +61,12 @@
 #include "handleSerial.h"
 #include "powerSleep.h"
 #include "state.h"
+#include "RTC_PCF8523.h"

 // DANIEL
 /*********************************************************************************\
  * Setup:
- *    System State structure
+ *    System State structure      Complete
  *    Setup Digital I/O pins
  *      Pin 2 (INT0)
  *      Pin 3 (INT1)
@@ -74,13 +75,14 @@
  *    Setup interrupts
 \*********************************************************************************/

-State_t State;                    // System State structure
+volatile State_t State;           // System State structure
+Date_t Date;                      // System Time and Date structure
 File dataFile;                    // File pointer for SD Card operations

 void setup()
 {
   resetState(&State);             // Setup the System State structure
-
+                                  // Load Date_t with Date/Time info
   disableUnneededPeripherals();   // Disable unneeded peripherals
 }

@@ -93,7 +95,7 @@
   *   Set serialOn flag.
   *   call serialPowerUp()
   \*****************************************/
-  if((digitalRead(5) == 0) && !State.serialOn)
+  if(/*(digitalRead(5) == 0) && */!State.serialOn)
   {
     State.serialOn = true;
     serialPowerUp();
@@ -106,7 +108,7 @@
   *   call function handleSerial();
   \*****************************************/
   if(State.serialOn)
-    handleSerial(&State);
+    handleSerial(&State, &Date);

   // DANIEL
   /*****************************************\
@@ -127,3 +129,30 @@
   if(!State.serialOn)
     enterSleep();
 }
+
+// DANIEL
+/* Function Title: INT0_ISR()
+ *
+ * Friendly Name:  Sensor Interrupt Service Routine (ISR)
+ *
+ * Description: increments the value of the pulse count variable by one, each time this
+ *              function is called by hardware.
+ */
+void INT0_ISR()
+{
+  State.pulseCount += 1;  // increment pulseCount variable by one
+}
+
+// DANIEL
+/* Function Title: INT1_ISR()
+ *
+ * Friendly Name:  Real Time Clock OUT Interrupt Service Routine (ISR)
+ *
+ * Description: sets the 4-second flag to true each time this function
+ *              is called by hardware. The Real Time Clock generates
+ *              the signal that calls this ISR once every four seconds.
+ */
+void INT1_ISR()
+{
+  State.flag4 = true;     // sets the "four second flag" to true
+}