Updates to arduino

Updates to arduino

--- arduino/WGDoor.ino
+++ arduino/WGDoor.ino
@@ -1,6 +1,13 @@
 #include <Wiegand.h>
 #define PIN_LENGTH 10
 #define MAX_USER_ACTION_DELAY_MS 10000
+#define SERIAL_INPUT_BUFFER_LENGTH 100
+#define PING_DELAY_MS 10000
+
+#define KEY_OK_STRING "ok"
+#define PING_STRING "ping"
+
+#define KEY_OK_PIN 4

 WIEGAND wg;
 bool isPinCodeSet = false;
@@ -10,12 +17,31 @@
 bool isKeyCodeSet = false;
 long lastKeyCode = 0;

+char serialinputbuffer[SERIAL_INPUT_BUFFER_LENGTH];
+int serialinputptr;
+
 unsigned long lastUserAction = 0;
+unsigned long lastPingSent = 0;

 void setup() {
   Serial.begin(9600);
+
   resetPinCode();
   wg.begin();
+  resetSerialInputBuffer();
+
+  pinMode(KEY_OK_PIN, OUTPUT);
+  digitalWrite(KEY_OK_PIN, HIGH);
+
+  Serial.println("{ \"status\": \"running\" }");
+}
+
+void resetSerialInputBuffer() {
+  for (int i=0; i<SERIAL_INPUT_BUFFER_LENGTH; i++) {
+    serialinputbuffer[i] = 0;
+  }
+
+  serialinputptr = 0;
 }

 void resetPinCode() {
@@ -45,38 +71,71 @@
     isKeyCodeSet = false;
 }

+void processWG() {
+  lastUserAction = millis();
+
+  if (wg.getWiegandType() == 4) {
+    int code = wg.getCode();
+    if (code == 27) {
+      resetPinCode();
+    } else if (code == 13) {
+      isPinCodeSet = true;
+    } else {
+      pincode[pincodeptr % PIN_LENGTH] = wg.getCode();
+      pincodeptr++;
+    }
+  } else {
+    lastKeyCode = wg.getCode();
+    isKeyCodeSet = true;
+  }
+
+  if (isPinCodeSet && isKeyCodeSet) {
+    printAndResetAccessCodes();
+  }
+}
+
+void processSerial() {
+  char c = Serial.read();
+
+  if (c == '\n') {
+    if (strncmp(serialinputbuffer, KEY_OK_STRING, strlen(KEY_OK_STRING)) == 0) {
+      digitalWrite(KEY_OK_PIN, LOW);
+      delay(500);
+      digitalWrite(KEY_OK_PIN, HIGH);
+    } else if (strncmp(serialinputbuffer, PING_STRING, strlen(PING_STRING)) == 0) {
+      Serial.println("was ping");
+    }
+
+    resetSerialInputBuffer();
+  } else {
+    if (serialinputptr >= SERIAL_INPUT_BUFFER_LENGTH) {
+      resetSerialInputBuffer();
+    } else {
+      serialinputbuffer[serialinputptr++] = c;
+    }
+  }
+}
+
 void loop() {
   if (wg.available()) {
-    lastUserAction = millis();
-
-    if (wg.getWiegandType() == 4) {
-      int code = wg.getCode();
-      if (code == 27) {
-        resetPinCode();
-      } else if (code == 13) {
-        isPinCodeSet = true;
-      } else {
-        pincode[pincodeptr % PIN_LENGTH] = wg.getCode();
-        pincodeptr++;
-      }
-    } else {
-      lastKeyCode = wg.getCode();
-      isKeyCodeSet = true;
-    }
-
-    if (isPinCodeSet && isKeyCodeSet) {
-      printAndResetAccessCodes();
-    }
+    processWG();
   }

   if (Serial.available()) {
-    char c = Serial.read();
-    Serial.print(c);
+    processSerial();
   }

-  if (lastUserAction + MAX_USER_ACTION_DELAY_MS < millis()) {
+  if (lastUserAction + MAX_USER_ACTION_DELAY_MS <= millis()) {
     lastUserAction = millis();
     resetPinCode();
     isKeyCodeSet = false;
   }
-}
+
+  if (lastPingSent + PING_DELAY_MS <= millis()) {
+    lastPingSent = millis();
+    Serial.print("{ \"ping\": ");
+    Serial.print(lastPingSent);
+    Serial.println(" }");
+  }
+
+}


Small change in Twitter example

Small change in Twitter example

--- WiFi/examples/TwitterClientWPA/TwitterClientWPA.ino
+++ WiFi/examples/TwitterClientWPA/TwitterClientWPA.ino
@@ -112,7 +112,7 @@
     Serial.println("making HTTP request...");
     // make HTTP GET request to twitter:
     client.println("GET /1/statuses/user_timeline.xml?screen_name=arduinoteam HTTP/1.1");
-    client.println("HOST: api.twitter.com");
+    client.println("HOST:api.twitter.com");
     client.println();
   }
   // note the time of this connect attempt:


Better error checking and yeilding.

Better error checking and yeilding.

--- water_heater_monitor/water_heater_monitor.ino
+++ water_heater_monitor/water_heater_monitor.ino
@@ -25,6 +25,8 @@
   // debugging...
   //strcpy(eagle_data, "0:05  120.0  110.0  12.0  159.0  100.0  110.0  ON  OFF  ");
   //postToPhant();
+  //data_index = 0;
+  //eagle_data[data_index] = '\0';
 }

 void loop () {
@@ -41,11 +43,6 @@
     }
   }

-  // Delays allow the ESP8266 to perform critical tasks
-  // defined outside of the sketch. These tasks include
-  // setting up, and maintaining, a WiFi connection.
-  delay(100);
-
   while (Serial.available()) {
     char c = Serial.read();

@@ -59,11 +56,15 @@

       unsigned long now = millis();

-      if ((now > lastUpdateTime + 60000 || now < lastUpdateTime) && strncmp(eagle_data, "RUNTIME", 7) != 0 && strchr(eagle_data, ':') != NULL) {
+      if ((now > lastUpdateTime + 60000 || now < lastUpdateTime) && strncmp(eagle_data, "RUNTIME", 7) != 0 && (eagle_data[1] == ':' || eagle_data[2] == ':')) {
         if (postToPhant()) {
           lastUpdateTime = now;
         }
       }
+
+      // Reset the data.  Hitting an LF should always do this, succesful send or not
+      data_index = 0;
+      eagle_data[data_index] = '\0';
     } else if (c != '\r') {
       // Capture everything else (but not a CR)
       if (data_index < 80) {
@@ -74,6 +75,8 @@
       }
       eagle_data[data_index] = '\0';
     }
+
+    yield();    // Yeild to the ESP8266 here, just in case
   }
 }

@@ -151,10 +154,6 @@

   phant.add("ambient_t", dht.readTemperature(true));

-  // Reset the eagle_data regardless of a successful send or not
-  data_index = 0;
-  eagle_data[data_index] = '\0';
-
   // Now connect to data.sparkfun.com, and post our data:
   WiFiClient client;


added header comments

added header comments

--- sweep_program1.ino
+++ sweep_program1.ino
@@ -1,4 +1,7 @@

+// sweep-program: Teensy 3.1 Arduino program to control 8 servos and 8 PWM laser outputs
+// for the kinetic artwork described here: http://www.instructables.com/id/Kinetic-light-work-with-servo-controlled-laser-mod/
+// Uses cos8() from the FastLED library http://fastled.io/

 #include "FastLED.h"
 #include <Servo.h>
@@ -6,8 +9,6 @@
 #include "gamma.h"

-//Servo myservo;  // create servo object to control a servo
-// a maximum of eight servo objects can be created

 int pos = 0;    // variable to store the servo position

@@ -17,6 +18,8 @@

 // number of channels
 #define NC 8
+
+

 Servo servo0;
 Servo servo1;
@@ -89,6 +92,7 @@

   Serial.begin(9600);

+  // can't do this in a loop for whatever reason :(
   servo0.attach(servo_pins[0]);
   servo1.attach(servo_pins[1]);
   servo2.attach(servo_pins[2]);
@@ -114,8 +118,7 @@
 }

-void loop()
-{
+void loop() {
   int button_state;

   // implement state machine


v3.2 Fix time display

v3.2 Fix time display

--- WeatherDisplay.ino
+++ WeatherDisplay.ino
@@ -450,9 +450,11 @@
   int TimeErrorOffset = -3;
   if (((time > 18) && (time < 21)) ||
       (time == 12) ||
-      (time == 0)  ||
       (time == 15)) {
     time += (TimeErrorOffset + 2);
+  }
+  else if (time == 0) {
+    time += (TimeErrorOffset + 0);
   }
   else {
     time += TimeErrorOffset;


'sketch' resolution independent

'sketch' resolution independent

--- sketch.ino
+++ sketch.ino
@@ -6,19 +6,19 @@
 {
   Serial.begin(115200); // JCB
   GD.begin();
-  GD.cmd_memset(0, 0, 480UL * 272UL);   // clear the bitmap
+  GD.cmd_memset(0, 0, long(GD.w) * GD.h);   // clear the bitmap
   GD.Clear();                           // draw the bitmap

-  GD.ColorRGB(0x101020);
+  GD.ColorRGB(0x202030);
   GD.cmd_text(240, 136, 31, OPT_CENTER, "sketch demo");

-  GD.BitmapLayout(L8, 480, 272);
-  GD.BitmapSize(NEAREST, BORDER, BORDER, 480, 272);
+  GD.BitmapLayout(L8, GD.w, GD.h);
+  GD.BitmapSize(NEAREST, BORDER, BORDER, GD.w, GD.h);
   GD.Begin(BITMAPS);
   GD.ColorRGB(0xffffff);
   GD.Vertex2ii(0, 0);
   GD.swap();
-  GD.cmd_sketch(0, 0, 480, 272, 0, L8); // start sketching
+  GD.cmd_sketch(0, 0, GD.w, GD.h, 0, L8); // start sketching
   GD.finish();                          // flush all commands
 }


turn down brightness a tad

turn down brightness a tad

--- src/blinky.ino
+++ src/blinky.ino
@@ -12,8 +12,6 @@
 #define PIXEL_TYPE NSFastLED::NEOPIXEL
 #define HUE_STEP 2 // 1..255, each loop increments hue by this value
 #define LOOP_DELAY_MS 50 //ms
-#define HSV_BRIGHTNESS 255
-#define HSV_SATURATION 255
 /* set this to match the number of patterns you flip
 between when holding the setup button */
 #define N_PATTERNS 3
@@ -32,7 +30,7 @@
 NSFastLED::CRGB leds[PIXEL_COUNT];
 uint8_t base_hue = 0;
 uint8_t pattern = 0;
-unsigned long gBrightness = 17;
+unsigned long gBrightness = 10;
 // this is ghetto debouncing, and will ignore input to the pattern button
 // for X cycles of LOOP_DELAY_MS once triggered
 uint8_t ignore_button_cycles = 0;
@@ -104,7 +102,7 @@
   NSFastLED::CHSV hsv;
   for (int i = 0 ; i < PIXEL_COUNT ; ++i){
     offset = ((float)i/(PIXEL_COUNT-1))*255;
-    hsv = NSFastLED::CHSV(base_hue+offset, HSV_SATURATION, HSV_BRIGHTNESS);
+    hsv = NSFastLED::CHSV(base_hue+offset, 255, 255);
     NSFastLED::hsv2rgb_rainbow(hsv, rgb);
     //if (random(PIXEL_COUNT*2) == 0) {
     //  leds[i] = NSFastLED::CRGB::White;
@@ -114,7 +112,7 @@
   }

   // set the center pixel to mirror what pixel 0 is
-  hsv = NSFastLED::CHSV(base_hue+offset, HSV_SATURATION, HSV_BRIGHTNESS);
+  hsv = NSFastLED::CHSV(base_hue+offset, 255, 255);
   hsv2rgb_rainbow(hsv, rgb);
   RGB.color(rgb.r, rgb.g, rgb.b);

@@ -146,7 +144,7 @@
 // rainbow pulsing with varied breathing cycles
 void pattern_phase_rainbow_pulse() {
   uint8_t cBrightness = NSFastLED::beatsin8(128, 0, 255);
-  NSFastLED::CHSV hsv = NSFastLED::CHSV(base_hue, HSV_SATURATION, cBrightness);
+  NSFastLED::CHSV hsv = NSFastLED::CHSV(base_hue, 255, cBrightness);
   NSFastLED::CRGB rgb;
   NSFastLED::hsv2rgb_rainbow(hsv, rgb);
   for (int i = 0 ; i < PIXEL_COUNT ; ++i){
@@ -159,7 +157,7 @@

 // pattern 3
 void pattern_hsv_circle_loop(){
-  NSFastLED::CHSV hsv = NSFastLED::CHSV(base_hue, HSV_SATURATION, HSV_BRIGHTNESS);
+  NSFastLED::CHSV hsv = NSFastLED::CHSV(base_hue, 255, 255);
   NSFastLED::CRGB rgb;
   NSFastLED::hsv2rgb_rainbow(hsv, rgb);
   for (int i = 0 ; i < PIXEL_COUNT ; ++i){


[feat] shunt turntime is dependant of temperature difference.

--- heater_control.ino
+++ heater_control.ino
@@ -13,6 +13,7 @@
 #define AD_SAMPLECNT 10
 #define FLAGS_DATACHANGE 0x01
 #define FLAGS_TIMEOUT 0x02
+#define FLAGS_EVALUATE 0x04

 #define OUTIO_ACTIVE 0x01

@@ -93,6 +94,7 @@
   struct variable *limit;
   struct variable *limit2;
   void *target;
+  time_t last_chk;
   int method;
 };

@@ -103,7 +105,7 @@
   {"boilReduced",   24.0},
   {"hhboil",        25.0},
   {"radiatorReq",   22.0}, // radiator requested temperature
-  {"radiatorAdd",   23.0},
+  {"radiatorAdd",   16.0},
   {"null",          0.0}
 };

@@ -138,13 +140,13 @@
   int target;
 };

-struct convert radiatorTab[]={ -30,22, // ambient -30 -> radiator 44.72 (remember to add "radiatorAdd")
-			       -20,19,
-			       -10,16,
-			         0,13,
-			        10,10,
+struct convert radiatorTab[]={ -30,33, // ambient -30 -> radiator=radiatorAdd+this
+			       -20,31,
+			       -10,28,
+			         0,21,
+			        10,11,
 			        20, 2,
-			       0xff,0xff}; // terminator
+			        0xff,0xff}; // terminator

 /*
  * METHOD_TURNON
@@ -170,25 +172,24 @@
  * and to store them to eeprom.
  */
 struct condition conditions[]= {
-  {0,&adArr[0],&variables[0],&variables[1],&outIoArr[0], METHOD_TURNON},       // start boiler if it is under 24.5, and off when it has reached 26.0
-  {1,&adArr[2],&variables[3],&variables[0],&variables[2],METHOD_CHANGELIMIT},  // if hothousewater is under hhboil, then boilTemp should be boilReduced.
-  {2,&adArr[1],&variables[5],&variables[4],radiatorTab,  METHOD_TABLE},        // changes in ambient will change radiatorReq with the help of radiatorAdd variable and radiatorTab table.
-  {3,&adArr[3],&variables[5],&variables[4],radiatorTab,  METHOD_TABLE_RECHECK} // changes in radiator will re-check radiatorReq.
+  {0,&adArr[0],&variables[0],&variables[1],&outIoArr[0], 0,METHOD_TURNON},       // start boiler if it is under 24.5, and off when it has reached 26.0
+  {1,&adArr[2],&variables[3],&variables[0],&variables[2],0,METHOD_CHANGELIMIT},  // if hothousewater is under hhboil, then boilTemp should be boilReduced.
+  {2,&adArr[1],&variables[5],&variables[4],radiatorTab,  0,METHOD_TABLE}        // changes in ambient will change radiatorReq with the help of radiatorAdd variable and radiatorTab table.
 };

 Timer sched;
 int measTimeout=1800;
-int shuntTimer=-1;

 EthernetClient client;
-M2XStreamClient m2xClient(&client, m2xKey);
+M2XStreamClient m2xClient(&client, m2xKey,idler);
 EthernetServer ipserver = EthernetServer(9000);
 EthernetClient ipclient;
 EthernetUDP Udp;
 unsigned int localPort = 8888;  // local port to listen for UDP packets
 Iot iot(&m2xClient);
+int adReadCnt;

 void setup() {
   int succ;
@@ -226,11 +227,13 @@
     }
     Serial.println();
   }
+  resetAdChannels(adArr,(sizeof(adArr) / sizeof(struct ad)));
   ipserver.begin();
   Udp.begin(localPort);
   setSyncInterval(7200);
   setSyncProvider(getNtpTime);
   sched.every(1000,processSensors);
+  sched.every(30000,evaluateConditions);
   sched.every(200,checkEthernet);
   _counters=(int *) malloc(sizeof(int) * sizeof(cntArr) / sizeof(struct cnt));
   for (int i=0;i<(sizeof(cntArr) / sizeof(struct cnt));i++) {
@@ -247,6 +250,11 @@
   refreshEvents();
 }

+void idler()
+{
+  sched.update();
+}
+
 void irqh0()
 {
   _counters[0]++;
@@ -271,18 +279,18 @@

 void processSensors()
 {
-  static int cnt=0;
+  //static unsigned int cnt=0;
   boolean timeouts=false;
   boolean cntTimeouts,cntChanges;
   boolean changes=false;
   time_t ts=now();
   int chcnt=(sizeof(adArr) / sizeof(struct ad));

-  if (!cnt)
-    resetAdChannels(adArr,chcnt);
-  readAdChannels(adArr,chcnt);
-  cnt++;
-  if ((cnt % AD_SAMPLECNT)==0) {
+  //if (!cnt)
+  //  resetAdChannels(adArr,chcnt);
+  //readAdChannels(adArr,chcnt);
+  //cnt++;
+  if (readAdChannels(adArr,chcnt)) {
     sched.oscillate(13,150, LOW,2);
     cntTimeouts=chkCntTimeouts(ts,false);
     cntChanges=chkCntChanged();
@@ -303,6 +311,7 @@
   }
 }

+
 void evaluateCondition(struct ad *source,time_t ts)
 {
   float value;
@@ -314,6 +323,9 @@

   for (int i=0;i<sizeof(conditions) / sizeof(struct condition);i++) {
     if (conditions[i].source == source) {
+      if (ts - conditions[i].last_chk < 30)
+	return;
+      conditions[i].last_chk = ts;
       value=source->measured.analog;
       limit=conditions[i].limit->value;
       switch (conditions[i].method) {
@@ -343,47 +355,35 @@
       case METHOD_TABLE:
 	iTable=(struct convert *) conditions[i].target;
 	conditions[i].limit2->value=resolveConversion(value,conditions[i].limit->value,iTable);
-        Serial.print(" requested radiator temp is ");
-        Serial.println(conditions[i].limit2->value);
-      case METHOD_TABLE_RECHECK:
 	float radReq=conditions[i].limit2->value;
 	float radiator=adArr[3].measured.analog;
 	float diff=radReq-radiator;

 	if (radiator==-273) // in startup this is -273 = 0 kelvin.
 	  return;
-	if (shuntTimer != -1) {
-	  sched.stop(shuntTimer);
-	  shuntTimer=-1;
-	}
+
+	Serial.print("requested radiator temp is ");
+	Serial.print(radReq);
+	Serial.print(" diff is ");
+	Serial.println(diff);
+	long turntime=abs(diff) * 1000;
+        if (turntime > 10000)
+	  turntime=10000;
+	else if (turntime < 800)
+	  turntime=800;
 	if (diff > 0.3) {
-          Serial.print("diff=");
-	  Serial.print(diff);
-	  Serial.println(" starting shunt up timer");
-	  shuntTimer=sched.every(9000,shuntUp);
+          sched.oscillate(30,turntime,LOW,1);
 	}
 	else if (diff < -0.3) {
-          Serial.print("diff=");
-	  Serial.print(diff);
-	  Serial.println(" Starting shunt down timer");
-	  shuntTimer=sched.every(9000,shuntDn);
+          sched.oscillate(31,turntime,LOW,1);
 	}
-        else
-	  Serial.println("turned shunt timer off");
+        else {
+	  conditions[i].source->flags &= ~FLAGS_EVALUATE;
+	}
 	break;
       }
     }
   }
-}
-
-void shuntUp()
-{
-  sched.oscillate(30,3000,LOW,1);
-}
-
-void shuntDn()
-{
-  sched.oscillate(31,3000,LOW,1);
 }

@@ -404,6 +404,10 @@
       break;
     }
   }
+  Serial.print("target = ");
+  Serial.print(start->source);
+  Serial.print(" / ");
+  Serial.println(stop->source);
   ret = (adder + start->target) - ((v - start->source) / (stop->source - start->source) * (start->target - stop->target));
   return ret;
 }
@@ -623,10 +627,13 @@
   int ddelta;
   float adelta;

+  adReadCnt++;
   for (int analogChannel = 0; analogChannel < cnt; analogChannel++) {
     digital= analogRead(ad[analogChannel].port);
     ad[analogChannel].measured.digital += digital;
   }
+  if (adReadCnt==AD_SAMPLECNT)
+    return 1;
   return 0;
 }

@@ -640,6 +647,7 @@
   for (int analogChannel = 0; analogChannel < cnt; analogChannel++) {
     if (ts-ad[analogChannel].last_send > timeout) {
       ad[analogChannel].flags |= FLAGS_DATACHANGE;
+      ad[analogChannel].flags |= FLAGS_EVALUATE;
       ret=true;
     }
   }
@@ -656,6 +664,7 @@
     digital = ad[analogChannel].measured.digital;
     if ((abs(digital - ad[analogChannel].prev.digital)) > ad[analogChannel].diff.digital) {
       ad[analogChannel].flags |= FLAGS_DATACHANGE;
+      ad[analogChannel].flags |= FLAGS_EVALUATE;
       ret=true;
     }
   }
@@ -673,7 +682,7 @@

   for (int analogChannel = 0; analogChannel < cnt; analogChannel++) {
     if (ad[analogChannel].flags & FLAGS_DATACHANGE) {
-      digital = ad[analogChannel].measured.digital / AD_SAMPLECNT;
+      digital = ad[analogChannel].measured.digital / adReadCnt;
       // inter- and extrapolation
       ddelta=ad[analogChannel].delta.digital;
       adelta=ad[analogChannel].delta.analog;
@@ -690,10 +699,21 @@
   return 0;
 }

+void evaluateConditions() {
+  int cnt=sizeof(adArr) / sizeof(struct ad);
+  time_t ts=now();
+
+  for (int i = 0; i < cnt; i++) {
+    if (adArr[i].flags & FLAGS_EVALUATE)
+      evaluateCondition(&adArr[i],ts);
+  }
+}
+
 void resetAdChannels(struct ad *ad, int cnt)
 {
   for (int analogChannel = 0; analogChannel < cnt; analogChannel++) {
     ad[analogChannel].flags &= ~FLAGS_DATACHANGE;
     ad[analogChannel].measured.digital = 0;
   }
-}
+  adReadCnt=0;
+}


Simplified the example a lot and finally got rid of the A-Star stuff.

--- examples/StepTest/StepTest.ino
+++ examples/StepTest/StepTest.ino
@@ -1,37 +1,18 @@
 #include <SPI.h>
 #include <AMIS30543.h>
-#include <AStar32U4Prime.h>  // TODO: remove

 const uint8_t amisSlaveSelect = 10;
 const uint8_t amisStepPin = 9;

 AMIS30543 stepper;

-AStar32U4PrimeButtonA buttonA;
-AStar32U4PrimeButtonB buttonB;
-AStar32U4PrimeButtonC buttonC;
-
 void setup()
 {
-  delay(1000);
-  Serial.begin(9600);
-  Serial.println("start");
+  SPI.begin();
+  pinMode(amisStepPin, OUTPUT);
+  delay(1);

-  SPI.begin();  //initialize SPI
   stepper.init(amisSlaveSelect);
-
-  pinMode(amisStepPin, OUTPUT);
-
-  Serial.println("AMIS SPI test");
-  while (1)
-  {
-    if (buttonB.getSingleDebouncedRelease())
-    {
-      Serial.println("button pushed");
-      break;
-    }
-  }
-
   stepper.setCurrentMilliamps(500);
   stepper.enableDriver();
 }


Delete C_CDELEM-Arduino.ino

Delete C_CDELEM-Arduino.ino

--- Examples/C_CDELEM-Arduino/C_CDELEM-Arduino.ino
+++ Examples/C_CDELEM-Arduino/C_CDELEM-Arduino.ino
@@ -1,56 +0,0 @@
-/*-------------------------------------------------------------------------------------------------------------------------------------------*
- * SE2R : C_CDELEM - Fonction de commande de booléen avec prise en compte de forçage et de défaut - Arduino                       12/06/2015 *
- *-------------------------------------------------------------------------------------------------------------------------------------------*
- *        C_CDELEM(boolean CDE, boolean DFT, boolean RES[], int CFG)                                                              12/06/2015 *
- *                CDE : Commande calculée ou donnée par l'utilisateur (peut être le résultat d'une fonction appelée plus haut)               *
- *                DFT : Défaut de l'équipement commandé. True signale un équipement en état normal. Un false signale un défaut               *
- *                RES : [00] Commande de l'équipement - forcément un tableau de taille au moins 1                                            *
- *                CFG : Commande de forçage.                                                                                *
- *                      <0 : RES maintenu à false                                                                                *
- *                      0  : RES figée dans son dernier état connu                                                                           *
- *                      1  : RES soumise à CDE et à DEF                                                                                *
- *                      2  : RES soumise seulement à DEF (comme si CDE était true en permanence)                                             *
- *                      3  : RES  maintenu à true                                                                                *
- *                      >3 : RES maintenu à false                                                                                *
- *-------------------------------------------------------------------------------------------------------------------------------------------*
- * Copyright SE2R under the APACHE Licence                                                                                *
- *-------------------------------------------------------------------------------------------------------------------------------------------*
- * Plate-formes testées : Arduino Leonardo, Arduino Uno, Industruino                                                                         *
- *-------------------------------------------------------------------------------------------------------------------------------------------*
- * 03/06/2015 : DD, SE2R : Testée et validée sur banc                                                                                *
- * 12/06/2015 : DD, SE2R : Ajout des commentaires d'appartenance à C_CDELEM                                                                  *
- *-------------------------------------------------------------------------------------------------------------------------------------------*/
-
-// Déclaration des bibliothèques nécessaires à l'exécution du programme ---------------------------------------------------------------------*
-#include <BMS.h>                         // Biblio   - SE2R - Fonctions BMS
-BMS BMS;
-
-// Déclaration des variables nécessaires à l'exécution de la fonction -----------------------------------------------------------------------*
-boolean FCO_XXXX;                        // C_CDELEM - Commande de marche depuis l'extérieur
-boolean ED2_DGL_XXXX;                    // C_CDELEM - Etat de l'information de défaut
-boolean FCC_XXXX[1];                     // C_CDELEM - Etat de la commande à transmettre à la sortie
-int VCO_XXXX;                            // C_CDELEM - Commande de forçage, ici en position auto
-void setup() {                           // Initialisation ----------------------------------------------------------------------------------*
-  pinMode(0, INPUT);                     // C_CDELEM - Affectation de la voie 00 en tant qu'entrée
-  pinMode(1, INPUT);                     // C_CDELEM - Affectation de la voie 01 en tant qu'entrée de commande
-  pinMode(7, OUTPUT);                    // C_CDELEM - Affectation de la voie 07 en tant que sortie
-  VCO_XXXX = 1;                          // C_CDELEM - Passage du forçage en position auto
-  Serial.begin(9600);                    // Port COM - Paramétrage du port série
-}
-void loop() {                            // Exécution ---------------------------------------------------------------------------------------*
-  if (digitalRead(2) == LOW) { ED2_DGL_XXXX = true; } else { ED2_DGL_XXXX = false; }  // Entrée de défaut NF (shunt = normal)
-  if (digitalRead(3) == LOW) { FCO_XXXX = true; } else { FCO_XXXX = false; }          // Entrée de demande de marche NO (shunt = demande)
-  BMS.C_CDELEM(FCO_XXXX, ED2_DGL_XXXX, FCC_XXXX, VCO_XXXX);
-  if (FCC_XXXX[0]) { digitalWrite(7, HIGH); } else { digitalWrite(7, LOW); }
-  Serial.print("Demande : ");
-  Serial.print("\t");
-  Serial.print(FCO_XXXX);
-  Serial.print("\t");
-  Serial.print("Defaut : ");
-  Serial.print("\t");
-  Serial.print(ED2_DGL_XXXX);
-  Serial.print("\t");
-  Serial.print("Commande : ");
-  Serial.print("\t");
-  Serial.println(FCC_XXXX[0]);
-}


Added a minimum difference between the extrema, so
the shofanduino doesn't turn on the fan when it
is connected for the first time, or when it is
reset.

This also needs a cap for the maximum, otherwise
it will go above the maximum value that the sensor
will give back!

--- shofanduino2/shofanduino2.ino
+++ shofanduino2/shofanduino2.ino
@@ -106,6 +106,8 @@
 // consts/variables for humidity sensor and averages etc.
 const int sensorPin = A0;    // select the input pin for the potentiometer
 const int milliseconds_sleep = 5000;
+const float min_humidity_diff= 10.0; // RH %
+const float max_humidity = 100.0; // needed because we add min_humidity_diff

 float thresholdLow = 0.0;
 float thresholdHigh = 0.0;
@@ -212,10 +214,13 @@
     // and env_min, so this means env_min goes up!
     env_min = humidity - (humidity - env_min) * env_min_decay;
   }
-  if (env_max < humidity) {
-    env_max = humidity;
+  float humidity_margin = humidity + min_humidity_diff;
+  humidity_margin = min(humidity_margin, max_humidity);
+
+  if (env_max < humidity_margin) {
+    env_max = humidity_margin;
   } else {
-    env_max = humidity + (env_max - humidity) * env_max_decay;
+    env_max = humidity_margin + (env_max - humidity_margin) * env_max_decay;
   }

   // New thresholds based on the envelope values. We


scale update

scale update

average, espReset

--- _03-hx711-scale-v2-battery-external-Interrupt-02/_03-hx711-scale-pro-mini/_03-hx711-scale-pro-mini.ino
+++ _03-hx711-scale-v2-battery-external-Interrupt-02/_03-hx711-scale-pro-mini/_03-hx711-scale-pro-mini.ino
@@ -162,11 +162,13 @@

   if ( Measured > 500 )
   {
+    delat(2000);
+    int average_Measured = int( scale.get_units(5) * 1000 );
     Serial.println("======> tilting detected, nemo is on pad");
-    /*
-    digitalWrite(espnemoIsOnPadPin, HIGH);
-    espReset();
-    */
+
+    for (int thisReading = 0; thisReading < numReadings; thisReading++) {
+      readings[thisReading] = average_Measured ;
+    }

   } else {
     Serial.println("======> tilting detected, but nemo is not on pad");
@@ -178,79 +180,73 @@
 void loop()
 {

-  //Serial.print("=====> checking weight :  ");
-  //Serial.println(millis() - startMills);
-  if ( IsEspReseted == LOW ) {
+  if ( IsEspReseted == LOW )
+  {
       Measured = int( scale.get_units(5) * 1000 );
-      Serial.println("");
       Serial.print("==> weight : ");
       Serial.print(Measured);
       Serial.print(" ==> ");
-  }
-
-  if (( Measured > 500 ) && ( Measured > (average - 200)) && ( IsEspReseted == LOW ) )
-  {
-    // Serial.println("======> nemo is on pad now");
-
-    total = total - readings[indexof];
-    readings[indexof] = Measured;
-    total = total + readings[indexof];
-    indexof = indexof + 1;
-
-    if (indexof >= numReadings)
-      indexof = 0;
-
-    average = total / numReadings;
-
-    Serial.print("  average ==>  ");
-    Serial.println(average);
-
-  }
-
-  if ( ( Measured <= 500 ) && ( IsEspReseted == LOW ) ) {
-    if ( Attempt == 1) {
-      Serial.println("");
-      Serial.print("============> nemo is not on pad now");
-    }
-    Serial.println("");
-    Attempt++;
+
+      if (( Measured > 500 ) && ( Measured > (average - 500)))
+      {
+            total = total - readings[indexof];
+            readings[indexof] = Measured;
+            total = total + readings[indexof];
+            indexof = indexof + 1;
+
+            if (indexof >= numReadings)
+            {
+              indexof = 0;
+            }
+
+            average = total / numReadings;
+
+            Serial.print("  average ==>  ");
+            Serial.println(average);
+      } else {
+            Serial.println("");
+      }
+
+      if ( Measured <= 500 )
+      {
+            if ( Attempt == 0 )
+            {
+              Serial.println("");
+              Serial.print("============> nemo is not on pad now");
+            }
+            Serial.println("");
+            Attempt++;
+      }
+
+      if ( Attempt == 10 )
+      {
+            Serial.println("======> Measurement has problem");
+            sleepNow();
+      }
+
+      if (( average > 1000 ) && ( Measured < (average - 1000)) )
+      {
+            VccValue = vcc.Read_Volts() * 1000 ;
+            Serial.println("");
+            Serial.print("==========> VCC ");
+            Serial.println(VccValue);
+            espReset();
+            IsEspReseted = HIGH;
+            Attempt = 0;
+      }
+      delay(500);
   }

   if ( IsEspReseted == HIGH ) {
-    Attempt++;
-  }
-
-  if (( average > 1000 ) && ( Measured < (average - 500)) && ( IsEspReseted == LOW ))
-  {
-    VccValue = vcc.Read_Volts() * 1000 ;
-    Serial.println("");
-    Serial.print("==========> VCC ");
-    Serial.println(VccValue);
-    //digitalWrite(espnemoIsOnPadPin, HIGH);
-    espReset();
-    digitalWrite(ledPowerPin, LOW);
-    delay(200);
-    digitalWrite(ledPowerPin, HIGH);
-    delay(200);
-    digitalWrite(ledPowerPin, LOW);
-    delay(200);
-    digitalWrite(ledPowerPin, HIGH);
-    IsEspReseted = HIGH;
-    Attempt = 0;
-    //delay(5000);
-  }
-
-  if (( Attempt == 20 ) && ( IsEspReseted == LOW ) )
-  {
-    Serial.println("======> Measurement has problem");
-    sleepNow();
-  }
-
-  if (( Attempt == 20 ) && ( IsEspReseted == HIGH ))
-  {
-    Serial.println("======> I2C has problem");
-    sleepNow();
-  }
+      Attempt++;
+      if ( Attempt == 20 )
+      {
+          Serial.println("======> I2C has problem");
+          sleepNow();
+      }
+      delay(1000);
+  }
+

   if ( mqttMsgSent == HIGH )
   {
@@ -261,12 +257,6 @@
     sleepNow();
   }

-  if ( IsEspReseted == LOW )
-  {
-    delay(500);
-  } else {
-    delay(1000);
-  }
 }

 void espReset()
@@ -275,6 +265,15 @@
   digitalWrite(espResetPin, LOW);
   delay(10);
   digitalWrite(espResetPin, HIGH);
+
+  digitalWrite(ledPowerPin, LOW);
+  delay(100);
+  digitalWrite(ledPowerPin, HIGH);
+  delay(100);
+  digitalWrite(ledPowerPin, LOW);
+  delay(100);
+  digitalWrite(ledPowerPin, HIGH);
+
 }

 void requestEvent()


Display current network parameters

Display current network parameters

--- Arduino_ESP8266_HttpServer.ino
+++ Arduino_ESP8266_HttpServer.ino
@@ -4,6 +4,14 @@

 int req[CHANNELS];
 char buff[BUFFER_SIZE+1];
+
+#define MAX_APNAME 64
+typedef struct NParams {
+  char APNAME[MAX_APNAME+1]="";
+  char APIP[3*4+3+1]="";
+  char JAPNAME[MAX_APNAME+1]="";
+  char STAIP[3*4+3+1]="";
+};

 const char PROGMEM headers_A[BUFFER_SIZE] = "Content-Type: text/html\r\nCache-Control: no-cache, no-store, must-revalidate\r\n";
 const char PROGMEM headers_B[BUFFER_SIZE] = "Pragma: no-cache\r\nExpires: -1\r\n\r\n";
@@ -113,6 +121,40 @@
           //DEBUG_SERIAL.println("CWLAP char at");
           //DEBUG_SERIAL.println(i);
         }
+      }
+    }
+  }
+}
+
+void callbackIP(char* line, void* context) {
+  NParams* p = (NParams*)context;
+  int o = 0;
+  int max = 0;
+  char* dst = NULL;
+  if (memcmp_P(line, PSTR("+CWSAP_CUR:\""), 12)==0) {
+    o = 12;
+    max = MAX_APNAME;
+    dst = p->APNAME;
+  } else if (memcmp_P(line, PSTR("+CWJAP_CUR:\""), 12)==0) {
+    o = 12;
+    max = MAX_APNAME;
+    dst = p->JAPNAME;
+  } else if (memcmp_P(line, PSTR("+CIFSR:APIP,\""), 13)==0) {
+    o = 13;
+    max = 3*4+3+1;
+    dst = p->APIP;
+  } else if (memcmp_P(line, PSTR("+CIFSR:STAIP,\""), 14)==0) {
+    o = 14;
+    max = 3*4+3+1;
+    dst = p->STAIP;
+  }
+  if (dst != NULL) {
+    for (int i = o; i-o < max; i++) {
+      if (line[i] == '"') {
+        break;
+      } else {
+        dst[i-o]=line[i];
+        dst[i-o+1]=0;
       }
     }
   }
@@ -133,17 +175,46 @@
     //netsend(n, buff);
   } else if (req[n] == 2) {
     char wifilist[CWLAP_MAX_LEN] = "";
-    commandWaitCallback_P(PSTR("AT+CWLAP\r\n"), 10000, 1000, &callbackCWLAP, (void*)wifilist);
-    while(waitData(100)) {
-      readLine();
-    }
     netsend_P(n, STATUS_200);
     netsend_P(n, headers_A);
     netsend_P(n, headers_B);
     netsend_P(n, HTML_PART_A);
     netsend_P(n, PSTR("Arduino httpd"));
     netsend_P(n, HTML_PART_B);
-    netsend_P(n, PSTR("WiFi networks:\r\n
"));
+
+    NParams nparams;
+    commandWaitCallback_P(PSTR("AT+CIFSR\r\n"), 1000, 1000, &callbackIP, (void*)&nparams);
+    commandWaitCallback_P(PSTR("AT+CWSAP_CUR?\r\n"), 1000, 1000, &callbackIP, (void*)&nparams);
+    commandWaitCallback_P(PSTR("AT+CWJAP_CUR?\r\n"), 1000, 1000, &callbackIP, (void*)&nparams);
+
+    netsend_P(n, PSTR("Network parameters:

SOFTAP NAME: "));
+    if (nparams.APNAME[0] != 0) {
+      netsend(n, nparams.APNAME);
+    } else {
+      netsend_P(n, PSTR("DISABLED"));
+    }
+    netsend_P(n, PSTR("

SOFTAP IP: "));
+    if (nparams.APIP[0] != 0) {
+      netsend(n, nparams.APIP);
+    } else {
+      netsend_P(n, PSTR("DISABLED"));
+    }
+    netsend_P(n, PSTR("

WLAN NAME: "));
+    if (nparams.JAPNAME[0] != 0) {
+      netsend(n, nparams.JAPNAME);
+    } else {
+      netsend_P(n, PSTR("NOT CONNECTED"));
+    }
+    netsend_P(n, PSTR("

WLAN IP: "));
+    if (nparams.STAIP[0] != 0) {
+      netsend(n, nparams.STAIP);
+    } else {
+      netsend_P(n, PSTR("NOT CONNECTED"));
+    }
+    netsend_P(n, PSTR("

"));
+
+    commandWaitCallback_P(PSTR("AT+CWLAP\r\n"), 10000, 1000, &callbackCWLAP, (void*)wifilist);
+    netsend_P(n, PSTR("WiFi networks:
"));
     char* token = strtok(wifilist, "\t");
     while (token != NULL) {
       buff[0] = 0;
@@ -153,7 +224,8 @@
       netsend(n, buff);
       token = strtok(NULL, "\t");
     }
-    netsend_P(n, PSTR("
<form method='GET'>Connect to network:"));
+
+    netsend_P(n, PSTR("
<form method='GET' action='wifisave'>Connect to network:"));
     netsend_P(n, PSTR("<input type='text' placeholder='network' name='n'/>"));
     netsend_P(n, PSTR("<input type='text' placeholder='password' name='p'/>"));
     netsend_P(n, PSTR("<input type='submit' value='Connect/Disconnect'/></form>"));


Migrate to m190 based printing.

Migrate to m190 based printing.

--- paperwallet/paperwallet.ino
+++ paperwallet/paperwallet.ino
@@ -1,185 +0,0 @@
-// Copyright 2013 Steven Pearson
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-#include <panic.h>
-#include <progress.h>
-#include <bignat.h>
-#include <bigint.h>
-#include <sha256.h>
-#include <rmd160.h>
-#include <base58.h>
-#include <bitelliptic.h>
-#include <bitaddress.h>
-#include <rng.h>
-#include <qrencode.h>
-#include <lcd5510.h>
-#include <printer.h>
-
-//Read high fuse bits
-//avrdude -v -patmega328p -cusbtiny -U hfuse:r:hfuse.txt:b
-
-//Disable Bootloader on reset
-//avrdude -v -patmega328p -cusbtiny -U hfuse:w:0xDF:m
-
-//Enable bootloader on reset
-//avrdude -v -patmega328p -cusbtiny -U hfuse:w:0xDE:m
-
-//burn without bootloader
-//avrdude -v -patmega328p -cusbtiny -U hfuse:w:0xDF:m -Uflash:w:/tmp/build2279538609720273931.tmp/paperwallet.cpp.hex:i
-
-void PANIC(byte errorCode){
-  Lcd::Clear();
-  Lcd::String(0,0,F("E"));
-  char buf[2];
-  buf[0]=errorCode+65;
-  buf[1]=NULL;
-  Lcd::String(0,1,buf);
-  for(;;){
-  }
-}
-
-void PROGRESS(float progress){
-  Lcd::Progress(5,progress);
-}
-
-void displayPrivate(uint8_t *PRIVATE){
-
-  char encoded[128];
-
-  bitaddress::generatePrivateWIF(PRIVATE,encoded,sizeof(encoded));
-
-  Lcd::Clear();
-  Lcd::String(0,0,F("Private Key"));
-  Lcd::String(0,1,encoded);
-}
-
-void displayPrivateQR(uint8_t *PRIVATE){
-  char encoded[128];
-  bitaddress::generatePrivateWIF(PRIVATE,encoded,sizeof(encoded));
-
-  Lcd::Clear();
-  displayQR(encoded);
-}
-
-void printPrivateQR(uint8_t *PRIVATE){
-  char encoded[128];
-  bitaddress::generatePrivateWIF(PRIVATE,encoded,sizeof(encoded));
-
-  printer::printPosition(F("477"),F("92"));
-  printQR(encoded);
-  char split[27];
-  memcpy(split,encoded,26);
-  split[26]=0;
-  printer::print(F("\x1B(s3T\x1B(s16H\x1B(s12V\r\n\x1b*p395X"));
-  printer::printLine(split);
-  printer::print(F("\x1b*p395X"));
-  printer::printLine(encoded+26);
-}
-
-void displayPublic(const struct bigint &x,const struct bigint &y){
-  char encoded[40];
-  bitaddress::generateAddress(x,y,encoded,sizeof(encoded));
-
-  Lcd::Clear();
-  Lcd::String(0,0,F("Address"));
-  Lcd::String(0,1,encoded);
-}
-
-void displayPublicQR(const struct bigint &x,const struct bigint &y){
-  char encoded[40];
-  bitaddress::generateAddress(x,y,encoded,sizeof(encoded));
-  Lcd::Clear();
-  displayQR(encoded);
-}
-
-void printPublicQR(const struct bigint &x,const struct bigint &y){
-  char encoded[40];
-  bitaddress::generateAddress(x,y,encoded,sizeof(encoded));
-  printer::print(F("\x1b*p1067Y\x1b*p257X"));
-  printer::printLine(encoded);
-  printer::printPosition(F("357"),F("1092"));
-  printQR(encoded);
-}
-
-void displayResults(uint8_t *PRIVATE,const struct bigint &x,const struct bigint &y){
-  displayPrivate(PRIVATE);
-  displayPublic(x,y);
-}
-
-void generatePrivateKey(uint8_t *PRIVATE){
-  rng::generate(PRIVATE);
-}
-
-void displayQR(const char *string){
-  qrcontext qr;
-
-  qr.qrencode(string);
-
-  Lcd::Bitmap(qr.qrframe);
-}
-
-void printQR(const char *string){
-  qrcontext qr;
-
-  qr.qrencode(string);
-
-  printer::printQR(qr);
-}
-
-uint8_t PRIVATE[32];
-WORD xbuf[32];
-WORD ybuf[32];
-struct bigint pubx(xbuf,sizeof(xbuf));
-struct bigint puby(ybuf,sizeof(ybuf));
-int state = 0;
-
-void setup(){
-  Lcd::Initialize();
-  Lcd::Clear();
-  //Lcd::String(17,1,F("Offline"));
-  Lcd::String(21,2,F("Wallet"));
-  //Lcd::String(11,3,F("Generator"));
-
-  pinMode(A1,INPUT);
-  pinMode(13,INPUT);
-  printer::initialize();
-
-  generatePrivateKey(PRIVATE);
-  bitaddress::generatePublicKey(PRIVATE,pubx,puby);
-}
-
-void loop(){
-  switch( state ){
-  case 0:
-    displayPrivate(PRIVATE);
-    break;
-  case 1:
-    displayPublic(pubx,puby);
-    break;
-  }
-  delay(1000);
-  int a1 = LOW;
-  int a0 = LOW;
-  while(a1==LOW && a0==LOW){
-    a0=digitalRead(13);
-    a1=digitalRead(A1);
-  }
-  if( a0 == HIGH ){
-    state++;
-    if( state == 2 ){
-      state =0;
-    }
-  }
-  else {
-    Lcd::Clear();
-    Lcd::String(0,1,F("Printing"));
-
-    printPrivateQR(PRIVATE);
-    printPublicQR(pubx,puby);
-    printer::formfeed();
-  }
-}
-
-
-


Update WebServer

Update WebServer

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

 // remote website ip address and port
-static byte _ttkserver[] = { 192, 168, 0, 1 };
+static byte _webserver[] = { 192, 168, 0, 1 };

 // Arduino IP
 static byte _arduinoIP[] = { 192, 168, 0, 42 };
@@ -234,7 +234,7 @@
   //ether.printIp(F("DNS IP: "), ether.dnsip);

   // Set Up destination IP
-  ether.copyIp(ether.hisip, _ttkserver);
+  ether.copyIp(ether.hisip, _webserver);
   ether.printIp(F("Destination Server: "), ether.hisip);

   // Register Ping Callback
@@ -533,7 +533,7 @@
   _app.eth.isHttpRequest = true;
   unsigned long dateHTTPrequest = millis();

-  ether.browseUrl(PSTR("/cakephp/points/add/"), _app.eth.url, PSTR("TTKSERVER"), requestUrlCallback);
+  ether.browseUrl(PSTR("/riot-server/points/add/"), _app.eth.url, PSTR("localhost"), requestUrlCallback);

   //
   // Wait end of HTTP Request


changed powerpin to match our dev boards

--- ardesp/power_switch_test/power_switch_test.ino
+++ ardesp/power_switch_test/power_switch_test.ino
@@ -10,8 +10,8 @@

 void setup() {

-  // Transmitter is connected to Arduino Pin #10
-  mySwitch.enableTransmit(4);
+  // Transmitter is connected to Arduino Pin #13
+  mySwitch.enableTransmit(13);

   // Optional set pulse length.
   // mySwitch.setPulseLength(320);


updated outside-deck with new sensors

updated outside-deck with new sensors

--- arduino/Sketches/outside_deck/outside_deck.ino
+++ arduino/Sketches/outside_deck/outside_deck.ino
@@ -1,7 +1,10 @@
 #include <Wire.h>
 #include <Adafruit_Sensor.h>
+#include <Adafruit_TSL2561.h>
+#include <aisa_TSL2561.h>
 #include <aisa_Cd5PhotoCell.h>
 #include <aisa_TMP36.h>
+#include <aisa_DHT.h>

 const String dataSeparator = ",";
 const String dataTypeTerminator = ":";
@@ -10,13 +13,17 @@

 aisa_TMP36 * tmp36;
 aisa_Cd5PhotoCell * cd5PhotoCell;
+aisa_TSL2561 * tsl2561;
+aisa_DHT * dht;

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

-    cd5PhotoCell = new aisa_Cd5PhotoCell(arduinoName, 4);
-    tmp36 = new aisa_TMP36(arduinoName, 5, 5.0, 100);
+    cd5PhotoCell = new aisa_Cd5PhotoCell(arduinoName, 0);
+    tmp36 = new aisa_TMP36(arduinoName, 1, 5.0, 100);
+    tsl2561 = new aisa_TSL2561(arduinoName);
+    dht = new aisa_DHT(arduinoName, 5, DHT22);
 }

 void sendDataSeparator()
@@ -72,6 +79,26 @@
     sendDataEnd(tmp36->getCelcius(false));
 }

+void sendTsl2561Data()
+{
+    sendDataType("TSL2561");
+    sendSensorName(tsl2561->getSensorName());
+    sendSensorPinName(tsl2561->getPinName());
+    sendData(tsl2561->getSensorId());
+    sendData(tsl2561->getLux());
+    sendData(tsl2561->getBroadband());
+    sendDataEnd(tsl2561->getInfrared(false));
+}
+
+void sendDhtData()
+{
+    sendDataType("DHT");
+    sendSensorName(dht->getSensorName());
+    sendSensorPinName(dht->getPinName());
+    sendData(dht->getTemperature());
+    sendDataEnd(dht->getHumidity());
+}
+
 void sendCd5PhotoCellData()
 {
     sendDataType("Cd5");
@@ -86,5 +113,14 @@

     sendCd5PhotoCellData();

-    delay(5000);
+    sendTsl2561Data();
+
+    sendDhtData();
+
+    delay(60000);
 }
+
+
+
+
+


Fixed error

Fixed error

--- mech/mech.ino
+++ mech/mech.ino
@@ -40,7 +40,7 @@
 	case cmdSetPos:
 		stepper1.moveTo(payload->pos.lPos);
 		stepper2.moveTo(payload->pos.c1Pos);
-		stepper2.moveTo(payload->pos.c2Pos);
+		stepper3.moveTo(payload->pos.c2Pos);
 		break;
 	}
 }


More efficient way to make sure NMEA has been validated before it ends up being parsed as GGA/RMC.

--- mega/mega.ino
+++ mega/mega.ino
@@ -2110,13 +2110,10 @@
     #endif
     b_string = gps_read_buffer;
     gps_read_buffer = nmea_read_buffer;
-    if(validate_and_maybe_remediate_gps_buffer())
-    {
-      parse_gps_buffer_as_gga();
-      if(gps_valid)
-      {
-        nmea_gga_timestamp = millis();
-      }
+    parse_gps_buffer_as_gga();
+    if(gps_valid)
+    {
+      nmea_gga_timestamp = millis();
     }
     gps_read_buffer = b_string;
   }
@@ -2128,13 +2125,10 @@
     #endif
     b_string = gps_read_buffer;
     gps_read_buffer = nmea_read_buffer;
-    if(validate_and_maybe_remediate_gps_buffer())
-    {
-      parse_gps_buffer_as_rmc();
-      if(gps_valid)
-      {
-        nmea_rmc_timestamp = millis();
-      }
+    parse_gps_buffer_as_rmc();
+    if(gps_valid)
+    {
+      nmea_rmc_timestamp = millis();
     }
     gps_read_buffer = b_string;
   }
@@ -2303,7 +2297,10 @@
   {
     a_string = nmea_read_buffer;
     nmea_read_buffer = hsnmea_read_buffer;
-    parse_nmea_sentence();
+    if(validate_nmea_buffer())
+    {
+      parse_nmea_sentence();
+    }
     nmea_read_buffer = a_string;
   }


Remove redundant spi code

Remove redundant spi code

--- transmitter/Monitor/Monitor.ino
+++ transmitter/Monitor/Monitor.ino
@@ -41,48 +41,12 @@
 //U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE|U8G_I2C_OPT_DEV_0);
 U8GLIB_SSD1306_128X64_2X u8g(U8G_I2C_OPT_NONE);

-// SPI interrupt routine
-ISR (SPI_STC_vect)
-{
-
-  // only listen if ss is low (arunino pin 8)
-  uint8_t port_b = PINB;
-  if (bitRead(port_b, PINB0)) {
-    return;
-  }
-
-  byte c = SPDR;  // grab byte from SPI Data Register
-
-  // add to buffer
-  if (spi_buffer_index < sizeof spi_buffer) {
-    spi_buffer[spi_buffer_index++] = c;
-  }
-
-  if (spi_buffer_index > 3) {
-    // full ack_payload
-    spi_buffer_index = 0;
-
-    // add to the buffer to be processed in loop
-    ack_payload.key = (spi_buffer[0] << 8) | spi_buffer[1];
-    ack_payload.val = (spi_buffer[2] << 8) | spi_buffer[3];
-    payload_buffer[payload_buffer_head] = ack_payload;
-
-    // Increment the index
-    payload_buffer_head++;
-    if (payload_buffer_head >= PAYLOAD_BUFFER_LENGTH) {
-      payload_buffer_head = 0;
-    }
-
-  }
-}
-
 void setup()
 {
   Serial.begin(115200);

   memset(&monitor, 0, sizeof(monitor_t));
   memset(&ack_payload, 0, sizeof(ack_t));
-

 }

@@ -142,37 +106,15 @@
     }
   }

-  // If head & tail are not in sync, process the next.
-  //if (payload_buffer_head != payload_buffer_tail) {
-  //  ack_t ack = payload_buffer[payload_buffer_tail];
-
-
-
-  /*
-    // Increment the tail index
-    payload_buffer_tail++;
-    if (payload_buffer_tail >= PAYLOAD_BUFFER_LENGTH) {
-      payload_buffer_tail = 0;
-    }
-    */
-  //}
-
-
-
- // monitor.pps = ack_flag; //tmp
-
   unsigned long now = millis();
   if ( now - fpsLast > 1000 ) {
     fps = fpsCounter;
     fpsCounter = 0;
     fpsLast = now;
-
-
   }

   displayUpdate();

-  //delay(250); // tmp
 }

 void displayUpdate()


fix code

fix code

--- little-switches/arduino/galoppo/galoppo.ino
+++ little-switches/arduino/galoppo/galoppo.ino
@@ -50,7 +50,7 @@
 }

 void loop() {
-  w = map(analogRead(pot),0,1023,0.25,3);
+  w = map(analogRead(pot)/1.0,0,1023,0.25,3);

   Serial.print("weight: ");
   Serial.println(w);
@@ -91,7 +91,7 @@
   long ii = millis();
   while (!fine) {
     digitalWrite(zampaPS,HIGH);
-    if ((millis() - ii) > (300*v) {
+    if ((millis() - ii) > (300*v)) {
       digitalWrite(zampaPS,LOW);
     }

@@ -106,14 +106,14 @@
       digitalWrite(zampaAS,HIGH);
     }
     if ((millis() - ii) > (450*v)) {
-      digitalWrite(zampaAS,HIGH);
+      digitalWrite(zampaAS,LOW);
     }

     if ((millis() - ii) > (225*v)) {
       digitalWrite(zampaAD,HIGH);
     }
     if ((millis() - ii) > (525*v)) {
-      digitalWrite(zampaAD,HIGH);
+      digitalWrite(zampaAD,LOW);
       fine = true;
     }


Examples: AICShield: SerialControlledSDWriter_Quad: update sample rate

--- examples/08-AIC_Shield/SerialControlledSDWriter_Quad/SerialControlledSDWriter_Quad.ino
+++ examples/08-AIC_Shield/SerialControlledSDWriter_Quad/SerialControlledSDWriter_Quad.ino
@@ -26,7 +26,7 @@
 #include "SerialManager.h"

 //set the sample rate and block size
-const float sample_rate_Hz = 44117.0f ; //24000 or 44117 or 96000 (or other frequencies in the table in AudioOutputI2S_F32)
+const float sample_rate_Hz = 44100.0f ; //24000 or 44100 or 96000 (or other frequencies in the table in AudioOutputI2S_F32)
 const int audio_block_samples = 64;     //do not make bigger than AUDIO_BLOCK_SAMPLES from AudioStream.h (which is 128)  Must be 128 for SD recording.
 AudioSettings_F32 audio_settings(sample_rate_Hz, audio_block_samples);


Update Relay.ino

Update Relay.ino

--- Examples/Relay/Relay.ino
+++ Examples/Relay/Relay.ino
@@ -44,7 +44,7 @@
   if (((millis() - THRESHOLD) > 60000) || (THRESHOLD == 0)) // Perform activity every minute
   {
     THRESHOLD = millis();
-
+    int state = digitalRead(12); // get the current state of pin
     // Condition below: It will turn the relay OFF (Normally Closed) on Sunrise plus-minus over-ride time
     if((client.Time() > (client.Sunrise() + OFF_OVER_RIDE)) && (client.Time() < (client.Sunset() + ON_OVER_RIDE)) && (((state == 0) && (client.getOverride(12) == 3)) || ((state == 1) && (client.getOverride(12) == 1))))
     {


Add copyright, and test my subversion setup.

--- SensorModule/SensorModule.ino
+++ SensorModule/SensorModule.ino
@@ -1,3 +1,27 @@
+/*
+ * Sample code for a generic multi-sensor alarm system device
+ *
+ * Copyright (c) 2015, 2016 Danny Backx
+ *
+ * License (MIT license):
+ *   Permission is hereby granted, free of charge, to any person obtaining a copy
+ *   of this software and associated documentation files (the "Software"), to deal
+ *   in the Software without restriction, including without limitation the rights
+ *   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ *   copies of the Software, and to permit persons to whom the Software is
+ *   furnished to do so, subject to the following conditions:
+ *
+ *   The above copyright notice and this permission notice shall be included in
+ *   all copies or substantial portions of the Software.
+ *
+ *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ *   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ *   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ *   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ *   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ *   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ *   THE SOFTWARE.
+ */
 #include <ESP8266WiFi.h>
 #include <UPnP.h>
 #include <UPnP/WebServer.h>


Added some comments to explain what callback functions get called when.

--- ServerSketch/ServerSketch.ino
+++ ServerSketch/ServerSketch.ino
@@ -306,7 +306,8 @@
   case LWS_CALLBACK_SERVER_WRITEABLE:

     // **********************************
-    // Send Data to Website
+    // Send Galileo's HW state to ALL clients
+    // This function is continuesly called
     // **********************************
     iNumBytes = sendStatusToWebsite(wsi);
     if (iNumBytes < 0)
@@ -318,10 +319,13 @@
     break;

   case LWS_CALLBACK_RECEIVE:
+
+    Serial.println("Cleaning Protocol");

     // **********************************
-    // Process Data Receieved from the Website
-    // **********************************
+    // Process Data Receieved from the Website
+    // Update Galileo's HW
+    // **********************************
     procWebMsg((char*) in, len);

     break;


rename print macros

rename print macros

--- Event_Printer/Event_Printer.ino
+++ Event_Printer/Event_Printer.ino
@@ -11,8 +11,8 @@

 /* Compile time Flags */
 #define DEBUG 0
-#define PRINT_TO_SERIAL_CONSOLE 0
-#define PRINT_TO_TFT 1
+#define PRINT_STATUS_TO_SERIAL_CONSOLE 0
+#define PRINT_STATUS_TO_TFT 1

 /* Helper Macros */
 #define HI_NIBBLE(b) (((b) >> 4) & 0x0F)
@@ -207,11 +207,11 @@
   else text += "Unknown";
   text += "\n";

-#if PRINT_TO_SERIAL_CONSOLE
+#if PRINT_STATUS_TO_SERIAL_CONSOLE
   Serial.println(text);
 #endif

-#if PRINT_TO_TFT
+#if PRINT_STATUS_TO_TFT
   tft.fillScreen(ST7735_BLACK);
   draw_text(&text, ST7735_WHITE);
 #endif


Randomly generate an ID on first boot.

Randomly generate an ID on first boot.

This will make it a bit simpler for other people to use the sketch, but it does make it harder to find out what your printer URL is. I'll address that soon.

--- printer.ino
+++ printer.ino
@@ -1,13 +1,13 @@
 #include <SPI.h>
 #include <Ethernet.h>
 #include <SD.h>
+#include <EEPROM.h>

 #include <SoftwareSerial.h>
 #include <Bounce.h>

 // ------- Settings ---------------------------------------------------

-const char *printerId = "abcdef123456"; // the unique ID for this printer.
 byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x86, 0x67 }; // physical mac address

 const char *printerType = "A2-raw"; // controls the format of the data sent from the server
@@ -34,6 +34,27 @@
 #define debug(a)
 #define debug2(a, b)
 #endif
+
+const byte idAddress = 0;
+char printerId[17]; // the unique ID for this printer.
+
+void initSettings() {
+  if (EEPROM.read(idAddress) == 255) {
+    randomSeed(analogRead(0) * analogRead(5));
+    for(int i = 0; i < 16; i += 2) {
+      printerId[i] = random(48, 57);
+      printerId[i+1] = random(97, 122);
+      EEPROM.write(idAddress + i, printerId[i]);
+      EEPROM.write(idAddress + i+1, printerId[i+1]);
+    }
+  } else {
+    for(int i = 0; i < 16; i++) {
+      printerId[i] = (char)EEPROM.read(idAddress + i);
+    }
+  }
+  printerId[16] = '\0';
+  debug2("Printer ID: ", printerId);
+}

 void initDiagnosticLEDs() {
   pinMode(errorLED, OUTPUT);
@@ -80,6 +101,7 @@
   Serial.begin(9600);
 #endif

+  initSettings();
   initSD();
   initNetwork();
   initPrinter();


Delete Arduino.ino

Delete Arduino.ino

Cleanup extra files...

--- Arduino/Arduino.ino
+++ Arduino/Arduino.ino
@@ -1,5 +0,0 @@
-/*
-*An Arduino Sketch...
-*Waiting to be uploaded
-*...
-*/


testing indicator logic

testing indicator logic

--- src/analog_sensors_board.ino
+++ src/analog_sensors_board.ino
@@ -52,8 +52,8 @@

 // Nessie LEDs and Water Sensors
-#define LED_GREEN 5
-#define LED_YELLOW 6
+#define LED_GREEN 6
+#define LED_YELLOW 5
 #define LED_RED 7
 #define SW_MOTOR 9
 #define WATER_FWD 10
@@ -180,7 +180,7 @@
         digitalWrite(LED_YELLOW, HIGH);
         digitalWrite(LED_RED, HIGH);

-        delay(DELAY_LEDS);
+        delay(1000);

         // LED flash off
         digitalWrite(LED_GREEN, LOW);
@@ -214,19 +214,19 @@
     if(status_sw_motor == LOW) {
         status_led_green = 0x01;
     } else {
-        status_led_green = 0x01 ^ status_led_green;
+        status_led_green = 0x00;
     }

     if(true) {
        status_led_yellow = 0x01;
     } else {
-       status_led_yellow = 0x01 ^ status_led_yellow;
+       status_led_yellow = 0x00;
     }

     if(status_water_fwd == HIGH && status_water_aft == HIGH) {
         status_led_red = 0x01;
     } else {
-        status_led_red = 0x01 ^ status_led_red;
+        status_led_red = 0x00;
     }

     // led slow-loop delta
@@ -240,6 +240,9 @@

         // update timestamp
         time_leds = millis();
+
+        // send indicators report
+        report_indicators();
     }

@@ -365,10 +368,6 @@
         report_humidity();

-        // send indicators report
-        report_indicators();
-
-
         // send timestamp
         Serial.print("$TIME,");
         Serial.println(time_slow, DEC);
@@ -382,18 +381,17 @@
 }

 void report_indicators() {
-    Serial.print("$IND,");
+    Serial.print("$WATER_FWD,");
+    Serial.println(status_water_fwd, DEC);
+    Serial.print("$WATER_AFT,");
+    Serial.println(status_water_aft, DEC);
+
+    Serial.print("$LED,");
     Serial.print(status_led_green, DEC);
     Serial.print(',');
     Serial.print(status_led_yellow, DEC);
     Serial.print(',');
-    Serial.print(status_led_red, DEC);
-    Serial.print(',');
-    Serial.print(status_sw_motor, DEC);
-    Serial.print(',');
-    Serial.print(status_water_fwd, DEC);
-    Serial.print(',');
-    Serial.println(status_water_aft, DEC);
+    Serial.println(status_led_red, DEC);
 }


Re-formatted RIODuino code

Re-formatted RIODuino code

--- RIODuino/RIODuino.ino
+++ RIODuino/RIODuino.ino
@@ -40,14 +40,17 @@

 void loop()
 {
-  if (Wire.available() >= 2) {
+  if (Wire.available() >= 2)
+  {
     byte regId = Wire.read();
     byte data = Wire.read();

-    if (regId == STACK_HEIGHT_REGISTER) {
+    if (regId == STACK_HEIGHT_REGISTER)
+    {
       height = data;
     }
-    if (regId == ALLIANCE_REGISTER) {
+    if (regId == ALLIANCE_REGISTER)
+    i{
       alliance = data;
     }
   }


bugfix

bugfix

--- esp_datalogger/esp_datalogger.ino
+++ esp_datalogger/esp_datalogger.ino
@@ -28,17 +28,17 @@
          "password" // PWD
          };

-long lastConnectionRetry = 0;
-int CONN_RETRY_DELAY = 1000;  // 1 minute
-
-long lastSensorCheck = 0;
+unsigned long lastConnectionRetry = 0;
+int CONN_RETRY_DELAY = 1000;
+
+unsigned long lastSensorCheck = 0;
 long SENSOR_CHECK_RATE = 300000; // 5 minutes

-long lastConnectionCheck = 0;
-long CONN_CHECK_RATE = 300000; // 5 minutes
-
-long lastSensorDataUpdate = 0;
-long SENSOR_DATA_UPDATE = 1200000; // 20 minutes
+unsigned long lastConnectionCheck = 0;
+long CONN_CHECK_RATE = 300000; // 5 minutes 300000
+
+unsigned long lastSensorDataUpdate = 0;
+long SENSOR_DATA_UPDATE = 1200000; // 20 min

 byte OUT_CONN_ID = 0;

@@ -106,7 +106,7 @@
     }
   }

-  long currentMillis = millis();
+  unsigned long currentMillis = millis();

   if (!connected && (currentMillis - lastConnectionRetry >= CONN_RETRY_DELAY)) {
     lastConnectionRetry = currentMillis;
@@ -129,7 +129,6 @@
     lastConnectionCheck = currentMillis;
     checkConnectionStatus();
   }
-
 }

 void initWifiModule() {
@@ -301,7 +300,7 @@
   clearSerialBuffer();

   swSerial.println(command);
-  long int time = millis();
+  unsigned long time = millis();

   if(debug){
     while(time + timeout > millis()){
@@ -386,7 +385,7 @@
     value = TEMP_ALARM_ID;
   }

-  if(data->humidity >= HUM_H_BOUND || data-> humidity <= HUM_L_BOUND ){
+  if(data->humidity >= HUM_H_BOUND || data->humidity <= HUM_L_BOUND ){
     value += HUM_ALARM_ID;
   }

@@ -399,4 +398,3 @@

-


YPR convertidos para graus/seg.

YPR convertidos para graus/seg.

--- quad/quad.ino
+++ quad/quad.ino
@@ -80,11 +80,13 @@
 /* Variáveis de orientação que vem do DMP */
 Quaternion q;        // [w, x, y, z]         Container do quaternion
 VectorFloat gravity; // [x, y, z]            Vetor de gravidade
+float ypr[3]; // [yaw, pitch, roll]   Container do yaw/pitch/roll e do vetor de gravidade
+float ypr_degree[3]; // [yaw, pitch, roll]   Container do yaw/pitch/roll e do vetor de gravidade em graus/segundo

 const int DMP_YAW = 0;
 const int DMP_PITCH = 1;
 const int DMP_ROLL = 2;
-float ypr[3]; // [yaw, pitch, roll]   Container do yaw/pitch/roll e do vetor de gravidade
+

 /****************
  * Interrupções *
@@ -264,7 +266,7 @@
     // is pilot asking for yaw change - if so feed directly to rate pid (overwriting yaw stab output)
     if(abs(rcYaw ) > 5) {
       yaw_stab_output = rcYaw;
-      yaw_target = ypr[DMP_YAW];   // remember this yaw for when pilot stops
+      yaw_target = ypr_degree[DMP_YAW];   // remember this yaw for when pilot stops
     }

     // pid_pitch_rate.calculate()
@@ -303,7 +305,7 @@
     motors[MOTOR_FL] = motors[MOTOR_FR] = motors[MOTOR_BL] = motors[MOTOR_BR] = 1000;

     // reset yaw target so we maintain this on takeoff
-    yaw_target = ypr[DMP_YAW];
+    yaw_target = ypr_degree[DMP_YAW];

     // reset PID integrals whilst on the ground
     // for(int i=0; i<6; i++)
@@ -393,6 +395,11 @@
       mpu.dmpGetQuaternion(&q, fifoBuffer);
       mpu.dmpGetGravity(&gravity, &q);
       mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
+
+      /* Converte para graus/segundo */
+      for (int i = 0; i < 3; i++) {
+        ypr_degree[i] = ypr[i] * 180/M_PI;
+      }
     }
   }
 }
@@ -435,9 +442,9 @@
   tmValues += padding("RCR=" + String(rcRoll), 8) + ";";
   tmValues += padding("RCO=" + String(rcOnOff), 8) + ";";
   tmValues += padding("RCD=" + String(rcDimmer), 8) + ";";
-  tmValues += padding("DMP=" + String(ypr[DMP_PITCH]), 10) + ";";
-  tmValues += padding("DMR=" + String(ypr[DMP_ROLL]), 10) + ";";
-  tmValues += padding("DMY=" + String(ypr[DMP_YAW]), 10) + ";";
+  tmValues += padding("DMP=" + String(ypr_degree[DMP_PITCH]), 10) + ";";
+  tmValues += padding("DMR=" + String(ypr_degree[DMP_ROLL]), 10) + ";";
+  tmValues += padding("DMY=" + String(ypr_degree[DMP_YAW]), 10) + ";";
   tmValues += padding("PIP=" + String(pitch_stab_output), 7) + ";";
   tmValues += padding("PIR=" + String(roll_stab_output), 7) + ";";
   tmValues += padding("PIY=" + String(yaw_stab_output), 7) + ";";


update

update

--- src/Firmware.ino
+++ src/Firmware.ino
@@ -7,7 +7,7 @@
 #define CURVE_SECTION 0.5
 #define NUM_STEPS 100
 #define NUM_AXIS 2
-#define DEBUG true
+// #define DEBUG true
 enum MOTION_STATE
 {
     MOTION_ACCELETING = 0,
@@ -49,12 +49,12 @@
     long targetPosition[NUM_AXIS];
     long startPosition[NUM_AXIS];
     long timerCount = 0;
-    long time = 625;
-    long defaultTime = 625;
-    long defaultAcceleration = 25;
-    long defaultAccelCount = 50;
-    long defaultDecelCount = 50;
-    long maxTime = 1250;
+    long time = 4250;
+    long defaultTime = 4250;
+    long defaultAcceleration = 64;
+    long defaultAccelCount = 200;
+    long defaultDecelCount = 200;
+    long maxTime = 2250;
     long minTime = 25;
     PlannerPoint points[POINTS_COUNT];
     MotionState states[STATES_COUNT];
@@ -73,6 +73,7 @@
     uint8_t powerPin = 10;
     String buffer = "";
     bool isFinish = true;
+    bool allowEnding = false;
 };
 SystemStatus _sys;
 MeStepper steppers[NUM_AXIS] = {MeStepper(SLOT_1), MeStepper(SLOT_2)};
@@ -88,6 +89,7 @@
         steppers[i].disableOutputs();
     }
     Serial.println("opened");
+    moveTo(0, 0);
 }

 void loop()
@@ -141,6 +143,8 @@
             }
         }
     }
+    _sys.isFinish = false;
+    _sys.allowEnding = false;
     switch (code)
     {
     case 'm':
@@ -246,15 +250,15 @@
 void lineTo(long x, long y)
 {
     waitingPushPoint();
-    // #ifdef DEBUG
-    //     String str = "line:";
-    //     str += x;
-    //     str += ",";
-    //     str += y;
-    //     str += ",";
-    //     str += _sys.speed;
-    //     Serial.println(str);
-    // #endif
+#ifdef DEBUG
+    String str = "line:";
+    str += x;
+    str += ",";
+    str += y;
+    str += ",";
+    str += _sys.speed;
+    Serial.println(str);
+#endif
     addMotion(x, y, _sys.power, _sys.speed, _sys.acceleration);
 }
 void addMotion(long x, long y, uint8_t power, uint8_t speed, uint8_t accelaration)
@@ -275,7 +279,7 @@
 }
 void finishCommand()
 {
-    if (commandsLength() < 2)
+    if (commandsLength() < STATES_COUNT)
     {
         Serial.print("ok:");
         Serial.println(commandsLength());
@@ -283,7 +287,7 @@
 }
 int8_t commandsLength()
 {
-    return _sys.plannedLength;
+    return _sys.statesLength;
 }
 void setPower(uint8_t power)
 {
@@ -325,40 +329,43 @@
     _sys.statesLength--;
     if (_sys.statesLength <= 0)
     {
-        if (!_sys.isFinish)
-        {
-            _sys.isFinish = true;
-            finishCommand();
-        }
+        finishCommand();
     }
 }
 void calcPlanned()
 {
-    if (_sys.plannedLength < 2 && _sys.statesLength > 1)
-    {
-        MotionState currentState = _sys.state;
-        shiftState();
-        MotionState nextState = _sys.state;
-        PlannerPoint point;
-        point.dir[0] = currentState.targetPosition[0] < nextState.targetPosition[0];
-        point.dir[1] = currentState.targetPosition[1] < nextState.targetPosition[1];
-        point.targetCount[0] = abs(nextState.targetPosition[0] - currentState.targetPosition[0]);
-        point.targetCount[1] = abs(nextState.targetPosition[1] - currentState.targetPosition[1]);
-        point.delta[0] = abs(point.targetCount[0]);
-        point.delta[1] = abs(point.targetCount[1]);
-        point.totalCount = point.delta[0] + point.delta[1];
-        point.enterSpeed = _sys.plannedIndex > 0 ? _sys.points[_sys.plannedIndex - 1].exitSpeed : _sys.defaultSpeed;
-        point.speed = fmax(1, currentState.speed);
-        point.exitSpeed = fmax(1, sqrt(nextState.speed));
-        point.acceleration = currentState.acceleration;
-        long dist = sqrt(point.delta[0] * point.delta[0] + point.delta[1] * point.delta[1]) / 2;
-        point.accelCount = point.totalCount - min(dist, _sys.defaultAccelCount);
-        point.decelCount = min(dist, _sys.defaultDecelCount);
-        point.power = nextState.power;
-        point.err = (point.delta[0] > point.delta[1] ? point.delta[0] : -point.delta[1]) / 2;
-        _sys.points[_sys.plannedIndex] = point;
-        _sys.plannedIndex++;
-        _sys.plannedLength++;
+    if (_sys.plannedLength < POINTS_COUNT)
+    {
+        if (_sys.statesLength > 1)
+        {
+            _sys.allowEnding = true;
+            MotionState currentState = _sys.state;
+            shiftState();
+            MotionState nextState = _sys.state;
+            PlannerPoint point;
+            point.dir[0] = currentState.targetPosition[0] < nextState.targetPosition[0];
+            point.dir[1] = currentState.targetPosition[1] < nextState.targetPosition[1];
+            point.targetCount[0] = abs(nextState.targetPosition[0] - currentState.targetPosition[0]);
+            point.targetCount[1] = abs(nextState.targetPosition[1] - currentState.targetPosition[1]);
+            point.delta[0] = (point.targetCount[0]);
+            point.delta[1] = (point.targetCount[1]);
+            point.totalCount = point.delta[0] + point.delta[1];
+            point.enterSpeed = _sys.plannedIndex > 0 ? _sys.points[_sys.plannedIndex - 1].exitSpeed : _sys.defaultSpeed;
+            point.speed = fmax(1, currentState.speed);
+            point.exitSpeed = fmax(1, sqrt(nextState.speed));
+            point.acceleration = currentState.acceleration;
+            long dist = sqrt(point.delta[0] * point.delta[0] + point.delta[1] * point.delta[1]) / 2;
+            point.accelCount = point.totalCount - min(dist, _sys.defaultAccelCount);
+            point.decelCount = min(dist, _sys.defaultDecelCount);
+            point.power = currentState.power;
+            point.err = (point.delta[0] > point.delta[1] ? point.delta[0] : -point.delta[1]) / 2;
+            _sys.points[_sys.plannedIndex] = point;
+            _sys.plannedIndex++;
+            _sys.plannedLength++;
+        }
+        else
+        {
+        }
     }
 }
 /**
@@ -369,15 +376,19 @@
  * */
 void shiftPlanned()
 {
-    if (_sys.plannedIndex > 0)
-    {
-        for (int i = 0; i < _sys.plannedIndex; i++)
+    if (_sys.plannedLength > 0)
+    {
+        for (int i = 0; i < _sys.plannedLength - 1; i++)
         {
             _sys.points[i] = _sys.points[i + 1];
         }
         _sys.plannedIndex--;
         _sys.plannedLength--;
     }
+    if (_sys.statesLength <= 0 && _sys.plannedLength <= 0)
+    {
+        finishCommand();
+    }
 }
 void lockTimer()
 {
@@ -401,37 +412,34 @@
 }
 void motionFinish()
 {
-    lockTimer();
-    shiftPlanned();
-    calcPlanned();
-    unlockTimer();
+    if (_sys.statesLength > 0 || _sys.plannedLength > 0)
+    {
+        lockTimer();
+        shiftPlanned();
+        calcPlanned();
+        unlockTimer();
+    }
     if (_sys.plannedLength > 0)
     {
         firePower(_sys.points[0].power);
         _sys.minTime = fmax(25, 100.0 / (_sys.points[0].speed / 100.0));
         _sys.maxTime = fmin(_sys.defaultTime, _sys.defaultTime / (_sys.points[0].exitSpeed / 50.0));
-        Serial.print("motion finish:");
-        Serial.print(_sys.points[0].speed);
-        Serial.print(" - ");
-        Serial.print(_sys.minTime);
-        Serial.print(" - ");
-        Serial.println(_sys.maxTime);
     }
 }
 void waitingPushPoint()
 {
     while (true)
     {
-        if (_sys.plannedLength < 2)
+        if (_sys.statesLength < STATES_COUNT)
         {
             break;
         }
-        delay(1);
-        // #ifdef DEBUG
-        //         String str = "waiting:";
-        //         str += _sys.statesIndex;
-        //         Serial.println(str);
-        // #endif
+        delay(200);
+#ifdef DEBUG
+        String str = "waiting:";
+        str += _sys.statesIndex;
+        Serial.println(str);
+#endif
     }
 }
 void initTimer()
@@ -528,16 +536,6 @@
                 }
                 else
                 {
-
-                    Serial.print("state:");
-                    Serial.print(_sys.isRunningState);
-                    Serial.print(" - ");
-                    Serial.print(_sys.points[0].totalCount);
-                    Serial.print(" - ");
-                    Serial.print(_sys.points[0].accelCount);
-                    Serial.print(" - ");
-                    Serial.print("time:");
-                    Serial.println(_sys.time);
                 }
             }
             break;
@@ -547,11 +545,9 @@
             if (_sys.time < _sys.maxTime)
             {
                 _sys.time += _sys.defaultAcceleration;
-                Serial.print("state:");
-                Serial.print(_sys.isRunningState);
-                Serial.print(" - ");
-                Serial.print("time:");
-                Serial.println(_sys.time);
+            }
+            else
+            {
             }
             break;
         }


Lower power tx

Lower power tx


Fix typo

Fix typo

--- hardware/esp8266com/esp8266/libraries/ESP8266WebServer/examples/SDWebServer/SDWebServer.ino
+++ hardware/esp8266com/esp8266/libraries/ESP8266WebServer/examples/SDWebServer/SDWebServer.ino
@@ -180,7 +180,7 @@
     return returnFail("NOT DIR");
   }
   dir.rewindDirectory();
-  server.setContentSize(CONTENT_SIZE_UNKNOWN);
+  server.setContentLength(CONTENT_LENGTH_UNKNOWN);
   server.send(200, "text/json", "");
   WiFiClient client = server.client();


Added some commented out code to be used for motor control

--- fed-arduino_V3/fed-arduino_V3.ino
+++ fed-arduino_V3/fed-arduino_V3.ino
@@ -30,16 +30,16 @@
 int lastStates[] = { 1, 1 };
 int pelletCount[] = { 0, 0 };

-const int STEPS_TO_INCREMENT = 64;
-const int MOTOR_STEPS_PER_REVOLUTION = 513;
-
-Adafruit_MotorShield gMotorShield = Adafruit_MotorShield();
-Adafruit_StepperMotor *gPtrToStepper = gMotorShield.getStepper(MOTOR_STEPS_PER_REVOLUTION,2);
-
 #define FILENAME "PelletData.csv"
 const int CS_pin = 10;
 SdFat SD;
 File dataFile;
+
+/*const int MOTOR_STEPS_PER_REVOLUTION = 513;
+const int STEPS_TO_INCREMENT = 64;
+Adafruit_MotorShield gMotorShield = Adafruit_MotorShield();
+Adafruit_StepperMotor *stepperMotors[] = { gMotorShield.getStepper(MOTOR_STEPS_PER_REVOLUTION,1), gMotorShield.getStepper(MOTOR_STEPS_PER_REVOLUTION,2) };
+//*/

 void setup() {
   //power saving stuff
@@ -66,7 +66,8 @@

   //motor shield stuff
   /*gMotorShield.begin();
-  gPtrToStepper->setSpeed(30);//*/
+  for (int i = 0; i < sizeof(stepperMotors); i++)
+  { stepperMotors[i]->setSpeed(30); } //*/

   //SD card init stuff
   Wire.begin();
@@ -158,13 +159,8 @@
     Serial.print(F("Replacing pellet #"));
     Serial.print(String(inputNum + 1));
     Serial.println(F("..."));
-
-    //power_twi_enable();
-    //gPtrToStepper->step(STEPS_TO_INCREMENT/2,FORWARD,DOUBLE);
-    //gPtrToStepper->step(STEPS_TO_INCREMENT,BACKWARD,DOUBLE);
-    //gPtrToStepper->release();
-    //power_twi_disable();
-    delay(1000);
+    //moveMotor(inputNum);
+    delay(500);
   }

   else if (PIStates[inputNum] == 0 & PIStates[inputNum] != lastStates[inputNum]) {
@@ -172,9 +168,6 @@
     Serial.print(F("Pellet #"));
     Serial.print(String(inputNum + 1));
     Serial.println(F(" replaced"));
-    //Serial.print(F("Time Elapsed Since Last Pellet: "));
-    //timeElapsed = millis() - startTime;
-    //Serial.println(timeElapsed);
   }

   else  { //if PIStates == 0
@@ -244,3 +237,12 @@
   String second = String(datetime.second(), DEC);
   return (month + "/" + day + " " + hour + ":" + minute + ":" + second);
 }
+
+/*void moveMotor(int motorNum)
+{
+    power_twi_enable();
+    stepperMotors[motorNum]->step(STEPS_TO_INCREMENT/2,FORWARD,DOUBLE);
+    stepperMotors[motorNum]->step(STEPS_TO_INCREMENT,BACKWARD,DOUBLE);
+    stepperMotors[motorNum]->release();
+    power_twi_disable();
+} //*/


Update mech.ino

Update mech.ino

--- mech/mech.ino
+++ mech/mech.ino
@@ -112,7 +112,7 @@

   stepperL.setMaxSpeed(2000);            //  Set maximum roration speed for "L" Motor 1
   stepperL.setSpeed(1500);               //  Set maximum calibration speed for "L" Motor 1
-  stepperL.setAcceleration(2000);        //  Set maximum acceleration for "L" Motor 1
+  stepperL.setAcceleration(4000);        //  Set maximum acceleration for "L" Motor 1

   stepperC1.setMaxSpeed(2000);           //  Set maximum roration speed for "C" Motor 2
   stepperC1.setSpeed(1000);              //  Set maximum calibration speed for "C" Motor 2
@@ -178,8 +178,7 @@
   isAutoTune = 1;
   stepperC1.moveTo(10);
   stepperC2.moveTo(10);
-  stepperL.setAcceleration(1600);
-  optimize(&stepperL, 1000, 0);
+  optimize(&stepperL, 2000, 0);
   optimize(&stepperC1, 20, 0);
   optimize(&stepperC2, 20, 0);
   isAutoTune = 0;


fix random color picking from lists

fix random color picking from lists

--- moodylite.ino
+++ moodylite.ino
@@ -73,10 +73,9 @@
 //**MODE CONFIG**//
 	//pin stuff here later
 	//mode 1 (just something to fill space atm)
-	// const RGB colors1[] = {red, yellow, green, cyan, blue, purple};//the colors to be cycled through go here
-	const RGB colors1[] = {red, green, blue};
+	const RGB colors1[] = {red, yellow, green, cyan, blue, purple};//the colors to be cycled through go here
 	// const RGB pattern1[] = {red, green, blue};//the pattern played when this mode is selected is set here
-	Mode mode1(colors1, 3);//create an instance of Mode for this mode
+	Mode mode1(colors1, 6);//create an instance of Mode for this mode

 	//mode2 example using a callback

@@ -97,7 +96,7 @@

 		mode1.isHSV = false;
-		mode1.random = false;
+		mode1.random = true;
 	}
 	// const unsigned long interval = 5000; //the interval of color change, the time it takes to fade from one color to the next
 	const unsigned long interval = 750;//fast for testing
@@ -189,7 +188,12 @@
 		if (len == 1) //if there is only one color abort
 			return *(clist);
 		if (activeMode->random) {//check if the next color should be random or not
-			return *(clist + (getRand() % (len-1)));//get random number, and limit it with modulo length - 1 to keep it in bounds
+			uint8_t rand = getRand() % (len-1);//get random number, and limit it with modulo length - 1 to keep it in bounds
+			if (rand == currentColor) //don't show the same color multiple times in a row
+				currentColor = (currentColor + 1) % (len-1);//the same limiting as above
+			else
+				currentColor = rand;
+			return *(clist + currentColor);
 		}
 		else //simply go to the next color if random is turned off
 			if (++currentColor >= len) {//increment the color index and check if it is out of bounds
@@ -201,7 +205,8 @@
 	}
 	int getRand () {
 		//return a random number
-		return analogRead(CFG::RANDPIN);//analog pin 'static' method of getting a random number
+		// return analogRead(CFG::RANDPIN);//analog pin 'static' method of getting a random number
+		return random(1024);
 	}
 	void setOutputColor(RGB color) {
 		//set the input color as the pwm output color
@@ -223,11 +228,15 @@
 	pinMode(CFG::RPIN, OUTPUT);
 	pinMode(CFG::GPIN, OUTPUT);
 	pinMode(CFG::BPIN, OUTPUT);
+	//setup the button pins with internal pullup enables to make wiring slightly easier
+	pinMode(CFG::BTN1, INPUT_PULLUP);
+	pinMode(CFG::BTN2, INPUT_PULLUP);
 	//set pins as with high or low depending of whether or not they are sourcing current
 	digitalWrite(CFG::RPIN, CFG::MODE);
 	digitalWrite(CFG::GPIN, CFG::MODE);
 	digitalWrite(CFG::BPIN, CFG::MODE);
 	//init other stuff
+	randomSeed(CFG::RANDPIN);//setup randomness
 	Moody::anim_init();
 	//setup serial if we need to do debugging printing
 	#ifdef DEBUGGING


merging fun

merging fun


Update template.ino

Update template.ino

Fixed wrong index

--- files/template.ino
+++ files/template.ino
@@ -214,7 +214,7 @@
     Serial.println("done!");
     uploadSuccess = true;
     //Change case
-    if (sampleType == 5) {
+    if (sampleType == 6) {
       sampleType = 1;
       // remember the time that the connection was made or attempted
       lastConnectionTime = millis();


koin bandung deployed

koin bandung deployed

--- Koin/fmw_bandung/fmw_bandung.ino
+++ Koin/fmw_bandung/fmw_bandung.ino
@@ -1,11 +1,14 @@
 #include "Hx711.h"
 #include "OutputManager.h"
-#define k1 41
-#define k2 52
-#define k3 105
+#define k1 46.5
+#define k2 56
+#define k3 112

-#define expectedW (k3*2 + k2 + k1*2)
-#define TOLERANSI 15
+#define expectedW (k3*2 + k2 + k1*2 - k1)//-- 26
+#define TOLERANSI (5)
+#define expectedMin (expectedW-5)
+#define expectedMax (expectedW+6)
+
 #define RELAYPIN A2
 static float Weight=0;
 static float selisih = 0;
@@ -48,14 +51,19 @@
     Serial.print(selisih,1);
     Serial.print(" ");
     Serial.print(expectedW,1);
+    Serial.print(" =[[== ");
+    Serial.print(expectedMin,1);
+    Serial.print("~");
+    Serial.print(expectedMax,1);

     Serial.println(" g");
-    if (selisih<TOLERANSI && selisih>-TOLERANSI)
+    //if (selisih<TOLERANSI && selisih>-TOLERANSI)
+    if (Weight>expectedMin && Weight<expectedMax)
     {
         delay(1000);
         Weight = scale->getGram();
-        selisih = Weight - expectedW;
-        if (selisih<TOLERANSI && selisih>-TOLERANSI)
+        //~ selisih = Weight - expectedW;
+		if (Weight>expectedMin && Weight<expectedMax)
         {
           Serial.println(" Succeed");
           RelayON(&output);


long probs

long probs

--- telemetryBox.ino
+++ telemetryBox.ino
@@ -34,15 +34,15 @@
 // connection settings
 STARTUP(WiFi.selectAntenna(ANT_EXTERNAL)); // use the u.FL antenna, get rid of this if not using an antenna
 float batterySOCmin = 40.0; // minimum battery state of charge needed for short wakeup time
-unsigned long wakeUpTimeoutShort = 5*60; // wake up every 5 mins when battery SOC > batterySOCmin
-unsigned long wakeUpTimeoutLong = 15*60; // wake up every 15 mins during long sleep, when battery is lower
+unsigned long wakeUpTimeoutShort = 300; // wake up every 5 mins when battery SOC > batterySOCmin
+unsigned long wakeUpTimeoutLong = 900; // wake up every 15 mins during long sleep, when battery is lower
 unsigned long connectedTime; // millis() at the time we actually get connected, used to see how long it takes to connect
 unsigned long connectionTime; // difference between connectedTime and startTime

 // for updating software
 bool waitForUpdate = false; // for updating software
-unsigned long updateTimeout = 10*60*1000; // 10 min timeout for waiting for software update
-unsigned long communicationTimeout = 5*60*1000; // wait 5 mins before sleeping
+unsigned long updateTimeout = 600000; // 10 min timeout for waiting for software update
+unsigned long communicationTimeout = 300000; // wait 5 mins before sleeping
 unsigned long bootupStartTime;

 // for publish and subscribe events


TG-6 #in-progress - mind menu logic to loop

--- AlarmClock.ino
+++ AlarmClock.ino
@@ -1,6 +1,5 @@
 // Libraries
 #include <LiquidCrystal.h>
-#include "lib/time/Time.h"

 // classes
 #include "classes/Menu.h"
@@ -12,21 +11,25 @@
 const int exitButton = 25;
 int buttonValues[4];

+// LOGIC
+MenuStruct *menuStruct;
+
+void readButtons();
+
 void setup() {
+    // HARDWARE INITS
     pinMode(enterButton, INPUT);
     pinMode(lessButton, INPUT);
     pinMode(moreButton, INPUT);
     pinMode(exitButton, INPUT);
+
+    // LOGIC INITS
+    menuStruct = constructMenuStruct();
 }

 void loop() {
     readButtons();
-    handleButtons();
-}
-
-void handleButtons() {
-
-
+    menuStruct->handleButtons(menuStruct, buttonValues);
 }

 void readButtons() {


Update arduino.ino

Update arduino.ino

--- arduino/arduino.ino
+++ arduino/arduino.ino
@@ -21,7 +21,7 @@
   int tmpButtonState = digitalRead(pinNumber);
   // if it has not been clicked yet and it's down we can send the message
   if (tmpButtonState == HIGH && buttonClicked == false) {
-    Serial.print("Hello World");
+    Serial.printLn("Hello World");
     digitalWrite(led, HIGH);
     delay(1000); // wait 1 s before sending the next message
     buttonClicked = true;


Fixed sending of duplicated data

Fixed sending of duplicated data

--- arduino/arduino.ino
+++ arduino/arduino.ino
@@ -50,7 +50,6 @@
   double T, absP;
   char status;
   if(bmp180Temperature(T)) {
-    Serial.println(T);
     status = pressure.startPressure(3);
     if (status != 0) {
         delay(status);


Temperature Reader: Won't output when input is 0

--- Modules/Sensor/TemperatureSensor/ArduinoCodes/TemperatureSensorATmega/TemperatureSensorATmega.ino
+++ Modules/Sensor/TemperatureSensor/ArduinoCodes/TemperatureSensorATmega/TemperatureSensorATmega.ino
@@ -62,5 +62,10 @@
     //mapping everything to: 32F - 150F

     int output_val = cutAndMap(temperature, 32, 150, 0, 255);
-    analogWrite(output_pin, output_val);
+
+    // shouldn't do anything when input voltage is 0
+    if(cutAndMap(input.filteredAnalogRead(AVERAGE), 50, 975, 0, 1023) <= 15)
+      analogWrite(output_pin, 0);
+    else
+      analogWrite(output_pin, output_val);
 }


clean up code

clean up code

--- keypad/keypad.ino
+++ keypad/keypad.ino
@@ -301,12 +301,6 @@
         tone(melodyPin, NOTE_C3,noteDuration);

         rainbowCycle(20);
-        lightRing(8, pixels.Color(100,150,100));
-        delay(125);
-        lightRing(10, pixels.Color(100,150,100));
-        delay(125);
-        lightRing(0, pixels.Color(100,150,100));
-        delay(125);

         break;
       case '#':
@@ -316,7 +310,7 @@
         tone(melodyPin, NOTE_E3,noteDuration);
         delay(125);
         tone(melodyPin, NOTE_D3,noteDuration);
-
+
         killRing();
         break;
       default:
@@ -399,12 +393,12 @@
 void rainbowCycle(uint8_t wait) {
   uint16_t i, j;

-  for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
+  for(j=0; j<1; j++) { // 5 cycles of all colors on wheel
     for(i=0; i< ringPixels; i++) {
       pixels.setPixelColor(i, Wheel(((i * 256 / ringPixels) + j) & 255));
+      pixels.show();
+      delay(wait);
     }
-    pixels.show();
-    delay(wait);
   }
 }


Tested, fixed bugs

Tested, fixed bugs


Typos everywhere, heh

Typos everywhere, heh

--- KSPboard.ino
+++ KSPboard.ino
@@ -172,7 +172,7 @@
   // reset current if no adj&stick flag or if adj and current are opposite signs
   if (!(adj || stick) || (dir > 0 && adj < 0) || (dir < 0 && adj > 0))
   {
-    dir = 0; // reset current direction to neatral
+    dir = 0; // reset current direction to neutral
   }
   else
   {
@@ -214,7 +214,7 @@

 void setupControl()
 {
-  // the rotary encore uses two wire differential signalling
+  // the rotary encoder uses two wire differential signalling
   attachInterrupt(
     digitalPinToInterrupt(PIN_ROT_CTRL_CLK),
     rotaryInterruptHandler,
@@ -278,7 +278,7 @@
   {
     if (digitalRead(PIN_ROT_CTRL_SW)) // if you press dis switch lock the sas control state
     {
-      controlLocked = controlState; // update local variable
+      controlLocked = controlState; // update locked variable

       Serial.println("this is where the good stuff goes, fuck yeah");


Use NC logic for emergency stop

Use NC logic for emergency stop

--- KomaRoof.ino
+++ KomaRoof.ino
@@ -155,7 +155,7 @@
 }

 void emergencyStopISR() {
-    emergencyStopPressed = (digitalRead(PIN_BUTTON_EMERGENCYSTOP) == LOW);
+    emergencyStopPressed = (digitalRead(PIN_BUTTON_EMERGENCYSTOP) == HIGH);
 }

 void limitSwitchOpenISR() {


Terminal: use own data receiver, remove hack with reloading Loader

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

 // XXX Read real user input from serial port of Arduino
 // XXX Write a character on screen instead of changing a pixel
-// XXX Don't use Loader application for reading more data

 // Arduino AVR    Gigatron Schematic Controller PCB
 // Uno     Name   OUT bit            CD4021     74HC595 (U39)
@@ -50,40 +49,106 @@
 }

 byte terminal[] = {
-  // XXX Replace with writing a letter on screen
-  0x11, 0x50, 0x44, // LDWI $4450        ; Load address of center of screen
-
-  0x2b, 0x30,       // STW  'p'          ; Store in variable 'p' (at $0030)
-  0xad,             // PEEK              ; Read current pixel value
-  0xe3, 0x01,       // ADDI 1            ; Increment
-  0xf0, 0x30,       // POKE 'p'          ; Write back pixel
-
-  // XXX Replace with own serial reader
-  0x11, 0x00, 0x02, // LDWI 'vCpuStart'  ; Where to go after SYS_Exec_88
-  0x2b, 0x1a,       // STW  'vLR'
-  0x11, 0x97, 0xf9, // LDWI 'Loader'     ; Loader image (XXX IHACK)
-  0x2b, 0x24,       // STW  'sysArgs+0'
-  0x59, 0xad,       // LDI  'SYS_Exec_88'
-  0x2b, 0x22,       // STW  'sysFn'
-  0xb4, 0xe2,       // SYS  $e2          ; 270-88/2
+ 0x11, // 0200 LDWI
+ 0xe9,
+ 0x02,
+ 0x2b, // 0203 STW
+ 0x30, // 0203 'NextByteIn_32'
+ 0x11, // 0205 LDWI
+ 0x0c,
+ 0x5b,
+ 0x2b, // 0208 STW
+ 0x32, // 0208 'B'
+ 0x21, // 020a LDW
+ 0x32, // 020a 'B'
+ 0x2b, // 020c STW
+ 0x24,
+ 0x59, // 020e LDI
+ 0xcf,
+ 0x5e, // 0210 ST
+ 0x27,
+ 0x21, // 0212 LDW
+ 0x30, // 0212 'NextByteIn_32'
+ 0x2b, // 0214 STW
+ 0x22,
+ 0xb4, // 0216 SYS
+ 0xfe,
+ 0x59, // 0218 LDI
+ 0xdb,
+ 0x5e, // 021a ST
+ 0x27,
+ 0xb4, // 021c SYS
+ 0xfe,
+ 0x59, // 021e LDI
+ 0xeb,
+ 0x5e, // 0220 ST
+ 0x27,
+ 0xb4, // 0222 SYS
+ 0xfe,
+ 0x59, // 0224 LDI
+ 0xfb,
+ 0x5e, // 0226 ST
+ 0x27,
+ 0xb4, // 0228 SYS
+ 0xfe,
+ 0x59, // 022a LDI
+ 0x02,
+ 0x5e, // 022c ST
+ 0x27,
+ 0x21, // 022e LDW
+ 0x30, // 022e 'NextByteIn_32'
+ 0x2b, // 0230 STW
+ 0x22,
+ 0xb4, // 0232 SYS
+ 0xfe,
+ 0x59, // 0234 LDI
+ 0x06,
+ 0x5e, // 0236 ST
+ 0x27,
+ 0x21, // 0238 LDW
+ 0x30, // 0238 'NextByteIn_32'
+ 0x2b, // 023a STW
+ 0x22,
+ 0xb4, // 023c SYS
+ 0xfe,
+ 0x1a, // 023e LD
+ 0x27,
+ 0xe3, // 0240 ADDI
+ 0x04,
+ 0x5e, // 0242 ST
+ 0x27,
+ 0x8c, // 0244 XORI
+ 0xf2,
+ 0x35, // 0246 BCC
+ 0x72, // 0247 NE
+ 0x36,
+ 0x59, // 0249 LDI
+ 0xb9,
+ 0x5e, // 024b ST
+ 0x27,
+ 0xb4, // 024d SYS
+ 0xfe,
+ 0x90, // 024f BRA
+ 0x08,
 };

 void loop() {
-  static byte payload[60];
+  static byte payload[2*60];
   memcpy(payload, terminal, sizeof terminal);
   noInterrupts();
   for (;;) {
     // Send one frame with false checksum to force
     // a checksum resync at the receiver
     checksum = 0;
-    sendFrame(-1, sizeof terminal, 0x7f00, payload);
+    sendFrame(-1, 60, 0x200, payload);

     // Setup checksum properly
     checksum = 'g';
-    sendFrame('L', sizeof terminal, 0x7f00, payload);
+    sendFrame('L', 60,                   0x200,      payload);
+    sendFrame('L', sizeof terminal - 60, 0x200 + 60, payload + 60);

     // Force execution
-    sendFrame('L', 0, 0x7f00, payload);
+    sendFrame('L', 0, 0x0200, payload + 60);
   }
 }


fix and change to 60fps to prevent sparkling

--- Patterns.ino
+++ Patterns.ino
@@ -164,9 +164,9 @@
   // The total quantity of LEDS
   int LEDSnum = LEDS_PER_ROW * LEDS_PER_ROW * LEDS_PER_ROW;
   // The number of fps required "frame per second"
-  int fps = 30;
+  int fps = 60;
   // The delta between 2 LED display to fit the fps requirements (in micro-second)
-  int deltaLED = 1000000. * LEDSnum / fps;
+  int deltaLED = 1000000. / LEDSnum / fps;
   for (int i = 0; i < (LEDSnum); ++i)
   {
     displayNum(i);


water flow sensor

water flow sensor

--- arduino_pico/arduino_pico.ino
+++ arduino_pico/arduino_pico.ino
@@ -1,8 +1,9 @@
 #include "OneWire.h"
 #include "DallasTemperature.h"
 #include "TimerOne.h"
+#include "typedefs.h"

-// Data wire is plugged into port 2 on the Arduino
+// Data wire is plugged into port ONE_WIRE_BUS on the Arduino
 #define ONE_WIRE_BUS A0
 #define TEMPERATURE_PRECISION 12

@@ -17,11 +18,20 @@
 float         heatTemp,        pipeTemp,        boilTemp;

+flow_sensor_t input_heat;
+flow_sensor_t input_pipe;
+
+// The hall-effect flow sensor outputs approximately 4.5 pulses per second per
+// litre/minute of flow.
+float calibrationFactor = 4.5;
+
+
 void setup(void)
 {
   // start serial port
   Serial.begin(57600);

+  // 1-wire devices temperature

   // Start up the library
   sensors.begin();
@@ -44,6 +54,43 @@

   Timer1.initialize(750000);
   Timer1.attachInterrupt( timerIsr ); // attach the service routine here
+
+
+  // Hall effect flow meter
+  input_heat = {
+    0,  // sensorInterrupt
+    2,  // sensorPin
+    0,  // pulseCount
+    0,  // flowRate
+    0,  // flowMilliLitres
+    0,  // totalMilliLitres
+    0,  // oldTime
+    pulseCounter_heat // pulseCounter
+  };
+
+  input_pipe = {
+    1,  // sensorInterrupt
+    3,  // sensorPin
+    0,  // pulseCount
+    0,  // flowRate
+    0,  // flowMilliLitres
+    0,  // totalMilliLitres
+    0,  // oldTime
+    pulseCounter_pipe // pulseCounter
+   };
+
+
+  pinMode(input_heat.sensorPin, INPUT);
+  digitalWrite(input_heat.sensorPin, HIGH);
+
+  pinMode(input_pipe.sensorPin, INPUT);
+  digitalWrite(input_pipe.sensorPin, HIGH);
+
+  // Configured to trigger on a FALLING state change (transition from HIGH
+  // state to LOW state)
+  attachInterrupt(input_heat.sensorInterrupt, input_heat.pulseCounter, FALLING);
+  attachInterrupt(input_pipe.sensorInterrupt, input_pipe.pulseCounter, FALLING);
+

 }

@@ -62,10 +109,84 @@
 void timerIsr()
 {
   interruptTemperature(); // get temperature data and request measure
+
+  loop_water_flow(&input_heat);
+  loop_water_flow(&input_pipe);
+}
+
+void loop_water_flow(flow_sensor_t* sensor_t)
+{
+   if((millis() - sensor_t->oldTime) > 1000)    // Only process counters once per second
+  {
+    // Disable the interrupt while calculating flow rate and sending the value to
+    // the host
+    detachInterrupt(sensor_t->sensorInterrupt);
+
+    // Because this loop may not complete in exactly 1 second intervals we calculate
+    // the number of milliseconds that have passed since the last execution and use
+    // that to scale the output. We also apply the calibrationFactor to scale the output
+    // based on the number of pulses per second per units of measure (litres/minute in
+    // this case) coming from the sensor.
+    sensor_t->flowRate = ((1000.0 / (millis() - sensor_t->oldTime)) * sensor_t->pulseCount) / calibrationFactor;
+
+    // Note the time this processing pass was executed. Note that because we've
+    // disabled interrupts the millis() function won't actually be incrementing right
+    // at this point, but it will still return the value it was set to just before
+    // interrupts went away.
+    sensor_t->oldTime = millis();
+
+    // Divide the flow rate in litres/minute by 60 to determine how many litres have
+    // passed through the sensor in this 1 second interval, then multiply by 1000 to
+    // convert to millilitres.
+    sensor_t->flowMilliLitres = (sensor_t->flowRate / 60) * 1000;
+
+    // Add the millilitres passed in this second to the cumulative total
+    sensor_t->totalMilliLitres += sensor_t->flowMilliLitres;
+
+    unsigned int frac;
+
+    // Print the flow rate for this second in litres / minute
+    Serial.print("Flow rate: ");
+    Serial.print(int(sensor_t->flowRate));  // Print the integer part of the variable
+    Serial.print(".");             // Print the decimal point
+    // Determine the fractional part. The 10 multiplier gives us 1 decimal place.
+    frac = (sensor_t->flowRate - int(sensor_t->flowRate)) * 10;
+    Serial.print(frac, DEC) ;      // Print the fractional part of the variable
+    Serial.print("L/min");
+    // Print the number of litres flowed in this second
+    Serial.print("  Current Liquid Flowing: ");             // Output separator
+    Serial.print(sensor_t->flowMilliLitres);
+    Serial.print("mL/Sec");
+
+    // Print the cumulative total of litres flowed since starting
+    Serial.print("  Output Liquid Quantity: ");             // Output separator
+    Serial.print(sensor_t->totalMilliLitres);
+    Serial.println("mL");
+
+    // Reset the pulse counter so we can start incrementing again
+    sensor_t->pulseCount = 0;
+
+    // Enable the interrupt again now that we've finished sending output
+    attachInterrupt( sensor_t->sensorInterrupt, sensor_t->pulseCounter, FALLING);
+  }
+}
+
+void loop(void){
+

 }

-void loop(void){
+/*
+Interrupt Service Routine
+ */
+void pulseCounter_heat()
+{
+  // Increment the pulse counter
+  input_heat.pulseCount++;
+}

-
+void pulseCounter_pipe()
+{
+  // Increment the pulse counter
+  input_pipe.pulseCount++;
 }


increase response threshold

increase response threshold

--- glass/glass.ino
+++ glass/glass.ino
@@ -47,7 +47,7 @@
 boolean ir_bcast_mode = true;
 unsigned long ir_time;
 unsigned int ir_cycle = 200;  // broadcat IR signal every X ms
-unsigned int ir_response_threshold = 300;
+unsigned int ir_response_threshold = 600;

 // EXPERIMENT
 const int MODE_IR = 1;


report other cell info

report other cell info

--- sketch_smartlock/sketch_smartlock.ino
+++ sketch_smartlock/sketch_smartlock.ino
@@ -7,7 +7,7 @@
 #include <LTask.h>
 #include <MQTTClient.h>

-#define JSON_BUF_SIZE 256
+#define JSON_BUF_SIZE 1024

 #define PIN_MOTOR 0
 #define PIN_LOCK_STATUS 5
@@ -67,7 +67,6 @@
   *(VMINT *)userData = vm_cell_open();
   return TRUE;
 }
-

 /*
   Wrapper to the low-level function vm_cell_get_cur_cell_info()
@@ -327,6 +326,15 @@
   }
 }

+static void add_cell_info(JsonArray& json_array, vm_cell_info_struct *info) {
+  JsonObject& cell = json_array.createNestedObject();
+  cell["mcc"] = info->mcc;
+  cell["mnc"] = info->mnc;
+  cell["lac"] = info->lac;
+  cell["ci"] = info->ci;
+  cell["sig"] = info->rxlev;
+}
+
 static void handle_report() {
   if (!g_report_lock && !g_report_other) {
     return;
@@ -348,13 +356,21 @@
     root["battery"] = LBattery.level();
     root["charge"] = (LBattery.isCharging() == true);

-    vm_cell_info_struct *current_cell_ptr = NULL;
+    VMINT *neighbor_cell_number;
+    vm_cell_info_struct *current_cell_ptr;
+    vm_cell_info_struct **neighbor_cell_ptr;
     LTask.remoteCall(&get_current_cell_info, (void *)&current_cell_ptr);
-    JsonObject& cell = root.createNestedObject("cell");
-    cell["mcc"] = current_cell_ptr->mcc;
-    cell["mnc"] = current_cell_ptr->mnc;
-    cell["lac"] = current_cell_ptr->lac;
-    cell["ci"] = current_cell_ptr->ci;
+    LTask.remoteCall(&get_neighbor_cell_number, (void *)&neighbor_cell_number);
+    LTask.remoteCall(&get_neighbor_cell_info, (void *)&neighbor_cell_ptr);
+
+    JsonArray& json_array = root.createNestedArray("cell");
+    add_cell_info(json_array, current_cell_ptr);
+    if (neighbor_cell_number && *neighbor_cell_number > 0) {
+      for (int i = 0; i < *neighbor_cell_number && i < 4; i++) {
+        add_cell_info(json_array, neighbor_cell_ptr[i]);
+      }
+    }
+
     g_report_other = false;
   }


fix lock status read

fix lock status read

--- sketch_smartlock/sketch_smartlock.ino
+++ sketch_smartlock/sketch_smartlock.ino
@@ -1,10 +1,12 @@
 #include <ArduinoJson.h>
 #include <LGPRS.h>
 #include <LGPRSClient.h>
+#include <LBattery.h>
 #include <LGPS.h>
+#define MQTT_BUFFER_SIZE 256
 #include <MQTTClient.h>

-#define JSON_BUF_SIZE 192
+#define JSON_BUF_SIZE 256

 #define PIN_MOTOR 0
 #define PIN_LOCK_STATUS 5
@@ -123,9 +125,10 @@
   uint8_t buf[256];
   bool rc = false;
   LGPRSClient net_client;
-  while (0 == net_client.connect("tick-t.yunba.io", 9977)) {
-    Serial.println("reconnect tick");
-    delay(500);
+  Serial.println("connect tick");
+  while (!net_client.connect("tick-t.yunba.io", 9977)) {
+    Serial.println(".");
+    delay(1000);
   }

   String data = "{\"a\":\"" + String(appkey) + "\",\"n\":\"1\",\"v\":\"v1.0\",\"o\":\"1\"}";
@@ -173,11 +176,11 @@
   bool rc = false;
   LGPRSClient net_client;

-  while (0 == net_client.connect("reg-t.yunba.io", 9944)) {
-    Serial.println("reconnect reg");
+  Serial.println("connect reg");
+  while (!net_client.connect("reg-t.yunba.io", 9944)) {
+    Serial.println(".");
     delay(1000);
   }
-  delay(200);

   String data;
   if (device_id == NULL)
@@ -292,6 +295,8 @@
   String gps = String((char *)g_gps_info.GPGGA);
   gps.trim();
   root["gps"] = gps;
+  root["battery"] = LBattery.level();
+  root["charge"] = (LBattery.isCharging() == true);

   String json;
   root.printTo(json);
@@ -365,7 +370,7 @@
       }
       break;
     case LOCK_UNLOCKED:
-      if (millis() - g_unlocked_ms < 100) {
+      if (millis() - g_unlocked_ms < 400) {
         break;
       }
       if (lock_status_on()) {
@@ -383,10 +388,10 @@
 static void check_network() {
   if (millis() - g_check_net_ms > 20000) {
     if (!g_mqtt_client.connected()) {
-      Serial.println("mqtt connection failed, reset gprs");
+      Serial.println("mqtt connection failed, try reconnect");
       LGPS.powerOff();
       sync_buzzer(2000);
-      g_status = STATUS_INIT_GPRS;
+      g_status = STATUS_INIT_YUNBA;
     } else {
       Serial.println("mqtt connection is ok");
     }
@@ -418,9 +423,9 @@
   digitalWrite(PIN_BUZZER, LOW);

   if (lock_status_on()) {
+    g_lock_status = LOCK_LOCKED;
+  } else {
     g_lock_status = LOCK_UNLOCKED;
-  } else {
-    g_lock_status = LOCK_LOCKED;
   }
   g_status = STATUS_INIT_GPRS;
 }


docs: Minor fixes in the documentation for the sample file.

Resolves: #40

--- examples/UltrasonicSimple/UltrasonicSimple.ino
+++ examples/UltrasonicSimple/UltrasonicSimple.ino
@@ -1,11 +1,13 @@
 /*
  * Ultrasonic Simple
- * Print the distance read for the
- * HR-SC04 Ultrasonic Sensor in centimeters.
+ * Prints the distance read by an ultrasonic sensor in
+ * centimeters. They are supported to four pins ultrasound
+ * sensors (liek HC-SC04) and three pins (like PING)))
+ * and Seeed Studio sesores).
  *
  * The circuit:
- * * Module HR-SC04 (4 pins) or PING))) (and other with 3 pins),
- *   attached to digital pins as follows:
+ * * Module HR-SC04 (four pins) or PING))) (and other with
+ *   three pins), attached to digital pins as follows:
  * ---------------------    ---------------------
  * | HC-SC04 | Arduino |    | 3 pins  | Arduino |
  * ---------------------    ---------------------
@@ -14,17 +16,18 @@
  * |   Echo  |   13    |    |   Gnd   |   GND   |
  * |   Gnd   |   GND   |    ---------------------
  * ---------------------
- * Note: You need not obligatorily use the pins 12 and 13
+ * Note: You need not obligatorily use the pins defined above
  *
- * By default, the distance returned by the distanceRead() method is
- * in centimeters, to get the distance in inches, pass INC as a parameter.
- * Example: Ultrasonic.distanceRead(INC)
+ * By default, the distance returned by the distanceRead()
+ * method is in centimeters, to get the distance in inches,
+ * pass INC as a parameter.
+ * Example: ultrasonic.distanceRead(INC)
  *
  * created 3 Apr 2014
  * by Erick Simões (github: @ErickSimoes | twitter: @AloErickSimoes)
  * modified 23 Jan 2017
  * by Erick Simões (github: @ErickSimoes | twitter: @AloErickSimoes)
- * modified 01 Mar 2017
+ * modified 03 Mar 2017
  * by Erick Simões (github: @ErickSimoes | twitter: @AloErickSimoes)
  *
  * This example code is released into the MIT License.