pair + timer off pnly

pair + timer off pnly

--- _09_ir_tx_rx/_09_ir_tx_rx.ino
+++ _09_ir_tx_rx/_09_ir_tx_rx.ino
@@ -27,12 +27,10 @@
   long magic;
   int pwrSrc;     // 1 : connected to TV, 0 : usb powered
   int wrkMode;    // 1 : thermostat + TV, 0 : thermostat
-  int startMode;  // if wrkMode == 1, 1 : run TV on/off or channel change, 0 : do nothing indicating a sign on the lcd
+  int startMode;  // if wrkMode == 1, 1 : auto start timer, pir, 0 : do nothing indicating a sign on the lcd
   int beepMode;   // 1 : beep on
-  int offMode;    // 1 : TV on/off, 0 : input change
   int channelGap; // 1 ~ 5
   int tvOnTime;   // 30 ~ 90
-  int tvOffTime;  // 5 ~ 20
 };

 // pins
@@ -77,10 +75,8 @@
 int o_wrkMode;
 int o_startMode;
 int o_beepMode;
-int o_offMode;
 int o_channelGap;
 int o_tvOnTime;
-int o_tvOffTime;

 // sw pin status
 int setUpStatus;
@@ -98,7 +94,6 @@
 unsigned long tv_left  = 0x20DFE01F;
 unsigned long tv_enter = 0x20DF22DD;
 unsigned long tv_onoff = 0x20DF10EF;
-

 //
 int r   = 0;
@@ -248,10 +243,8 @@
   eeprom_read(o_wrkMode, wrkMode);
   eeprom_read(o_startMode, startMode);
   eeprom_read(o_beepMode, beepMode);
-  eeprom_read(o_offMode, offMode);
   eeprom_read(o_channelGap, channelGap);
  // eeprom_read(o_tvOnTime, tvOnTime);
- // eeprom_read(o_tvOffTime, tvOffTime);

   // temp sensor
   sensors.begin();
@@ -288,7 +281,6 @@
     if ( o_pwrSrc == 1 ) {

       // input change
-      o_offMode = 0;
       tvPowerStatus = 1;
       timerStatus = 1;

@@ -310,7 +302,6 @@
   int updateTempCArrayEvent = t.every(300000, doUpdateTempCArray);

   o_tvOnTime  = 2;
-  o_tvOffTime = 1;

 }

@@ -326,7 +317,6 @@
 {

   t.update();
-

   // receiving ir and change status
   // remote on / off, tv remote on / off
@@ -397,12 +387,10 @@
     switch (results->value) {
       case 0xFF02FD: // remote on
         if ( o_wrkMode == 1 ) {
-         // t.stop(tvIsOffEvent);
-         // t.stop(tvIsOnEvent);
           timerStatus = 0;
         } else {
           timerStatus = 1;
-         // tvOnTimer();
+          tvOnTimer();
           temp_Mills = millis();
         }
         o_wrkMode = ! o_wrkMode;
@@ -411,10 +399,8 @@
         break;
       case 0xFF9867: // remote off
         if ( timerStatus == 1 ) {
-          //t.stop(tvIsOffEvent);
-          //t.stop(tvIsOnEvent);
         } else {
-          //tvOnTimer();
+          tvOnTimer();
           temp_Mills = millis();
         }
         timerStatus = ! timerStatus;
@@ -422,12 +408,10 @@
         break;
       case 0x20DF10EF: // tv remote on/off
         if ( tvPowerStatus == 1 ) {
-          //t.stop(tvIsOffEvent);
-          //t.stop(tvIsOnEvent);
           timerStatus = 0;
         } else {
           timerStatus = 1;
-          //tvOnTimer();
+          tvOnTimer();
           temp_Mills = millis();
         }
         tvPowerStatus = ! tvPowerStatus;
@@ -458,36 +442,14 @@
 {
   long time_o_tvOnTime = o_tvOnTime * 1000 * 60 ;
   tvIsOnEvent = t.after(time_o_tvOnTime , doTvOffTimer);
-  t.stop(tvIsOffEvent);
-}
-
-void tvOffTimer()
-{
-  long time_o_tvOffTime = o_tvOffTime * 1000 * 60;
-  tvIsOffEvent = t.after(time_o_tvOffTime , doTvOnTimer);
-  t.stop(tvIsOnEvent);
-}
+}
+

 void doTvOffTimer()
 {
-  // if ( o_wrkMode == 1 && o_startMode == 1 ) {
-
-  tvOffTimer();
   lcd.setCursor(15, 0);
   lcd.write(6);
-  irSendTvbytimer(0);
-  // }
-}
-
-void doTvOnTimer()
-{
-  //if ( o_wrkMode == 1 && o_startMode == 1 ) {
-
-  tvOnTimer();
-  lcd.setCursor(15, 0);
-  lcd.print(" ");
-  irSendTvbytimer(1);
-  // }
+  irSendTvOutbytimer(0);
 }

 //
@@ -498,12 +460,12 @@
     case 1:
       lcd.setCursor(15, 0);
       lcd.print(" ");
-      irSendTvbypir(1);
+      irSendTvOutbypir(1);
       break;
     case 0:
       lcd.setCursor(15, 0);
       lcd.write(6);
-      irSendTvbypir(0);
+      irSendTvOutbypir(0);
       break;
   }
   // }
@@ -511,79 +473,48 @@
 }

-void irSendTvbytimer(int onoff)
-{
-  switch (onoff) {
+void irSendTvOutbypir(int a)
+{
+
+  if (DEBUG_PRINT) {
+    Serial.println("IRSend CH change called");
+  }
+  switch (a) {
+    case 0:
+      irsend.sendNEC(tv_input, 32);
+      delay(3000);
+      for ( int i = 0 ; i < o_channelGap ; i++ ) {
+        irsend.sendNEC(tv_left, 32);
+        delay(300);
+      }
+      irsend.sendNEC(tv_enter, 32);
+      break;
     case 1:
-     // if ( tvPowerStatus == 0 )
-     // {
-        irSendTvOut(1);
-        tvPowerStatus = 1;
-        temp_Mills = millis();
-      //}
-      break;
-    case 0:
-      //if ( tvPowerStatus == 1 )
-      //{
-        irSendTvOut(0);
-        tvPowerStatus = 0;
-        temp_Mills = millis();
-      //}
-      break;
-  }
-}
-
-void irSendTvbypir(int onoff)
-{
-  if ( tvPowerStatus == 1 ) {
-    switch (onoff) {
-      case 1:
-        irSendTvOut(1);
-        break;
-      case 0:
-        irSendTvOut(0);
-        break;
-    }
-  }
-}
-
-void irSendTvOut(int a)
-{
-  if ( o_offMode == 1 ) {
-    if (DEBUG_PRINT) {
-      Serial.println("IRSend on/off called");
-    }
-    irsend.sendNEC(tv_onoff, 32);
-    delay(300);
-    irrecv.enableIRIn();
-  } else {
-    if (DEBUG_PRINT) {
-      Serial.println("IRSend CH change called");
-    }
-    switch (a) {
-      case 0:
-        irsend.sendNEC(tv_input, 32);
-        delay(3000);
-        for ( int i = 0 ; i < o_channelGap ; i++ ) {
-          irsend.sendNEC(tv_left, 32);
-          delay(300);
-        }
-        irsend.sendNEC(tv_enter, 32);
-        break;
-      case 1:
-        irsend.sendNEC(tv_input, 32);
-        delay(3000);
-        for ( int i = 0 ; i < o_channelGap ; i++ ) {
-          irsend.sendNEC(tv_right, 32);
-          delay(300);
-        }
-        irsend.sendNEC(tv_enter, 32);
-        break;
-    }
-  }
+      irsend.sendNEC(tv_input, 32);
+      delay(3000);
+      for ( int i = 0 ; i < o_channelGap ; i++ ) {
+        irsend.sendNEC(tv_right, 32);
+        delay(300);
+      }
+      irsend.sendNEC(tv_enter, 32);
+      break;
+  }
+
   irrecv.enableIRIn();
 }

+//
+void irSendTvOutbytimer(int a)
+{
+  if (DEBUG_PRINT) {
+    Serial.println("IRSend on/off called");
+  }
+  irsend.sendNEC(tv_onoff, 32);
+  delay(300);
+  irrecv.enableIRIn();
+  tvPowerStatus = ! tvPowerStatus ;
+
+}

 // TimeTime
 void displaytimeleft() {
@@ -596,11 +527,9 @@
   }
   */

-  if ( tvPowerStatus == 1) {
-    timeleft = (( o_tvOnTime * 1000 ) * 60 ) - (millis() - temp_Mills) ;
-  } else {
-    timeleft = (( o_tvOffTime * 1000 ) * 60 ) - (millis() - temp_Mills ) ;
-  }
+
+  timeleft = (( o_tvOnTime * 1000 ) * 60 ) - (millis() - temp_Mills) ;
+

   String str_a = String(int(timeleft));
   int length_a = str_a.length();
@@ -845,27 +774,6 @@
   lcd.setCursor(0, 0);
   lcd.print("Select");
   lcd.setCursor(0, 1);
-  lcd.print("TV off mode");
-  lcd.setCursor(15, 1);
-  lcd.print("*");
-
-  irrecv.resume();
-  while (irrecv.decode(&results) != 1 ) { }
-  alarm_set();
-
-  lcd.clear();
-  lcd.setCursor(0, 0);
-  lcd.print("ON : TV on / off");
-  lcd.setCursor(0, 1);
-  lcd.print("OFF: IN change");
-
-  o_offMode = initialise_boolean_select();
-  alarm_set();
-
-  lcd.clear();
-  lcd.setCursor(0, 0);
-  lcd.print("Select");
-  lcd.setCursor(0, 1);
   lcd.print("channel gap");
   lcd.setCursor(15, 1);
   lcd.print("*");
@@ -904,11 +812,17 @@
   o_tvOnTime = initialise_number_select(30, 90, 50, 5);
   alarm_set();

-  lcd.clear();
-  lcd.setCursor(0, 0);
-  lcd.print("Select timer");
-  lcd.setCursor(0, 1);
-  lcd.print("for TV auto on");
+  int initialise_eeprom_done =  initialise_eeprom(o_pwrSrc, o_wrkMode, o_startMode, o_beepMode, o_channelGap, o_tvOnTime) ;
+
+  while (initialise_eeprom_done != 1 ) { }
+
+  lcd.clear();
+  lcd.setCursor(0, 0);
+  lcd.print("Setup is done");
+  lcd.setCursor(0, 1);
+  if ( setUpStatus == 0 ) {
+    lcd.print("change setup sw");
+  }
   lcd.setCursor(15, 1);
   lcd.print("*");

@@ -918,34 +832,6 @@

   lcd.clear();
   lcd.setCursor(0, 0);
-  lcd.print("ON : change no");
-  lcd.setCursor(0, 1);
-  lcd.print("OFF : done");
-
-  o_tvOffTime = initialise_number_select(5, 20, 10, 5);
-  alarm_set();
-
-
-  int initialise_eeprom_done =  initialise_eeprom(o_pwrSrc, o_wrkMode, o_startMode, o_beepMode, o_offMode, o_channelGap, o_tvOnTime, o_tvOffTime) ;
-
-  while (initialise_eeprom_done != 1 ) { }
-
-  lcd.clear();
-  lcd.setCursor(0, 0);
-  lcd.print("Setup is done");
-  lcd.setCursor(0, 1);
-  if ( setUpStatus == 0 ) {
-    lcd.print("change setup sw");
-  }
-  lcd.setCursor(15, 1);
-  lcd.print("*");
-
-  irrecv.resume();
-  while (irrecv.decode(&results) != 1 ) { }
-  alarm_set();
-
-  lcd.clear();
-  lcd.setCursor(0, 0);
   lcd.print("Press any button");
   lcd.setCursor(0, 1);
   lcd.print("to reset");
@@ -958,16 +844,14 @@
 }

-int initialise_eeprom(int o_pwrSrc, int o_wrkMode, int o_startMode, int o_beepMode, int o_offMode, int o_channelGap, int o_tvOnTime, int o_tvOffTime)
+int initialise_eeprom(int o_pwrSrc, int o_wrkMode, int o_startMode, int o_beepMode, int o_channelGap, int o_tvOnTime)
 {
   eeprom_write(o_pwrSrc, pwrSrc);
   eeprom_write(o_wrkMode, wrkMode);
   eeprom_write(o_startMode, startMode);
   eeprom_write(o_beepMode, beepMode);
-  eeprom_write(o_offMode, offMode);
   eeprom_write(o_channelGap, channelGap);
   eeprom_write(o_tvOnTime, tvOnTime);
-  eeprom_write(o_tvOffTime, tvOffTime);
   eeprom_write(magic_number, magic);

   alarm_set();


Inserted a switch button..

Inserted a switch button..

--- BlinkLed/BlinkLed/BlinkLed.ino
+++ BlinkLed/BlinkLed/BlinkLed.ino
@@ -14,17 +14,21 @@
 */

 const int builtinLed = 13;
+const int switchButton = 9;

 // the setup function runs once when you press reset or power the board
 void setup() {
-  // initialize digital pin 13 as an output.
-  pinMode(builtinLed, OUTPUT);
+	// initialize digital pin 13 as an output & pin 9 as input.
+	pinMode(builtinLed, OUTPUT);
+	pinMode(switchButton, INPUT);
 }

 // the loop function runs over and over again forever
 void loop() {
-  digitalWrite(builtinLed, HIGH);   // turn the LED on (HIGH is the voltage level)
-  delay(1000);						// wait for a second
-  digitalWrite(builtinLed, LOW);    // turn the LED off by making the voltage LOW
-  delay(1000);						// wait for a second
+	if (switchButton == LOW) {
+		digitalWrite(builtinLed, HIGH);
+	}
+	else {
+		digitalWrite(builtinLed, LOW);
+	}
 }


- minor changes on device ID

- minor changes on device ID

--- Device_LinkItOne/LASS/LASS.ino
+++ Device_LinkItOne/LASS/LASS.ino
@@ -279,7 +279,7 @@
 //----- MQTT -----
 #define MQTT_PROXY_IP "gpssensor.ddns.net"  // Current LASD server
 #define DEVICE_TYPE  "LinkItONE"
-#define DEVICE_ID "FT1_002"    // REPLACE: The device ID you like, please start from LASD. Without this prefix, maybe it will be filter out.
+#define DEVICE_ID "FT1_001"    // REPLACE: The device ID you like, please start from LASD. Without this prefix, maybe it will be filter out.
 #define MQTT_TOPIC_PREFIX "LASS/Test"
 #define PARTNER_ID "LASS-Partner1"
 char mqttTopic[64];


Added authors

Added authors

etc.

--- Nokia_TMP_and_Trimpot/Nokia_TMP_and_Trimpot.ino
+++ Nokia_TMP_and_Trimpot/Nokia_TMP_and_Trimpot.ino
@@ -1,4 +1,10 @@
-#include <SPI.h> // We'll use SPI to transfer data. Faster!
+
+// Sources:
+// http://playground.arduino.cc/Code/PCD8544
+// http://dlnmh9ip6v2uc.cloudfront.net/datasheets/LCD/Monochrome/Nokia_5110_Example.pde
+// http://forum.arduino.cc/index.php?topic=176794.0
+
+#include <SPI.h> // We'll use SPI to transfer  data. Faster!

 #define PIN_SCE   7
 #define PIN_RESET 6


removed stop from lockedrotorcheck

removed stop from lockedrotorcheck

--- Exhibit_MomentumTable.ino
+++ Exhibit_MomentumTable.ino
@@ -75,7 +75,7 @@
 if  (allStopVar == 0){
     calculateRPM();
     discSlipCheck();
-    lockedRotorCheck();
+   // lockedRotorCheck();
 }
     now = millis();
     //MQTT Connection Check
@@ -97,15 +97,14 @@

 void calculateRPM(){
 if (millis() - prevMillis == 1000){
-  //  detachInterrupt(HALLSENSORPIN);              //disable interrupts while running calculate
+    detachInterrupt(HALLSENSORPIN);              //disable interrupts while running calculate
     rpm = pulseCount * 60;          //converting frequency to RPM
     pulseCount = 0;                 //reset pulse counter
     prevMillis = millis();          //update prevMillis
     Serial.print("RPM: ");
     Serial.println(rpm);
- //   attachInterrupt(digitalPinToInterrupt(HALLSENSORPIN), sensorPulseCount, RISING);
-    //reattach interrupt
-    }
+    attachInterrupt(digitalPinToInterrupt(HALLSENSORPIN), sensorPulseCount, RISING);
+		}
   }

 void motionControlStart(){
@@ -122,6 +121,7 @@
             }
         if (pulseCount > 1){
         Serial.println("motion started, system running");
+		pulseCount = 0;
         restartCount = 0; // set restart counter to 0, since we're started
         allStopVar = 0; // Set allstop condition to off
 		Serial.print("AllStopVar ");


Implement a basic time synchronisation command (TODO: has offset equal to transmission latency)

--- arduino/rflink/rflink.ino
+++ arduino/rflink/rflink.ino
@@ -28,6 +28,7 @@

 static uint8_t node_id;
+static int32_t time_offset = 0;

 typedef struct {
     uint8_t len;
@@ -179,7 +180,7 @@
     uint8_t type = buf->data[2];

     Serial.print(argv[0]);
-    Serial.print(" ");
+    Serial.print(" 00 ");
     Serial.print(dest, HEX);
     Serial.print(" ");
     Serial.print(type, HEX);
@@ -190,12 +191,26 @@
     return 0;
 }

+static int do_time(int argc, char *argv[])
+{
+    uint32_t time = millis() + time_offset;
+    if (argc == 2) {
+        time = atoi(argv[1]);
+        // recalculate time offset
+        time_offset = time - millis();
+    }
+    Serial.print(argv[0]);
+    Serial.print(" 00 ");
+    Serial.println(time);
+}
+
 static const cmd_t commands[] = {
     {"help",    do_help,    "lists all commands"},
     {"id",      do_id,      "[id] gets/sets the node id"},
     {"ping",    do_ping,    "[node] sends a ping to node"},
     {"s",       do_send,    "[node] [type] [data] sends data"},
     {"r",       do_recv,    "[node] returns data from buffer"},
+    {"time",    do_time,    "[time] gets/set the time"},
     {"", NULL, ""}
 };

@@ -243,7 +258,7 @@
         if (sec != prev_sec) {
             prev_sec = sec;
             // update beacon
-            beacon.time = m;
+            beacon.time = m + time_offset;
             beacon.frame++;
             beacon.slot_offs = 10;
             beacon.slot_size = 10;
@@ -285,6 +300,8 @@
             memcpy(&beacon, &rcv[3], sizeof(beacon));
             // determine next send time
             next_send = m + beacon.slot_offs + (beacon.slot_size * node_id);
+            // recalculate time offset
+            time_offset = beacon.time - m;
             break;

         case 0x01:


test of ssh key

test of ssh key

--- ardesp/waterelf_gripple/waterelf_gripple.ino
+++ ardesp/waterelf_gripple/waterelf_gripple.ino
@@ -423,7 +423,7 @@
 void startAP() {
   WiFi.mode(WIFI_AP_STA);
   WiFi.softAPConfig(apIP, apIP, netMsk);
-  WiFi.softAP(apSSID,"BIGSECRET!");
+  WiFi.softAP(apSSID,"BIGSECRETS!");
   dln(startupDBG, "Soft AP started");
 }


Manejo del puerto serie

Manejo del puerto serie

--- LM4F_E003/LM4F_E003.ino
+++ LM4F_E003/LM4F_E003.ino
@@ -1,71 +1,71 @@
-/*******************************************************************************
- *
- *                  Manejo del puerto serie
- *
- *******************************************************************************
- * FileName:        LM4F_E002
- * Processor:       EX-LM4F120XL
- * Complier:        Energia 0101e0017
- * Author:          Pedro Sánchez (MrChunckuee)
- * Blog:            http://mrchunckuee.blogspot.com/
- * Email:           mrchunckuee.psr@gmail.com
- * Description:     Este ejemplo basico para el manejo del puerto serial
- *******************************************************************************
- * Rev.         Date            Comment
- *   v1.00      14/10/2016      Creación del firmware
- ******************************************************************************/
-
-unsigned char inputByte = 0; // incoming serial byte
-
-void setup(){
-// start serial port at 9600 bps
-  Serial.begin(9600);
-  pinMode(RED_LED, OUTPUT);
-  pinMode(BLUE_LED, OUTPUT);
-  pinMode(GREEN_LED, OUTPUT);
-}
-
-void loop(){
-  if (Serial.available() > 0) {
-    inputByte = Serial.read(); // get incoming byte
-    switch(inputByte){
-      case 'a':
-        digitalWrite(RED_LED,HIGH);
-        Serial.print("LED Rojo encendido\n");
-      break;
-      case 'b':
-        digitalWrite(RED_LED,LOW);
-        Serial.print("LED Rojo apagado");
-      break;
-      case 'c':
-        digitalWrite(GREEN_LED,HIGH);
-        Serial.print("LED Verde encendido");
-      break;
-      case 'd':
-        digitalWrite(GREEN_LED,LOW);
-       Serial.print("LED Verde apagado");
-      break;
-      case 'e':
-        digitalWrite(BLUE_LED,HIGH);
-        Serial.print("LED Azul encendido");
-      break;
-      case 'f':
-        digitalWrite(BLUE_LED,LOW);
-        Serial.print("LED Azul apagado");
-      break;
-      case 'g':
-        digitalWrite(RED_LED,LOW);
-        digitalWrite(GREEN_LED,LOW);
-        digitalWrite(BLUE_LED,LOW);
-        Serial.print("LEDs apagados");
-      break;
-      default:
-        digitalWrite(RED_LED,LOW);
-        digitalWrite(GREEN_LED,LOW);
-        digitalWrite(BLUE_LED,LOW);
-      break;
-    }
-  }
-}
-
+/*******************************************************************************
+ *
+ *                  Manejo del puerto serie
+ *
+ *******************************************************************************
+ * FileName:        LM4F_E003
+ * Processor:       EX-LM4F120XL
+ * Complier:        Energia 0101e0017
+ * Author:          Pedro Sánchez (MrChunckuee)
+ * Blog:            http://mrchunckuee.blogspot.com/
+ * Email:           mrchunckuee.psr@gmail.com
+ * Description:     Este ejemplo basico para el manejo del puerto serial
+ *******************************************************************************
+ * Rev.         Date            Comment
+ *   v1.00      14/10/2016      Creación del firmware
+ ******************************************************************************/

+unsigned char inputByte = 0; // incoming serial byte
+
+void setup(){
+// start serial port at 9600 bps
+  Serial.begin(9600);
+  pinMode(RED_LED, OUTPUT);
+  pinMode(BLUE_LED, OUTPUT);
+  pinMode(GREEN_LED, OUTPUT);
+}
+
+void loop(){
+  if (Serial.available() > 0) {
+    inputByte = Serial.read(); // get incoming byte
+    switch(inputByte){
+      case 'a':
+        digitalWrite(RED_LED,HIGH);
+        Serial.print("LED Rojo encendido\n");
+      break;
+      case 'b':
+        digitalWrite(RED_LED,LOW);
+        Serial.print("LED Rojo apagado");
+      break;
+      case 'c':
+        digitalWrite(GREEN_LED,HIGH);
+        Serial.print("LED Verde encendido");
+      break;
+      case 'd':
+        digitalWrite(GREEN_LED,LOW);
+       Serial.print("LED Verde apagado");
+      break;
+      case 'e':
+        digitalWrite(BLUE_LED,HIGH);
+        Serial.print("LED Azul encendido");
+      break;
+      case 'f':
+        digitalWrite(BLUE_LED,LOW);
+        Serial.print("LED Azul apagado");
+      break;
+      case 'g':
+        digitalWrite(RED_LED,LOW);
+        digitalWrite(GREEN_LED,LOW);
+        digitalWrite(BLUE_LED,LOW);
+        Serial.print("LEDs apagados");
+      break;
+      default:
+        digitalWrite(RED_LED,LOW);
+        digitalWrite(GREEN_LED,LOW);
+        digitalWrite(BLUE_LED,LOW);
+      break;
+    }
+  }
+}
+
+


added accelerometer starter

added accelerometer starter

--- src/basic/basic.ino
+++ src/basic/basic.ino
@@ -4,8 +4,10 @@
 #include "keys.h"
 SoftwareSerial myLoraSerial(7, 8); // RX, TX
 #define RST  2
-static const int RXPin = 4, TXPin = 3;
 static const int buzzerPin = 5;
+#define RXPin 4
+#define TXPin 3
+#define GPSPower 10
 static const uint32_t GPSBaud = 9600;
 // The serial connection to the GPS device
 SoftwareSerial gpsSerial(RXPin, TXPin);
@@ -18,9 +20,27 @@
 unsigned long lastExecutionMillis = 0;
 unsigned long lastSendMillis = 0;
 unsigned long lastBeepMillis = 0;
-
-
-
+#define accelX A0 // X pin connected to Analog 0
+#define accelY A1 // Y pin connected to Analog 1
+#define accelZ A2 // Z pin connected to Analog 2
+
+#define tolerance 20 // Sensitivity of the Alarm
+
+//Accelerometer limits
+int xMin; //Minimum x Value
+int xMax; //Maximum x Value
+int xVal; //Current x Value
+
+int yMin; //Minimum y Value
+int yMax; //Maximum y Value
+int yVal; //Current y Value
+
+int zMin; //Minimum z Value
+int zMax; //Maximum z Value
+int zVal; //Current z Value
+
+
+boolean gpsPowered = false;
 // Setup routine runs once when you press reset
 void setup() {
   pinMode(13, OUTPUT);
@@ -52,18 +72,99 @@
   }

   delay(500);
-  Serial.println("Initializing GPS...");
-  gpsSerial.begin(GPSBaud);
-  Serial.println("Initialized GPS");
+  Serial.println("Calibrating Accelerometer...");
+  calibrateAccel();
+  Serial.println("Calibrated Accelerometer");

   led_off();
   delay(2000);
 }
-
+// Function used to calibrate the Accelerometer
+void calibrateAccel(){
+
+ //initialise x,y,z variables
+ xVal = analogRead(accelX);
+ xMin = xVal;
+ xMax = xVal;
+
+ yVal = analogRead(accelY);
+ yMin = yVal;
+ yMax = yVal;
+
+ zVal = analogRead(accelZ);
+ zMin = zVal;
+ zMax = zVal;
+
+
+ //calibrate the Accelerometer (should take about 0.5 seconds)
+ for (int i=0; i<50; i++){
+ // Calibrate X Values
+ xVal = analogRead(accelX);
+ if(xVal>xMax){
+ xMax=xVal;
+ }else if (xVal < xMin){
+ xMin=xVal;
+ }
+
+ // Calibrate Y Values
+ yVal = analogRead(accelY);
+ if(yVal>yMax){
+ yMax=yVal;
+ }else if (yVal < yMin){
+ yMin=yVal;
+ }
+
+ // Calibrate Z Values
+ zVal = analogRead(accelZ);
+ if(zVal>zMax){
+ zMax=zVal;
+ }else if (zVal < zMin){
+ zMin=zVal;
+ }
+
+ //Delay 10msec between readings
+ delay(10);
+ }
+ printValues(); //Only useful when connected to computer- using serial monitor.
+}
+
+boolean checkMotion(){
+ boolean tempB=false;
+ xVal = analogRead(accelX);
+ yVal = analogRead(accelY);
+ zVal = analogRead(accelZ);
+
+ if(xVal >(xMax+tolerance)||xVal < (xMin-tolerance)){
+ tempB=true;
+ Serial.print("X Failed = ");
+ Serial.println(xVal);
+ }
+
+ if(yVal >(yMax+tolerance)||yVal < (yMin-tolerance)){
+ tempB=true;
+ Serial.print("Y Failed = ");
+ Serial.println(yVal);
+ }
+
+ if(zVal >(zMax+tolerance)||zVal < (zMin-tolerance)){
+ tempB=true;
+ Serial.print("Z Failed = ");
+ Serial.println(zVal);
+ }
+
+ return tempB;
+}
+
 // the loop routine runs over and over again forever:
 void loop() {
   int currentMillis = millis();
-
+  if(!gpsPowered && checkMotion()){
+    powerGps();
+  }
+
+  if(!gpsPowered){
+    return;
+  }
   //if(currentMillis - lastExecutionMillis < 5000){
   //  return;
   //}
@@ -95,7 +196,14 @@
   }
   led_off();
 }
-
+void powerGps() {
+  digitalWrite(GPSPower,1);
+  delay(200);
+  Serial.println("Initializing GPS...");
+  gpsSerial.begin(GPSBaud);
+  Serial.println("Initialized GPS");
+  gpsPowered = true;
+}
 boolean receivedBikeKillSignal() {
   String response = myLora.getRx();
   if(response && response.length() > 0) {
@@ -116,7 +224,7 @@

 void transmit_coords(double float_latitude, double float_longitude){
   Serial.println("Transimitting coords...");
-  uint8_t coords[6]; // 6*8 bits = 48
+  uint8_t coords[7]; // 6*8 bits = 48
   int32_t lat = float_latitude * 10000;
   int32_t lon = float_longitude * 10000;

@@ -128,6 +236,7 @@
   coords[3] = lon;
   coords[4] = lon >> 8;
   coords[5] = lon >> 16;
+  coords[6] = receivedBikeKillSignal();
   myLoraSerial.listen();
   TX_RETURN_TYPE result = myLora.txBytes(coords, sizeof(coords));
   if(result == TX_FAIL)
@@ -147,6 +256,29 @@
 {
   digitalWrite(13, 0);
 }
+
+void printValues(){
+ Serial.print("xMin=");
+ Serial.print(xMin);
+ Serial.print(", xMax=");
+ Serial.print(xMax);
+ Serial.println();
+
+ Serial.print("yMin=");
+ Serial.print(yMin);
+ Serial.print(", yMax=");
+ Serial.print(yMax);
+ Serial.println();
+
+ Serial.print("zMin=");
+ Serial.print(zMin);
+ Serial.print(", zMax=");
+ Serial.print(zMax);
+ Serial.println();
+
+ Serial.println("------------------------");
+}
+

 void displayInfo()
 {


Update custom_color_array.ino

Update custom_color_array.ino

added custom color name examples at bottom of code

--- custom_color_array.ino
+++ custom_color_array.ino
@@ -51,3 +51,23 @@
 }//end_main_loop

+//---------------------------------------------------------------
+/*
+Not used here in this code, but here are examles of how you can
+assign custom color names (using RGB, HSV, web names, or hex)
+which can later be used in your code.
+
+CRGB myColorA (0,128,128);
+CHSV myColorB (160,128,255);
+
+CRGB myColorC = CHSV(42,128,255);
+CRGB myColorD = CRGB::Purple;
+CRGB myColorE = 0xE1A024;
+
+#define myColorF CRGB(128,0,255)
+#define myColorG 0x902C02
+
+Then in your code you can do:
+leds[i] = myColorA;
+
+*/


Add communication module

Add communication module

--- RGB_lamps/RGB_lamps.ino
+++ RGB_lamps/RGB_lamps.ino
@@ -10,6 +10,7 @@
 RGBLamp lamps[4];
 int colors[216][3];
 int dayCols[20][3];
+int cycleFade[4] = {0,0,0,0};

 void setup() {

@@ -26,69 +27,11 @@
   lamps[2].create(8,9,10);
   lamps[3].create(11,12,13);

-  // Sets all lamps to a random color
-  /*for (int lamp = 0; lamp < 4; lamp++) {
-    int col[] = {random(0, 255),random(0, 255),random(0, 255)};
-    lamps[lamp].setColor(col);
-    //lamps[lamp].on();
-  }*/
-
-  // Start Cols
-  int col[8][3];
-
-  // Red
-  col[0][0] = 255;
-  col[0][1] = 0;
-  col[0][2] = 0;
-
-  // Green
-  col[1][0] = 0;
-  col[1][1] = 255;
-  col[1][2] = 0;
-
-  // Blue
-  col[2][0] = 0;
-  col[2][1] = 0;
-  col[2][2] = 255;
-
-  // Yellow
-  col[3][0] = 255;
-  col[3][1] = 255;
-  col[3][2] = 0;
-
-  // White
-  col[4][0] = 255;
-  col[4][1] = 255;
-  col[4][2] = 255;
-
-  // Orange
-  col[5][0] = 255;
-  col[5][1] = 69;
-  col[5][2] = 0;
-
-  // Magenta
-  col[6][0] = 255;
-  col[6][1] = 0;
-  col[6][2] = 255;
-
-  // Cyan
-  col[7][0] = 0;
-  col[7][1] = 255;
-  col[7][2] = 255;
-
-  // Olive
-  col[8][0] = 128;
-  col[8][1] = 128;
-  col[8][2] = 0;
-
-  for(int i=0; i < 9;i++) {
-    for (int lamp = 0; lamp < 4; lamp++) {
-      lamps[lamp].setColor(col[i]);
-    }
-    delay(200);
-  }
-
   setColors();
+
+  for (int lamp = 0; lamp < 4; lamp++) {
+    lamps[lamp].fade(3000, dayCols[10]);
+  }
 }

 // This will carry out the fades and so on. These must be run each loop! (!!!)
@@ -101,11 +44,80 @@
     }
   }

-  if(finish) {
+  // Old fade mechanism
+  /*if(finish) {
     // Sets all lamps to fade to a random color
     for (int lamp = 0; lamp < 4; lamp++) {
       lamps[lamp].fade(10000, colors[random(0, 215)]);
     }
+  }*/
+}
+
+void controller() {
+  // Read controll data from the serial port to decide what to do with the lamps
+  if(Serial.available() > 0) {
+    delay(100);
+
+    // Setup variables for control
+    unsigned char ctrl = Serial.read();
+    int selected_lamp = 5; // As 4 should be the higest needed value.
+    int r,g,b;
+
+    // Lamp select
+    selected_lamp = (ctrl & 224) >> 5;
+
+    // Mode select
+    ctrl = ctrl & 31; // Remove the selector bits
+
+    if (ctrl == 0) {
+      // Set color for lamp(s)
+      Serial.println("Set Color");
+      char cols[3];
+      Serial.readBytes(cols,3);
+
+      int col[] = {cols[0],cols[1],cols[2]};
+      for(int i = 0; i < 3; i++) {
+        col[i] = col[i] < 0 ? col[i] + 256 : col[i];
+      }
+      if (selected_lamp < 4) {
+        lamps[selected_lamp].setColor(col);
+      }
+      else {
+        for(int lamp = 0; lamp < 4; lamp++) {
+          lamps[lamp].setColor(col);
+        }
+      }
+    }
+    else if (ctrl == 1) {
+      //Fade to color for lamp(s)
+      char cols[4];
+      Serial.readBytes(cols,4);
+      int col[] = {cols[0],cols[1],cols[2]};
+      for(int i = 0; i < 3; i++) {
+        col[i] = col[i] < 0 ? col[i] + 256 : col[i];
+      }
+      Serial.print("Fade Color:");
+      Serial.print(col[0]);
+      Serial.print("-");
+      Serial.print(col[1]);
+      Serial.print("-");
+      Serial.println(col[2]);
+      int fade_time = cols[3];
+
+      if (selected_lamp < 4) {
+        lamps[selected_lamp].fade(fade_time*100,col);
+      }
+      else {
+        for(int lamp = 0; lamp < 4; lamp++) {
+          lamps[lamp].fade(fade_time*100,col);
+        }
+      }
+    }
+    else {
+      Serial.println("Ooops");
+
+    }
+
   }
 }

@@ -231,6 +243,7 @@
 void loop() {

   // This is where the fun begins
+  controller();
   work();

 }


Fix watchdog timing

Fix watchdog timing

--- device.ino
+++ device.ino
@@ -3,6 +3,14 @@
  FloatHub Arduino Code
  (c) 2011-2014 Modiot Labs
  (begun June 6, 2011)
+
+
+  March 26, 2014
+
+  Realized that watchdog_timestamps have to be set to current millis()
+  values, not stale variables that may have been set some time ago in the
+  WiFi code where some calls are blocking and a lot of time may have
+  elapsed.

   April 4, 2014
@@ -88,7 +96,7 @@
 //#define GPS_DEBUG_ON
 //#define PUMP_DEBUG_ON
 //#define EXECUTION_PATH_DEBUG_ON
-#define NMEA_DEBUG_ON
+//#define NMEA_DEBUG_ON
 //#define DEBUG_MEMORY_ON
 //#define STRESS_MEMORY_ON
 //#define BYPASS_AES_ON
@@ -214,13 +222,13 @@
 unsigned long idle_reporting_interval = 600000;   	//  When idle, report data every 10 minutes
 unsigned long console_reporting_interval = 5000;  	//  Report to USB console every 5 seconds
 unsigned long console_interval = 250;             	//  Check console for input every 250 milliseconds
-unsigned long gprs_or_wifi_watchdog_interval = 90000;  	//  Reboot the GPRS module after 90 seconds of no progress
+unsigned long gprs_or_wifi_watchdog_interval = 120000;  //  Reboot the GPRS/wifi module after 2 minutes of no connection
 unsigned long wifi_scan_interval = 30000;         	//  How often to look for wifi networks
 unsigned long wifi_read_interval = 8000;           	//  Do wifi i/o communications every 8 seconds
 unsigned long led_update_interval = 200;          	//  Update the LED's every 200 miliseconds
 unsigned long nmea_update_interval = 100;         	//  Update NMEA in serial line every 1/10 of a second
+unsigned long hardware_watchdog_interval = 120000; 	//  Do a hardware reset if we don't pat the dog every 2 minutes
 boolean green_led_state = false;         	  	//  For cycling on and off
-unsigned long hardware_watchdog_interval = 120000; 	//  Do a hardware reset if we don't pat the dog every 2 minutes

 unsigned long sensor_previous_timestamp = 0;
 unsigned long gps_previous_timestamp = 0;
@@ -460,7 +468,7 @@
 void wifi_setup()
 {
   #ifdef WIFI_DEBUG_ON
-  debug_info(F("Wifi init"));
+  debug_info(F("wifi init"));
   #endif
   if (!cc3000.begin())
   {
@@ -469,9 +477,10 @@
     #endif
   }
   else
-  {
+  {
     cc3000.reboot(NULL);
     cc3000.setPrinter(NULL);
+    set_wireless_timeouts();
   }
 }
 #endif
@@ -970,7 +979,7 @@

   //
-  //  Handle EEPROM logic for persistant settings (if the first 6 bytes of
+  //  Handle EEPROM logic for persistant settings (if the first 5 bytes of
   //  EEPROM memory are not all set to 42, then this is a completely
   //  unitialized device)
   //
@@ -2618,16 +2627,37 @@

 #ifdef WIFI_NOT_CELL

+void set_wireless_timeouts()
+{
+  unsigned long aucDHCP = 14400;
+  unsigned long aucARP = 3600;
+  unsigned long aucKeepalive = 10;
+  unsigned long aucInactivity = 30;
+  if (netapp_timeout_values(&aucDHCP, &aucARP, &aucKeepalive, &aucInactivity) != 0)
+  {
+    #ifdef WIFI_DEBUG_ON
+    debug_info(F("wifi FAIL set timeouts"));
+    #endif
+  }
+  else
+  {
+    #ifdef WIFI_DEBUG_ON
+    debug_info(F("wifi set timeouts"));
+    #endif
+  }
+}
+
 void nuke_wireless(void)
 {
-  unsigned long current_timestamp = millis();
   #ifdef WIFI_DEBUG_ON
-  debug_info(F("*** Resetting Wifi ***"));
+  debug_info(F("*** Resetting wifi ***"));
   #endif
   cc3000.disconnect();
   cc3000.reboot(NULL);
+  set_wireless_timeouts();
   wifi_on_home_network = false;
   wifi_communication_state = idle;
+  unsigned long current_timestamp = millis();
   gprs_or_wifi_watchdog_timestamp = current_timestamp;
   return;
 }
@@ -2641,13 +2671,21 @@
   uint32_t ip = 0;
   if(cc3000.getHostByName(temp_string_a, &ip) && ip > 0)
   {
+
+    #ifdef WIFI_DEBUG_ON
+    unsigned long before = now();
+    debug_info(F("wifi connect ..."));
+    #endif
     cc3000_client = cc3000.connectTCP(ip, float_hub_server_port);
+    #ifdef WIFI_DEBUG_ON
+    debug_info("took ", (int) (now()- before));
+    #endif
     if(cc3000_client.connected())
     {
       return true;
     }
     #ifdef WIFI_DEBUG_ON
-    debug_info(F("Wifi No comm"));
+    debug_info(F("wifi No comm"));
     #endif
     cc3000_client.close();
     return false;
@@ -2655,13 +2693,13 @@
   if(ip < 1)
   {
     #ifdef WIFI_DEBUG_ON
-    debug_info(F("Wifi DNS failure"));
+    debug_info(F("wifi DNS failure"));
     #endif
   }
   else
   {
     #ifdef WIFI_DEBUG_ON
-    debug_info(F("Wifi DNS lookup failure"));
+    debug_info(F("wifi DNS lookup failure"));
     #endif
   }
   return false;
@@ -2697,6 +2735,28 @@
 }

+/*
+bool displayConnectionDetails(void)
+{
+  uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;
+
+  if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
+  {
+    Serial.println(F("Unable to retrieve the IP Address!\r\n"));
+    return false;
+  }
+  else
+  {
+    Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
+    Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
+    Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
+    Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
+    Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
+    Serial.println();
+    return true;
+  }
+}
+*/

 void wifi_read()
 {
@@ -2704,6 +2764,9 @@
   {
     return;
   }
+
+  //displayConnectionDetails();
+
   unsigned long current_timestamp = millis();
   if(current_timestamp - gprs_or_wifi_watchdog_timestamp > gprs_or_wifi_watchdog_interval)
   {
@@ -2715,7 +2778,7 @@
   {
     wifi_communication_state = idle;
     #ifdef WIFI_DEBUG_ON
-    debug_info(F("Wifi no conn yet"));
+    debug_info(F("wifi no conn yet"));
     #endif
     return;
   }
@@ -2723,7 +2786,7 @@
   if(!cc3000.checkDHCP())
   {
     #ifdef WIFI_DEBUG_ON
-    debug_info(F("Wifi no IP yet"));
+    debug_info(F("wifi no IP yet"));
     #endif
     return;
   }
@@ -2737,8 +2800,9 @@
         if(push_latest_message_out_socket())
         {
           #ifdef WIFI_DEBUG_ON
-          debug_info(F("Wifi Sent FHx"));
+          debug_info(F("wifi Sent FHx"));
           #endif
+          current_timestamp = millis();
           gprs_or_wifi_watchdog_timestamp = current_timestamp;
           wifi_communication_state = waiting_for_response;
           wifi_read_buffer = "";
@@ -2746,7 +2810,7 @@
         #ifdef WIFI_DEBUG_ON
         else
         {
-          debug_info(F("Wifi sock prob"));
+          debug_info(F("wifi sock prob"));
         }
         #endif
       }
@@ -2771,6 +2835,7 @@
     if(wifi_read_buffer.indexOf("$FHR$ OK") > -1)
     {
       gprs_or_wifi_watchdog_counter = 0;
+      current_timestamp = millis();
       gprs_or_wifi_watchdog_timestamp = current_timestamp;
       pop_off_message_queue();
       if(latest_message_to_send.length() > 0)
@@ -2778,20 +2843,25 @@
         if(push_latest_message_out_socket())
         {
           #ifdef WIFI_DEBUG_ON
-          debug_info(F("Wifi more FHx"));
+          debug_info(F("wifi more FHx"));
           #endif
+          current_timestamp = millis();
+          gprs_or_wifi_watchdog_timestamp = current_timestamp;
           wifi_communication_state = waiting_for_response;
           wifi_read_buffer = "";
         }
         else
         {
           #ifdef WIFI_DEBUG_ON
-          debug_info(F("Wifi Hangup"));
+          debug_info(F("wifi Hangup"));
           #endif
         }
       }
       else
       {
+        #ifdef WIFI_DEBUG_ON
+        debug_info(F("wifi No Msgs"));
+        #endif
         wifi_read_buffer = "";
         cc3000_client.close();
         wifi_communication_state = idle;
@@ -2826,14 +2896,15 @@
   //if(cc3000.connectToAP(temp_string_a, temp_string_b, encryption_type))
   {
     #ifdef WIFI_DEBUG_ON
-    debug_info(F("WiFi home net "), encryption_type);
+    debug_info(F("wifi home net "), encryption_type);
     #endif
     wifi_on_home_network = true;
+    //set_wireless_timeouts();
   }
   else
   {
     #ifdef WIFI_DEBUG_ON
-    debug_info(F("Failed WiFi home"));
+    debug_info(F("Failed wifi home"));
     #endif
   }
 }
@@ -2853,7 +2924,7 @@
   //

   #ifdef WIFI_DEBUG_ON
-  debug_info(F("=== Wifi scan start ==="));
+  debug_info(F("=== wifi scan start ==="));
   #endif

   wifi_on_home_network = false;
@@ -2912,7 +2983,7 @@
   cc3000.stopSSIDscan();

   #ifdef WIFI_DEBUG_ON
-  debug_info(F("=== Wifi scan end ==="));
+  debug_info(F("=== wifi scan end ==="));
   #endif

@@ -2941,8 +3012,9 @@
     //if(cc3000.connectToAP(temp_string_a, temp_string_a, WLAN_SEC_UNSEC))
     {
       #ifdef WIFI_DEBUG_ON
-      debug_info("Wifi open connect: " + open_network_name);
+      debug_info("wifi open connect: " + open_network_name);
       #endif
+      //set_wireless_timeouts();
     }
     else
     {
@@ -3140,7 +3212,7 @@
   }

   //
-  //  Check the watchdog timer and give up all hope if it's
+  //  Check the watchdog timer and give up all hope if it's been too long
   //

   if(current_timestamp - gprs_or_wifi_watchdog_timestamp > gprs_or_wifi_watchdog_interval)


Start off uninitialized

Start off uninitialized

--- arduino/blinkytape_orb.ino
+++ arduino/blinkytape_orb.ino
@@ -18,10 +18,11 @@

 // state
 CRGB leds[NUM_LEDS];
-uint8_t hue = HUE_RED;
-uint8_t val = PULSE_MAX_VAL;
-bool pulse = true;
-long pulse_duration = PULSE_DURATION_FAST;
+bool initialized;
+uint8_t hue;
+uint8_t val;
+bool pulse;
+long pulse_duration;

@@ -53,7 +54,11 @@

   for (uint8_t v = val; v != new_val; v += incr) {
     for (int i = 0; i < NUM_LEDS; i++) {
-      leds[i] = CHSV(hue, 255, v);
+      if (initialized) {
+        leds[i] = CHSV(hue, 255, v);
+      } else {
+        leds[i] = CRGB(v, v, v);
+      }
     }
     FastLED.show();

@@ -74,9 +79,15 @@
   FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
   FastLED.setCorrection(LED_CORRECTION);

+  initialized = false;
+  val = PULSE_MAX_VAL;
+  pulse = true;
+  pulse_duration = PULSE_DURATION_MED;
+
   for (int i = 0; i < NUM_LEDS; i++) {
-    leds[i] = CHSV(hue, 255, val);
+    leds[i] = CRGB(val, val, val);
   }
+  FastLED.show();
 }

 void loop() {
@@ -130,6 +141,8 @@
           break;
       }

+      initialized = true;
+
       fade(PULSE_MIN_VAL, CHANGE_DURATION / 2);
     }
   }


Added license to source file

Added license to source file

--- leave_tips/leave_tips.ino
+++ leave_tips/leave_tips.ino
@@ -1,7 +1,32 @@
+/*
+  The MIT License (MIT)
+
+  Copyright (c) 2015 Peter Kropf
+
+  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.
+*/
+
 /*
   leave_tips
   turns LEDs on and off following a randomly timed pattern.
  */
+

 const int mLed = 13;       // status led to monitor state changes
 unsigned long mTimer = 0;  // time till turning off status led


fix(?) servo ud

fix(?) servo ud

--- servo/servo.ino
+++ servo/servo.ino
@@ -6,7 +6,7 @@

 bool servo_ud_flag = 0;
 int servo_ud_max = 90, servo_ud_min = 10;
-
+int servo_ud_now = 90;

 int servo_ud_fun(int servo_ud_now)
 {
@@ -44,7 +44,6 @@
 void loop()
 {

-    int servo_ud_now = 90;
     //*以角度控制
     for(int i = 10;i <= 170;i++)
     {


Use correct #include format

Use correct #include format

Even though either  format works I think the angle brackets are more
correct as the double quotes are used for including files in the same
folder.

--- examples/EEPROMallocationExample/EEPROMallocationExample.ino
+++ examples/EEPROMallocationExample/EEPROMallocationExample.ino
@@ -1,5 +1,5 @@
 // Demonstrates usage of the EEPROMallocation library
-#include "EEPROMallocation.h"
+#include <EEPROMallocation.h>
 #include <EEPROM.h>

 int address1;


Display 1 decimal of float

Display 1 decimal of float

--- seven-segment-float/src/seven-segment-float.ino
+++ seven-segment-float/src/seven-segment-float.ino
@@ -58,8 +58,6 @@

 byte displayNum[] = {off, off, off, off};  //array for display numbers from msb to lsb

-bool negative = false;
-
 const long refreshInterval = 10; //refresh delay in microseconds
 long previousRefresh = 0; //previous refresh time
 int refreshLoop = 0;  //counter for refreshing loop
@@ -95,8 +93,9 @@
     displayNumber();
   }

-  //testCaseAllNum();
-  splitNumber(1000);
+  testCaseAllNum();
+  //splitNumber(-99.99999);
+
 }

 void clearLEDs() {
@@ -117,84 +116,6 @@
 void displayNumber() {
   //turn on the LEDs accoring to the number stored in array num on the refresh cycle
   updateShiftRegister(displayNum[refreshLoop]);
-}
-
-void splitNumber(double n) {
-  //takes the input n and puts into the array num, split into 4 digits from lsb to msb
-  double fractional;
-  double integral;
-  int digitsLeft = 0;
-  int index = 0;
-
-  int splitLeft[4]={-1,-1,-1,-1};
-  int splitRight[4]={0,0,0,0};
-
-  //clear previous values of the num array
-  for (int i=0; i<4; i++)
-  {
-    displayNum[i] = off;
-    negative = false;
-  }
-
-  if (n < 0) {
-    n = abs(n);
-    negative = true;
-  }
-
-  fractional = modf(n, &integral);
-  int whole = int(integral);
-  digitsLeft = numToArray(whole, splitLeft);
-  int decimal = int(fractional * (pow(10,digitsLeft)));
-  numToArray(decimal, splitRight);
-
-  for (int i=0; i<digitsLeft; i++) {
-      displayNum[i] = numbers[splitRight[i]];
-      index++;
-  }
-
-  for (int j=0; j<4; j++) {
-    if (splitLeft[j]!=-1)
-      displayNum[j+index] = numbers[splitLeft[j]];
-  }
-
-  if (digitsLeft > 0)
-    displayNum[digitsLeft]++;
-}
-
-int numToArray(int x, int store[]) {
-  int left = 0;
-
-  // if x is 0 to 9
-  if (x < 10) {
-    store[0] = x;
-    left = 3;
-  }
-  //else if x is 10-99
-  else if (x < 100) {
-    store[1] = x / 10;
-    store[0] = x % 10;
-    left = 2;
-  }
-  //else if x is 100-999
-  else if (x < 1000) {
-    store[2] = x / 100;
-    x = x % 100;
-    store[1] = x / 10;
-    store[0] = x % 10;
-    left = 1;
-  }
-  //else if x is 1000-9999
-  else if (x < 10000) {
-    store[3] = x / 1000;
-    x = x % 1000;
-    store[2] = x / 100;
-    x = x % 100;
-    store[1] = x / 10;
-    store[0] = x % 10;
-    left = 0;
-  }
-
-  return left;
 }

 void updateShiftRegister(byte leds) {
@@ -204,12 +125,78 @@
    digitalWrite(latchPin, HIGH);
 }

+bool splitNumber(double n) {
+  //takes the input n and puts into the array num, split into 4 digits from lsb to msb
+  double fractional;
+  double integral;
+  int i;
+  bool negative = false;
+
+  int store[]={-1,-1,-1,-1};
+
+  //clear previous values of the num array
+  for (i=0; i<4; i++)
+    displayNum[i] = off;
+
+  if (n < 0.0) {
+    n = abs(n);
+    negative = true;
+  }
+
+  fractional = modf(n, &integral);
+  fractional = round(fractional*10);
+  int decimal = int(fractional);
+  int whole = int(integral);
+
+  if (decimal >= 10) {
+    decimal = 0;
+    whole++;
+  }
+
+  if (negative) {
+    if (whole >= 100)
+      return false;
+    displayNum[3] = minus;
+  }
+  else {
+    if (whole >= 1000)
+      return false;
+  }
+
+  displayNum[0] = numbers[decimal];
+
+  // if whole is 0 to 9
+  if (whole < 10) {
+    store[1] = whole;
+  }
+  //else if whole is 10-99
+  else if (whole < 100) {
+    store[2] = whole / 10;
+    store[1] = whole % 10;
+  }
+  //else if whole is 100-999
+  else if (whole < 1000) {
+    store[3] = whole / 100;
+    whole = whole % 100;
+    store[2] = whole / 10;
+    store[1] = whole % 10;
+  }
+
+  for (i=1; i<4; i++) {
+    if (store[i]!=-1)
+      displayNum[i] = numbers[store[i]];
+  }
+
+  displayNum[1]++;
+
+  return true;
+}

 //global variables for the test function
-const long testInterval = 500; //counter delay in milliseconds
+const long testInterval = 50; //counter delay in milliseconds

 long previousTestTime = 0; //previous count time
-double testLoop = 0; //counter for counting loop
+double testLoop = -100; //counter for counting loop

 void testCaseAllNum() {
   //test case, a loop timer that runs through each integer from 0 to 9999
@@ -220,10 +207,10 @@

     splitNumber(testLoop);

-    testLoop+=0.05;
+    testLoop+=0.1;

     //reset loop to 0 at end of displayable integers
-    if (testLoop > 9999)
-      testLoop = 0;
-  }
-}
+    if (testLoop > 1000)
+      testLoop = -100;
+  }
+}


blink temperature reading if warning has been issued

--- short-circuit-limiter/short-circuit-limiter.ino
+++ short-circuit-limiter/short-circuit-limiter.ino
@@ -258,8 +258,7 @@
       u8g2.clearBuffer();
       u8g2.setFont(u8g2_font_7x13_tr);

-
-      switch(nextState){
+      switch(currentState){
         case STATE_WINDOW_BEFORE:
           u8g2.drawStr(0,10, "Limiter: In Effect");
           break;
@@ -277,6 +276,8 @@
           break;
        }

+       bool tempWarning = temperatureWarningCheck(temperature);
+
        char valueBuff[10];
        char fullBuff[30];

@@ -284,20 +285,24 @@
        sprintf(fullBuff,"Current  : %sA", valueBuff);
        u8g2.drawStr(0,33, fullBuff);

-       dtostrf(temperature, 3, 0, valueBuff);
-       sprintf(fullBuff,"Curr Temp: %sC", valueBuff);
-       u8g2.drawStr(0,47, fullBuff);
+       static bool blinkTempOn = false;
+       blinkTempOn = !blinkTempOn;
+
+       //Start blinking when temperature is warning range
+       if(!tempWarning || blinkTempOn){
+          dtostrf(temperature, 3, 0, valueBuff);
+          sprintf(fullBuff,"Curr Temp: %sC", valueBuff);
+          u8g2.drawStr(0,47, fullBuff);
+       }

        u8g2.setFont(u8g2_font_5x8_tr);
        dtostrf(CURRENT_ENABLE_THRESHOLD, 4, 2, valueBuff);
        sprintf(fullBuff,"Enable Current: %sA", valueBuff);
        u8g2.drawStr(0,63, fullBuff);

-
-
        u8g2.sendBuffer();

-       temperatureWarningCheck(temperature);
+
     }
   }

@@ -542,11 +547,12 @@

 }

-
-void temperatureWarningCheck(float temperature){
+//Returns true if temperature threshold has been reached
+bool temperatureWarningCheck(float temperature){

   if(temperature >= TEMP_MAX){
     nextState = STATE_TEMP_MAX;
+    return true;

   } else if(temperature >= TEMP_WARN){
     static unsigned long lastTempAlert = 0;
@@ -557,7 +563,11 @@
       lastTempAlert = currentTime;
       shortBeepXTimesNoDelay(5);
     }
-
-  }
-}
-
+
+    return true;
+
+  }
+
+  return false;
+}
+


Update RemoteLEDSender.ino

Update RemoteLEDSender.ino

--- examples/RemoteLEDSender/RemoteLEDSender.ino
+++ examples/RemoteLEDSender/RemoteLEDSender.ino
@@ -1,6 +1,9 @@
 #include <ICSC.h>

 ICSC icsc(Serial, 1);
+
+//comment out the line above and uncomment the line below to use this with ChainDuinos
+//ICSC icsc(Serial, 1 ,2); // last argument specifies DE pin on ChainDuino

 void setup()
 {


Revert "Edit SD Server example to use the new Write(Stream) method"

This reverts commit 4ae8a6d631d532409dde5ea35af03bccbb62974f.

--- hardware/esp8266com/esp8266/libraries/ESP8266WebServer/examples/SDWebServer/SDWebServer.ino
+++ hardware/esp8266com/esp8266/libraries/ESP8266WebServer/examples/SDWebServer/SDWebServer.ino
@@ -111,10 +111,23 @@
     dataType = 0;
     path = 0;

-    if(client.write(dataFile) != dataFile.size()){
+    uint8_t obuf[WWW_BUF_SIZE];
+
+    while (dataFile.available() > WWW_BUF_SIZE){
+      dataFile.read(obuf, WWW_BUF_SIZE);
+      if(client.write(obuf, WWW_BUF_SIZE) != WWW_BUF_SIZE){
+        DBG_OUTPUT_PORT.println("Sent less data than expected!");
+        dataFile.close();
+        return true;
+      }
+    }
+    uint16_t leftLen = dataFile.available();
+    dataFile.read(obuf, leftLen);
+    if(client.write(obuf, leftLen) != leftLen){
       DBG_OUTPUT_PORT.println("Sent less data than expected!");
+      dataFile.close();
+      return true;
     }
-
     dataFile.close();
     client.stop();
     return true;


Implement AP reconnection.

Implement AP reconnection.

This should deal with the losing the wireless connection.

--- water_heater_monitor/water_heater_monitor.ino
+++ water_heater_monitor/water_heater_monitor.ino
@@ -37,15 +37,8 @@
     Serial.println(F("unable to initialise the CC3000!"));
     while(1);
   }
-  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
-    Serial.println(F("wireless connection failed!"));
-    while(1);
-  }
-  Serial.println(F("wireless connection successful."));

-  while (!cc3000.checkDHCP()) {
-    delay(100);
-  }
+  reconnectToAP();

   uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;
   if (!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv)) {
@@ -111,6 +104,21 @@
 }

+void reconnectToAP () {
+  while (!cc3000.checkConnected()) {
+    if (cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
+      Serial.println(F("AP connection successful."));
+      while (!cc3000.checkDHCP()) {
+        delay(100);
+      }
+    } else {
+      Serial.println(F("AP connection failure... attempting to reconnect..."));
+      delay(30000);
+    }
+  }
+}
+
+
 void updateWeb() {
   Serial.println(F("Sending data..."));

@@ -171,5 +179,9 @@
     Serial.println(F("Done."));
   } else {
     Serial.println(F("Web server connection failed."));
+    if (!cc3000.checkConnected()) {
+      Serial.println(F("Wifi appears down, attempting to reconnect..."));
+      reconnectToAP();
+    }
   }
 }


Fixing small typo

Fixing small typo

--- examples/OPL3Duo/SerialPassthrough/SerialPassthrough.ino
+++ examples/OPL3Duo/SerialPassthrough/SerialPassthrough.ino
@@ -53,7 +53,7 @@
 			byte bank = (x1>>2);
 			byte reg = ((x1<<6)&0x0c0)|((x2>>1)&0x3f);
 			byte data = ((x2<<7)&0x80)|(x3&0x7f);
-			opl3.write(bank, reg, data);
+			opl3Duo.write(bank, reg, data);
 		}
 	}
 #endif


head switch

head switch

--- sketchbook/printer/printer.ino
+++ sketchbook/printer/printer.ino
@@ -1,4 +1,5 @@
 #include <Motor.h>
+#include <Switch.h>

 int posX = 0;
 int posY = 0;
@@ -9,6 +10,7 @@
 Motor motorX(2, 3, 4, 5);
 Motor motorY(6, 7, 8, 9);
 Motor motorZ(10, 11, 12, 13);
+Switch head(14); // change this

 void setup() {
     Serial.begin(9600);
@@ -128,8 +130,10 @@
                 cmdMotor(posZ, motorZ);
                 break;
             case '+': // head on
+                head.on();
+                break;
             case '-': // head off
-                Serial.write("err not implemented\n");
+                head.off();
                 break;
             case '\r':
             case '\n':


spelling

spelling

--- code/firmware/firmware.ino
+++ code/firmware/firmware.ino
@@ -122,7 +122,7 @@
   calOtherReferenceVoltage = readSensorValueFromEEPROM(11);
   calOtherReferenceCurrent = readSensorValueFromEEPROM(13);

-  // check wether this is the first run
+  // check whether this is the first run
   if (isFirstRun != isFirstRunDef) {
     isFirstRun = isFirstRunDef;
     isStreamingSensorData = isStreamingSensorDataDef;


NemoWeightAvg

NemoWeightAvg

--- _04-mqtt-lcd-dust-sensor/_04-mqtt-lcd-dust-sensor-esp-12/_04-mqtt-lcd-dust-sensor-esp-12.ino
+++ _04-mqtt-lcd-dust-sensor/_04-mqtt-lcd-dust-sensor-esp-12/_04-mqtt-lcd-dust-sensor-esp-12.ino
@@ -209,7 +209,7 @@
   }

   if ( receivedtopic == "esp8266/arduino/s06" ) {
-    NW  = root["NemoWeight"];
+    NW  = root["NemoWeightAvg"];
   }

   if ( receivedtopic == "raspberrypi/doorpir" )


30s MQTT retry interval, address WiFi dropouts while MQTT disconnected

--- Arduino_Sketch/HASwitchPlate/HASwitchPlate.ino
+++ Arduino_Sketch/HASwitchPlate/HASwitchPlate.ino
@@ -419,18 +419,18 @@
         debugPrintln(String(F("MQTT connection attempt ")) + String(mqttReconnectCount) + String(F(" failed with rc ")) + String(mqttClient.returnCode()) + String(F(".  Restarting device.")));
         espReset();
       }
-      debugPrintln(String(F("MQTT connection attempt ")) + String(mqttReconnectCount) + String(F(" failed with rc ")) + String(mqttClient.returnCode()) + String(F(".  Trying again in 10 seconds.")));
-      nextionSetAttr("p[0].b[1].txt", "\"WiFi Connected:\\r" + WiFi.localIP().toString() + "\\rMQTT Connect to" + String(mqttServer) + "\\rFAILED rc=" + String(mqttClient.returnCode()) + "\\rRetry in 10 sec\"");
+      debugPrintln(String(F("MQTT connection attempt ")) + String(mqttReconnectCount) + String(F(" failed with rc ")) + String(mqttClient.returnCode()) + String(F(".  Trying again in 30 seconds.")));
+      nextionSetAttr("p[0].b[1].txt", "\"WiFi Connected:\\r" + WiFi.localIP().toString() + "\\rMQTT Connect to" + String(mqttServer) + "\\rFAILED rc=" + String(mqttClient.returnCode()) + "\\rRetry in 30 sec\"");
       unsigned long mqttReconnectTimer = millis(); // record current time for our timeout
-      while ((millis() - mqttReconnectTimer) < 10000)
-      { // Handle HTTP and OTA while we're waiting 10sec for MQTT to reconnect
-        yield();
+      while ((millis() - mqttReconnectTimer) < 30000)
+      { // Handle HTTP and OTA while we're waiting 30sec for MQTT to reconnect
         if (nextionHandleInput())
         { // Process user input from HMI
           nextionProcessInput();
         }
         webServer.handleClient();
         ArduinoOTA.handle();
+        delay(10);
       }
     }
   }
@@ -2000,14 +2000,7 @@
     httpMessage += FPSTR(HTTP_END);
     webServer.send(200, "text/html", httpMessage);

-    WiFiUDP::stopAll(); // Keep mDNS responder and MQTT traffic from breaking things
-    if (mqttClient.connected())
-    {
-      debugPrintln(F("LCD OTA: LCD firmware upload starting, closing MQTT connection."));
-      mqttClient.publish(mqttStatusTopic, "OFF");
-      mqttClient.publish(mqttSensorTopic, "{\"status\": \"unavailable\"}");
-      mqttClient.disconnect();
-    }
+    WiFiUDP::stopAll(); // Keep mDNS responder from breaking things

     debugPrintln(String(F("LCD OTA: Attempting firmware upload")));
     debugPrintln(String(F("LCD OTA: upload.filename: ")) + String(upload.filename));
@@ -2029,7 +2022,7 @@

     if (nextionOtaResponse())
     {
-      debugPrintln(F("LCD OTA: LCD upload command accepted."));
+      debugPrintln(F("LCD OTA: LCD upload command accepted"));
     }
     else
     {
@@ -2037,7 +2030,24 @@
       espReset();
     }
   }
-  else if (upload.status == UPLOAD_FILE_WRITE)
+  else if (upload.status == UPLOAD_FILE_END)
+  {
+    if (lcdOtaTransferred >= tftFileSize)
+    {
+      if (nextionOtaResponse())
+      {
+        debugPrintln(String(F("LCD OTA: Success, wrote ")) + String(lcdOtaTransferred) + " of " + String(tftFileSize) + " bytes.");
+        delay(5000); // extra delay while the LCD does its thing
+        espReset();
+      }
+      else
+      {
+        debugPrintln(F("LCD OTA: Failure"));
+        espReset();
+      }
+    }
+  }
+  else //if (upload.status == UPLOAD_FILE_WRITE)
   {
     static int lcdOtaChunkCounter = 0;
     static uint16_t lcdOtaPartNum = 0;
@@ -2092,7 +2102,7 @@
       if (nextionOtaResponse())
       {
         debugPrintln(String(F("LCD OTA: Success, wrote ")) + String(lcdOtaTransferred) + " of " + String(tftFileSize) + " bytes.");
-        // delay(5000); // extra delay while the LCD does its thing
+        delay(5000); // extra delay while the LCD does its thing
         espReset();
       }
       else
@@ -2102,36 +2112,7 @@
       }
     }
   }
-  else if (upload.status == UPLOAD_FILE_END)
-  {
-    if (lcdOtaTransferred >= tftFileSize)
-    {
-      if (nextionOtaResponse())
-      {
-        debugPrintln(String(F("LCD OTA: Success, wrote ")) + String(lcdOtaTransferred) + " of " + String(tftFileSize) + " bytes.");
-        // delay(5000); // extra delay while the LCD does its thing
-        espReset();
-      }
-      else
-      {
-        debugPrintln(F("LCD OTA: Failure"));
-        // delay(5000); // delay for user to read output
-        espReset();
-      }
-    }
-  }
-  else if (upload.status == UPLOAD_FILE_ABORTED)
-  {
-    debugPrintln(F("LCD OTA: ERROR: upload.status returned: UPLOAD_FILE_ABORTED"));
-    // delay(5000); // delay for user to read output
-    espReset();
-  }
-  else
-  {
-    debugPrintln(String(F("LCD OTA: upload.status returned: ")) + String(upload.status));
-    // delay(5000); // delay for user to read output
-    espReset();
-  }
+
 }

 ////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -2385,14 +2366,13 @@
 void debugPrintln(String debugText)
 { // Debug output line of text to our debug targets
   String debugTimeText = "[+" + String(float(millis()) / 1000, 3) + "s] " + debugText;
+  Serial.println(debugTimeText);
   if (debugSerialEnabled)
   {
     SoftwareSerial debugSerial = SoftwareSerial(17, 1); // 17==nc for RX, 1==TX pin
     debugSerial.begin(115200);
     debugSerial.println(debugTimeText);
     debugSerial.flush();
-    Serial.println(debugTimeText);
-    Serial.flush();
   }
   if (debugTelnetEnabled)
   {
@@ -2411,15 +2391,13 @@
   // happens.  Far better to put everything into a line and send it all out in one packet using
   // debugPrintln.
   if (debugSerialEnabled)
+  Serial.print(debugText);
   {
     SoftwareSerial debugSerial = SoftwareSerial(17, 1); // 17==nc for RX, 1==TX pin
     debugSerial.begin(115200);
     debugSerial.print(debugText);
     debugSerial.flush();
-    Serial.print(debugText);
-    Serial.flush();
-  }
-
+  }
   if (debugTelnetEnabled)
   {
     if (telnetClient.connected())


Add compile time check of board; this example sketch is Arduino Mega only.

--- examples/Sandbox/CosaMegaUARTs/CosaMegaUARTs.ino
+++ examples/Sandbox/CosaMegaUARTs/CosaMegaUARTs.ino
@@ -30,6 +30,10 @@
  * This file is part of the Arduino Che Cosa project.
  */

+#include "Cosa/Board.hh"
+#if !defined(__ARDUINO_MEGA__)
+#error CosaMegaUARTs: board not supported.
+#endif
 #include "Cosa/Trace.hh"
 #include "Cosa/IOBuffer.hh"
 #include "Cosa/IOStream/Driver/UART.hh"


Fixed the comment at the top of the main file for now

--- Arduboy-box-dude.ino
+++ Arduboy-box-dude.ino
@@ -1,13 +1,7 @@
- /*
-  Breakout
- Copyright (C) 2011 Sebastian Goscik
- All rights reserved.
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) any later version.
- */
+/*
+  Albert Filice
+  Box Dude, or Block Dude
+*/

 #include <SPI.h>
 #include "Arduboy.h"


Update connect4.ino

Update connect4.ino

Fixing bugs discovered during testing at Old No 7 on 3rd March

--- connect4.ino
+++ connect4.ino
@@ -36,7 +36,7 @@
   dropCounter(board, 'O', c - '0');
   displayBoard(board);

-  if (score(board, 'X', 'O') < -500) {
+  if (score(board, 'X', 'O') == -1000) {
     Serial.println();
     Serial.println ("****CONGRATULATIONS YOU WIN**** ");
     Serial.println();
@@ -53,7 +53,7 @@
     dropCounter(board, 'X', best);
     displayBoard(board);

-    if (score(board, 'X', 'O') > 500) {
+    if (score(board, 'X', 'O') == 1000) {
       Serial.println();
       Serial.println ("****COMISERATIONS YOU LOST****");
       Serial.println();
@@ -118,7 +118,11 @@
           else if (addScore == 0) addScore = 1;
           else if (addScore == 1) addScore = 10;
           else if (addScore == 10) addScore = 100;
-          else if (addScore == 100) addScore = 1000;
+          else if (addScore == 100) {
+            // The game has been won
+            totalScore = 1000;
+            goto gameWon;
+          }
         }

         if (board[j] == oppToken) {
@@ -130,7 +134,11 @@
           else if (addScore == 0) addScore = -1;
           else if (addScore == -1) addScore = -10;
           else if (addScore == -10) addScore = -100;
-          else if (addScore == -100) addScore = -1000;
+          else if (addScore == -100) {
+            // The game has been won
+            totalScore = -1000;
+            goto gameWon;
+          }
         }
         // Move to next position in group of 4
         j += lineStep;
@@ -141,42 +149,40 @@
       totalScore += addScore;
     }
   }
-  return totalScore;
+  gameWon: return totalScore;
 }

-int bestMove(char board[], char token, char oppToken, byte &best, byte lookAhead) {
+int bestMove(char board[], char token, char oppToken, byte &bestCol, byte lookAhead) {

   int bestScore = -9999;
-  byte best2;

   // Evaluate each choice of column
   for (byte col = 0; col < 7; col++) {
+    if (board[col] == '.') {

-    int thisScore;
-
-    // Make a copy of the board
-    char boardCopy[43];
-    for (byte i = 0; i < 43; i++) boardCopy[i] = board[i];
-
-    // Drop token onto the copy of the board
-    dropCounter(boardCopy, token, col);
-
-    if (lookAhead == 0)
-      // Don't look any more moves ahead, just evaluate the board as-is
+      int thisScore;
+
+      // Make a copy of the board
+      char boardCopy[43];
+      for (byte i = 0; i < 43; i++) boardCopy[i] = board[i];
+
+      // Drop token onto the copy of the board
+      dropCounter(boardCopy, token, col);
       thisScore = score(boardCopy, token, oppToken);
-    else {
-      // Look more moves ahead, but swap places with opponent since it will be their turn next
-      thisScore = -bestMove(boardCopy, oppToken, token, best2, lookAhead - 1);
-    }

-    // Check this choice of column - best so far?
-    if (thisScore > bestScore) {
-      // Yes, a new best choice found
-      bestScore = thisScore;
-      best = col;
+      if (abs(thisScore) < 1000 && lookAhead > 0) {
+        // Look more moves ahead, but swap places with opponent since it will be their turn next
+        byte oppBestCol;
+        thisScore = -bestMove(boardCopy, oppToken, token, oppBestCol, lookAhead - 1);
+      }
+
+      // Check this choice of column - best so far?
+      if (thisScore > bestScore) {
+        // Yes, a new best choice found
+        bestScore = thisScore;
+        bestCol = col;
+      }
     }
   }
   return bestScore;
 }
-
-


Mistake trying to revert?

Mistake trying to revert?

wth.

--- jacksclock12/jacksclock12.ino
+++ jacksclock12/jacksclock12.ino
@@ -1,9 +1,11 @@
 /* ================================================================================== //
 //
-//    Jack's 420 Clock - 2014
-//    Written for Arduino Uno Rev. 3
-//    Adafruit Hardware: Real Time Clock: DS1307, Neopixel (40 RGB-LED) Shield,
-//    7-Segment Display, 14-Segment Aphanumeric Display, Backlight Module
+//    Jack's 420 Clock
+//
+//    *** TO DO ***
+//    * Clean up both switch functions
+//    * Auto Dim: Debounce / Smoothing
+//    * Fix RGB LED
 //
 // ================================================================================== */

@@ -16,6 +18,7 @@
 #include <Adafruit_NeoPixel.h>

 // Input/Output Pins
+<<<<<<< HEAD
 int photoCellIn =       A1;      // Auto Dimming
 int nightLightIn =      A2;      // Backlight
 int clockLightIn =      A3;      // 7-Sebment
@@ -41,13 +44,43 @@
 int neoBrightness = 100;         // Neopixel Shield
 boolean running = false;         // Colon On/Off
 //volatile int state = LOW;        // For Reminder Switch Interrupt
+=======
+int photoCellIn = A1;         // Auto Dimming
+int nightLightIn = A2;        // Backlight
+int clockLightIn = A3;        // 7-Sebment
+int NeoPixel = 6;             // RGB-LED: Green
+int uvLED = 7;                // LEDs: UV
+int reminderSwitchIn = 8;     // Reminder Switch *** NOT WORKING ***
+int fourTwentyLED = 9;        // LED: Green
+int piezoOut = 10;            // Speaker
+int nightLightOut = 11;       // Backlight
+int brightSwitchIn = 12;      // Auto Brightness
+int dstSwitchIn = 13;         // Savings Time Switch
+
+
+// Variables
+int clockKnob;                // Potentiometer 1
+int lightKnob;                // Potentiometer 2
+int clockBrightness;          // 7-Segment & Alphanumeric
+int lightBrightness;          // Backlight
+int dstState;                 // DST
+int reminderState;            // Switch (Reminder)
+int autoBrightState;          // Switch (Auto-Dimmer)
+int photoCellRead;            // Photo Cell
+int autoBrightAverage;        // Photo Cell
+long previousMillis;          // For counting of xfade timer
+int fourTwentyBright = 0;     // 420 LED
+int fadeAmount = 2;           // 420 LED
+boolean running = false;      // Colon On/Off
+int counter = 0;              // Counts notes played
+int numReadings = 25;         // Smoothing function: # of Readings
+>>>>>>> parent of 044ddaa... Many fixes + last working version before interrupts

 // Setup Components
 RTC_DS1307 RTC;
 Adafruit_7segment disp = Adafruit_7segment();
 Adafruit_AlphaNum4 alpha4 = Adafruit_AlphaNum4();
 Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, NeoPixel, NEO_GRB + NEO_KHZ800);
-

 // ================================================================================== //
 //                                  *** SETUP ***
@@ -75,7 +108,6 @@
   attachInterrupt(1, rainbowOff, LOW);                      // Interrupt
 }

-
 // ================================================================================== //
 //                                  *** LOOP ***
 // ================================================================================== //
@@ -87,7 +119,11 @@
   blinkColon();                          // Blink Colon
   adjustBrightness();                    // Check Switch & Adjust brightness
   fourTwentyCheck();                     // Check if 4:20pm & Run Alarm
+<<<<<<< HEAD
   reminderSwitch();                      // LED / Reminder
+=======
+  reminderSwitch();                      // LED / Reminder
+>>>>>>> parent of 044ddaa... Many fixes + last working version before interrupts
 }

 // ================================================================================== //
@@ -216,9 +252,19 @@
 void reminderSwitch()                                   // Checks Switch & Activates LED
 {
   Serial.println(reminderState);                        // Turn back on when ready to test this function
-  disp.drawColon(true);
   reminderState = digitalRead(reminderSwitchIn);        // Check Reminder Switch
+<<<<<<< HEAD
   if (reminderState == HIGH) rainbowCycle(35);             // If On: Run Rainbow Crossfade
+=======
+  if (reminderState == 1)                               // If On: Run Crossfade Part 1 / 3
+  {
+  rainbowCycle(1);
+  }
+  else
+  {
+  strip.show();                                           // Initialize all pixels to 'off'
+  }
+>>>>>>> parent of 044ddaa... Many fixes + last working version before interrupts
 }

 void rainbowOff()
@@ -243,7 +289,8 @@
     total = total + readings[index];                    // add the reading to the total
     index = index + 1;                                  // advance to next position in array

-    if (index >= numReadings) index = 0;                           // if we're at the end of the array...
+    if (index >= numReadings)                           // if we're at the end of the array...
+      index = 0;

     average = total / numReadings;
     autoBrightAverage = average;
@@ -262,7 +309,7 @@
     previousMillis = currentMillis;

     tone(piezoOut, note, duration);                          //Play tone on buzzerPin
-    if (counter % 2 == 0)                                    // Alternate Green then UV LED's
+    if (counter % 2 == 0)
     {
       digitalWrite(fourTwentyLED, HIGH);
       delay(duration);
@@ -275,16 +322,17 @@
       digitalWrite(uvLED, LOW);
     }
     noTone(piezoOut);
-    counter++;
-  }
-}
-
-
-void rainbowCycle(uint8_t wait)                                                            // Runs rainbow led setup
-{
+
+    counter++;    //Increment counter
+  }
+}
+
+
+void rainbowCycle(uint8_t wait)                                                               // Makes the rainbow equally distributed throughout
+{
   uint16_t i, j;
-  for (j = 0; j < 256 ; j++)                                                               // *1 cycles of all colors on wheel
-  {
+  for (j = 0; j < 256 * 5; j++)                                                               // 5 cycles of all colors on wheel
+  {
     for (i = 0; i < strip.numPixels(); i++)
     {
       strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
@@ -295,7 +343,8 @@
 }

-uint32_t Wheel(byte WheelPos)                                      // The colours are a transition r - g - b - r - g.... & Input value 0 - 255 to get a color value.
+// The colours are a transition r - g - b - r - g.... ||  Input value 0 - 255 to get a color value.
+uint32_t Wheel(byte WheelPos)
 {
   if (WheelPos < 85)
   {
@@ -322,16 +371,13 @@
 void adjustBrightness()                                          // Brightness Check & Adjust
 {
   smooth();                                                      // Averages photocell readings
-  int clockKnob = analogRead(clockLightIn);                      // Check & Map Potentiometers/Photocell
-  int clockBrightness = map(clockKnob, 0, 1023, 2, 15);
-  int lightKnob = analogRead(nightLightIn);
-  int lightBrightness = map(lightKnob, 0, 1023, 50, 255);        // Backlight
-  int neoBrightness = map(lightKnob, 0, 1023, 1, 200);
+  clockKnob = analogRead(clockLightIn);                          // Check & Map Potentiometers/Photocell
+  clockBrightness = map(clockKnob, 0, 1023, 2, 15);
+  lightKnob = analogRead(nightLightIn);
+  lightBrightness = map(lightKnob, 0, 1023, 50, 255);
   int autoBright1 = map(autoBrightAverage, 1, 1023, 2, 15);
   int autoBright2 = map(autoBrightAverage, 1, 1023, 50, 255);
-
-  strip.setBrightness(neoBrightness);                            // Set Neopixel Brightness
-
+
   autoBrightState = digitalRead(brightSwitchIn);                 // Adjust Brightness (if Auto Switch On)
   if (autoBrightState == 1)
   {
@@ -344,9 +390,9 @@
     disp.setBrightness(clockBrightness);                          // Use Potentiometers to Set Brightness
     alpha4.setBrightness(clockBrightness);
     analogWrite(nightLightOut, lightBrightness);
-  }
-}
-
+    strip.setBrightness(lightBrightness);
+  }
+}

 void themeMusic()
 {
@@ -363,11 +409,11 @@
     beep(NOTE_C4, 500);
     beep(NOTE_E4, 250);
     beep(NOTE_F4, 250);
-    beep(NOTE_G4, 500);
-    beep(NOTE_C4, 250);
-    beep(NOTE_E4, 250);
-    beep(NOTE_F4, 250);
-  }
+  }
+  beep(NOTE_G4, 500);
+  beep(NOTE_C4, 250);
+  beep(NOTE_E4, 250);
+  beep(NOTE_F4, 250);
   for (int i = 0; i < 3; i++)
   {
     beep(NOTE_G3, 500);


Combined motor control and encoder readings

--- controller/controller.ino
+++ controller/controller.ino
@@ -9,6 +9,73 @@
 boolean stringComplete = false;  // whether the string is complete
 Timer t;

+/// Encoder
+int encoder0PinA = 2;
+int encoder0PinB = 11;
+int encoder0Pos = 0;
+int encoder0PinALast = LOW;
+volatile int n = LOW;
+int last = 0;
+
+int encoder1PinA = 5;
+int encoder1PinB = A2;
+int encoder1Pos = 0;
+int encoder1PinALast = LOW;
+volatile int n2 = LOW;
+int last1 = 0;
+
+void measureLeftEncoder()
+{
+    n = digitalRead(encoder1PinA);
+    if ((encoder1PinALast == LOW) && (n == HIGH))
+    {
+        if (analogRead(encoder1PinB) < 450)
+        {
+            encoder1Pos--;
+        }
+        else
+        {
+            encoder1Pos++;
+        }
+    }
+    encoder1PinALast = n;
+}
+
+void measureRightEncoder()
+{
+    n = digitalRead(encoder0PinA);
+    if ((encoder0PinALast == LOW) && (n == HIGH))
+    {
+        if (digitalRead(encoder0PinB) == LOW)
+        {
+            //if (analogRead(encoder0PinB) < 450) {
+            encoder0Pos--;
+        }
+        else
+        {
+            encoder0Pos++;
+        }
+    }
+    encoder0PinALast = n;
+}
+void printStuff()
+{
+    if (last != encoder0Pos)
+    {
+        Serial.print ("A");
+        Serial.println (encoder0Pos);
+        last = encoder0Pos;
+    }
+
+    if (last1 != encoder1Pos)
+    {
+        Serial.print ("B");
+        Serial.println (encoder1Pos);
+        last1 = encoder1Pos;
+    }
+}
+///
+
 void setup()
 {
   // initialize serial:
@@ -17,6 +84,16 @@
   inputString.reserve(200);

   pinMode(LED_PIN, OUTPUT);
+
+  // Initialize Encoders
+  pinMode (encoder0PinA, INPUT);
+  pinMode (encoder0PinB, INPUT);
+  pinMode (encoder1PinA, INPUT);
+  // pinMode (encoder1PinB, INPUT); // Analog
+  attachInterrupt(0, measureRightEncoder, CHANGE);
+
+  // Print encoder values every second
+  t.every(1000, printStuff);

   // Left motor power wiring is reversed.
   motors.flipLeftMotor(true);
@@ -28,6 +105,10 @@

 void loop()
 {
+  // Measure left encoder manually
+  measureLeftEncoder();
+
+  // Timer updates
   t.update();
 }


RX devide Listens Before Talk

RX devide Listens Before Talk

--- crossbow.ino
+++ crossbow.ino
@@ -15,6 +15,8 @@
 #include <PPMReader.h>
 PPMReader ppmReader(PPM_INPUT_PIN, PPM_INPUT_INTERRUPT);

+bool canTransmit = true;
+
 #endif

 /*
@@ -28,6 +30,8 @@
 Adafruit_SSD1306 display(OLED_RESET);

 int ppm[PPM_CHANNEL_COUNT] = {0};
+
+bool canTransmit = false;

 #endif

@@ -145,6 +149,11 @@

         if (qspCrc == incomingByte) {
             //CRC is correct
+
+        #ifdef DEVICE_MODE_RX
+            //If devide received a valid frame, that means it can start to talk
+            canTransmit = true;
+        #endif

             switch (frameId) {
                 case QSP_FRAME_RC_DATA:
@@ -419,7 +428,7 @@
     }
 #endif

-    if (transmitPayload) {
+    if (canTransmit && transmitPayload) {
         transmitPayload = false;

         radioPacketStart();


Ajout de la direction (non ajusté) et de la lecture d'un interrupteur sur la mannette.

--- controle_par_mannette/controle_par_mannette.ino
+++ controle_par_mannette/controle_par_mannette.ino
@@ -3,7 +3,7 @@
 // norbert-base -> controle_par_manette
 //
 // Permet de contrôler la base Tonka de Norbert en utilisant
-// une mannette fabriquée en Lego
+// une mannette fabriquee en Lego
 //
 // David Beaudette (2016)
 //
@@ -27,16 +27,16 @@
 const int encodeur_int_a = 0;
 const int encodeur_int_b = 1;

-// Numéro de pin des sorties vers les moteurs
+// Numero de pin des sorties vers les moteurs
 const int moteur_avant   =  9;
 const int moteur_arriere = 10;
 const int moteur_gauche  = 11;
 const int moteur_droite  =  6;

-// Numéro de pin de l'entrée de direction
+// Numero de pin de l'entree de direction
 const int mesure_direction = A6;

-// Numéro de pin de la mannette
+// Numero de pin de la mannette
 const int mannette_avant   =  4;
 const int mannette_arriere =  7;
 const int mannette_gauche  =  8;
@@ -47,9 +47,19 @@
 // Batterie
 const int batterie = A4;

+// Convertisseur analogique a numerique
+const float adc_vref = 3.4f;
+const float adc_max_f32 = 1023.0f;
+const float adc_to_volts = adc_vref / adc_max_f32;
+
 // Capteurs de distance
 const int ir_avant   = A3;
 const int ir_arriere = A2;
+const float ir_fonction_coeff[5] = { 0.034f,
+                                    -0.424f,
+                                     1.760f,
+                                    -3.127f,
+                                     2.388f};

 // Bouton
 const int bouton = 19;
@@ -64,15 +74,29 @@
 const int filtre_mannette_pot_decal = 5;

 // Parametres de controle des moteurs
+const int vitesse_av_moteur_nom = int(0.2f * 255.0f);
 const int vitesse_zero_tol_tic_par_cycle = 3;
-const float moteur_gain_pid[3] = {0.05f, 0.01f, 0.0f};
-const float moteur_ir_gain_pid[3] = {0.3f, 0.01f, 0.0f};
-
-// Périodes entre les appels de fonction
-const int periode_affichage_ms = 1000;
+const float moteur_av_gain_pid[3] = {0.05f, 0.01f, 0.0f};
+const int moteur_av_zone_morte = int(0.2f * 255.0f);
+
+const float moteur_gd_gain_pid[3] = {0.05f, 0.01f, 0.0f};
+const int moteur_gd_zone_morte = 100;
+
+// Periodes entre les appels de fonction
+const int periode_affichage_ms          = 1000;
+const int periode_controle_moteurs_ms   = 100;
 const int periode_lecture_analogique_ms = 10;
-const int periode_controle_moteurs_ms = 100;
-
+const int periode_controle_led_ms       = 10;
+
+
+/////////////////////////////////////////////////////////////
+//
+// Types de donnees
+//
+/////////////////////////////////////////////////////////////
+
+enum direction_t {gauche, centre, droite};
+enum mouvement_t {recule, arrete, avance};

 /////////////////////////////////////////////////////////////
 //
@@ -93,15 +117,25 @@

 // Controle de la vitesse
 long vitesse_tic_par_cycle = 0;
-long vitesse_cmd;
+long vitesse_av_cmd;
 long roue_phase_precedente = 0;
 long moteur_integrale_erreur = 0;
 long moteur_erreur_prec = 0;

+// Controle de la direction
+long moteur_gd_integrale_erreur = 0;
+long moteur_gd_erreur_prec = 0;
+long vitesse_gd_cmd;
+
+// État de la mannette
+direction_t interrupteur_mannette_precedent = centre;
+mouvement_t mannette_mouvement_precedent  = arrete;
+bool interrupteur_mannette_modifiee = false;
+
 // Communication avec le cerveau RPi
 //CmdMessenger cerveau = CmdMessenger(Serial, ',',';','/');

-// Séquenceur de fonctions
+// Sequenceur de fonctions
 Timer sequenceur;

 /////////////////////////////////////////////////////////////
@@ -116,11 +150,16 @@
 // Using direct port manipulation for quadrature decoding.
 void interruption_encodeur();

-// Lecture des entrées analogiques et mise a jour des filtres
+// Lecture des entrees analogiques et mise a jour des filtres
 void lire_entrees_analogiques();

-// Affichage de l'état du systeme
+// Affichage de l'etat du systeme
 void affichage();
+
+// Controle de la led sur la manette
+void allume_led();
+void eteint_led();
+void controle_led();

 // Controle de la propulsion
 void controle_moteurs();
@@ -142,7 +181,7 @@
 /////////////////////////////////////////////////////////////

 void setup() {
-  // Initialisation de la communication série
+  // Initialisation de la communication serie
   Serial.begin(115200);
   char o_accent_circonflexe = 244;
   Serial.print(F("Contr"));
@@ -156,13 +195,16 @@
   pinMode(moteur_gauche,  OUTPUT);
   pinMode(moteur_droite,  OUTPUT);

-  // Initialisation des entrées de la mannette
+  // Initialisation des entrees de la mannette
   pinMode(mannette_avant,   INPUT_PULLUP);
   pinMode(mannette_arriere, INPUT_PULLUP);
   pinMode(mannette_gauche,  INPUT_PULLUP);
   pinMode(mannette_droite,  INPUT_PULLUP);

-  // Entrées analogiques
+  // Affichage sur la manette
+  pinMode(mannette_del,   OUTPUT);
+
+  // Entrees analogiques
   pinMode(mannette_pot, INPUT);
   pinMode(mesure_direction, INPUT);
   pinMode(ir_avant,   INPUT);
@@ -170,7 +212,7 @@
   pinMode(batterie, INPUT);
   analogReference(EXTERNAL);

-  // Entrées numériques
+  // Entrees numeriques
   pinMode(bouton, INPUT_PULLUP);

   // Initialisation de l'encodeur de roue
@@ -181,7 +223,7 @@

   // Initialisation du PID de la direction

-  // Initialisation des fonctions périodiques
+  // Initialisation des fonctions periodiques
   sequenceur.every(periode_lecture_analogique_ms,
                    lire_entrees_analogiques);

@@ -193,6 +235,9 @@

   sequenceur.every(periode_controle_moteurs_ms,
                    controle_direction);
+
+  sequenceur.every(periode_controle_led_ms,
+                   controle_led);
 }

 /////////////////////////////////////////////////////////////
@@ -229,7 +274,7 @@
   portd = pd;
 }

-// Lecture et filtrage des entrées analogiques
+// Lecture et filtrage des entrees analogiques
 void lire_entrees_analogiques() {
   // Mise a jour des filtres
   batterie_filtre += (analogRead(batterie) - batterie_filtre) >> filtre_batterie_decal;
@@ -243,26 +288,68 @@
 void affichage() {

 #if DEBOGGAGE
-  Serial.print(F("Mannette avant:"));
-  Serial.println(digitalRead(mannette_avant));
-  Serial.print(F("Mannettea arriere:"));
-  Serial.println(digitalRead(mannette_arriere));
-  Serial.print(F("La phase de la roue droite est:"));
+  Serial.println();
+  Serial.print(F("Mannette mouvement: "));
+  switch(mannette_mouvement_precedent)
+  {
+      case recule: Serial.println(F("recule.")); break;
+      case arrete: Serial.println(F("arrete.")); break;
+      case avance: Serial.println(F("avance.")); break;
+  }
+  Serial.print(F("Mannette direction: "));
+  switch(interrupteur_mannette_precedent)
+  {
+      case gauche: Serial.println(F("gauche.")); break;
+      case centre: Serial.println(F("centre.")); break;
+      case droite: Serial.println(F("droite.")); break;
+  }
+  Serial.print(F("La phase de la roue droite est: "));
   Serial.println(lire_phase());
-  Serial.print(F("La vitesse est:"));
+
+  Serial.print(F("La vitesse est: "));
   Serial.println(vitesse_tic_par_cycle);
-  Serial.print(F("La vitesse commandée est:"));
-  Serial.println(vitesse_cmd);
-  Serial.print(F("L'etat du bouton est:"));
+
+  Serial.print(F("La vitesse commandee est: "));
+  Serial.println(vitesse_av_cmd);
+
+  Serial.print(F("L'etat du bouton est: "));
   Serial.println(digitalRead(bouton));
-  Serial.print(F("L'etat de la batterie est:"));
-  Serial.println(batterie_filtre);
-  Serial.print(F("L'etat du capteur avant est:"));
-  Serial.println(ir_avant_filtre);
-  Serial.print(F("L'etat du capteur arriere est:"));
-  Serial.println(ir_arriere_filtre);
-  Serial.print(F("L'etat du potentiometre de la mannette est:"));
+
+  Serial.print(F("L'etat de la batterie est: "));
+  Serial.print(static_cast<float>(batterie_filtre) * 0.0125f);
+  Serial.print(F(" V ("));
+  Serial.print(batterie_filtre);
+  Serial.println(F(")."));
+
+  float ir_distance;
+  float a;
+  Serial.print(F("L'etat du capteur avant est: "));
+  a = static_cast<float>(ir_avant_filtre) * adc_to_volts;
+  ir_distance =  ir_fonction_coeff[0] * a * a * a * a;
+  ir_distance += ir_fonction_coeff[1] * a * a * a;
+  ir_distance += ir_fonction_coeff[2] * a * a;
+  ir_distance += ir_fonction_coeff[3] * a;
+  ir_distance += ir_fonction_coeff[4];
+  Serial.print(ir_distance * 100.0f);
+  Serial.print(F(" cm ("));
+  Serial.print(ir_avant_filtre);
+  Serial.println(F(")."));
+
+  Serial.print(F("L'etat du capteur arriere est: "));
+  a = static_cast<float>(ir_arriere_filtre) * adc_to_volts;
+  ir_distance =  ir_fonction_coeff[0] * a * a * a * a;
+  ir_distance += ir_fonction_coeff[1] * a * a * a;
+  ir_distance += ir_fonction_coeff[2] * a * a;
+  ir_distance += ir_fonction_coeff[3] * a;
+  ir_distance += ir_fonction_coeff[4];
+  Serial.print(ir_distance * 100.0f);
+  Serial.print(F(" cm ("));
+  Serial.print(ir_arriere_filtre);
+  Serial.println(F(")."));
+
+  Serial.print(F("L'etat du potentiometre de la mannette est: "));
   Serial.println(mannette_pot_filtre);
+
   Serial.print(F("Direction lue: "));
   Serial.println(direction_filtre);

@@ -270,19 +357,51 @@

 }

+void lecture_interrupteur_mannette() {
+
+  // Lire l'etat des controles sur la manette
+  int interrupteur_gauche = !digitalRead(mannette_gauche);
+  int interrupteur_droite = !digitalRead(mannette_droite);
+
+  direction_t interrupteur_mannette_actuel;
+
+  if(interrupteur_gauche) {
+    interrupteur_mannette_actuel = gauche;
+  }
+  else if(interrupteur_droite) {
+    interrupteur_mannette_actuel = droite;
+  }
+  else {
+    interrupteur_mannette_actuel = centre;
+  }
+
+  // Mise a jour de la memoire de direction
+  if(interrupteur_mannette_precedent == interrupteur_mannette_actuel) {
+    interrupteur_mannette_modifiee = false;
+  }
+  else {
+    interrupteur_mannette_modifiee = true;
+  }
+  interrupteur_mannette_precedent = interrupteur_mannette_actuel;
+}
+
 void controle_direction() {

-  // Lire l'état des controles sur la manette
-  int commande_gauche = digitalRead(mannette_gauche);
-  int commande_droite = digitalRead(mannette_droite);
-  int vitesse_cmd = map(mannette_pot_filtre, 0, 1023, -255, 255);
-  if(vitesse_cmd < -100) {
-    analogWrite(moteur_gauche, -vitesse_cmd);
+  int direction_cmd = constrain(mannette_pot_filtre, 12, 980);
+
+  vitesse_gd_cmd = constrain((int)pid(moteur_gd_integrale_erreur,
+                                      moteur_gd_erreur_prec,
+                                      direction_cmd,
+                                      direction_filtre - 36,
+                                      moteur_gd_gain_pid), -255, 255);
+
+  if(vitesse_gd_cmd < -moteur_gd_zone_morte) {
+    analogWrite(moteur_gauche, -vitesse_gd_cmd);
     analogWrite(moteur_droite, 0);
   }
-  else if(vitesse_cmd > 100) {
+  else if(vitesse_gd_cmd > moteur_gd_zone_morte) {
     analogWrite(moteur_gauche, 0);
-    analogWrite(moteur_droite, vitesse_cmd);
+    analogWrite(moteur_droite, vitesse_gd_cmd);
   }
   else {
     analogWrite(moteur_gauche, 0);
@@ -290,59 +409,95 @@
   }
 }

+void allume_led() {
+  digitalWrite(mannette_del, 1);
+}
+
+void eteint_led() {
+  digitalWrite(mannette_del, 0);
+}
+
+void controle_led() {
+
+  switch(interrupteur_mannette_precedent)
+  {
+    case gauche:
+      allume_led();
+      break;
+    case centre:
+      if(interrupteur_mannette_modifiee) {
+        sequenceur.oscillate(mannette_del, 1000U, 1, 3);
+      }
+      break;
+    case droite:
+      eteint_led();
+      break;
+  }
+}
+
 void controle_moteurs() {

-  // Lire l'état des controles sur la manette
-  int commande_avance = digitalRead(mannette_avant);
-  int commande_recule = digitalRead(mannette_arriere);
-
+  // Lire l'etat des controles sur la manette
+  int commande_avance = !digitalRead(mannette_avant);
+  int commande_recule = !digitalRead(mannette_arriere);
+
+  mouvement_t mannette_mouvement_actuel;
+
+  if(commande_avance) {
+    mannette_mouvement_actuel = avance;
+  }
+  else if(commande_recule) {
+    mannette_mouvement_actuel = recule;
+  }
+  else {
+    mannette_mouvement_actuel = arrete;
+  }
+
   // Lire la phase de la roue
   long roue_phase_courante = lire_phase();
   vitesse_tic_par_cycle = roue_phase_courante - roue_phase_precedente;

-  // PWM entre 20% et 100%
-  int vitesse_moteur_min = int(0.2f * 255.0f);
-  int vitesse_moteur_nom = int(0.2f * 255.0f);
   if(digitalRead(bouton) == LOW) {
-    // Vitesse basée sur la distance arriere
-    vitesse_cmd = map(ir_arriere_filtre, 184, 850, 20, 255);
-  }
-  else if(commande_avance == HIGH && commande_recule == HIGH) {
+    // Vitesse basee sur la distance arriere
+    vitesse_av_cmd = map(ir_arriere_filtre, 184, 850, 20, 255);
+  }
+  else if(mannette_mouvement_actuel == arrete) {
     // Freinage
-    vitesse_cmd = constrain((int)pid(moteur_integrale_erreur,
+    vitesse_av_cmd = constrain((int)pid(moteur_integrale_erreur,
                                      moteur_erreur_prec,
                                      0,
                                      vitesse_tic_par_cycle,
-                                     moteur_gain_pid), -255, 255);
+                                     moteur_av_gain_pid), -255, 255);
   }
   else {
-    if(commande_avance == LOW) {
+    if(mannette_mouvement_actuel == avance) {
       // Activer le moteur avant
-       vitesse_cmd = vitesse_moteur_nom;
+       vitesse_av_cmd = vitesse_av_moteur_nom;
     }
-    else if(commande_recule == LOW) {
+    else if(mannette_mouvement_actuel == recule) {
       // Activer le moteur arrière
-       vitesse_cmd = -vitesse_moteur_nom;
+       vitesse_av_cmd = -vitesse_av_moteur_nom;
     }
   }

   // Mise a jour de la commande PWM
-  if(abs(vitesse_cmd) < vitesse_moteur_min) vitesse_cmd = 0;
-  if(vitesse_cmd > 0) {
+  if(abs(vitesse_av_cmd) < vitesse_av_moteur_min) vitesse_av_cmd = 0;
+  if(vitesse_av_cmd > moteur_av_zone_morte) {
     // Activer le moteur avant
-    analogWrite(moteur_avant, vitesse_cmd);
+    analogWrite(moteur_avant, vitesse_av_cmd);
     analogWrite(moteur_arriere, 0);
   }
-  else if(vitesse_cmd < 0) {
+  else if(vitesse_av_cmd < -moteur_av_zone_morte) {
     // Activer le moteur arrière
     analogWrite(moteur_avant, 0);
-    analogWrite(moteur_arriere, -vitesse_cmd);
+    analogWrite(moteur_arriere, -vitesse_av_cmd);
   }
   else {
     analogWrite(moteur_avant, 0);
     analogWrite(moteur_arriere, 0);
   }
-  // Mise a jour de la phase précédente
+  // Mise a jour de la memoire
+  mannette_mouvement_precedent = mannette_mouvement_actuel;
   roue_phase_precedente = roue_phase_courante;
 }

@@ -354,7 +509,7 @@

   long erreur = commande_desiree - lecture;

-  // A voir si l'intégrale diverge sans mise a jour conditionnelle
+  // A voir si l'integrale diverge sans mise a jour conditionnelle
   integrale += erreur;

   float commande_pid = gain_pid[0] * (float)erreur +


Allow us to pass an 'error code' to terminalError.

It's not really an error code as such; it's just the number of times to
flash the error LED.  This'll be useful to display a different 'code'
when the system fails for different reasons.

--- printer.ino
+++ printer.ino
@@ -171,7 +171,7 @@
       debug("Cleared cache");
     } else {
       debug("Failed to clear cache. Aborting.");
-      terminalError();
+      terminalError(3);
       return;
     }
   }
@@ -267,8 +267,8 @@
   flashErrorLEDs(5, 100);
 }

-inline void terminalError() {
-  flashErrorLEDs(3, 500);
+inline void terminalError(unsigned int times) {
+  flashErrorLEDs(times, 500);
   systemOK = false;
   digitalWrite(errorLED, HIGH);
 }


Break out SDA and SCL pins into defines.

--- usermods/ssd1306_i2c_oled_u8g2/wled06_usermod.ino
+++ usermods/ssd1306_i2c_oled_u8g2/wled06_usermod.ino
@@ -1,12 +1,18 @@
 #include <U8x8lib.h> // from https://github.com/olikraus/u8g2/
+
+//The SCL and SDA pins are defined here.
+//Lolin32 boards use SCL=4 SDA=5
+#define U8X8_PIN_SCL 5
+#define U8X8_PIN_SDA 4
+

 // If display does not work or looks corrupted check the
 // constructor reference:
 // https://github.com/olikraus/u8g2/wiki/u8x8setupcpp
 // or check the gallery:
 // https://github.com/olikraus/u8g2/wiki/gallery
-U8X8_SSD1306_128X32_UNIVISION_HW_I2C u8x8(U8X8_PIN_NONE, 5,
-                                          4); // Pins are Reset, SCL, SDA
+U8X8_SSD1306_128X32_UNIVISION_HW_I2C u8x8(U8X8_PIN_NONE, U8X8_PIN_SCL,
+                                          U8X8_PIN_SDA); // Pins are Reset, SCL, SDA

 // gets called once at boot. Do all initialization that doesn't depend on
 // network here


Fail fast if we can't clear the cache.

Fail fast if we can't clear the cache.

After initialization, the error LED will flash three times, indicating a
failure to clear the cache.  The sketch will then 'terminate' in as much
as it won't do anything in the main loop.

I've seen the sketch fail to clear the cache on multiple occassions.
I'm not 100% sure how it gets in this state but the only solution
appears to be deleting the cache ('TMP') or formatting the card in
another machine.

There's some duplication between `abortDueToCacheFailure` and
`recoverableError` that I should be able to factor out later.

I've removed the `systemError` function and inlined the switching on of
the error LED.  This is so that I can use a boolean named systemError to
indicate that the sketch should terminate.

--- printer.ino
+++ printer.ino
@@ -146,6 +146,9 @@
   initDiagnosticLEDs();
 }

+// -- Flag to indicate whether we've encountered an irrecoverable error
+
+boolean systemError = false;

 // -- Check for new data and download if found

@@ -154,6 +157,16 @@
 unsigned long content_length = 0;
 boolean statusOk = false;

+void abortDueToCacheFailure() {
+  delay(1000);
+  for(int i = 1; i <= 3; i++) {
+    digitalWrite(errorLED, HIGH); delay(500);
+    digitalWrite(errorLED, LOW); delay(500);
+  }
+  systemError = true;
+  digitalWrite(errorLED, HIGH);
+}
+
 void checkForDownload() {
   unsigned long length = 0;
   content_length = 0;
@@ -167,7 +180,9 @@
     if (SD.remove(cacheFilename)) {
       debug("Cleared cache");
     } else {
-      debug("Failed to clear cache");
+      debug("Failed to clear cache. Aborting.");
+      abortDueToCacheFailure();
+      return;
     }
   }
   File cache = SD.open(cacheFilename, FILE_WRITE);
@@ -230,7 +245,7 @@
         debug2("Failure, content length: ", content_length);
         if (content_length != length) debug2("length: ", length);
         if (content_length != cache.size()) debug2("cache: ", cache.size());
-        systemError();
+        digitalWrite(errorLED, HIGH);
       }
 #endif
     } else {
@@ -261,11 +276,6 @@
   }
 }

-inline void systemError() {
-  digitalWrite(errorLED, HIGH);
-  // ... and stay on.
-}
-
 // -- Print send any data from the cache to the printer

 inline void printFromDownload() {
@@ -286,15 +296,17 @@
 Bounce bouncer = Bounce(buttonPin, 5); // 5 millisecond debounce

 void loop() {
-  if (downloadWaiting) {
-    bouncer.update();
-    if (bouncer.read() == HIGH) {
-      printFromDownload();
-    }
-  } else {
-    checkForDownload();
-    if (!downloadWaiting) {
-      delay(pollingDelay);
-    }
-  }
-}
+  if (!systemError) {
+    if (downloadWaiting) {
+      bouncer.update();
+      if (bouncer.read() == HIGH) {
+        printFromDownload();
+      }
+    } else {
+      checkForDownload();
+      if (!downloadWaiting) {
+        delay(pollingDelay);
+      }
+    }
+  }
+}


use setAPStaticIPConfig instead  of (old?) setAPConfig in first example

--- examples/AutoConnect/AutoConnect.ino
+++ examples/AutoConnect/AutoConnect.ino
@@ -17,7 +17,7 @@
     //wifiManager.resetSettings();

     //set custom ip for portal
-    //wifiManager.setAPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
+    //wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));

     //fetches ssid and pass from eeprom and tries to connect
     //if it does not connect it starts an access point with the specified name


Fix typo date to data

Fix typo date to data

--- examples/RFID-Cloner/RFID-Cloner.ino
+++ examples/RFID-Cloner/RFID-Cloner.ino
@@ -1,6 +1,6 @@
 /*
  * Copy the RFID card data into variables and then
- * scan the second empty card to copy all the date
+ * scan the second empty card to copy all the data
  * ----------------------------------------------------------------------------
  * Example sketch/program which will try the most used default keys listed in
  * https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys to dump the


Update ENC28J60.ino

Update ENC28J60.ino

--- examples/BoardsAndShields/ENC28J60/ENC28J60.ino
+++ examples/BoardsAndShields/ENC28J60/ENC28J60.ino
@@ -19,6 +19,15 @@
  *
  * For this example you need UIPEthernet library:
  *   https://github.com/ntruchsess/arduino_uip
+ *
+ * Typical wiring would be:
+ *  VCC -- 5V
+ *  GND -- GND
+ *  CS  -- D10
+ *  SI  -- D11
+ *  SCK -- D13
+ *  SO  -- D12
+ *  INT -- D2
  *
  * Feel free to apply it to any other example. It's simple!
  *


(WIP) draw improvement

(WIP) draw improvement

--- VirtualShield/examples/RGBLED-Draw/RGBLED-Draw.ino
+++ VirtualShield/examples/RGBLED-Draw/RGBLED-Draw.ino
@@ -39,6 +39,7 @@
 const int tappedHash = 38322;
 const int pressedHash = 56990;
 const int releasedHash = 13117;
+const int enteredHash = 54231;

 int ids[gridcolumns][gridrows];
 int touchX, touchY;
@@ -57,13 +58,14 @@
     if (shift) {
       strip.ShiftAllPixels();
     }
-    char tag[3] = {48+x, 48+y, 0};
-    if (ids[x][y] > 0) {
-      screen.clearId(ids[x][y]);
+
+    if (false) { //ids[x][y] > 0) {
+      screen.change(ids[x][y], visibleColor(colors[x][y].color));
+    } else {
+      char tag[3] = {48+x, 48+y, 0};
+      ids[x][y] = screen.fillRectangle(cwidth * x + (cwidth/2 - cellwidth/2), rheight * y + (rheight/2 - cellheight/2),
+        cellwidth, cellheight, visibleColor(colors[x][y].color), String(tag), true);
     }
-
-    ids[x][y] = screen.fillRectangle(cwidth * x + (cwidth/2 - cellwidth/2), rheight * y + (rheight/2 - cellheight/2),
-      cellwidth, cellheight, visibleColor(colors[x][y].color), String(tag));
 }

 void drawGrid()
@@ -115,26 +117,7 @@
       y = tag[1]-48;
   }

-  if (shieldEvent->actionHash == pressedHash) {
-    pressedX = x;
-    pressedY = y;
-  }
-
-  if (shieldEvent->actionHash == releasedHash) {
-    releasedX = x;
-    releasedY = y;
-    if (pressedX <= releasedX && pressedY <= releasedY && (pressedX+pressedY < releasedX+releasedY)) {
-      for (int ix=pressedX; ix<=releasedX; ix++) {
-        for (int iy=pressedY; iy<=releasedY; iy++) {
-          setColor(ix,iy,selectedColor,false);
-        }
-      }
-
-      strip.ShiftAllPixels();
-    }
-  }
-
-  if (shieldEvent->actionHash == tappedHash) {
+  if (shieldEvent->actionHash == tappedHash || shieldEvent->actionHash == enteredHash) {
     if (tag[1] == 0 && tag[0] < 48+(colorCount+1) && tag[0] >= 48) {
       //color
       if (tag[0] == 48+(colorCount)) {
@@ -160,6 +143,12 @@

 void setup()
 {
+  for (int x=0; x<gridcolumns; x++) {
+    for (int y=0; y<gridrows; y++) {
+      ids[x][y] = 0;
+    }
+  }
+
   shield.setOnRefresh(refresh);
   screen.setOnEvent(screenEvent);