RC3 supporting MEGA & Tiny84

RC3 supporting MEGA & Tiny84

--- examples/RF12/RF12demo/RF12demo.ino
+++ examples/RF12/RF12demo/RF12demo.ino
@@ -3,9 +3,15 @@
 // 2009-05-06 <jc@wippler.nl> http://opensource.org/licenses/mit-license.php

 // this version adds flash memory support, 2009-11-19
-// Adding frequency features. 2013-09-05 JohnOH
-// Added postbox semaphore feature 2013-10-24 JohnOH
-
+// Adding frequency features. 2013-09-05
+// Added postbox semaphore feature 2013-10-24
+// For the ATTiny84 node number 15 is recommended since
+// this node number cannot be stored in eeprom
+// Node numbers 16-31 can only be used if MAX_NODES and thereby
+// the size of the nodes array is adjusted accordingly
+//
+// ATTiny84 listed to PA0 (DIO1) for command input
+//
 #include <JeeLib.h>
 #include <util/crc16.h>
 #include <avr/eeprom.h>
@@ -37,12 +43,12 @@
 #define LED_PIN   9     // activity LED, comment out to disable
 #endif
 ///////////   Workplace   //////////
-/*
+
 static unsigned long now () {
   // FIXME 49-day overflow
   return millis() / 1000;
 }
-*/
+
 static void activityLed (byte on) {
 #ifdef LED_PIN
   pinMode(LED_PIN, OUTPUT);
@@ -99,7 +105,7 @@
 static int value;
 static byte stack[RF12_MAXDATA+4], top, sendLen, dest;
 static byte testbuf[RF12_MAXDATA], testCounter, useHex;
-static byte nodes[MAX_NODES + 1];
+static byte nodes[MAX_NODES + 1];  // [0] is unused
 static byte band,postingsIn = 0, postingsOut = 0;

 void displayVersion(uint8_t newline );
@@ -693,8 +699,8 @@
 #endif
       break;
       case 'i': // set node id
-        if ((value > 0) && (value < 32)) {
-          nodes[value] = 0;                                      // Prevent allocation of this node number
+        if ((value > 0) && (value <= MAX_NODES + 1)) {                   // Node 15 can exist but only as the RF12Demo node
+          if (value < MAX_NODES) nodes[value] = 0;                       // Prevent allocation of this node number
           config.nodeId = (config.nodeId & 0xE0) + (value & 0x1F);
           saveConfig();
         }
@@ -712,7 +718,7 @@
             showString(PSTR("\rInvalid\n"));
         }
         break;
- /*
+
       case 'o': // Increment frequency within band
           Serial.print(frequency);
 ///
@@ -734,7 +740,7 @@
             Serial.println();
           }
         break;
- */
+
       case 'g': // set network group
         if (value <= 255) {
           config.group = value;
@@ -753,11 +759,7 @@
         break;
       case 't': // broadcast a maximum size test packet, request an ack
         cmd = 'a';
-#if defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny44__)
-        sendLen = RF12_MAXDATA - 50;
-#else
         sendLen = RF12_MAXDATA;
-#endif
         dest = 0;
         for (byte i = 0; i < RF12_MAXDATA; ++i)
           testbuf[i] = i + testCounter;
@@ -778,9 +780,6 @@
         if (value) activityLed(1);
         else activityLed(0);
         break;
-#endif
-#if defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny44__)
-#else
       case 'f': // send FS20 command: <hchi>,<hclo>,<addr>,<cmd>f
         rf12_initialize(0, RF12_868MHZ, 0);
         activityLed(1);
@@ -819,10 +818,10 @@
           showString(PSTR("erased\n"));
         }
         break;
+#endif
       case 'z': // put the ATmega in ultra-low power mode (reset needed)
         if (value == 123) Sleep;
         break;
-#endif
         case 'q': // turn quiet mode on or off (don't report bad packets)
         if (value) config.flags |= QUIET;
           else config.flags &= ~QUIET;


whoops

whoops

--- examples/RF12/RF12demo/RF12demo.ino
+++ examples/RF12/RF12demo/RF12demo.ino
@@ -4,7 +4,7 @@

 // this version adds flash memory support, 2009-11-19

-#define RF69_COMPAT 1 // define this to use the RF69 driver i.s.o. RF12
+#define RF69_COMPAT 0 // define this to use the RF69 driver i.s.o. RF12
 #include <JeeLib.h>
 #include <util/crc16.h>
 #include <util/parity.h>


Fixed error after renaming of static pin access function (InputPin::read).

--- examples/Canvas/CosaCanvasPins/CosaCanvasPins.ino
+++ examples/Canvas/CosaCanvasPins/CosaCanvasPins.ino
@@ -56,7 +56,7 @@
     tft.draw_rect(10, y, tft.WIDTH - 20, 16);
     tft.set_cursor(15, y + 5);
     cout.printf_P(PSTR("D%d"), x);
-    tft.set_pen_color(Pin::is_set(x) ? Canvas::RED : Canvas::GREEN);
+    tft.set_pen_color(InputPin::read(x) ? Canvas::RED : Canvas::GREEN);
     tft.fill_circle(35, y + 8, 5);
     tft.set_cursor(55, y + 5);
     cout.printf_P(PSTR("A%d %d"), x, AnalogPin::sample(x));


[feat] Initial counter code. Interrupt 1, Mega cards pin io pin number 3 is used to count electricity meters pulses. KWh is counted from these pulses and sent to IoT cloud. More structured way of reading counters is coming later.

--- heater_control.ino
+++ heater_control.ino
@@ -16,9 +16,15 @@
 char feedId[33] = ""; // Feed you want to push to
 char m2xKey[33] = ""; // Your M2X access key

+volatile unsigned int _kwCounter = 0;   // counter for the number of interrupts
+int digvalue=150; // in 30 seconds
+float analogvalue=1.0;
+float kw=0.0;
+
 IPAddress ip(192,168,1,177);
 IPAddress gateway(192,168,1, 1);
 IPAddress subnet(255, 255, 0, 0);
+

 struct dig2a
 {
@@ -39,6 +45,18 @@
   struct dig2a delta;
 };

+/*
+struct cnt {
+  int *counter;
+  char *name;
+  int flags;
+  int last_send;
+  struct dig2a prev;
+  struct dig2a diff;
+  struct dig2a scale;
+  struct dig2a measured;
+};
+*/

 struct ad adArr[]= {          //prev   dif    min       max         meas    delta
   {0,"boiler",       0,0,     0,0.0, 0,0.5, 174,21.0, 935, 100.0,  0,0.0,  0,0.0},
@@ -46,6 +64,12 @@
   {2,"hothousewater",0,0,     0,0.0, 0,0.5, 7,  21.0, 1023,100.0,  0,0.0,  0,0.0},
   {3,"radiator",     0,0,     0,0.0, 0,0.3, 7,  21.0, 539,  36.5,  0,0.0,  0,0.0}
 };
+
+/*
+struct cnt cntArr[] = {       //prev  dif    scale   measured
+  {&_kwCounter,"electricity",  0,0,     0,0.0, 0,0.3, 150,1.0,  0,0.0}
+}
+*/

 int readAdChannels(struct ad *ad, int cnt);
 String buildServerMsg(struct ad *ad,int cnt);
@@ -95,6 +119,7 @@
   setSyncProvider(getNtpTime);
   sched.every(1000,processAD);
   sched.every(200,checkEthernet);
+  attachInterrupt(1, elmeter, CHANGE);
 }

@@ -102,6 +127,12 @@
 {
   sched.update();
   refreshEvents();
+}
+
+
+void elmeter()
+{
+  _kwCounter++;
 }

 void processAD()
@@ -113,15 +144,27 @@
     resetAdChannels(adArr,sizeof(adArr) / sizeof(struct ad));
   readAdChannels(adArr,sizeof(adArr) / sizeof(struct ad));
   cnt++;
-  if (cnt==AD_SAMPLECNT) {
+  if ((cnt % AD_SAMPLECNT)==0) {
     sched.oscillate(13,150, LOW,2);
     calcAdChannels(adArr,sizeof(adArr) / sizeof(struct ad));
     sendM2X(adArr,sizeof(adArr) / sizeof(struct ad));
-    cnt=0;
-  }
-}
-
-
+    resetAdChannels(adArr,sizeof(adArr) / sizeof(struct ad));
+  }
+  if ((cnt % (AD_SAMPLECNT * 3))==0) {
+    calcKw();
+  }
+}
+
+
+void calcKw()
+{
+  static unsigned int prevCnt=0;
+
+  if (prevCnt!=0) {
+    kw=(_kwCounter-prevCnt) / (digvalue * analogvalue);
+  }
+  prevCnt=_kwCounter;
+}

 void checkEthernet()
 {
@@ -160,15 +203,19 @@

 int sendM2X(struct ad *ad,int cnt)
 {
-  const char *streamNames[4];
-  int counts[4];
-  const char *ats[4];
-  double values[4];
+  const char *streamNames[5];
+  int counts[5];
+  const char *ats[5];
+  double values[5];
   int m2xpos=0;
   String timebuf;
   char chbuf[22];
   int response;
-
+  static float prevkw=0.0;
+  static int cntLastSend=0;
+  bool timeout=false;
+  int ts;
+
   timebuf=String(year())+"-"+
     len2(month())+"-"+
     len2(day())+"T"+
@@ -186,6 +233,17 @@
       m2xpos++;
     }
   }
+  ts=now();
+  timeout=(ts-cntLastSend > measTimeout);
+  if (timeout || (abs(kw-prevkw) > 0.30)) {
+    values[m2xpos]=kw;
+    counts[m2xpos]=1;
+    ats[m2xpos]=chbuf;
+    streamNames[m2xpos]="electricity";
+    cntLastSend=ts;
+    prevkw=kw;
+    m2xpos++;
+  }
   if (m2xpos) {
     if (feedId[0]==0) {
       Serial.println("feed id not known");
@@ -268,7 +326,7 @@
 {
   int digital=0;
   int ddelta;
-  float adelta,foo;
+  float adelta;

   for (int analogChannel = 0; analogChannel < cnt; analogChannel++) {
     digital= analogRead(ad[analogChannel].port);
@@ -281,7 +339,7 @@
 {
   int digital=0;
   int ddelta;
-  float adelta,foo;
+  float adelta;
   int ts=now();
   bool timeout=false;


code format

code format

use 2 space for 1 tab like arduino ide

--- examples/ReadNUID/ReadNUID.ino
+++ examples/ReadNUID/ReadNUID.ino
@@ -42,67 +42,67 @@
 byte nuidPICC[3];

 void setup() {
-    Serial.begin(9600);
-    SPI.begin(); // Init SPI bus
-    rfid.PCD_Init(); // Init MFRC522
+  Serial.begin(9600);
+  SPI.begin(); // Init SPI bus
+  rfid.PCD_Init(); // Init MFRC522

-    for (byte i = 0; i < 6; i++) {
-        key.keyByte[i] = 0xFF;
-    }
+  for (byte i = 0; i < 6; i++) {
+    key.keyByte[i] = 0xFF;
+  }

-    Serial.println(F("This code scan the MIFARE Classsic NUID."));
-    Serial.print(F("Using the following key:"));
-    printHex(key.keyByte, MFRC522::MF_KEY_SIZE);
+  Serial.println(F("This code scan the MIFARE Classsic NUID."));
+  Serial.print(F("Using the following key:"));
+  printHex(key.keyByte, MFRC522::MF_KEY_SIZE);
 }

 void loop() {

-    // Look for new cards
-    if ( ! rfid.PICC_IsNewCardPresent())
-        return;
+  // Look for new cards
+  if ( ! rfid.PICC_IsNewCardPresent())
+    return;

-    // Verify if the NUID has been readed
-    if ( ! rfid.PICC_ReadCardSerial())
-        return;
+  // Verify if the NUID has been readed
+  if ( ! rfid.PICC_ReadCardSerial())
+    return;

-    Serial.print(F("PICC type: "));
-    MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
-    Serial.println(rfid.PICC_GetTypeName(piccType));
+  Serial.print(F("PICC type: "));
+  MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
+  Serial.println(rfid.PICC_GetTypeName(piccType));

-    // Check is the PICC of Classic MIFARE type
-    if (piccType != MFRC522::PICC_TYPE_MIFARE_MINI &&
-        piccType != MFRC522::PICC_TYPE_MIFARE_1K &&
-        piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
-        Serial.println(F("Your tag is not of type MIFARE Classic."));
-        return;
+  // Check is the PICC of Classic MIFARE type
+  if (piccType != MFRC522::PICC_TYPE_MIFARE_MINI &&
+    piccType != MFRC522::PICC_TYPE_MIFARE_1K &&
+    piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
+    Serial.println(F("Your tag is not of type MIFARE Classic."));
+    return;
+  }
+
+  if (rfid.uid.uidByte[0] != nuidPICC[0] ||
+    rfid.uid.uidByte[1] != nuidPICC[1] ||
+    rfid.uid.uidByte[2] != nuidPICC[2] ||
+    rfid.uid.uidByte[3] != nuidPICC[3] ) {
+    Serial.println(F("A new card has been detected."));
+
+    // Store NUID into nuidPICC array
+    for (byte i = 0; i < 4; i++) {
+      nuidPICC[i] = rfid.uid.uidByte[i];
     }
+
+    Serial.println(F("The NUID tag is:"));
+    Serial.print(F("In hex: "));
+    printHex(rfid.uid.uidByte, rfid.uid.size);
+    Serial.println();
+    Serial.print(F("In dec: "));
+    printDec(rfid.uid.uidByte, rfid.uid.size);
+    Serial.println();
+  }
+  else Serial.println(F("Card read previously."));

-    if (rfid.uid.uidByte[0] != nuidPICC[0] ||
-        rfid.uid.uidByte[1] != nuidPICC[1] ||
-        rfid.uid.uidByte[2] != nuidPICC[2] ||
-        rfid.uid.uidByte[3] != nuidPICC[3] ) {
-        Serial.println(F("A new card has been detected."));
+  // Halt PICC
+  rfid.PICC_HaltA();

-        // Store NUID into nuidPICC array
-        for (byte i = 0; i < 4; i++) {
-            nuidPICC[i] = rfid.uid.uidByte[i];
-        }
-
-        Serial.println(F("The NUID tag is:"));
-        Serial.print(F("In hex: "));
-        printHex(rfid.uid.uidByte, rfid.uid.size);
-        Serial.println();
-        Serial.print(F("In dec: "));
-        printDec(rfid.uid.uidByte, rfid.uid.size);
-        Serial.println();
-    }
-    else Serial.println(F("Card read previously."));
-
-    // Halt PICC
-    rfid.PICC_HaltA();
-
-    // Stop encryption on PCD
-    rfid.PCD_StopCrypto1();
+  // Stop encryption on PCD
+  rfid.PCD_StopCrypto1();
 }

@@ -110,18 +110,18 @@
  * Helper routine to dump a byte array as hex values to Serial.
  */
 void printHex(byte *buffer, byte bufferSize) {
-    for (byte i = 0; i < bufferSize; i++) {
-        Serial.print(buffer[i] < 0x10 ? " 0" : " ");
-        Serial.print(buffer[i], HEX);
-    }
+  for (byte i = 0; i < bufferSize; i++) {
+    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
+    Serial.print(buffer[i], HEX);
+  }
 }

 /**
  * Helper routine to dump a byte array as dec values to Serial.
  */
 void printDec(byte *buffer, byte bufferSize) {
-    for (byte i = 0; i < bufferSize; i++) {
-        Serial.print(buffer[i] < 0x10 ? " 0" : " ");
-        Serial.print(buffer[i], DEC);
-    }
+  for (byte i = 0; i < bufferSize; i++) {
+    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
+    Serial.print(buffer[i], DEC);
+  }
 }


Add code for particle boards

Add code for particle boards


Enhanced: Test InputDebounce library, using callback functions

--- examples/Test_InputDebounce_Callbacks/Test_InputDebounce_Callbacks.ino
+++ examples/Test_InputDebounce_Callbacks/Test_InputDebounce_Callbacks.ino
@@ -25,9 +25,11 @@
 #define BUTTON_DEBOUNCE_DELAY   20   // [ms]

 static const int pinLED = LED_BUILTIN; // 13
-static const int pinSwitch = 2;
+static const int pinSwitchA = 2;
+static const int pinSwitchB = 3;

-static InputDebounce buttonTest; // not enabled yet, setup has to be called later
+static InputDebounce buttonTestA; // not enabled yet, setup has to be called first, see setup() below
+static InputDebounce buttonTestB;

 void buttonTest_pressedCallback(uint8_t pinIn)
 {
@@ -65,19 +67,21 @@
   // init serial
   Serial.begin(9600);

-  Serial.println("Test InputDebounce library, using callbacks");
+  Serial.println("Test InputDebounce library, using callback functions");

-  // register callbacks
-  buttonTest.registerCallbacks(buttonTest_pressedCallback, buttonTest_releasedCallback, buttonTest_pressedDurationCallback);
+  // register callback functions (shared, used by all buttons)
+  buttonTestA.registerCallbacks(buttonTest_pressedCallback, buttonTest_releasedCallback, buttonTest_pressedDurationCallback);
+  buttonTestB.registerCallbacks(buttonTest_pressedCallback, buttonTest_releasedCallback, buttonTest_pressedDurationCallback);

-  // setup input button (debounced)
-  buttonTest.setup(pinSwitch, BUTTON_DEBOUNCE_DELAY, InputDebounce::PIM_INT_PULL_UP_RES);
+  // setup input buttons (debounced)
+  buttonTestA.setup(pinSwitchA, BUTTON_DEBOUNCE_DELAY, InputDebounce::PIM_INT_PULL_UP_RES);
+  buttonTestB.setup(pinSwitchB, BUTTON_DEBOUNCE_DELAY, InputDebounce::PIM_INT_PULL_UP_RES);

   // examples
-  // buttonTest.registerCallbacks(buttonTest_pressedCallback, buttonTest_releasedCallback, NULL);
-  // buttonTest.setup(pinSwitch);
-  // buttonTest.setup(pinSwitch, DEFAULT_INPUT_DEBOUNCE_DELAY);
-  // buttonTest.setup(pinSwitch, BUTTON_DEBOUNCE_DELAY, InputDebounce::PIM_EXT_PULL_UP_RES);
+  // buttonTestA.registerCallbacks(buttonTest_pressedCallback, buttonTest_releasedCallback, NULL); // no continuous pressed-on time duration
+  // buttonTestA.setup(pinSwitchA);
+  // buttonTestA.setup(pinSwitchA, BUTTON_DEBOUNCE_DELAY);
+  // buttonTestA.setup(pinSwitchA, DEFAULT_INPUT_DEBOUNCE_DELAY, InputDebounce::PIM_EXT_PULL_UP_RES);
 }

 void loop()
@@ -85,7 +89,8 @@
   unsigned long now = millis();

   // poll button state
-  buttonTest.process(now); // callbacks called in context of this function
+  buttonTestA.process(now); // callbacks called in context of this function
+  buttonTestB.process(now);

   delay(1); // [ms]
 }


Transfer changes made to circuit

Transfer changes made to circuit

--- PlainReflow.ino
+++ PlainReflow.ino
@@ -40,14 +40,16 @@
 PID control_PID(&PID_in, &PID_out, &PID_setpoint,2,5,1, DIRECT);

 // Digital outputs
+//     relay -> fan
+const int FAN = 3;
 //     relays -> heating elements
-const int HEATINGROD1 = 3;
-const int HEATINGROD2 = 4;
+const int HEATINGROD1 = 4;
+const int HEATINGROD2 = 5;
 //     MOSFET -> thermistor
 const int THERMISTOR_MOSFET = 13;

 // Analog input for temperature measurement:
-const int TEMP_INP = A0;
+const int TEMP_INP = A7;

 void plot_callback(void) {
   // plotting thread
@@ -106,6 +108,8 @@
     avg += analogRead(TEMP_INP);
   }
   avg /= 5;
+  // Disable thermistor again so it doesn't heat up / break
+  digitalWrite(THERMISTOR_MOSFET, HIGH);

   double inp_voltage = avg * 1.1 / 1023; // Reference voltage = 1.1V,
                                          // maximum value = 1023 (10 bits)
@@ -127,6 +131,8 @@
   oven_off();
   pinMode(HEATINGROD1, OUTPUT);
   pinMode(HEATINGROD2, OUTPUT);
+
+  pinMode(TEMP_INP, INPUT);

   // MOSFET for disabling thermistor:
   pinMode(THERMISTOR_MOSFET, OUTPUT);


added blynk functionality

added blynk functionality

--- SonoffBoilerplate.ino
+++ SonoffBoilerplate.ino
@@ -15,6 +15,7 @@
    gpio 14 - pin 5 on header

 */
+
 #define SONOFF_BUTTON    0
 #define SONOFF_RELAY    12
 #define SONOFF_LED      13
@@ -52,8 +53,12 @@
 const int CMD_BUTTON_CHANGE = 1;

 int cmd = CMD_WAIT;
-int state = HIGH;
-
+int relayState = HIGH;
+
+//inverted button state
+int buttonState = HIGH;
+
+static long startPress = 0;

 void tick()
 {
@@ -74,12 +79,20 @@

-static int relayState = 0;
-static long startPress = 0;
-
 void setState(int s) {
   digitalWrite(SONOFF_RELAY, s);
   digitalWrite(SONOFF_LED, (s + 1) % 2); // led is active low
+  Blynk.virtualWrite(6, s*255);
+}
+
+void turnOn() {
+  relayState = LOW;
+  setState(relayState);
+}
+
+void turnOff() {
+  relayState = HIGH;
+  setState(relayState);
 }

 void toggleState() {
@@ -95,6 +108,81 @@
   shouldSaveConfig = true;
 }

+
+void toggle() {
+  Serial.println("toggle state");
+  Serial.println(relayState);
+  relayState = relayState == HIGH ? LOW : HIGH;
+  setState(relayState);
+}
+
+void restart() {
+  ESP.reset();
+  delay(1000);
+}
+
+void reset() {
+  //reset settings to defaults
+  /*
+    WMSettings defaults;
+    settings = defaults;
+    EEPROM.begin(512);
+    EEPROM.put(0, settings);
+    EEPROM.end();
+  */
+  //reset wifi credentials
+  WiFi.disconnect();
+  delay(1000);
+  ESP.reset();
+  delay(1000);
+}
+
+
+//off - button
+BLYNK_WRITE(0) {
+  int a = param.asInt();
+  if (a != 0) {
+    turnOff();
+  }
+}
+
+//on - button
+BLYNK_WRITE(1) {
+  int a = param.asInt();
+  if (a != 0) {
+    turnOn();
+  }
+}
+
+//toggle - button
+BLYNK_WRITE(2) {
+  int a = param.asInt();
+  if (a != 0) {
+    toggle();
+  }
+}
+
+//restart - button
+BLYNK_WRITE(3) {
+  int a = param.asInt();
+  if (a != 0) {
+    restart();
+  }
+}
+
+//restart - button
+BLYNK_WRITE(4) {
+  int a = param.asInt();
+  if (a != 0) {
+    reset();
+  }
+}
+
+//status - display
+BLYNK_READ(5) {
+  Blynk.virtualWrite(5, relayState);
+}
+
 void setup()
 {
   Serial.begin(115200);
@@ -118,7 +206,7 @@
   EEPROM.get(0, settings);
   EEPROM.end();

-  if(settings.salt != EEPROM_SALT) {
+  if (settings.salt != EEPROM_SALT) {
     Serial.println("Invalid settings in EEPROM, trying with defaults");
     WMSettings defaults;
     settings = defaults;
@@ -130,7 +218,7 @@

   WiFiManagerParameter custom_blynk_text("Blynk config. <br/> No token to disable.");
   wifiManager.addParameter(&custom_blynk_text);
-
+
   WiFiManagerParameter custom_blynk_token("blynk-token", "blynk token", settings.blynkToken, 33);
   wifiManager.addParameter(&custom_blynk_token);

@@ -154,7 +242,7 @@
   //save the custom parameters to FS
   if (shouldSaveConfig) {
     Serial.println("Saving config");
-
+
     strcpy(settings.blynkToken, custom_blynk_token.getValue());
     strcpy(settings.blynkServer, custom_blynk_server.getValue());
     strcpy(settings.blynkPort, custom_blynk_port.getValue());
@@ -162,17 +250,17 @@
     Serial.println(settings.blynkToken);
     Serial.println(settings.blynkServer);
     Serial.println(settings.blynkPort);
-
+
     EEPROM.begin(512);
     EEPROM.put(0, settings);
     EEPROM.end();
   }
-
+
   //config blynk
-  if(strlen(settings.blynkToken) == 0) {
+  if (strlen(settings.blynkToken) == 0) {
     BLYNK_ENABLED = false;
-  }
-  if(BLYNK_ENABLED) {
+  }
+  if (BLYNK_ENABLED) {
     Blynk.config(settings.blynkToken, settings.blynkServer, atoi(settings.blynkPort));
   }

@@ -208,8 +296,8 @@
   //setup relay
   pinMode(SONOFF_RELAY, OUTPUT);

-  setState(HIGH);
-
+  turnOn();
+
   Serial.println("done setup");
 }

@@ -220,7 +308,7 @@
   //ota loop
   ArduinoOTA.handle();
   //blynk connect and run loop
-  if(BLYNK_ENABLED) {
+  if (BLYNK_ENABLED) {
     Blynk.run();
   }
   //delay(200);
@@ -230,37 +318,23 @@
       break;
     case CMD_BUTTON_CHANGE:
       int currentState = digitalRead(SONOFF_BUTTON);
-      if (currentState != state) {
-        if (state == LOW && currentState == HIGH) {
+      if (currentState != buttonState) {
+        if (buttonState == LOW && currentState == HIGH) {
           long duration = millis() - startPress;
           if (duration < 1000) {
             Serial.println("short press - toggle relay");
-            relayState = !relayState;
-            setState(relayState);
+            toggle();
           } else if (duration < 5000) {
             Serial.println("medium press - reset");
-            ESP.reset();
-            delay(1000);
+            restart();
           } else if (duration < 60000) {
             Serial.println("long press - reset settings");
-            //reset settings to defaults
-            /*
-            WMSettings defaults;
-            settings = defaults;
-            EEPROM.begin(512);
-            EEPROM.put(0, settings);
-            EEPROM.end();
-            */
-            //reset wifi credentials
-            WiFi.disconnect();
-            delay(1000);
-            ESP.reset();
-            delay(1000);
+            reset();
           }
-        } else if (state == HIGH && currentState == LOW) {
+        } else if (buttonState == HIGH && currentState == LOW) {
           startPress = millis();
         }
-        state = currentState;
+        buttonState = currentState;
       }
       break;
   }


battery percent position

battery percent position


renamed ramming speed t super speed

renamed ramming speed t super speed

--- master/master.ino
+++ master/master.ino
@@ -1228,7 +1228,7 @@
 		if (ballInZone && goalDetected && abs(goalAngle) < 10){
 			// GO!
 			targetDir = goalAngle;
-			targetVelocity = RAMMING_SPEED;
+			targetVelocity = SUPER_SPEED;
 			// kick!
 			if (capChargedTime > kickTime){
 				kick();


Simpify code.

Simpify code.

--- lib-arduino/ACNode/examples/ExtractorfanNode/ExtractorfanNode.ino
+++ lib-arduino/ACNode/examples/ExtractorfanNode/ExtractorfanNode.ino
@@ -203,7 +203,7 @@
     machinestate = WAITING;
   }

-  digitalWrite(RELAY_GPIO, laststate == RUNNING ? 1 : 0));
+  digitalWrite(RELAY_GPIO, (laststate == RUNNING) ? 1 : 0);

   aartLed.set(state[machinestate].ledState);


little

little

--- testarduino/sw18020p/sw18020p.ino
+++ testarduino/sw18020p/sw18020p.ino
@@ -1,3 +1,5 @@
+// SW-18020P Electronic Vibration Sensor
+// https://www.youtube.com/watch?v=z7SdrIMMTj0
 // Connection
 // +5V -> SW18020P -> R330ohm -> LED -> GND
 void setup() {}


Refactoring

Refactoring

--- module/module.ino
+++ module/module.ino
@@ -107,7 +107,7 @@
 			Serial.print(messages.cardUpdated);
 			delay(timeToRemoveCard);
 		}
-		// -----------------------------------------------------------------
+		// --------------------------------------------------------------------
   		// Push to ThingSpeak
   		// Turn LED off
 		digitalWrite(ledPin, LOW);
@@ -120,7 +120,7 @@
 		}
 		updateThingSpeak(userID, elapsedTime);
 		lastSend = millis();
-		// -----------------------------------------------------------------
+		// --------------------------------------------------------------------
 		// Finished, prepare for next loop by switching to RFID serial port
 		Serial.println(messages.done);
 	}
@@ -148,7 +148,7 @@
 	const int pollInterval = 900;
 	const int minCount = 6;
 	// some variables used in this scope
-	unsigned char serialBuffer[bufferSizeSNR];
+	unsigned char serialNumber[bufferSizeSNR];
 	unsigned long startTime = 0;
 	unsigned int periodX, periodY;
 	unsigned int lastPeriodX, lastPeriodY;
@@ -168,7 +168,7 @@
 		// Polling logic (approximately every second)
 		sendCommand(CMD_GET_SNR, blockID, machineID, keyA, NULL);
 		// if card is missing, increment a counter
-		if (!getResponse(serialBuffer)) {
+		if (!getResponse(serialNumberk)) {
 			pollCounter += 1;
 			// if the counter reaches a specified timeout, return
 			if (pollCounter == pollTimeout) {


Fixed typo

Fixed typo

--- module/module.ino
+++ module/module.ino
@@ -168,7 +168,7 @@
 		// Polling logic (approximately every second)
 		sendCommand(CMD_GET_SNR, blockID, machineID, keyA, NULL);
 		// if card is missing, increment a counter
-		if (!getResponse(serialNumberk)) {
+		if (!getResponse(serialNumber)) {
 			pollCounter += 1;
 			// if the counter reaches a specified timeout, return
 			if (pollCounter == pollTimeout) {
@@ -276,4 +276,4 @@

 unsigned int calculateTime(unsigned int startTime) {
 	return (millis() - startTime)/1000;
-}+}


Arduino: Feature/Fix: Reset variable for linear actuator cmd to 0, so there needs to be a continuous stream of data to actuate motor.

--- Arduino/soil_sensor_w_linear_actuator/soil_sensor_w_linear_actuator.ino
+++ Arduino/soil_sensor_w_linear_actuator/soil_sensor_w_linear_actuator.ino
@@ -51,7 +51,6 @@

 void setup()
 {
-
    // Initialize ROS node
    nh.initNode();
    nh.advertise(pub_temp);
@@ -107,8 +106,8 @@
   humid_msg.data = humidity;
   pub_temp.publish(&temp_msg);
   pub_humid.publish(&humid_msg);
-  pub_linear_command_echo.publish(&linear_actuator_cmd_echo_msg);
-
+  pub_linear_command_echo.publish(&linear_actuator_cmd_echo_msg); // Topic to ensure linear_actuator_cmd msg is received
+
   //Serial.println(linear_actuator_cmd);
   // For ROS
   // 1
@@ -117,22 +116,32 @@
     analogWrite(PWMA, 64);
     digitalWrite(AIN1, HIGH);       // sets the digital pin 13 on
     digitalWrite(AIN2, LOW);        // sets the digital pin 13 off
-
-  }
-
-  // 0
-  else if (linear_actuator_cmd == 10) // Stop
-  {
-    analogWrite(PWMA, 0);
-  }
-
+
+  }// End else if for moving down
+
   // 2
   else if (linear_actuator_cmd == 12) // Move up
   {
     analogWrite(PWMA, 64);
     digitalWrite(AIN1, LOW);       // sets the digital pin 13 on
     digitalWrite(AIN2, HIGH);  // LOW, LOW -> Freeze, HIGH, HIGH -> Freeze
-  }
+  } // End else if for moving up
+
+  // 0: By Default, it should stop unless a signal is given
+  else // if (linear_actuator_cmd == 10) // Stop
+  {
+    analogWrite(PWMA, 0);
+  } // End else
+
+  // After publishing the echo message.
+  // Set it to be 0, so that a continuous stream of linear_actuator_cmd messages have to be sent
+  // If it is not set to non-zero in the next time step, the else would trigger and turn off the motor
+  linear_actuator_cmd_echo_msg.data = 0;
+
+  // Reset the variable for the linear actuator cmd to 0, so there needs to be a continuous stream of data for it to actuate the motor
+  // linear_actuator_cmd = 0; This does not work, as actuator_msg.data is still the old value, linear_actuator_cmd takes value from actuator_msg.data
+  actuator_msg.data = 0;
+

   // Test
   //nh.loginfo("Linear Actuator Cmd: %d", linear_actuator_cmd);
@@ -152,6 +161,8 @@
     //Serial.print("I received: ");
     //Serial.println(incomingByte, DEC);

+    // The code in here is to test the logic when using Serial monitor to send the inputs into the ProMini
+    // Instead of using a ROS topic
     // 1
     if (incomingByte == 49)// Move down
     {
@@ -175,8 +186,16 @@
     {
       analogWrite(PWMA, 0);
     }
-
+
+    // If Serial Testing used...Earlier intermediate testing code
+    // Reset incoming Byte to 0 at end of receiving the message
+    incomingByte = 0;
   } // End Serial.available()
+
+  //if (incomingByte != 48) or (incomingByte != 49)
+  //{
+  //  analogWrite(PWMA, 0);
+  //}

   // For Debugging
   // Waiting for Serial Input
@@ -187,4 +206,4 @@

   //nh.spinOnce();

-}
+} // End of Main Loop


code cleanup with the same functionality

--- WS2812_Test.ino
+++ WS2812_Test.ino
@@ -1,150 +1,78 @@
-// Uncomment this line if you have any interrupts that are changing pins - this causes the library to be a little bit more cautious
-// #define FAST_SPI_INTERRUPTS_WRITE_PINS 1
-
-// Uncomment this line to force always using software, instead of hardware, SPI (why?)
-// #define FORCE_SOFTWARE_SPI 1
-
-// Uncomment this line if you want to talk to DMX controllers
-// #define FASTSPI_USE_DMX_SIMPLE 1
-
 #include "FastSPI_LED2.h"

+// define the number of LEDs
 #define NUM_LEDS 120

 CRGB leds[NUM_LEDS];

 void setup() {
-  // sanity check delay - allows reprogramming if accidently blowing power w/leds
-  delay(1000);
+    // sanity check delay - allows reprogramming if accidently blowing power w/leds
+    delay(1000);

-  // For safety (to prevent too high of a power draw), the test case defaults to
-  // setting brightness to 50% brightness
-  LEDS.setBrightness(127);
+    // setting brightness to 25%
+    LEDS.setBrightness(63);

-  LEDS.addLeds<WS2811, 13>(leds, NUM_LEDS);
-
-  //reset all the LEDs
-  memset(leds, 0,  NUM_LEDS * sizeof(struct CRGB));
-  LEDS.show();
+    LEDS.addLeds<WS2811, 13, GRB>(leds, NUM_LEDS); //GRB for the correct color order
+
+    //reset all the LEDs
+    memset(leds, 0,  NUM_LEDS * sizeof(struct CRGB));
+    LEDS.show();
 }

 void loop()
 {
-  for(int i = 0; i < NUM_LEDS; i++)
-  {
-    memset(leds, 0,  NUM_LEDS * sizeof(struct CRGB));
-
-    int pos = i;
-    for(int j = 0; j < 10; j++)
+    for(int i = 0; i < NUM_LEDS; i++)
     {
-      if(pos - j >= 0)
-      {
-        leds[pos - j].g = 128 - (j * 10);
-      }
-      else
-      {
-        leds[pos + NUM_LEDS - j].g = 128 - (j * 10);
-      }
+        memset(leds, 0,  NUM_LEDS * sizeof(struct CRGB));
+
+        int pos = i;
+
+        for(int color = 0; color < 6; color++)
+        {
+            CRGB curColor;
+            switch(color)
+            {
+            case 0:
+                curColor = CRGB(255,0,0);
+                break;
+            case 1:
+                curColor = CRGB(0,255,0);
+                break;
+            case 2:
+                curColor = CRGB(0,0,255);
+                break;
+            case 3:
+                curColor = CRGB(200,200,0);
+                break;
+            case 4:
+                curColor = CRGB(200,0,200);
+                break;
+            case 5:
+                curColor = CRGB(0,200,200);
+                break;
+            }
+
+            for(int j = 0; j < 10; j++)
+            {
+                if(pos - j >= 0)
+                {
+                    leds[pos - j] = curColor;
+                }
+                else
+                {
+                    leds[pos + NUM_LEDS - j] = curColor;
+                }
+                curColor.nscale8(180);
+            }
+
+            pos = pos + (NUM_LEDS / 6);
+            if(pos >= NUM_LEDS)
+            {
+                pos = pos - NUM_LEDS;
+            }
+        }
+
+        LEDS.show();
+        delay(100);
     }
-
-    pos = pos + (NUM_LEDS / 6);
-    if(pos >= NUM_LEDS)
-    {
-      pos = pos - NUM_LEDS;
-    }
-
-    for(int j = 0; j < 10; j++)
-    {
-      if(pos - j >= 0)
-      {
-        leds[pos - j].r = 128 - (j * 10);
-      }
-      else
-      {
-        leds[pos + NUM_LEDS - j].r = 128 - (j * 10);
-      }
-    }
-
-    pos = pos + (NUM_LEDS / 6);
-    if(pos >= NUM_LEDS)
-    {
-      pos = pos - NUM_LEDS;
-    }
-
-    for(int j = 0; j < 10; j++)
-    {
-      if(pos - j >= 0)
-      {
-        leds[pos - j].b = 128 - (j * 10);
-      }
-      else
-      {
-        leds[pos + NUM_LEDS - j].b = 128 - (j * 10);
-      }
-    }
-
-    pos = pos + (NUM_LEDS / 6);
-    if(pos >= NUM_LEDS)
-    {
-      pos = pos - NUM_LEDS;
-    }
-
-    for(int j = 0; j < 10; j++)
-    {
-      if(pos - j >= 0)
-      {
-        leds[pos - j].g = 128 - (j * 10);
-        leds[pos - j].r = 128 - (j * 10);
-      }
-      else
-      {
-        leds[pos + NUM_LEDS - j].g = 128 - (j * 10);
-        leds[pos + NUM_LEDS - j].r = 128 - (j * 10);
-      }
-    }
-
-    pos = pos + (NUM_LEDS / 6);
-    if(pos >= NUM_LEDS)
-    {
-      pos = pos - NUM_LEDS;
-    }
-
-    for(int j = 0; j < 10; j++)
-    {
-      if(pos - j >= 0)
-      {
-        leds[pos - j].r = 128 - (j * 10);
-        leds[pos - j].b = 128 - (j * 10);
-      }
-      else
-      {
-        leds[pos + NUM_LEDS - j].r = 128 - (j * 10);
-        leds[pos + NUM_LEDS - j].b = 128 - (j * 10);
-      }
-    }
-
-    pos = pos + (NUM_LEDS / 6);
-    if(pos >= NUM_LEDS)
-    {
-      pos = pos - NUM_LEDS;
-    }
-
-    for(int j = 0; j < 10; j++)
-    {
-      if(pos - j >= 0)
-      {
-        leds[pos - j].b = 128 - (j * 10);
-        leds[pos - j].g = 128 - (j * 10);
-      }
-      else
-      {
-        leds[pos + NUM_LEDS - j].b = 128 - (j * 10);
-        leds[pos + NUM_LEDS - j].g = 128 - (j * 10);
-      }
-    }
-
-
-    LEDS.show();
-    delay(100);
-  }
 }


Reduced protocol size

Reduced protocol size

--- arduino/RemoteSocketControl/RemoteSocketControl.ino
+++ arduino/RemoteSocketControl/RemoteSocketControl.ino
@@ -30,12 +30,16 @@
   if (Serial.available()){

     // blocking read, wait for a incoming request
-    long inc = Serial.parseInt();
+    byte inc = Serial.read();

     // parse incoming request according to specificied protocol
-    byte group = (inc & 0xFF0000) >> 16;
-    byte socket = (inc & 0xFF00) >> 8;
-    byte state = inc & 0xFF;
+    byte group = inc >> 4;
+    byte socket = (inc & 0x14) >> 1;
+    byte state = inc & 0x1;
+
+    Serial.println(group, DEC);
+    Serial.println(socket, DEC);
+    Serial.println(state, DEC);

     // get the command
     int command = groups[group].sockets[socket].off;


[added] dirty logic to test PGA309

[added] dirty logic to test PGA309

--- arduino_sketches/PGA309/testPin_I2C/testPin_I2C.ino
+++ arduino_sketches/PGA309/testPin_I2C/testPin_I2C.ino
@@ -2,19 +2,28 @@
 #include "PGA309.h"

 #define PGA309ADDR 0x40
+#define REG3 0x0500
+#define REG4 0x8000
+#define REG6 0x0600

 PGA309 pga(PGA309ADDR);

 void setup() {
 	Serial.begin(9600);
 	Wire.begin();
-	Serial.println(pga.getAddress());
 	byte* data;

 	//Setting the test pin high enables direct writing of internal registers and stops transactions with External EEPROM
 	pga.enableTestPin();
-	Serial.print("Status of writing to the PGA309 internal register: ");
-	Serial.println(pga.writePGA309Register(0x03, 0x1248));
+	Serial.print("Status of writing to the PGA309 internal register 3: ");
+	Serial.println(pga.writePGA309Register(0x03, REG3));
+	delay(10);
+	Serial.print("Status of writing to the PGA309 internal register 4: ");
+	Serial.println(pga.writePGA309Register(0x04, REG4));
+	delay(10);
+	Serial.print("Status of writing to the PGA309 internal register 6: ");
+	Serial.println(pga.writePGA309Register(0x06, REG6));
+	delay(10);
 	int testdata;
 	testdata = pga.readPGA309Register(0x03);
 	if (testdata != 0){
@@ -27,7 +36,35 @@
 			Serial.print(pga.binaryFormat(data[i],8));
 			Serial.print(" ");
 		}
+		Serial.println();
 	}
+	testdata = pga.readPGA309Register(0x04);
+	if (testdata != 0){
+		Serial.print("There was error while reading: ");
+		Serial.println(testdata);
+	} else {
+		Serial.print("Successfully read data from the register. Data: ");
+		data = pga.getRecData();
+		for (int i = 0; i < 2; i++){
+			Serial.print(pga.binaryFormat(data[i],8));
+			Serial.print(" ");
+		}
+		Serial.println();
+	}
+	testdata = pga.readPGA309Register(0x06);
+	if (testdata != 0){
+		Serial.print("There was error while reading: ");
+		Serial.println(testdata);
+	} else {
+		Serial.print("Successfully read data from the register. Data: ");
+		data = pga.getRecData();
+		for (int i = 0; i < 2; i++){
+			Serial.print(pga.binaryFormat(data[i],8));
+			Serial.print(" ");
+		}
+		Serial.println();
+	}
+
 }

 void loop() {


Toggle backlight with Light button

Toggle backlight with Light button

--- TiLDA_Mke/examples/HelloWorld/HelloWorld.ino
+++ TiLDA_Mke/examples/HelloWorld/HelloWorld.ino
@@ -42,6 +42,10 @@
  */
 void button_handler(buttonid_t id, uint8_t state)
 {
+  // Toggle backlight on pressing Light button
+  if(state && (id == BUTTON_LIGHT))
+    tilda.setBacklight(!tilda.backlight());
+
   SerialUSB.print("Button ");
   SerialUSB.print(id);
   if(state)


[refact] changed more OO style coding. Plain C seems to be hard to handle. More OO to come..

--- heater_control.ino
+++ heater_control.ino
@@ -99,29 +99,31 @@
   int method;
 };

-struct bypassValve {
-  char *name;
-  struct ad *actualTemp;
-  time_t changed;
-  int up;
-  int dn;
-  float targetAd;
-  int timeMultiplier;
-  int latency;         // seconds, how long does it take after up, or down op the realise change in targetAd.
-  float hysteresis;
-  int minTurntime;     // milliseconds
-  int maxTurntime;     // milliseconds
-};
-
-
-
+class bypassValve {
+ public:
+  bypassValve(char *name,float *actual,int up,int dn,int timeMultiplier,int latency,float sensitivity,int minTurnTime,int maxTurnTime);
+  void setTarget(float val);
+  int turnBypass(time_t ts);
+
+ private:
+  char *_name;
+  float *_actualTemp;
+  time_t _changed;
+  int _up;
+  int _dn;
+  float _targetTemp;
+  int _timeMultiplier;
+  int _latency;         // seconds, how long does it take after up, or down op the realise change in targetAd.
+  float _sensitivity;
+  int _minTurnTime;     // milliseconds
+  int _maxTurnTime;     // milliseconds
+};

 struct variable variables[]= {
   {"boilTemp",      0,24.5},
   {"boilHysteresis",0, 1.5},
   {"boilReduced",   0,24.0},
   {"hhboil",        0,25.0},
-  {"radiatorReq",   0,22.0}, // radiator requested temperature
   {"radiatorAdd",   0,16.0},
   {"null",          0,0.0 }
 };
@@ -135,9 +137,7 @@
   {5,"radiator",     0,0,     0,0.0, 0,0.3, 7,  21.0, 539,  36.5,  0,-273.0,  0,0.0}
 };

-struct bypassValve bypasses[]= {
-  {"heating",&adArr[3],0,30,31,20.0,1000,30,0.3,800,10000}
-};
+bypassValve bp1("heating",&adArr[3].measured.analog,30,31,1000,30,0.3,800,10000);

 // counters are kept in array, this for preparing to have more of them.

@@ -192,7 +192,7 @@
 struct condition conditions[]= {
   {0,&adArr[0],&variables[0],&variables[1],&outIoArr[0], 0,METHOD_TURNON},       // start boiler if it is under 24.5, and off when it has reached 26.0
   {1,&adArr[2],&variables[3],&variables[0],&variables[2],0,METHOD_CHANGELIMIT},  // if hothousewater is under hhboil, then boilTemp should be boilReduced.
-  {2,&adArr[1],&variables[5],&variables[4],radiatorTab,  0,METHOD_TABLE}        // changes in ambient will change radiatorReq with the help of radiatorAdd variable and radiatorTab table.
+  {2,&adArr[1],&variables[4],NULL,radiatorTab,           0,METHOD_TABLE}         // changes in ambient will change radiatorReq with the help of radiatorAdd variable and radiatorTab table.
 };

@@ -250,7 +250,7 @@
   setSyncInterval(7200);
   setSyncProvider(getNtpTime);
   sched.every(1000,processSensors);
-  sched.every(30000,evaluateConditions);
+  sched.every(10000,evaluateConditions);
   sched.every(200,checkEthernet);
   _counters=(int *) malloc(sizeof(int) * sizeof(cntArr) / sizeof(struct cnt));
   for (int i=0;i<(sizeof(cntArr) / sizeof(struct cnt));i++) {
@@ -282,6 +282,55 @@
   _counters[1]++;
 }

+bypassValve::bypassValve(char *name,float *actual,int up,int dn,int timeMultiplier,int latency,float sensitivity,int minTurnTime,int maxTurnTime) {
+  _name=name;
+  _actualTemp=actual;
+  _up=up;
+  _dn=dn;
+  _timeMultiplier=timeMultiplier;
+  _latency=latency;
+  _changed=0;
+  _sensitivity=sensitivity;
+  _minTurnTime=minTurnTime;
+  _maxTurnTime=maxTurnTime;
+  _targetTemp=-273;
+}
+
+void bypassValve::setTarget(float val) {
+  _targetTemp=val;
+}
+
+int bypassValve::turnBypass(time_t ts) {
+  int ret=1;
+  float diff;
+  long turntime;
+
+  if (*_actualTemp==-273) return ret;
+
+  if ((ts - _changed) > _latency-1)
+    _changed =ts;
+  else {
+    return ret;
+  }
+
+  diff = _targetTemp - *_actualTemp;
+  turntime=abs(diff) * _timeMultiplier;
+  Serial.print(" diff is ");
+  Serial.println(diff);
+
+  if (turntime > _maxTurnTime)
+    turntime=_maxTurnTime;
+  else if (turntime < _minTurnTime)
+    turntime=_minTurnTime;
+
+  if (diff > _sensitivity)
+    sched.oscillate(_up,turntime,LOW,1);
+  else if (diff < (-1.0 * _sensitivity))
+    sched.oscillate(_dn,turntime,LOW,1);
+  else
+    ret=0;
+  return ret;
+}

 int resetVariable(char *name)
 {
@@ -341,8 +390,6 @@

   for (int i=0;i<sizeof(conditions) / sizeof(struct condition);i++) {
     if (conditions[i].source == source) {
-      if (ts - conditions[i].last_chk < 30)
-	return;
       conditions[i].last_chk = ts;
       value=source->measured.analog;
       limit=conditions[i].limit->value;
@@ -373,47 +420,15 @@
       case METHOD_TABLE:
 	// calculate target
 	iTable=(struct convert *) conditions[i].target;
-	conditions[i].limit2->value=resolveConversion(value,conditions[i].limit->value,iTable);
-	float radReq=conditions[i].limit2->value;
-	if (!turnBypass(0,ts,radReq))
+	float target=resolveConversion(value,conditions[i].limit->value,iTable);
+	bp1.setTarget(target);
+	if (!bp1.turnBypass(ts))
 	  conditions[i].source->flags &= ~FLAGS_EVALUATE;
-
 	break;
       }
     }
   }
 }
-
-
-
-int turnBypass(int bno,time_t ts,float requested)
-{
-  int ret=1;
-  float diff;
-  long turntime;
-
-  bypasses[bno].targetAd=requested;
-  if (bypasses[bno].actualTemp->measured.analog==-273) return ret;
-
-  diff = requested - bypasses[bno].actualTemp->measured.analog;
-  turntime=abs(diff) * bypasses[bno].timeMultiplier;
-  Serial.print(" diff is ");
-  Serial.println(diff);
-  bypasses[bno].changed=ts;
-  if (turntime > bypasses[bno].maxTurntime)
-    turntime=bypasses[bno].maxTurntime;
-  else if (turntime < bypasses[bno].minTurntime)
-    turntime=bypasses[bno].minTurntime;
-
-  if (diff > bypasses[bno].hysteresis)
-    sched.oscillate(bypasses[bno].up,turntime,LOW,1);
-  else if (diff < (-1.0 * bypasses[bno].hysteresis))
-    sched.oscillate(bypasses[bno].dn,turntime,LOW,1);
-  else
-    ret=0;
-  return ret;
-}
-

 /* find boundings from conversion table
  * and convert / interpolate according to the table


Added lat/lon to display

Added lat/lon to display

--- mwsLCD/mwsLCD.ino
+++ mwsLCD/mwsLCD.ino
@@ -471,12 +471,10 @@

   lcd.clear();
   lcd.print(F("Lon:"));
-  lcd.print(gps.location.lng(), 4);
-  lcd.print(F(" (dd.d)"));
+  lcd.print(gps.location.lng(), 6);
   lcd.setCursor(0, 2);
   lcd.print(F("Lat:"));
-  lcd.print(gps.location.lat(), 4);
-  lcd.print(F(" (dd.d)"));
+  lcd.print(gps.location.lat(), 6);
   delay(5000);

   lcd.clear();


Connect screen, engine off fix, delay fix.

--- Wemos/ATSDashboard.ino
+++ Wemos/ATSDashboard.ino
@@ -52,14 +52,28 @@
   // init done

   display.display();
-  delay(1000);
   display.clearDisplay();
+  display.setTextSize(1);
+  display.setTextColor(WHITE);
+  display.setCursor(0,0);
+  display.print("Connecting to ");
+  display.println(ssid);
+  display.display();

   WiFi.begin(ssid, password);

   while (WiFi.status() != WL_CONNECTED) {
+  display.print(".");
+  display.display();
     delay(500);
   }
+  display.clearDisplay();
+  display.setCursor(0,0);
+  display.println("Connected!");
+  display.print("IP: ");
+  display.println(WiFi.localIP());
+  display.display();
+  delay(1000);

   display.clearDisplay();

@@ -107,13 +121,17 @@
   int thespeedlimit = thing.substring(thing.indexOf("<l>") + 3, thing.lastIndexOf("</l>")).toInt();
   String engineState = thing.substring(thing.indexOf("<e>") + 3, thing.lastIndexOf("</e>"));
   bool IsOverLimit = (thespeed > thespeedlimit);
+  if (thespeedlimit == 0)
+  {
+    IsOverLimit = false;
+  }

   display.clearDisplay();
   display.setTextSize(1);
   display.setTextColor(WHITE);
   display.setCursor(0,0);
   display.println("Speed:");
-  if (engineState=="0")
+  if (engineState=="")
   {
   display.print("Engine off");
   }
@@ -155,7 +173,7 @@
   display.print("km/h");
   }
   display.display();
-  //delay(250);
+  delay(1000);
   }
   }
 }


added braking action

added braking action

--- arduino/arduino/arduino.ino
+++ arduino/arduino/arduino.ino
@@ -115,6 +115,15 @@
   }
 }

+void driveStop(int button)
+{
+  if(button == 5)
+  {
+    evshield.bank_b.motorStop(SH_Motor_1, SH_Next_Action_Brake);
+    evshield.bank_a.motorStop(SH_Motor_1, SH_Next_Action_Brake);
+  }
+}
+
 void driveBackward(int button)
 {
   if(button == 2)


Update pinout for new board.

Update pinout for new board.

--- arduino/monitor/monitor.ino
+++ arduino/monitor/monitor.ino
@@ -18,9 +18,9 @@
 const byte DIO_RAIN = 2;
 const byte DIO_WIND_SPEED = 3;

-const byte DIO_XBEE_SLEEP = 9;
-const byte DIO_XBEE_RX = 10;
-const byte DIO_XBEE_TX = 11;
+const byte DIO_XBEE_SLEEP = 10;
+const byte DIO_XBEE_RX = 11;
+const byte DIO_XBEE_TX = 12;

 const byte LED = 13;


upurs_usb_port: Now working for UPCFS, UPXROM, and UPURSFS on a BBC Micro

--- upurs_usb_port/upurs_usb_port.ino
+++ upurs_usb_port/upurs_usb_port.ino
@@ -28,13 +28,13 @@
 // USE_INVERTED_SOFTWARE_SERIAL will give you an accurate baud rate, with the
 // inverted logic levels that it expects:

-// #define USE_INVERTED_SOFTWARE_SERIAL
+#define USE_INVERTED_SOFTWARE_SERIAL

 // If you're connecting TXD and RXD via an inverter (perhaps a CPLD running
 // the code in spi_sd_card/cpld), USE_SOFTWARE_SERIAL will give you the an
 // accurate baud rate that should be compatible with UPURS:

-#define USE_SOFTWARE_SERIAL
+// #define USE_SOFTWARE_SERIAL

 // Alternatively you can leave both of the above undefined to use hardware
 // serial, which is a bit easier on the AVR, but runs at a slightly high baud
@@ -54,14 +54,20 @@

 // #define IGNORE_BBC_RX

+// Define DEBUG_REPORT_WHEN_QUIET to output a report on the state of the
+// system every second when nothing else is happening:
+
+// #define DEBUG_REPORT_WHEN_QUIET
+
 // ----------------------------------------------------------------------

 #if defined(USE_INVERTED_SOFTWARE_SERIAL) || defined(USE_SOFTWARE_SERIAL)
 #include <SoftwareSerial.h>
 #endif

-// Serial receive -- PD2, D0.
-#define RXD_PIN 0
+// Serial receive -- usually PD2, D0, but we need one with a pin change
+// interrupt, so we use pin 8 (PB4/PCINT4/ADC11)
+#define RXD_PIN 8

 // Serial transmit -- PD3, D1.
 #define TXD_PIN 1
@@ -106,7 +112,7 @@
 	digitalWrite(RTS_PIN, HIGH);
 }

-// static unsigned long last_activity = 0;
+static unsigned long last_activity = 0;

 void loop() {
 	// static int written = 0;
@@ -119,22 +125,24 @@
 #ifdef DEBUG_USB_LOOPBACK
 			SerialUSB.write(c);
 #endif
-			// last_activity = millis();
+			last_activity = millis();
 			// ++written;
 		}

 #ifndef IGNORE_BBC_RX
 		while (SerialBBC.available()) {
 			SerialUSB.write(SerialBBC.read());
-			// last_activity = millis();
+			last_activity = millis();
 		}
 #endif

-		// if (millis() - last_activity > 1000) {
-		// 	SerialUSB.print("status: ");
-		// 	SerialUSB.print(digitalRead(CTS_PIN) == HIGH ? "cts high" : "cts low");
-		// 	SerialUSB.println();
-		// 	last_activity = millis();
-		// }
+#ifdef DEBUG_REPORT_WHEN_QUIET
+		if (millis() - last_activity > 1000) {
+			SerialUSB.print("status: ");
+			SerialUSB.print(digitalRead(CTS_PIN) == HIGH ? "cts high" : "cts low");
+			SerialUSB.println();
+			last_activity = millis();
+		}
+#endif
 	}
 }


Adjust for low power mode.

Adjust for low power mode.

--- examples/Benchmarks/CosaBenchmarkDataLogger/CosaBenchmarkDataLogger.ino
+++ examples/Benchmarks/CosaBenchmarkDataLogger/CosaBenchmarkDataLogger.ino
@@ -16,7 +16,22 @@
  * Lesser General Public License for more details.
  *
  * @section Description
- * Benchmark Analog data-logging over IOStream/UART.
+ * Benchmark Analog data-logging over IOStream/UART. Is it possible
+ * to achieve 4K samples per second and write the values in text
+ * format over the serial/uart?
+ *
+ * Bits per sample: 10
+ * Sample range: [0..1023], [0..5V]
+ * Micro-seconds per conversion: 112
+ *
+ * Samples per second: 4,000
+ * Micro-seconds per sample: 250
+ *
+ * Max number of characters: 4,000 * (4 + 2) = 24,000
+ * Max number of bits: 24,000 * (1 + 8 + 2) = 264,000
+ *
+ * Avg number of characters: 4,000 * (2 + 2) = 16,000
+ * Avg number of bits: 16,000 * (1 + 8 + 2) = 196,000
  *
  * This file is part of the Arduino Che Cosa project.
  */
@@ -43,7 +58,7 @@
 void setup()
 {
   // Start serial output with given baud-rate
-  uart.begin(500000);
+  uart.begin(250000);
   // uart.begin(2000000);
   // uart.begin(1000000);
   // uart.begin(500000);
@@ -61,6 +76,9 @@
   // Install capture idle time
   ::yield = iowait;

+  // Power up ADC
+  AnalogPin::powerup();
+
   // Start timers
   Watchdog::begin();
   RTC::begin();
@@ -69,7 +87,7 @@
 void loop()
 {
   uint16_t SAMPLES = 1000;
-  float Ksps;
+  float ksps;

   // 1000 samples with 1 ms period; simple sample and print
   idle = 0L;
@@ -84,20 +102,20 @@
     trace.flush();
   }
   INFO("per sample:%ul us", trace.measure / SAMPLES);
-  Ksps = ((float) SAMPLES * 1000.0) / trace.measure;
+  ksps = ((float) SAMPLES * 1000.0) / trace.measure;
   trace << PSTR("effective sample rate (") << SAMPLES << PSTR(" samples):")
-	<< Ksps << PSTR(" Ksps")
+	<< ksps << PSTR(" ksps")
 	<< endl;
   trace << PSTR("idle:") << (idle * 100.0) / RTC::micros() << '%'
 	<< endl;
   sleep(5);

-  // 1000 samples with 125 us period; pipe-line sample request and print
+  // 1000 samples with 250 us period; pipe-line sample request and print
   idle = 0L;
   MEASURE("performance:", 1) {
     for (uint16_t i = 0; i < SAMPLES;) {
       probe.sample_request();
-      PERIODIC(timer, 500) {
+      PERIODIC(timer, 250) {
 	uint16_t sample = probe.sample_await();
 	probe.sample_request();
 	trace << sample << endl;
@@ -107,9 +125,9 @@
     trace.flush();
   }
   INFO("per sample:%ul us", trace.measure / SAMPLES);
-  Ksps = ((float) SAMPLES * 1000.0) / trace.measure;
+  ksps = ((float) SAMPLES * 1000.0) / trace.measure;
   trace << PSTR("effective sample rate (") << SAMPLES << PSTR(" samples):")
-	<< Ksps << PSTR(" Ksps")
+	<< ksps << PSTR(" ksps")
 	<< endl;
   trace << PSTR("idle:") << (idle * 100.0) / RTC::micros() << '%'
 	<< endl;


Timestamp calculation was changed.

Timestamp calculation was changed.

--- DiveIno.ino
+++ DiveIno.ino
@@ -179,6 +179,9 @@
     Serial.print(F("RTC time: "));
     Serial.println(settings.getCurrentTimeText());

+    Serial.print(F("Now timestamp: "));
+    Serial.println(nowTimestamp());
+
 	tft.InitLCD();

 	displayScreen(MENU_SCREEN);
@@ -230,6 +233,19 @@
 	}
 }

+time_t nowTimestamp()
+{
+#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
+	return now();
+#elif defined(__SAM3X8E__) || defined(__SAM3X8H__)
+	tmElements_t tm;
+	if (RTC.read(tm)) {
+	    return makeTime(tm);
+	}
+#endif
+	return 0;
+}
+
 //////////
 // Dive //
 //////////
@@ -348,10 +364,10 @@

 void diveUnderWater()
 {
-	unsigned int measurementDifference = now() - timerTimestamp;
+	unsigned int measurementDifference = nowTimestamp() - timerTimestamp;

 	if (measurementDifference > 0) {
-		timerTimestamp = now();
+		timerTimestamp = nowTimestamp();

 		float pressureInMillibar = seaLevelPressureSetting;
 		float temperatureInCelsius = 0;
@@ -393,7 +409,7 @@

 		switch (currentScreen) {
 			case GAUGE_SCREEN: {
-				view.drawDiveDuration(now()-diveStartTimestamp);
+				view.drawDiveDuration(nowTimestamp()-diveStartTimestamp);

 				//Instead of dive information we will display the current time
 				view.drawCurrentTime(settings.getCurrentTimeText());
@@ -406,7 +422,7 @@

 				if (currentMode == DIVE_PROGRESS_MODE) {
 					//Progress with the dive, if we are deeper than 1.2 meter
-					unsigned int intervalDuration = now()-diveStartTimestamp-diveDurationInSeconds;
+					unsigned int intervalDuration = nowTimestamp()-diveStartTimestamp-diveDurationInSeconds;
 					calculateSafetyStop(maxDepthInMeter, depthInMeter, intervalDuration);

 					diveDurationInSeconds = diveDurationInSeconds + intervalDuration;
@@ -418,7 +434,7 @@
 					}
 				} else {
 					//No dive progress - reset the dive timestamp
-					diveStartTimestamp = now();
+					diveStartTimestamp = nowTimestamp();
 				}
 			}
 			break;
@@ -433,8 +449,8 @@
 	}

 	//Store the the current time as seconds since Jan 1 1970 at the start of the dive
-	diveStartTimestamp = now();
-	timerTimestamp = now();
+	diveStartTimestamp = nowTimestamp();
+	timerTimestamp = nowTimestamp();

 	previousPressureInMillibar = seaLevelPressureSetting;

@@ -469,7 +485,7 @@
 		LastDiveData* lastDiveData = lastDive.loadLastDiveData();

 		//Last dive happened within 48 hours and there is an active no fly time
-		if (lastDiveData != NULL &&	(lastDiveData->diveDateTimestamp + 172800) > now() && lastDiveData->noFlyTimeInMinutes > 0) {
+		if (lastDiveData != NULL &&	(lastDiveData->diveDateTimestamp + 172800) > nowTimestamp() && lastDiveData->noFlyTimeInMinutes > 0) {

 			Serial.print("BEFORE dive No Fly time (min): ");
 			Serial.println(lastDiveData->noFlyTimeInMinutes);
@@ -487,7 +503,7 @@
 			}

 			//Calculate surface time in minutes
-			int surfaceTime = (now() - lastDiveData->diveDateTimestamp) / 60;
+			int surfaceTime = (nowTimestamp() - lastDiveData->diveDateTimestamp) / 60;

 			Serial.print("Surface time (min): ");
 			Serial.println(surfaceTime);
@@ -578,8 +594,11 @@
 		///////////////////////////
 		// Update Last Dive Data //

+		Serial.print("Stopped timestamp: ");
+		Serial.println(nowTimestamp());
+
 		LastDiveData* lastDiveData = new LastDiveData;
-		lastDiveData->diveDateTimestamp = now();
+		lastDiveData->diveDateTimestamp = nowTimestamp();
 		lastDiveData->diveDate = currentTimeText;
 		lastDiveData->maxDepthInMeters = diveResult->maxDepthInMeters;
 		lastDiveData->durationInSeconds = diveResult->durationInSeconds;
@@ -1134,10 +1153,16 @@
 			diveResult = buhlmann.initializeCompartments();

 			lastDiveData = lastDive.loadLastDiveData();
+
 			if (lastDiveData != NULL && lastDiveData->diveDateTimestamp > 0 ) {

+			    Serial.print(F("Now timestamp: "));
+			    Serial.println(nowTimestamp());
+				Serial.print("Last dive timestamp: ");
+				Serial.println(lastDiveData->diveDateTimestamp);
+
 				//Calculate surface interval
-				surfaceIntervalInMinutes = (now() - lastDiveData->diveDateTimestamp) / 60;
+				surfaceIntervalInMinutes = (nowTimestamp() - lastDiveData->diveDateTimestamp) / 60;

 				Serial.print("Surface interval (min): ");
 				Serial.println(surfaceIntervalInMinutes);


set speed + simplify

set speed + simplify

--- Arduino/base_subscriber.ino
+++ Arduino/base_subscriber.ino
@@ -12,6 +12,12 @@

 uint8_t messageTTL = 100;
 uint16_t messageTimestamp = 0;
+
+// Speed Pin, Pin A, Pin B
+uint8_t motor_0[] = {3, 4, 5};
+uint8_t motor_1[] = {6, 7, 8};
+uint8_t motor_2[] = {0, 0, 0};
+uint8_t motor_3[] = {0, 0, 0};

 // **********
 // ROS Messages
@@ -47,6 +53,13 @@
 // **********
 // Motor
 // **********
+
+void SetMotorSimple(uint8_t motor[], uint8_t speed)
+{
+    if (motor[0] == 0 and motor[1] == 0 motor[3] == 0) { return; }
+
+    SetMotor(motor[0], motor[1], motor[3], speed);
+}

 void SetMotor(uint8_t pinSpeed, uint8_t pin1, uint8_t pin2, uint8_t speed)
 {
@@ -88,11 +101,17 @@
 {
     if(messageTimestamp + messageTTL > millis())
     {
-        // TODO - Update pins
+        SetMotorSimple(motor_0, messageData[0]);
+        SetMotorSimple(motor_1, messageData[1]);
+        SetMotorSimple(motor_2, messageData[2]);
+        SetMotorSimple(motor_3, messageData[3]);
     }
     else
     {
-        // TODO - STOP!
+        SetMotorSimple(motor_0, 0);
+        SetMotorSimple(motor_1, 0);
+        SetMotorSimple(motor_2, 0);
+        SetMotorSimple(motor_3, 0);
     }

     rosNode.spinOnce();


Fixes a typo

Fixes a typo

--- BlinkSerial/BlinkSerial.ino
+++ BlinkSerial/BlinkSerial.ino
@@ -16,7 +16,7 @@
 void loop() {
     counter++;
     Serial.print("Hello world "); // Write a string to the serial interface
-    Serial.pringln(counter); // Write a integer to the serial interface and end the line
+    Serial.println(counter); // Write a integer to the serial interface and end the line
     digitalWrite(led, counter % 2); // Toggle the led pin on every increase of counter
     delay(1000); // Delays for 1 second
 }


Removed explicit bool array initialization

--- module/module.ino
+++ module/module.ino
@@ -155,7 +155,7 @@
 	unsigned int pulseCount = 0;
 	unsigned int pollCounter = 0;
 	int i = 0;
-	bool signals[] = {0,0,0};
+	bool signals[sampleSize];

 	// Only here temporarily for debugging
 	if (debug) {
@@ -278,7 +278,7 @@
 			numInvalid += 1;
 		}
 	}
-  //Serial.print(signals[0]); Serial.print(signals[1]); Serial.print(signals[2]); Serial.print(" ");
+  	//Serial.print(signals[0]); Serial.print(signals[1]); Serial.print(signals[2]); Serial.print(" ");
 	Serial.print(numValid); Serial.print(numInvalid);
 	Serial.print(" ");
   	//delay(1);


Rolled my own bearing finder, but realized it already exists in tinygps++.  Fell back to library version.

--- shipStation/shipStation.ino
+++ shipStation/shipStation.ino
@@ -30,22 +30,12 @@
   Serial.print(RxGps.location.lat(), 6); Serial.print(",");
   Serial.print(RxGps.location.lng(), 6); Serial.print(",");
   Serial.print(RxGps.altitude.meters()); Serial.print(",");
-  Serial.println(findBearing(RxGps, TxGps));
-}
-
-double findBearing(TinyGPSPlus A, TinyGPSPlus B){
-  // Returns bearing from point A to point B
-  // See http://www.igismap.com/formula-to-find-bearing-or-heading-angle-between-two-points-latitude-longitude/
-  double cosA = cos(A.location.lat());
-  double cosB = cos(B.location.lat());
-  double sinA = sin(A.location.lat());
-  double sinB = sin(B.location.lat());
-  double lamLong = A.location.lng()-B.location.lng();
-  return atan2(
-    cosB*sin(lamLong),
-    cosA*sinB-sinA*cosB*cos(lamLong)
+  double courseTo = TinyGPSPlus::courseTo(
+    TxGps.location.lat(), TxGps.location.lng(),
+    RxGps.location.lat(), RxGps.location.lng()
   );
-
+  Serial.print(courseTo); Serial.print(",");
+  Serial.println(TinyGPSPlus::cardinal(courseTo));
 }

 void loop() {


Add loop calls to subs; reformat output

Add loop calls to subs; reformat output

--- AzElSensor/AzElSensor.ino
+++ AzElSensor/AzElSensor.ino
@@ -88,7 +88,7 @@
   I2CwriteByte(MAG_ADDRESS,0x0A,0x16);

    pinMode(13, OUTPUT);
-  Timer1.initialize(100000);         // initialize timer1, and set a 1/2 second period
+  Timer1.initialize(1000000);         // initialize timer1, and set a 1/2 second period
   Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt

@@ -124,8 +124,14 @@

   // Display time
   Serial.print (millis()-ti,DEC);
-  Serial.print ("\t");
-
+
+  Serial.print( "\tACC:" );
+  accelerometer_subr();
+  Serial.print( "\tMAG:" );
+  subr_magnetometer();
+  Serial.print( "\tGYR:" );
+  gyro_subr();
+  Serial.println( "" );

   // _______________
   // ::: Counter :::
@@ -135,8 +141,8 @@
 //  Serial.print ("\t");

   // End of line
-  Serial.println("");
-  delay(500);
+  //Serial.println("");
+  //delay(500);

   // ____________________________________
   // :::  accelerometer and gyroscope :::
@@ -155,11 +161,11 @@

   //print accelerometer data
     Serial.print (ax,DEC);
-    Serial.print ("\t");
+    Serial.print (",");
     Serial.print (ay,DEC);
-    Serial.print ("\t");
+    Serial.print (",");
     Serial.print (az,DEC);
-    Serial.print ("\t");
+    Serial.print (",");
   }

@@ -175,11 +181,11 @@

   // print gyroscope data
     Serial.print (gx,DEC);
-    Serial.print ("\t");
+    Serial.print (",");
     Serial.print (gy,DEC);
-    Serial.print ("\t");
+    Serial.print (",");
     Serial.print (gz,DEC);
-    Serial.print ("\t");
+    Serial.print (",");

   }
   // _____________________
@@ -209,11 +215,11 @@

   // print magnetometer data
     Serial.print (mx,DEC);//(mx+200,DEC);
-    Serial.print ("\t");
+    Serial.print (",");
     Serial.print (my,DEC);//(my-70,DEC);
-    Serial.print ("\t");
+    Serial.print (",");
     Serial.print (mz,DEC);//(mz-700,DEC);
-    Serial.print ("\t");
+    Serial.print (",");

   }


Extract temp measurement to a "thread"

Extract temp measurement to a "thread"

Larger P seems to work better for this rather slow feedback loop.

--- incuino/incuino.ino
+++ incuino/incuino.ino
@@ -1,5 +1,9 @@
 #include <OneWire.h>
 #include <PID_v1.h>
+#include <Thread.h>
+#include <ThreadController.h>
+#include <TimerOne.h>
+

 // OneWire DS18S20, DS18B20, DS1822 Temperature Example
 //
@@ -35,20 +39,53 @@
 #define SENSOR_PIN 10
 #define DELAY 1000

+class SensorThread: public Thread {
+  public:
+    float value;
+    int pin;
+
+  void run(){
+    value = getTemp();
+    runned();
+  }
+};
+
 OneWire ds(SENSOR_PIN);  // on pin 10 (a 4.7K resistor is necessary)

 //Define Variables we'll be connecting to
 double Setpoint, Input, Output;
 //Specify the links and initial tuning parameters
-double Kp=2.0, Ki=5.0, Kd=1.0;
+double Kp=70.0, Ki=0.6, Kd=0.6;
 PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);
 int WindowSize = 100;
-uint32_t PID_interval = 10000;
+uint32_t PID_interval = 30000;
 unsigned long windowStartTime;
+
+SensorThread tempSensor = SensorThread();
+
+// Instantiate a new ThreadController
+ThreadController controller = ThreadController();
+
+// This is the callback for the Timer
+void timerCallback(){
+  controller.run();
+}

 void setup(void) {
   Serial.begin(9600);
   pinMode(RELAY_PIN, OUTPUT);
+
+   // Configures Thread
+  tempSensor.pin = SENSOR_PIN;
+  tempSensor.setInterval(10000);
+
+  // Add the Threads to our ThreadController
+  controller.add(&tempSensor);
+
+  Timer1.initialize(10000000);
+  Timer1.attachInterrupt(timerCallback);
+  Timer1.start();
+
   windowStartTime = millis();
   Setpoint = 28.0;
   myPID.SetOutputLimits(0, WindowSize); //tell the PID to range between 0 and the full window size
@@ -98,21 +135,21 @@
   return (float) raw / 16.0;
 }

-void loop(void) {
+float getTemp() {
   byte i;
   byte present = 0;
   byte data[12];
   byte addr[8];
-  float celsius;
-  double ratio;
+  unsigned long startTime;

   ds.reset_search();
   if ( !ds.search(addr)) {
     Serial.println("No more addresses.");
     Serial.println();
     ds.reset_search();
-    delay(3000);
-    return;
+    startTime = millis();
+    while(millis() - startTime < 3000);
+    return -1000;
   }

   Serial.print("ROM =");
@@ -123,20 +160,23 @@

   if (OneWire::crc8(addr, 7) != addr[7]) {
       Serial.println("CRC is not valid!");
-      return;
+      return -1000;
   }

   // the first ROM byte indicates which chip
   int type_s = getChipType(addr[0]);
+

   if(!ds.reset()) {
     Serial.println("Failed to reset");
-    return;
+    return -1000;
   }
   ds.select(addr);
   ds.write(0x44, 1);        // start conversion, with parasite power on at the end
-
-  delay(DELAY);     // maybe 750ms is enough, maybe not
+
+  startTime = millis();
+  while(millis() - startTime < 1000);
+  // maybe 750ms is enough, maybe not
   // we might do a ds.depower() here, but the reset will take care of it.

   present = ds.reset();
@@ -158,7 +198,16 @@
   Serial.print(OneWire::crc8(data, 8), HEX);
   Serial.println();

-  Input = convertTemp(data, type_s);
+  return convertTemp(data, type_s);
+}
+
+void loop(void) {
+  double ratio;
+  float temp = tempSensor.value;
+  if(temp == -1000){
+    return;
+  }
+  Input = temp;
   myPID.Compute();
   windowStartTime = millis();
   Serial.println();
@@ -173,11 +222,9 @@
   Serial.print("Runtime: ");
   Serial.println(PID_interval * ratio);

-  if( PID_interval * ratio > 500) {
-    Serial.println("LOW");
-    digitalWrite(RELAY_PIN, LOW);
-    while(millis() - windowStartTime < PID_interval * ratio);
-  }
+  Serial.println("LOW");
+  digitalWrite(RELAY_PIN, LOW);
+  while(millis() - windowStartTime < PID_interval * ratio);

   Serial.println("HIGH");
   digitalWrite(RELAY_PIN, HIGH);


Fix typo recieve

Fix typo recieve

--- Zowi_Testing_v3/Zowi_Testing_v3.ino
+++ Zowi_Testing_v3/Zowi_Testing_v3.ino
@@ -160,7 +160,7 @@
   // Setup callbacks for SerialCommand commands
   SCmd.addCommand("S", stopp);            //  sendAck();
   SCmd.addCommand("L", receiveLED);       //  sendAck();
-  SCmd.addCommand("T", recieveBuzzer);    //  sendAck();
+  SCmd.addCommand("T", receiveBuzzer);    //  sendAck();
   SCmd.addCommand("M", receiveMovement);  //  sendAck();
   SCmd.addCommand("R", receiveName);      //  sendAck();
   SCmd.addCommand("E", requestName);
@@ -637,7 +637,7 @@
 }

 //Function to receive buzzer commands
-void recieveBuzzer(){
+void receiveBuzzer(){

   //sendAck();
   stopp();


remove revValue average

remove revValue average

--- _06-power_meter/_06-power_meter.ino
+++ _06-power_meter/_06-power_meter.ino
@@ -251,11 +251,11 @@
   payload = "{\"VIrms\":";
   payload += average;
   payload += ",\"revValue\":";
-  payload += ( revValue + oldrevValue ) / 2 ;
+  payload += revValue;
   payload += ",\"revMills\":";
-  payload += ( revMills + oldrevMills ) / 2 ;
+  payload += revMills;
   payload += ",\"powerAvg\":";
-  payload += ( average + ((revValue + oldrevValue ) / 2 )) / 2 ;
+  payload += (( average + revValue ) / 2) ;
   payload += ",\"Stddev\":";
   payload += ave.stddev();
   payload += ",\"FreeHeap\":";


modifica GET

modifica GET

--- nodeMCU/plant/functions.ino
+++ nodeMCU/plant/functions.ino
@@ -17,25 +17,34 @@
 {
    WiFiClient client;

-   if (client.connect(server, 3000)) { // use ip 184.106.153.149 or api.thingspeak.com
+   if (client.connect(server, 3000)) {
    Serial.println("WiFi Client connected ");

    String postStr= String(rnd);

-   String url = "GET /dato/acquisisci/" + postStr;
-     Serial.println(url);
+//   String url = "GET /dato/acquisisci/" + postStr;
+//     Serial.println(postStr);

-     client.print(url);
-     client.print("HTTP/1.0 \n\n");
-     Serial.println("HTTP/1.0 \n\n");
+     client.print("GET ");
+//     client.print(server);
+//     client.print(":3000");
+     client.print("/dato/acquisisci/");
+     Serial.print("GET /dato/acquisisci/");

-     client.println();
+     client.print(postStr);
+     Serial.print(postStr);
+
+//     client.println();
+//     Serial.println();
+
+     client.print(" HTTP/1.1 \n");
+//     client.println();

-
-
-   delay(1000);
+     Serial.println(" HTTP/1.1 \n\n");
+
+   delay(2000);
+   client.stop();

    }//end if
-   sent++;
- client.stop();
+
 }//end send


Changed "server.org" to Blynk Cloud

Changed "server.org" to Blynk Cloud

--- examples/BoardsAndShields/Arduino_Ethernet_Manual/Arduino_Ethernet_Manual.ino
+++ examples/BoardsAndShields/Arduino_Ethernet_Manual/Arduino_Ethernet_Manual.ino
@@ -41,7 +41,7 @@
   Serial.begin(9600);
   Blynk.begin(auth, server_ip, 8442, arduino_ip, dns_ip, gateway_ip, subnet_mask, arduino_mac);
   // Or like this:
-  //Blynk.begin(auth, "server.org", 8442, arduino_ip, dns_ip, gateway_ip, subnet_mask, arduino_mac);
+  //Blynk.begin(auth, "cloud.blynk.cc", 8442, arduino_ip, dns_ip, gateway_ip, subnet_mask, arduino_mac);
 }

 void loop()


Port nach Arduino Mega 2560

Port nach Arduino Mega 2560

--- Arduino_Humidor_Monitoring/Arduino_Humidor_Monitoring.ino
+++ Arduino_Humidor_Monitoring/Arduino_Humidor_Monitoring.ino
@@ -9,23 +9,23 @@
  * Als zusatz wird noch ein OLED Display am Humidor eingebaut um den derzeitigen Status anzuzeigen.
  * Genauso verwenden wir die Bibliothek ArduinoJson und bauen für die Übertragung ein Json String.
  *
- * Arduino Nano V3 Pinbelegung:
+ * Arduino Mega 2560 R3 Pinbelegung:
  * ----------------------------
  * VCC = 5V
  * GND = GND
- * D2  = TX Pin ESP8266 WIFI
- * D3  = RX Pin ESP8266 WIFI
+ * D22  = TX Pin ESP8266 WIFI
+ * D23  = RX Pin ESP8266 WIFI
  * 3.3V= VCC ESP8266 WIFI
  * ---
- * D4  = DHT11 Sensor
+ * D24  = DHT11 Sensor
  * ---
  * A4  = I2C OLED Display (SDA)
  * A5  = I2C OLED Display (SCL)
  * ---
  * D5  = (PWM) Servo Motor
  * ---
- * D7  = LED (Power)
- * D8  = LED (Activity)
+ * D26  = LED (Power)
+ * D27  = LED (Activity)
  * ---
  *
  * OLED Display SSD1306:
@@ -82,12 +82,12 @@
 // Sender ID for Database
 unsigned long int ID = 234576987654321;

-int led_pwr=7;
-int led_act=8;
+int led_pwr=26;
+int led_act=27;

 // ESP8266 WIFI
 #include<SoftwareSerial.h>
-SoftwareSerial wifi(2,3); //RX, TX
+SoftwareSerial wifi(14,15); //RX, TX
 boolean NO_IP=false;
 boolean WIFI_CONN=false;
 String IP="";
@@ -100,22 +100,22 @@

 //Servo Lib
 #include <Servo.h>
-int servo_pin = 5; // Declare the Servo pin
+int servo_pin = 2; // Declare the Servo pin
 Servo servo1; // Create a servo object
 int pos_open = 130; // open position in degrees
 int pos_close = 15; // close position in degrees

 //DHT11 Lib
-int dhtPin = 4;
+int dhtPin = 24;
 #include "DHT.h"
 DHT dht;

 // delay between the measurements in Milliseconds
-unsigned long stime = 1800000; // delay time between the transmitting
-unsigned long mtime = 900000; // delay time between the measurements
+//unsigned long stime = 1800000; // delay time between the transmitting
+//unsigned long mtime = 900000; // delay time between the measurements
 // only for tests
-//unsigned long stime = 20000;
-//unsigned long mtime = 10000;
+unsigned long stime = 20000;
+unsigned long mtime = 10000;

 boolean isopen; // Field to check if open or closed

@@ -146,8 +146,10 @@
   if(state==1){
     digitalWrite(led_act, LOW);
     digitalWrite(led_act, HIGH);
+    Serial.println("act");
   } else {
     digitalWrite(led_act, LOW);
+    Serial.println("act low");
   }
 }

@@ -275,7 +277,7 @@
   pinMode(led_pwr, OUTPUT);
   pinMode(led_act, OUTPUT);

-  digitalWrite(led_pwr, HIGH);
+  digitalWrite(led_pwr, LOW);
   digitalWrite(led_act, LOW);

   //wifi_init();
@@ -300,7 +302,7 @@
   //falls die Befeuchtung aktiv ist pruefe alle 30 Sekunden die Werte
   if (isopen) {
     if ((unsigned long)(currmillis - task2) >= 30000) {
-      act(1);
+      //act(1);
       byte i;
       //Serial.println(F("check if hum"));
       if ((float)(get_hum() <= 65.0 || get_hum() <= 70.0)) {
@@ -326,12 +328,13 @@
   if ((unsigned long)(currmillis - task1) >= stime || (currmillis == 1000)) {
     //Serial.println(F("check DHT22"));
     //TransmitData(get_temp(), get_hum());
-    act(1);
+    //act(1);
     root["temperature"] = get_temp();
     root["Humidity"] = get_hum();
     TransmitData();
     task1 = millis();
     act(0);
+    Serial.println("send data");
   }

   // Sende Messdaten wenn die Befeuchtung aktiv ist alle 60 Sekunden
@@ -352,7 +355,7 @@
     byte i;
     //Serial.println(F("check if hum"));
     if ((float)(get_hum() <= 65.0 || get_hum() <= 70.0)) {
-      act(1);
+      //act(1);
       if (!isopen) {
         //oeffne die Belueftung und starte den Luefter
         Serial.println(F("Switch fan on"));
@@ -373,11 +376,13 @@

 // Read temperature as Celsius (the default)
 float get_temp() {
+  Serial.println("Read Temp");
   return dht.getTemperature();
 }

 // Read humidity
 float get_hum() {
+  Serial.println("Read Hum");
   return dht.getHumidity();
 }

@@ -385,12 +390,11 @@
 void chk_wifi_conn(){
   if(!WIFI_CONN){
     // get ip address
+    Serial.println(F("get ip"));
     get_ip();
     delay(2000);
     // check ip and NO_IP to True
     check_ip(5000);
-  } else {
-    // do nothing
   }

   if(!NO_IP && !WIFI_CONN){
@@ -406,6 +410,7 @@
   /*
   * Send JSON Data
   */
+  Serial.println(F("Start transmit data"));
   if(isopen){
     root["open"]="True";
   } else {
@@ -413,13 +418,13 @@
   }

   if(!WIFI_CONN){
+    Serial.println(F("check wifi con"));
     chk_wifi_conn();
-  } else {
-    // do nothing
   }

   String jsonstring;
   root.printTo(jsonstring);
+  Serial.println(F("connect to server"));

   wifi.print("AT+CIPSTART=\"TCP\",");
   wifi.print("\"10.20.50.74\"");


SerialFlash: fix compile errors

SerialFlash: fix compile errors

Old SerialFlash directory was still there-- delete it

--- libraries/SerialFlash/examples/CopyFromSerial/CopyFromSerial.ino
+++ libraries/SerialFlash/examples/CopyFromSerial/CopyFromSerial.ino
@@ -1,267 +0,0 @@
-/*
- * This is free and unencumbered software released into the public domain.
- *
- * Anyone is free to copy, modify, publish, use, compile, sell, or
- * distribute this software, either in source code form or as a compiled
- * binary, for any purpose, commercial or non-commercial, and by any
- * means.
- *
- * In jurisdictions that recognize copyright laws, the author or authors
- * of this software dedicate any and all copyright interest in the
- * software to the public domain. We make this dedication for the benefit
- * of the public at large and to the detriment of our heirs and
- * successors. We intend this dedication to be an overt act of
- * relinquishment in perpetuity of all present and future rights to this
- * software under copyright law.
- *
- * 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 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.
- *
- * For more information, please refer to <http://unlicense.org>
- * -------------------------------------------------------------------------
- *
- * This is example code to 1) format an SPI Flash chip, and 2) copy raw
- * audio files (mono channel, 16 bit signed, 44100Hz) to it using the
- * SerialFlash library.  The audio can then be played back using the
- * AudioPlaySerialflashRaw object in the Teensy Audio library.
- *
- * To convert a .wav file to the proper .RAW format, use sox:
- * sox input.wav -r 44100 -b 16 --norm -e signed-integer -t raw OUTPUT.RAW remix 1,2
- *
- * Note that the OUTPUT.RAW filename must be all caps and contain only the following
- * characters: A-Z, 0-9, comma, period, colon, dash, underscore.  (The SerialFlash
- * library converts filenames to caps, so to avoid confusion we just enforce it here).
- *
- * It is a little difficult to see what is happening; aswe are using the Serial port
- * to upload files, we can't just throw out debug information.  Instead, we use the LED
- * (pin 13) to convey state.
- *
- * While the chip is being formatted, the LED (pin 13) will toggle at 1Hz rate.  When
- * the formatting is done, it flashes quickly (10Hz) for one second, then stays on
- * solid.  When nothing has been received for 3 seconds, the upload is assumed to be
- * completed, and the light goes off.
- *
- * Use the 'rawfile-uploader.py' python script (included in the extras folder) to upload
- * the files.  You can start the script as soon as the Teensy is turned on, and the
- * USB serial upload will just buffer and wait until the flash is formatted.
- *
- * This code was written by Wyatt Olson <wyatt@digitalcave.ca> (originally as part
- * of Drum Master http://drummaster.digitalcave.ca and later modified into a
- * standalone sample).
- *
- * Enjoy!
- *
- * SerialFlash library API: https://github.com/PaulStoffregen/SerialFlash
- */
-
-#include <SerialFlash.h>
-#include <SPI.h>
-
-//Buffer sizes
-#define USB_BUFFER_SIZE      128
-#define FLASH_BUFFER_SIZE    4096
-
-//Max filename length (8.3 plus a null char terminator)
-#define FILENAME_STRING_SIZE      13
-
-//State machine
-#define STATE_START      0
-#define STATE_SIZE      1
-#define STATE_CONTENT    2
-
-//Special bytes in the communication protocol
-#define BYTE_START      0x7e
-#define BYTE_ESCAPE      0x7d
-#define BYTE_SEPARATOR    0x7c
-
-#define CSPIN             21
-
-void setup(){
-  Serial.begin(9600); // initialize Serial communication
-  while(!Serial) ;    // wait for serial port to connect.
-
-  pinMode(13, OUTPUT);
-
-  SerialFlash.begin(CSPIN);
-
-  //We start by formatting the flash...
-  uint8_t id[5];
-  SerialFlash.readID(id);
-  SerialFlash.eraseAll();
-
-  //Flash LED at 1Hz while formatting
-  while (!SerialFlash.ready()) {
-    delay(500);
-    digitalWrite(13, HIGH);
-    delay(500);
-    digitalWrite(13, LOW);
-  }
-
-  //Quickly flash LED a few times when completed, then leave the light on solid
-  for(uint8_t i = 0; i < 10; i++){
-    delay(100);
-    digitalWrite(13, HIGH);
-    delay(100);
-    digitalWrite(13, LOW);
-  }
-  digitalWrite(13, HIGH);
-
-  //We are now going to wait for the upload program
-  while(!Serial.available());
-
-  SerialFlashFile flashFile;
-
-  uint8_t state = STATE_START;
-  uint8_t escape = 0;
-  uint8_t fileSizeIndex = 0;
-  uint32_t fileSize = 0;
-  char filename[FILENAME_STRING_SIZE];
-
-  char usbBuffer[USB_BUFFER_SIZE];
-  uint8_t flashBuffer[FLASH_BUFFER_SIZE];
-
-  uint16_t flashBufferIndex = 0;
-  uint8_t filenameIndex = 0;
-
-  uint32_t lastReceiveTime = millis();
-
-  //We assume the serial receive part is finished when we have not received something for 3 seconds
-  while(Serial.available() || lastReceiveTime + 3000 > millis()){
-    uint16_t available = Serial.readBytes(usbBuffer, USB_BUFFER_SIZE);
-    if (available){
-      lastReceiveTime = millis();
-    }
-
-    for (uint16_t usbBufferIndex = 0; usbBufferIndex < available; usbBufferIndex++){
-      uint8_t b = usbBuffer[usbBufferIndex];
-
-      if (state == STATE_START){
-        //Start byte.  Repeat start is fine.
-        if (b == BYTE_START){
-          for (uint8_t i = 0; i < FILENAME_STRING_SIZE; i++){
-            filename[i] = 0x00;
-          }
-          filenameIndex = 0;
-        }
-        //Valid characters are A-Z, 0-9, comma, period, colon, dash, underscore
-        else if ((b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9') || b == '.' || b == ',' || b == ':' || b == '-' || b == '_'){
-          filename[filenameIndex++] = b;
-          if (filenameIndex >= FILENAME_STRING_SIZE){
-            //Error name too long
-            flushError();
-            return;
-          }
-        }
-        //Filename end character
-        else if (b == BYTE_SEPARATOR){
-          if (filenameIndex == 0){
-            //Error empty filename
-            flushError();
-            return;
-          }
-
-          //Change state
-          state = STATE_SIZE;
-          fileSizeIndex = 0;
-          fileSize = 0;
-
-        }
-        //Invalid character
-        else {
-          //Error bad filename
-          flushError();
-          return;
-        }
-      }
-      //We read 4 bytes as a uint32_t for file size
-      else if (state == STATE_SIZE){
-        if (fileSizeIndex < 4){
-          fileSize = (fileSize << 8) + b;
-          fileSizeIndex++;
-        }
-        else if (b == BYTE_SEPARATOR){
-          state = STATE_CONTENT;
-          flashBufferIndex = 0;
-          escape = 0;
-
-          if (SerialFlash.exists(filename)){
-            SerialFlash.remove(filename);  //It doesn't reclaim the space, but it does let you create a new file with the same name.
-          }
-
-          //Create a new file and open it for writing
-          if (SerialFlash.create(filename, fileSize)) {
-            flashFile = SerialFlash.open(filename);
-            if (!flashFile) {
-              //Error flash file open
-              flushError();
-              return;
-            }
-          }
-          else {
-            //Error flash create (no room left?)
-            flushError();
-            return;
-          }
-        }
-        else {
-          //Error invalid length requested
-          flushError();
-          return;
-        }
-      }
-      else if (state == STATE_CONTENT){
-        //Previous byte was escaped; unescape and add to buffer
-        if (escape){
-          escape = 0;
-          flashBuffer[flashBufferIndex++] = b ^ 0x20;
-        }
-        //Escape the next byte
-        else if (b == BYTE_ESCAPE){
-          //Serial.println("esc");
-          escape = 1;
-        }
-        //End of file
-        else if (b == BYTE_START){
-          //Serial.println("End of file");
-          state = STATE_START;
-          flashFile.write(flashBuffer, flashBufferIndex);
-          flashFile.close();
-          flashBufferIndex = 0;
-        }
-        //Normal byte; add to buffer
-        else {
-          flashBuffer[flashBufferIndex++] = b;
-        }
-
-        //The buffer is filled; write to SD card
-        if (flashBufferIndex >= FLASH_BUFFER_SIZE){
-          flashFile.write(flashBuffer, FLASH_BUFFER_SIZE);
-          flashBufferIndex = 0;
-        }
-      }
-    }
-  }
-
-  //Success!  Turn the light off.
-  digitalWrite(13, LOW);
-}
-
-void loop(){
-  //Do nothing.
-}
-
-void flushError(){
-  uint32_t lastReceiveTime = millis();
-  char usbBuffer[USB_BUFFER_SIZE];
-  //We assume the serial receive part is finished when we have not received something for 3 seconds
-  while(Serial.available() || lastReceiveTime + 3000 > millis()){
-    if (Serial.readBytes(usbBuffer, USB_BUFFER_SIZE)){
-      lastReceiveTime = millis();
-    }
-  }
-}


adding links to libraries

adding links to libraries

eventually will move these to readme

--- firmware/SensorBoard_node/SensorBoard_node.ino
+++ firmware/SensorBoard_node/SensorBoard_node.ino
@@ -1,12 +1,12 @@
-#include <RFM69.h>  // from lowpowerlab
+#include <RFM69.h>  //  https://github.com/LowPowerLab/RFM69
 #include <SPI.h>
-#include <SPIFlash.h> //get it here: https://www.github.com/lowpowerlab/spiflash
+#include <SPIFlash.h> // https://www.github.com/lowpowerlab/spiflash
 #include <Arduino.h>
-#include <Wire.h>
-#include "Adafruit_SHT31.h"
-#include "SparkFunMPL3115A2.h"
-#include <Adafruit_Sensor.h>  // from Adafruit's github
-#include <Adafruit_TSL2561_U.h>
+#include <Wire.h>
+#include "Adafruit_SHT31.h" //https://github.com/adafruit/Adafruit_SHT31
+#include "SparkFunMPL3115A2.h" // https://github.com/sparkfun/SparkFun_MPL3115A2_Breakout_Arduino_Library/tree/master/src
+#include <Adafruit_Sensor.h>  // https://github.com/adafruit/Adafruit_Sensor
+#include <Adafruit_TSL2561_U.h> // https://github.com/adafruit/Adafruit_TSL2561
 #include <avr/sleep.h>
 #include <avr/wdt.h>


Added some comments and more logic to loop

--- src/bikelight/bikelight.ino
+++ src/bikelight/bikelight.ino
@@ -53,6 +53,8 @@
   Wire.onReceive(receiveEvent);
 }

+// want to count button presses within a certain time.
+
 void loop() {
   //store state of switch
   int frontReading = digitalRead(frontSwitch);
@@ -71,10 +73,13 @@
       frontButtonState = frontReading;
     }
     if (frontButtonState == LOW){ //pull up resistor enabled, pulled low when pushed
-
+      frontButtonCounter++;
     }
     if (backReading!= backButtonState){
       backButtonState = backReading;
+    }
+    if (backButtonState == LOW){ //pull up resistor enabled, pulled low when pushed
+        backButtonCounter++;
     }
   }


Revert "Revert "remove mqtt cert""

Revert "Revert "remove mqtt cert""

This reverts commit 7b608709c7d80b3ee336f10499d51f25ff61dc48.


Fix typo in Complete.ino

Fix typo in Complete.ino

--- examples/Complete/Complete.ino
+++ examples/Complete/Complete.ino
@@ -143,7 +143,7 @@
     /****************************************/
     // connect
     /*Serial.print("connect: ");
-    Serial.println(getStatus(wifi.connect(ESP8266_PROTOCOL_TCP, IPAddress(192.168.4.100), 4000)));*/
+    Serial.println(getStatus(wifi.connect(ESP8266_PROTOCOL_TCP, IPAddress(192,168,4,100), 4000)));*/

     // send
     /*Serial.print("send: ");


Add Mario themes

Add Mario themes


dir rearrangement

dir rearrangement

--- tank_water_level.ino
+++ tank_water_level.ino
@@ -1,44 +0,0 @@
-/*
-Using this sketch you can calculate water volume in cylinder.
-Based on ultrasonic sensor and NewPing library(which provides output smoothing).
-tH = Total Height (tank height)
-distance = Difference between ultrasonic sensor and water surface. (automaticaly calculated)
-f= Fill height calculated by: tH - distance
-v= volume calculated by: V(tank) = (πr2*f/1000)
-bubblestack - 2016
-by
-Nika Chkhikvishvili & Davit Gokadze
-http://bubblestack.io
-*/
-
-#include <NewPing.h>
-
-#define TRIGGER_PIN  12
-#define ECHO_PIN     13
-#define MAX_DISTANCE 300
-
-
-float distance;
-float tH=86; // Total Height of Tank in cm.
-float radius=10;
-float sqr_R=sq(radius); // Square Radius of Tank 10cm*10cm;
-float litre=1000; //1 litre 1000 ml;
-float volume;
-float f; // fill height
-float Pi=3.14;
-
-NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
-
-void setup() {
-  Serial.begin(9600);
-}
-
-void loop() {
-  delay(1000);
-  int uS = sonar.ping_median(15); // median filter, error correction
-   distance=(uS / US_ROUNDTRIP_CM); // calculate distance
-   f=(tH-distance); //  calculate fill height of tank
-   volume=(Pi*sqr_R*f/1000); // calculate volume of liquid
-    Serial.println(volume);
-
- }


SHE'S VERKING (logical aspects of Motor Controller finished)

--- DomeAutomation/RObhat_motor_controller_v2/RObhat_motor_controller_v2.ino
+++ DomeAutomation/RObhat_motor_controller_v2/RObhat_motor_controller_v2.ino
@@ -1,7 +1,7 @@
 #include <Arduino.h>
 // #include <stdio.h>

-const int motorAF_neutral = 9;     // motor circuit is connected to pin 5
+const int motorAF_neutral = 9; // motor circuit is connected to pin 5
 const int motorAF_hot = 8;
 const int motorAR_neutral = 12; // motor circuit is connected to pin 5
 const int motorAR_hot = 11;
@@ -50,6 +50,8 @@
         pinMode(buttonBR, INPUT_PULLUP); // input, shorting to ground pulls input
         // low, so "LOW" state is on
         Serial.begin(9600); // sets the data rate for the serial monitor tool
+        motorOff("A");
+        motorOff("B");
 }

 bool *
@@ -130,18 +132,20 @@
         }

         // Serial monitor
-        if (Serial.available()) {
+        if (Serial.available())
+        {
                 String serialText =
                         Serial.readStringUntil('&'); // reads incoming data from the serial port
-                if (serialText == "onAF") // turn on A
-                {
-                        motorOn("A", "F");
+                if (serialText == "onAF") { // turn on A
+                        // motorOn("A", "F");
+                        buttonState[0] = LOW;
                         currentState[0] = LOW;
                         currentState[1] = HIGH;
                         Serial.println("Serial A: \t\t FWD");
-                } else if (serialText == "onAR") // turn on A
-                {
-                        motorOn("A", "R");
+                } else if (serialText == "onAR") { // turn on A
+
+                        // motorOn("A", "R");
+                        buttonState[1] = LOW;
                         currentState[1] = LOW;
                         currentState[0] = HIGH;
                         Serial.println("Serial A: \t\t REV");
@@ -150,16 +154,20 @@
                         currentState[0] = HIGH;
                         currentState[1] = HIGH;
                         Serial.println("Serial A: \t\t OFF");
-                }
-                if (serialText == "onBF") // turn on B
-                {
-                        motorOn("B", "F");
+                } else{
+                        Serial.println("Serial A: \t\t N/A");
+                }
+
+                if (serialText == "onBF") { // turn on B
+                        // motorOn("B", "F");
+                        buttonState[2] = LOW;
                         currentState[2] = LOW;
                         currentState[3] = HIGH;
                         Serial.println("Serial B: \t\t FWD");
-                } else if (serialText == "onBR") // turn on B
-                {
-                        motorOn("B", "R");
+                } else if (serialText == "onBR") { // turn on B
+
+                        // motorOn("B", "R");
+                        buttonState[3] = LOW;
                         currentState[2] = HIGH;
                         currentState[3] = LOW;
                         Serial.println("Serial B: \t\t REV");
@@ -168,56 +176,42 @@
                         currentState[2] = HIGH;
                         currentState[3] = HIGH;
                         Serial.println("Serial B: \t\t OFF");
-                }
-        }
-
-        if (buttonState[0] == LOW and not (buttonState[1] == LOW)) // 4
-        {
-                // Serial.println("A: \t\t FWD");
-                motorOn("A", "F");
-        } else if (buttonState[1] == LOW and not (buttonState[0] == LOW)) // 4
-        {
-                // Serial.println("A: \t\t REV");
-                motorOn("A", "R");
-        } else if (buttonState[0] == LOW and buttonState[1] == LOW and currentState[0] == LOW and not (currentState[1] == LOW)) // 1
-        {
-                buttonState[1] = HIGH;
-                // Serial.println("A: \t\t FWD");
-                motorOn("A", "F");
-        } else if (buttonState[0] == LOW and buttonState[1] == LOW and currentState[1] == LOW and not (currentState[0] == LOW)) // 1
-        {
-                buttonState[0] = HIGH;
-                // Serial.println("A: \t\t REV");
-                motorOn("A", "R");
-        } else // 4+1
-        {
-                // Serial.println("A: \t\t OFF");
-                // motorOff("A");
-        }
-
-        if (buttonState[2] == LOW and not (buttonState[3] == LOW)) // 4
-        {
-                // Serial.println("B: \t\t FWD");
-                motorOn("B", "F");
-        } else if (buttonState[3] == LOW and not (buttonState[2] == LOW)) // 4
-        {
-                // Serial.println("B: \t\t REV");
-                motorOn("B", "R");
-        } else if (buttonState[2] == LOW and buttonState[3] == LOW and currentState[2] == LOW and not (currentState[3] == LOW)) // 1
-        {
-                buttonState[3] = HIGH;
-                // Serial.println("B: \t\t FWD");
-                motorOn("B", "F");
-        } else if (buttonState[2] == LOW and buttonState[3] == LOW and currentState[3] == LOW and not (currentState[2] == LOW)) // 1
-        {
-                buttonState[2] = HIGH;
-                // Serial.println("B: \t\t REV");
-                motorOn("B", "R");
-        } else // 4+1
-        {
-                // Serial.println("B: \t\t OFF");
-                // motorOff("B");
-        }
+                }else{
+                        Serial.println("Serial B: \t\t N/A");
+                }
+        }
+
+        if (buttonState[0] == LOW) {
+                if (not (digitalRead(motorAR_hot) == HIGH or currentState[1] == LOW) or buttonState[1] == HIGH) {
+                        motorOn("A", "F");
+                }
+        }
+
+        if (buttonState[1] == LOW) {
+                if (not (digitalRead(motorAF_hot) == HIGH or currentState[0] == LOW) or buttonState[0] == HIGH ) {
+                        motorOn("A", "R");
+                }
+
+        }
+        if (buttonState[0] == HIGH and buttonState[1] == HIGH) {
+                motorOff("A");
+        }
+        if (buttonState[2] == LOW) {
+                if (not (digitalRead(motorBR_hot) == HIGH or currentState[3] == LOW) or buttonState[3] == HIGH) {
+                        motorOn("B", "F");
+                }
+        }
+
+        if (buttonState[3] == LOW) {
+                if (not (digitalRead(motorBF_hot) == HIGH or currentState[2] == LOW) or buttonState[2] == HIGH ) {
+                        motorOn("B", "R");
+                }
+
+        }
+        if (buttonState[2] == HIGH and buttonState[3] == HIGH) {
+                motorOff("B");
+        }
+

         if (digitalRead(motorAF_hot) == HIGH) {
                 Serial.println("A: \t\t FWD");
@@ -237,8 +231,8 @@

         Serial.println("===========================");
         delay(TIME);
-        motorOff("A");
-        motorOff("B");
+        // motorOff("A");
+        // motorOff("B");
         iters++;
         bool * currentState = buttonState;
 }