Write the LEDButton to its own library

Write the LEDButton to its own library

--- Dremelfuge.ino
+++ Dremelfuge.ino
@@ -1,43 +1,3 @@
-#include "Button.h"
-
-class LEDButton : public Button
-{
-  private:
-    const uint8_t ledOutPin;
-
-    bool ledState;
-  public:
-    // call Button(int, int) constructor using constructor initialization list, setting inherited member data for you
-    LEDButton(const uint8_t pin, const uint8_t ledOutPin, uint16_t debounceDelay=500) : Button(pin, false, debounceDelay), ledOutPin(ledOutPin)
-    {
-      //LED off by default
-      ledState = LOW;
-    }
-
-    void ledOn()
-    {
-      ledState = HIGH;
-      digitalWrite(ledOutPin, ledState);
-    }
-    void ledOff()
-    {
-      ledState = LOW;
-      digitalWrite(ledOutPin, ledState);
-    }
-    void ledToggle()
-    {
-      ledState = !ledState;
-      digitalWrite(ledOutPin, ledState);
-    }
-
-    void begin()
-    {
-      Button::begin();                      // call base class version of begin()
-      pinMode(ledOutPin, OUTPUT);
-      digitalWrite(ledOutPin, ledState);
-    }
-};
-
 /*
 Dremelfuge ETC Project 2015-2016
 Adapted from Orlov's Instructable on Arduino Powered Centrifuge
@@ -46,9 +6,12 @@
 */

 #include <LiquidCrystal.h>               // include the library code for display
+                                         // because it's a file inside of the Arduino.app 's library folder, use <> DIRECTIVE
+#include "LEDButton.h"                   // include custom library local to the .ino--within the same sketch folder
+                                         // because it's a relative path in the same directory, use "" LITERAL PATHNAME

 //---GLOBAL VARIABLES--//
-//*** these variables MUST be global because they're being used by multiple totally separate functions--static local won't do
+//:: ***these variables MUST be global because they're being used by multiple totally separate functions--static local won't do
 LiquidCrystal lcd = LiquidCrystal(12, 11, 5, 4, 3, 6);   // initialize the library with the numbers of the interface pins

 // White Pushbutton
@@ -74,14 +37,14 @@
 inline void lcdPrintFormattedSecs(unsigned long seconds);

 void setup()
-{
+{
   const uint8_t LCD_COLUMNS = 20, LCD_ROWS = 4;

   wpb.begin();
-  wpb.ledOn();
-
+  wpb.turnLEDOn();
+
   pinMode(MOTOR_PIN, OUTPUT);
-  pinMode(POT_PIN, INPUT);
+  pinMode(POT_PIN, INPUT);

   lcd.begin(LCD_COLUMNS, LCD_ROWS);
   lcd.setCursor(0, 0);
@@ -109,12 +72,12 @@
     case Mode::SETTING_TIME:
     {
       countdown = map(analogRead(POT_PIN), 0, 1024, 0, 901);
-
+
       lcd.setCursor(0, 1);
       lcd.print(F("Set time: <"));
       lcdPrintFormattedSecs(countdown);
       lcd.print(F(">   "));
-
+
       if(wpb.pressed())
       {
         // then implicitly set in stone the countdown value, change display, and enter next block
@@ -124,7 +87,7 @@
         lcd.setCursor(10, 1);
         lcdPrintFormattedSecs(countdown);
         lcd.print(F("    "));
-
+
         countdown*= (long)1000;                       //*** to save space, the ATmega328P chip of UNO uses 2-byte ints, which can hold at max 32 767; operator*(int, int) will still return an int, but in this case an overflowed int;
                                                       //*** initSetTime, a long, will just be assigned the overflowed value--it won't force operator*(int, int) to return a long.
                                                       //*** so, by typecasting 1000 or using 1000L, you make the compiler promote analogRead() to a long, so operator*(long, long) will return the expected value, within range of sizeof long
@@ -132,18 +95,18 @@
       }
       break;
     }
-
-
+
+
     case Mode::SETTING_SPEED:
     {
       motorSpeed = map(analogRead(POT_PIN), 0, 1024, 0, 255);
-
+
       lcd.setCursor(11, 2);
       lcd.print(F("<"));
       //map printing of motorSpeed to rpm range?!
       lcd.print(motorSpeed);
       lcd.print(F(">  "));
-
+
       if(wpb.pressed())
       {
         // then implicitly set in stone the motorSpeed value, change display, pre-start the countdown, and switch block
@@ -152,25 +115,25 @@
         lcd.setCursor(11, 2);
         lcd.print(motorSpeed);
         lcd.print(F("  "));
-
+
         spinningStartTime = millis();
-
+
         mode = Mode::SPINNING;
       }
       break;
     }
-
-
+
+
     case Mode::SPINNING:
     {
       unsigned long secondsLeft = (countdown - (millis() - spinningStartTime))/1000;  //*** save RAM AND flash memory by only doing this calculation once per case in loop()
       analogWrite(MOTOR_PIN, motorSpeed);
-
+
       lcd.setCursor(0, 1);
       lcd.print(F("Finished in: "));
       lcdPrintFormattedSecs(secondsLeft);
       lcd.print(F("  "));
-
+
       if(wpb.pressed() || secondsLeft == 0)
       {
         digitalWrite(MOTOR_PIN, LOW);
@@ -178,11 +141,11 @@
       }
       break;
     }
-  }
-}
+  }
+}

 inline void lcdPrintFormattedSecs(unsigned long seconds) //*** inline = suggestion to the compiler to paste the raw code of this function wherever it's called == performance optimization, no hopping pointers to callers and callbacks
 {
-  //***
+  //***
   lcd.print(seconds/60); lcd.print(F(":")); lcd.print((seconds%60 < 10 ? F("0") : F(""))); lcd.print(seconds%60);
 }


Fixed compilation

Fixed compilation

--- testsuite/REV20Motor/REV20Motor.ino
+++ testsuite/REV20Motor/REV20Motor.ino
@@ -122,7 +122,8 @@
 //// Suppress unnecessary activity when room dark, eg to avoid disturbance if device crashes/restarts,
 //// unless recent UI use because value is being fitted/adjusted.
 //ValveDirect_t ValveDirect([](){return(AmbLight.isRoomDark());});
-OTRadValve::DRV8850HardwareDriver<m1, m2, motorNSleep, 1, MOTOR_DRIVE_MC_AIN> motorDriver;
+OTRadValve::ValveMotorDirectV1HardwareDriver<m1, m2, MOTOR_DRIVE_MI_AIN, MOTOR_DRIVE_MC_AIN, motorNSleep> motorDriver;
+
 //OTRadValve::ValveMotorDirectV1HardwareDriver<motorLeft, motorRight, motorCurrent, motorEncoder> motorDriver;
 OTRadValve::TestValveMotor ValveDirect((OTRadValve::HardwareMotorDriverInterface *)(&motorDriver));


Removed example code for ApiClient.

Removed example code for ApiClient.

--- examples/ApiClientJson/ApiClientJson.ino
+++ examples/ApiClientJson/ApiClientJson.ino
@@ -1,40 +0,0 @@
-
-#include <Bridge.h>
-#include <ApiClient.h>
-
-ApiClient client;
-
-void setup() {
-  pinMode(13, OUTPUT);
-  digitalWrite(13, LOW);
-  Bridge.begin();
-  digitalWrite(13, HIGH);
-
-  Serial.begin(115200);
-
-  while (!Serial);
-}
-
-void loop() {
-
-  client.setContentTypeHeader(F("application/json"));
-  client.setUserAgentHeader(F("Arduino/0.1a"));
-  client.setAuthorizationHeader(F("YOUR_WRITE_KEY"));
-
-  client.post(
-    "https://api.keen.io/3.0/projects/YOUR_PROJECT_ID/events",
-    "YOUR_JSON_DATA"
-  );
-
-  client.printRequest();
-
-  while (client.available()) {
-    char c = client.read();
-    Serial.print(c);
-  }
-  Serial.println();
-  Serial.flush();
-
-  delay(2000);
-}
-


goto label removing standard loop is a cleaner solution

--- examples/receive_check/receive_check.ino
+++ examples/receive_check/receive_check.ino
@@ -17,19 +17,13 @@
 {
     Serial.begin(115200);

-START_INIT:
-
-    if(CAN_OK == CAN.begin(CAN_500KBPS))                   // init can bus : baudrate = 500k
-    {
-        Serial.println("CAN BUS Shield init ok!");
-    }
-    else
+    while (CAN_OK != CAN.begin(CAN_500KBPS))              // init can bus : baudrate = 500k
     {
         Serial.println("CAN BUS Shield init fail");
-        Serial.println("Init CAN BUS Shield again");
+        Serial.println(" Init CAN BUS Shield again");
         delay(100);
-        goto START_INIT;
     }
+    Serial.println("CAN BUS Shield init ok!");
 }

@@ -45,12 +39,12 @@
         unsigned long canId = CAN.getCanId();

         Serial.println("-----------------------------");
-        Serial.print("get data from ID: ");
+        Serial.print("Get data from ID: ");
         Serial.println(canId, HEX);

         for(int i = 0; i<len; i++)    // print the data
         {
-            Serial.print(buf[i]);
+            Serial.print(buf[i], HEX);
             Serial.print("\t");
         }
         Serial.println();


clean it, make it work better

clean it, make it work better

--- nuncha/nuncha.ino
+++ nuncha/nuncha.ino
@@ -5,12 +5,6 @@
 #include <ADSR.h>

 #define CONTROL_RATE 128 // powers of 2 please
-
-int bumpy_input = 0;
-int constrain_input = 0;
-
-int rollpitch = 0;
-
 #include <Oscil.h> // oscillator template
 #include <tables/sin2048_int8.h> // sine table for oscillator

@@ -123,16 +117,16 @@
    bool stickDn = ( yStick < - StickThresh ? true : false );
    bool stickUp = ( yStick >   StickThresh ? true : false );

-     constrain_input = constrain(Nunchuck . getRoll(), -180, -1);
-     bumpy_input = map(-constrain_input, 1, 180, 0, 11);
-     rollLeft = rollLAverage.next(bumpy_input);
+     int Linput = constrain(Nunchuck . getRoll(), -180, -1);
+     int BLinput = map(-Linput, 1, 180, 1, 11);
+     rollLeft = rollLAverage.next(BLinput);

-     constrain_input = constrain(Nunchuck . getRoll(), 0, 180);
-     bumpy_input = map(constrain_input, 0, 180, 0, 11);
-     rollRight = rollRAverage.next(bumpy_input);
+     int Rinput = constrain(Nunchuck . getRoll(), 0, 180);
+     int BRinput = map(Rinput, 0, 180, 1, 11);
+     rollRight = rollRAverage.next(BRinput);

-     constrain_input = constrain(Nunchuck . getPitch(), 18, 174);
-     bumpy_input = map(constrain_input, 100, 150, 440, 880);
+     int constrain_input = constrain(Nunchuck . getPitch(), 18, 174);
+     int bumpy_input = map(constrain_input, 18, 174, 440, 880);
      pitch = pitchAverage.next(bumpy_input);

    if ( stickUp )
@@ -145,7 +139,7 @@
    }

      aSin.setFreq((int)pitch);
-     if (rollRight < rollLeft )
+     if (rollLeft > rollRight )
      {
        aRight.setFreq(0);
         aLeft.setFreq( (int)((pitch/2) + 18*rollLeft));
@@ -170,13 +164,14 @@
      gain = envelope3.next();
      gain2 = envelope4.next();
    }
+
 }

 int updateAudio(){
     int synth;

-    if( rollRight == 0 )
+    if( rollLeft > rollRight )
     {
       synth = ((long)gain * aSin.next() + (int)gain2 * aLeft.next()) >> 9 ;
     }


minor: auto-format code, only

minor: auto-format code, only

--- TeensyChordPlayer.ino
+++ TeensyChordPlayer.ino
@@ -187,11 +187,11 @@
   // put your setup code here, to run once:

   Serial.begin(115200);
-
+
   if (!hasAudioBoard) {
     analogWriteResolution(12); //only needed if we're using the built-in DAC for audio out
   }
-
+
   for (int i = 3; i < 7; i++) {
     pinMode(i, INPUT_PULLUP);
   }
@@ -224,14 +224,14 @@
   drum4.secondMix(0.0);
   drum4.pitchMod(0.0);

-
-   if (hasAudioBoard) {
-     sgtl5000_1.enable();
-     sgtl5000_1.volume(0.5);
-   } else {
-     mixerFinal.gain(1, 0.3);
-     mixerFinal.gain(2, 0.3);
-   }
+
+  if (hasAudioBoard) {
+    sgtl5000_1.enable();
+    sgtl5000_1.volume(0.5);
+  } else {
+    mixerFinal.gain(1, 0.3);
+    mixerFinal.gain(2, 0.3);
+  }
   AudioInterrupts();
 }

@@ -253,8 +253,8 @@
     if (hasAudioBoard) {
       sgtl5000_1.volume(volume);
     } else {
-      mixerFinal.gain(1, volume/2);
-      mixerFinal.gain(2, volume/2);
+      mixerFinal.gain(1, volume / 2);
+      mixerFinal.gain(2, volume / 2);
     }
     nextVolumeUpdate = ms + 50;
   }


removing unused debug feature.

removing unused debug feature.

--- src/rx5808-pro-diversity/rx5808-pro-diversity.ino
+++ src/rx5808-pro-diversity/rx5808-pro-diversity.ino
@@ -163,10 +163,6 @@
     pinMode(receiverB_led,OUTPUT);
 #endif
     setReceiver(useReceiverA);
-#ifdef DEBUG
-    Serial.begin(115200);
-    Serial.println(F("START:"));
-#endif
     // SPI pins for RX control
     pinMode (slaveSelectPin, OUTPUT);
     pinMode (spiDataPin, OUTPUT);


Added water sensor to water_mote_v0_1

Added water sensor to water_mote_v0_1

--- water_mote_v0_1/water_mote_v0_1.ino
+++ water_mote_v0_1/water_mote_v0_1.ino
@@ -6,8 +6,9 @@
    Circuit:
    * Arduino UNO
    * Ethernet shield attached to pins 10, 11, 12, 13
-   * Water sensor attached to digitial pin 2
+   * Door sensor attached to digitial pin 2
    * Temperature/Humidity (DHT11) sensor attached to digital pin 3
+   * Water sensor attached to digital pin 8

    Created 22-JAN-2017 by Jon Brule
 ----------------------------------------------------------------------------- */
@@ -20,14 +21,17 @@
 #define DEVICE_NAME "water_mote_01"
 #define MAC_ADDR { 0x90, 0xA2, 0xDA, 0x00, 0x4B, 0x2A }
 #define MQTT_SERVER "mqtt.autohome.brule.net"
-#define MQTT_USERID "XXXXXX"
-#define MQTT_PASSWD "XXXXXX"
+#define MQTT_USERID "pi"
+#define MQTT_PASSWD "J8n@ut0!7"
+#define WATER_PIN 8

 byte macAddr[] = MAC_ADDR;
 MQTT mqtt(DEVICE_NAME, macAddr, MQTT_SERVER, MQTT_USERID, MQTT_PASSWD);

 DHTSensor dhts(DHT_PIN);
-int doorState = digitalRead(DOOR_PIN);
+int doorState;
+
+

 boolean startup = true;

@@ -35,8 +39,13 @@
   Serial.begin(115200);
   mqtt.setup();
   dhts.setup();
+
   pinMode(DOOR_PIN, INPUT_PULLUP);
+  doorState = digitalRead(DOOR_PIN);
   attachInterrupt(digitalPinToInterrupt(DOOR_PIN), doorOpen, CHANGE);
+
+  pinMode(WATER_PIN, INPUT);
+
   delay(1000);
   startup = false;
 }
@@ -44,18 +53,22 @@
 void loop() {
   mqtt.check();
   readSensors();
-  delay(15000);
+  delay(10000);
+  //sleep();
 }

 void readSensors() {
   float temperature = dhts.temperature();
   float humidity = dhts.humidity();
+  boolean waterPresent = isExposedToWater();

   String json = "{";
   json += "\"temperature\": ";
   json += temperature;
   json += ", \"humidity\": ";
   json += humidity;
+  json += ", \"water\": ";
+  json += (waterPresent ? "PRESENT" : "NOT PRESENT");
   json += ", \"door\": \"";
   json += (doorState == LOW ? "OPEN" : "CLOSED");
   json += "\"}";
@@ -77,3 +90,6 @@
   last_interrupt_time = interrupt_time;
 }

+boolean isExposedToWater() {
+  return (digitalRead(WATER_PIN) == LOW);
+}


Modified Arduino code

Modified Arduino code

--- supplements/arduino_control/arduino_control_v2.ino
+++ supplements/arduino_control/arduino_control_v2.ino
@@ -125,19 +125,19 @@

   p_sv.attach(32, 500, 2500);
   y_sv.attach(33, 500, 2500);
-  p_sv.write(90, servo_speed, true); // set the intial position of the servo
+  p_sv.write(90, servo_speed, true); // Set the intial position of the servo
   y_sv.write(90, servo_speed, true);

   while (Serial1.available())
   {
-    JY901.CopeSerialData(Serial1.read()); //Call JY901 data cope function
+    JY901.CopeSerialData(Serial1.read());
   }
 }

 void loop() {
   while (Serial1.available())
   {
-    JY901.CopeSerialData(Serial1.read()); //Call JY901 data cope function
+    JY901.CopeSerialData(Serial1.read()); // Call JY901 data copy function
   }
   x_ang = (float)JY901.stcAngle.Angle[0]/32768*180;
   y_ang = (float)JY901.stcAngle.Angle[1]/32768*180;
@@ -146,7 +146,7 @@
   pitch_msg.data = x_ang; // We make x axis as yaw
   pub_pitch.publish(&pitch_msg);

-  yaw_msg.data = 90.0 - z_ang;
+  yaw_msg.data = 90.0 + z_ang;
   pub_yaw.publish(&yaw_msg);

   float x_acc = (float)JY901.stcAcc.a[0]/32768*16;
@@ -155,7 +155,6 @@
   checkVibration(x_acc, y_acc, z_acc);

   nh.spinOnce();
-  delay(50);

   checkSleep();


Added some simple debug prints during initialization

--- arduino/KnexElevator/KnexElevator.ino
+++ arduino/KnexElevator/KnexElevator.ino
@@ -33,7 +33,6 @@
 #include <stdint.h>

 #include "BlinkerTask.h"
-#include "CarPositioningTask.h"

 // /////////////////////////////////////////////////////////////////////////////
@@ -47,8 +46,6 @@

 // Application Tasks
 BlinkerTask gvBlinkerTask;
-CarPositioningTask gvCarOnePositioningTask(1);
-CarPositioningTask gvCarTwoPositioningTask(2);

 ////////////////////////////////////////////////////////////////////////////////
@@ -56,13 +53,14 @@
 {
     // Debug console
     Serial.begin(115200);
+    Serial.println("ENTER: setup()");

     // Bring up the application tasks
-    gvBlinkerTask.initialize();
-    gvCarOnePositioningTask.initialize();
-    gvCarTwoPositioningTask.initialize();
+    gvBlinkerTask.Initialize();

     // FreeRTOS task scheduler takes over from here.
+    Serial.println("LEAVE: setup()");
+    Serial.println("FreeRTOS Scheduler Running...");
     return;
 }


bug fix

bug fix

--- arduino/motor_driver/motor_driver.ino
+++ arduino/motor_driver/motor_driver.ino
@@ -333,12 +333,16 @@
   if (EEPROM.read(EEPROM_REMEMBER_POSITION) == 1) {
     // check if encoder value can be recovered after crash
     if (encoder0Pos ^ encoder0ChecksumKey == encoder0Checksum) {
-      // yes! let's claim we're homed
-      reboots++;
-      return true;
-    }
-  }
-
+      // sanity check
+      if (encoder0Pos > 10 && encoder0Pos < 100000) {
+        // yes! let's claim we're homed
+        reboots++;
+        return true;
+      }
+    }
+  }
+
+  encoder0Pos = -1;
   return false;
 }


arduino_repeater: Fix repeating bug - wrong buffer

--- arduino_repeater/arduino_repeater.ino
+++ arduino_repeater/arduino_repeater.ino
@@ -177,7 +177,7 @@
           //random delay to try and avoid packet collision
           delay(random(50, 800));

-          rf69.send((uint8_t*)data, packet_len, rfm_power);
+          rf69.send((uint8_t*)buf, packet_len, rfm_power);
         }
       }
     }


first successful sending of temp data

first successful sending of temp data

--- TreibBoje1.ino
+++ TreibBoje1.ino
@@ -97,6 +97,9 @@
 #ifdef SEND_DATA
   // Transmitter is connected to Arduino Pin #10 (TX_PIN)
   theSender.enableTransmit(TX_PIN);
+
+  // default in RCSwitch library is 10
+  //theSender.setRepeatTransmit(10);

   // Optional set pulse length.
   theSender.setPulseLength(200);
@@ -155,22 +158,40 @@
   return 0;
 }

+#ifdef SEND_DATA
+ #define SEND_SYNC(_x) theSender.send((_x & 0x1ff) | 0x0e00, 12)
+ #define SEND_T1(_x) theSender.send((_x & 0x1ff) | (0x0100 << 1), 12)
+ #define SEND_T2(_x) theSender.send((_x & 0x1ff) | (0x0200 << 1), 12)
+ #define SEND_T3(_x) theSender.send((_x & 0x1ff) | (0x0300 << 1), 12)
+ #define SEND_T4(_x) theSender.send((_x & 0x1ff) | (0x0400 << 1), 12)
+ #define SEND_T5(_x) theSender.send((_x & 0x1ff) | (0x0500 << 1), 12)
+#else
+ #define SEND_SYNC(_x) {}
+ #define SEND_T1(_x) {}
+ #define SEND_T2(_x) {}
+ #define SEND_T3(_x) {}
+ #define SEND_T4(_x) {}
+ #define SEND_T5(_x) {}
+#endif // SEND_DATA
+
 /**
  * Main loop
  */
 void loop() {

 #ifdef SEND_DATA
-  // send dumy telegram
-  theSender.send(0, 12);
-  theSender.send(4095, 12);
-#endif // SEND_DATA
+  // send some dummy telegrams, cannot set 0!
+  //theSender.send(0x0e01, 12);
+  //theSender.send(0x0e02, 12);
+  //theSender.send(0x0fff, 12);
+#endif // SEND_DATA
+
+  SEND_SYNC(1);

 #ifdef READ_SENSORS
   if ( sensors.getDeviceCount() > 0 ) {
     sensors.requestTemperatures(); // Send the command to get temperatures

-#ifdef DEBUG
     float temp;

     // printout of temperature sensor values in the order they are enumerated at the 1-wire bus
@@ -178,33 +199,56 @@
     // alternative printout, only known sensors correctly prefixed
     if ( sensors.isConnected( gSensor1 ) ) {
       temp = sensors.getTempC( gSensor1 );
+#ifdef DEBUG
       Serial << "T1: " << temp << " "
-             << getRawTemperature(temp, TEMPERATURE_PRECISION);
+             << getRawTemperature(temp, TEMPERATURE_PRECISION)
+             << " ";
+#endif // DEBUG
+      SEND_T1(getRawTemperature(temp, TEMPERATURE_PRECISION));
     }
     if ( sensors.isConnected( gSensor2 ) ) {
       temp = sensors.getTempC( gSensor2 );
+#ifdef DEBUG
       Serial << "T2: " << temp << " "
-             << getRawTemperature(temp, TEMPERATURE_PRECISION);
+             << getRawTemperature(temp, TEMPERATURE_PRECISION)
+             << " ";
+#endif // DEBUG
+      SEND_T2(getRawTemperature(temp, TEMPERATURE_PRECISION));
     }
     if ( sensors.isConnected( gSensor3 ) ) {
       temp = sensors.getTempC( gSensor3 );
+#ifdef DEBUG
       Serial << "T3: " << temp << " "
-             << getRawTemperature(temp, TEMPERATURE_PRECISION);
+             << getRawTemperature(temp, TEMPERATURE_PRECISION)
+             << " ";
+#endif // DEBUG
+      SEND_T3(getRawTemperature(temp, TEMPERATURE_PRECISION));
     }
     if ( sensors.isConnected( gSensor4 ) ) {
       temp = sensors.getTempC( gSensor4 );
+#ifdef DEBUG
       Serial << "T4: " << temp << " "
-             << getRawTemperature(temp, TEMPERATURE_PRECISION);
+             << getRawTemperature(temp, TEMPERATURE_PRECISION)
+             << " ";
+#endif // DEBUG
+      SEND_T4(getRawTemperature(temp, TEMPERATURE_PRECISION));
     }
     if ( sensors.isConnected( gSensor5 ) ) {
       temp = sensors.getTempC( gSensor5 );
+#ifdef DEBUG
       Serial << "T5: " << temp << " "
-             << getRawTemperature(temp, TEMPERATURE_PRECISION);
-    }
+             << getRawTemperature(temp, TEMPERATURE_PRECISION)
+             << " ";
+#endif // DEBUG
+      SEND_T5(getRawTemperature(temp, TEMPERATURE_PRECISION));
+    }
+#ifdef DEBUG
     Serial.println();
 #endif // DEBUG
   } // if ( getDeviceCount() > 0 )
 #endif // READ_SENSORS
+
+  SEND_SYNC(2);
 }

 /**
@@ -241,4 +285,4 @@
   Serial.println();
 }

-
+


Needed to initialize the sweep servo.

Needed to initialize the sweep servo.

--- src/sketch.ino
+++ src/sketch.ino
@@ -24,6 +24,7 @@
   Serial.begin(9600);
   blinker.begin();
   blinker.blinkNumber(8); // For Leonardo
+  sweepServo.begin();

   mover.begin();


Make doublegliss arduino function

Make doublegliss arduino function

Signed-off-by: Mark Knoop <f1b5a91d4d6ad523f2610114591c007e75d15084@markknoop.com>

--- src/sketch.ino
+++ src/sketch.ino
@@ -14,7 +14,8 @@
 #define decelLook      10 // start looking for sensor this many steps early
 #define minPulse      500
 #define maxPulse     2300
-#define durationGlissCompensation 480
+#define durationGlissMult 0.935
+#define durationGlissDiff 160

 /*************************
  * communication commands
@@ -34,21 +35,25 @@
 #define rNoRecentre    11
 #define rSetDuration   12
 #define rReset         13
+#define rDoubleGliss   14
+// array sizes
 #define rDurlength      5
-#define rLength        14
+#define rLength        25
 /*
  * ranges:
     21-39  set halfturns
     40-112 set startpitch
    120-192 set endpitch
-   203-209 tests
+   203-210 tests
  */

 char serialIncoming[rLength];
 char newDuration[rDurlength];
 int halfTurns;
 unsigned int duration;
+unsigned int midDuration;
 float startPitch;
+float midPitch;
 float endPitch;
 boolean dir;
 boolean recentre;
@@ -73,8 +78,10 @@
 void defaults() {
     halfTurns = 1;
     duration = 500;
+    midDuration = 500;
     startPitch = 72;
-    endPitch = 36;
+    midPitch = 48;
+    endPitch = 60;
     dir = true;
     recentre = true;
 }
@@ -221,29 +228,44 @@
     digitalWrite(LED_BUILTIN, LOW);
 }

-long durationgliss(int duration, float startpitch, float endpitch, bool dir, bool recentre) {
+long _durationgliss(int duration, float startpitch, float endpitch, bool dir,
+        bool recentre, bool accel, bool decel) {
     int startpulse = pitchToPulse(startpitch);
     int endpulse = pitchToPulse(endpitch);
-    unsigned long glissTime = max(0, (duration * 1000L) -
-        (((maxPulse + startpulse) * (accelSteps / 2)) +
-         ((endpulse + maxPulse) * (accelSteps / 2))) -
-        (durationGlissCompensation * 1000L));
+    int accelsteps = accelSteps * accel;
+    int decelsteps = accelSteps * decel;
+    unsigned long glissTime = (duration * 1000L) -
+        (((max(maxPulse, startpulse) + startpulse) * (accelsteps / 2)) +
+         ((endpulse + max(maxPulse, endpulse)) * (decelsteps / 2)));
+    glissTime = max(0, (glissTime * durationGlissMult) - (durationGlissDiff * 1000L));
     int glisssteps = glissTime / ((startpulse + endpulse) / 2);
     digitalWrite(LED_BUILTIN, HIGH);
     digitalWrite(dirPin, dir);
     delayMicroseconds(pulseWidth);
-    for (int i=0; i<accelSteps; i++) {
-        onestep(map(i, 0, accelSteps, max(maxPulse, startpulse), startpulse));
+    for (int i=0; i<accelsteps; i++) {
+        onestep(map(i, 0, accelsteps, max(maxPulse, startpulse), startpulse));
     }
     for (int i=0; i<glisssteps; i++) {
         onestep(map(i, 0, glisssteps, startpulse, endpulse));
     }
-    for (int i=0; i<accelSteps; i++) {
-        onestep(map(i, 0, accelSteps, endpulse, max(maxPulse, endpulse)));
+    for (int i=0; i<decelsteps; i++) {
+        onestep(map(i, 0, decelsteps, endpulse, max(maxPulse, endpulse)));
         if (i>(accelSteps - (decelLook * recentre) && digitalRead(sensorPin))) break;
     }
     if (recentre) findsensor(max(maxPulse, endpulse));
     digitalWrite(LED_BUILTIN, LOW);
+    return glissTime;
+}
+
+long durationgliss(int duration, float startpitch, float endpitch, bool dir, bool recentre) {
+    return _durationgliss(duration, startpitch, endpitch, dir, recentre, true, true);
+}
+
+long doublegliss(int durationone, int durationtwo, float startpitch,
+        float midpitch, float endpitch, bool dir, bool recentre) {
+    long glissTime;
+    glissTime = _durationgliss(durationone, startpitch, midpitch, dir, false, true, false);
+    glissTime += _durationgliss(durationtwo, midpitch, endpitch, dir, recentre, false, true);
     return glissTime;
 }

@@ -321,6 +343,28 @@
         Serial.print(" calctime ");
         Serial.println(calcdur, DEC);
     } else if (style == 5) {
+        // double gliss
+        Serial.print("midduration ");
+        Serial.print(midDuration, DEC);
+        Serial.print(", duration ");
+        Serial.println(duration, DEC);
+        Serial.print("startpitch ");
+        Serial.print(startPitch, DEC);
+        Serial.print(" midpitch ");
+        Serial.print(midPitch, DEC);
+        Serial.print(" endpitch ");
+        Serial.print(endPitch, DEC);
+        Serial.print(" direction ");
+        Serial.print(dir, DEC);
+        Serial.print(" recentre ");
+        Serial.print(recentre, DEC);
+        Serial.print(" time ");
+        unsigned long starttime = millis();
+        long calcdur = doublegliss(midDuration, duration, startPitch, midPitch, endPitch, dir, recentre);
+        Serial.print(millis() - starttime);
+        Serial.print(" calctime ");
+        Serial.println(calcdur, DEC);
+    } else if (style == 6) {
         // scale
         for (int i=36; i<73; i++) {
             long dur = 666;
@@ -333,14 +377,18 @@
             durationturn(dur, i, i % 2, false);
             Serial.println(millis() - starttime);
         }
-    } else if (style == 6) {
+    } else if (style == 7) {
         // show settings
         Serial.print("halfturns ");
         Serial.print(halfTurns, DEC);
+        Serial.print(", midduration ");
+        Serial.print(midDuration, DEC);
         Serial.print(", duration ");
         Serial.println(duration, DEC);
         Serial.print("startpitch ");
         Serial.print(startPitch, DEC);
+        Serial.print(", midpitch ");
+        Serial.print(midPitch, DEC);
         Serial.print(", endpitch ");
         Serial.println(endPitch, DEC);
         Serial.print("direction ");
@@ -354,8 +402,9 @@
         Serial.println("205: 0xcd: timedturn");
         Serial.println("206: 0xce: durationturn");
         Serial.println("207: 0xcf: durationgliss");
-        Serial.println("208: 0xd0: scale");
-        Serial.println("209: 0xd1: show settings");
+        Serial.println("208: 0xd0: doublegliss");
+        Serial.println("209: 0xd1: scale");
+        Serial.println("210: 0xd2: show settings");
     }
     delay(333);
 }
@@ -392,9 +441,12 @@
             for (byte d=0; d<rDurlength; d++) {
                 newDuration[d] = serialIncoming[++i];
             }
+            midDuration = duration; // midDuration is previous duration
             duration = atoi(newDuration);
         } else if (data == rReset) {
             defaults();
+        } else if (data == rDoubleGliss) {
+            doublegliss(midDuration, duration, startPitch, midPitch, endPitch, dir, recentre);
         } else if (data < 21) {
             true;
         } else if (data < 40) {
@@ -404,10 +456,11 @@
         } else if (data < 120) {
             true;
         } else if (data < 193) {
+            midPitch = endPitch; // midPitch is previous endPitch
             endPitch = pitchbyteToMidi(data - 120);
         } else if (data < 203) {
             true;
-        } else if (data < 210) {
+        } else if (data < 211) {
             test(data - 203);
             flashled();
         }


Adjust duration correction factors with SC timing

Signed-off-by: Mark Knoop <f1b5a91d4d6ad523f2610114591c007e75d15084@markknoop.com>

--- src/sketch.ino
+++ src/sketch.ino
@@ -22,10 +22,8 @@
 #define maxPulse     2300 // microseconds

 // pitch correction
-#define durationGlissMul 0.9
-#define durationGlissAdd -20
-#define durationTurnMul 1
-#define durationTurnAdd 0
+#define durationGlissMul 0.95
+#define durationGlissAdd -290
 #define glissAdd       -0.45

 /*************************
@@ -161,7 +159,6 @@

 void turn(int halfturns, float pitch, bool dir) {
     int fullspeedsteps = (halfTurnSteps * halfturns) - (accelSteps * 2);
-    // leave this without durationTurn adjustments
     int pulse = pitchToPulse(pitch);
     int startstoppulse = max(maxPulse, pulse);
     digitalWrite(dirPin, dir);
@@ -183,13 +180,13 @@
 }

 void turnUntilNext(float pitch, bool dir) {
-    // leave this without durationTurn adjustments
     int pulse = pitchToPulse(pitch);
     int startstoppulse = max(maxPulse, pulse);
+    int accelsteps = map(pitch, 48, 72, accelSteps-10, accelSteps+10);
     digitalWrite(dirPin, dir);
     delayMicroseconds(pulseWidth);
-    for (int i=0; i<accelSteps; i++) {
-        oneStep(map(i, 0, accelSteps, startstoppulse, pulse));
+    for (int i=0; i<accelsteps; i++) {
+        oneStep(map(i, 0, accelsteps, startstoppulse, pulse));
         if (alarmState) return;
     }
     sendReady();
@@ -197,8 +194,8 @@
         oneStep(pulse);
         if (alarmState) return;
     }
-    for (int i=0; i<accelSteps; i++) {
-        oneStep(map(i, 0, accelSteps, pulse, startstoppulse));
+    for (int i=0; i<accelsteps; i++) {
+        oneStep(map(i, 0, accelsteps, pulse, startstoppulse));
         if (i>(accelSteps - decelLook) && digitalRead(sensorPin)) break;
         if (alarmState) return;
     }
@@ -208,18 +205,20 @@
     int glisssteps = (halfTurnSteps * halfturns) - (accelSteps * 2);
     int startpulse = pitchToPulse(startpitch + glissAdd);
     int endpulse = pitchToPulse(endpitch + glissAdd);
+    int accelsteps = map(startpitch, 48, 72, accelSteps-10, accelSteps+10);
+    int decelsteps = map(endpitch, 48, 72, accelSteps-10, accelSteps+10);
     digitalWrite(dirPin, dir);
     delayMicroseconds(pulseWidth);
-    for (int i=0; i<accelSteps; i++) {
-        oneStep(map(i, 0, accelSteps, max(maxPulse, startpulse), startpulse));
+    for (int i=0; i<accelsteps; i++) {
+        oneStep(map(i, 0, accelsteps, max(maxPulse, startpulse), startpulse));
         if (alarmState) return;
     }
     for (int i=0; i<glisssteps; i++) {
         oneStep(map(i, 0, glisssteps, startpulse, endpulse));
         if (alarmState) return;
     }
-    for (int i=0; i<accelSteps; i++) {
-        oneStep(map(i, 0, accelSteps, endpulse, max(maxPulse, endpulse)));
+    for (int i=0; i<decelsteps; i++) {
+        oneStep(map(i, 0, decelsteps, endpulse, max(maxPulse, endpulse)));
         if (i>(accelSteps - decelLook) && digitalRead(sensorPin)) break;
         if (alarmState) return;
     }
@@ -259,6 +258,8 @@

 long _durationGliss(unsigned long duration, float startpitch, float endpitch,
         int sustainstart, int sustainend, bool dir, bool recentre) {
+    // adjust duration
+    duration = max(0, duration + durationGlissAdd) * durationGlissMul;
     int startsustainpulse = pitchToPulse(startpitch + glissAdd - 1);
     int startpulse = pitchToPulse(startpitch + glissAdd);
     int endpulse = pitchToPulse(endpitch + glissAdd);
@@ -268,7 +269,6 @@
     unsigned long glisstime = ((duration - sustainstart) * 1000L) -
         (((max(maxPulse, startpulse) + startpulse) * (accelsteps / 2)) +
          ((endpulse + max(maxPulse, endpulse)) * (decelsteps / 2)));
-    glisstime = max(0, (glisstime * durationGlissMul) + (durationGlissAdd * 1000L));
     int glisssteps = glisstime / ((startpulse + endpulse) / 2);
     int sustainstartsteps = (sustainstart * 1000L) / startpulse;
     int sustainendsteps = (sustainend * 1000L) / endpulse;


Added DNS server support

Added DNS server support

--- src/sketch.ino
+++ src/sketch.ino
@@ -89,6 +89,7 @@

 void setup() {
   Serial.begin(9600);
+  delay(1000);
   Lcd.begin();

   pinMode(reedPin, INPUT);
@@ -98,7 +99,7 @@
   Lcd.infoMessage("  Starting up.");

   // start Ethernet
-  Ethernet.begin(mac, ip);
+  Ethernet.begin(mac, ip, gateway, dns_server);
   Lcd.setSecondLine("Getting Time...");
   // get time
   setStartTime();


Add strip test function

Add strip test function

Grounding output 17 when powered is applied to the Teensy, initiates a test which cycles through 8 colors (the last is black) to verify that the strips are connected and working.

--- TeensyStripController.ino
+++ TeensyStripController.ino
@@ -1,323 +1,389 @@
-/********************************************************************************************************
- ** TeensyStrip Controller
- ** ----------------------
- **
- ** This Sketch turns a Teensy 3.1, 3.2 or later into a controller for WS2811/WS2812 based led strips.
- ** This strip controller was originally designed for use with the Direct Output Framework, but since
- ** the communication protocol is simple and communication uses the virtual com port of the Teensy
- ** it should be easy to controll the strips from other applications as well.
- **
- ** The most important part of the code is a slightly hacked version (a extra method to set the length of the
- ** strips dynamiccaly has been added) of Paul Stoffregens excellent OctoWS2811 LED Library.
- ** For more information on the lib check out:
- ** https://github.com/PaulStoffregen/OctoWS2811
- ** http://www.pjrc.com/teensy/td_libs_OctoWS2811.html
- **
- *********************************************************************************************************/
- /*
-    License:
-    --------
-    Permission is hereby granted, free of charge, to any person obtaining a copy
-    of this software and associated documentation files (the "Software"), to deal
-    in the Software without restriction, including without limitation the rights
-    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-    copies of the Software, and to permit persons to whom the Software is
-    furnished to do so, subject to the following conditions:
-    The above copyright notice and this permission notice shall be included in
-    all copies or substantial portions of the Software.
-    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-    THE SOFTWARE.
-*/
-
-#include "OctoWS2811Ext.h" //A slightly hacked version of the OctoWS2811 lib which allows for dynamic setting of the number of leds is used.
-
-//Definiton of Major and Minor part of the firmware version. This value can be received using the V command.
-//If something is changed in the code the number should be increased.
-#define FirmwareVersionMajor 1
-#define FirmwareVersionMinor 2
-
-//Defines the max number of leds which is allowed per ledstrip.
-//This number is fine for Teensy 3.2, 3.1. For newer Teensy versions (they dont exists yet) it might be possible to increase this number.
-#define MaxLedsPerStrip 1100
-
-//Defines the Pinnumber to which the built in led of the Teensy is connected.
-//For Teensy 3.2, 3.1 this is pin 13, if you use a newer Teensy version (not available at the time of writing) you might need to change this number.
-#define LedPin 13
-
-
-//Memory buffers for the OctoWS2811 lib
-DMAMEM int displayMemory[MaxLedsPerStrip*6];
-int drawingMemory[MaxLedsPerStrip*6];
-
-//Variable used to control the blinking and flickering of the led of the Teensy
-elapsedMillis BlinkTimer;
-int BlinkMode;
-elapsedMillis BlinkModeTimeoutTimer;
-
-//Config definition for the OctoWS2811 lib
-const int config = WS2811_RGB | WS2811_800kHz; //Dont change the color order (even if your strip are GRB). DOF takes care of this issue (see config of ledstrip toy)
-
-OctoWS2811Ext leds(MaxLedsPerStrip, displayMemory, drawingMemory, config);
-
-word configuredStripLength=64;
-
-//Setup of the system. Is called once on startup.
-void setup() {
-  Serial.begin(9600); // This has no effect. USB bitrate (12MB) will be used anyway.
-
-  //Initialize the lib for the leds
-  leds.setStripLength(configuredStripLength);
-  leds.begin();
-  leds.show();
-
-  //Initialize the led pin
-  pinMode(LedPin,OUTPUT);
-
-  SetBlinkMode(0);
-}
-
-//Main loop of the programm gets called again and again.
-void loop() {
-  // put your main code here, to run repeatedly:
-
-  //Check if data is available
-  if (Serial.available()) {
-
-    byte receivedByte = Serial.read();
-    switch (receivedByte) {
-      case 'L':
-        //Set length of strips
-        SetLedStripLength();
-        break;
-      case 'F':
-        //Fill strip area with color
-        Fill();
-        break;
-      case 'R':
-        //receive data for strips
-        ReceiveData();
-        break;
-      case 'O':
-        //output data on strip
-        OutputData();
-        break;
-      case 'C':
-        //Clears all previously received led data
-        ClearAllLedData();
-        break;
-      case 'V':
-        //Send the firmware version
-        SendVersion();
-        break;
-      case 'M':
-        //Get max number of leds per strip
-        SendMaxNumberOfLeds();
-        break;
-      default:
-        // no unknown commands allowed. Send NACK (N)
-        Nack();
-      break;
-    }
-
-
-    SetBlinkMode(1);
-
-
-  }
-  Blink();
-}
-
-
-//Sets the mode for the blinking of the led
-void SetBlinkMode(int Mode) {
-  BlinkMode=Mode;
-  BlinkModeTimeoutTimer=0;
-}
-
-//Controls the blinking of the led
-void Blink() {
-  switch(BlinkMode) {
-    case 0:
-      //Blinkmode 0 is only active after the start of the Teensy until the first command is received.
-      if(BlinkTimer<1500) {
-        digitalWrite(LedPin,0);
-      } else if(BlinkTimer<1600) {
-        digitalWrite(LedPin,1);
-      } else {
-        BlinkTimer=0;
-        digitalWrite(LedPin,0);
-      }
-    break;
-    case 1:
-      //Blinkmode 1 is activated when the Teensy receives a command
-      //Mode expires 500ms after the last command has been received resp. mode has been set
-      if(BlinkTimer>30) {
-        BlinkTimer=0;
-        digitalWrite(LedPin,!digitalRead(LedPin));
-      }
-      if(BlinkModeTimeoutTimer>500) {
-        SetBlinkMode(2);
-      }
-    break;
-    case 2:
-      //Blinkmode 2 is active while the Teensy is waiting for more commands
-      if(BlinkTimer<1500) {
-        digitalWrite(LedPin,0);
-      } else if(BlinkTimer<1600) {
-        digitalWrite(LedPin,1);
-      } else if(BlinkTimer<1700) {
-        digitalWrite(LedPin,0);
-      } else if(BlinkTimer<1800) {
-        digitalWrite(LedPin,1);
-      }else {
-        BlinkTimer=0;
-        digitalWrite(LedPin,0);
-      }
-      default:
-      //This should never be active
-      //The code is only here to make it easier to determine if a wrong Blinkcode has been set
-      if(BlinkTimer>2000) {
-        BlinkTimer=0;
-        digitalWrite(LedPin,!digitalRead(LedPin));
-      }
-      break;
-  }
-
-}
-
-
-//Outputs the data in the ram to the ledstrips
-void OutputData() {
-   leds.show();
-   Ack();
-}
-
-
-//Fills the given area of a ledstrip with a color
-void Fill() {
-  word firstLed=ReceiveWord();
-
-  word numberOfLeds=ReceiveWord();
-
-  int ColorData=ReceiveColorData();
-
-   if( firstLed<=configuredStripLength*8 && numberOfLeds>0 && firstLed+numberOfLeds-1<=configuredStripLength*8 ) {
-       word endLedNr=firstLed+numberOfLeds;
-       for(word ledNr=firstLed; ledNr<endLedNr;ledNr++) {
-         leds.setPixel(ledNr,ColorData);
-       }
-       Ack();
-   } else {
-     //Number of the first led or the number of leds to receive is outside the allowed range
-     Nack();
-   }
-
-
-}
-
-
-//Receives data for the ledstrips
-void ReceiveData() {
-  word firstLed=ReceiveWord();
-
-  word numberOfLeds=ReceiveWord();
-
-  if( firstLed<=configuredStripLength*8 && numberOfLeds>0 && firstLed+numberOfLeds-1<=configuredStripLength*8 ) {
-    //FirstLedNr and numberOfLeds are valid.
-    //Receive and set color data
-
-    word endLedNr=firstLed+numberOfLeds;
-    for(word ledNr=firstLed; ledNr<endLedNr;ledNr++) {
-      leds.setPixel(ledNr,ReceiveColorData());
-    }
-
-    Ack();
-
-  } else {
-    //Number of the first led or the number of leds to receive is outside the allowed range
-    Nack();
-  }
-}
-
-//Sets the length of the longest connected ledstrip. Length is restricted to the max number of allowed leds
-void SetLedStripLength() {
-   word stripLength=ReceiveWord();
-   if(stripLength<1 || stripLength>MaxLedsPerStrip) {
-     //stripLength is either to small or above the max number of leds allowed
-     Nack();
-   } else {
-     //stripLength is in the valid range
-     configuredStripLength=stripLength;
-     leds.setStripLength(stripLength);
-     leds.begin();  //Reinitialize the OctoWS2811 lib (not sure if this is needed)
-
-     Ack();
-   }
-}
-
-//Clears the data for all configured leds
-void  ClearAllLedData() {
-  for(word ledNr=0;ledNr<configuredStripLength*8;ledNr++) {
-    leds.setPixel(ledNr,0);
-  }
-  Ack();
-}
-
-
-//Sends the firmware version
-void SendVersion() {
-  Serial.write(FirmwareVersionMajor);
-  Serial.write(FirmwareVersionMinor);
-  Ack();
-}
-
-//Sends the max number of leds per strip
-void SendMaxNumberOfLeds() {
-  byte B=MaxLedsPerStrip>>8;
-  Serial.write(B);
-  B=MaxLedsPerStrip&255;
-  Serial.write(B);
-  Ack();
-}
-
-
-//Sends a ack (A)
-void Ack() {
-  Serial.write('A');
-}
-
-//Sends a NACK (N)
-void Nack() {
-  Serial.write('N');
-}
-
-//Receives 3 bytes of color data.
-int ReceiveColorData() {
-  while(!Serial.available()) {};
-  int colorValue=Serial.read();
-  while(!Serial.available()) {};
-  colorValue=(colorValue<<8)|Serial.read();
-  while(!Serial.available()) {};
-  colorValue=(colorValue<<8)|Serial.read();
-
-  return colorValue;
-
-
-}
-
-//Receives a word value. High byte first, low byte second
-word ReceiveWord() {
-  while(!Serial.available()) {};
-  word wordValue=Serial.read()<<8;
-  while(!Serial.available()) {};
-  wordValue=wordValue|Serial.read();
-
-  return wordValue;
-}
-
-
+/********************************************************************************************************
+ ** TeensyStrip Controller
+ ** ----------------------
+ **
+ ** This Sketch turns a Teensy 3.1, 3.2 or later into a controller for WS2811/WS2812 based led strips.
+ ** This strip controller was originally designed for use with the Direct Output Framework, but since
+ ** the communication protocol is simple and communication uses the virtual com port of the Teensy
+ ** it should be easy to controll the strips from other applications as well.
+ **
+ ** The most important part of the code is a slightly hacked version (a extra method to set the length of the
+ ** strips dynamiccaly has been added) of Paul Stoffregens excellent OctoWS2811 LED Library.
+ ** For more information on the lib check out:
+ ** https://github.com/PaulStoffregen/OctoWS2811
+ ** http://www.pjrc.com/teensy/td_libs_OctoWS2811.html
+ **
+ *********************************************************************************************************/
+ /*
+    License:
+    --------
+    Permission is hereby granted, free of charge, to any person obtaining a copy
+    of this software and associated documentation files (the "Software"), to deal
+    in the Software without restriction, including without limitation the rights
+    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+    copies of the Software, and to permit persons to whom the Software is
+    furnished to do so, subject to the following conditions:
+    The above copyright notice and this permission notice shall be included in
+    all copies or substantial portions of the Software.
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+    THE SOFTWARE.
+
+  Required Connections
+  --------------------
+    pin 2:  LED Strip #1    OctoWS2811 drives 8 LED Strips.
+    pin 14: LED strip #2    All 8 are the same length.
+    pin 7:  LED strip #3
+    pin 8:  LED strip #4    A 100 ohm resistor should used
+    pin 6:  LED strip #5    between each Teensy pin and the
+    pin 20: LED strip #6    wire to the LED strip, to minimize
+    pin 21: LED strip #7    high frequency ringining & noise.
+    pin 5:  LED strip #8
+    pin 15 & 16 - Connect together, but do not use
+    pin 4 - Do not use
+    pin 3 - Do not use as PWM.  Normal use is ok.
+
+*/
+
+#include "OctoWS2811Ext.h" //A slightly hacked version of the OctoWS2811 lib which allows for dynamic setting of the number of leds is used.
+
+//Definiton of Major and Minor part of the firmware version. This value can be received using the V command.
+//If something is changed in the code the number should be increased.
+#define FirmwareVersionMajor 1
+#define FirmwareVersionMinor 3
+
+//Defines the max number of leds which is allowed per ledstrip.
+//This number is fine for Teensy 3.2, 3.1. For newer Teensy versions (they dont exists yet) it might be possible to increase this number.
+#define MaxLedsPerStrip 1100
+
+//Defines the Pinnumber to which the built in led of the Teensy is connected.
+//For Teensy 3.2, 3.1 this is pin 13, if you use a newer Teensy version (not available at the time of writing) you might need to change this number.
+#define LedPin 13
+
+// Defines the Pinnumber for the test button which is low when pressed
+#define TestPin 17
+
+//Memory buffers for the OctoWS2811 lib
+DMAMEM int displayMemory[MaxLedsPerStrip*6];
+int drawingMemory[MaxLedsPerStrip*6];
+
+//Variable used to control the blinking and flickering of the led of the Teensy
+elapsedMillis BlinkTimer;
+int BlinkMode;
+elapsedMillis BlinkModeTimeoutTimer;
+
+//Config definition for the OctoWS2811 lib
+const int config = WS2811_RGB | WS2811_800kHz; //Dont change the color order (even if your strip are GRB). DOF takes care of this issue (see config of ledstrip toy)
+
+OctoWS2811Ext leds(MaxLedsPerStrip, displayMemory, drawingMemory, config);
+
+word configuredStripLength=144;
+
+//Setup of the system. Is called once on startup.
+void setup() {
+  Serial.begin(9600); // This has no effect. USB bitrate (12MB) will be used anyway.
+
+  //Initialize the lib for the leds
+  leds.setStripLength(configuredStripLength);
+  leds.begin();
+  leds.show();
+
+  //Initialize the led pin
+  pinMode(LedPin,OUTPUT);
+
+  SetBlinkMode(0);
+
+  //Initialize and find value of the test pin
+  pinMode(TestPin,INPUT_PULLUP);
+  if (! digitalRead(TestPin)) {
+    // run test if button is grounded
+    Test();
+  }
+}
+
+//Main loop of the programm gets called again and again.
+void loop() {
+  // put your main code here, to run repeatedly:
+
+  //Check if data is available
+  if (Serial.available()) {
+
+    byte receivedByte = Serial.read();
+    switch (receivedByte) {
+      case 'L':
+        //Set length of strips
+        SetLedStripLength();
+        break;
+      case 'F':
+        //Fill strip area with color
+        Fill();
+        break;
+      case 'R':
+        //receive data for strips
+        ReceiveData();
+        break;
+      case 'O':
+        //output data on strip
+        OutputData();
+        break;
+      case 'C':
+        //Clears all previously received led data
+        ClearAllLedData();
+        break;
+      case 'V':
+        //Send the firmware version
+        SendVersion();
+        break;
+      case 'M':
+        //Get max number of leds per strip
+        SendMaxNumberOfLeds();
+        break;
+      default:
+        // no unknown commands allowed. Send NACK (N)
+        Nack();
+      break;
+    }
+
+
+    SetBlinkMode(1);
+
+
+  }
+  Blink();
+}
+
+
+//Sets the mode for the blinking of the led
+void SetBlinkMode(int Mode) {
+  BlinkMode=Mode;
+  BlinkModeTimeoutTimer=0;
+}
+
+//Controls the blinking of the led
+void Blink() {
+  switch(BlinkMode) {
+    case 0:
+      //Blinkmode 0 is only active after the start of the Teensy until the first command is received.
+      if(BlinkTimer<1500) {
+        digitalWrite(LedPin,0);
+      } else if(BlinkTimer<1600) {
+        digitalWrite(LedPin,1);
+      } else {
+        BlinkTimer=0;
+        digitalWrite(LedPin,0);
+      }
+    break;
+    case 1:
+      //Blinkmode 1 is activated when the Teensy receives a command
+      //Mode expires 500ms after the last command has been received resp. mode has been set
+      if(BlinkTimer>30) {
+        BlinkTimer=0;
+        digitalWrite(LedPin,!digitalRead(LedPin));
+      }
+      if(BlinkModeTimeoutTimer>500) {
+        SetBlinkMode(2);
+      }
+    break;
+    case 2:
+      //Blinkmode 2 is active while the Teensy is waiting for more commands
+      if(BlinkTimer<1500) {
+        digitalWrite(LedPin,0);
+      } else if(BlinkTimer<1600) {
+        digitalWrite(LedPin,1);
+      } else if(BlinkTimer<1700) {
+        digitalWrite(LedPin,0);
+      } else if(BlinkTimer<1800) {
+        digitalWrite(LedPin,1);
+      }else {
+        BlinkTimer=0;
+        digitalWrite(LedPin,0);
+      }
+      default:
+      //This should never be active
+      //The code is only here to make it easier to determine if a wrong Blinkcode has been set
+      if(BlinkTimer>2000) {
+        BlinkTimer=0;
+        digitalWrite(LedPin,!digitalRead(LedPin));
+      }
+      break;
+  }
+
+}
+
+
+//Outputs the data in the ram to the ledstrips
+void OutputData() {
+   leds.show();
+   Ack();
+}
+
+
+//Fills the given area of a ledstrip with a color
+void Fill() {
+  word firstLed=ReceiveWord();
+
+  word numberOfLeds=ReceiveWord();
+
+  int ColorData=ReceiveColorData();
+
+   if( firstLed<=configuredStripLength*8 && numberOfLeds>0 && firstLed+numberOfLeds-1<=configuredStripLength*8 ) {
+       word endLedNr=firstLed+numberOfLeds;
+       for(word ledNr=firstLed; ledNr<endLedNr;ledNr++) {
+         leds.setPixel(ledNr,ColorData);
+       }
+       Ack();
+   } else {
+     //Number of the first led or the number of leds to receive is outside the allowed range
+     Nack();
+   }
+
+
+}
+
+
+//Receives data for the ledstrips
+void ReceiveData() {
+  word firstLed=ReceiveWord();
+
+  word numberOfLeds=ReceiveWord();
+
+  if( firstLed<=configuredStripLength*8 && numberOfLeds>0 && firstLed+numberOfLeds-1<=configuredStripLength*8 ) {
+    //FirstLedNr and numberOfLeds are valid.
+    //Receive and set color data
+
+    word endLedNr=firstLed+numberOfLeds;
+    for(word ledNr=firstLed; ledNr<endLedNr;ledNr++) {
+      leds.setPixel(ledNr,ReceiveColorData());
+    }
+
+    Ack();
+
+  } else {
+    //Number of the first led or the number of leds to receive is outside the allowed range
+    Nack();
+  }
+}
+
+//Sets the length of the longest connected ledstrip. Length is restricted to the max number of allowed leds
+void SetLedStripLength() {
+   word stripLength=ReceiveWord();
+   if(stripLength<1 || stripLength>MaxLedsPerStrip) {
+     //stripLength is either to small or above the max number of leds allowed
+     Nack();
+   } else {
+     //stripLength is in the valid range
+     configuredStripLength=stripLength;
+     leds.setStripLength(stripLength);
+     leds.begin();  //Reinitialize the OctoWS2811 lib (not sure if this is needed)
+
+     Ack();
+   }
+}
+
+//Clears the data for all configured leds
+void  ClearAllLedData() {
+  for(word ledNr=0;ledNr<configuredStripLength*8;ledNr++) {
+    leds.setPixel(ledNr,0);
+  }
+  Ack();
+}
+
+
+//Sends the firmware version
+void SendVersion() {
+  Serial.write(FirmwareVersionMajor);
+  Serial.write(FirmwareVersionMinor);
+  Ack();
+}
+
+//Sends the max number of leds per strip
+void SendMaxNumberOfLeds() {
+  byte B=MaxLedsPerStrip>>8;
+  Serial.write(B);
+  B=MaxLedsPerStrip&255;
+  Serial.write(B);
+  Ack();
+}
+
+
+//Sends a ack (A)
+void Ack() {
+  Serial.write('A');
+}
+
+//Sends a NACK (N)
+void Nack() {
+  Serial.write('N');
+}
+
+//Receives 3 bytes of color data.
+int ReceiveColorData() {
+  while(!Serial.available()) {};
+  int colorValue=Serial.read();
+  while(!Serial.available()) {};
+  colorValue=(colorValue<<8)|Serial.read();
+  while(!Serial.available()) {};
+  colorValue=(colorValue<<8)|Serial.read();
+
+  return colorValue;
+
+
+}
+
+//Receives a word value. High byte first, low byte second
+word ReceiveWord() {
+  while(!Serial.available()) {};
+  word wordValue=Serial.read()<<8;
+  while(!Serial.available()) {};
+  wordValue=wordValue|Serial.read();
+
+  return wordValue;
+}
+
+// Colors for testing - assumes WS2812 color order of G, R, B
+/*
+#define RED    0x00FF00
+#define GREEN  0xFF0000
+#define BLUE   0x0000FF
+#define YELLOW 0xFFFF00
+#define PINK   0x10FF88
+#define ORANGE 0x45FF00
+#define WHITE  0xFFFFFF
+#define BLACK  0x000000
+*/
+
+// Less intense colors for testing - assumes WS2812 color order of G, R, B
+#define RED    0x003F00
+#define GREEN  0x3F0000
+#define BLUE   0x00003F
+#define YELLOW 0x3F3F00
+#define PINK   0x043F22
+#define ORANGE 0x0B3F00
+#define WHITE  0x3F3F3F
+#define BLACK  0x000000
+
+void Test() {
+  int microsec = 3000000;  // change them all in 3 seconds
+
+  ColorWipe(RED, microsec);
+  ColorWipe(GREEN, microsec);
+  ColorWipe(BLUE, microsec);
+  ColorWipe(YELLOW, microsec);
+  ColorWipe(PINK, microsec);
+  ColorWipe(ORANGE, microsec);
+  ColorWipe(WHITE, microsec);
+  ColorWipe(BLACK, microsec);
+}
+
+void ColorWipe(int color, int wait)
+{
+  for (int i=0; i < leds.numPixels(); i++) {
+    leds.setPixel(i, color);
+  }
+  leds.show();
+  delayMicroseconds(wait);
+}


DELETE: File misnamed

DELETE: File misnamed

--- microSD/microSD.ino/microSD.ino.ino
+++ microSD/microSD.ino/microSD.ino.ino
@@ -1,23 +0,0 @@
-#include <SD.h>                      // need to include the SD library
-#define SD_ChipSelectPin 10
-#include <TMRpcm.h>           //  also need to include this library...
-
-TMRpcm tmrpcm;   // create an object for use in this sketch
-
-void setup(){
-
-  tmrpcm.speakerPin = 9; //11 on Mega, 9 on Uno, Nano, etc
-
-  Serial.begin(9600);
-  if (!SD.begin(SD_ChipSelectPin)) {  // see if the card is present and can be initialized:
-    Serial.println("SD fail");
-    return;   // don't do anything more if not
-  }
-}
-
-void loop(){
-
-   tmrpcm.play("POESound.wav");
-
-
-}


Update iGPS.ino

Update iGPS.ino

修正缺失ADC_KEY

--- iGPS.ino
+++ iGPS.ino
@@ -36,6 +36,8 @@
 };

 #define NUM_KEYS 5
+
+int ADC_KEY[5] = { 50, 200, 400, 600, 800 };

 // GPS Serial
 SoftwareSerial GPSSerial(GPS_TX, GPS_RX); // RX, TX
@@ -312,15 +314,13 @@
         }
  */
 // Convert ADC value to key number
-int getKey() {
-  int input = analogRead(KEY_PIN);
-
-  int k = NUM_KEYS; // No valid key pressed
-
-  for (k = 0; k < NUM_KEYS; k++) {
-    if (input < ADC_KEY[k]) {
-      return k;
-    }
-  }
-  return k;
-}
+int LCD4884::getKey(void) {
+      int input = analogRead(KEY_PIN);
+
+	for (int k = 0; k < NUM_KEYS; k++) {
+		if (input < ADC_KEY[k]) {
+			return k;
+		}
+	}
+	return -1;
+}


Updated simple time stamps

Updated simple time stamps

--- Arduino/sketchbook/XbeeCppTest/XbeeCppTest.ino
+++ Arduino/sketchbook/XbeeCppTest/XbeeCppTest.ino
@@ -32,13 +32,15 @@
 time_t current_time;
 void setup()
 {
-  start_time = now();
+  //start_time = now();
+
   pinMode(led_pin, OUTPUT);
 	digitalWrite(led_pin, led_off);
 	digitalWrite(reset_pin, HIGH);
 	pinMode(reset_pin, OUTPUT);
   Serial.begin(BAUD_RATE);
   Serial.println("Starting the Receiver!");
+  second(start_time);
   Serial.print("Starting time: ");
   Serial.println(start_time);

@@ -94,7 +96,7 @@
 	}
 if(enable == 1)
 {
-    delay(2000);
+    delay(500);
   uint16_t length = tx_packet.prepare2send();
   uint16_t i;


Change pin for easier wiring on arduino nano

--- Arduino/KiteBarUnit/KiteBarUnit.ino
+++ Arduino/KiteBarUnit/KiteBarUnit.ino
@@ -13,15 +13,16 @@

 // Port definition

-#define     A_PIN  2 // Linear encoder one
-#define     B_PIN  3 // Linear encoder other one
-#define RESET_PIN  4 // Linear encoder absolute reference
+#define         A_PIN  2 // Linear encoder one
+#define         B_PIN  3 // Linear encoder other one
+#define     RESET_PIN  4 // Linear encoder absolute reference
+#define  DATA_OUT_PIN  5 // RF module ATAD pin
 #define   LED_PIN 13 // Built-in led
-const int   POT_PIN = A0; // Potentiometer
-const int LINE_TENSION_PIN = A1; // For line tension measurement
+const int   POT_PIN = A7; // Potentiometer
+const int LINE_TENSION_PIN = A6; // For line tension measurement

-RH_ASK driver(4800, 11, 12);
+RH_ASK driver(4800, 11, DATA_OUT_PIN);
 //Transmitter : ATAD D12

 uint8_t data[4];  // 2 element array of unsigned 8-bit type, holding Joystick readings


Send the current video index to a shift register

--- Arduino/LightPlayer/LightPlayer.ino
+++ Arduino/LightPlayer/LightPlayer.ino
@@ -7,6 +7,9 @@
 enum {
   SD_CHIP_SELECT = 4,
   APA106_DATA = 6,
+  SHIFT_REGISTER_CLOCK = 8,
+  SHIFT_REGISTER_LATCH = 9,
+  SHIFT_REGISTER_DATA = 10,
   SD_MISO = 11,
   SD_MOSI = 12,
   SD_CLK = 13,
@@ -142,6 +145,7 @@
 struct SdContext {
   FatFile dir;
   File file;
+  uint8_t index;
 };

 SdContext RootContext;
@@ -150,6 +154,7 @@

 #define infile (&(Context->file))
 #define curr_dir (&(Context->dir))
+#define curr_index (Context->index)

 unsigned long startMillis;

@@ -162,6 +167,10 @@
   pinMode(RF_REMOTE_BUTTON_C, INPUT_PULLUP);
   pinMode(RF_REMOTE_BUTTON_B, INPUT_PULLUP);
   pinMode(RF_REMOTE_BUTTON_A, INPUT_PULLUP);
+
+  pinMode(SHIFT_REGISTER_LATCH, OUTPUT);
+  pinMode(SHIFT_REGISTER_CLOCK, OUTPUT);
+  pinMode(SHIFT_REGISTER_DATA, OUTPUT);

   drawSplashScreen(frame);
   LEDstrip.sendPixels(sizeof(frame) / sizeof(*frame), frame);
@@ -554,6 +563,21 @@
   }
 }

+void updateVideoIndexDisplay()
+{
+  static uint8_t last_index;
+  if (curr_index == last_index) {
+    return;
+  }
+
+  last_index = curr_index;
+  digitalWrite(SHIFT_REGISTER_LATCH, LOW);
+  shiftOut(SHIFT_REGISTER_DATA, SHIFT_REGISTER_CLOCK, LSBFIRST, last_index - 1);
+  digitalWrite(SHIFT_REGISTER_LATCH, HIGH);
+
+  cout << F("\nUpdated video index display to video number ") << (int16_t)last_index;
+}
+
 void nextFile()
 {
   if (infile->isOpen()) {
@@ -564,16 +588,18 @@
     infile->openNext(curr_dir);
     if (infile->isOpen()) {
       if (!infile->isDir() && !infile->isHidden() && !infile->isSystem()) {
+        ++curr_index;
 #ifdef DEBUG
         char buf[13];
         infile->getName(buf, sizeof(buf));
-        cout << F("\nOpened file: ") << buf;
+        cout << F("\nnext opened file ") << (int16_t)curr_index << F(": ") << buf;
 #endif
         return;
       }
       infile->close();
     } else {
       curr_dir->rewind();
+      curr_index = 0;
     }
   }
 }
@@ -590,7 +616,16 @@
     if (index < 2) {
       // Advance to past last file of directory.
       dir_t dir;
-      while (curr_dir->readDir(&dir) > 0);
+      curr_index = 0;
+      while (curr_dir->readDir(&dir) > 0) {
+        if (dir.name[0] != DIR_NAME_DELETED
+            && !(dir.attributes & (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY
+                                   | DIR_ATT_HIDDEN | DIR_ATT_SYSTEM)))
+        {
+          ++curr_index;
+        }
+      }
+      ++curr_index;
       continue;
     }
     // position to possible previous file location.
@@ -601,10 +636,11 @@

       if (infile->isOpen()) {
         if (!infile->isDir() && !infile->isHidden() && !infile->isSystem()) {
+          --curr_index;
 #ifdef DEBUG
           char buf[13];
           infile->getName(buf, sizeof(buf));
-          cout << F("\nOpened prev file: ") << buf;
+          cout << F("\nprev opened file ") << (int16_t)curr_index << F(": ") << buf;
 #endif
           return;
         }
@@ -667,6 +703,7 @@
   }

   handleQueuedCommands();
+  updateVideoIndexDisplay();
   adjustFrameColors();

   unsigned long frame_time = 50 + frame_len * 25UL;


Corrected serial parsing logic. Corrected typo in active state define statement.

--- Arduino/SerialRelay/SerialRelay.ino
+++ Arduino/SerialRelay/SerialRelay.ino
@@ -21,9 +21,9 @@
 #define RELAY_5 6
 #define RELAY_6 7
 #define RELAY_7 8
-#define RELAY_8 13
+#define RELAY_8 9

-#define ACTIVE = LOW
+#define ACTIVE LOW

 void setup() {
   // Initialize pins. Set all pins inactive.
@@ -34,8 +34,8 @@

   // Initialize serial communication.
   Serial.begin(9600);
-  Serial.WriteLine("SerialRelay V1.0");
-  Serial.WriteLine("Ready ...");
+  Serial.write("SerialRelay V1.0");
+  Serial.write("Ready ...");
 }

 void TurnOffPins() {
@@ -47,38 +47,38 @@
 void loop() {
   // read the sensor:
   if (Serial.available() > 0) {
-    String inByte = Serial.readString();
+    int inByte = Serial.read();

     switch (inByte) {
-      case 'A':
+      case 'a':
         TurnOffPins();
         digitalWrite(RELAY_1, ACTIVE);
 	break;
-      case 'B':
+      case 'b':
         TurnOffPins();
         digitalWrite(RELAY_2, ACTIVE);
 	break;
-      case 'C':
+      case 'c':
         TurnOffPins();
         digitalWrite(RELAY_3, ACTIVE);
 	break;
-      case 'D':
+      case 'd':
         TurnOffPins();
         digitalWrite(RELAY_4, ACTIVE);
 	break;
-      case 'E':
+      case 'e':
         TurnOffPins();
         digitalWrite(RELAY_5, ACTIVE);
 	break;
-      case 'F':
+      case 'f':
         TurnOffPins();
         digitalWrite(RELAY_6, ACTIVE);
 	break;
-      case 'G':
+      case 'g':
         TurnOffPins();
         digitalWrite(RELAY_7, ACTIVE);
 	break;
-      case 'H':
+      case 'h':
         TurnOffPins();
         digitalWrite(RELAY_8, ACTIVE);
 	break;


Motor command interfaces

Motor command interfaces

--- rover/rover.ino
+++ rover/rover.ino
@@ -41,15 +41,92 @@
   if (adk.isReady()) {
       adk.read(&bytesRead, BUFFSIZE, buffer);
     if (bytesRead > 0) {
-      jeepCommandInterpreter(buffer[0]);
+      jeepCommandInterpreter(buffer[0], buffer[1]);
     }
   }
 }

-void jeepCommandInterpreter(uint8_t command) {
+void jeepCommandInterpreter(uint8_t command, uint8_t speed) {
   switch(command) {
+    case 0:
+      goForward(speed);
+      break;
+    case 1:
+      goBackward(speed);
+      break;
+    case 2:
+      goLeft(speed);
+      break;
+    case 3:
+      goRight(speed);
+      break;
     default:
       Serial.println("Command not available");
       break;
   }
 }
+
+// Main movement command
+void goForward(uint8_t speed) {
+}
+
+void goBackward(uint8_t speed) {
+  turnBack();
+  goForward(speed);
+}
+
+void goLeft(uint8_t speed) {
+  turnLeft();
+  goForward(speed);
+}
+
+void goRight(uint8_t speed) {
+  turnRight();
+  goForward(speed);
+}
+
+// Helper movement
+int speedToPower(uint8_t speed) {
+  int v;
+  switch(speed) {
+    case 1:
+      v = 150;
+      break;
+    case 2:
+      v = 250;
+      break;
+    case 3:
+      v = 300;
+      break;
+    default:
+      v = 0;
+      break;
+  }
+
+  // Return a safe motor power
+  return motorProtection(v);
+}
+
+void turnLeft() {
+}
+
+void turnRight() {
+}
+
+void turnBack() {
+}
+
+void stopEngine() {
+  motor.setM1Speed(0);
+  motor.setM2Speed(0);
+}
+
+// Emergency checks
+int motorProtection(int v) {
+  if (v <= MAX_POWER && v >= MIN_POWER) {
+    return v;
+  } else {
+    return 0;
+  }
+}
+


Support for switching music set

Support for switching music set

--- Guzheng/Guzheng.ino
+++ Guzheng/Guzheng.ino
@@ -20,6 +20,7 @@
  * analog values can cause strange values. Comment out the below if
  * you notice anything strange, because this is probably the culprit */
 #define NODELAY
+
 #ifndef NODELAY
 #define DELAY 10
 #endif
@@ -34,23 +35,24 @@

 // Values for different notes
 // Currently a C scale, starting from middle C (C4)
+#define note1 0x3C
+#define note2 0x3E
+#define note3 0x40
+#define note4 0x41
+#define note5 0x43
+#define note6 0x45
+#define note7 0x47
 #define note8 0x48
-#define note7 0x47
-#define note6 0x45
-#define note5 0x43
-#define note4 0x41
-#define note3 0x40
-#define note2 0x3E
-#define note1 0x3C
-
-#define note9 0x48
-#define note10 0x4A
-#define note11 0x4C
-#define note12 0x4D
-#define note13 0x4F
-#define note14 0x51
-#define note15 0x53
-#define note16 0x54
+
+// A minor scale
+#define note9 0x39
+#define note10 0x3B
+#define note11 0x3C
+#define note12 0x3E
+#define note13 0x40
+#define note14 0x41
+#define note15 0x43
+#define note16 0x45

 int r0 = 0;
 int r1 = 0;


fixed bug sending move

fixed bug sending move

--- tictactoe/tictactoe.ino
+++ tictactoe/tictactoe.ino
@@ -204,7 +204,6 @@
     }

     // 2- Send move to server
-    Serial.println("Sending move...");
     sendMove(player_move);

     // 3 -Check victory conditions
@@ -464,17 +463,21 @@

   //If ack -> notReceived = false
   //If wait_for_rival -> delay 1000
-  while(notReceived){
-    String res = sendAndWait(MSG_DO_MOVE + SEP_CHAR_COMMANDS + player_id + SEP_CHAR_PARAMETERS  + player_move +  END_CHAR);
-    String command = getCommand(res);
+  String res = sendAndWait(MSG_DO_MOVE + SEP_CHAR_COMMANDS + player_id + SEP_CHAR_PARAMETERS  + player_move +  END_CHAR);
+  String command = getCommand(res);
+  while(notReceived){
     if (command.startsWith(CMD_ACK)){
       Serial.println("Sent");
       notReceived = false;
     }
-    else if (command.startsWith(CMD_WAIT_FOR_RIVAL)){
+    else if (command.startsWith(CMD_WAIT_FOR_RIVAL) && command.startsWith(CMD_WAIT_FOR_TURN)){
       Serial.println("Waiting for the rival to retrieve previous move...");
       delay(1000);
-    }
+      res = sendAndWait(MSG_DO_MOVE + SEP_CHAR_COMMANDS + player_id + SEP_CHAR_PARAMETERS  + player_move +  END_CHAR);
+      command = getCommand(res);
+    } else {
+      Serial.println("Unknown command");
+    }
   }
 }


Added more invaders

Added more invaders


Update Ubidots_save_value.ino

Update Ubidots_save_value.ino

--- examples/Ubidots_save_value/Ubidots_save_value.ino
+++ examples/Ubidots_save_value/Ubidots_save_value.ino
@@ -5,18 +5,18 @@
 #include <Adafruit_FONA.h>

-#define APN "Your_apn_of_your_SIM_here"
-#define USER "Your_username_here"  // if your apn doesnt have username just put ""
-#define PASS "Your_password_here"  // if your apn doesnt have password just put ""
-#define TOKEN "Your_token_here"  // Remplace it with your token
-#define ID "Your_id_here" // Remplace it with your variable ID
+#define APN      // The APN of your operator
+#define USER ""  // if your apn doesnt have username just leave it ""
+#define PASS ""  // if your apn doesnt have password just leave it ""
+#define TOKEN "Your_token_here"  // Replace it with your Ubidots token
+#define ID "Your_id_here" // Replace it with your Ubidots' variable ID

 Ubidots client(TOKEN);

 void setup() {
   Serial.begin(115200);
   delay(2000);
-  client.gprsNetwork(F(APN),F(USER),F(PASS));  // First set your apn data
+  client.gprsNetwork(F(APN),F(USER),F(PASS));
 }

 void loop() {
@@ -25,5 +25,5 @@
   client.checkFona();
   client.gprsOnFona();
   client.save_value(value, ID);
-  delay(600);  // 600 milliseconds
-}+  delay(1000);
+}


Measuring total screen update time

Measuring total screen update time

--- ArduinoAudioSpectrumAnalyzer.ino
+++ ArduinoAudioSpectrumAnalyzer.ino
@@ -102,6 +102,22 @@
 	}
 }

+inline String paddedString(const String& s, const uint8_t width, const bool leftJustify = true /* otherwise right-justify */)
+{
+	String padded;
+
+	if (leftJustify)
+		padded = s;
+
+	for (int i = 0; i < (int)s.length() - width; ++i) // If len < s.length(), the loop will handle it correctly, i. e. do nothing
+		padded += ' ';
+
+	if (!leftJustify)
+		padded += s;
+
+	return padded;
+}
+
 void loop()
 {
 	if (samplingWindowFull)
@@ -111,27 +127,20 @@

 		memcpy(previousFhtValues, fht_log_out, FHT_N / 2);
 		runFHT();
+
+		const auto start = millis();
+
 		updateTextDisplay();
 		updateSpectrumDisplay();
 		updateVuDisplay();
+
+		tft.setTextSize(2);
+		tft.setTextColor(0x051F, 0x0000);
+		tft.setCursor(0, 0);
+		tft.print(paddedString(String(millis() - start), 4));
+
 		samplingWindowFull = false; // Allow the new sample set to be collected - only after the delay. Else the sample set would be 60 ms stale by the time we get to process it.
 	}
-}
-
-inline String paddedString(const String& s, const uint8_t width, const bool leftJustify = true /* otherwise right-justify */)
-{
-	String padded;
-
-	if (leftJustify)
-		padded = s;
-
-	for (int i = 0; i < (int)s.length() - width; ++i) // If len < s.length(), the loop will handle it correctly, i. e. do nothing
-		padded += ' ';
-
-	if (!leftJustify)
-		padded += s;
-
-	return padded;
 }

 #define RGB_to_565(R, G, B) static_cast<uint16_t>(((R & 0xF8) << 8) | ((G & 0xFC) << 3) | (B >> 3))
@@ -144,8 +153,6 @@

 inline void updateSpectrumDisplay()
 {
-	const auto start = millis();
-
 	assert(FHT_N == 256);
 	//for (int i = 1; i < 128; ++i) // What's the deal with bin 0?
 	//{
@@ -180,10 +187,6 @@
 	tft.setTextColor(RGB_to_565(0, 255, 10), RGB_to_565(0, 0, 0));
 	tft.setCursor(90, 0);
 	tft.print(paddedString(String(rmsHistory.back()), 4));
-
-	tft.setTextColor(RGB_to_565(0, 200, 255), RGB_to_565(0, 0, 0));
-	tft.setCursor(0, 0);
-	tft.print(paddedString(String(millis() - start), 4));
 }

 inline void updateTextDisplay()


Properly indent and comment code (noop)

Properly indent and comment code (noop)

--- HHI_switches_gripper/HHI_switches_gripper.ino
+++ HHI_switches_gripper/HHI_switches_gripper.ino
@@ -27,50 +27,55 @@
 int new_degrees = 0;

 void setup(){
-  Serial.begin(9600); //begin serial communications
-  ServoGripper.attach(GripPin); //Declare the Servo to be Connected to GripPin
-  pinMode(StimPin, OUTPUT); // Set TENS output to StimPin
-  for(int i = 0; i < NUM_LED; i++){ //initialize LEDs as outputs
-    pinMode(leds[i], OUTPUT);
-  pinMode(aQ1, OUTPUT);
-
-  }
-  MAX = MAX_High; //This sets the default to people with high EMG activity.
+    Serial.begin(9600); //begin serial communications
+    ServoGripper.attach(GripPin); //Declare the Servo to be Connected to GripPin
+    pinMode(StimPin, OUTPUT); // Set TENS output to StimPin
+    for(int i = 0; i < NUM_LED; i++){ //initialize LEDs as outputs
+        pinMode(leds[i], OUTPUT);
+        pinMode(aQ1, OUTPUT);
+    }
+    MAX = MAX_High; //This sets the default to people with high EMG activity.
 }

 void loop(){
-  for(int i = 0; i < 10; i++){    //take ten readings in ~0.02 seconds
-    reading[i] = analogRead(A0) * multiplier;
-    delay(2);
-  }
-  for(int i = 0; i < 10; i++){   //average the ten readings
-    finalReading += reading[i];
-  }
-  finalReading /= 10;
-  for(int j = 0; j < NUM_LED; j++){  //write all LEDs low and stim pin low
+    // take ten readings in ~0.02 seconds
+    for(int i = 0; i < 10; i++){
+        reading[i] = analogRead(A0) * multiplier;
+        delay(2);
+    }

-    digitalWrite(leds[j], LOW);
-    digitalWrite(StimPin, LOW);
-  }
-  Serial.println(finalReading);
-  finalReading = constrain(finalReading, 0, MAX);
-  litLeds = map(finalReading, 0, MAX, 0, NUM_LED);
+    // average the ten readings
+    for(int i = 0; i < 10; i++){
+        finalReading += reading[i];
+    }
+    finalReading /= 10;

-  for(int k = 0; k < litLeds; k++){
-    digitalWrite(leds[k], HIGH); // This turns on the LEDS
-    if (k >= Threshold){
-      digitalWrite(StimPin, HIGH); // This turns on the TENS as a function of which LED is lit
+    // write all LEDs low and stim pin low
+    for(int j = 0; j < NUM_LED; j++){
+        digitalWrite(leds[j], LOW);
+        digitalWrite(StimPin, LOW);
     }
-  }

-  new_degrees = map(finalReading, 0 ,MAX, 165, 0); //Translate the analog reading to degrees for the servo (from 165° to 0°).
+    Serial.println(finalReading);
+    finalReading = constrain(finalReading, 0, MAX);
+    litLeds = map(finalReading, 0, MAX, 0, NUM_LED);

-if (millis() - OldTime > UpdateTime){
-  if(abs(new_degrees-old_degrees) > threshold_degrees){
-    ServoGripper.write(new_degrees); //Move the servo according to the degrees calculated
-  }
-  OldTime = millis();
-  old_degrees = new_degrees;
-}
+    for (int k = 0; k < litLeds; k++) {
+        digitalWrite(leds[k], HIGH); // This turns on the LEDS
+        if (k >= Threshold) {
+            digitalWrite(StimPin, HIGH); // This turns on the TENS as a function of which LED is lit
+        }
+    }
+
+    // Translate the analog reading to degrees for the servo (from 165° to 0°).
+    new_degrees = map(finalReading, 0 ,MAX, 165, 0);
+
+    if (millis() - OldTime > UpdateTime) {
+        if(abs(new_degrees-old_degrees) > threshold_degrees) {
+            ServoGripper.write(new_degrees); //Move the servo according to the degrees calculated
+        }
+        OldTime = millis();
+        old_degrees = new_degrees;
+    }
 }


Abstracted battery volatge for roof

Abstracted battery volatge for roof

--- roof_sensor_serial/roof_sensor_serial.ino
+++ roof_sensor_serial/roof_sensor_serial.ino
@@ -20,6 +20,7 @@
 #define TEMP_PIN_1 12         // Temp Sensor connected to digital pin 12
 #define TEMP_PIN_1_TYPE DHT22 // Temp Sensor type
 #define TEMP_PIN_1_DELAY 10   // How often to update sensor
+#define BATTERY_DELAY 60      // How often to update voltage

 #define TEXT_RAIN_FLIP "RAIN FLIP" // serial text to print on rain flip
 #define TEXT_WIND_UPDATE "W:"      // serial text to print on wind update
@@ -35,6 +36,7 @@
 unsigned long lastmillis  = 0;           // last time main loop reported
 volatile byte half_revolutions = 0;      // number of wind (half) revolutions since reset
 int tempCounter    = 0;                  // counter for how many seconds since last temp reading
+int batteryCounter = 0;                  // counter for how many seconds since last battery reading

 DHT dht(TEMP_PIN_1, TEMP_PIN_1_TYPE);    // Declare the DHT sensor

@@ -62,6 +64,12 @@
       updateTemp();                         // then get us temp data
     } else {
       tempCounter++;                        // otherwise, increment loop count
+    }
+
+    if (batteryCounter > BATTERY_DELAY) { // if we've ran this loop 10 times
+      updateVoltage();                      // then get us temp data
+    } else {
+      batteryCounter++;                     // otherwise, increment loop count
     }

     lastmillis = millis();                  // update lastmillis
@@ -95,8 +103,6 @@
     Serial.print(TEXT_HUMIDITY);
     Serial.println(h);
   }
-  updateVoltage();
-
   tempCounter = 1;
 }


Temperature Polynomial Function

Temperature Polynomial Function

The code calculating the temperature from the temp sender was put in a function and removed from the loop to clean up the loop

--- WVO_Controller_0.6.3/WVO_Controller_0.6.3.ino
+++ WVO_Controller_0.6.3/WVO_Controller_0.6.3.ino
@@ -196,34 +196,10 @@
   p.x = map(p.x, TS_MINX, TS_MAXX, 0, 240);
   p.y = map(p.y, TS_MINY, TS_MAXY, 0, 320);

-  int sensorValue = analogRead(A11);
-  float voltage = sensorValue * (5.0 / 1023.0);
-  float v6 = voltage * voltage * voltage * voltage * voltage * voltage;
-  float v5 = voltage * voltage * voltage * voltage * voltage;
-  float v4 = voltage * voltage * voltage * voltage;
-  float v3 = voltage * voltage * voltage;
-  float v2 = voltage * voltage;
-
-  temp = (-1.4591 * v6 + 21.784 * v5 - 125.74 * v4 + 350.06 * v3 - 473.05 * v2 + 216.06 * voltage + 267.96) * 0.93;
-  // polynomial approximation of signal voltages vs temperature of temp sender with experimentally determined correction factor of 0.93.
-  // see excel sheet for more info.       C:\Users\Max\Google Drive\Sync\Bub\WVO Controller\Oil Temp gage values
-  //float voltage, degreesC, degreesF;			// calculate temperature reading based on voltages
-  //voltage = getVoltage(temperaturePin);
-  //degreesC = (voltage - 0.5) * 100.0;
-  //degreesF = degreesC * (9.0/5.0) + 32.0;
-  // subtract the last reading:
-  total = total - readings[index];              // read from the sensor:
-  readings[index] = temp;                       // add the reading to the total:
-  total = total + readings[index];              // advance to the next position in the array:
-  index = index + 1;                            // if we're at the end of the array...
-  if (index >= numReadings)                     // ...wrap around to the beginning:
-    index = 0;                                  // calculate the average:
-  average = total / numReadings;
-
+  temperature();
   screen_brightness();
   fuelGage();
   fuelPressure();
-

   if (page == 0 && purgeState == 0)
   {
@@ -1126,6 +1102,32 @@
   analogWrite(backlightPin, backlightValue);
 }

+void temperature()
+{
+  int sensorValue = analogRead(A11);
+  float voltage = sensorValue * (5.0 / 1023.0);
+  float v6 = voltage * voltage * voltage * voltage * voltage * voltage;
+  float v5 = voltage * voltage * voltage * voltage * voltage;
+  float v4 = voltage * voltage * voltage * voltage;
+  float v3 = voltage * voltage * voltage;
+  float v2 = voltage * voltage;
+
+  temp = (-1.4591 * v6 + 21.784 * v5 - 125.74 * v4 + 350.06 * v3 - 473.05 * v2 + 216.06 * voltage + 267.96) * 0.93;
+  // polynomial approximation of signal voltages vs temperature of temp sender with experimentally determined correction factor of 0.93.
+  // see excel sheet for more info.       C:\Users\Max\Google Drive\Sync\Bub\WVO Controller\Oil Temp gage values
+  //float voltage, degreesC, degreesF;      // calculate temperature reading based on voltages
+  //voltage = getVoltage(temperaturePin);
+  //degreesC = (voltage - 0.5) * 100.0;
+  //degreesF = degreesC * (9.0/5.0) + 32.0;
+  // subtract the last reading:
+  total = total - readings[index];              // read from the sensor:
+  readings[index] = temp;                       // add the reading to the total:
+  total = total + readings[index];              // advance to the next position in the array:
+  index = index + 1;                            // if we're at the end of the array...
+  if (index >= numReadings)                     // ...wrap around to the beginning:
+    index = 0;                                  // calculate the average:
+  average = total / numReadings;
+}

 //float getVoltage(int pin)				        // function that reads the value of the temperature pin and returns it
 // to be converted into a temperature value.


firmware: more semantic log

firmware: more semantic log

--- firmware/firmware.ino
+++ firmware/firmware.ino
@@ -310,7 +310,7 @@
   }else if(cmd[0]=='P'){
     Serial.print("POS X");Serial.print(curX);Serial.print(" Y");Serial.println(curY);
   }
-  Serial.println("OK");
+  Serial.println("Command received.");
 }

 // local data


Remove dead code

Remove dead code

--- moros/moros.ino
+++ moros/moros.ino
@@ -27,8 +27,6 @@
     interrupt_number = interrupt_number_;
     attachInterrupt(interrupt_number, interrupt_handler, RISING);
   };
-
-  static inline void handle_button_interrupt(int button);
 };

 class Screen {


Changed some time config

Changed some time config

--- src/Weather-Station.ino
+++ src/Weather-Station.ino
@@ -58,7 +58,7 @@

 int types[] = {BMP180T,BMP180P,DHT22T,DHT22H,DHT22HI,LDR,DS3231};
 unsigned long lastUpdate[] = {0,0,0,0,0,0,0};
-unsigned long updateTimes[] = {60000,60000,60000,60000,60000,30000,30000};
+unsigned long updateTimes[] = {60000,60000,60000,60000,60000,60000,60000};
 int pins[] = {NOTUSED,NOTUSED,NOTUSED,NOTUSED,NOTUSED,A1,NOTUSED};

 int secureAnalogRead(int pin) {
@@ -110,7 +110,8 @@
 #elif CONNECTION_TYPE == 1

 void sendCommand(String c, String v) {
-  String data = c + "_" + v;
+  RtcDateTime now = Rtc.GetDateTime();
+  String data = printDateTime(now) + "_" + c + "_" + v;
   const char* datachar = data.c_str();

   radio.powerUp();


親機判定論理のバグ

親機判定論理のバグ

--- 1_practice/esp32_17_talk/esp32_17_talk.ino
+++ 1_practice/esp32_17_talk/esp32_17_talk.ino
@@ -88,7 +88,7 @@
     if(!strlen(talk)) return;               // talkに代入されていれば以下を実行
     Serial.print(talk);                     // AquesTalkへ出力する
     Serial.print('\r');                     // 改行コード（CR）を出力する
-    if(mode==0) return;                     // 親機の時だけ以下を実施
+    if(mode) return;                        // 親機の時だけ以下を実施
     udp.beginPacket(SENDTO, PORT);          // UDP送信先を設定
     udp.print("atalk_0,");                  // 親機デバイス名を送信
     udp.println(talk);                      // 音声用データを他の子機へ送信


Delete balancing_tank.ino

Delete balancing_tank.ino

--- ESP8266/Water_Level_Temp/balancing_tank.ino
+++ ESP8266/Water_Level_Temp/balancing_tank.ino
@@ -1,413 +0,0 @@
-//Project: Monitor water level (HC-SR04P) of Balacing tank and the Temperature of Water (DS18b20) / Ambient (DHT22)
-//         Send alert via Blynk app if water level is too high, or water temperature is higher than 28 C
-
-/*
-//https://community.blynk.cc/t/water-tank-level-indicator-with-low-level-warning-notifications/26271
-
-//v1.0 - Wifi Manager + Blynk
-//v1.1 - added deep sleep function - https://community.blynk.cc/t/esp-deep-sleep/5622/13
-//v1.2 - added run time change of deep sleep interval via UI setup
-//v1.3 -
-
-//**** Blynk Virtual Pin Assignments****
-// V0 - Water temperature alert
-// V1 - Tank Height (cm)
-// V2 - Sensor distance from Tank (cm)
-// V3 - Temperature
-// V4 - Battery voltage
-// V6 - Numeric Widget - Sleep interval (mins)
-// V9 - Level V widget - Water Level %
-//V10 - Numeric Widget - Level exceed then will trigger Alert
-//V11 - Button Widget -  To enable / disable Alert
-//V12 - Distance - height from sensor to water level
-
-Hardware:
-1. Wemos D1 Pro
-2. DS18B20 Temperature Sensor
-3. Ultra Sonic Sensor
-4. 4.7k resistor - put between D4 and VCC
-
-
-Ultra sonic Sensor: Vcc - D7, Gnd - Gnd, Echo - D6, Trigger - D5
-DS18820 - Vcc - D8, Gnd - Gnd, Data - D4
-
-Todo
-----
-- if sonar sensor out of range --> don't save but Alert
-- water temperature alert
-
-*/
-
-#include <OneWire.h>
-#include <DallasTemperature.h>
-#include <ESP8266WiFi.h>
-#include <BlynkSimpleEsp8266.h>
-
-char auth[] = "<blynk toke>";n
-
-char ssid[] = "wifi";
-char pass[] = "pwd";
-
-BlynkTimer timer;
-
-//HC-SR04 ultra sonic sensor
-#define trigPin D5  // Trigger Pin
-#define echoPin D6  // Echo Pin
-#define RadarPowerPin D7 //GPIO12 = D6, GPIO14 = D5, GPIO15 = D8
-
-//DS18820 temperature sensor
-#define sensorPin D4
-#define TempPowerPin D8
-
-#define filterSamples   15              // filterSamples should  be an odd number, no smaller than 3
-
-int alertLevelCounter = 0; //Counter starts at zero
-//int volume1; // for smoothing algorithum
-double wLevel; // for smoothing algorithum
-int levelAlert;
-int wateralert = 0;
-//int sensSmoothArray1 [filterSamples];   // array for holding raw sensor values for sensor1
-int smoothDistance;                     // variables for sensor1 data
-
-//double alertInMin = 0.5;                //Alert time following alert water level being reached (0.5 = 30secs)
-//const int alertDuration = 2;            //Alert sent every 2 minutes
-
-int checkFreq = 2;                //how often run the check / sleep for how long before wake up, in mins
-int tankHeight = 100;             //tank's height
-int heightFrTank = 20;            //sensor distance from tank
-long duration, distance;          // Duration used to calculate distance
-
-//init DS11820
-OneWire oneWire(sensorPin);
-DallasTemperature DS18B20(&oneWire);
-float temp;
-float volt;
-
-BLYNK_CONNECTED() { // runs once at device startup, once connected to server.
-  Blynk.syncVirtual(V1);
-  Blynk.syncVirtual(V2);
-  Blynk.syncVirtual(V6);
-  Blynk.syncVirtual(V10);
-  Blynk.syncVirtual(V11);
-}
-
-BLYNK_WRITE(V1) {
-  tankHeight = param.asInt();
-  Serial.print("\nTank's Height: ");
-  Serial.println(tankHeight);
-  Serial.println();
-}
-
-BLYNK_WRITE(V2) {
-  heightFrTank = param.asInt();
-  Serial.print("Height from Tank: ");
-  Serial.println(heightFrTank);
-  Serial.println();
-}
-
-BLYNK_WRITE(V6) {
-  checkFreq = param.asInt();
-  Serial.print("Sleep Interval: ");
-  Serial.println(checkFreq);
-  Serial.println();
-}
-
-BLYNK_WRITE(V10) {
-  levelAlert = param.asInt();
-  Serial.print("Water Level Alert: ");
-  Serial.println(levelAlert);
-  Serial.println();
-}
-
-BLYNK_WRITE(V11) {
-
-  int alertOff = param.asInt();
-
-  if(alertOff == 0) {
-    resetWaterLevelAlert();
-    wateralert = 1;
-    Serial.print("Level Alert is OFF.");
-    Serial.println();
-  }
-  else {
-    resetWaterLevelAlert();
-    wateralert = 0;
-    Serial.print("Level Alert is ON.");
-    Serial.println();
-  }
-
-}
-
-void resetWaterLevelAlert() {
-  alertLevelCounter = 0;
-  wateralert = 0;
-}
-
-void checkWaterLevel() {
-  Serial.print("Water Level (%) = ");
-  Serial.println(wLevel);
-  Serial.print("Level Alert (%) = ");
-  Serial.println(levelAlert);
-  Serial.print("Alert (1 = off, 0 = on) = ");
-  Serial.println(wateralert);
-
-  if(wLevel > levelAlert && wateralert == 0){
-//    alertLevelCounter += 1;
-    Blynk.notify("Water Tank Level Alert"); // send push notification to blynk app
-
-  }
-
-//  if(alertLevelCounter > alertInMin * 60 && wateralert == 0){
-//    Blynk.notify("Water Tank Level Alert"); // send push notification to blynk app
-//    wateralert = 1;
-//    resetWaterLevelAlert();
-//  }
-}
-
-void MeasureCmForSmoothing() {
-
-  //take multiple reading
-
-  digitalWrite(RadarPowerPin, HIGH);  //provide power
-  delay(1000);
-
-    smoothDistance = mesureDistance();
-
-  digitalWrite(RadarPowerPin, LOW);  //turn off power
-  delay(100);
-
-  Serial.print("Smoothed Distance: ");
-  Serial.println(smoothDistance);
-
-  //tank height 100 cm, sensor is 20 cm above the tank
-  wLevel = (tankHeight + heightFrTank - smoothDistance);
-
-  Serial.print("Water Level (cm): ");
-  Serial.println(wLevel);
-
-  //convert to %
-  wLevel = wLevel / tankHeight * 100;
-
-  Serial.print("Water Level (%): ");
-  Serial.println(wLevel);
-
-  Blynk.virtualWrite(V12, smoothDistance); // virtual pin
-  Blynk.virtualWrite(V9, wLevel); // virtual pin
-  delay(1000);
-}
-
-void UploadMeasureCmForSmoothing() {
-
-  Blynk.virtualWrite(V3, temp); // Water level %
-  Blynk.virtualWrite(V4, volt); // battery
-  Blynk.virtualWrite(V9, wLevel); // Water level %
-  Blynk.virtualWrite(V12, smoothDistance); // virtual pin
-
-}
-
-
-void setup() {
-  Serial.begin(115200);
-  Blynk.begin(auth, ssid, pass);
-
-  pinMode(trigPin, OUTPUT);
-  pinMode(echoPin, INPUT);
-  //pin to provide power to ultra sonic sensor
-  pinMode(RadarPowerPin, OUTPUT);
-
-  //pin to provide power to temperature sensor
-  pinMode(TempPowerPin, OUTPUT);
-
-  Serial.println("Measure Water Temperature");
-  measurementEvent();
-
-  Serial.println("\nMeasure Water Level");
-  MeasureCmForSmoothing();
-
-  Serial.println("Upload Data");
-  UploadMeasureCmForSmoothing();
-
-  Serial.println("check WaterLevel Alert");
-  checkWaterLevel();
-
-  goToSleep();
-
-}
-
-void loop() {
-
-}
-
-int digitalSmooth(int rawIn, int *sensSmoothArray){     // "int *sensSmoothArray" passes an array to the function - the asterisk indicates the array name is a pointer
-int j, k, temp, top, bottom;
-long total;
-static int i;
-// static int raw[filterSamples];
-static int sorted[filterSamples];
-boolean done;
-
-i = (i + 1) % filterSamples;    // increment counter and roll over if necc. -  % (modulo operator) rolls over variable
-sensSmoothArray[i] = rawIn;                 // input new data into the oldest slot
-
-// Serial.print("raw = ");
-
- for (j=0; j<filterSamples; j++){     // transfer data array into anther array for sorting and averaging
-     sorted[j] = sensSmoothArray[j];
- }
-
-   done = 0;                // flag to know when we're done sorting
- while(done != 1){        // simple swap sort, sorts numbers from lowest to highest
-      done = 1;
-        for(j = 0; j < (filterSamples - 1); j++){
-           if(sorted[j] > sorted[j + 1]){     // numbers are out of order - swap
-             temp = sorted[j + 1];
-             sorted [j+1] =  sorted[j] ;
-             sorted [j] = temp;
-             done = 0;
-           }
-        }
-  }
-
-   // throw out top and bottom 15% of samples - limit to throw out at least one from top and bottom
-   //  bottom = max(((filterSamples * 15)  / 100), 1);
-   //  top = min((((filterSamples * 85) / 100) + 1  ), (filterSamples - 1));   // the + 1 is to make up for asymmetry caused by integer rounding
-   bottom = max(((filterSamples * 20)  / 100), 1);
-   top = min((((filterSamples * 80) / 100) + 1  ), (filterSamples - 1));   // the + 1 is to make up for asymmetry caused by integer rounding
-   k = 0;
-   total = 0;
-  for( j = bottom; j< top; j++){
- total += sorted[j];  // total remaining indices
- k++;
- //Serial.print(sorted[j]);
- //Serial.print("   ");
- //terminal.print(sorted[j]);
- //terminal.println("   ");
-
-  }
-   //terminal.print("average: ");
-   //terminal.println(total/k);
-   //terminal.flush();
-   //Serial.println();
-   //Serial.print("average = ");
-   //Serial.println(total/k);
-  return total / k;    // divide by number of samples
-}
-
-int mesureSingleDistance() {
-      long duration, distance;
-
-      digitalWrite(trigPin, LOW);
-      delayMicroseconds(2);
-      digitalWrite(trigPin, HIGH);
-      delayMicroseconds(10);
-      digitalWrite(trigPin, LOW);
-      duration = pulseIn(echoPin, HIGH);
-      distance = (duration/2) / 29.1;
-
-      Serial.print("Distance: ");
-      Serial.println(distance);
-
-      return distance;
-  }
-
-/**
- * mresure distnce average delay 10ms
- */
-int mesureDistance() {
-    const int ULTRASONIC_MIN_DISTANCE = heightFrTank;  //20
-    const int ULTRASONIC_MAX_DISTANCE = tankHeight + heightFrTank;  //120
-
-      int i, total_count = 0, total_distance = 0, distance, values[10], average, temp, new_count = 0;
-
-      for(i=0; i<5; i++){
-          distance = mesureSingleDistance();
-          //check if out of range
-          if(distance > ULTRASONIC_MIN_DISTANCE && distance < ULTRASONIC_MAX_DISTANCE) {
-              total_distance += distance;
-              values[total_count++]=distance;
-              Serial.printf("Value %d...\n", distance);
-          }
-      }
-
-      Serial.print("total_count = ");
-      Serial.println(total_count);
-      if(total_count > 0) {
-
-          average = total_distance / total_count;
-          total_distance = 0;
-          Serial.printf("Average %d...\n", average);
-
-          for(i=0; i<total_count; i++){
-              temp = (average - values[i])*100/average;
-              Serial.printf("Analyze %d....%d...\n", values[i],temp);
-              if(temp < 10 && temp > -10){
-                  total_distance += values[i];
-                  new_count++;
-              }
-          }
-
-          if(new_count > 0) {
-//              Serial.print("total_distance = ");
-//              Serial.println(total_distance);
-//              Serial.print("new_count = ");
-//              Serial.println(new_count);
-              return total_distance / new_count;
-          }
-      }
-      Serial.println("Sonar sensor out of range");
-      return 0;  //return 0 meaning the sensor out of range
-  }
-
-void goToSleep() {
-  // calculate required sleep time and go to sleep
-
-  Serial.print(" Going to sleep now for ");
-  Serial.print(checkFreq);
-  Serial.println(" mins");
-
-  ESP.deepSleep(checkFreq * 60 * 1000000); //deepSleep is microseconds 1 sec = 1000000
-  delay(100);
-
-} // end of void goToSleep()
-
-void measurementEvent() {
-
-
-  //******Measure Water Temperature*********************************************
-  digitalWrite(TempPowerPin, HIGH);  //provide power
-  delay(2000);
-
-  DS18B20.begin();
-  DS18B20.requestTemperatures();
-  temp = DS18B20.getTempCByIndex(0); // Celcius
-  Serial.print("Temperature (C) = ");
-  Serial.println(temp);
-
-  digitalWrite(TempPowerPin, LOW);  //turn off power
-  delay(100);
-
-  //******Battery Voltage Monitoring*********************************************
-  //depend on 220k or 100k resistor used, toggle between this 2 calculation
-
-  // using 220k
-  // Voltage divider R1=100k, R2 = (220k + 100k) + 220k = 540k
-  // Calculation to get the factor: 4.2v * 100/540 = 0.7777, 0.7777 * y = 4.2, y = 5.4
-//  float calib_factor = 5.28; // change this value to calibrate the battery voltage, 5.28 is so call calibrated
-//  float calib_factor = 5.4;
-
-  // using 100k
-  // Voltage divider R1 = 100k, R2 = (220k + 100k) + 100k = 420k;
-  // Calculation to get the factor: 4.2v * 100/420 = 1, 1 * y = 4.2, y = 4.2
-  float calib_factor = 4.2;
-
-  unsigned long raw = analogRead(A0);
-//  Serial.print("raw analog = ");
-//  Serial.println(raw);
-  float volt = raw * calib_factor/1024;
-
-  Serial.print( "\nVoltage = ");
-  Serial.print(volt, 2); // print with 2 decimal places
-  Serial.println (" V");
-
- //*******************************************************************************
-}


reduced distance between single frames

reduced distance between single frames

--- arduino/kurbel/kurbel.ino
+++ arduino/kurbel/kurbel.ino
@@ -24,8 +24,8 @@
 long last_value = 0;
 long act_value = 0;

-//int distance = 10; // how many ticks until keypress is fired, 10 seemed to result in ~8 keys per round
-int distance = 6; // how many ticks until keypress is fired, 10 seemed to result in ~8 keys per round
+int distance = 10; // how many ticks until keypress is fired, 10 seemed to result in ~8 keys per round
+//int distance = 6; // how many ticks until keypress is fired, 10 seemed to result in ~8 keys per round

 void loop() {


Include voltage reading

Include voltage reading

--- arduino/sender/sender.ino
+++ arduino/sender/sender.ino
@@ -212,7 +212,7 @@
       //digitalWrite(DEBUG_LED_MOTION, HIGH);

       char buf[50];
-      sprintf(buf, "c=%lu,F_DOWN_STAT", count);
+      sprintf(buf, "c=%lu,mv=%u,F_DOWN_STAT", count, readVcc());
       transmit(buf);

       count++;
@@ -220,7 +220,7 @@
       //digitalWrite(DEBUG_LED_MOTION, HIGH);

       char buf[50];
-      sprintf(buf, "c=%lu,F_UP_STAT", count);
+      sprintf(buf, "c=%lu,mv=%u,F_UP_STAT", count, readVcc());
       transmit(buf);

       count++;


Change order.

Change order.

--- examples/mqtt_simple_test/mqtt_simple_test.ino
+++ examples/mqtt_simple_test/mqtt_simple_test.ino
@@ -30,9 +30,22 @@
 MqttWrapper *mqtt;
 DHT *dht;

-void init_dht(DHT **dht, uint8_t pin, uint8_t dht_type);
-void read_dht(DHT *dht, float *temp, float *humid);

+
+void connect_wifi()
+{
+    WiFi.begin(ssid, pass);
+
+    int retries = 0;
+    while ((WiFi.status() != WL_CONNECTED))
+    {
+        Serial.print(".");
+        retries++;
+        delay(500);
+    }
+
+    Serial.println("WIFI CONNECTED ");
+}

 void callback(const MQTT::Publish& pub) {
     if (pub.payload_string() == "0") {
@@ -50,21 +63,6 @@
     }
 }

-void connect_wifi()
-{
-    WiFi.begin(ssid, pass);
-
-    int retries = 0;
-    while ((WiFi.status() != WL_CONNECTED))
-    {
-        Serial.print(".");
-        retries++;
-        delay(500);
-    }
-
-    Serial.println("WIFI CONNECTED ");
-}
-
 void hook_before_publish(JsonObject** root) {
   JsonObject& data = (*(*root))["d"];

@@ -80,11 +78,11 @@

 void setup() {
     Serial.begin(115200);
+    pinMode(0, INPUT_PULLUP);
     delay(10);

+    connect_wifi();
     init_dht(&dht, DHTPIN, DHTTYPE);
-
-    connect_wifi();

     mqtt = new MqttWrapper("128.199.104.122");
     mqtt->connect(callback);
@@ -94,7 +92,12 @@
 void loop() {
     mqtt->loop();

-    if (millis() % 12000 == 0) {
+    if (digitalRead(0) == LOW) {
+        while(digitalRead(0) == LOW) {
+            mqtt->loop();
+            yield();
+        }
         mqtt->sync_pub(String("0"));
     }
+
 }


Changed Point to TSPoint

Changed Point to TSPoint

In the latest version of the TouchScreen library ,
https://github.com/adafruit/Touch-Screen-Library
Class "Point" has been renamed TSPoint. I have updated this to reflect
that.

--- SWTFT-Shield/examples/tftpaint/tftpaint.ino
+++ SWTFT-Shield/examples/tftpaint/tftpaint.ino
@@ -77,7 +77,11 @@
 void loop()
 {
   digitalWrite(13, HIGH);
-  Point p = ts.getPoint();
+  // Recently Point was renamed TSPoint in the TouchScreen library
+  // If you are using an older version of the library, use the
+  // commented definition instead.
+  // Point p = ts.getPoint();
+  TSPoint p = ts.getPoint();
   digitalWrite(13, LOW);

   // if sharing pins, you'll need to fix the directions of the touchscreen pins