Update taqi.ino

Update taqi.ino

--- taqi/taqi.ino
+++ taqi/taqi.ino
@@ -1,358 +1,358 @@
-//#define __DEBUG__
-
-#define threshold 500
-#define baud 9600
-#define short_del 500
-#define long_del 2000
-
-const unsigned int red[] = {10, 7, 2, 13}; //r1, r2, r3, r4
-const unsigned int yellow[] = {9, 6, 3, 12};
-const unsigned int green[] = {8, 5, 4, 11};
-const unsigned int ir[] = {A2, A3, A1, A0};
-
-bool reading[] = {false, false, false, false};
-
-enum LIGHT {FIRST = 0, SECOND = 1, THIRD = 2, FOURTH = 3, NONE = 4};
-
-LIGHT light;
-
-int index = 4;
-
-void debug(void){
-  Serial.println (" == DEBUG BEGIN == ");
-  for (int i = 0; i < 4; i++){
-    Serial.println("IR [ " + String(i) + "] = " + String(analogRead(ir[i])));
-    delay(short_del);
-  }
-  Serial.println (" == DEBUG END == ");
-  Serial.println();
-  delay(long_del);
-}
-
-void setup() {
-  Serial.begin(baud);
-  for (int i = 0; i < 4; i++){
-    pinMode(red[i], OUTPUT);
-    pinMode(yellow[i], OUTPUT);
-    pinMode(green[i], OUTPUT);
-    pinMode(ir[i], INPUT);
-  }
-}
-
-int whichLight(void){
-  if (analogRead(ir[0]) < threshold) return FIRST;
-  else if (analogRead(ir[1]) < threshold) return SECOND;
-  else if (analogRead(ir[2]) < threshold) return THIRD;
-  else if (analogRead(ir[3]) < threshold) return FOURTH;
-  else return NONE;
-}
-
-void offAll (void){
-  for (int i = 0; i < 4; i++){
-    digitalWrite (red[i], LOW);
-    digitalWrite (yellow[i], LOW);
-    digitalWrite (green[i], LOW);
-  }
-}
-
-void firstLight(void){
-  offAll();
-  digitalWrite (green[FIRST], HIGH);
-  digitalWrite(red[SECOND], HIGH);
-  digitalWrite(red[THIRD], HIGH);
-  digitalWrite(red[FOURTH], HIGH);
-}
-
-void secondLight(void){
-  offAll();
-  digitalWrite(green[SECOND], HIGH);
-  digitalWrite(red[FIRST], HIGH);
-  digitalWrite(red[THIRD], HIGH);
-  digitalWrite(red[FOURTH], HIGH);
-}
-
-
-void thirdLight(void){
-  offAll();
-  digitalWrite(green[THIRD], HIGH);
-  digitalWrite(red[FIRST], HIGH);
-  digitalWrite(red[SECOND], HIGH);
-  digitalWrite(red[FOURTH], HIGH);
-}
-
-void fourthLight(void){
-  offAll();
-  digitalWrite(green[FOURTH], HIGH);
-  digitalWrite(red[FIRST], HIGH);
-  digitalWrite(red[THIRD], HIGH);
-  digitalWrite(red[SECOND], HIGH);
-}
-
-
-void onAll(void){
-  for (int i = 0; i < 4; i++) {
-    digitalWrite(red[i], HIGH);
-    digitalWrite(yellow[i], HIGH);
-    digitalWrite(green[i], HIGH);
-  }
-}
-
-
-void onIdle(void){
-
-  index = whichLight();
-
-  // For first light
-  digitalWrite(green[FIRST], HIGH);
-  digitalWrite(red[SECOND], HIGH);
-  digitalWrite(red[THIRD], HIGH);
-  digitalWrite(red[FOURTH], HIGH);
-  delay(long_del);
-  digitalWrite(green[FIRST], LOW);
-  digitalWrite(red[SECOND], LOW);
-  digitalWrite(red[THIRD], LOW);
-  digitalWrite(red[FOURTH], LOW);
-
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
-  delay(short_del);
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
-
-  index = whichLight();
-
-  //For second
-  digitalWrite(green[SECOND], HIGH);
-  digitalWrite(red[FIRST], HIGH);
-  digitalWrite(red[THIRD], HIGH);
-  digitalWrite(red[FOURTH], HIGH);
-  delay(long_del);
-  digitalWrite(green[SECOND], LOW);
-  digitalWrite(red[FIRST], LOW);
-  digitalWrite(red[THIRD], LOW);
-  digitalWrite(red[FOURTH], LOW);
-
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
-  delay(short_del);
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
-
-  index = whichLight();
-
-  //For third
-  digitalWrite(green[THIRD], HIGH);
-  digitalWrite(red[FIRST], HIGH);
-  digitalWrite(red[SECOND], HIGH);
-  digitalWrite(red[FOURTH], HIGH);
-  delay(long_del);
-  digitalWrite(green[THIRD], LOW);
-  digitalWrite(red[FIRST], LOW);
-  digitalWrite(red[SECOND], LOW);
-  digitalWrite(red[FOURTH], LOW);
-
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
-  delay(short_del);
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
-
-  index = whichLight();
-
-  //For fourth
-  digitalWrite(green[FOURTH], HIGH);
-  digitalWrite(red[FIRST], HIGH);
-  digitalWrite(red[SECOND], HIGH);
-  digitalWrite(red[THIRD], HIGH);
-  delay(long_del);
-  digitalWrite(green[FOURTH], LOW);
-  digitalWrite(red[FIRST], LOW);
-  digitalWrite(red[SECOND], LOW);
-  digitalWrite(red[THIRD], LOW);
-
-  index = whichLight();
-
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
-  delay(short_del);
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
-
-}
-
-#ifdef __DEBUG__
-void loop() { onAll(); }
-
-#else
-
-
-
-void loop(){
-
-  int index = 4;
-
-  index = whichLight();
-
-  while(index != NONE){
-    index = whichLight();
-    switch(index){
-      case FIRST:
-        firstLight();
-        break;
-      case SECOND:
-        secondLight();
-        break;
-
-      case THIRD:
-        thirdLight();
-        break;
-
-      case FOURTH:
-        fourthLight();
-        break;
-
-      default:
-        offAll();
-        break;
-    }
-  }
-
-  while(whichLight() == NONE){
-
-  if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-
-      // For first light
-  digitalWrite(green[FIRST], HIGH);
-  digitalWrite(red[SECOND], HIGH);
-  digitalWrite(red[THIRD], HIGH);
-  digitalWrite(red[FOURTH], HIGH);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  delay(long_del);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  digitalWrite(green[FIRST], LOW);
-  digitalWrite(red[SECOND], LOW);
-  digitalWrite(red[THIRD], LOW);
-  digitalWrite(red[FOURTH], LOW);
-  index = whichLight();
-
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
-  index = whichLight();
-  delay(short_del);
-  index = whichLight();
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
-
-  index = whichLight();
-
-  //For second
-  digitalWrite(green[SECOND], HIGH);
-  digitalWrite(red[FIRST], HIGH);
-  digitalWrite(red[THIRD], HIGH);
-  digitalWrite(red[FOURTH], HIGH);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  delay(long_del);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  digitalWrite(green[SECOND], LOW);
-  digitalWrite(red[FIRST], LOW);
-  digitalWrite(red[THIRD], LOW);
-  digitalWrite(red[FOURTH], LOW);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  delay(short_del);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
-
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-
-  //For third
-  digitalWrite(green[THIRD], HIGH);
-  digitalWrite(red[FIRST], HIGH);
-  digitalWrite(red[SECOND], HIGH);
-  digitalWrite(red[FOURTH], HIGH);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  delay(long_del);
-  digitalWrite(green[THIRD], LOW);
-  digitalWrite(red[FIRST], LOW);
-  digitalWrite(red[SECOND], LOW);
-  digitalWrite(red[FOURTH], LOW);
-
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  delay(short_del);
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-
-
-  //For fourth
-  digitalWrite(green[FOURTH], HIGH);
-  digitalWrite(red[FIRST], HIGH);
-  digitalWrite(red[SECOND], HIGH);
-  digitalWrite(red[THIRD], HIGH);
-
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-
-  delay(long_del);
-  digitalWrite(green[FOURTH], LOW);
-  digitalWrite(red[FIRST], LOW);
-  digitalWrite(red[SECOND], LOW);
-  digitalWrite(red[THIRD], LOW);
-
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  delay(short_del);
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
-
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-
-  }
-}
-
-
-#endif
-
+//#define __DEBUG__
+
+#define threshold 500
+#define baud 9600
+#define short_del 500
+#define long_del 2000
+
+const unsigned int red[] = {10, 7, 2, 13}; //r1, r2, r3, r4
+const unsigned int yellow[] = {9, 6, 3, 12};
+const unsigned int green[] = {8, 5, 4, 11};
+const unsigned int ir[] = {0, 1, 2, 3};
+
+bool reading[] = {false, false, false, false};
+
+enum LIGHT {FIRST = 0, SECOND = 1, THIRD = 2, FOURTH = 3, NONE = 4};
+
+LIGHT light;
+
+int index = 4;
+
+void debug(void){
+  Serial.println (" == DEBUG BEGIN == ");
+  for (int i = 0; i < 4; i++){
+    Serial.println("IR [ " + String(i) + "] = " + String(analogRead(ir[i])));
+    delay(short_del);
+  }
+  Serial.println (" == DEBUG END == ");
+  Serial.println();
+  delay(long_del);
+}
+
+void setup() {
+  Serial.begin(baud);
+  for (int i = 0; i < 4; i++){
+    pinMode(red[i], OUTPUT);
+    pinMode(yellow[i], OUTPUT);
+    pinMode(green[i], OUTPUT);
+    pinMode(ir[i], INPUT);
+  }
+}
+
+int whichLight(void){
+  if (analogRead(ir[0]) < threshold) return FIRST;
+  else if (analogRead(ir[1]) < threshold) return SECOND;
+  else if (analogRead(ir[2]) < threshold) return THIRD;
+  else if (analogRead(ir[3]) < threshold) return FOURTH;
+  else return NONE;
+}
+
+void offAll (void){
+  for (int i = 0; i < 4; i++){
+    digitalWrite (red[i], LOW);
+    digitalWrite (yellow[i], LOW);
+    digitalWrite (green[i], LOW);
+  }
+}
+
+void firstLight(void){
+  offAll();
+  digitalWrite (green[FIRST], HIGH);
+  digitalWrite(red[SECOND], HIGH);
+  digitalWrite(red[THIRD], HIGH);
+  digitalWrite(red[FOURTH], HIGH);
+}
+
+void secondLight(void){
+  offAll();
+  digitalWrite(green[SECOND], HIGH);
+  digitalWrite(red[FIRST], HIGH);
+  digitalWrite(red[THIRD], HIGH);
+  digitalWrite(red[FOURTH], HIGH);
+}
+
+
+void thirdLight(void){
+  offAll();
+  digitalWrite(green[THIRD], HIGH);
+  digitalWrite(red[FIRST], HIGH);
+  digitalWrite(red[SECOND], HIGH);
+  digitalWrite(red[FOURTH], HIGH);
+}
+
+void fourthLight(void){
+  offAll();
+  digitalWrite(green[FOURTH], HIGH);
+  digitalWrite(red[FIRST], HIGH);
+  digitalWrite(red[THIRD], HIGH);
+  digitalWrite(red[SECOND], HIGH);
+}
+
+
+void onAll(void){
+  for (int i = 0; i < 4; i++) {
+    digitalWrite(red[i], HIGH);
+    digitalWrite(yellow[i], HIGH);
+    digitalWrite(green[i], HIGH);
+  }
+}
+
+
+void onIdle(void){
+
+  index = whichLight();
+
+  // For first light
+  digitalWrite(green[FIRST], HIGH);
+  digitalWrite(red[SECOND], HIGH);
+  digitalWrite(red[THIRD], HIGH);
+  digitalWrite(red[FOURTH], HIGH);
+  delay(long_del);
+  digitalWrite(green[FIRST], LOW);
+  digitalWrite(red[SECOND], LOW);
+  digitalWrite(red[THIRD], LOW);
+  digitalWrite(red[FOURTH], LOW);
+
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
+  delay(short_del);
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
+
+  index = whichLight();
+
+  //For second
+  digitalWrite(green[SECOND], HIGH);
+  digitalWrite(red[FIRST], HIGH);
+  digitalWrite(red[THIRD], HIGH);
+  digitalWrite(red[FOURTH], HIGH);
+  delay(long_del);
+  digitalWrite(green[SECOND], LOW);
+  digitalWrite(red[FIRST], LOW);
+  digitalWrite(red[THIRD], LOW);
+  digitalWrite(red[FOURTH], LOW);
+
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
+  delay(short_del);
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
+
+  index = whichLight();
+
+  //For third
+  digitalWrite(green[THIRD], HIGH);
+  digitalWrite(red[FIRST], HIGH);
+  digitalWrite(red[SECOND], HIGH);
+  digitalWrite(red[FOURTH], HIGH);
+  delay(long_del);
+  digitalWrite(green[THIRD], LOW);
+  digitalWrite(red[FIRST], LOW);
+  digitalWrite(red[SECOND], LOW);
+  digitalWrite(red[FOURTH], LOW);
+
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
+  delay(short_del);
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
+
+  index = whichLight();
+
+  //For fourth
+  digitalWrite(green[FOURTH], HIGH);
+  digitalWrite(red[FIRST], HIGH);
+  digitalWrite(red[SECOND], HIGH);
+  digitalWrite(red[THIRD], HIGH);
+  delay(long_del);
+  digitalWrite(green[FOURTH], LOW);
+  digitalWrite(red[FIRST], LOW);
+  digitalWrite(red[SECOND], LOW);
+  digitalWrite(red[THIRD], LOW);
+
+  index = whichLight();
+
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
+  delay(short_del);
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
+
+}
+
+#ifdef __DEBUG__
+void loop() { onAll(); }
+
+#else
+
+
+
+void loop(){
+
+  int index = 4;
+
+  index = whichLight();
+
+  while(index != NONE){
+    index = whichLight();
+    switch(index){
+      case FIRST:
+        firstLight();
+        break;
+      case SECOND:
+        secondLight();
+        break;
+
+      case THIRD:
+        thirdLight();
+        break;
+
+      case FOURTH:
+        fourthLight();
+        break;
+
+      default:
+        offAll();
+        break;
+    }
+  }
+
+  while(whichLight() == NONE){
+
+  if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+
+      // For first light
+  digitalWrite(green[FIRST], HIGH);
+  digitalWrite(red[SECOND], HIGH);
+  digitalWrite(red[THIRD], HIGH);
+  digitalWrite(red[FOURTH], HIGH);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  delay(long_del);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  digitalWrite(green[FIRST], LOW);
+  digitalWrite(red[SECOND], LOW);
+  digitalWrite(red[THIRD], LOW);
+  digitalWrite(red[FOURTH], LOW);
+  index = whichLight();
+
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
+  index = whichLight();
+  delay(short_del);
+  index = whichLight();
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
+
+  index = whichLight();
+
+  //For second
+  digitalWrite(green[SECOND], HIGH);
+  digitalWrite(red[FIRST], HIGH);
+  digitalWrite(red[THIRD], HIGH);
+  digitalWrite(red[FOURTH], HIGH);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  delay(long_del);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  digitalWrite(green[SECOND], LOW);
+  digitalWrite(red[FIRST], LOW);
+  digitalWrite(red[THIRD], LOW);
+  digitalWrite(red[FOURTH], LOW);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  delay(short_del);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
+
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+
+  //For third
+  digitalWrite(green[THIRD], HIGH);
+  digitalWrite(red[FIRST], HIGH);
+  digitalWrite(red[SECOND], HIGH);
+  digitalWrite(red[FOURTH], HIGH);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  delay(long_del);
+  digitalWrite(green[THIRD], LOW);
+  digitalWrite(red[FIRST], LOW);
+  digitalWrite(red[SECOND], LOW);
+  digitalWrite(red[FOURTH], LOW);
+
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  delay(short_del);
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+
+
+  //For fourth
+  digitalWrite(green[FOURTH], HIGH);
+  digitalWrite(red[FIRST], HIGH);
+  digitalWrite(red[SECOND], HIGH);
+  digitalWrite(red[THIRD], HIGH);
+
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+
+  delay(long_del);
+  digitalWrite(green[FOURTH], LOW);
+  digitalWrite(red[FIRST], LOW);
+  digitalWrite(red[SECOND], LOW);
+  digitalWrite(red[THIRD], LOW);
+
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  delay(short_del);
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
+
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+
+  }
+}
+
+
+#endif
+


Implemented food, score and a rather buggy tail

--- snack/snack.ino
+++ snack/snack.ino
@@ -3,8 +3,9 @@
 // make an instance of arduboy used for many functions
 Arduboy arduboy;

-struct coords
+class coords
 {
+  public:
   int X = 0;
   int Y = 0;
 };
@@ -16,11 +17,9 @@
   int X = 0;
   int Y = 0;
   char dir = 'R';
-
-  Player()
-  {
-
-  }
+  int Len = 1;
+  static const int MaxLength = 10;
+  Coords *Moves[MaxLength] = {NULL};
 };

 typedef struct player Player;
@@ -34,11 +33,77 @@
 int minY = 0;

 int score = 0;
+int arrayPosition = 0;

 void GenerateFood()
 {
-  foodLocation.X = 0;
-  foodLocation.Y = 0;
+  arduboy.initRandomSeed();
+  foodLocation.X = random(minX, maxX);
+  foodLocation.Y = random(minY, maxY);
+}
+
+void StartGame()
+{
+  p1.X = 1;
+  p1.Y = 1;
+  GenerateFood();
+}
+
+//TODO only log move if location has changed.
+void LogMove()
+{
+  if(p1.Moves[arrayPosition] == NULL)
+  {
+      p1.Moves[arrayPosition] = new Coords();
+
+  }
+      p1.Moves[arrayPosition]->X = p1.X;
+      p1.Moves[arrayPosition]->Y = p1.Y;
+
+  if(arrayPosition < p1.Len)
+  {
+    arrayPosition += 1;
+
+  }
+  else
+  {
+    arrayPosition = 0;
+  }
+}
+
+void CollisionDetection()
+{
+  if(p1.X == foodLocation.X && p1.Y == foodLocation.Y)
+  {
+    p1.Len += 1;
+    score += 1;
+    LogMove();
+    GenerateFood();
+  }
+}
+
+void DrawTail()
+{
+  int tailPosition = arrayPosition;
+  for (int i=0; i < p1.Len; i++){
+      if(p1.Moves[tailPosition] != NULL)
+      {
+         arduboy.drawPixel(p1.Moves[tailPosition]->X, p1.Moves[tailPosition]->Y, 1);
+      }
+      else
+      {
+        return;
+      }
+
+      if(tailPosition > 0)
+      {
+        tailPosition -= 1;
+      }
+      else
+      {
+        tailPosition = 0;
+      }
+   }
 }

 // This function runs once in your game.
@@ -51,8 +116,7 @@
   // default 60 and it saves us battery life
   arduboy.setFrameRate(15);

-  p1.X = 1;
-  p1.Y = 1;
+ StartGame();
 }

@@ -66,10 +130,7 @@
   // first we clear our screen to black
   arduboy.clear();

-  // the next couple of lines will deal with checking if the D-pad buttons
-  // are pressed and move our text accordingly.
-  // We check to make sure that x and y stay within a range that keeps the
-  // text on the screen.
+  CollisionDetection();

   if(arduboy.pressed(RIGHT_BUTTON)) {
     p1.dir = 'R';
@@ -117,11 +178,14 @@
   }

   arduboy.drawPixel(p1.X, p1.Y, 1);
-  // (positions start at 0, 0)
-  //arduboy.setCursor(4, 9);
-
-  // then we print to screen what is in the Quotation marks ""
-  //arduboy.print(F("Hello, world!"));
+  arduboy.drawPixel(foodLocation.X, foodLocation.Y, 1);
+  DrawTail();
+  LogMove();
+
+  arduboy.setCursor(0, 0);
+  arduboy.print("Score ");
+  arduboy.print(score);
+

   // then we finaly we tell the arduboy to display what we just wrote to the display
   arduboy.display();


LAN works if sensor reading is commented

--- net_th_meter/net_th_meter.ino
+++ net_th_meter/net_th_meter.ino
@@ -24,8 +24,8 @@

 #define DHT_TYPE      DHT22 // DHT 22
 #define ONE_WIRE_CNT  3     // count of 1-wire connections
-#define TCP_PORT      1000//502   // Modbus TCP default port
-#define RESPONSE_LEN  7     // length of Modbus TCP response
+#define TCP_PORT      502   // Modbus TCP default port
+#define RESPONSE_LEN  29    // length of Modbus TCP response

 // DHT instance
 DHT dht(DHT_PIN, DHT_TYPE);
@@ -43,7 +43,11 @@
 EthernetServer server = EthernetServer(TCP_PORT);
 EthernetClient client;
 boolean clientConnected = false;
-byte response[RESPONSE_LEN] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06};
+byte response[RESPONSE_LEN] =
+  { 0x00, 0x00, 0x00, 0x00, 0x00, 0x17, 0x00, 0x03, 0x14, // bytes 0-9 - according to Modbus TCP specification
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,       // bytes 10-17 - holding registers 1-2, 3-4: dht_t, dht_h
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,       // bytes 18-25 - holding registers 5-6, 7-8: ds_t0, ds_t1
+    0x00, 0x00, 0x00, 0x00 };                             // bytes 26-29 - holding registers 9-10: ds_t2

 // Speed control
 unsigned long time;
@@ -141,9 +145,9 @@
   }

   if (!clientConnected) {
+    // connection is considered to be established only when data are received
     client = server.available();
     if (client) {
-      client.flush();
       clientConnected = true;
       Serial.println("New client is connected");
     } else {


SetTime: don't echo written binary strings to serial

--- SetTime/SetTime.ino
+++ SetTime/SetTime.ino
@@ -234,6 +234,7 @@
     // wait for writing to go through
   }

+#if 0
   writeCurByte = 0;
   writeCurBit = 0;

@@ -246,6 +247,7 @@
     }
   }
   Serial.println();
+#endif
 }

 void insertBits(int n, uint8_t* dst, int dstBit, uint8_t data)


Add comments and use pipe constant

Add comments and use pipe constant

--- WirelessTrigger.ino
+++ WirelessTrigger.ino
@@ -110,7 +110,7 @@

     radio.startListening();
     radio.printDetails();
-    radio.writeAckPayload(1, &ackVal, 1);
+    radio.writeAckPayload(primaryPipeIndex, &ackVal, 1);

 #if ROLE == ROLE_GROUND
     //pinMode(heartbeatLEDGreenPin, OUTPUT);
@@ -158,9 +158,12 @@
         if (recvByte == heightInitialVal)
         {
             // TODO: Figure out why the first byte isn't already gone
+
+            // Declare a buffer to store the packet and read the data into it
             byte buffer[sizeof(float) + 1];
             receiveData(&buffer, sizeof(buffer));

+            // Dereference the data portion of the packet as a float
             lastAltitude = *(float*)(&(buffer[1]));
             Serial.println("Got altitude " + String(lastAltitude));
         }
@@ -174,6 +177,7 @@
     if (triggerButton.longPress()) {
         Serial.println(F("Sending trigger byte"));

+        // Record the last-sent signal
         lastTriggerType = true;
         lastTriggerSignalTime = millis();

@@ -182,6 +186,7 @@
     else if (resetButton.longPress()) {
         Serial.println(F("Sending reset byte"));

+        // Record the last-sent signal
         lastTriggerType = false;
         lastTriggerSignalTime = millis();

@@ -206,7 +211,7 @@
         display.print(lastTriggerType ? "Sent TRIGGER" : "Sent RESET      ");
     }
     else {
-        String altString = (lastAltitude == -1) ? "Null" : String(lastAltitude);
+        String altString = (lastAltitude == -1) ? "Unknown" : String(lastAltitude);
         display.print("ALTITUDE: " + altString + "        ");
     }
 #endif
@@ -226,9 +231,13 @@
         case ackVal:
             Serial.println(F("Heartbeat byte received"));

+            // Get the altitude value
             float altitude = getAltitude();

+            // Construct the packet. Has a one-byte header.
             byte packetData[sizeof(float) + 1] = { heightInitialVal };
+            // Get a pointer to the last 4 bytes of the packet buffer
+            // and set it to the altitude value
             float* packetFloatPortion = (float*)&packetData[1];
             *packetFloatPortion = altitude;

@@ -264,8 +273,8 @@
 bool receiveData(void* recvBuf, uint8_t numBytes) {
     if (radio.available()) {
         radio.read(recvBuf, numBytes);
-        // acks that we received it
-        radio.writeAckPayload(1, &ackVal, 1);
+        // Prep an ack for the next time we receive data
+        radio.writeAckPayload(primaryPipeIndex, &ackVal, 1);
         return true;
     }
     else {
@@ -280,13 +289,14 @@
     return val;
 }

-// send numBytes bytes on the radio from val
+// Sends arbitrary data of length numBytes from the given address
 byte sendData(void* val, int numBytes) {
     byte recvByte;

     if (radio.available())
         Serial.println(F("Data available before request was sent! This probably means something was not read correctly."));

+    // Print bytes that are going to be sent
     Serial.print(F("Sending data {"));
     for (int i = 0; i < numBytes; i++)
     {
@@ -295,18 +305,19 @@
     }
     Serial.println(F("}"));

+    // Stop listening temporarily so we can write
     radio.stopListening();
-    bool writeResult = radio.write(val, numBytes);
+    bool writeSuccess = radio.write(val, numBytes);
     radio.startListening();

-    if (writeResult) {
+    if (writeSuccess) {
         if (!radio.available()) {
-            Serial.println(F("Empty recv!"));
+            Serial.println(F("Empty receive buffer! Was expecting an ack."));
             return 0;
         }
         else {
             radio.read(&recvByte, 1);
-            radio.writeAckPayload(1, &ackVal, 1);
+            radio.writeAckPayload(primaryPipeIndex, &ackVal, 1);

             Serial.print(F("Received ack"));
         }


New telemetry

New telemetry

--- RobotBase.ino
+++ RobotBase.ino
@@ -6,8 +6,8 @@
 #include <TM1650.h>

 #define LED_PIN 13
-#define RC_RX_PIN 12
-#define RC_TX_PIN 11
+#define DRIVER_RX_PIN 12
+#define DRIVER_TX_PIN 11
 #define SSC_RX_PIN 10
 #define SSC_TX_PIN 9
 // power management //
@@ -16,28 +16,41 @@
 #define MOTOR_ENABLE_PIN 7
 #define MOTOR_DISABLE_PIN 8

+// uptime //
+byte NewSecond = 0;
+byte HalfSecond = 0;
+unsigned long uptimeSeconds = 0;
+
 // host communication //
-#define MAX_COMMAND 16
-#define BUF_SIZE 18
-byte buf[BUF_SIZE];
+#define MAX_COMMAND_LENGTH 16
+#define COMMAND_BUFFER_SIZE 18
+byte buf[COMMAND_BUFFER_SIZE];
 byte cmd = 0;
-byte bytes = 0;
+byte bytesInBuffer = 0;
 byte crc = 0;

+// power measurment //
+#define AMPS_SIZE 30
+#define AMPS_INTERVAL 50
+int amps[AMPS_SIZE];
+byte ampsIndex = 0;
+unsigned long lastAmpsTime = 0;
+long uAh = 0;
 Adafruit_INA219 ina219;
+
+#define DISPLAY_ALTER_INTERVAL 1500
 TM1650 tm;
+unsigned long lastTmTime = 0;
+int tmMode = 0;

 // common vars //
 unsigned long lastCommandTime;
 unsigned long commandTimeout = 2500;
 boolean IsConnected = false;
-unsigned long lastTmTime = 0;
-int tmMode = 0;
-#define DISPLAY_ALTER_INTERVAL 1500

 // RoboClaw //
 #define RC_ADDR 0x80
-RoboClaw roboclaw(RC_RX_PIN, RC_TX_PIN);
+RoboClaw roboclaw(DRIVER_RX_PIN, DRIVER_TX_PIN);
 boolean driveEnabled = false;
 unsigned long lastDriveCommandTime;
 unsigned long driveCommandTimeout = 20000;
@@ -73,7 +86,7 @@
   digitalWrite(MOTOR_ENABLE_PIN, LOW);
   digitalWrite(POWER_PIN, LOW);
   digitalWrite(MOTOR_DISABLE_PIN, LOW);
-  motor_power(false);
+  motorPower(false);

   // TM1650 display setup
   Wire.begin();
@@ -101,18 +114,74 @@

 void loop()
 {
+  MaintainUptime();
+
   // serial input
   ReadSerial();
   if (IsConnected) CheckCommandTimeout();
   if (driveEnabled) CheckDriveCommandTimeout();
-  UpdateVA();
+  ReadAmps();
+  DisplayVA();

   // motors
   if (motor_counter > 0) motor_counter--;
   if (motor_counter == 0) updateMotors();
 }

-void UpdateVA()
+void MaintainUptime()
+{
+  if (millis() % 1000 <= 500 && HalfSecond == 0)
+  {
+    NewSecond = 1;
+    HalfSecond = 1;
+  }
+
+  if (millis() % 1000 > 500) HalfSecond = 0;
+
+  if (NewSecond == 1)
+  {
+    uptimeSeconds++;
+    NewSecond = 0;
+  }
+}
+
+//=======================================
+
+//          in-robot Volts/Amps measurment
+
+//=======================================
+
+void ReadAmps()
+{
+  unsigned long ampsTime = millis();
+  if (ampsTime < lastAmpsTime) lastAmpsTime = 0;
+  if (ampsTime - lastAmpsTime > AMPS_INTERVAL)
+  {
+    lastAmpsTime = ampsTime;
+    amps[ampsIndex] = int(ina219.getCurrent_mA());
+    ampsIndex++;
+    if (ampsIndex >= AMPS_SIZE)
+    {
+      ampsIndex = 0;
+      UpdateUAh();
+    }
+  }
+}
+
+int getAvgAmps()
+{
+  long ampsSum = 0;
+  for (int i = 0; i < AMPS_SIZE; i++) ampsSum += amps[i];
+  return int(ampsSum / AMPS_SIZE);
+}
+
+void UpdateUAh()
+{
+  int mA = getAvgAmps();
+  uAh += int(mA * 5 / 12);
+}
+
+void DisplayVA()
 {
   unsigned long tmTime = millis();
   if (tmTime < lastTmTime) lastTmTime = 0;
@@ -120,17 +189,13 @@
   {
     if (tmMode == 0)
     {
-      float shuntvoltage = ina219.getShuntVoltage_mV();
-      float busvoltage = ina219.getBusVoltage_V();
-      int voltage = (int)(busvoltage * 100 + shuntvoltage / 10);
-      displayInt(voltage, 2);
+      displayVolts();
       tmMode = 1;
     }
     else
     if (tmMode == 1)
     {
-      int mA = abs(int(ina219.getCurrent_mA()));
-      displayInt(mA, 1);
+      displayAmps();
       if (IsConnected) tmMode = 2;
       else tmMode = 0;
     }
@@ -143,6 +208,18 @@

     lastTmTime = tmTime;
   }
+}
+
+void displayVolts()
+{
+    int voltage = int(ina219.getBusVoltage_V() * 100);
+    displayInt(voltage, 2);
+}
+
+void displayAmps()
+{
+  int mA = getAvgAmps();
+  displayInt(mA, 1);
 }

 void displayInt(int value, int dot)
@@ -162,28 +239,35 @@

 //=======================================

+
+
+//=======================================
+
 // read serial data into buffer. execute command
 void ReadSerial()
 {
+  byte b;
   while (Serial.available())
   {
-    buf[bytes] = Serial.read();
-    if (buf[bytes] == 10 || buf[bytes] == 13 || bytes >= MAX_COMMAND)
-    {
-      if (bytes > 0) Execute();
+    b = Serial.read();
+    buf[bytesInBuffer] = b;
+    if (b == 10 || b == 13 || bytesInBuffer >= MAX_COMMAND_LENGTH)
+    {
+      if (bytesInBuffer > 0) Execute();
+      bytesInBuffer = 0; // empty input buffer (only one command at a time)
       return;
     }
-    bytes++;
+    bytesInBuffer++;
   }
 }

 boolean crc8ok()
 {
   crc = 0;
-  for (byte i = 0; i < bytes - 1; i++) crc8(buf[i]);
-  if (crc == buf[bytes - 1]) return true;
+  for (byte i = 0; i < bytesInBuffer - 1; i++) crc8(buf[i]);
+  if (crc == buf[bytesInBuffer - 1]) return true;
   // if error
-  bytes = 0; // empty input buffer
+  bytesInBuffer = 0; // empty input buffer
   driveStop(); // disable motors
   Serial.println("crc"); // report CRC error
   return false;
@@ -242,7 +326,6 @@
 // the second is a subcommand
 void Execute()
 {
-  bytes = 0; // empty input buffer (only one command at a time)
   cmd = buf[0];
   if (cmd == 0 || cmd == 32) return;

@@ -252,7 +335,7 @@
   else
   if (cmd == 's') servo();
   else
-  if (cmd == 'b') battery();
+  if (cmd == 't') telemetry(); // reply contains a-amps, b-volts, c-charge, u-uptime
   else
   if (cmd == 'i') ina();
   else
@@ -273,40 +356,31 @@

 //=======================================

-// 'power off' command
-void power()
-{
-  pulsePin(POWER_PIN, 20);
-}
-
-//=======================================
-
-
-
-
-
-// power sensing
-
-
-
-
-
-//=======================================
-
-// 'battery voltage' command
-// result in mV and mA
-void battery()
-{
-  float shuntvoltage = ina219.getShuntVoltage_mV();
-  float busvoltage = ina219.getBusVoltage_V();
-  int current_mA;
-  current_mA = int(ina219.getCurrent_mA());
-  int voltage;
-  voltage = (int)(busvoltage * 1000 + shuntvoltage);
+
+
+
+
+// telemetry
+
+
+
+
+
+//=======================================
+
+// telemetry: battery and uptime
+void telemetry()
+{
+  int mV = int(ina219.getBusVoltage_V() * 1000);
+  int mA = getAvgAmps();
   Serial.write('b');
-  Serial.println(voltage);
+  Serial.println(mV);
   Serial.write('a');
-  Serial.println(current_mA);
+  Serial.println(mA);
+  Serial.write('c');
+  Serial.println(uAh);
+  Serial.write('u');
+  Serial.println(uptimeSeconds);
 }

 // INA219 control commands
@@ -335,6 +409,18 @@

+// 'power off' command
+void power()
+{
+  pulsePin(POWER_PIN, 20);
+}
+
+
+//=======================================
+
+
+
+

 // control motors

@@ -433,14 +519,14 @@
 {
   if (action)
   {
-      motor_power(true);
+      motorPower(true);
       driveUART(true);
       lastDriveCommandTime = millis();
   }
   else
   {
       driveUART(false);
-      motor_power(false);
+      motorPower(false);
   }
 }

@@ -452,7 +538,7 @@
   driveEnabled = action;
 }

-void motor_power(boolean action)
+void motorPower(boolean action)
 {
   if (action)
   {
@@ -638,7 +724,7 @@
 {
   byte i = 0;
   byte fin = index + count;
-  if (fin > BUF_SIZE) fin = BUF_SIZE;
+  if (fin > COMMAND_BUFFER_SIZE) fin = COMMAND_BUFFER_SIZE;
   while (buf[index] >= '0' && buf[index] <= '9' && index < fin)
   {
     i *= 10;
@@ -653,7 +739,7 @@
 {
   uint16_t i = 0;
   byte fin = index + count;
-  if (fin > BUF_SIZE) fin = BUF_SIZE;
+  if (fin > COMMAND_BUFFER_SIZE) fin = COMMAND_BUFFER_SIZE;
   while (buf[index] >= '0' && buf[index] <= '9' && index < fin)
   {
     i *= 10;


Changes to arduino sketch

Changes to arduino sketch

--- arduino/main/main.ino
+++ arduino/main/main.ino
@@ -1,7 +1,7 @@
 #include <LedControl.h>
 #include <Time.h>

-
+//Eugenio Moro

 #define SCROLL_DELAY 10 //ms
 #define LED_INTENSITY 1 //1-15


array of thresh

array of thresh

--- guitar-arduino.ino
+++ guitar-arduino.ino
@@ -26,8 +26,10 @@
 #define TUNING -12

-#define LASER_ANALOG_TH 975 //for analog read of bpw34. 900-1023 means laser is blocked, 0-600 means laser hit diode
-#define LASER_ANALOG_THOLD_US 5000 //[us] fastest accepted laser state change to prevent noise, fast strum may not be accepted
+//const int LASER_ANALOG_TH[] = {960, 920, 975, 711, 900, 975}; //for analog read of bpw34. 900-1023 means laser is blocked, 0-600 means laser hit diode
+int LASER_ANALOG_TH[] = {1024, 1024, 1024, 1024, 1024, 1024}; //for analog read of bpw34. 900-1023 means laser is blocked, 0-600 means laser hit diode
+#define LASER_ANALOG_EMPH 975 //for analog read of bpw34. 900-1023 means laser is blocked, 0-600 means laser hit diode
+#define LASER_ANALOG_THOLD_US 500 //[us] fastest accepted laser state change to prevent noise, fast strum may not be accepted
 //off topic: measured fastest cadence of strumming is 120ms(120000us)
 #define LASER_THOLD 1000 //[us]
 #define STOP_THOLD 500000 //[us]
@@ -326,9 +328,10 @@

 inline void laser_common_analog(int l_idx, boolean laser_blocked) {
   unsigned long us = micros();
-  if (laser_blocked != laser_status[l_idx]) { //ISR invoked but status did not change from current, do not know why ISR is called -> ignore
+  if (laser_blocked != laser_status[l_idx]) { //if all lasers blocked using palm, do not play tones when unblocking

     if (us > (laser_status_last_update_us[l_idx] + LASER_ANALOG_THOLD_US)) {
+      laser_status_last_update_us[l_idx] = us;

       laser_status[l_idx] = laser_blocked;

@@ -337,7 +340,6 @@
         send_stop_tone_event(true, true);
       }

-      laser_status_last_update_us[l_idx] = us;
       send_laser_event((boolean)laser_blocked, l_idx);
     } //else ignore, change was due to jitter, likely

@@ -422,6 +424,7 @@
   pinMode(stop_tone_pin, INPUT_PULLUP);
   attachInterrupt(digitalPinToInterrupt(stop_tone_pin), stop_ISR, FALLING);

+  delay(1000); //because analogRead returns strange values at start
 }

@@ -429,6 +432,26 @@
 //-------------------------
 void loop()
 {
+
+/* Debugging laser transistor levels
+      int a = analogRead(laser_pins[0]);
+      send_midi_debug(0, (int)((float)a / 8));
+      a = analogRead(laser_pins[1]);
+      send_midi_debug(1, (int)((float)a / 8));
+      a = analogRead(laser_pins[2]);
+      send_midi_debug(2, (int)((float)a / 8));
+      delay(200);
+      a = analogRead(laser_pins[3]);
+      send_midi_debug(3, (int)((float)a / 8));
+      a = analogRead(laser_pins[4]);
+      send_midi_debug(4, (int)((float)a / 8));
+      a = analogRead(laser_pins[5]);
+      send_midi_debug(5, (int)((float)a / 8));
+      delay(200);
+      return;
+*/
+
+
   bool narazil_na_prst = false;
   //scan fret by fret
   for (int f = 0; f <= (NO_FRETS-1); f++) { //f<=12
@@ -455,7 +478,7 @@

   //read analog emphasis
   boolean blocked = false;
-  if (analogRead(emphasis_pin) > LASER_ANALOG_TH)
+  if (analogRead(emphasis_pin) > LASER_ANALOG_EMPH)
     blocked = true;
   if (last_alaser_status[6] != blocked) { //status changed
     last_alaser_status[6] = blocked;
@@ -465,10 +488,24 @@
   //read lasers
   for (int i = 0; i < 6; i++) {
     boolean blocked = false;
-    if (analogRead(laser_pins[i]) > LASER_ANALOG_TH)
+
+    int a = analogRead(laser_pins[i]);
+//    if (i==1){
+//    send_midi_debug(i, (int)((float)a / 8));
+//    send_midi_debug(i, (int)((float)LASER_ANALOG_TH[i] / 8));
+//    delay(100);
+//    }
+    if (a > LASER_ANALOG_TH[i]+5)
       blocked = true;
-
+    else {
+      int delta = (int)((a - LASER_ANALOG_TH[i]) / 2);
+      if (delta < -1) delta = -1;
+      if (delta > 1) delta = 1;
+      LASER_ANALOG_TH[i] += delta; //update level of laser sensors dynamically
+    }
+
     if (last_alaser_status[i] != blocked) { //status changed
+//      send_midi_debug(i, (int)((float)a / 8));
       last_alaser_status[i] = blocked;
       laser_common_analog(i, blocked);
     }


IP and subnet now configurable via config GUI. Gateway and dns to follow.

--- mqttHA_Point/mqttHA_Point.ino
+++ mqttHA_Point/mqttHA_Point.ino
@@ -83,7 +83,7 @@
       }
   }
   else {
-     if (wifiConnectDHCP())
+     if (wifiConnectFixed())
      {
       Serial.println("");
       Serial.println("Connected to wifi network :/ ");
@@ -121,7 +121,7 @@
   return false;
 }
 /////////////////////////////////////////////////////////////////////////////////////////////////////////
-bool wifiConnectDHCP(void) {
+bool wifiConnectFixed(void) {
 //  String esubnet="";
 //  Serial.println("Reading EEPROM DHCP subnet");
 //  for (int i = 129; i < 133; ++i)
@@ -132,6 +132,10 @@
   IPAddress esubnet(EEPROM.read(133),EEPROM.read(134),EEPROM.read(135),EEPROM.read(136));
   IPAddress egateway(EEPROM.read(137),EEPROM.read(138),EEPROM.read(139),EEPROM.read(140));
   IPAddress edns(EEPROM.read(141),EEPROM.read(142),EEPROM.read(143),EEPROM.read(144));
+
+  Serial.println("Connecting with fixed IP");
+  Serial.print("IP: ");
+  Serial.println(estaticIP);
   Serial.print("subnet: ");
   Serial.println(esubnet);
   WiFi.mode(WIFI_STA);
@@ -251,12 +255,32 @@
         content += st;
         content += "
Key: <input type='password' name='pass' length=64>
";
         content += "
Select IP Address Mode
";
-        content += "
<select name='dhcpEnable'>";
+        content += "
<select id='dhcpEnable' name='dhcpEnable'>";
         content += "<option value='T' selected>DHCP</option>";
         content += "<option value='F'>Fixed</option>";
         content += "</select>
";
+        content += "
";
+        content += "
Enter Fixed IP Parameters
";
+        content += "
";
+        content += "IP Address: ";
+        content += "<input type='text' name='IP' length=64 pattern='((^|\\.)((25[0-5])|(2[0-4]\\d)|(1\\d\\d)|([1-9]?\\d))){4}$'>";
+        content += "
";
+        content += "
";
+        content += "Subnet Mask: ";
+        content += "<input type='text' name='subnet' length=64 pattern='((^|\\.)((25[0-5])|(2[0-4]\\d)|(1\\d\\d)|([1-9]?\\d))){4}$'>";
+        content += "
";
+        content += "
";
+        content += "Gateway: ";
+        content += "<input type='text' name='gateway' length=64 pattern='((^|\.)((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]?\d))){4}$'>";
+        content += "
";
+        content += "
";
+        content += "DNS Server: ";
+        content += "<input type='text' name='dns' length=64 pattern='((^|\.)((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]?\d))){4}$'>";
+        content += "
";
+        content += "
";
         content += "<input type='submit' value='Enter'>";
         content += "</form>";
+        content += "";
         content += "";
         content += "";
         server.send(200, "text/html", content);
@@ -265,6 +289,7 @@
         String qsid = server.arg("ssid");
         String qpass = server.arg("pass");
         String qdhcpEnable = server.arg("dhcpEnable");
+
         if (qsid.length() > 0 && qpass.length() > 0) {
           Serial.println("clearing eeprom");
           for (int i = 0; i < 128; ++i) { EEPROM.write(i, 0); }
@@ -290,7 +315,44 @@
           Serial.println("writing eeprom DHCP enable:");
           EEPROM.write(128, qdhcpEnable[0]);
           Serial.print("Wrote: ");
-            Serial.println(qdhcpEnable[0]);
+          Serial.println(qdhcpEnable[0]);
+
+
+          char buf[16];
+          char *digits;
+          int k;
+
+          String qIP = server.arg("IP");
+          qIP.toCharArray(buf,15);
+          digits = strtok(buf, ".");
+          k = 129;
+          while(digits != NULL ) {
+              Serial.println(atoi(digits));
+              EEPROM.write(k,atoi(digits));
+              k++;
+              digits = strtok(NULL, ".");
+           }
+
+          String qsubnet = server.arg("subnet");
+          qsubnet.toCharArray(buf,15);
+          digits = strtok(buf, ".");
+          k = 133;
+          while(digits != NULL ) {
+              Serial.println(atoi(digits));
+              EEPROM.write(k,atoi(digits));
+              k++;
+              digits = strtok(NULL, ".");
+           }
+
+
+
+//            for (int i = 0; i < qIP.length(); ++i)
+//            {
+//              EEPROM.write(129+i, qIP[i]);
+//              Serial.print("Wrote: ");
+//              Serial.println(qIP[i]);
+//            }
+
           EEPROM.commit();
           content = "{\"Success\":\"saved to eeprom... reset to boot into new wifi\"}";
           statusCode = 200;
@@ -442,29 +504,29 @@
   digitalWrite(SEARCH_LED, HIGH);
   digitalWrite(LED_BUILTIN, HIGH); //Turn off

-  char egIP[16] = "192.168.0.68";
-  char egsubnet[16] = "255.255.255.0";
+//  char egIP[16] = "192.168.0.68";
+//  char egsubnet[16] = "255.255.255.0";
   char eggateway[16] = "192.168.0.1";
   char egdns[16] = "8.8.8.8";
   char *digits;
-
-  digits = strtok(egIP, ".");
-  int k = 129;
-  while(digits != NULL ) {
-      Serial.println(atoi(digits));
-      EEPROM.write(k,atoi(digits));
-      k++;
-      digits = strtok(NULL, ".");
-   }
+  int k;
+//  digits = strtok(egIP, ".");
+//  int k = 129;
+//  while(digits != NULL ) {
+//      Serial.println(atoi(digits));
+//      EEPROM.write(k,atoi(digits));
+//      k++;
+//      digits = strtok(NULL, ".");
+//   }

-  digits = strtok(egsubnet, ".");
-  k = 133;
-  while(digits != NULL ) {
-      Serial.println(atoi(digits));
-      EEPROM.write(k,atoi(digits));
-      k++;
-      digits = strtok(NULL, ".");
-   }
+//  digits = strtok(egsubnet, ".");
+//  k = 133;
+//  while(digits != NULL ) {
+//      Serial.println(atoi(digits));
+//      EEPROM.write(k,atoi(digits));
+//      k++;
+//      digits = strtok(NULL, ".");
+//   }

   digits = strtok(eggateway, ".");
   k = 137;


sleep_time passe a 60s

sleep_time passe a 60s

--- teleInfo.ino
+++ teleInfo.ino
@@ -16,7 +16,7 @@
 #define BUFSIZE 15

 // durée entre 2 rafraichissements des données
-#define SLEEP_TIME (30 * 1000)
+#define SLEEP_TIME (60 * 1000)

 MySensor gw;


Update loopFunctions.ino

Update loopFunctions.ino

--- arduino/loopFunctions.ino
+++ arduino/loopFunctions.ino
@@ -16,6 +16,7 @@
 }

 ACT communicate(SENS sens, ACT temp) {
+  // Serial will come in the format: 'ACT,led:1,pan:120,tilt:43,lf:0,rf:0,lb:100,rb:110'
   if (Serial.available() > 0) {
     char inData[100]; // Allocate some space for the string
     char inChar; // Where to store the character read


スリープ時間の変更

スリープ時間の変更

--- 2_example/example13_ntp/example13_ntp.ino
+++ 2_example/example13_ntp/example13_ntp.ino
@@ -9,7 +9,7 @@
 #define PASS "password"                     // パスワード
 #define SENDTO "192.168.0.255"              // 送信先のIPアドレス
 #define PORT 1024                           // 送信のポート番号
-#define SLEEP_P 29*60*1000000               // スリープ時間 29分(uint32_t)
+#define SLEEP_P 59*60*1000000               // スリープ時間 59分(uint32_t)
 #define DEVICE "timer_1,"                   // デバイス名(5文字+"_"+番号+",")
 #define NTP_SERVER "ntp.nict.jp"            // NTPサーバのURL
 #define NTP_PORT 8888                       // NTP待ち受けポート


added initiator/replier id

added initiator/replier id

--- rf95_ping/rf95_ping.ino
+++ rf95_ping/rf95_ping.ino
@@ -12,9 +12,10 @@
 #include <RH_RF95.h>

 typedef struct {
-    char msg[5];    // ping or pong
-    int count;      // counter
-    int rssi;       // signal strength
+	char msg[5];    // ping or pong
+	int count;      // counter
+	int rssi;       // signal strength
+	int initiator, replier;
 } pingpong_t;

 // Singleton instance of the radio driver
@@ -22,70 +23,89 @@
 static pingpong_t ping;
 static pingpong_t pong;

-void setup()
-{
-    Serial.begin(9600);
-    Serial.println("Hello World from Server!");
-    if (!rf95.init())
-        Serial.println("init failed");
-    // Defaults after init are 434.0MHz, 13dBm, Bw = 125 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on
-    rf95.setFrequency(869.525);
-    rf95.setModemConfig(RH_RF95::Bw125Cr48Sf4096);
+void setup() {
+	Serial.begin(115200);
+	Serial.println(F("Hello World from Server!"));
+	if (!rf95.init())
+		Serial.println(F("init failed"));
+	// Defaults after init are 434.0MHz, 13dBm, Bw = 125 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on
+	rf95.setFrequency(869.525);
+	rf95.setModemConfig(RH_RF95::Bw125Cr48Sf4096);

-    // init ping
-    strcpy(ping.msg, "ping");
-    ping.count = 0;
-    ping.rssi = 0;
-
+	//    rf95.setTxPower(20);
+
+	// init ping
+	strcpy(ping.msg, "ping");
+	ping.count = 0;
+	ping.rssi = 0;
+	ping.initiator = 1; // FIXME CHANGE THIS TO SOMETHING UNIQUE
+	pong.replier = -1;
+
+	pong.initiator = -1;
+	pong.replier = ping.initiator;
 }
+
+static char line[128];
+static uint8_t buf[64];

 void loop()
 {
-    char line[32];
-    uint8_t buf[64];
+	// send a ping
+	ping.count++;

-    // send a ping
-    ping.count++;
-    strcpy(ping.msg, "ping");
-    sprintf(line, "Sending PING(%d,%d) ...", ping.count, ping.rssi);
-    Serial.println(line);
-    rf95.send((uint8_t *)&ping, sizeof(ping));
-    rf95.waitPacketSent();
+	sprintf(line, "Sending PING(%d,%d) ...", ping.count, ping.rssi);
+	Serial.println(line);

-    // wait some random time in reception mode
-    unsigned long wait = random(1000, 5000);
-    sprintf(line, "Listening for %d ms ...", wait);
-    Serial.println(line);
+	rf95.send((uint8_t *)&ping, sizeof(ping));
+	rf95.waitPacketSent();

-    unsigned long now = millis();
-    while ((millis() - now) < wait) {
-        uint8_t len;
-        if (rf95.available()) {
-            rf95.recv(buf, &len);
-            if (len == sizeof(pong)) {
-                memcpy(&pong, buf, sizeof(pong));
-                if (strcmp(pong.msg, "ping") == 0) {
-                    // got ping
-                    sprintf(line, "Recv PING(%d,%d)", pong.count, pong.rssi);
-                    Serial.println(line);
-                    // send pong
-                    strcpy(pong.msg, "pong");
-                    pong.rssi = rf95.lastRssi();
-                    sprintf(line, "Send PONG(%d,%d)", pong.count, pong.rssi);
-                    Serial.println(line);
-                    rf95.send((uint8_t *)&pong, sizeof(pong));
-                    rf95.waitPacketSent();
-                }
-                if (strcmp(pong.msg, "pong") == 0) {
-                    // got pong, print stats
-                    sprintf(line, "Got PONG(%d,%d)", pong.count, pong.rssi);
-                    Serial.println(line);
-                }
-            } else {
-                Serial.println("Got spurious message!");
-            }
-        }
-    }
+	// wait some random time in reception mode
+	unsigned long wait = random(1000, 5000);
+	sprintf(line, "Listening for %lu ms ...", wait);
+	Serial.println(line);
+
+	unsigned long now = millis();
+	while (millis() - now < wait) {
+		uint8_t len = sizeof(buf);
+
+		if (rf95.available()) {
+			rf95.recv(buf, &len);
+
+			if (len == sizeof(pong)) {
+				memcpy(&pong, buf, sizeof(pong));
+
+				if (strcmp(pong.msg, "ping") == 0) {
+					// got ping
+					sprintf(line, "Recv PING(%d,%d,%d)", pong.count, pong.rssi, pong.initiator);
+					Serial.println(line);
+					// send pong
+					strcpy(pong.msg, "pong");
+					pong.rssi = rf95.lastRssi();
+					pong.replier = ping.initiator;
+					sprintf(line, "Send PONG(%d,%d,%d)", pong.count, pong.rssi, pong.replier);
+					Serial.println(line);
+					rf95.send((uint8_t *)&pong, sizeof(pong));
+					rf95.waitPacketSent();
+				}
+				else if (strcmp(pong.msg, "pong") == 0) {
+					// got pong, print stats
+					sprintf(line, "Got PONG(%d,%d,%d)", pong.count, pong.rssi, pong.replier);
+					Serial.println(line);
+				}
+				else {
+					sprintf(line, "???(%d,%d,%d,%d,%s)", pong.count, pong.rssi, pong.initiator, pong.replier, pong.msg);
+					Serial.println(line);
+				}
+			} else {
+				Serial.print(F("Got spurious message: "));
+
+				for(uint8_t i=0; i<len; i++) {
+					Serial.print(buf[i], HEX);
+					Serial.print(' ');
+				}
+
+				Serial.println(F(""));
+			}
+		}
+	}
 }
-
-


Update no conditioning code to read from both even and odd pins

--- Arduino/v0.3.0_no_conditioning/v0.3.0_no_conditioning.ino
+++ Arduino/v0.3.0_no_conditioning/v0.3.0_no_conditioning.ino
@@ -12,7 +12,7 @@
   //Set D pins to input
   DDRD = 0x00;

-  Serial.begin(230400);
+  Serial.begin(2000000);
   //Serial.println("Starting...");

   setupClockSignals();
@@ -36,6 +36,7 @@
   ICR1 = 15;
   OCR1B = 7;
   OCR1A = 7;
+
 //   ICR1 = 45;
 //  OCR1B = 22;
 //  OCR1A = 22;
@@ -51,8 +52,8 @@

 ISR(TIMER1_COMPA_vect) {
   static byte currentByte = 0x00;
-  byte pinVal = PIND >> 7;
-  boolean byteReady = collectBit(pinVal, &currentByte);
+  byte pinVals = (PIND >> 6) & 0b00000011;
+  boolean byteReady = collectBits(pinVals, &currentByte);

 //  PORTD = 0b00000100;
 //  delayMicroseconds(1);
@@ -65,11 +66,13 @@
 }

 //@return true if byte is full/complete
-boolean collectBit(byte inputBit, byte *currentByte){
+boolean collectBits(byte inputBits, byte *currentByte){
   static int bitCounter = 0;
-  *currentByte |= inputBit << bitCounter;
+  *currentByte |= inputBits << bitCounter;
+  bitCounter += 2;
+
   //modulo is very slow, so we do a bitwise operation. Equivelant to % 8
-   bitCounter = (++bitCounter) & 0b00000111;
+  bitCounter = bitCounter & 0b00000111;

   if (bitCounter == 0) {
     return true;


v2.1

v2.1

Forgot to divide by ten for the first average

--- photon-files/powermonitor.ino
+++ photon-files/powermonitor.ino
@@ -37,7 +37,7 @@
             cnt2 = cnt2 + 1;
         }

-        RMScurrent = RMScurrent + pow((3.3*avgsamp/4095-Vmid)*20,2);//convert to a current, square it, and sum
+        RMScurrent = RMScurrent + pow((3.3*avgsamp/40950-Vmid)*20,2);//convert to a current, square it, and sum
     }

     RMScurrent = sqrt(RMScurrent/250);//root mean of 2500/10 = 250 averaged samples


Cleanup, interrupts, asm

Cleanup, interrupts, asm

Remove old crap.
Change FastLed functions to use asm.
Setup interrupts for button.


move json buf to local, discard as quickly as possible

--- src/neurite.ino
+++ src/neurite.ino
@@ -70,7 +70,6 @@
 static ESP8266WiFiMulti WiFiMulti;
 #endif
 static char cfg_buf[NEURITE_CFG_SIZE];
-StaticJsonBuffer<NEURITE_CFG_SIZE> json_buf;

 const char STR_READY[] PROGMEM = "neurite ready";

@@ -240,6 +239,7 @@

 static int cfg_load_sync(struct neurite_data_s *nd)
 {
+	StaticJsonBuffer<NEURITE_CFG_SIZE> json_buf;
 	log_dbg("in\n\r");
 	if (!cfg_load(nd)) {
 		log_err("load cfg failed\n\r");
@@ -275,6 +275,7 @@

 static bool cfg_save_sync(struct neurite_data_s *nd)
 {
+	StaticJsonBuffer<NEURITE_CFG_SIZE> json_buf;
 	JsonObject& json = json_buf.createObject();

 	cfg_run_dump(nd);
@@ -305,6 +306,7 @@
 		log_err("load cfg failed\n\r");
 		return false;
 	}
+	StaticJsonBuffer<NEURITE_CFG_SIZE> json_buf;
 	JsonObject& json = json_buf.parseObject(cfg_buf);
 	if (!json.success()) {
 		log_err("parse cfg failed\n\r");


Fixed coding styles by latest configurations

--- tests/TestStringRefs/TestStringRefs.ino
+++ tests/TestStringRefs/TestStringRefs.ino
@@ -11,8 +11,8 @@
 #include <RTest.h>
 #include <string.h>

-class BasicStringRef:
-public RAbstractStringRef
+class BasicStringRef :
+  public RAbstractStringRef
 {
 public:
   BasicStringRef(const char *str);
@@ -21,7 +21,7 @@
   unsigned int
   length(void) const
   {
-    return static_cast < unsigned int > (mLength);
+    return static_cast<unsigned int>(mLength);
   }

   char
@@ -53,14 +53,15 @@
 {
 }

-template < class DerivedType, class StringRefType >
-class BasicTestStringRef:
-public RTest
-{
-public:
-  typedef BasicTestStringRef < DerivedType, StringRefType > ThisType;
-
-  BasicTestStringRef(const __FlashStringHelper * str)
+template <class DerivedType, class StringRefType>
+class BasicTestStringRef :
+  public RTest
+{
+public:
+  typedef BasicTestStringRef<DerivedType, StringRefType> ThisType;
+
+  BasicTestStringRef(const __FlashStringHelper *str)
+
     : RTest(str)
     , mNormalString0("")
     , mNormalString1("a")
@@ -195,14 +196,14 @@
   DerivedType *
   getDerived()
   {
-    return static_cast < DerivedType * > (const_cast < ThisType * > (this));
+    return static_cast<DerivedType *>(const_cast<ThisType *>(this));
   }

   inline
   const DerivedType *
   getDerived() const
   {
-    return static_cast < DerivedType * > (const_cast < ThisType * > (this));
+    return static_cast<DerivedType *>(const_cast<ThisType *>(this));
   }

 public:
@@ -211,27 +212,27 @@
   const char *mNormalString2;
   const char *mNormalString3;
   const char *mNormalString4;
-
   const __FlashStringHelper *mFlashString0;
   const __FlashStringHelper *mFlashString1;
   const __FlashStringHelper *mFlashString2;
   const __FlashStringHelper *mFlashString3;
   const __FlashStringHelper *mFlashString4;
-
   String mString0;
   String mString1;
   String mString2;
   String mString3;
   String mString4;
 };
+
 class TestBasicStringRef
-: public BasicTestStringRef < TestBasicStringRef, BasicStringRef >
-{
-public:
-  typedef BasicStringRef                                           StringRefType;
-  typedef BasicTestStringRef < TestBasicStringRef, StringRefType > BaseType;
+  : public BasicTestStringRef<TestBasicStringRef, BasicStringRef>
+{
+public:
+  typedef BasicStringRef                                        StringRefType;
+  typedef BasicTestStringRef<TestBasicStringRef, StringRefType> BaseType;

   TestBasicStringRef()
+
     : BaseType(F("TestBasicStringRef"))
     , mStringRef0(mNormalString0)
     , mStringRef1(mNormalString1)
@@ -250,14 +251,15 @@
 }

 class TestConstStringRef
-: public BasicTestStringRef < TestConstStringRef, RConstStringRef >
+  : public BasicTestStringRef<TestConstStringRef, RConstStringRef>
 {
 public:
   typedef RConstStringRef
     StringRefType;
-  typedef BasicTestStringRef < TestConstStringRef, RConstStringRef > BaseType;
+  typedef BasicTestStringRef<TestConstStringRef, RConstStringRef> BaseType;

   TestConstStringRef()
+
     : BaseType(F("TestConstStringRef"))
     , mStringRef0(mNormalString0)
     , mStringRef1(mNormalString1)
@@ -276,13 +278,14 @@
 }

 class TestFlashStringRef
-: public BasicTestStringRef < TestFlashStringRef, RFlashStringRef >
-{
-public:
-  typedef RFlashStringRef                                          StringRefType;
-  typedef BasicTestStringRef < TestFlashStringRef, StringRefType > BaseType;
+  : public BasicTestStringRef<TestFlashStringRef, RFlashStringRef>
+{
+public:
+  typedef RFlashStringRef                                       StringRefType;
+  typedef BasicTestStringRef<TestFlashStringRef, StringRefType> BaseType;

   TestFlashStringRef()
+
     : BaseType(F("TestFlashStringRef"))
     , mStringRef0(mFlashString0)
     , mStringRef1(mFlashString1)
@@ -301,13 +304,14 @@
 }

 class TestStringRef
-: public BasicTestStringRef < TestStringRef, RStringRef >
-{
-public:
-  typedef RStringRef                                          StringRefType;
-  typedef BasicTestStringRef < TestStringRef, StringRefType > BaseType;
+  : public BasicTestStringRef<TestStringRef, RStringRef>
+{
+public:
+  typedef RStringRef                                       StringRefType;
+  typedef BasicTestStringRef<TestStringRef, StringRefType> BaseType;

   TestStringRef()
+
     : BaseType(F("TestStringRef"))
     , mStringRef0(&mString0)
     , mStringRef1(&mString1)


Added IP Address setting

Added IP Address setting

--- servduino/servduino.ino
+++ servduino/servduino.ino
@@ -1,17 +1,21 @@
+#include <Ethernet.h>
+#include <EthernetClient.h>
+#include <EthernetServer.h>
+
 #include <SPI.h>
-#include <Ethernet.h>

 char incomingByte = 0;
 char message[6];
 int index = 0;

 byte mac[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+byte ip[] = {192, 168, 0, 10}

 EthernetServer server(5001);

 void setup() {
   Serial.begin(9600);
-  Ethernet.begin(mac);
+  Ethernet.begin(mac, ip);
   server.begin();
 }


max 1023

max 1023

--- MotorTest/MotorTest.ino
+++ MotorTest/MotorTest.ino
@@ -11,11 +11,11 @@
 void loop() {

-  byte pwm = joystickMapValues( analogRead(PIN_THROTTLE), 0, 512, 1024, false );
+  byte pwm = joystickMapValues( analogRead(PIN_THROTTLE), 0, 512, 1023, false );
   analogWrite(PIN_MOTOR, pwm);

   //Serial.println(pwm);
-  //delay(250);
+  //delay(100);
 }

 int joystickMapValues(int val, int lower, int middle, int upper, bool reverse)


rework including noise calibration (untested)

--- noise_monitor/noise_monitor.ino
+++ noise_monitor/noise_monitor.ino
@@ -1,14 +1,15 @@
 #include "LoRa.h"

-// node info
-#define NODE_INFO "'info': 'ttn-zh-noise'"
-
-// version string
-#define VERSION "'version': 'v0.1'"
-
-// true: print debug info on serial
-// false: don't print debug info to serial
-#define PRINT_DEBUG false
+// LORA_ENABLE true: connect & send via lora
+// LORA_ENABLE false: switch lora communication off
+#define LORA_ENABLE true
+
+// PRINT_DEBUG true: print debug info on serial
+// PRINT_DEBUG false: don't print debug info to serial
+#define PRINT_DEBUG true
+
+// number of bytes for a lora message
+#define LORA_MESSAGE_SIZE 12

 // analog input noise pin
 #define PIN_NOISE A0
@@ -16,148 +17,310 @@
 // size of inner loop to get min max levels
 #define CNT_MAX 2000

-// number of loops to acuumulate noise sampling
-#define CNT_ACC 350
+// number of samples used to calibrate min and max
+#define CALIBRATION_SAMPLES 50
+
+// size of diff histo for calibration
+#define CALIBRATION_HISTO_SIZE 10
+
+#define LINE "--------------------------"
+
+// lora end-device address (DevAddr)
+// for ttn zurich, please use the address space 5A4801xx
+// you need to set the devaddr in file LoRa.cpp
+// use an individual address for each device when using the ttn prototype infrasructure
+// "mac set devaddr 0x5A48012E\r\n"
+
+// network key and application key are also set in file LoRa.cpp
+// "mac set nwkskey 2B7E151628AED2A6ABF7158809CF4F3C\r\n"
+// "mac set appskey 2B7E151628AED2A6ABF7158809CF4F3C\r\n"
+
+// number of seconds to accumulate until tranmitting data
+// transmissions start every 20 seconds. over time the interval between transmissions is increasing to 120 seconds
+static const float SAMPLE_INTERVAL[] = {20.0, 20.0, 20.0, 30.0, 30.0, 30.0, 30.0, 60.0, 60.0, 120.0};
+static const int SAMPLE_INTERVAL_MAX_INDEX = 9;
+
+// the lora lib
+LoRa LoraLib;

 // gobal vars for sound level
 int cnt, val_min, val_max, diff;

 // global vars for accumulated noise measures
-int acc_cnt, acc_sum, acc_max;
+int acc_max, acc_sum, acc_cnt, samples_cnt;
 long acc_start;

-// the lora lib
-LoRa LoraLib;
+// global vars for calibration
+int calibration_diff[CALIBRATION_SAMPLES];
+int calibration_histo[CALIBRATION_HISTO_SIZE];
+
+// minimum difference for noise reading (updated during calibration)
+int diff_min;
+
+// variable to check if node is in transmission mode
+boolean nodeIsTransmitting = false;
+boolean dataReadyToSend = false;
+
+// char buffer for lora payload data
+uint8_t loraData[] = "Hello, world!";

 void setup() {
   Serial.begin(9600);
   pinMode(13, OUTPUT);
+
+  if (PRINT_DEBUG) {
+    Serial.println(LINE);
+    Serial.println("Starting setup ...");
+  }

   initLora();
   initSensor();
-  resetSensorValues();
+  resetRawSensorValues();
   resetNoiseLevelValues();
+
+  if (PRINT_DEBUG) {
+    Serial.println(LINE);
+  }
 }

 void loop() {
-  // update noise level vars from sensor value
-  updateSensorValues(analogRead(PIN_NOISE));
-
-  // update/print current noise level
-  if(cnt == CNT_MAX) {
-    diff = smoothDiff(val_max - val_min);
-    printDiff(diff);
-    updateNoiseLevelValues(diff);
-    resetSensorValues();
-
-    // print/send noise data for last time window
-    if(acc_cnt == CNT_ACC) {
-      printNoiseLevel();
+    updateRawSensorValues(analogRead(PIN_NOISE));
+
+    // update/print current noise level
+    if (cnt == CNT_MAX) {
+      updateNoiseLevelCalibration();
+      diff = val_max - val_min < diff_min? 0: val_max - val_min - diff_min;
+      printDiff(diff, acc_cnt);
+      updateNoiseLevelValues(diff);
+      resetRawSensorValues();
+    }
+
+    if(sampleTime() >= SAMPLE_INTERVAL[samples_cnt]) {
       sendLora();
-      resetNoiseLevelValues();
-    }
-  }
+    }
 }

 // configure lora module
 void initLora() {
+  if (!LORA_ENABLE) {
+    if (PRINT_DEBUG) {
+      Serial.println("WARNING: LoRA disabled, not connecting");
+    }
+
+    return;
+  }
+
+  if (PRINT_DEBUG) {
+    Serial.println("Configuring LoRa module...");
+  }
+
   // serial to communicate with lora chip
   Serial1.begin(57600);
   delay(3000);
-
-  if(PRINT_DEBUG) {
-    Serial.println("--------------------------");
-    Serial.println("Configuring LoRa module...");
-  }

   LoraLib.LoRaConfig();

   if(PRINT_DEBUG) {
     Serial.println("LoRa module ready.");
-    Serial.println("--------------------------");
   }
 }

 void sendLora() {
-  LoraLib.LoRaSendAndReceive(getJson());
-}
-
-// assemble data package for lora
-String getJson() {
-  String s = String(NODE_INFO) + ", ";
-  s += String(VERSION) + ", ";
-  s += "'acc': '" + String(getNoiseLevelNormalized()) + "', ";
-  s += "'max': '" + String(acc_max) + "'";
-  return s;
-}
-
-// get normalizes accumulated noise
-double getNoiseLevelNormalized() {
-  return acc_sum / ((millis() - acc_start) / 1000.0);
-}
-
-// set reference to internal to increase sensitivity
+  printNoiseLevel();
+  prepareDataForTransmission();
+  resetNoiseLevelValues();
+
+  if (PRINT_DEBUG) {
+    Serial.println(LINE);
+    if (!LORA_ENABLE) {
+      Serial.println("WARNING: Not sending data any data, LoRA is disabled");
+    }
+  }
+
+  if (LORA_ENABLE && dataReadyToSend) {
+    if (PRINT_DEBUG) {
+      Serial.println("Sending data via LoRA");
+      Serial.println("aaaabbbbcccc (int values encoded in hex format: a=max, b=sum, c=cnt)");
+      Serial.println((char*)loraData);
+      Serial.println(LINE);
+    }
+
+    nodeIsTransmitting = true;
+    LoraLib.LoRaSendAndReceive((char*)loraData);
+    nodeIsTransmitting = false;
+  }
+
+  // update sample counting
+  samples_cnt++;
+
+  if (samples_cnt >= SAMPLE_INTERVAL_MAX_INDEX) {
+    samples_cnt = SAMPLE_INTERVAL_MAX_INDEX;
+  }
+
+}
+
+// encode acc_max, acc_sum, acc_cnt to loraData array in hex format
+// loraData then contains the 0 terminated string aaaabbbbcccc (int values encoded in hex format: a=max, b=sum, c=cnt)
+void prepareDataForTransmission() {
+  byte high, low;
+  high = highByte(acc_max);
+  low = lowByte(acc_max);
+  loraData[0] = highNibble(high);
+  loraData[1] = lowNibble(high);
+  loraData[2] = highNibble(low);
+  loraData[3] = lowNibble(low);
+
+  high = highByte(acc_sum);
+  low = lowByte(acc_sum);
+  loraData[4] = highNibble(high);
+  loraData[5] = lowNibble(high);
+  loraData[6] = highNibble(low);
+  loraData[7] = lowNibble(low);
+
+  high = highByte(acc_cnt);
+  low = lowByte(acc_cnt);
+  loraData[8] = highNibble(high);
+  loraData[9] = lowNibble(high);
+  loraData[10] = highNibble(low);
+  loraData[11] = lowNibble(low);
+
+  loraData[12] = 0;
+}
+
+byte highNibble(byte value) {
+  byte b = value >> 4;
+  return b > 9 ? b + 0x37 : b + 0x30;
+}
+
+byte lowNibble(byte value) {
+  byte b = value & 0xF;
+  return b > 9 ? b + 0x37 : b + 0x30;
+}
+
 void initSensor() {
+  // set reference to internal to increase sensor reading sensitivity
   analogReference(INTERNAL);
-}
-
-void resetSensorValues() {
+
+  // set pin for microphone
+  pinMode(PIN_NOISE, INPUT);
+
+  // init min noise reading differences
+  diff_min = 0;
+
+  // reset number of samples sent
+  samples_cnt = 0;
+}
+
+// reset variables for raw noise measurments
+void resetRawSensorValues() {
   cnt = 0;
   val_min = 2000;
   val_max = 0;
   diff = 0;
 }

+// reset variables for accumulated noise measurments
 void resetNoiseLevelValues() {
   acc_cnt = 0;
   acc_sum = 0;
   acc_max = 0;
 }

-void updateSensorValues(int val) {
-  if (val < val_min) { val_min = val; }
-  if (val > val_max) { val_max = val; }
-
+// update variables for raw noise measurments
+void updateRawSensorValues(int val) {
+  if (val < val_min) {
+    val_min = val;
+  }
+  if (val > val_max) {
+    val_max = val;
+  }
+
   cnt++;
 }

+// update calibration of noise level differences
+void updateNoiseLevelCalibration() {
+
+  // init calibration histo
+  if (acc_cnt == 0) {
+    for (int i = 0; i < CALIBRATION_HISTO_SIZE; i++) {
+      calibration_histo[i] = 0;
+    }
+  }
+
+  // collecting samples for calibration
+  if (acc_cnt < CALIBRATION_SAMPLES) {
+    calibration_diff[acc_cnt] = val_max - val_min;
+  }
+  // computing current calibration
+  else if (acc_cnt == CALIBRATION_SAMPLES) {
+    // update histogram for calibration
+    for (int i = 0; i < CALIBRATION_SAMPLES; i++) {
+      if (calibration_diff[i] < CALIBRATION_HISTO_SIZE) {
+        calibration_histo[calibration_diff[i]]++;
+      }
+    }
+
+    // reset diff_min
+    diff_min = 0;
+
+    // find best diff_min.
+    // assumpion: most frequent noise diff value represents silence
+    for (int i = 1; i < CALIBRATION_HISTO_SIZE; i++) {
+      if (calibration_histo[i] > calibration_histo[diff_min]) {
+        diff_min = i;
+      }
+    }
+
+    if (PRINT_DEBUG) {
+      Serial.println(LINE);
+      Serial.print("new calibration difference: ");
+      Serial.println(diff_min);
+      Serial.println(LINE);
+    }
+  }
+}
+
+// update variables for accumulated noise measurments
 void updateNoiseLevelValues(int d) {
-  if(acc_cnt == 0) {
+  if (acc_cnt == 0) {
     acc_start = millis();
   }
-
-  if (diff > acc_max) {
-    acc_max = d;
+
+  if (diff > acc_max) {
+    acc_max = d;
   }

   acc_sum += d;
   acc_cnt++;
-}
-
-// diff values of 2 and below don't seem to be meaningful
-int smoothDiff(int d) {
-  if(d >= 2) {
-    return d - 2;
-  }
-
-  if(d >= 1) {
-    return d - 1;
-  }
-
-  return d;
+
+  dataReadyToSend = true;
+}
+
+// returns the accumulated noise normalized by sampling time
+double getNoiseLevelNormalized() {
+  return acc_sum / sampleTime();
+}
+
+// returns the time (seconds) since sampling started
+double sampleTime() {
+  return (millis() - acc_start) / 1000.0;
 }

 // print current noise level
-void printDiff(int d) {
-  if(PRINT_DEBUG) {
-    Serial.print(getDiffString(d));
-    Serial.print(" ");
-    Serial.print(d);
-    Serial.print(" (min ");
-    Serial.print(val_min);
-    Serial.print(" max ");
-    Serial.print(val_max);
-    Serial.println(")");
+void printDiff(int d, int cnt) {
+  if (PRINT_DEBUG) {
+    Serial.print(getDiffString(d));
+    Serial.print(" ");
+    Serial.print(d);
+    Serial.print(" (min ");
+    Serial.print(val_min);
+    Serial.print(" max ");
+    Serial.print(val_max);
+    Serial.print(") cnt=");
+    Serial.print(cnt);
+    Serial.print(" time=");
+    Serial.println(sampleTime());
   }
 }

@@ -181,14 +344,17 @@
 // print accumulated noise info
 void printNoiseLevel() {
   if(PRINT_DEBUG) {
-    Serial.print("--- noise ");
+    Serial.println(LINE);
+    Serial.print("Noise ");
     Serial.print(getNoiseLevelNormalized());
-    Serial.print(" (sum ");
-    Serial.print(acc_sum);
-    Serial.print(" max ");
-    Serial.print(acc_max);
-    Serial.print(") json ");
-    Serial.println(getJson());
-  }
-}
-
+    Serial.print(" (max ");
+    Serial.print(acc_max);
+    Serial.print(" sum ");
+    Serial.print(acc_sum);
+    Serial.print(" cnt ");
+    Serial.print(acc_cnt);
+    Serial.print(")");
+    Serial.println();
+  }
+}
+


Update LED output after setting timeZone.

Instead of waiting for the update.

--- webserver.ino
+++ webserver.ino
@@ -165,6 +165,7 @@
         return;
       }
       timeZone = newTimeZone;
+      updateChannels();
     }
     webServer.send( 200, "text/plain", "Timezone is " + String( timeZone ) );
   });


Buffer Log

Buffer Log

--- sonarMain/sonarMain.ino
+++ sonarMain/sonarMain.ino
@@ -7,6 +7,8 @@
 //Comment out to disable serial debugging
 #define debugOn

+#define BUFFER_LENGTH 64
+
 // Sonar ISR
 #include "sonarInterupt.h"
 void SetupSonar(void);
@@ -14,6 +16,8 @@

 // I2C Response Buffer
 char i2c_buff[32] = {0};
+int i2c_buffer_ready = 0;
+int i2c_buffer_len = 0;

 int main(void){
 	//Start Serial Communication if Debugging Mode is activated
@@ -78,7 +82,16 @@
 }

 void I2C_Request(){
-	Wire.write(i2c_buff);
+	if(i2c_buffer_ready >= 0 && i2c_buffer_ready < i2c_buffer_len){
+		// Write next char
+		Wire.write(i2c_buff[i2c_buffer_ready]);
+		Serial.print(i2c_buff[i2c_buffer_ready]);
+		Serial.print("\n");
+		i2c_buffer_ready++;
+	} else if (i2c_buffer_ready >= i2c_buffer_len){
+		// Reset Counter
+		i2c_buffer_ready = -1;
+	}
 	return;
 }

@@ -93,6 +106,7 @@
 	}

 	// Parse Request
+	i2c_buffer_ready = -1; // Mark Arduino as busy
 	if(buff[0] == 's' && numBytes >= 2){
 		// Read sonar id
 		int sonar;
@@ -108,5 +122,8 @@
 		// Write back error
 		sprintf(i2c_buff, "ERROR\n", SonarReading[0]);
 	}
+	i2c_buffer_ready = 0; // Mark Arduino as ready
+	i2c_buffer_len = strlen(i2c_buff);
+
 	return;
 }


change display test wait logic

change display test wait logic

Tidy up logic for showing display test.

--- src/monitor-firmware.ino
+++ src/monitor-firmware.ino
@@ -14,9 +14,10 @@
 // Status bits
 byte status_bits;

-// Showing display test
-byte showing_dt;
-const int DPY_TST_DURATION = 1000; // milliseconds
+// Showing display test and time at which test started
+bool showing_dt;
+unsigned long dt_shown_at;
+const int DPY_TST_DURATION = 500; // milliseconds

 // Is processor stopped?
 bool halted;
@@ -73,19 +74,19 @@
     digitalWrite(MISO, LOW);
     digitalWrite(DLOAD, LOW);

+    // Set up MX7219 with display test on
+    setupMX7219();
+    setMX7219Reg(MX7219_SCN_LIMIT, 0x06);   // Scan digits 0-6
+    setMX7219Reg(MX7219_DPLY_TEST, 0x01);   // Enable display test
+    showing_dt = true; dt_shown_at = millis();
+
     // Initial address/data bus values
     address_bus = data_bus = 0;

     // Initially all status bits are off
     status_bits = 0;

-    // Set up MX7219
-    setupMX7219();
-    setMX7219Reg(MX7219_SCN_LIMIT, 0x06);   // Scan digits 0-6
-
-    // Display test
-    showing_dt = 1;
-
+    // Processor is in running state
     halted = false;

     next_demo_loop_at = millis() + DEMO_LOOP_PERIOD;
@@ -94,8 +95,8 @@

 void loop() {
     // Display test off after DPY_TST_DURATION milliseconds
-    if(showing_dt && (millis() > DPY_TST_DURATION)) {
-        showing_dt = 1;
+    if(showing_dt && (millis() - dt_shown_at > DPY_TST_DURATION)) {
+        showing_dt = false;
         setMX7219Reg(MX7219_DPLY_TEST, 0x00);
     }


Structs plus Arduino equals not fun. Included times three for mechanical to digital rotations.

--- src/pong_launcher/arduino_code/launcher_arduino/launcher_arduino.ino
+++ src/pong_launcher/arduino_code/launcher_arduino/launcher_arduino.ino
@@ -31,6 +31,8 @@

 #include <PID_v1.h>

+//#include "motor_struct.h"
+

 //Pin definitions
@@ -60,6 +62,27 @@
 int C1bot = A1;
 int C2bot = A2;
 int C3bot = A3;
+
+//struct Motor_Struct {
+//  int top1;
+//  int top2;
+//  int top3;
+//  int bot1;
+//  int bot2;
+//  int bot3;
+//
+//  int h1;
+//  int h2;
+//  int h3;
+//
+//  volatile double curSpeed;
+//
+//  volatile int timeold;
+//
+//  volatile int hall1, hall2, hall3;
+//
+//  double pid_setpoint, pid_input, pid_output;
+//};

 //Hall effect sensors
 int ha1 = 2;
@@ -434,7 +457,9 @@
 	hallA2 = digitalRead(ha2);
 	hallA3 = digitalRead(ha3);
 	time = millis();
-	curSpeedA = 1/(3 * (time - timeoldA));
+	curSpeedA = 1/(3 * (time - timeoldA)); // just remove the 3
+        // 3 digital rotations per single mechanical rotation
+        curSpeedA *= 3;
 	timeoldA = time;
 	oldSpeedA = curSpeedA;

@@ -457,7 +482,9 @@
 	hallB3 = digitalRead(hb3);

 	time = millis();
-	curSpeedB = 1/(3 * (time - timeoldB));
+	curSpeedB = 1/(3 * (time - timeoldB)); // just remove the 3
+        // 3 digital rotations per single mechanical rotation
+        curSpeedB *= 3;
 	timeoldB = time;
 	oldSpeedB = curSpeedB;

@@ -478,7 +505,9 @@
 	hallC3 = digitalRead(hc3);

 	time = millis();
-	curSpeedC = 1/(3 * (time - timeoldC));
+	curSpeedC = 1/(3 * (time - timeoldC)); // just remove the 3
+        // 3 digital rotations per single mechanical rotation
+        curSpeedC *= 3;
 	timeoldC = time;
 	oldSpeedC = curSpeedC;


#define to const char*

#define to const char*

--- examples/UbidotsGetValue/UbidotsGetValue.ino
+++ examples/UbidotsGetValue/UbidotsGetValue.ino
@@ -10,12 +10,12 @@
  * Define Constants
  ****************************************/
 // Your GPRS credentials, if any
-#define APN             "Put_the_APN_here"
-#define USER            "Put_the_APN_user_here"
-#define PASS            "Put_the_APN_pwd_here"
-#define TOKEN           "Put_your_Ubidots_token_here"
-#define DEVICE_LABEL    "Put_your_device_API_label"
-#define VARIABLE_LABEL  "Put_your_variable_API_label"
+const char *APN  =           "Put_the_APN_here"
+const char *USER =           "Put_the_APN_user_here"
+const char *PASS =           "Put_the_APN_pwd_here"
+const char *TOKEN=           "Put_your_Ubidots_token_here"
+const char *DEVICE_LABEL=    "Put_your_device_API_label"
+const char *VARIABLE_LABEL= "Put_your_variable_API_label"

 Ubidots client(TOKEN,APN,USER,PASS);


Fixes problem that can not get IR code

Fixes problem that can not get IR code

--- minirum/minirum.ino
+++ minirum/minirum.ino
@@ -11,6 +11,8 @@

 #define SEND_PIN 12
 #define RECV_PIN 14
+#define TIMEOUT MAX_TIMEOUT_MS
+#define CAPTURE_BUFFER_SIZE 1024

 char* localName = "minirum-";
 String ssid = "";
@@ -24,7 +26,7 @@

 ESP8266WebServer webServer(80);
 IRsend irsend(SEND_PIN);
-IRrecv irrecv(RECV_PIN);
+IRrecv irrecv(RECV_PIN, CAPTURE_BUFFER_SIZE, TIMEOUT, true);

 String dumpIRcode (decode_results *results) {
   String s = "";


simpler clientId

simpler clientId

--- examples/microblu_eth/microblu_eth.ino
+++ examples/microblu_eth/microblu_eth.ino
@@ -735,10 +735,8 @@
     //oops we're not connected yet or we lost connection
     Serial.println(F("connecting..."));

-    String clientIdStr = "microblu_" + String(random(500000)) + "_" + String(random(500000));
-    int clientId_len = clientIdStr.length() + 1;
-    char clientId[clientId_len];
-    clientIdStr.toCharArray(clientId, clientId_len);
+    char clientId[40] = "mb_";
+    strcat(clientId, UUID);

     if (microblu.connect(clientId, UUID, TOKEN)){


id added to pingprobe's rply

id added to pingprobe's rply

--- deploy-dist/rootfolder/sketches/ArdulinkProtocol/ArdulinkProtocol.ino
+++ deploy-dist/rootfolder/sketches/ArdulinkProtocol/ArdulinkProtocol.ino
@@ -38,6 +38,7 @@
   Serial.begin(115200);

   Serial.print("alp://rply/");
+  Serial.print("ok?id=0");
   Serial.print('\n'); // End of Message
   Serial.flush();


Fix moving too slow for wide lenses

Fix moving too slow for wide lenses

I don't know what I was thinking about with that /10.

--- pano-controller.ino
+++ pano-controller.ino
@@ -213,7 +213,7 @@
         if (HID::isEventOk(event) || HID::isEventCancel(event)) break;

         pos_x = joystick.getPositionX();
-        horiz_rpm = DYNAMIC_HORIZ_RPM(camera.getHorizFOV()/10);
+        horiz_rpm = DYNAMIC_HORIZ_RPM(camera.getHorizFOV());
         if (pos_x == 0){
             if (HID::isEventRight(event)) pos_x = 1;
             if (HID::isEventLeft(event)) pos_x = -1;
@@ -228,7 +228,7 @@
         }

         pos_y = joystick.getPositionY();
-        vert_rpm = DYNAMIC_VERT_RPM(camera.getVertFOV()/10);
+        vert_rpm = DYNAMIC_VERT_RPM(camera.getVertFOV());
         if (pos_y == 0){
             if (HID::isEventUp(event)) pos_y = 1;
             if (HID::isEventDown(event)) pos_y = -1;


Minor change to CS/US duration names

Minor change to CS/US duration names

Also started working on adding laser pulses to conditioning trials.

--- Arduino/private/ledpuff/ledpuff.ino
+++ Arduino/private/ledpuff/ledpuff.ino
@@ -9,6 +9,7 @@
 int led = 9;
 int whisker = 10;
 int tonech = 11;
+int laser = 12;
 int puff = 13;

 // Used internally to select channels for CS/US
@@ -18,13 +19,17 @@
 // Task variables (time in ms, freq in hz)
 int campretime = 200;
 int camposttime = 800;
-int cs = 500;
+int csdur = 500;
 int csch = 1;   // default to LED
 int usch = 3;   // default to ipsi corneal puff
 int ISI = 200;
-int us = 20;
+int usdur = 20;
 int residual;
 int tonefreq5 = 10000;
+
+// Added as temporary fix to allow laser stim during trial
+int laserdelay = 0; // delay from CS onset until laser onset
+int laserdur = 0; // duration of laser pulse

 unsigned long trialtime = 0; // For keeping track of elapsed time during trial

@@ -37,6 +42,7 @@
   pinMode(whisker, OUTPUT);
   pinMode(tonech, OUTPUT);
   pinMode(greenled, OUTPUT);
+  pinMode(laser, OUTPUT);

   // Default all output pins to LOW - for some reason they were floating high on the Due before I (Shane) added this
   digitalWrite(camera, LOW);
@@ -45,6 +51,7 @@
   digitalWrite(whisker, LOW);
   digitalWrite(tonech, LOW);
   digitalWrite(greenled, LOW);
+  digitalWrite(laser, LOW);

   Serial.begin(9600);
 }
@@ -88,10 +95,10 @@
         csch = value;
         break;
       case 5:
-        cs = value;
+        csdur = value;
         break;
       case 6:
-        us = value;
+        usdur = value;
         break;
       case 7:
         ISI = value;
@@ -104,6 +111,12 @@
         break;
       case 10:
         usch = value;
+        break;
+      case 11:
+        laserdelay = value;
+        break;
+      case 12:
+        laserdur = value;
         break;
     }
     delay(4); // Delay enough to allow next 3 bytes into buffer (24 bits/9600 bps = 2.5 ms, so double it for safety).
@@ -129,7 +142,7 @@
   // starting a trial
   trialtime = millis();

-  if (cs <= ISI) {
+  if (csdur <= ISI) {
     doTrace();
   }
   else { doDelay(); }
@@ -152,6 +165,10 @@
 */

 void doDelay() {
+
+  if laserdur > 0 {
+    doDelayWithLaser();
+  }

   csON();

@@ -159,20 +176,20 @@

   usON();

-  if (cs < (ISI+us)) {
-   delay(cs-ISI);
+  if (csdur < (ISI+usdur)) {
+   delay(csdur-ISI);
    csOFF();
-   residual = us - (cs-ISI);
+   residual = usdur - (csdur-ISI);
   }
   else {
-    residual = us;
+    residual = usdur;
   }

   delay(residual);                  // wait for remainder of us (or all if cs is longer)

   usOFF();

-  residual = cs - ISI - us;
+  residual = csdur - ISI - usdur;
   if (residual > 0) {
     delay(residual);          // wait for whatever additional time cs is on
   }
@@ -185,24 +202,60 @@

   csON();

-  delay(cs);
+  delay(csdur);

   csOFF();

-  residual = ISI-cs;
+  residual = ISI-csdur;

   if (residual > 0) {
     delay(residual);    // residual is trace period
   }

   usON();
-  delay(us);                  // wait for us
+  delay(usdur);                  // wait for us
   usOFF();

 }

+void doDelayWithLaser() {
+  csON();
+
+  // We have to figure out what the order of state transitions should be
+  // This seems better implemented as a DAG (directed acyclic graph), where
+  // each node is a state transition and the edges are delays.
+  // Can we do this relatively easily in Arduino? We first need to sort based on
+  // delays from trial onset, then make a priority queue for each state transition and
+  // it's associated residual delay.
+
+  delay(ISI);
+
+  usON();
+
+  if (csdur < (ISI+usdur)) {
+   delay(csdur-ISI);
+   csOFF();
+   residual = usdur - (csdur-ISI);
+  }
+  else {
+    residual = usdur;
+  }
+
+  delay(residual);                  // wait for remainder of us (or all if cs is longer)
+
+  usOFF();
+
+  residual = csdur - ISI - usdur;
+  if (residual > 0) {
+    delay(residual);          // wait for whatever additional time cs is on
+  }
+
+  csOFF();
+
+}
+
 void csON() {
- if (cs > 0) {
+ if (csdur > 0) {
     switch (csch) {
       case 1:
         digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
@@ -211,10 +264,10 @@
         digitalWrite(whisker, HIGH);   // turn the LED on (HIGH is the voltage level)
         break;
       case 5:
-        tone(tonech, tonefreq5, cs);
+        tone(tonech, tonefreq5, csdur);
         break;
       case 6:
-        tone(tonech, tonefreq5, cs);
+        tone(tonech, tonefreq5, csdur);
         break;
       case  7:
         digitalWrite(greenled, HIGH); // turn the green LED on (HIGH is the voltage level)
@@ -225,7 +278,7 @@

 void csOFF() {
-     if (cs > 0) {
+     if (csdur > 0) {
     switch (csch) {
       case 1:
         digitalWrite(led, LOW);   // turn the LED on (HIGH is the voltage level)


Whitespace

Whitespace

--- walk.ino
+++ walk.ino
@@ -9,7 +9,7 @@
 void setup()
 {
   Serial.begin(1000000); // JCB
-  GD.begin();
+  GD.begin();
   LOAD_ASSETS();  //' }load
   for (int i = 0; i < 256; i++)
     a[i] = GD.random(512);


Oops... forgot to commit the changes concerning the not-so-dynamic number of frames and overlays...

--- code/oakpowerboard/oakpowerboard.ino
+++ code/oakpowerboard/oakpowerboard.ino
@@ -60,10 +60,10 @@
   ui.setFrameAnimation(SLIDE_LEFT);

   // Add frames
-  ui.setFrames(frames, frameCount);
+  ui.setFrames(frames, 2);

   // Add overlays
-  ui.setOverlays(overlays, overlaysCount);
+  ui.setOverlays(overlays, 1);

   // Inital UI takes care of initalising the display too.
   ui.init();


still working version

still working version

--- Margoulineur2000.ino
+++ Margoulineur2000.ino
@@ -153,21 +153,25 @@
     switch (relativePosition)
     {
       case 0:
-        nfc_read(3);
+        lcd.clear();
+        nfc_read(3, false);
         break;
       case 1:
         lcd.clear();
         nfc_write();
         break;
       case 2:
-      break;
+        lcd.clear();
+        nfc_read(4, false);
+        break;
       case 3:
-      break;
+        lcd.clear();
+        break;
     }
    }
 }

-int encoderWrite(byte dormitory)
+int encoderWrite()
 {
   int newPosition;
   myEnc.write(0);
@@ -216,7 +220,7 @@
   uint8_t data[16]; // = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};                         // Array to store block data during reads
 /**/

-  int newBalance = encoderWrite(3) * 100;
+  int newBalance = encoderWrite() * 100;
   Serial.print("New value = ");Serial.println(newBalance);
   uint8_t balance[] = {0, 0};
   balance[0] = newBalance / 256;
@@ -369,7 +373,7 @@
   Serial.flush();
 }

-void                nfc_read(byte dormitory)
+void                nfc_read(byte dormitory, bool mode)
 {
   t_nfc_handler     nfc_handler;

@@ -414,7 +418,7 @@
         {
           // Starting of a new sector ... try to to authenticate
           Serial.print("------------------------Sector ");Serial.print(nfc_handler.currentblock/4, DEC);Serial.println("-------------------------");
-           Serial.print("keys used:");
+            Serial.print("keys used:");

           if (nfc_handler.currentblock >= 5 * 4 && nfc_handler.currentblock <= 6 * 4)
           {
@@ -455,9 +459,7 @@
           }
           Serial.println("");
           if (nfc_handler.success)
-          {
             nfc_handler.authenticated = true;
-          }
           else
           {
             Serial.println("Authentication error");
@@ -479,14 +481,7 @@
           {
             // Read successful
             Serial.print("Block ");Serial.print(nfc_handler.currentblock, DEC);
-            if (nfc_handler.currentblock < 10)
-            {
-              Serial.print("  ");
-            }
-            else
-            {
-              Serial.print(" ");
-            }
+            Serial.print(" ");
             // Dump the raw data
             nfc.PrintHexChar(nfc_handler.data, 16);

@@ -506,9 +501,7 @@
       }
     }
     else
-    {
       Serial.println("Ooops ... this doesn't seem to be a Mifare Classic card!");
-    }
   }
   lcd.clear();
   lcd.print("Balance :");


Add white space

Add white space

--- RouterReset_Yun/RouterReset_Yun.ino
+++ RouterReset_Yun/RouterReset_Yun.ino
@@ -73,14 +73,18 @@

 void resetRouter() {
   if(digitalRead(switchPin) == HIGH) {
+
     digitalWrite(routerPin1, LOW);
     digitalWrite(routerPin2, LOW);
+
     for(int i=0; i<resetRouterTimeSec; i++) {
       if(digitalRead(switchPin) == LOW) break;
       delay(1000);
     }
+
     digitalWrite(routerPin1, HIGH);
     digitalWrite(routerPin2, HIGH);
+
     delay(resetRouterTimeSec*1000);
   }
 }


mixed up max/min

mixed up max/min

--- shofanduino2/shofanduino2.ino
+++ shofanduino2/shofanduino2.ino
@@ -112,7 +112,7 @@
   getValues();
   env_min = humidity;
   env_max = humidity + min_humidity_diff;
-  env_max = max(env_max, max_humidity);
+  env_max = min(env_max, max_humidity);

   // calculate decay
   float t = milliseconds_sleep / 1000.0f;


using rtc mem to preserve rev count

using rtc mem to preserve rev count

--- _06-power_meter/_06-power_meter.ino
+++ _06-power_meter/_06-power_meter.ino
@@ -9,14 +9,26 @@
 #include "EmonLib.h" // Include Emon Library
 #include <Average.h>

+extern "C" {
+#include "user_interface.h"
+}
+
 #define _IS_MY_HOME
 // WIFI
 #ifdef _IS_MY_HOME
-//#include "/usr/local/src/ap_settingii.h"
 #include "/usr/local/src/ap_setting.h"
 #else
 #include "ap_setting.h"
 #endif
+
+#define RTC_MAGIC 12345678
+
+typedef struct _tagPoint {
+  uint32 magic;
+  uint32 salt;
+} RTC_REVCOUNT;
+
+RTC_REVCOUNT rtc_mem_revcount;

 #define DEBUG_PRINT 0

@@ -94,6 +106,26 @@

 long lastReconnectAttempt = 0;
 long calcIrmsmillis = 0;
+
+void rtc_check()
+{
+  // system_rtc_mem_read(64... not work, use > 64
+  system_rtc_mem_read(100, &rtc_mem_revcount, sizeof(rtc_mem_revcount));
+  if (DEBUG_PRINT) {
+    Serial.print("=================> rtc mem mgic / salt :  ");
+    Serial.print(rtc_mem_revcount.magic);
+    Serial.print(" / ");
+    Serial.println(rtc_mem_revcount.salt);
+  }
+
+  if (rtc_mem_revcount.magic != RTC_MAGIC) {
+    if (DEBUG_PRINT) {
+      Serial.println("===============> rtc mem init...");
+    }
+    rtc_mem_revcount.magic = RTC_MAGIC;
+    rtc_mem_revcount.salt = 5255;
+  }
+}

 void wifi_connect() {
   // WIFI
@@ -191,6 +223,9 @@
     Serial.begin(115200);
   }
   delay(20);
+
+  rtc_check();
+
   if (DEBUG_PRINT) {
     Serial.println("power meter test!");

@@ -215,7 +250,7 @@
   clientName += String(micros() & 0xff, 16);

   lastReconnectAttempt = 0;
-  revCounts = 0 ;
+  revCounts = rtc_mem_revcount.salt ;

   getResetInfo = "hello from ESP8266 s07 ";
   getResetInfo += ESP.getResetInfo().substring(0, 30);
@@ -315,44 +350,44 @@
       }

       if ( revMills > 600 ) {
-      revValue = (float(( 3600  * 1000 ) / ( 600 * float(revMills) ) ) * 1000);
+        revValue = (float(( 3600  * 1000 ) / ( 600 * float(revMills) ) ) * 1000);
       }

       if ( oldrevValue == 0 ) {
-      oldrevValue = revValue;
-    }
-
-    if ( oldrevMills == 0 ) {
-      oldrevMills = revMills;
-    }
-
-    payload = "{\"VIrms\":";
-              payload += average;
-              payload += ",\"revValue\":";
-              payload += revValue;
-              payload += ",\"revMills\":";
-              payload += revMills;
-              payload += ",\"powerAvg\":";
-              payload += (( average + revValue ) / 2) ;
-              payload += ",\"Stddev\":";
-              payload += ave.stddev();
-              payload += ",\"calcIrmsmillis\":";
-              payload += calcIrmsmillis;
-              payload += ",\"revCounts\":";
-              payload += revCounts;
-              payload += ",\"FreeHeap\":";
-              payload += ESP.getFreeHeap();
-              payload += ",\"RSSI\":";
-              payload += WiFi.RSSI();
-              payload += ",\"millis\":";
-              payload += (millis() - timemillis);
-              payload += "}";
-
-    if ( doorStatus != olddoorStatus ) {
-
-      doorpayload = "{\"DOOR\":";
-
-      if ( doorStatus == 0 ) {
+        oldrevValue = revValue;
+      }
+
+      if ( oldrevMills == 0 ) {
+        oldrevMills = revMills;
+      }
+
+      payload = "{\"VIrms\":";
+      payload += average;
+      payload += ",\"revValue\":";
+      payload += revValue;
+      payload += ",\"revMills\":";
+      payload += revMills;
+      payload += ",\"powerAvg\":";
+      payload += (( average + revValue ) / 2) ;
+      payload += ",\"Stddev\":";
+      payload += ave.stddev();
+      payload += ",\"calcIrmsmillis\":";
+      payload += calcIrmsmillis;
+      payload += ",\"revCounts\":";
+      payload += revCounts;
+      payload += ",\"FreeHeap\":";
+      payload += ESP.getFreeHeap();
+      payload += ",\"RSSI\":";
+      payload += WiFi.RSSI();
+      payload += ",\"millis\":";
+      payload += (millis() - timemillis);
+      payload += "}";
+
+      if ( doorStatus != olddoorStatus ) {
+
+        doorpayload = "{\"DOOR\":";
+
+        if ( doorStatus == 0 ) {
           doorpayload += "\"CLOSED\"";
         }
         else {
@@ -365,12 +400,22 @@
       }

       if (((millis() - sentMills) > REPORT_INTERVAL ) && ( irStatus == oldirStatus )) {
-      sendmqttMsg(topic, payload);
+        sendmqttMsg(topic, payload);
         sentMills = millis();
       }

       if ( irStatus != oldirStatus ) {
-      sendmqttMsg(topic, payload);
+        rtc_mem_revcount.salt = revCounts;
+        if (system_rtc_mem_write(100, &rtc_mem_revcount, sizeof(rtc_mem_revcount))) {
+          if (DEBUG_PRINT) {
+            Serial.println("rtc mem write is ok");
+          }
+        } else {
+          if (DEBUG_PRINT) {
+            Serial.println("rtc mem write is fail");
+          }
+        }
+        sendmqttMsg(topic, payload);
         sentMills = millis();
         oldirStatus = irStatus ;
         oldrevValue = revValue ;


Make setup tolerant to errors

Make setup tolerant to errors

--- payload/payload.ino
+++ payload/payload.ino
@@ -32,12 +32,11 @@
 // For more info, see "setupable.h".
 //custom::Setupable* setupables[] = {  };

-// Setup the object. Trap the thread if no card is found.
+// Setup the object. Swallow any errors.
 template <typename T> void setup_general(T obj, char* error_message, char* success_message) {
   if (!obj.begin()) {
     Serial.println(error_message);
-    Serial.println("PROGRAM WILL NOT PROCEED.");
-    while (1) { /* Trap the thread. */ }
+    // Swallow the error; fault tolerance is required.
   }
   Serial.println(success_message);
   Serial.println();


Delete ESP8266_Shield_SwSerial.ino

Delete ESP8266_Shield_SwSerial.ino

--- examples/BoardsAndShields/ESP8266_Shield_SwSerial/ESP8266_Shield_SwSerial.ino
+++ examples/BoardsAndShields/ESP8266_Shield_SwSerial/ESP8266_Shield_SwSerial.ino
@@ -1,62 +0,0 @@
-/**************************************************************
- * Blynk is a platform with iOS and Android apps to control
- * Arduino, Raspberry Pi and the likes over the Internet.
- * You can easily build graphic interfaces for all your
- * projects by simply dragging and dropping widgets.
- *
- *   Downloads, docs, tutorials: http://www.blynk.cc
- *   Blynk community:            http://community.blynk.cc
- *   Social networks:            http://www.fb.com/blynkapp
- *                               http://twitter.com/blynk_app
- *
- * Blynk library is licensed under MIT license
- * This example code is in public domain.
- *
- **************************************************************
- *
- * This example shows how to use ESP8266 Shield via SoftwareSerial
- * (on UNO, Nano, Mini...) to connect your project to Blynk.
- *
- * For this example you need a modified ITEAD WeeESP8266 library:
- *   https://github.com/vshymanskyy/ITEADLIB_Arduino_WeeESP8266
- *
- * Please adjust the settings in the ESP8266.h:
- *   Set ESP8266_USE_SOFTWARE_SERIAL, if needed
- *   Set USER_SEL_VERSION to the version of your module
- *
- * Note: Ensure a stable serial connection to ESP8266!
- *       Hardware serial is preferred.
- *
- * Change WiFi ssid, pass, and Blynk auth token to run :)
- * Feel free to apply it to any other example. It's simple!
- *
- **************************************************************/
-//#define BLYNK_DEBUG
-#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
-#include <ESP8266.h>
-#include <BlynkSimpleShieldEsp8266.h>
-
-#include <SoftwareSerial.h>
-SoftwareSerial SwSerial(2, 3); // RX, TX
-ESP8266 wifi(SwSerial);
-
-// You should get Auth Token in the Blynk App.
-// Go to the Project Settings (nut icon).
-char auth[] = "YourAuthToken";
-
-void setup()
-{
-  Serial.begin(9600);   // Set console baud rate
-  while (!Serial) {}
-
-  SwSerial.begin(9600);  // Set ESP8266 baud rate
-  while (!SwSerial) {}
-
-  Blynk.begin(auth, wifi, "ssid", "pass");
-}
-
-void loop()
-{
-  Blynk.run();
-}
-


TW-50: simple background that eventually support color change and clean up.

--- tinywatch.ino
+++ tinywatch.ino
@@ -5,19 +5,23 @@
 #include "lib_RenderBuffer.h"
 #include "lib_StringBuffer.h"

-//Determines which version of TinyScreen we are using.
-TinyScreen display = TinyScreen(TinyScreenPlus);
-//Buffer used for drawing.
-RenderBuffer<uint16_t,20> buffer;
-char isTimeSet = 0;
-//Temp sleep
-char isSleep = 0;
-
-
 //Pinouts for TinyShield BLE.
 #define BLE_REQ 10
 #define BLE_RDY 2
 #define BLE_RST 9
+
+const int SCREEN_WIDTH = 48;
+
+//Determines which version of TinyScreen we are using.
+TinyScreen display = TinyScreen(TinyScreenPlus);
+//Buffer used for drawing.
+RenderBuffer<uint16_t, 20> buffer;
+int rBackground = 0;
+int gBackground = 0;
+int bBackground = 0;
+char isTimeSet = 0;
+//Temp sleep
+char isSleep = 0;

 //Instantiate BLE peripheral.
 BLEPeripheral blePeripheral = BLEPeripheral(BLE_REQ, BLE_RDY, BLE_RST);
@@ -33,11 +37,11 @@
   display.setFlip(true);
   display.setBrightness(10);
   display.setBitDepth(buffer.is16bit());
-
+
   bleSetup();
 }

-void bleSetup(){
+void bleSetup() {
   //Name of BLE peripheral when connecting to master.
   blePeripheral.setLocalName("tinywatch");
   blePeripheral.setAppearance(0xC0);
@@ -51,9 +55,9 @@
   //Bind events for connects and disconnects.
   blePeripheral.setEventHandler(BLEConnected, blePeripheralConnectHandler);
   blePeripheral.setEventHandler(BLEDisconnected, blePeripheralDisconnectHandler);
-
+
   timeCharacteristic.setEventHandler(BLEWritten, setTimeHandler);
-
+
   //Start BLE service.
   blePeripheral.begin();
 }
@@ -61,21 +65,23 @@
 void loop() {
   blePeripheral.poll();
   BLECentral central = blePeripheral.central();
-
-  if(isTimeSet){
+
+  if (isTimeSet) {
     renderBackground();
     renderTime();
     renderDate();
-  } else if(!central || !central.connected()){
-    buffer.drawText("Searching...",15,8,buffer.rgb(255,255,255), &liberationSans_8ptFontInfo);
+  } else if (!central || !central.connected()) {
+    buffer.drawText("Searching...", 15, 8, buffer.rgb(255, 255, 255), &liberationSans_8ptFontInfo);
   }

   //temp sleep
   isSleep ? display.off() : display.on();
-  if(display.getButtons(TSButtonUpperLeft)){
+  if (display.getButtons(TSButtonUpperLeft)
+    && display.getButtons(TSButtonUpperRight)) {
     isSleep = isSleep ? 0 : 1;
     delay(250);
   }
+
   refreshScreen();
 }

@@ -87,55 +93,34 @@
   messageWithSecondDelay("Disconnected...");
 }

-void setTimeHandler(BLECentral& central, BLECharacteristic& characteristic){
+void setTimeHandler(BLECentral& central, BLECharacteristic& characteristic) {
   setTime(timeCharacteristic.valueBE());
   isTimeSet = 1;
 }

-void messageWithSecondDelay(String msg){
-  buffer.drawText(stringBuffer.start().put(msg.c_str()).get(),15,8,buffer.rgb(255,255,255), &liberationSans_8ptFontInfo);
+void messageWithSecondDelay(String msg) {
+  buffer.drawText(stringBuffer.start().put(msg.c_str()).get(), 15, 8, buffer.rgb(255, 255, 255), &liberationSans_8ptFontInfo);
   refreshScreen();
   delay(1000);
 }

-void refreshScreen(){
+void refreshScreen() {
   buffer.flush(display);
   stringBuffer.reset();
 }

-void renderTime(){
-  buffer.drawText(stringBuffer.start().put(hour() < 10 ? "0" : "").putDec(hour()).put(":").put(minute() < 10 ? "0" : "").putDec(minute()).put(":").put(second() < 10 ? "0" : "").putDec(second()).get(),22,16,buffer.rgb(255,255,255), &liberationSans_12ptFontInfo);
+void renderTime() {
+  char* timeString = stringBuffer.start().put(hour() < 10 ? "0" : "").putDec(hour()).put(":").put(minute() < 10 ? "0" : "").putDec(minute()).put(":").put(second() < 10 ? "0" : "").putDec(second()).get();
+  buffer.drawText(timeString, 22, 16, buffer.rgb(255, 255, 255), &liberationSans_12ptFontInfo);
 }

-void renderDate(){
-  buffer.drawText(stringBuffer.start().putDec(month()).put("-").putDec(day()).put("-").putDec(year()).get(),28,34,buffer.rgb(255,255,255), &liberationSans_8ptFontInfo);
+void renderDate() {
+  char* dateString = stringBuffer.start().putDec(month()).put("-").putDec(day()).put("-").putDec(year()).get();
+  buffer.drawText(dateString, 26, 34, buffer.rgb(255, 255, 255), &liberationSans_8ptFontInfo);
 }

-void renderBackground(){
-  //Dawn
-  if (hour() == 7)
-    buffer.drawRect(0,0,96,64)->filledRect(buffer.rgb(98,90,70));
-  if (hour() == 8)
-    buffer.drawRect(0,0,96,64)->filledRect(buffer.rgb(95,40,20));
-  if (hour() == 9)
-    buffer.drawRect(0,0,96,64)->filledRect(buffer.rgb(88, 57, 30));
-  if (hour() == 10)
-    buffer.drawRect(0,0,96,64)->filledRect(buffer.rgb(100, 97, 100));
-  if (hour() == 11)
-    buffer.drawRect(0,0,96,64)->filledRect(buffer.rgb(100, 100, 100));
-  //Sun
-  if (hour() == 12)
-    buffer.drawRect(0,0,96,64)->filledRect(buffer.rgb(100, 100, 97));
-  if (hour() >= 13 && hour() < 20)
-    buffer.drawRect(0,0,96,64)->filledRect(buffer.rgb(100, 100, 100));
-  //Dusk
-  if (hour() == 20)
-    buffer.drawRect(0,0,96,64)->filledRect(buffer.rgb(97,85,56));
-  //Night
-  if (hour() >= 21 || hour() < 7)
-    buffer.drawRect(0,0,96,64)->filledRect(buffer.rgb(0, 0, 0));
-  //Ocean
-  buffer.drawRect(0,48,94,16)->filledRect(buffer.rgb(28, 107, 160));
+void renderBackground() {
+  buffer.drawRect(0, 0, 96, 64)->filledRect(buffer.rgb(rBackground, gBackground, bBackground));
 }

 //TODO: Method to render orientation.


Bugfix: PTT in Memory mode missing

Bugfix: PTT in Memory mode missing

--- src/Arduino/_23cm-trx/loops.ino
+++ src/Arduino/_23cm-trx/loops.ino
@@ -87,6 +87,9 @@
       setRxFreq(rxFreqHz);
       lcd.setCursor(14,0); lcd.print("M"); lcd.print(selectedMemory);
     }
+
+    /* Handle PTT */
+    if (isPTTPressed()) { transmit(); }
   }
 }


Fix EraseEEPROM example

Fix EraseEEPROM example

--- examples/EraseEEPROM/EraseEEPROM.ino
+++ examples/EraseEEPROM/EraseEEPROM.ino
@@ -15,7 +15,7 @@
   EEPROM.begin(4); // Only one byte cleared, but 4 is the minimum for begin()
   #endif

-  EEPROM.write(EEPROM_POSITION, 0);
+  EEPROM.write(EEPROM_OFFSET, 0);

   #ifdef ESP8266
   EEPROM.commit();


Added first test for Signal class

Added first test for Signal class

--- examples/TestSignals/TestSignals.ino
+++ examples/TestSignals/TestSignals.ino
@@ -1,10 +1,17 @@
+#include <Arduino.h>
+#include <Arduino_FreeRTOS.h>
+#include <StandardCplusplus.h>
+#include <RabirdToolkit.h>

-void setup()
-{
+#include <RSignal.h>
+
+Rt::RSignal0<> a;
+
+void setup() {
+  a.clear();
 }

-void loop()
-{
+void loop() {
 }


small changes

small changes

--- examples/alarm_clock/alarm_clock.ino
+++ examples/alarm_clock/alarm_clock.ino
@@ -4,7 +4,7 @@
  */

 #include <WearableWayfinder.h>
-#include <Adafruit_GFX.h>   stroke // Core graphics library
+#include <Adafruit_GFX.h> // Core graphics library
 #include <Adafruit_ST7735.h> // Hardware-specific library
 #include <Wire.h>
 #include <SPI.h>