start using struct

start using struct

--- main/main.ino
+++ main/main.ino
@@ -61,6 +61,40 @@
   B11111,
   B11111
 };
+
+struct EngineVariable
+{
+  char shortLabel;
+  char longLabel;
+  double currentValue;
+  double previousValue;
+  double minimum;
+  double maximum;
+  char unit;
+};
+
+EngineVariable engine_map   = {"MAP", "MAP", 0.0, 0.0, 10.0, 250.0, "KPA"};
+EngineVariable calc_vac     = {"VAC", "VACUUM", 0.0, 0.0, -200.0, 100.0, "HG"};
+EngineVariable calc_bst     = {"BST", "BOOST", 0.0, 0.0, 0.0, 50.0, "PSI"};
+EngineVariable engine_rpm   = {"RPM", "RPM", 0.0, 0.0, 0.0, 6500.0, ""};
+EngineVariable engine_clt   = {"CLT", "TEMP", 0.0, 0.0, 20.0, 250.0, ""};
+EngineVariable engine_tps   = {"TPS", "THROTTLE", 0.0, 0.0, 0.0, 100.0, "%"};
+EngineVariable engine_pw1   = {"PW1", "PULSE WIDTH 1", 0.0, 0.0, 0.0, 50.0, "MS"};
+EngineVariable engine_pw2   = {"PW2", "PULSE WIDTH 2", 0.0, 0.0, 0.0, 50.0, "MS"};
+EngineVariable engine_iat   = {"IAT", "AIR TEMP", 0.0, 0.0, 20.0, 150.0, ""};
+EngineVariable engine_adv   = {"ADV", "ADVANCE", 0.0, 0.0, 10.0, 60.0, "DEG"};
+EngineVariable engine_tgt   = {"TGT", "AIR FUEL TARGET", 0.0, 0.0, 10.0, 20.0, ""};
+EngineVariable engine_afr   = {"AFR", "AIR FUEL RATIO", 0.0, 0.0, 10.0, 20.0, ""};
+EngineVariable engine_ego   = {"EGO", "EGO CORRECTION", 0.0, 0.0, 0.0, 100.0, "%"};
+EngineVariable engine_egt   = {"EGT", "EXHAUST TEMP", 0.0, 0.0, 20.0, 2000.0, ""};
+EngineVariable engine_pws   = {"PWS", "PULSE WIDTH SEQ", 0.0, 0.0, 0.0, 50.0, "MS"};
+EngineVariable engine_bat   = {"BAT", "BATTERY", 0.0, 0.0, 0.0, 20.0, "V"};
+EngineVariable engine_sr1   = {"SR1", "SENSOR 1", 0.0, 0.0, 0.0, 10000.0, ""};
+EngineVariable engine_sr2   = {"SR2", "SENSOR 2", 0.0, 0.0, 0.0, 10000.0, ""};
+EngineVariable engine_knk   = {"KNK", "KNOCK RTD", 0.0, 0.0, 0.0, 50.0, "DEG"};
+EngineVariable engine_vss   = {"VSS", "SPEED", 0.0, 0.0, 0.0, 300.0, "MPH"};
+EngineVariable engine_tcr   = {"TCR", "TRACTION RTD", 0.0, 0.0, 0.0, 50.0, "DEG"};
+EngineVariable engine_lct   = {"LCT", "LAUNCH CTRL", 0.0, 0.0, 0.0, 100.0, "DEG"};

 long startTime;
 long endTime;
@@ -114,12 +148,12 @@
   if(currentMillis - lastMillis >= interval) {
     lastMillis = currentMillis;
     lcd.setCursor(4, 2);
-    lcd.print(tgt);
-    draw_bar(tgt, 3, 10.0, 20.0);
+    lcd.print(engine_tgt.currentValue);
+    draw_bar(engine_tgt.currentValue, 3, 10.0, 20.0);

     lcd.setCursor(4, 0);
-    lcd.print(afr);
-    draw_bar(afr, 1, 10.0, 20.0);
+    lcd.print(engine_afr.currentValue);
+    draw_bar(engine_afr.currentValue, 1, 10.0, 20.0);

     //Serial.println(tgt);
     //Serial.println((double)badDataCount / (double)goodDataCount);
@@ -136,8 +170,16 @@

         unsigned int canId = CAN.getCanId();

-
-
+        switch(canId) {
+          case 1514:
+            engine_tgt.currentValue = (double)buf[0] / 10.0;
+            engine_afr.currentValue = (double)buf[1] / 10.0;
+            break;
+          default:
+            //do nothing
+            break;
+        }
+          /*
         if(canId == 1514) {
           Serial.println("-----------------------------");
           Serial.print("Get data from ID: ");
@@ -151,6 +193,7 @@
           }
           Serial.println();
         }
+        */

   }


add can values

add can values

--- main/main.ino
+++ main/main.ino
@@ -211,7 +211,6 @@
             engine_ego.previousValue = engine_ego.currentValue;
             engine_ego.currentValue = (buf[2] * 256 + buf[3]) / 10.0;

-            //not fully tested
             engine_egt.previousValue = engine_egt.currentValue;
             engine_egt.currentValue = (buf[4] * 256 + buf[5]) / 10.0;

@@ -223,10 +222,31 @@
             engine_bat.previousValue = engine_bat.currentValue;
             engine_bat.currentValue = (buf[0] * 256 + buf[1]) / 10.0;

-
+            //not tested
+            engine_sr1.previousValue = engine_sr1.currentValue;
+            engine_sr1.currentValue = (buf[2] * 256 + buf[3]) / 10.0;
+
+            //not tested
+            engine_sr2.previousValue = engine_sr2.currentValue;
+            engine_sr2.currentValue = (buf[4] * 256 + buf[5]) / 10.0;
+
+            //not tested
+            engine_knk.previousValue = engine_knk.currentValue;
+            engine_knk.currentValue = (buf[6] * 256) / 10.0;
+
             break;
           case 1516:
-
+            //not tested
+            engine_vss.previousValue = engine_vss.currentValue;
+            engine_vss.currentValue = (buf[0] * 256 + buf[1]) / 10.0;
+
+            //not tested
+            engine_tcr.previousValue = engine_tcr.currentValue;
+            engine_tcr.currentValue = (buf[2] * 256 + buf[3]) / 10.0;
+
+            engine_lct.previousValue = engine_lct.currentValue;
+            engine_lct.previousValue = (buf[4] * 256 + buf[5]) / 10.0;
+
             break;
           default:
             //do nothing


refactor temperature part (arduino)

refactor temperature part (arduino)

--- Arduino/AlphaChairArduino/AlphaChairArduino.ino
+++ Arduino/AlphaChairArduino/AlphaChairArduino.ino
@@ -9,16 +9,17 @@

 Thread fsrThread = Thread(); // For measuring Pressure data in other thread

-//  Mosfet
-int MOSFET_C1 = 6;
+//  Mosfet channel
+int MOSFET_C1 = 10;
 int MOSFET_C2 = 7;
-
 //  UNO board
 int INB = 8;
 int INA = 9;
 //  Analog read
-int PRESSURE = A0;
-int TEMPERATURE = A1;
+int PRESSURE_0 = A0;
+int PRESSURE_1 = A1;
+int PRESSURE_2 = A2;
+int PRESSURE_3 = A3;

 bool isTMPOn = false;

@@ -33,6 +34,7 @@
   pinMode(INB,OUTPUT);
   pinMode(MOSFET_C1, OUTPUT);
   pinMode(MOSFET_C2, OUTPUT);
+  digitalWrite(MOSFET_C1,LOW);
   fsrThread.onRun(readPressure);
   fsrThread.enabled = false;
   fsrThread.setInterval(1000);
@@ -44,7 +46,9 @@
   String response = "";
   while(BTSerial.available()){
     char tempChar = BTSerial.read();
-    if(tempChar != '\n')
+    if(tempChar == '\n'){
+      break;
+    }
     response.concat(tempChar);
   }
   if(response.length()>1){
@@ -52,7 +56,6 @@
     response = response.substring(0,1);
     MAX_TMP = resInt.toInt();
   }
-
   if(response.equals(PPR_ON)){
     Serial.println(response);
     digitalWrite(INA,HIGH);
@@ -73,10 +76,11 @@
   }else if(response.equals(TMP_OFF)){
     Serial.println(response);
     MAX_TMP = 0;
+    digitalWrite(MOSFET_C1,LOW);
     isTMPOn = false;
   }

-  if(isTMPOn){
+  if(isTMPOn && MAX_TMP >0){
     readTmp();
   }

@@ -86,20 +90,22 @@

 // Runnable for fsrThread
 void readPressure(){
-  int fsrData = analogRead(PRESSURE);
-  Serial.println("Pressure : "+ String(fsrData));
-  BTSerial.println(fsrData);
+  int frontRight = analogRead(PRESSURE_0)*5;
+  int frontLeft = analogRead(PRESSURE_1)*5;
+  int backRight = analogRead(PRESSURE_2)*5;
+  int backLeft = analogRead(PRESSURE_3)*5;
+  Serial.println("0 : "+ String(frontRight));
+  Serial.println("1 : "+ String(frontLeft));
+  Serial.println("2 : "+ String(backRight));
+  Serial.println("3 : "+ String(backLeft));
+
+  if(frontRight>2000){
+    BTSerial.println("right leg side");
+  }
 }

 void readTmp(){
-  float analogTmp = (float)analogRead(TEMPERATURE)*5/1024;
-  float currTmp = 100*(analogTmp-0.5);
-  if(currTmp < MAX_TMP){
     digitalWrite(MOSFET_C1,HIGH);
-    digitalWrite(MOSFET_C2,HIGH);
-  }else{
-    digitalWrite(MOSFET_C1,LOW);
-    digitalWrite(MOSFET_C2,LOW);
-  }
+    Serial.println(String(MAX_TMP));
 }


20150217.1251

--- cmdMULTIsens/src/sketch.ino
+++ cmdMULTIsens/src/sketch.ino
@@ -66,7 +66,7 @@
         Serial.println("D | d : DHT22 calculated Dewpoint");
         Serial.println("E | e : DHT22 calculated Dewpoint2");
         Serial.println("H | h : DHT22 humidity");
-        Serial.println("I | i : DHT22 calculated Heat index")
+        Serial.println("I | i : DHT22 calculated Heat index");
         Serial.println("R | r : DHT22 all sensor data (S,H,D,E,I)");
         Serial.println("S | s : DHT22 temperature");
         Serial.println("T | t : TMP36 temperature");
@@ -92,7 +92,7 @@
       case 'I':
       case 'i':
         // DHT calculated HeatIndex
-        Value = computeHeatIndex(dht.readTemperature(), dht.readHumidity());
+        Value = dht.computeHeatIndex(dht.readTemperature(), dht.readHumidity());
         Serial.print(Value);
         break;
       case 'A':


Add 'valid_app' flag to EEPROM so we don't load application if it's invalid

--- libraries/BLE/examples/ble_uart_project_with_dfu_template/bootloader_setup.ino
+++ libraries/BLE/examples/ble_uart_project_with_dfu_template/bootloader_setup.ino
@@ -92,6 +92,7 @@
   uint16_t crc_local;

   /* Data to be stored */
+  uint8_t valid_app = 1;
   uint8_t valid_ble = 1;
   uint8_t *p = (uint8_t *) &(state->aci_pins);
   uint8_t pipes[] = {
@@ -103,13 +104,14 @@
   uint8_t interval_h = (uint8_t) adv_interval >> 8;
   uint8_t interval_l = (uint8_t) adv_interval >> 0;

-  /* len = valid data flag + pin struct + credit byte + pipe array +
+  /* len = valid app flag + valid data flag + pin struct + credit byte + pipe array +
    * timeout + interval + crc
    */
-  uint8_t len = 1 + sizeof(aci_pins_t) + 1 + sizeof(pipes) + 6;
+  uint8_t len = 2 + sizeof(aci_pins_t) + 1 + sizeof(pipes) + 6;

   /* Compute CRC16 */
-  crc_local = crc_16_ccitt(0xFFFF, &valid_ble, 1);
+  crc_local = crc_16_ccitt(0xFFFF, &valid_app, 1);
+  crc_local = crc_16_ccitt(crc_local, &valid_ble, 1);
   crc_local = crc_16_ccitt(crc_local, p, sizeof(aci_pins_t));
   crc_local = crc_16_ccitt(crc_local, &(state->data_credit_total), 1);
   crc_local = crc_16_ccitt(crc_local, pipes, sizeof(pipes));
@@ -138,6 +140,7 @@
    */
   addr = 0;

+  EEPROM.write(addr++, valid_app);
   EEPROM.write(addr++, valid_ble);

   for (uint8_t i = 0; i < sizeof(aci_pins_t); i++)


Update GPRS_LoopHandle.ino

Update GPRS_LoopHandle.ino

--- example/GPRS_LoopHandle/GPRS_LoopHandle.ino
+++ example/GPRS_LoopHandle/GPRS_LoopHandle.ino
@@ -27,6 +27,7 @@

 void setup() {
   Serial.begin(9600);
+  while(!Serial);;
   Serial.println("GPRS - LoopHandle Test...");
   gprs.preInit();
   while(0 != gprs.init()) {


Update IRrecvDumpV2.ino

Update IRrecvDumpV2.ino

- Cleaned up layout of output, removed trailing commas
- buffer sizes are now correct
- no need to add 0 for space at end, as sendRAW takes care of this

--- examples/IRrecvDumpV2/IRrecvDumpV2.ino
+++ examples/IRrecvDumpV2/IRrecvDumpV2.ino
@@ -90,7 +90,7 @@
 {
   // Print Raw data
   Serial.print("Timing[");
-  Serial.print(results->rawlen, DEC);
+  Serial.print(results->rawlen-1, DEC);
   Serial.println("]: ");

   for (int i = 1;  i < results->rawlen;  i++) {
@@ -106,7 +106,7 @@
       if (x < 1000)  Serial.print(" ") ;
       if (x < 100)   Serial.print(" ") ;
       Serial.print(x, DEC);
-      Serial.print(", ");
+      if (i < results->rawlen-1) Serial.print(", "); //',' not needed for last one
     }
     if (!(i % 8))  Serial.println("");
   }
@@ -121,18 +121,18 @@
   // Start declaration
   Serial.print("unsigned int  ");          // variable type
   Serial.print("rawData[");                // array name
-  Serial.print(results->rawlen + 1, DEC);  // array size
+  Serial.print(results->rawlen - 1, DEC);  // array size
   Serial.print("] = {");                   // Start declaration

   // Dump data
   for (int i = 1;  i < results->rawlen;  i++) {
     Serial.print(results->rawbuf[i] * USECPERTICK, DEC);
-    Serial.print(",");
+    if ( i < results->rawlen-1 ) Serial.print(","); // ',' not needed on last one
     if (!(i & 1))  Serial.print(" ");
   }

   // End declaration
-  Serial.print("0};");  // Turn LED off at the end
+  Serial.print("};");  //

   // Comment
   Serial.print("  // ");


Comment out power pins in ADXL example code.

With a note that you should uncomment them if you want to power the
ADXL335 (on Adafruit breakout) by plugging it directly into the Arduino.

--- Arduino/ADXL335/ADXL335.ino
+++ Arduino/ADXL335/ADXL335.ino
@@ -1,9 +1,14 @@
-int vinpin = A0;
-int voutpin = A1;
-int gndpin = A2;
 int zpin = A3;
 int ypin = A4;
 int xpin = A5;
+
+// Uncomment the following lines if you're using an ADXL335 on an
+// Adafruit breakout board (https://www.adafruit.com/products/163)
+// and want to plug it directly into (and power it from) the analog
+// input pins of your Arduino board.
+//int vinpin = A0;
+//int voutpin = A1;
+//int gndpin = A2;

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


added new function to receiver

added new function to receiver

now it turns outputs 0 when input is 0

--- Modules/Sensor/Receiver/ArduinoCodes/ReceiverATmega/ReceiverATmega.ino
+++ Modules/Sensor/Receiver/ArduinoCodes/ReceiverATmega/ReceiverATmega.ino
@@ -57,9 +57,8 @@
 int output_val = 0;
 void loop()
 {
- //shouldn't do anything when input voltage is 0

-  if(cutAndMap(input.filteredAnalogRead(AVERAGE),50,975,0,1023) <= 1){
+  if(cutAndMap(input.filteredAnalogRead(AVERAGE),50,975,0,1023) <= 1){        //shouldn't do anything when input voltage is 0
     output_val = 0;
   }


verbessert display time

verbessert display time

--- Door_status/Door_status.ino
+++ Door_status/Door_status.ino
@@ -8,6 +8,10 @@
   digitalWrite(10,LOW);
   return pulseIn(9,HIGH);
 }
+
+  boolean state = true;
+  unsigned long d;
+  int t;

 void setup() {
   pinMode(10,OUTPUT);
@@ -21,15 +25,26 @@
 }

 void loop() {
-  unsigned long d;
   d = ultras()/58;
   if (d > 3)
   {
+    if (state)
+    {
+      t = millis();
+    }
     lcd.print("Door is open!   ");
+    lcd.setCursor(4,1);
+    lcd.print("before ");
+    lcd.print((millis()-t)/1000);
+    lcd.print("s");
+    state = false;
   }
   else
   {
     lcd.setCursor(8,0);
     lcd.print("closed!");
+    lcd.setCursor(4,1);
+    lcd.print("<Arduino>   ");
+    state = true;
   }
 }


formatting

formatting

--- WVO_Controller_0.6.3/WVO_Controller_0.6.3.ino
+++ WVO_Controller_0.6.3/WVO_Controller_0.6.3.ino
@@ -292,22 +292,22 @@
     currentMillis = millis();
     //Serial.println(previousMillis);
     //Serial.println(currentMillis);
-    countdown = (purgeTime - (currentMillis - previousMillis) / 1000); 		// if time since purge started is less than purgeSetTime, keep running purge
-    if (countdown != oldCountdown)						// if old and new countdown values are different, write countdown to screen
-    {
-      if (countdown >= 10)							// if countdown is < 10, center countdown value on screen
+    countdown = (purgeTime - (currentMillis - previousMillis) / 1000);     // if time since purge started is less than purgeSetTime, keep running purge
+    if (countdown != oldCountdown)            // if old and new countdown values are different, write countdown to screen
+    {
+      if (countdown >= 10)              // if countdown is < 10, center countdown value on screen
       {
         Tft.fillRectangle(90, 140, 70, 40, BLACK);
         Tft.drawNumber(countdown, 90, 140, 5, WHITE);
       }
-      else									// otherwise, countdown is greater than 9, and countdown is centered
+      else                  // otherwise, countdown is greater than 9, and countdown is centered
       {
         Tft.fillRectangle(90, 140, 60, 40, BLACK);
         Tft.drawNumber(countdown, 100, 140, 5, WHITE);
       }
     }
     oldCountdown = countdown;
-    if ((currentMillis - previousMillis > purgeTime * 1000UL))		// if the purge time has ran longer than purgeSetTime,
+    if ((currentMillis - previousMillis > purgeTime * 1000UL))    // if the purge time has ran longer than purgeSetTime,
       // run returnOff which will turn off the Return valve
     {
       p.x = 0;


-arduino light work

-arduino light work

--- arduino/src/robotLEDControllerrev2/robotLEDControllerrev2.ino
+++ arduino/src/robotLEDControllerrev2/robotLEDControllerrev2.ino
@@ -119,24 +119,24 @@
       //    clearLeds();
     }
     else if (incomingByte == 98){ //b
-      dataRecieved[0] = true;
-      dataRecieved[1] = true;
-      dataRecieved[2] = false;
-      dataRecieved[3] = true;
-      //    setRed();
-    }
-    else if (incomingByte == 99){ //c
       dataRecieved[0] = false;
       dataRecieved[1] = false;
       dataRecieved[2] = false;
       dataRecieved[3] = true;
-      //    setGreen();
-    }
-    else if (incomingByte == 100){ //d
+      //    setRed();
+    }
+    else if (incomingByte == 99){ //c
       dataRecieved[0] = false;
       dataRecieved[1] = false;
       dataRecieved[2] = true;
-      dataRecieved[3] = true;
+      dataRecieved[3] = false;
+      //    setGreen();
+    }
+    else if (incomingByte == 100){ //d
+      dataRecieved[0] = false;
+      dataRecieved[1] = true;
+      dataRecieved[2] = true;
+      dataRecieved[3] = false;
       //    shootAndCollect();
     }
     else if (incomingByte == 101){ //e


:bug: :racehorse: Change example to use event based Wi-Fi connection

--- examples/FullyFeatured/FullyFeatured.ino
+++ examples/FullyFeatured/FullyFeatured.ino
@@ -1,10 +1,45 @@
 #include <ESP8266WiFi.h>
+#include <Ticker.h>
 #include <AsyncMqttClient.h>

+#define WIFI_SSID "My_Wi-Fi"
+#define WIFI_PASSWORD "my-awesome-password"
+
+#define MQTT_HOST IPAddress(192, 168, 1, 10)
+#define MQTT_PORT 1883
+
 AsyncMqttClient mqttClient;
+Ticker mqttReconnectTimer;
+
+WiFiEventHandler wifiConnectHandler;
+WiFiEventHandler wifiDisconnectHandler;
+Ticker wifiReconnectTimer;
+
+void connectToWifi() {
+  wifiReconnectTimer.detach();
+  Serial.println("Connecting to Wi-Fi...");
+  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
+}
+
+void onWifiConnect(const WiFiEventStationModeGotIP& event) {
+  Serial.println("Connected to Wi-Fi.");
+  connectToMqtt();
+}
+
+void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) {
+  Serial.println("Disconnected from Wi-Fi.");
+  mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
+  wifiReconnectTimer.attach(2, connectToWifi);
+}
+
+void connectToMqtt() {
+  Serial.println("Connecting to MQTT...");
+  mqttReconnectTimer.detach();
+  mqttClient.connect();
+}

 void onMqttConnect(bool sessionPresent) {
-  Serial.println("** Connected to the broker **");
+  Serial.println("Connected to MQTT.");
   Serial.print("Session present: ");
   Serial.println(sessionPresent);
   uint16_t packetIdSub = mqttClient.subscribe("test/lol", 2);
@@ -21,13 +56,16 @@
 }

 void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
-  Serial.println("** Disconnected from the broker **");
-  Serial.println("Reconnecting to MQTT...");
-  mqttClient.connect();
+  Serial.println("Disconnected from MQTT.");
+
+  if (WiFi.isConnected()) {
+    Serial.println("Connecting to MQTT...");
+    mqttReconnectTimer.attach(2, connectToMqtt);
+  }
 }

 void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
-  Serial.println("** Subscribe acknowledged **");
+  Serial.println("Subscribe acknowledged.");
   Serial.print("  packetId: ");
   Serial.println(packetId);
   Serial.print("  qos: ");
@@ -35,13 +73,13 @@
 }

 void onMqttUnsubscribe(uint16_t packetId) {
-  Serial.println("** Unsubscribe acknowledged **");
+  Serial.println("Unsubscribe acknowledged.");
   Serial.print("  packetId: ");
   Serial.println(packetId);
 }

 void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
-  Serial.println("** Publish received **");
+  Serial.println("Publish received.");
   Serial.print("  topic: ");
   Serial.println(topic);
   Serial.print("  qos: ");
@@ -59,7 +97,7 @@
 }

 void onMqttPublish(uint16_t packetId) {
-  Serial.println("** Publish acknowledged **");
+  Serial.println("Publish acknowledged.");
   Serial.print("  packetId: ");
   Serial.println(packetId);
 }
@@ -68,17 +106,9 @@
   Serial.begin(115200);
   Serial.println();
   Serial.println();
-  WiFi.persistent(false);
-  WiFi.mode(WIFI_STA);
-  Serial.print("Connecting to Wi-Fi");
-  WiFi.begin("WiFi_SSID", "Wi-Fi password");

-  while (WiFi.status() != WL_CONNECTED) {
-    delay(500);
-    Serial.print(".");
-  }
-
-  Serial.println(" OK");
+  wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);
+  wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);

   mqttClient.onConnect(onMqttConnect);
   mqttClient.onDisconnect(onMqttDisconnect);
@@ -86,11 +116,10 @@
   mqttClient.onUnsubscribe(onMqttUnsubscribe);
   mqttClient.onMessage(onMqttMessage);
   mqttClient.onPublish(onMqttPublish);
-  mqttClient.setServer(IPAddress(192, 168, 1, 20), 1883);
-  mqttClient.setKeepAlive(5).setCleanSession(false).setWill("topic/online", 2, true, "no").setCredentials("username", "password").setClientId("myDevice");
-  Serial.println("Connecting to MQTT...");
-  mqttClient.connect();
+  mqttClient.setServer(MQTT_HOST, MQTT_PORT);
+
+  connectToWifi();
 }

 void loop() {
-}
+}


Fixed some bugs. Driving and rotating bucket work. Need to correct actuating.

--- src/ExcavatorDriverROS/ExcavatorDriverROS.ino
+++ src/ExcavatorDriverROS/ExcavatorDriverROS.ino
@@ -162,7 +162,7 @@
   for (int motorID = 0; motorID < NUM_EXCAVATOR_MOTORS; ++motorID) {
     driveForwards(motorID, 0);
   }
-  currentExcavatorCommand.drive_speed = 0;
+  excavatorStatus.drive_speed = 0;
 }

 /**
@@ -221,34 +221,25 @@
   delayMicroseconds(1000);
 }

-
-
-
-// Function that takes a SIGNED speed value and converts it to an UNSIGNED drive command.
-void helpDrive(char motorID, char speed)
-{
-  if (speed < 0)
-  {
-    driveBackwards(motorID, -speed);
-  }
-  else
-  {
-    driveForwards(motorID, speed);
-  }
-}
-
 // Function to drive the wheels
 void driveAllMotors()
 {
-  if(currentStatus == START_DRIVING)
-  {
-    helpDrive(FRONT_LEFT_DRIVE_MOTOR_ID, currentExcavatorCommand.drive_speed);
-    helpDrive(FRONT_RIGHT_DRIVE_MOTOR_ID, currentExcavatorCommand.drive_speed);
-    helpDrive(BACK_LEFT_DRIVE_MOTOR_ID, currentExcavatorCommand.drive_speed);
-    helpDrive(BACK_RIGHT_DRIVE_MOTOR_ID, currentExcavatorCommand.drive_speed);
-    excavatorStatus.drive_speed = currentExcavatorCommand.drive_speed;
-    currentStatus = IS_DRIVING;
-  }
+  if (currentExcavatorCommand.drive_speed < 0){
+    for (int i = 0; i < 4; ++i)
+    {
+       driveForwards(i, -currentExcavatorCommand.drive_speed);
+       excavatorStatus.drive_speed = currentExcavatorCommand.drive_speed;
+    }
+  }
+  else{
+    for (int i = 0; i < 4; ++i)
+    {
+      driveBackwards(i, currentExcavatorCommand.drive_speed);
+      excavatorStatus.drive_speed = currentExcavatorCommand.drive_speed;
+    }
+  }
+
+  currentStatus = IS_DRIVING;
 }

@@ -516,6 +507,8 @@
   excavatorNode.subscribe(commandSubscriber);
   excavatorNode.subscribe(conveyorSubscriber);
   excavatorNode.subscribe(setActualStepCount);
+  excavatorNode.advertise(pubexcavatorStatus);
+  excavatorNode.advertise(pubDebug);
   setupExcavatorStatus();

   pinMode(DIRECTION_PIN, OUTPUT);
@@ -545,14 +538,14 @@
     //TODO: This will never happen right now, may want for competition though
     return;
   }
-
+
   //Currently stopped, don't do anything.
   // ASSUMES the robot is stopped when currentStatus is set to STOPPED.
   if (currentStatus == STOPPED) {
     // do nothing
   }

-
+
   if(currentConveyorStatus == START_ROTATING_CONVEYOR){
     conveyorStopTime = millis() + (long)conveyorRotationTime*1000;
     driveConveyor();
@@ -586,11 +579,11 @@

   if (currentStatus == ACTUATING) {
     if(needsToActuate(currentExcavatorCommand.excavation_height)){
-       moveToPercent(currentExcavatorCommand.excavation_height);
-       excavatorStatus.excavate_speed = toPercent(currentSteps);
+      moveToPercent(currentExcavatorCommand.excavation_height);
+      excavatorStatus.excavate_speed = toPercent(currentSteps);
     }
     else{
-       currentStatus = START_DIGGING;
+      currentStatus = START_DIGGING;
     }
   }

@@ -629,3 +622,4 @@

+


renomeado função Soldas para Vertical

renomeado função Soldas para Vertical

--- EMP-B-Due.ino
+++ EMP-B-Due.ino
@@ -23,9 +23,7 @@
 #define NomeMandibula "Mandibula" // Ciclo da Mandíbula
 #define NomeFaca "Faca" // Ciclo da Faca
 #define NomeRefrigeracao "Refrigeracao" // Ciclo da Refrigeração
-#define NomeSoldas "Soldas" // Ciclo das Soldas Vertical e Horizontal
-#define NomeSoldaVertical "Solda Vertical"
-#define NomeSoldaHorizontal "Solda Horizontal"
+#define NomeVertical "Solda Vertical" // Ciclo da Solda Vertical
 #define NomeSoldaDatador "Solda Datador"
 // ENTRADAS
 const byte bt_geral = 22;        // Entrada do botão de Liga/Desliga Geral
@@ -48,7 +46,7 @@
 const byte faca = 42; // Saída da Faca
 const byte refrigeracao = 44; // Saída da Refrigeração
 const byte datador = 46; // Saída do Datador
-const byte soldas = 48; // Saída das Soldas Vertical e Horizontal
+const byte vertical = 48; // Saída da Solda Vertical
 // SAÍDAS PWM
 const byte solda_vertical_PWM = 33; // Saída da Solda Vertical
 const byte solda_horizontal_PWM = 35; // Saída da Solda Horizontal
@@ -72,10 +70,10 @@
 const unsigned long fim_refrigeracao = 1450; // Tempo de saída da função Refrigeração
 // DATADOR
 const unsigned long inicio_datador = 0; // Tempo de entrada da função Datador
-const unsigned long fim_datador = 700; // Tempo de saída da função Datador
+const unsigned long fim_datador = 400; // Tempo de saída da função Datador
 // SOLDAS VERTICAL E HORIZONTAL
-const unsigned long inicio_soldas = 0; // Tempo de entrada da função Soldas Horizontal e Vertical
-const unsigned long fim_soldas = 400; // Tempo de saída da função Soldas Horizontal e Vertical
+const unsigned long inicio_vertical = 0; // Tempo de entrada da função Solda Vertical
+const unsigned long fim_vertical = 400; // Tempo de saída da função Solda Vertical

 // REMOVER >>
 const byte saida_teste = 3;
@@ -143,9 +141,9 @@
 // DATADOR
 unsigned long ti_datador = inicio_datador;
 unsigned long tf_datador = fim_datador;
-// SOLDAS VERTICAL E HORIZONTAL
-unsigned long ti_soldas = inicio_soldas;
-unsigned long tf_soldas = fim_soldas;
+// SOLDA VERTICAL
+unsigned long ti_vertical = inicio_vertical;
+unsigned long tf_vertical = fim_vertical;

 void setup() {
   Serial.begin(9600);
@@ -176,7 +174,7 @@
   pinMode(faca, SAIDA);
   pinMode(refrigeracao, SAIDA);
   pinMode(datador, SAIDA);
-  pinMode(soldas, SAIDA);
+  pinMode(vertical, SAIDA);
   // ESTADO INICIAL DAS SAÍDAS
   resetCompleto();

@@ -228,7 +226,7 @@
     funcaoSegura(faca, NomeFaca, ti_faca, tf_faca, sensor_mandibula);
     funcaoBloqueante(refrigeracao, NomeRefrigeracao, ti_refrigeracao, tf_refrigeracao);
     funcaoComLiberacao(datador, NomeDatador, ti_datador, tf_datador, datador_ligado);
-    funcaoSimples(soldas, NomeSoldas, ti_soldas, tf_soldas);
+    funcaoSimples(vertical, NomeVertical, ti_vertical, tf_vertical);
   }
   funcaoReset();
 }
@@ -318,8 +316,8 @@
     ajustaCiclo(&tf_refrigeracao, fim_refrigeracao);
     ajustaCiclo(&ti_datador, inicio_datador);
     ajustaCiclo(&tf_datador, fim_datador);
-    ajustaCiclo(&ti_soldas, inicio_soldas);
-    ajustaCiclo(&tf_soldas, fim_soldas);
+    ajustaCiclo(&ti_vertical, inicio_vertical);
+    ajustaCiclo(&tf_vertical, fim_vertical);
   }
 }

@@ -510,7 +508,7 @@
   desligaFuncao(faca, NomeFaca);
   desligaFuncao(refrigeracao, NomeRefrigeracao);
   desligaFuncao(datador, NomeDatador);
-  desligaFuncao(soldas, NomeSoldas);
+  desligaFuncao(vertical, NomeVertical);
 }

 void resetCompleto() {
@@ -529,7 +527,7 @@
   desliga(faca);
   desliga(refrigeracao);
   desliga(datador);
-  desliga(soldas);
+  desliga(vertical);

   desliga(solda_vertical_PWM);
   desliga(solda_horizontal_PWM);


Change name of variable keeping track of whether initial, do-only-once instructions were already called--to make it more readable. Also move true assignment to inside that conditional block.

--- Dremelfuge.ino
+++ Dremelfuge.ino
@@ -126,14 +126,14 @@

     case Mode::SPINNING:
     {
-      static bool init = false;
-      if(!init)
+      static bool changedUIString = false;    //*** because changedUIString is static, its state will always persist
+      if(!changedUIString)
       {
         lcd.setCursor(0, 1);
         lcd.print(F("Finished in: "));
+        changedUIString = true;               //*** this block becomes unreachable after this, because this true value is remembered
       }

-      init = true;
       unsigned long secondsLeft = (countdown - (millis() - spinningStartTime))/1000;  //*** save RAM AND flash memory by only doing this calculation once per case in loop()
       analogWrite(MOTOR_PIN, motorSpeed);

@@ -144,7 +144,7 @@
       if(wpb.pressed() || secondsLeft == 0)
       {
         digitalWrite(MOTOR_PIN, LOW);
-        init = false;
+        changedUIString = false;
         mode = Mode::SETTING_TIME;
       }
       break;


1.0 RC6

1.0 RC6

-added parameters allowing you to declare MPU6050 blade axis orientation
- [RGB USERS] added the possibility to choose from a set of colors YOU
defined

--- Lightsaber.ino
+++ Lightsaber.ino
@@ -43,6 +43,14 @@
 #endif

 /*
+ * MPU6050 device ORIENTATION
+ * Choose which MPU's axis is parallel to blade axis
+ */
+//#define BLADE_X
+#define BLADE_Y
+//#define BLADE_Z
+
+/*
  * DEFINED PINS
  * Modify to match your project setup
  * DO NOT USE PINS:
@@ -59,18 +67,39 @@
 #define LEDSTRING4 			9
 #define LEDSTRING5 			10
 #define LEDSTRING6 			11
-#ifdef LUXEON
+
+#ifdef LUXEON
+/*
+ * MY_OWN_COLORS
+ * If you want to manually specify your own colors
+ */
+#define MY_OWN_COLORS
+//#define FIXED_RANGE_COLORS
+
+#define LED_RED 			3
+#define LED_GREEN 			5
+#define LED_BLUE 			6
+
+#define BLASTER_FLASH_TIME  5
+#define CLASH_BLINK_TIME    15
+#endif
+
+/* FOR RGB USERS
+ * How do you want to handle your colors ?
+ */
+# ifdef MY_OWN_COLORS
+/* COLORS
+ * Number of colors YOU defined in getColor function
+ */
+#define COLORS		 		3
+#endif
+#ifdef FIXED_RANGE_COLORS
 /* COLORS
  * Number of colors to chose from
  * Range : 6<->600
+ * Default: 48
  */
 #define COLORS		 		48
-#define LED_RED 			3
-#define LED_GREEN 			5
-#define LED_BLUE 			6
-
-#define BLASTER_FLASH_TIME  5
-#define CLASH_BLINK_TIME    15
 #endif

 #define DFPLAYER_RX			8
@@ -104,6 +133,7 @@
  * WARNING ! A too high value may burn your leds. Please make your maths !
  */
 #define MAX_BRIGHTNESS		200
+

 /*
  * DEBUG PARAMETERS
@@ -522,12 +552,31 @@
 		 * We detect swings as hilt's orientation change
 		 * since IMUs sucks at determining relative position in space
 		 */
+#ifdef BLADE_Z
 		if (abs(quaternion.w) > storage.swingTreshold and !swingSuppress
 				and aaWorld.z < 0
 				and abs(quaternion.z) < (9 / 2) * storage.swingTreshold
 				and (abs(quaternion.x) > 3 * storage.swingTreshold
-						or abs(quaternion.y) > 3 * storage.swingTreshold)	// We don't want to treat blade Z axe rotations as a swing
-				) {
+						or abs(quaternion.y) > 3 * storage.swingTreshold)// We don't want to treat blade Z axe rotations as a swing
+		)
+#endif
+#ifdef BLADE_Y
+		if (abs(quaternion.w) > storage.swingTreshold and !swingSuppress
+				and aaWorld.y < 0
+				and abs(quaternion.y) < (9 / 2) * storage.swingTreshold
+				and (abs(quaternion.x) > 3 * storage.swingTreshold
+						or abs(quaternion.z) > 3 * storage.swingTreshold)// We don't want to treat blade Y axe rotations as a swing
+				)
+#endif
+#ifdef BLADE_X
+				if (abs(quaternion.w) > storage.swingTreshold and !swingSuppress
+						and aaWorld.x < 0
+						and abs(quaternion.x) < (9 / 2) * storage.swingTreshold
+						and (abs(quaternion.z) > 3 * storage.swingTreshold
+								or abs(quaternion.y) > 3 * storage.swingTreshold)// We don't want to treat blade X axe rotations as a swing
+				)
+#endif
+				{
 			/*
 			 *  THIS IS A SWING !
 			 */
@@ -545,11 +594,29 @@
 			printQuaternion(quaternion, 1);
 #endif

-		} else if (abs(quaternion.w) > storage.swingTreshold and !swingSuppress
+		}
+#ifdef BLADE_Z
+		else if (abs(quaternion.w) > storage.swingTreshold and !swingSuppress
 				and (aaWorld.z > 0
 						and abs(quaternion.z) > (13 / 2) * storage.swingTreshold
 						and abs(quaternion.x) < 3 * storage.swingTreshold
 						and abs(quaternion.y) < 3 * storage.swingTreshold)// We specifically  treat blade Z axe rotations as a swing
+#endif
+#ifdef BLADE_Y
+		else if (abs(quaternion.w) > storage.swingTreshold and !swingSuppress
+				and (aaWorld.y > 0
+						and abs(quaternion.y) > (13 / 2) * storage.swingTreshold
+						and abs(quaternion.x) < 3 * storage.swingTreshold
+						and abs(quaternion.z) < 3 * storage.swingTreshold)// We specifically  treat blade Z axe rotations as a swing
+#endif
+#ifdef BLADE_X
+				else if (abs(quaternion.w) > storage.swingTreshold and !swingSuppress
+						and (aaWorld.x > 0
+								and abs(quaternion.x) > (13 / 2) * storage.swingTreshold
+								and abs(quaternion.z) < 3 * storage.swingTreshold
+								and abs(quaternion.y) < 3 * storage.swingTreshold)// We specifically  treat blade Z axe rotations as a swing
+#endif
+
 				) {
 			/*
 			 *  THIS IS A WRIST TWIST !
@@ -568,7 +635,6 @@
 				swingSuppress = SWING_SUPPRESS * 10;
 				delay(OPERATING_DELAY * 3);
 			}
-
 #ifdef LS_SWING_DEBUG
 			Serial.print(F("WRIST\t s="));
 			Serial.print(swingSuppress);
@@ -777,7 +843,7 @@
 			case 2:
 			confMenuStart(9);

-			confParseValue(storage.mainColor, 0, COLORS-1, 1);
+			confParseValue(storage.mainColor, 0, COLORS - 1, 1);

 			if (modification) {

@@ -792,7 +858,7 @@
 			case 3:
 			confMenuStart(10);

-			confParseValue(storage.clashColor, 0, COLORS-1, 1);
+			confParseValue(storage.clashColor, 0, COLORS - 1, 1);

 			if (modification) {

@@ -947,6 +1013,7 @@
 #endif
 	if (actionMode) {
 		if (soundFont.getForce()) {
+
 			// Some Soundfont may not have Force sounds
 			repeat = false;
 			mp3.playTrackFromDir(soundFont.getForce(), soundFont.getFolder());
@@ -1257,6 +1324,50 @@
 	}
 } //lightFlicker

+inline void lightChangeColor(uint8_t color, bool lightup) {
+	getColor(color);
+	if (lightup) {
+		for (uint8_t i = 0; i <= 2; i++) {
+			analogWrite(ledPins[i],
+					MAX_BRIGHTNESS * currentColor[i] / 100);
+		}
+	}
+} //lightChangeColor
+#endif
+
+#ifdef MY_OWN_COLORS
+inline void getColor(uint8_t id) {
+	currentColor[3] = id;
+	switch (id) {
+		case 0:
+		//Red
+		currentColor[0] = 100;
+		currentColor[1] = 0;
+		currentColor[2] = 0;
+		break;
+		case 1:
+		//Green
+		currentColor[0] = 0;
+		currentColor[1] = 100;
+		currentColor[2] = 0;
+		break;
+		case 2:
+		//Blue
+		currentColor[0] = 0;
+		currentColor[1] = 0;
+		currentColor[2] = 100;
+		break;
+		default:
+		// White?
+		currentColor[0] = 100;
+		currentColor[1] = 100;
+		currentColor[2] = 100;
+		break;
+	}
+} //getColor
+#endif
+
+#ifdef FIXED_RANGE_COLORS
 inline void getColor(uint8_t id) {
 	uint8_t tint = (COLORS / 6);
 	uint8_t step = 100 / tint;
@@ -1293,17 +1404,7 @@
 		currentColor[2] = 100 - (step * (id % tint));
 	}

-}
-
-inline void lightChangeColor(uint8_t color, bool lightup) {
-	getColor(color);
-	if (lightup) {
-		for (uint8_t i = 0; i <= 2; i++) {
-			analogWrite(ledPins[i],
-					MAX_BRIGHTNESS * currentColor[i] / 100);
-		}
-	}
-} //lightChangeColor
+} //getColor
 #endif

 // ====================================================================================
@@ -1501,14 +1602,14 @@
 			Serial.print(F("COLOR1\nCur:"));
 			Serial.println(storage.mainColor);
 			lightChangeColor(storage.mainColor, true);
-			value=storage.mainColor;
+			value = storage.mainColor;
 			break;
 			case 10:
 			lightOff(ledPins, false);
 			Serial.print(F("COLOR2\nCur:"));
 			Serial.println(storage.clashColor);
 			lightChangeColor(storage.clashColor, true);
-			value=storage.clashColor;
+			value = storage.clashColor;
 			break;
 			case 11:
 			lightOff(ledPins, false);


Add temp option for hardcoded adress

Add temp option for hardcoded adress

--- sensorSlave/sensorSlave.ino
+++ sensorSlave/sensorSlave.ino
@@ -3,7 +3,7 @@
 #define ARRAY_LENGTH(x)  (sizeof(x) / sizeof((x)[0]))

 //#define LOG_SERIAL
-
+#define HARDCODEDADRESS 8
 //TODO
 //
 // store read frequency in EEPROM
@@ -30,6 +30,7 @@

 void setup()
 {
+#ifndef HARDCODEDADRESS
   int i2cAddress = 0;
   for (int i=0;i<ARRAY_LENGTH(addressPins);i++){
     pinMode(addressPins[i], INPUT_PULLUP);
@@ -43,6 +44,9 @@
   }

   Wire.begin(i2cAddress);
+#else
+  Wire.begin(HARDCODEDADRESS);
+#endif

   Wire.onReceive(receiveEvent);
   Wire.onRequest(requestEvent);


Update rfid_default_keys.ino

Update rfid_default_keys.ino

Added new pin layout info; standardizing format and info


Actualizacion codigo potenciometro de luces ritmnicas

--- luces_ritmicas_potenciometro/luces_ritmicas_potenciometro.ino
+++ luces_ritmicas_potenciometro/luces_ritmicas_potenciometro.ino
@@ -1,68 +1,47 @@
-/*Luces ritmicas potenciometro
-* Copyright: codigoelectronica.com
-* Author: Oscar Fernandez
+/*Luces ritmicas potenciómetro
+* Copyright: codigoelectronica.com <codioelectronica@gmail.com>
+* Author: Oscar Fernandez Alzate <oscarfdzalz@gmail.com>
 * License: MIT
 */
+//Pines para los leds
+const int pins[8] = {2,3,4,5,6,7,8,9};
+
+//Secuencia de los leds
+const byte vumeter[9] = {0b00000000,  //0
+                          0b00000001, //1
+                          0b00000011, //2
+                          0b00000111, //3
+                          0b00001111, //4
+                          0b00011111, //5
+                          0b00111111, //6
+                          0b01111111, //7
+                          0b11111111  //8
+                        };
+
 void setup() {
-  //Iniciamos puerto serial
-  Serial.begin(9600);
-  pinMode(2, OUTPUT);
-  pinMode(3, OUTPUT);
-  pinMode(4, OUTPUT);
-  pinMode(5, OUTPUT);
-  pinMode(6, OUTPUT);
-  pinMode(7, OUTPUT);
+  //Ponemos los pines como salida
+  for(int i = 0; i < 8; i++) {
+    pinMode(pins[i], OUTPUT);
+  }
 }

 void loop() {
-  //Leemos puesrto analogo
-  int sensorValue = analogRead(A0);
-  //Calculamos voltaje
-  float voltaje = (sensorValue*5.0)/1024;
-  //Verificamos el voltaje para encender los leds
-  if(voltaje < 0.8){
-    digitalWrite(2, HIGH);
-    digitalWrite(3, LOW);
-    digitalWrite(4, LOW);
-    digitalWrite(5, LOW);
-    digitalWrite(6, LOW);
-    digitalWrite(7, LOW);
-  }else if(voltaje >= 0.9 & voltaje <= 1.6){
-    digitalWrite(2, HIGH);
-    digitalWrite(3, HIGH);
-    digitalWrite(4, LOW);
-    digitalWrite(5, LOW);
-    digitalWrite(6, LOW);
-    digitalWrite(7, LOW);
-  }else if(voltaje >= 1.7 & voltaje <= 2.5){
-    digitalWrite(2, HIGH);
-    digitalWrite(3, HIGH);
-    digitalWrite(4, HIGH);
-    digitalWrite(5, LOW);
-    digitalWrite(6, LOW);
-    digitalWrite(7, LOW);
-  }else if(voltaje >= 2.6 & voltaje <= 3.3){
-    digitalWrite(2, HIGH);
-    digitalWrite(3, HIGH);
-    digitalWrite(4, HIGH);
-    digitalWrite(5, HIGH);
-    digitalWrite(6, LOW);
-    digitalWrite(7, LOW);
-  }else if(voltaje >= 3.4 & voltaje <= 4.1){
-    digitalWrite(2, HIGH);
-    digitalWrite(3, HIGH);
-    digitalWrite(4, HIGH);
-    digitalWrite(5, HIGH);
-    digitalWrite(6, HIGH);
-    digitalWrite(7, LOW);
-  }else if(voltaje >= 4.2 & voltaje <= 5.0){
-    digitalWrite(2, HIGH);
-    digitalWrite(3, HIGH);
-    digitalWrite(4, HIGH);
-    digitalWrite(5, HIGH);
-    digitalWrite(6, HIGH);
-    digitalWrite(7, HIGH);
+  //Lectura del puerto A0
+  int valueAnalog = analogRead(0);
+  //Conversión para obtener la secuencia
+  int positionLed = (valueAnalog * 9) / 1024;
+  delay(10);
+  lightVumeter(positionLed);
+}
+
+/**
+ * Función para encender los led segun el número de
+ * secuencia
+ */
+void lightVumeter(int number) {
+  byte numberBit = vumeter[number];
+  for (int i = 0; i < 8; i++)  {
+    int bit = bitRead(numberBit, i);
+    digitalWrite(pins[i], bit);
   }
-  Serial.println(voltaje);
-  delay(10);
 }


strings to PROGMEM

strings to PROGMEM

--- nodemcu-rgbstrip.ino
+++ nodemcu-rgbstrip.ino
@@ -6,11 +6,10 @@
 #include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager
 #include <ArduinoJson.h>          //https://github.com/bblanchon/ArduinoJson

-/* Store strings in PROGMEM
-
-*/
+/* Store strings in PROGMEM */
 const char CANNOT_CONNECT[] PROGMEM = {'Cannot connect to the AP: '};
 const char MOUNTFAIL[] PROGMEM = {'Failed to mount file system!'};
+const char FSMOUNTED[] PROGMEM = {'mounted file system'};
 const char SAVEWCONF[] PROGMEM = {'Saving the WiFi configuration...'};
 const char CONFMODE[] PROGMEM = {'Entered to configuration mode...'};
 const char RESETNODE[] PROGMEM = {'Entered to configuration mode...'};
@@ -19,11 +18,27 @@
 const char MACMSG[] PROGMEM = {'MAC Address: '};
 const char APIPSTR[] PROGMEM = {'AP IP: '};
 const char NOCONF[] PROGMEM = {'Config file not found!'};
+const char CONFOPEN[] PROGMEM = {'saveConfigCallback: opened config file for writing the config'};
+const char CONFFAILOPEN[] PROGMEM = {'saveConfigCallback: cannot open the config file for write'};
+const char CONFOPENSAVE[] PROGMEM = {'saveConfigCallback: config file has been opened for savig the config and JSON buffer has been created successfully'};
+const char CONFSAVED[] PROGMEM = {'saveConfigCallback: config save ok'};
+const char CONFOPENED[] PROGMEM = {'config opened for read'};
+const char CONFOPENING[] PROGMEM = {'opening the config file...'};
+const char CONFPARSED[] PROGMEM = {'\nparsed json'};
+const char CONFPARSEFAIL[] PROGMEM = {'failed to parse the config'};
+const char CONFDEL[] PROGMEM = {'Deleting the saved config file...'};
+const char RESET[] PROGMEM = {'Reset...'};
+const char WIFIOK[] PROGMEM = {'Connected'};
+const char WIFIFAIL[] PROGMEM = {'WiFi: failed to connect to the AP'};
+const char WIFICONF[] PROGMEM = {'Current config: '};
+const char WIFIIP[] PROGMEM = {'IP: '};

+/* Global constants */
+#define MAX_CONNTRY 5
 #define PWM_FREQ 100
-#define AP_PASSW "xxx0xxx"
 #define CONFNAME "/wificreds.conf"

+/* Global variables */
 ESP8266WebServer myServer(8080);
 String stassid = "";
 String stapass = "";
@@ -31,9 +46,9 @@
 void deleteWifiConfig() {
   cli();
   if (SPIFFS.exists(CONFNAME)) {
-    Serial.println("Deleting the saved config file...");
+    Serial.println(FPSTR(CONFDEL));
     SPIFFS.remove(CONFNAME);
-    Serial.println("Restart...");
+    Serial.println(FPSTR(RESET));
     ESP.reset();
   }
 }
@@ -45,18 +60,18 @@
   stapass = WiFi.psk();
   File configFile = SPIFFS.open(CONFNAME, "w");
   if (configFile) {
-        Serial.println("saveConfigCallback: opened config file for writing the config");
+        Serial.println(FPSTR(CONFOPEN));
   } else {
-        Serial.println("saveConfigCallback: cannot open the config file for write");
+        Serial.println(FPSTR(CONFFAILOPEN));
         return;
   }
-  Serial.println("saveConfigCallback: config file has been opened for savig the config and JSON buffer has been created successfully");
+  Serial.println(FPSTR(CONFOPENSAVE));
   StaticJsonBuffer<200> jsonBuffer;
   JsonObject& json = jsonBuffer.createObject();
   json["sta_ssid"] = stassid;
   json["sta_pass"] = stapass;
   json.printTo(configFile);
-  Serial.println("saveConfigCallback: config save ok");
+  Serial.println(FPSTR(CONFSAVED));
 }

 void configModeCallback(WiFiManager *myWfMan) {
@@ -83,18 +98,19 @@
   /* remove saved config and restart if the flash button is pushed */
   attachInterrupt(digitalPinToInterrupt(D3), deleteWifiConfig, CHANGE);

+/* Setup PWM */
   analogWriteFreq(PWM_FREQ);
   analogWriteRange(1023);

- // Try to load config
+ /* Try to load config */
  if (SPIFFS.begin()) {
-    Serial.println("mounted file system");
+    Serial.println(FPSTR(FSMOUNTED));
     if (SPIFFS.exists(CONFNAME)) {
       //file exists, reading and loading
-      Serial.println("reading config file");
+      Serial.println(FPSTR(CONFOPENING));
       File configFile = SPIFFS.open(CONFNAME, "r");
       if (configFile) {
-        Serial.println("opened config file");
+        Serial.println(FPSTR(CONFOPENED));
         size_t size = configFile.size();
         // Allocate a buffer to store contents of the file.
         std::unique_ptr<char[]> buf(new char[size]);
@@ -104,20 +120,20 @@
         JsonObject& json = jsonBuffer.parseObject(buf.get());
         json.printTo(Serial);
         if (json.success()) {
-          Serial.println("\nparsed json");
+          Serial.println(FPSTR(CONFPARSED));
           stassid = String((const char*)json["sta_ssid"]);
           stapass = String((const char*)json["sta_pass"]);
           hasSavedConfig = true;
         } else {
-          Serial.println("failed to load json config");
+          Serial.println(FPSTR(CONFPARSEFAIL));
         }
       }
     } else {
-      Serial.println("No config file");
+      Serial.println(FPSTR(NOCONF));
     }
   } else {
-    Serial.println("failed to mount FS");
-    Serial.println("Reset...");
+    Serial.println(FPSTR(MOUNTFAIL));
+    Serial.println(FPSTR(RESET));
     Serial.println("");
     ESP.reset();
   }
@@ -139,10 +155,11 @@
   /* Connect to the AP if not connected by the WiFiManager */
   WiFi.setAutoConnect(false);
   WiFi.setAutoReconnect(true);
-  for (uint8_t count = 5; count > 0; count--) {
+  for (uint8_t count = MAX_CONNTRY; count > 0; count--) {
     if (!WiFi.isConnected()) {
       WiFi.begin(stassid.c_str(), stapass.c_str());
     } else {
+      Serial.println(FPSTR(WIFIFAIL));
       break;
     }
     delay(1000);
@@ -158,15 +175,16 @@
   } else {
     WiFi.setAutoConnect(true);
     Serial.println("");
-    Serial.println("Connected");
-    Serial.println("Current config: ");
+    Serial.println(FPSTR(WIFIOK));
+    Serial.println(FPSTR(WIFICONF));
     WiFi.printDiag(Serial);
-    Serial.print("IP: ");
+    Serial.print(FPSTR(WIFIIP));
     Serial.println(WiFi.localIP());
   }

   /*
       TODO: Setup the webserver (myServer)
+      TODO: Setup the MQTT client
   */
 }


correções no acionamento e datador

correções no acionamento e datador

--- EMP-B-Due.ino
+++ EMP-B-Due.ino
@@ -263,14 +263,12 @@
              &maquina_ligada);
   if (maquina_ligada) {
     ligaFuncao(geral, NomeGeral);
-  } else {
-    if (ligado(geral) && !desligamento_suave){
-      desligamento_suave = VERDADEIRO;
-      escreveSerial("Fazendo desligamento suave.");
-    } else if (desligamento_suave && conta_ciclos == desligarEm) {
-      desligaFuncao(geral, NomeGeral);
-      resetCompleto();
-    }
+  } else if (ligado(geral) && !desligamento_suave){
+    desligamento_suave = VERDADEIRO;
+    escreveSerial("Fazendo desligamento suave.");
+  } else if (desligamento_suave && conta_ciclos == desligarEm) {
+    desligaFuncao(geral, NomeGeral);
+    resetCompleto();
   }
 }

@@ -288,11 +286,11 @@
   if (maquina_ligada) {
     btUmClique(bt_datador, &estbt_datador, &estbta_datador, &atr_datador,
                &datador_ligado);
-  }
-  if (datador_ligado) {
-    ligaFuncao(led_datador, NomeDatador);
-  } else {
-    desligaFuncao(led_datador, NomeDatador);
+    if (datador_ligado) {
+      ligaFuncao(led_datador, NomeDatador);
+    } else {
+      desligaFuncao(led_datador, NomeDatador);
+    }
   }
 }

@@ -327,10 +325,6 @@
   resetado = VERDADEIRO;
   fotocelula_liberada = FALSO;
   fotocelula_cortou = FALSO;
-  // if (desligamento_suave && desligarEm){
-  //   reiniciaSaidas();
-  //   resetCompleto();
-  // } else
   if (desligamento_suave){
     if (dosador_ligado){
       dosador_ligado = FALSO;
@@ -414,12 +408,6 @@
   } else if (tempo_atual >= fim || inativo(seguranca)) {
     desligaFuncao(saida, nome);
   }
-
-  // if (ativo(seguranca)){
-  //   funcaoSimples(saida, nome, inicio, fim);
-  // } else {
-  //   bloqueioPorAlarme("Sensor da Mandíbula");
-  // }
 }

 void funcaoBloqueante(const byte saida, String nome, unsigned long inicio, unsigned long fim, boolean contra_mandibula){


risolti i problemi per l'invio della GET

--- nodeMCU/plant/functions.ino
+++ nodeMCU/plant/functions.ino
@@ -22,25 +22,21 @@

    String postStr= String(rnd);

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

-     client.print("GET ");
-//     client.print(server);
-//     client.print(":3000");
-     client.print("/dato/acquisisci/");
-     Serial.print("GET /dato/acquisisci/");
+   client.println(url);
+   Serial.println(url);
+
+   client.println("Host: 192.168.1.67:3000");
+   Serial.println("Host: 192.168.1.67:3000");
+
+   client.println("Connection: close");
+   Serial.println("Connection: close");

-     client.print(postStr);
-     Serial.print(postStr);
+   client.println();

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

    delay(2000);
    client.stop();


added wifi measurement

added wifi measurement

--- firmware/src/PoolBuddy.ino
+++ firmware/src/PoolBuddy.ino
@@ -50,9 +50,9 @@
     compensate_temp_ph();
     measure_ph();
     measure_orp();
+    measure_wifi();
     nextSampleTime = millis() + SAMPLE_INTERVAL;
     soc = lipo.getSOC();
-    wifi = WiFi.RSSI();
   }
   if(millis() > nextSleepTime) {
     Particle.publish("waterdata", water_data(), PRIVATE);
@@ -126,6 +126,12 @@
   }
 }

+void measure_wifi() {
+  float wifi_db = WiFi.RSSI();
+  if(wifi_db < 0)
+    wifi = (int)((-wifi_db / 127)*100);
+}
+
 int calibrate_ph(String arg) {
   String commandString = String("Cal");
   commandString.concat(",");


More work on the wand lights, new cyclotron animation option for startup

SloBlo now blinks when booting/venting, rear light and vent light are
tied to activate switch, top light flashes yellow after firing 5 seconds
and fast red after firing for 10 seconds. As pack vents all wand lights
shut down, sloblo then flashes red. 2 more neopixels added to the
powercell/cyclotron chain for doing the nfilter venting effect

--- Arduino/Neutrino_Wand/Neutrino_Wand.ino
+++ Arduino/Neutrino_Wand/Neutrino_Wand.ino
@@ -52,6 +52,7 @@
 // available options
 // ##############################
 const bool useGameCyclotronEffect = true; // set this to true to get the fading previous cyclotron light in the idle sequence
+const bool useCyclotronFadeInEffect = true; // Instead of the yellow alternate flashing on boot/vent this fades the cyclotron in from off to red

 // Possible Pack states
 bool powerBooted = false; // has the pack booted up
@@ -84,8 +85,6 @@
 const String listenTrack =    "T12     WAV";
 const String goodTrack =      "T13     WAV";
 const String thatTrack =      "T14     WAV";
-const String neverTrack =     "T15     WAV";
-const String hardTrack =      "T16     WAV";
 const String neutronizedTrack="T17     WAV";
 const String boxTrack =       "T18     WAV";
 const String themeTrack =     "T19     OGG";
@@ -93,17 +92,16 @@
 // this queue holds a shuffled list of dialog tracks we can pull from so we don't
 // play the same ones twice
 QueueArray <int> dialogQueue;
+int numDialog = 8;
+int dialogArray[8] = {1,2,3,4,5,6,7,8};

 // dialog trigger times/states
 unsigned long startDialogMillis;
-int dialogArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // array with an index for each dialog
 const int dialogWaitTime = 5000; // how long to hold down fire for a dialog to play
 const int warnWaitTime = 10000;  // how long to hold down fire before warning sounds

 // Arduino setup function
-void setup() {
-  randomSeed(analogRead(A0)); // try to get a good random seed
-
+void setup() {
   // softwareserial at 9600 baud for the audio board
   ss.begin(9600);

@@ -164,12 +162,16 @@
     // pull the next dialog
     return dialogQueue.dequeue();
   }else{
-    // queue is empty so reset it and pull the first
-    // random dialog
-    int numDialog = sizeof(dialogArray) / sizeof(int);
-    shuffleTrackArray( dialogArray, numDialog );
-
-    for (int i = 0; i < numDialog; i++){
+    randomSeed(micros() +  ss.read());
+
+    for (int i=0; i<numDialog; i++){
+      int pos = random(numDialog);
+      int t = dialogArray[i];
+      dialogArray[i] = dialogArray[pos];
+      dialogArray[pos] = t;
+    }
+
+    for (int i=0; i<numDialog; i++){
       dialogQueue.enqueue(dialogArray[i]);
     }

@@ -177,20 +179,11 @@
   }
 }

-// function for sorting arrays found here.
-// https://forum.arduino.cc/index.php?topic=345964.0
-void shuffleTrackArray(int * array, int size){
-  int last = 0;
-  int temp = array[last];
-  for (int i = 0; i < size; i++){
-    int index = random(size);
-    array[last] = array[index];
-    last = index;
-  }
-  array[last] = temp;
-}
-
 /* ************* Main Loop ************* */
+// helper function to set light states for the cyclotron
+int cyclotronRunningFadeOut = 255;  // we reset this variable every time we change the cyclotron index so the fade effect works
+int cyclotronRunningFadeIn = 0;  // we reset this variable every time we change the cyclotron index so the fade effect works
+
 // intervals that can be adjusted in real time to speed up animations
 int pwr_interval = 60;        // interval at which to cycle lights for the powercell. We update this in the loop to speed up the animation so must be declared here (milliseconds)
 int cyc_interval = 1000;      // interval at which to cycle lights for the cyclotron.
@@ -234,11 +227,11 @@
       poweredDown = false;
       shuttingDown = false;
       powerSequenceOne(currentMillis, pwr_interval, cyc_interval, cyc_fade_interval);
-      setWandLightState(1, 2);               // set back light orange
-      setWandLightState(3, 0);               //set sloblow red
+      setWandLightState(3, 0, 0);               //set sloblow red
       venting = false;
       setVentLightState(ventStart, ventEnd, 2);
     } else {
+      setWandLightState(3, 7, currentMillis);   //set sloblow red blinking
       powerSequenceBoot(currentMillis);
     }

@@ -255,9 +248,11 @@

     if( startup == true && safety_switch == 1 ){
       if( venting == false && powerBooted == true ){
-        setWandLightState(2, 3);    //set body blue
+        setWandLightState(1, 2, 0);    //  set back light orange
+        setWandLightState(2, 3, 0);    //  set body led blue
       }else{
-        setWandLightState(2, 4);    //set body blue
+        setWandLightState(1, 4, 0);    //  set back light off
+        setWandLightState(2, 4, 0);    //  set body led off
       }
     }

@@ -312,8 +307,8 @@
             if (playing == 1 || shouldWarn == false ) {
               shouldWarn = true;
               playTrack(warnTrack); // play the firing track with the warning
-              setWandLightState(0, 2);    // set top light orange
             }
+            setWandLightState(0, 8, currentMillis);    // set top light red flashing
           } else if ( diff > dialogWaitTime) { // if we are in the dialog playing interval
             pwr_interval = 30;    // speed up the powercell animation
             firing_interval = 30; // speed up the bar graph animation
@@ -322,11 +317,14 @@
             if (playing == 1) {
               playTrack(blastTrack); // play the normal blast track
             }
+            setWandLightState(0, 6, currentMillis);    // set top light orange flashing
           }
         }
       } else { // now the button is no longer pressed
         if (fire == true) { // if we were firing let's reset the animations and play the correct final firing track
           clearFireStrobe();
+          setWandLightState(0, 4, currentMillis);    // set top light off
+
           pwr_interval = 60;
           firing_interval = 40;
           cyc_interval = 1000;
@@ -361,17 +359,14 @@
               case (6):
                 playTrack(thatTrack);
                 break;
-              case (7):
-                playTrack(neverTrack);
-                break;
               case (8):
-                playTrack(hardTrack);
+                playTrack(neutronizedTrack);
                 break;
               case (9):
-                playTrack(neutronizedTrack);
+                playTrack(boxTrack);
                 break;
-              case (10):
-                playTrack(boxTrack);
+              default:
+                playTrack(endTrack);
                 break;
             }
           } else {
@@ -383,7 +378,8 @@
     } else {
       // if the safety is switched off play the click track
       if (safety == true) {
-        setWandLightState(2, 4);    //set body off
+        setWandLightState(1, 4, 0);    //  set back light off
+        setWandLightState(2, 4, 0);    //set body off
         safety = false;
         playTrack(clickTrack);
       }
@@ -394,6 +390,7 @@
         playTrack(shutdownTrack); // play the pack shutdown track
         shuttingDown = true;
       }
+      cyclotronRunningFadeOut = 255;
       powerSequenceShutdown(currentMillis);
     }else{
       if (startup == true) { // if started reset the variables
@@ -411,7 +408,9 @@
 /*************** Wand Light Helpers *********************/
 unsigned long prevFlashMillis = 0; // last time we changed a powercell light in the idle sequence
 bool flashState = false;
-void setWandLightState(int lednum, int state){
+int wandFastFlashInterval = 100; // interval at which we flash the top led on the wand
+int wandMediumFlashInterval = 500; // interval at which we flash the top led on the wand
+void setWandLightState(int lednum, int state, int currentMillis){
   switch ( state ) {
     case 0: // set led red
       wandLights.setPixelColor(lednum, wandLights.Color(255, 0, 0));
@@ -427,6 +426,54 @@
       break;
     case 4: // set led off
       wandLights.setPixelColor(lednum, 0);
+      break;
+    case 5: // fast white flashing
+      if (currentMillis - prevFlashMillis > wandFastFlashInterval) {
+        prevFlashMillis = currentMillis;
+        if( flashState == false ){
+          wandLights.setPixelColor(lednum, wandLights.Color(255, 255, 255));
+          flashState = true;
+        }else{
+          wandLights.setPixelColor(lednum, 0);
+          flashState = false;
+        }
+      }
+      break;
+    case 6: // slower orange flashing
+      if (currentMillis - prevFlashMillis > wandMediumFlashInterval) {
+        prevFlashMillis = currentMillis;
+        if( flashState == false ){
+          wandLights.setPixelColor(lednum, wandLights.Color(255, 127, 0));
+          flashState = true;
+        }else{
+          wandLights.setPixelColor(lednum, 0);
+          flashState = false;
+        }
+      }
+      break;
+    case 7: // medium red flashing
+      if (currentMillis - prevFlashMillis > wandMediumFlashInterval) {
+        prevFlashMillis = currentMillis;
+        if( flashState == false ){
+          wandLights.setPixelColor(lednum, wandLights.Color(255, 0, 0));
+          flashState = true;
+        }else{
+          wandLights.setPixelColor(lednum, 0);
+          flashState = false;
+        }
+      }
+      break;
+    case 8: // fast red flashing
+      if (currentMillis - prevFlashMillis > wandFastFlashInterval) {
+        prevFlashMillis = currentMillis;
+        if( flashState == false ){
+          wandLights.setPixelColor(lednum, wandLights.Color(255, 0, 0));
+          flashState = true;
+        }else{
+          wandLights.setPixelColor(lednum, 0);
+          flashState = false;
+        }
+      }
       break;
   }

@@ -461,6 +508,7 @@

 unsigned long prevCycBootMillis = 0;    // the last time we changed a cyclotron light in the boot sequence
 const int cyc_boot_interval = 400;      // interval at which to cycle lights (milliseconds).
+const int cyc_boot_alt_interval = 600;      // interval at which to cycle lights (milliseconds).

 unsigned long prevShtdMillis = 0;       // last time we changed a light in the idle sequence
 const int pwr_shutdown_interval = 200;  // interval at which to cycle lights (milliseconds).
@@ -478,8 +526,6 @@
 int currentBootLevel = -1;          // current powercell boot level sequence led
 int currentLightLevel = 15;         // current powercell boot light sequence led

-// helper function to set light states for the cyclotron
-int cyclotronRunningFadeOut = 255;  // we reset this variable every time we change the cyclotron index so the fade effect works
 void setCyclotronLightState(int startLed, int endLed, int state ){
   switch ( state ) {
     case 0: // set all leds to red
@@ -504,6 +550,16 @@
           cyclotronRunningFadeOut--;
         }else{
           powerStick.setPixelColor(i, 0);
+        }
+      }
+      break;
+    case 4: // fade all leds to red
+      for(int i=startLed; i <= endLed; i++) {
+        if( cyclotronRunningFadeIn < 255 ){
+          powerStick.setPixelColor(i, 255 * cyclotronRunningFadeIn/255, 0, 0);
+          cyclotronRunningFadeIn++;
+        }else{
+          powerStick.setPixelColor(i, powerStick.Color(255, 0, 0));
         }
       }
       break;
@@ -519,6 +575,7 @@
   powerShutdownSeqNum = 15;
   currentLightLevel = 15;
   currentBootLevel = -1;
+  cyclotronRunningFadeIn = 0;

   // shutoff the leds
   for ( int i = 0; i <= c4End; i++) {
@@ -540,30 +597,38 @@
 bool reverseBootCyclotron = false;
 void powerSequenceBoot(int currentMillis) {
   bool doUpdate = false;
-
-  if (currentMillis - prevCycBootMillis > cyc_boot_interval) {
-    prevCycBootMillis = currentMillis;
-
-    // START CYCLOTRON
-    if( reverseBootCyclotron == false ){
-      setCyclotronLightState(c1Start, c1End, 1);
-      setCyclotronLightState(c2Start, c2End, 2);
-      setCyclotronLightState(c3Start, c3End, 1);
-      setCyclotronLightState(c4Start, c4End, 2);
-
+
+  // START CYCLOTRON
+  if( useCyclotronFadeInEffect == false ){
+    if (currentMillis - prevCycBootMillis > cyc_boot_interval) {
+      prevCycBootMillis = currentMillis;
+
+      if( reverseBootCyclotron == false ){
+        setCyclotronLightState(c1Start, c1End, 1);
+        setCyclotronLightState(c2Start, c2End, 2);
+        setCyclotronLightState(c3Start, c3End, 1);
+        setCyclotronLightState(c4Start, c4End, 2);
+
+        doUpdate = true;
+        reverseBootCyclotron = true;
+      }else{
+        setCyclotronLightState(c1Start, c1End, 2);
+        setCyclotronLightState(c2Start, c2End, 1);
+        setCyclotronLightState(c3Start, c3End, 2);
+        setCyclotronLightState(c4Start, c4End, 1);
+
+        doUpdate = true;
+        reverseBootCyclotron = false;
+      }
+    }
+  }else{
+    if (currentMillis - prevCycBootMillis > cyc_boot_alt_interval) {
+      prevCycBootMillis = currentMillis;
+      setCyclotronLightState(c1Start, c4End, 4);
       doUpdate = true;
-      reverseBootCyclotron = true;
-    }else{
-      setCyclotronLightState(c1Start, c1End, 2);
-      setCyclotronLightState(c2Start, c2End, 1);
-      setCyclotronLightState(c3Start, c3End, 2);
-      setCyclotronLightState(c4Start, c4End, 1);
-
-      doUpdate = true;
-      reverseBootCyclotron = false;
-    }
-    // END CYCLOTRON
-  }
+    }
+  }
+  // END CYCLOTRON

   if (currentMillis - prevPwrBootMillis > pwr_boot_interval) {
     // save the last time you blinked the LED


Better HTTP Request Handling

Better HTTP Request Handling

--- MainStation/MainStation.ino
+++ MainStation/MainStation.ino
@@ -62,7 +62,7 @@
 static const byte _mymac[] = {0x74, 0x69, 0x69, 0x2D, 0x30, 0x31 };

 // remote website ip address and port
-static const char _website[] PROGMEM = "http://www.example.com/";
+static const char _website[] PROGMEM = "example.com";

 // Remote URL
 static const char _baseURL[] PROGMEM = "/riot-server/points/add/";
@@ -507,7 +507,7 @@

   //
   // Wait end of HTTP Request
-  while(millis() - dateHTTPrequest < HTTP_TIMEOUT && ( _app.eth.isHttpRequest || ether.clientWaitingGw() ))
+  while(millis() - dateHTTPrequest < HTTP_TIMEOUT && _app.eth.isHttpRequest )
   {
     ether.packetLoop(ether.packetReceive());
   }
@@ -522,7 +522,8 @@
   }

   // Workaround to clean Ethernet ...
-  for(int i=0;i<100;i++)
+  const unsigned long dateHTTPend = millis();
+  while(millis() - dateHTTPend < HTTP_TIMEOUT)
   {
     ether.packetLoop(ether.packetReceive());
   }


Bridge.ino example: comment fixed

Bridge.ino example: comment fixed

--- libraries/Bridge/examples/Bridge/Bridge.ino
+++ libraries/Bridge/examples/Bridge/Bridge.ino
@@ -26,8 +26,8 @@
 #include <YunServer.h>
 #include <YunClient.h>

-// Listen on default port 5555, the webserver on the Yún
-// will forward there all the HTTP requests for us.
+// Listen to the default port 5555, the Yún webserver
+// will forward there all the HTTP requests you send
 YunServer server;

 void setup() {


Changed some config

Changed some config

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

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

 int secureAnalogRead(int pin) {
   delay(0.01);


Update ChangeUID.ino

Update ChangeUID.ino

Added new pin layout info; standardizing format and info

--- examples/ChangeUID/ChangeUID.ino
+++ examples/ChangeUID/ChangeUID.ino
@@ -23,15 +23,17 @@
  http://mac86project.altervista.org/

  ----------------------------------------------------------------------------- Nicola Coppola
- * Pin layout should be as follows:
- * Signal     Pin              Pin               Pin
- *            Arduino Uno      Arduino Mega      MFRC522 board
- * ------------------------------------------------------------
- * Reset      9                5                 RST
- * SPI SS     10               53                SDA
- * SPI MOSI   11               51                MOSI
- * SPI MISO   12               50                MISO
- * SPI SCK    13               52                SCK
+ * Typical pin layout used:
+ * -----------------------------------------------------------------------------------------
+ *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
+ *             Reader/PCD   Uno           Mega      Nano v3    Leonardo/Micro   Pro Micro
+ * Signal      Pin          Pin           Pin       Pin        Pin              Pin
+ * -----------------------------------------------------------------------------------------
+ * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
+ * SPI SS      SDA(SS)      10            53        D10        10               10
+ * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
+ * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
+ * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
  *
  * The reader can be found on eBay for around 5 dollars. Search for "mf-rc522" on ebay.com.
  */


Have a working model of the centralized server side OTA update system.

Signed-off-by: Braden Licastro <79d6010d7e15bbb3aa5be04af4e1cdfb0e9c5bfd@live.com>

--- sketches/LRSideLamp/LRSideLamp.ino
+++ sketches/LRSideLamp/LRSideLamp.ino
@@ -1,4 +1,6 @@
 /*
+ * Software Revision: 3.13
+ *
  * Configuration for Home Assistant:
  *   light:
  *   # Interior: Living Room Side Lamp
@@ -11,8 +13,8 @@

 #include <ESP8266WiFi.h>    // https://github.com/esp8266/Arduino (GNUv2.1 licence)
 #include <PubSubClient.h>   // https://github.com/knolleary/pubsubclient (no licence)
-#include <ArduinoOTA.h>
-
+#include <ESP8266HTTPClient.h>
+#include <ESP8266httpUpdate.h>

 #define DEBUG
 #define MQTT_VERSION MQTT_VERSION_3_1_1
@@ -31,14 +33,13 @@
 // MQTT: client ID, broker IP, port, username & password
 const char*       MQTT_CLIENT_ID    = "<REDACTED>";
 const char*       MQTT_SERVER_IP    = "<REDACTED>";
-const uint16_t    MQTT_SERVER_PORT  = 1883;
+const uint8_t     MQTT_SERVER_PORT  = 1883;
 const char*       MQTT_USERNAME     = "<REDACTED>";
 const char*       MQTT_PASSWORD     = "<REDACTED>";

-// OTA: hostname & password
-const char*       OTA_HOSTNAME      = MQTT_CLIENT_ID;
-const char*       OTA_PASSWORD      = "<REDACTED>";
-const uint16_t    OTA_PORT          = 8266;
+// OTA Information
+const char*       OTA_SERVER_IP      = "<REDACTED>";
+const uint8_t     OTA_PORT           = 80;

 // MQTT: topics
 // Interior: Living Room Side Lamp
@@ -69,8 +70,11 @@
 PubSubClient      g_mqttClient(g_wifiClient);

 // Other event handling
-const uint8_t     DEBOUNCE_DELAY    = 200; // Delay in MS
-long              DEBOUNCE_TIME     = 0;
+const uint8_t       DEBOUNCE_DELAY    = 200; // Delay in MS is .2 sec
+unsigned long       DEBOUNCE_TIME     = 0;
+const unsigned long UPDATE_DELAY      = 300000; // Delay in MS is 5 mins
+unsigned long       UPDATE_TIME       = 0;
+

 //############################################################################
 //
@@ -265,6 +269,41 @@

 //############################################################################
 //
+//                              OTA Updates
+//
+//############################################################################
+/*
+ * Function called to check for updates from the binary server
+ *   INPUT:  NA
+ *   Return: NA
+ */
+void checkForUpdates() {
+  #ifdef DEBUG
+    Serial.println(F("INFO:  OTA update check beginning..."));
+  #endif
+
+  // Make the server side call and hold onto the HTTP return status
+  t_httpUpdate_return state = ESPhttpUpdate.update(OTA_SERVER_IP, OTA_PORT, "/updater.php");
+
+  // Do something based on the response from the server
+  #ifdef DEBUG
+    switch (state) {
+      case HTTP_UPDATE_FAILED:
+        Serial.println(F("ERROR: OTA update failed."));
+        break;
+      case HTTP_UPDATE_NO_UPDATES:
+        Serial.println(F("INFO:  OTA update not available. Already running latest version."));
+        break;
+      case HTTP_UPDATE_OK:
+        Serial.println(F("INFO:  OTA update succeeded."));
+        break;
+    }
+  #endif
+}
+
+
+//############################################################################
+//
 //                            SETUP and LOOP
 //
 //############################################################################
@@ -288,39 +327,6 @@
   // Configure and connect to MQTT broker.
   g_mqttClient.setServer(MQTT_SERVER_IP, MQTT_SERVER_PORT);
   g_mqttClient.setCallback(callback);
-
-  // Configure and initialize OTA listener.
-  ArduinoOTA.setHostname(OTA_HOSTNAME);
-  ArduinoOTA.setPassword(OTA_PASSWORD);
-  ArduinoOTA.setPort(OTA_PORT);
-
-  #ifdef DEBUG
-    ArduinoOTA.onStart([]() {
-      Serial.println(F("INFO:  OTA session started."));
-    });
-    ArduinoOTA.onEnd([]() {
-      Serial.println(F("INFO:  OTA session ended."));
-    });
-    ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
-      Serial.printf("INFO:  OTA rogress is %u%%\r", (progress / (total / 100)));
-    });
-    ArduinoOTA.onError([](ota_error_t error) {
-      Serial.printf("ERROR: [%u] ", error);
-      if (error == OTA_AUTH_ERROR) {
-        Serial.println("Auth Failed");
-      } else if (error == OTA_BEGIN_ERROR) {
-        Serial.println("Begin Failed");
-      } else if (error == OTA_CONNECT_ERROR) {
-        Serial.println("Connect Failed");
-      } else if (error == OTA_RECEIVE_ERROR) {
-        Serial.println("Receive Failed");
-      } else if (error == OTA_END_ERROR) {
-        Serial.println("End Failed");
-      }
-    });
-  #endif
-
-  ArduinoOTA.begin();
 }

 /*
@@ -328,15 +334,15 @@
  */
 void loop() {
   // Ensure connection to MQTT broker is active, if not fix it.
-  if (!g_mqttClient.connected()) {
+  if (WiFi.status() != WL_CONNECTED) {
+    setupWifi();
+  }else if (!g_mqttClient.connected()) {
     reconnect();
   }

   // Listen for messages from the broker.
   g_mqttClient.loop();

-  // Listen for OTA messages
-  ArduinoOTA.handle();

   // Prevent bouncing when performing actions following a read.
   if (millis() - DEBOUNCE_TIME >= DEBOUNCE_DELAY) {
@@ -378,4 +384,13 @@
     // Set the last time of button press.
     DEBOUNCE_TIME = millis();
   }
+
+  // Check for code updates at a throttled pace.
+  if (millis() - UPDATE_TIME >= UPDATE_DELAY) {
+    //Check for update.
+    checkForUpdates();
+
+    // Set the last time of update check.
+    UPDATE_TIME = millis();
+  }
 }


update

update


never ends

never ends

--- telemetryBox.ino
+++ telemetryBox.ino
@@ -126,8 +126,7 @@
 void measureUS() {
     // the pulseIn from the sensor needs to be read often, otherwise it gets backed up with old measurements
     // perhaps using the analog signal would be better
-    waterHeight = 0;
-    waterHeight2 = 0;
+    waterHeightSum = 0;
     for (int i = 0; i < 100; i++) {
         duration = pulseIn(A0, HIGH);
         distance = duration / uSperInch; // in inches


Fetch data from Arduino updated

Fetch data from Arduino updated

--- arduino/test_sp/test_sp.ino
+++ arduino/test_sp/test_sp.ino
@@ -1,16 +1,24 @@
+#include <LiquidCrystal.h>
 #include <TimeLib.h>
 #include <Time.h>
 #include <ArduinoJson.h>

-int brink = 18;
+const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
+LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

 void setup() {
   Serial.begin(19200);
+  pinMode(13, OUTPUT);
+  digitalWrite(13, HIGH);
+  lcd.begin(16, 2);
+  lcd.setCursor(0, 0);
+  lcd.print("hello");
+  lcd.setCursor(0, 1);
 }

 void loop() {
   sendData();
-  //readData();
+  readData();
 }

 void sendData() {
@@ -25,7 +33,7 @@
   JsonObject& data_3 = data.createNestedObject();

   root["measuredAt"] = String(year()) + '-' + String(month()) + '-' + String(day()) + ' ' + String(hour()) + ':' + String(minute()) + ':' + String(second());
-  root["brink"] = random(17, 25);
+  root["brink"] = 19;

   data_0["sensor"] = "dht22";
   data_0["label"] = "inside temperature";
@@ -48,14 +56,11 @@
 }

 void readData() {
+  //lcd.print(Serial.available());
+  lcd.setCursor(0, 1);
   if (Serial.available() > 0) {
-    Serial.flush();
-    brink = Serial.readString().toInt();
-    Serial.println(brink);
+    digitalWrite(13, LOW);
+    String data = Serial.readString();
+    lcd.print(data);
   }
 }
-
-//{"measurements":[{"sensor":"dht22","label":"insidetemperature","value":17},{"sensor":"thermistor","label":"outsidetemperature","value":22},{"sensor":"pt100","label":"moduletemperature","value":25},{"sensor":"dht22","label":"dampness","value":53}],"measured_at":"1/1/1970 0:5:44"}
-
-
-


Made very minor comment formatting change for consistency.

Signed-off-by: Braden Licastro <79d6010d7e15bbb3aa5be04af4e1cdfb0e9c5bfd@live.com>

--- sketches/LRSideLamp/LRSideLamp.ino
+++ sketches/LRSideLamp/LRSideLamp.ino
@@ -272,6 +272,7 @@
 //                              OTA Updates
 //
 //############################################################################
+
 /*
  * Function called to check for updates from the binary server
  *   INPUT:  NA


minor adjustment of display

minor adjustment of display

--- sketches/WeatherPod/WeatherPod.ino
+++ sketches/WeatherPod/WeatherPod.ino
@@ -26,7 +26,7 @@
 } configType;

 char buffer[10];
-configType config = { 2000 };
+configType config = { 3000 };

 void readBMP(int timerId) {
@@ -69,11 +69,11 @@
 }

 void displayPressure(int timerId) {
-	SevenSegment.printUnits(config.pressureInches, "I");
+	SevenSegment.printUnits(config.pressureInches, "i");
 }

 void displayHumiduty(int timerId) {
-	SevenSegment.printUnits(config.humidityPercent, "H");
+	SevenSegment.printUnits(config.humidityPercent, "h");
 }


updates to msg and polling

updates to msg and polling

--- OxFloodNet_Sensor/OxFloodNet_Sensor.ino
+++ OxFloodNet_Sensor/OxFloodNet_Sensor.ino
@@ -3,26 +3,28 @@
  * Availabe form http://www.coolcomponents.co.uk/ultrasonic-range-finder-xl-ez3.html
  *
  * Transmits reading every 5 minutes
- * Data transmitted is of form aXXRIVRnnn--
- * Battery readings every 10th cycle  aXXBATTv.vvv
+ * Data transmitted is of form aXXUnnn-----
+ * Battery readings every 10th cycle  aXXBvvvv----
  *
- * Where XX is the device ID, nnn is the distance to the water in cm, v.vvv is battery voltage
+ * Where XX is the device ID, nnn is the distance to the water in cm, vvvv is battery voltage in mV
+ * Other messages sent are: aXXSTARTED upon startup
+ * aXXUMax----- and aXXUErr----- if max range is reached or an error in the reading is seen.
  *
  * Sensor is controled using a single N-Channel MOSFET, Gate to SENSOR_ENABLE,
  * Source to GND, Drain to -ve of sensor, Sensor +ve to +3V.
  *
+ * NOTE: For initial testing, wakeup time set to 5mins and battery interval to 4 cycles
  * (c) Andrew D Lindsay 2014
  */
-

 #include "LLAPSerial.h"	// include the library
 #include <OneWire.h>
 #include <DallasTemperature.h>

-#define VERSION_STRING "V0.6"
+#define VERSION_STRING "V0.7"

 // Number of readings before a battery reading is taken
-#define BATTERY_READ_INTERVAL 10
+#define BATTERY_READ_INTERVAL 4

 // Hardware pin defines
 // Enable SRF
@@ -353,7 +355,7 @@
   // Determine if we need to send a battery voltage reading or a distance reading
   if( --batteryCountDown <= 0 ) {
     int mV = readVcc();
-    LLAP.sendIntWithDP("BATT", mV, 3 );
+    LLAP.sendIntWithDP("B", mV, 3 );
     batteryCountDown = BATTERY_READ_INTERVAL;
   }
   else {
@@ -362,13 +364,13 @@
     // Send reading 5 times to make sure it gets through
     for(int n = 0; n<3; n++ ) {
       if( cm > 17 ) {
-        LLAP.sendInt( "RIVR", cm );
+        LLAP.sendInt( "U", cm );
       }
       else if( cm == 0 ) {
-        LLAP.sendMessage( "RIVRMax" );
+        LLAP.sendMessage( "UMax" );
       }
       else {
-        LLAP.sendMessage( "RIVRErr" );
+        LLAP.sendMessage( "UErr" );
       }
       delay(30);
     }


Arduino: TX8/RX9, LED13 on serial input

Arduino: TX8/RX9, LED13 on serial input

--- dummycomm.ino
+++ dummycomm.ino
@@ -6,7 +6,7 @@

 #define LED 13
 #define BTX 8
-#define BRX 7
+#define BRX 9
 #define CARRIER 2
 #define ERROR -1

@@ -108,6 +108,7 @@

 void loop() {
 	int frame,i;
+	digitalWrite(LED, HIGH);
 	Serial.println("enter size:");
 	while(Serial.available() <= 0);
 	bytesbuf[0]=Serial.parseInt();
@@ -116,7 +117,7 @@
 		while(Serial.available() <= 0);
 		bytesbuf[++i]=Serial.parseInt();
 	}
-	digitalWrite(LED, HIGH);
+	digitalWrite(LED, LOW);
 	digitalWrite(BTX, LOW);
 	for(i=0; i<32; i++) {
 		sendCarrier(BTX, sleepms);
@@ -134,7 +135,6 @@
 		}
 		bytebits[--i] = frame;
 	}
-	digitalWrite(LED, LOW);
 	Serial.print("byte read: ");
 	Serial.println(bytebitsGet());
 }