most recent code

most recent code

--- integration/integration.ino
+++ integration/integration.ino
@@ -23,7 +23,7 @@

 // angle PID control definitions
 double current_angle = 0;
-double target_angle = 7;
+double target_angle = 6.5;
 double error = 0;
 double last_error = 0;
 double delta_error = 0;
@@ -42,23 +42,21 @@
 double sp_Kp = 5;
 double sp_Kd = 0.5;
 double sp_Ki = 0;
-double starting_bias = 7;
+double starting_bias = 6.5;

 // other definitions
 int p1, p2;
 double robot_angle;
 int control_decision = 0;
-
-<<<<<<< HEAD
-=======
-
-//info
-enum state {idle,forward_drive, backup, left_turn,right_turn};
+double factor1 = 1;
+double factor2 = 1;
+bool toggle = false;
+
+// receive info
+enum state {idle,forward, backup, left_turn,right_turn};
 state gesture_state = idle;
-int turning_speed;
-bool should_catapult;
-
->>>>>>> 206c86daf8a79e890468a8966aa9a831e7c4b4e7
+state command = idle;
+
 //========================================== don't see this section ===========================================//
 // volatile interrupt data
 volatile double motor_speed = 0;
@@ -162,72 +160,22 @@
 void timeOut2Handler() {
   if (micros() - last_time2 > 5000) motor_speed2 = 0;
 }
-
 // ========================================= don't see above section =======================================//

-<<<<<<< HEAD
-
-void setup() {
-  Serial.begin(115200);
-=======
 void receive_info() {
-   String command1 =  Serial.readStringUntil('#');
-   Serial.print("after somdthing");
-   char command[30];
-   command1.toCharArray(command, 30);
-   char *parseChar1; // For state
-   char *parseChar2; // For turning_speed
-   char *parseChar3; // For catapult
-   char *parseChar4; // For the last null
-   parseChar1 = strtok(command, " ");
-   parseChar2 = strtok(NULL, " ");
-   parseChar3 = strtok(NULL, " ");
-   parseChar4 = strtok(NULL, " ");
-   /* Integrety checking */
-   int cur_state = atoi(parseChar1) - 1;
-   int cur_speed = atoi(parseChar2);
-   int cur_cata = atoi(parseChar3) - 1;
-
-   if (cur_state < 0 || cur_state > (right_turn + 1)) {
-    //Serial.println("Fail state");
+  int raw_command = Serial.read() - 49;
+  // Integrity checking
+  if (raw_command < idle || raw_command > right_turn) {
+    Serial.print("Fail state");
     return;
-   }
-   if (cur_cata < 0 || cur_cata > 1) {
-    //Serial.println("Fail cata");
-    return;
-   }
-   if (!parseChar2 || !parseChar3 || parseChar4) {
-    //Serial.println("Fail token number");
-    return;
-   }
-
-   gesture_state = (state)cur_state;
-   turning_speed = cur_speed;
-   should_catapult = (cur_cata > 0);
-   //Serial.println(command1);
-   //Serial.println(gesture_state);
-   //Serial.println(turning_speed);
-   //Serial.println(should_catapult);
-
-
-
-
-   //int int_command1 = command1.toInt();
-   //String command2 = Serial.readStringUntil(' ');
-   //int int_command2 = command2.toInt();
-   //String command3 = Serial.readStringUntil('#');
-   //int int_command3 = command3.toInt();
-   //Serial.println("Command: ");
-   //Serial.println(int_command1);
-   //Serial.println(int_command2);
-   //Serial.println(int_command3);
-
-
-}
+  }
+  command = (state)raw_command;
+  Serial.print(command);
+}
+
 void setup() {
   Serial.begin(115200);
   digitalWrite(8,LOW);
->>>>>>> 206c86daf8a79e890468a8966aa9a831e7c4b4e7
   pinMode(21, OUTPUT);
   pinMode(12, OUTPUT);
   pinMode(13, OUTPUT);
@@ -311,19 +259,68 @@
 }

 void loop() {
-<<<<<<< HEAD
   digitalWrite(5, LOW);
-=======
-  if(Serial.available()>0){
-    //Serial.print("has serial");
-    //digitalWrite(8,HIGH);
+  if (Serial.available()) {
     receive_info();
    }
   digitalWrite(5, LOW);
+  // =========================================== 1. FSM state actions ============================================== //
+  if (gesture_state == idle) {
+    if (target_speed > 0) {
+      target_speed = max(0, target_speed - 0.001);
+    } else {
+      target_speed = min(0, target_speed + 0.001);
+    }
+  }
+  if (gesture_state == forward) {
+    target_speed = min(0.5, target_speed + 0.001);
+  }
+  if (gesture_state == backup) {
+    target_speed = max(-0.5, target_speed - 0.001);
+  }
+  if (gesture_state == left_turn) {
+    target_speed = max(-0.5, target_speed - 0.001);
+    factor1 = 0.8;
+    factor2 = 1.3;
+    toggle = false;
+  }
+  if (gesture_state == right_turn){
+    target_speed = max(-0.5, target_speed - 0.001);
+    factor1 = 1.3;
+    factor2 = 0.8;
+    toggle = true;
+  }
+  // ========================================= 2. FSM state transitions ============================================ //
+//  if ((gesture_state == idle) && (command == forward)) {
+//    gesture_state = forward;
+//  }
+//  if ((gesture_state == idle) && (command == backup)) {
+//    gesture_state = backup;
+//  }
+//  if ((gesture_state == forward) && (command == idle)) {
+//    gesture_state = idle;
+//  }
+//  if ((gesture_state == forward) && (command == backup)) {
+//    gesture_state = backup;
+//  }
+//  if ((gesture_state == backup) && (command == idle)) {
+//    gesture_state = idle;
+//  }
+//  if ((gesture_state == backup) && (command == forward)) {
+//    gesture_state = forward;
+//  }
+  gesture_state = command;

->>>>>>> 206c86daf8a79e890468a8966aa9a831e7c4b4e7
-  // =========================================== 1. setpoint pid control =========================================== //
-  current_speed = motor_speed * A_trend_first;
+  if (1) {
+    Serial.print(gesture_state);Serial.print("   ");
+    Serial.println(target_speed);
+  }
+  // =========================================== 3. setpoint pid control =========================================== //
+  if (!toggle) {
+    current_speed = motor_speed * A_trend_first;
+  } else {
+    current_speed = motor_speed2 * A_trend_first;
+  }
   speed_error = -(current_speed - target_speed);
   delta_speed_error = speed_error - last_speed_error;
   speed_error_sum = speed_error_sum + speed_error;
@@ -337,7 +334,7 @@
   }
   digitalWrite(5, HIGH);

-  // =========================================== 2. update sensor data ============================================== //
+  // =========================================== 4. update sensor data ============================================== //
   while (i2cRead(0x3B, i2cData, 14));
   accX = ((i2cData[0] << 8) | i2cData[1]);
   accY = ((i2cData[2] << 8) | i2cData[3]);
@@ -382,7 +379,7 @@
     Serial.println();
   }

-  // =========================================== 3. angle pid control ============================================== //
+  // =========================================== 5. angle pid control ============================================== //
   robot_angle = kalAngleX;
   error = robot_angle - target_angle;
   delta_error = error - last_error;
@@ -391,15 +388,14 @@
   if (control_decision > 255) {control_decision = 255;integrated_error -= error;}
   else if (control_decision< -255) {control_decision = -255;integrated_error -= error;}
   if (control_decision > 0){
-    motorControl(control_decision, control_decision,1,1);
-    //motorControl(int(control_decision*0.8), int(control_decision*1.2),1,1);
+    motorControl(control_decision * factor1, control_decision * factor2,1,1);
   } else {
-    motorControl(-control_decision, -control_decision, 2,2);
-    //motorControl(-int(control_decision*0.8), -int(control_decision*1.2),2,2);
+    motorControl(-control_decision * factor1, -control_decision * factor2, 2,2);
   }
   last_error = error;
   if (0) { // set to 1 to activate
     Serial.print("  robot_angle=");Serial.println(robot_angle);
     Serial.print("  control decision=");Serial.println(control_decision);
   }
-}
+  //delay(2);
+}


Fix comments

Fix comments

Header comment somehow got loused up on the last commit.

--- examples/bmp/bmp.ino
+++ examples/bmp/bmp.ino
@@ -1,10 +1,14 @@
 /***************************************************
   This is a example sketch demonstrating bitmap drawing
-  capabilities of the SSD1351 library  for the 1.5"
-  16-bit Color OLED with SSD1351 driver chip
+  capabilities of the SSD1351 library for the 1.5"
+  and 1.27" 16-bit Color OLEDs with SSD1351 driver chip

   Pick one up today in the adafruit shop!
   ------> http://www.adafruit.com/products/1431
+  ------> http://www.adafruit.com/products/1673
+
+  If you're using a 1.27" OLED, change SSD1351HEIGHT in Adafruit_SSD1351.h
+ 	to 96 instead of 128

   These displays use SPI to communicate, 4 or 5 pins are required to
   interface


Store clock period in microseconds.

Store clock period in microseconds.

--- examples/seq/seq.ino
+++ examples/seq/seq.ino
@@ -68,9 +68,9 @@
   bool stage_slew[8];
   uint8_t stage_count;
   bool diradd_mode;
-  float slew_rate;
-  float gate_time;
-  uint16_t clock_period;
+  uint8_t slew_rate;
+  uint8_t gate_time;
+  unsigned long clock_period;
   bool clock_ext;
 };

@@ -170,9 +170,8 @@
  private:
   bool partial_gate()
   {
-    uint16_t elapsed = millis() - clock_time;
     return (seq_values.clock_ext && clock_gate)
-           || (elapsed < (seq_values.gate_time * seq_values.clock_period / 16))
+           || (millis() - clock_time < (seq_values.gate_time * (seq_values.clock_period / 16000)))
            || retrigger;
   }

@@ -249,21 +248,21 @@
     {
       params.vals.slew_rate = 8;
     }
-    seq_values.slew_rate = (float)params.vals.slew_rate / 16.0;
+    seq_values.slew_rate = params.vals.slew_rate;

     if(params.vals.gate_time < 0 || params.vals.gate_time > 16)
     {
       params.vals.gate_time = 8;
     }
-    seq_values.gate_time = (float)params.vals.gate_time / 16.0;
+    seq_values.gate_time = params.vals.gate_time;

     if(params.vals.clock_bpm < 0 || params.vals.clock_bpm > 30)
     {
       params.vals.clock_bpm = 0;
     }
-    seq_values.clock_period = bpm_to_ms(params.vals.clock_bpm);
+    seq_values.clock_period = bpm_to_us(params.vals.clock_bpm);
     seq_values.clock_ext = !(bool)params.vals.clock_bpm;
-    Timer1.initialize(seq_values.clock_period * 1000);
+    Timer1.initialize(seq_values.clock_period);
     Timer1.attachInterrupt(clock_isr);

     // draw global elements
@@ -384,7 +383,7 @@
               {
                 params.vals.slew_rate = 16;
               }
-              seq_values.slew_rate = (float)params.vals.slew_rate / 16.0;
+              seq_values.slew_rate = params.vals.slew_rate;
               display->fill_rect(57, 3, 16, 5, DUINO_SSD1306::White);
               display_slew_rate(57, 3, params.vals.slew_rate, DUINO_SSD1306::Black);
               break;
@@ -398,7 +397,7 @@
               {
                 params.vals.gate_time = 16;
               }
-              seq_values.gate_time = (float)params.vals.gate_time / 16.0;
+              seq_values.gate_time = params.vals.gate_time;
               display->fill_rect(79, 3, 16, 5, DUINO_SSD1306::White);
               display_gate_time(79, 3, params.vals.gate_time, DUINO_SSD1306::Black);
               break;
@@ -412,7 +411,7 @@
               {
                 params.vals.clock_bpm = 30;
               }
-              seq_values.clock_period = bpm_to_ms(params.vals.clock_bpm);
+              seq_values.clock_period = bpm_to_us(params.vals.clock_bpm);
               seq_values.clock_ext = !(bool)params.vals.clock_bpm;
               display->fill_rect(99, 1, 19, 9, DUINO_SSD1306::White);
               display_clock(100, 2, params.vals.clock_bpm, DUINO_SSD1306::Black);
@@ -525,7 +524,7 @@
     }
     else
     {
-      Timer1.setPeriod(seq_values.clock_period * 1000);
+      Timer1.setPeriod(seq_values.clock_period);
       Timer1.attachInterrupt(clock_isr);
     }
   }
@@ -535,9 +534,9 @@
     return ((float)note - 36.0) / 12.0;
   }

-  uint16_t bpm_to_ms(uint8_t bpm)
-  {
-    return 600000 / bpm;
+  unsigned long bpm_to_us(uint8_t bpm)
+  {
+    return 6000000 / (unsigned long)bpm;
   }

   void display_slew_rate(int16_t x, int16_t y, uint8_t rate, DUINO_SSD1306::SSD1306Color color)


Constant renames, #if DEBUG blocks

Constant renames, #if DEBUG blocks

Capitalize WIDTH/HEIGHT now that they're constants.
Rename BASE_WIDTH to BASE_WID to make future find/replace unambiguous
with WIDTH.
Compile out all DEBUG code when it's #defined false.
Print meaningful stuff during the startup pattern.

--- blume.ino
+++ blume.ino
@@ -5,8 +5,8 @@

 // These settings change per project!
 #define NUM_LEDS    72
-#define BASE_WIDTH  12
-// If true, adds 1 to BASE_WIDTH for every other row
+#define BASE_WID  12
+// If true, adds 1 to BASE_WID for every other row
 #define STAGGERED false
 // Wiring is in a zig-zag pattern.
 #define ZIGZAG   false
@@ -17,7 +17,7 @@
 // CUCUMBER: 104/6/true/false
 // VICTORIA HAT: 28/16/false/false/Clock=2
 // CARO THING: 18/1/false/false
-// NEHA BULB: 76/6/true/falsese
+// NEHA BULB: 76/6/true/false
 // STOPH: 20/1/false/false
 // NINA: 18/1/false/false
 // TREVOR: 75/6/true/false
@@ -29,7 +29,7 @@
 // BLUME DUBIOUS: 60/6/true/false
 // BLUME FEATHER: 72/12/false/false

-#define DEBUG true
+#define DEBUG false

 // Only change these settings if you're wired to different pins, using a non-APA102 chipset,
 // using a different COLOR_ORDER for RGB, etc.
@@ -53,7 +53,7 @@
 // EVERYTHING BELOW HERE WON'T CHANGE FOR A NORMAL PROJECT.

 #if TEXTMODE
-// Include this here because it uses keywords we #define below like "width" and "height"
+// Include this here because it uses keywords we #define below like "WIDTH" and "HEIGHT"
 #include "Adafruit_GFX.h"
 #endif

@@ -67,12 +67,12 @@
 #define SRAM_SIZE 2048
 // Assume we need this much for everything else
 #define VAR_ALLOWANCE (NUM_LEDS * 3 + 850)
-#define MAX_FRAMES (BASE_WIDTH == 1 ? (SRAM_SIZE - VAR_ALLOWANCE) / NUM_LEDS : 0)
-
-#define width (STAGGERED ? BASE_WIDTH * 2 + 1 : BASE_WIDTH)
+#define MAX_FRAMES (BASE_WID == 1 ? (SRAM_SIZE - VAR_ALLOWANCE) / NUM_LEDS : 0)
+
+#define WIDTH (STAGGERED ? BASE_WID * 2 + 1 : BASE_WID)
 #define logical_num_leds (STAGGERED ? NUM_LEDS * 2 : NUM_LEDS)
 // Add extra row if there's a remainder.
-#define height (logical_num_leds / width + (logical_num_leds % width ? 1 : 0))
+#define HEIGHT (logical_num_leds / WIDTH + (logical_num_leds % WIDTH ? 1 : 0))
 int eepromStart;
 long saveTarget;
 long lastFrameTime;
@@ -109,14 +109,14 @@
 BlumeGFX::~BlumeGFX(void) {
 }
 void BlumeGFX::drawPixel(int16_t x, int16_t y, uint16_t color) {
-  if (x < 0 || x >= width || y < 0 || y >= height) {
+  if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT) {
     return;
   }
-  setAt(x, height-1-y, realColor);
+  setAt(x, HEIGHT-1-y, realColor);
   printed = true;
 }

-BlumeGFX gfx = BlumeGFX(width, height);
+BlumeGFX gfx = BlumeGFX(WIDTH, HEIGHT);

 // Max length 32
 char text[32] = "Hello World! I'm Grant.";
@@ -126,7 +126,7 @@
   if (initialize) {
     gfx.setFont(&Picopixel);
     gfx.setTextWrap(false);
-    pos = width;
+    pos = WIDTH;
     nextShift = 0;
   }
   if (!nextShift || millis() >= nextShift) {
@@ -138,7 +138,7 @@
     gfx.printed = false;
     gfx.print(text);
     if (!gfx.printed) {
-      pos = width;
+      pos = WIDTH;
     }
   }
 }
@@ -161,24 +161,23 @@
   FastLED.setBrightness(0);
   FastLED.show();

-  /*Serial.print(width);
-  Serial.print('x');
-  Serial.println(height);*/
-
-  if (DEBUG) {
-    FastLED.setBrightness(3);
-    fill_solid(leds, NUM_LEDS, 0xFF0000);
-    FastLED.delay(500);
-    Serial.println(F("Hello"));
-    fill_solid(leds, NUM_LEDS, 0x00FF00);
-    FastLED.delay(500);
-    Serial.println(F("World"));
-    fill_solid(leds, NUM_LEDS, 0x0000FF);
-    FastLED.delay(500);
-    Serial.println(F("!"));
-    fill_solid(leds, NUM_LEDS, 0x000000);
-    FastLED.delay(500);
-  }
+#if DEBUG
+  FastLED.setBrightness(3);
+  fill_solid(leds, NUM_LEDS, 0xFF0000);
+  FastLED.delay(500);
+  Serial.print(F("Width: "));
+  Serial.println(WIDTH);
+  fill_solid(leds, NUM_LEDS, 0x00FF00);
+  FastLED.delay(500);
+  Serial.print(F("Height: "));
+  Serial.println(HEIGHT);
+  fill_solid(leds, NUM_LEDS, 0x0000FF);
+  FastLED.delay(500);
+  Serial.print(F("Number of LEDs: "));
+  Serial.println(NUM_LEDS);
+  fill_solid(leds, NUM_LEDS, 0x000000);
+  FastLED.delay(500);
+#endif

   // Should be first time only: Write a valid eepromStart address
   EEPROM.put(EEPROM_START_POINTER_ADDR, 0x2);
@@ -193,18 +192,19 @@
 }

 void doFPS() {
-  if (DEBUG) {
-    static byte totalLoops = 0;
-    static long totalDurations = 0;
-    totalDurations += lastFrameDuration;
-    totalLoops++;
-    if (totalLoops == 100) {
-      Serial.print(F("FPS: "));
-      Serial.println((float)totalLoops / (float)totalDurations * 1000.0);
-      totalLoops = 0;
-      totalDurations = 0;
-    }
-  }
+// This is a no-op when DEBUG=false
+#if DEBUG
+  static byte totalLoops = 0;
+  static long totalDurations = 0;
+  totalDurations += lastFrameDuration;
+  totalLoops++;
+  if (totalLoops == 100) {
+    Serial.print(F("FPS: "));
+    Serial.println((float)totalLoops / (float)totalDurations * 1000.0);
+    totalLoops = 0;
+    totalDurations = 0;
+  }
+#endif
 }
 void loop() {
   lastFrameDuration = millis() - lastFrameTime;
@@ -217,7 +217,7 @@
 }

 inline bool isImaginary(byte x, byte y) {
-  return x >= width || y >= height || (
+  return x >= WIDTH || y >= HEIGHT || (
     STAGGERED && (x % 2 != y % 2));
 }
 void setAt(byte x, byte y, CRGB color) {
@@ -225,13 +225,13 @@
     if (isImaginary(x, y)) {
       return;
     }
-    byte idx = x / 2 + (x % 2) * (BASE_WIDTH + 1) + width * (y / 2);
+    byte idx = x / 2 + (x % 2) * (BASE_WID + 1) + WIDTH * (y / 2);
     if (idx >= NUM_LEDS) {
       return;
     }
     leds[idx] = color;
   } else {
-    byte idx = ((ZIGZAG && y % 2) ? (width - 1 - x) : x) + y * width;
+    byte idx = ((ZIGZAG && y % 2) ? (WIDTH - 1 - x) : x) + y * WIDTH;
     if (idx < NUM_LEDS) {
       leds[idx] = color;
     }
@@ -239,8 +239,8 @@
 }
 void fillRow(byte row, CRGB color) {
   if (STAGGERED) {
-    byte start = row * width / 2;
-    byte num = width / 2;
+    byte start = row * WIDTH / 2;
+    byte num = WIDTH / 2;
     if (row % 2) {
       start += 1;
     } else {
@@ -251,25 +251,25 @@
     }
     fill_solid(leds + start, num, color);
   } else {
-    for (byte j = 0; j < width; j++) {
-      if (row * width + j < NUM_LEDS) {
-        leds[row * width + j] = color;
+    for (byte j = 0; j < WIDTH; j++) {
+      if (row * WIDTH + j < NUM_LEDS) {
+        leds[row * WIDTH + j] = color;
       }
     }
   }
 }
 void fillCol(byte col, CRGB color) {
   if (ZIGZAG) {
-    for (byte i = 0; i < height; i++) {
+    for (byte i = 0; i < HEIGHT; i++) {
       setAt(col, i, color);
     }
   } else if (STAGGERED) {
-    for (byte i = col / 2 + (col % 2) * (BASE_WIDTH + 1);
-         i < NUM_LEDS; i += width) {
+    for (byte i = col / 2 + (col % 2) * (BASE_WID + 1);
+         i < NUM_LEDS; i += WIDTH) {
       leds[i] = color;
     }
   } else {
-    for (byte j = col; j < NUM_LEDS; j+= width) {
+    for (byte j = col; j < NUM_LEDS; j+= WIDTH) {
       leds[j] = color;
     }
   }
@@ -308,7 +308,7 @@
     } else {
       if (question == 'D') {
         // Send dimensions.
-        byte dims[] = { '!', 'D', width, height, NUM_LEDS, MAX_FRAMES };
+        byte dims[] = { '!', 'D', WIDTH, HEIGHT, NUM_LEDS, MAX_FRAMES };
         sendSeparately(dims, sizeof(dims));
       }
     }
@@ -363,9 +363,9 @@
     }
 #endif
     saveTarget = 0;
-    if (DEBUG) {
-      Serial.println(F("SAVED!"));
-    }
+#if DEBUG
+    Serial.println(F("SAVED!"));
+#endif
   }
 }

@@ -379,20 +379,20 @@
     }
 #endif
   }
-  if (DEBUG) {
-    Serial.print(F("settings: "));
-    Serial.print(settings.brightness);
-    Serial.print(',');
-    Serial.print(settings.mode);
-    Serial.print(',');
-    Serial.print(settings.hue);
-    Serial.print(',');
-    Serial.print(settings.saturation);
-    Serial.print(',');
-    Serial.print(settings.c1);
-    Serial.print(',');
-    Serial.println(settings.c2);
-  }
+#if DEBUG
+  Serial.print(F("settings: "));
+  Serial.print(settings.brightness);
+  Serial.print(',');
+  Serial.print(settings.mode);
+  Serial.print(',');
+  Serial.print(settings.hue);
+  Serial.print(',');
+  Serial.print(settings.saturation);
+  Serial.print(',');
+  Serial.print(settings.c1);
+  Serial.print(',');
+  Serial.println(settings.c2);
+#endif

   FastLED.setBrightness(settings.brightness);
   if ((settings.mode == 'C' || settings.mode == 'R') &&
@@ -457,7 +457,7 @@
     // c2 is size 0-100 if vertical, 101-201 if horizontal
     rainbow = settings.c1 > 100;
     horizontal = settings.c2 > 100;
-    dimension = horizontal ? width : height;
+    dimension = horizontal ? WIDTH : HEIGHT;
     speed = float(int(rainbow ? settings.c1 - 101 : settings.c1) - 50) * dimension / 8000.0;
     // First convert size to [0,100]
     size = horizontal ? settings.c2 - 101 : settings.c2;
@@ -549,8 +549,8 @@
 #define GREEN 1
 #define BLUE 2
 void runBlobs(bool initialize) {
-  static float xPos[] = { (float)width / 2.0, (float)width / 2.0, (float)width / 2.0 };
-  static float yPos[] = { (float)height / 2.0, (float)height / 2.0, (float)height / 2.0 };
+  static float xPos[] = { (float)WIDTH / 2.0, (float)WIDTH / 2.0, (float)WIDTH / 2.0 };
+  static float yPos[] = { (float)HEIGHT / 2.0, (float)HEIGHT / 2.0, (float)HEIGHT / 2.0 };
   static float xIncrement[3];
   static float yIncrement[3];
   static int steps[] = { 0, 0, 0 };
@@ -561,20 +561,20 @@
       // Cancel any pending movements since we may have a new speed
       steps[c] = 0;
       // Initialize size for this blob
-      size[c] = mapRange(*(&settings.saturation + c), 0, 255, 0, max(width, height));
+      size[c] = mapRange(*(&settings.saturation + c), 0, 255, 0, max(WIDTH, HEIGHT));
     }
   }

   CRGB color;
   // Render the spots.
-  for (byte x = 0; x < width; x++) {
-    for (byte y = 0; y < height; y++) {
+  for (byte x = 0; x < WIDTH; x++) {
+    for (byte y = 0; y < HEIGHT; y++) {
       if (isImaginary(x, y)) {
         continue;
       }
       for (byte c = RED; c <= BLUE; c++) {
-        float xDist = distance(x, xPos[c], width);
-        float yDist = distance(y, yPos[c], height);
+        float xDist = distance(x, xPos[c], WIDTH);
+        float yDist = distance(y, yPos[c], HEIGHT);
         float dist = sqrt(xDist * xDist + yDist * yDist);
         color[c] = 255.0 * (size[c] - min(size[c], dist)) / size[c];
       }
@@ -586,11 +586,11 @@
   // Two-dimensional displays want one of (x,y) to be zero sometimes so
   // the movement isn't always diagonal. One-dimensional displays always want
   // movement in whichever is the meaningful dimension.
-  bool allowZero = width > 1 || height > 1;
+  bool allowZero = WIDTH > 1 || HEIGHT > 1;
   for (byte c = RED; c <= BLUE; c++) {
     if (!steps[c]) {
-      xIncrement[c] = (float)(random(allowZero ? 0 : width * settings.hue / 2, width * settings.hue) + 100) / 10000.0;
-      yIncrement[c] = (float)(random(allowZero ? 0 : height * settings.hue / 2, height * settings.hue) + 100) / 10000.0;
+      xIncrement[c] = (float)(random(allowZero ? 0 : WIDTH * settings.hue / 2, WIDTH * settings.hue) + 100) / 10000.0;
+      yIncrement[c] = (float)(random(allowZero ? 0 : HEIGHT * settings.hue / 2, HEIGHT * settings.hue) + 100) / 10000.0;
       if (random(2)) {
         xIncrement[c] *= -1;
       }
@@ -601,10 +601,10 @@
     }
     xPos[c] += xIncrement[c] * lastFrameDuration;
     yPos[c] += yIncrement[c] * lastFrameDuration;
-    while (xPos[c] > width) xPos[c] -= width;
-    while (yPos[c] > height) yPos[c] -= height;
-    while (xPos[c] < 0) xPos[c] += width;
-    while (yPos[c] < 0) yPos[c] += height;
+    while (xPos[c] > WIDTH) xPos[c] -= WIDTH;
+    while (yPos[c] > HEIGHT) yPos[c] -= HEIGHT;
+    while (xPos[c] < 0) xPos[c] += WIDTH;
+    while (yPos[c] < 0) yPos[c] += HEIGHT;
     steps[c]--;
   }
 }
@@ -623,8 +623,8 @@
   static long frameTarget;
   if (initialize) {
     frameTarget = 0;
-    for (byte x = 0; x < width; x++) {
-      for (byte y = 0; y < height; y++) {
+    for (byte x = 0; x < WIDTH; x++) {
+      for (byte y = 0; y < HEIGHT; y++) {
         if (!isImaginary(x, y)) {
           oneRandom(x, y);
         }
@@ -635,8 +635,8 @@
     byte x;
     byte y;
     do {
-      x = random(width);
-      y = random(height);
+      x = random(WIDTH);
+      y = random(HEIGHT);
     } while (isImaginary(x, y));
     if (millis() > frameTarget) {
       oneRandom(x, y);


changed the conveyors during attack

changed the conveyors during attack

--- TWANG.ino
+++ TWANG.ino
@@ -1,6 +1,6 @@
 // Required libs
-#include <EEPROM.h>
-#include <LiquidCrystal.h>
+#include <EEPROM.h>
+#include <LiquidCrystal.h>
 #include "FastLED.h"
 #include "I2Cdev.h"
 #include "MPU6050.h"
@@ -124,7 +124,7 @@
 	FastLED.setBrightness(BRIGHTNESS);
 	FastLED.setDither(1);

-	lcd.begin(20, 4);
+	lcd.begin(20, 4);
 	updateStats();

 	// Life LEDs
@@ -660,6 +660,7 @@
 				else {
 					playerPositionModifier = (MAX_PLAYER_SPEED - 4);
 				}
+        playerPositionModifier = attacking ? playerPositionModifier/2 : playerPositionModifier;
 			}
 		}
 	}
@@ -743,7 +744,7 @@
 }

 void EEPROM_writeint(long address, int value) {
-	EEPROM.write(address, ((value >> 0) & 0xFF));
+	EEPROM.write(address, ((value >> 0) & 0xFF));
 	EEPROM.write(address + 1, ((value >> 8) & 0xFF));
 }

@@ -838,4 +839,4 @@

-
+


Issue #19: implemented serial communication from Arduino to Node.js app in order to get status update from arduino

--- arduino/OpenROV/OpenROV.ino
+++ arduino/OpenROV/OpenROV.ino
@@ -67,6 +67,8 @@
   // send voltage
   if (time.elapsed(1000)) {
     vout.send(vout.read());
+    Serial.print("time:");
+    Serial.println(millis());
   }
   // else if (time.elapsed(500)) {
   //   digitalWrite(13, HIGH);


Fixed bug with re-using the same timer causing other events such as sending stats not to trigger

--- arduino/OpenROV/OpenROV.ino
+++ arduino/OpenROV/OpenROV.ino
@@ -11,6 +11,8 @@
 Device iout("iout", 3, iout.analog, iout.in);
 Device light("light", 5, light.analog, light.out);
 Timer time;
+Timer statustime;
+Timer controltime;

 Servo tilt;
 // IMPORTANT!
@@ -49,6 +51,8 @@
   motors.reset();

   time.reset();
+  statustime.reset();
+  controltime.reset();

 // initialize all the readings to 0:
   for (int thisReading = 0; thisReading < numReadings; thisReading++)
@@ -87,7 +91,7 @@
   }

   //to reduce AMP spikes, smooth large power adjustments out
-  if (time.elapsed (100)) {
+  if (controltime.elapsed (100)) {
     if (p<c_motorp) c_motorp--;
     if (p>c_motorp) c_motorp++;
     if (v<c_motorv) c_motorv--;
@@ -121,7 +125,7 @@
   }

   // send voltage and current
-  if (time.elapsed(1000)) {
+  if (statustime.elapsed(1000)) {
     vout.send(vout.read());
     iout.send(average);
     Serial.print("time:");


Added comments

Added comments

--- ZUArm.ino
+++ ZUArm.ino
@@ -1,9 +1,20 @@
 //Servo.h is the library required to directly deal with servo motors
 #include <Servo.h>
-
+/*
+ Pinout from base to grip:
+ Motor 0 => 3
+ Motor 1 & 2 => 5
+ Motor 3 => 6
+ Motor 4 => 9
+ Motor 5 => 10
+ Motor 6 => 11
+ */
 int thetaPin[] = {3,5,6,9,10,11};
+// Introduce lower and upper limits for each motor due to mechanical
+// limits
 int lowerLimit[] = {0,0,0,0,0,16};
 int upperLimit[] = {180,180,120,120,60};
+// Number of motor pins
 const int numberOfMotors = 6;
 //We define a servo instance for each motor
 Servo thetaServo[numberOfMotors];
@@ -15,19 +26,25 @@
   for (int i = 0; i < numberOfMotors; i++) {
     thetaServo[i].attach(thetaPin[i]);
   }
+  //Go to Home position
    for (int i = 0; i < numberOfMotors; i++) {
     thetaServo[i].write(lowerLimit[i]);
   }
 }
 int Angle;
 void loop() {
-  //When the serial buffer contains the data we parse the data to send to the
-  //motors, data is sent as follows xx yy zz w
-  //Where xx is theta1 and yy is theta2 and zz is theta3 and w is the grip condition
+  /*
+   Serial sends values in this format:
+   xx yy:
+   Where xx is the motor number, yy is the angle to be sent
+   if xx is larger than the number of motors Arduino responds with
+   Servo values
+   */
   while (Serial.available()) {
    int servoNo = Serial.readStringUntil(' ').toInt();
    if (servoNo < numberOfMotors) {
      Angle = Serial.readStringUntil(':').toInt();
+     // We check if the value of the Angle fits the limits
      if (Angle < lowerLimit[servoNo]) {
       thetaServo[servoNo].write(lowerLimit[servoNo]);
      } else if (Angle > upperLimit[servoNo]) {
@@ -35,12 +52,12 @@
      } else {
       thetaServo[servoNo].write(Angle);
      }
+     //For debugging purposes
 //     Serial.print("Theta ");
 //   Serial.print(servoNo);
 //   Serial.print(" Was sent an angle of ");
 //   Serial.println(Angle);
    } else {
-//    Serial.println("HERE");
     for (int i = 0; i < numberOfMotors; i++) {
       int val = thetaServo[i].read();
       Serial.println(val);


Delete auto_lights.ino

Delete auto_lights.ino

--- auto_lights.ino
+++ auto_lights.ino
@@ -1,38 +0,0 @@
-
-#include <Ultrasonic.h>
-
-Ultrasonic ultrasonic(8, 9); // (Trig PIN,Echo PIN)
-
-int distance = 0;
-int pirPin = 10;    //the digital pin connected to the PIR sensor's output
-
-int maxdistance=45;
-
-
-#define street_light 4
-
-void setup() {
-  Serial.begin (9600);
-  pinMode(pirPin, INPUT);
-  pinMode(street_light, OUTPUT);
-
-}
-
-void loop() {
-
-  distance = ultrasonic.Ranging(CM);
-  Serial.print(distance);
-  Serial.println(" cm" );
-  delay(500);
-  if (distance <= maxdistance && digitalRead(pirPin) == HIGH) {
-    Serial.print("MOTION");
-    digitalWrite(street_light, HIGH);     // Street Light ON
-    delay(500);
-  }
-  else if (distance >= maxdistance && digitalRead(pirPin) == LOW)
-  {
-    digitalWrite(street_light, LOW);     // Street Light OFF
-    delay(500);
-  }
-
-}


datalogger, orden de codigo y librerias de time

--- datalogger/datalogger.ino
+++ datalogger/datalogger.ino
@@ -1,117 +1,208 @@
-/*Reloj de tiempo real con DS1307 en arduino
+/**Datalogger de para temperatura y humedad del hambiente
 *
 * Copyright: codigoelectronica.com
 * Author: Oscar Fernandez
-* License: MIT
+* License: MIT*/
+
+/* Circuito
+* Buzzer      pin 0
+* Led Green   pin 1
+* CS          pin 4
+* MOSI        pin 11
+* MISO        pin 12
+* CLK         pin 13
 */

-//Cargamos librerias
+/*Cargamos librerias*/
 #include <Time.h>
 #include <Wire.h>
 #include <DS1307RTC.h>
 #include <TimeAlarms.h>
 #include <SPI.h>
 #include <SD.h>
-
-String date = "", dateTime = "", time = "", timeDate = "";
+#include <dht.h>
+
+/*Inicializamos las variables*/
+/**Pines*/
+const int buzzer = 0;
+const int led_green = 1;
+const int DHT11_PIN = 3;
 const int chipSelect = 4;
-
-
-//Iniciamos el programa
+const int reference5v = 5;
+
+/**Variables*/
+String dateRTC = "", dateT = "";
+String timeRTC = "", timeT = "";
+String dateTimeRTC = "", dateTimeT = "";
+int error[1];//Variable para error
+int temperature = 0, humidity = 0;
+
+tmElements_t tm;
+dht DHT;
+
+/**Iniciamos el programa*/
 void setup () {
-  //Configuramos el serial
   Serial.begin(9600);
-  pinMode(10, OUTPUT);
-  //actualizamos la hora
-  if (!SD.begin(chipSelect)) {
-    Serial.println("Card failed, or not present");
-    // don't do anything more:
+  pinMode(10, OUTPUT);//Selector de chip de SD
+  /*Verificamos la SD*/
+  if (!SD.begin(chipSelect)){
+    error[0] = 1;
     return;
   }
+  tmElements_t tm;
+  if (RTC.read(tm)){
+    error[1] = 0;
+  }else{
+    error[1] = 1;
+  }
+  /**Cargamos la hora y fecha a las variables de time*/
   setSyncProvider(RTC.get);
-
-  UpdateTime();
-   Alarm.timerRepeat(3600, RepeatsHour);
-   Alarm.timerRepeat(15, SaveSD);
+  UpdateArduinoTime();
+  clockDisplay(3);
+  Alarm.timerRepeat(3600, RepeatsHour);
+  Alarm.timerRepeat(15, SaveSD);
 }

 void loop () {
- digitalClockDisplay();
-
+  errorStart();
+  clockDisplay(1);
+  displayMeteorology();
   Alarm.delay(1000);
+}
+
+void errorStart(){
+  if(error[0] == 1){
+    ErrorBuzzer(3,100,"La SD no funciona o no esta presente.");
+  }else if(error[1] == 1){
+    if (RTC.chipPresent()){
+      ErrorBuzzer(2,200,"El RTC esta detenido, por favor inicielo.");
+    }else{
+      ErrorBuzzer(2,200,"El RTC no funciona o no esta presente.");
+    }
+  }
 }

 void SaveSD(){
   String dataString = "";
-  clockDisplayRTC();
-  clockDisplayTime();
-  int sensor = analogRead(0);
-  float sens = ((sensor * 5.0) / 1024)*10;
-  dataString += dateTime+","+String(sens)+","+timeDate;
-
+  clockRTC();
+  clockTime();
+  float sens = getTemperature();
+  dataString += dateTimeRTC+","+String(sens)+","+dateTimeT;
+  saveDataSD(dataString);
+}
+
+/*La funcion RepeatsHour permite ejecutar un proceso cada hora*/
+void RepeatsHour(){
+  toggleLed(buzzer, 100);
+  Serial.println("Repeticion de hora");
+}
+
+/*La funcion saveSD permite guardar en la sd*//**
+* String dataString Informacion a guardar*/
+void saveDataSD(String stringData){
   File dataFile = SD.open("datalog.txt",FILE_WRITE);
-
-  // if the file is available, write to it:
   if (dataFile) {
-    dataFile.println(dataString);
+    dataFile.println(stringData);
     dataFile.close();
-    // print to the serial port too:
-    Serial.println(dataString);
-    digitalWrite(1, HIGH);   // turn the LED on (HIGH is the voltage level)
-    delay(100);              // wait for a second
-    digitalWrite(1, LOW);    // turn the LED off by making the voltage LOW
-    delay(100);
-  }
-  // if the file isn't open, pop up an error:
-  else {
-    Serial.println("error opening datalog.txt");
-  }
-}
-
-void RepeatsHour(){
-  digitalWrite(0, HIGH);   // turn the LED on (HIGH is the voltage level)
-  delay(100);              // wait for a second
-  digitalWrite(0, LOW);    // turn the LED off by making the voltage LOW
-  delay(100);
-  Serial.println("15 second timer");
-}
-void UpdateTime() {
+    toggleLed(led_green,200);
+    error[0] = 0;
+  }else{
+    error[0] = 1;
+    errorStart();
+  }
+}
+
+
+
+void displayMeteorology(){
+  meteorology();
+  Serial.print(humidity);
+  Serial.print(",\t");
+  Serial.println(temperature);
+}
+
+void meteorology(){
+  temperature = 0;
+  humidity = 0;
+  DHT.read11(DHT11_PIN);
+  temperature = DHT.temperature;
+  humidity = DHT.humidity;
+}
+
+/*La funcion clockRTC permite leer el reloj del RTC*/
+void clockRTC() {
+  dateTimeRTC = "";
+  tmElements_t tm;
+  RTC.read(tm);
+  dateRTC = String(tmYearToCalendar(tm.Year)) + "/" + String(tm.Month) + "/" + String(tm.Day);
+  timeRTC = String(tm.Hour) + ":" + String(tm.Minute) + ":" + String(tm.Second);
+  dateTimeRTC = dateRTC + " " + timeRTC;
+}
+
+/*La funcion clockTime permite leer el reloj de arduino*/
+void clockTime() {
+  dateTimeT = "";
+  timeT = String(hour())+":"+String(minute())+":"+String(second());
+  dateT = String(year())+"/"+String(month())+"/"+String(day());
+  dateTimeT += dateT+" "+timeT;
+}
+
+/*La funcion clockDisplay permite imprimir la fecha y hora por terminal de
+comandos*//**
+* int value Valor a seleccionar (1-> fecha externa, 2-> fecha interna, 3-> Todas las fechas)*/
+void clockDisplay(int value){
+  clockRTC();
+  clockTime();
+  switch(value){
+    case 1:
+      Serial.println("Reloj externo");
+      Serial.println(dateTimeRTC);
+    break;
+    case 2:
+      Serial.println("Reloj interno");
+      Serial.println(dateTimeT);
+    break;
+    case 3:
+      Serial.println("Reloj externo");
+      Serial.println(dateTimeRTC);
+      Serial.println("Reloj interno");
+      Serial.println(dateTimeT);
+    break;
+  }
+}
+
+/*Funcion UpdateTime para actualizar la hora en relog interno de con el RTC*/
+void UpdateArduinoTime() {
   tmElements_t tm;
   RTC.read(tm);
   setTime(tm.Hour, tm.Minute, tm.Second, tm.Day, tm.Month, tmYearToCalendar(tm.Year));
 }

-void clockDisplayRTC() {
-  dateTime = "";
-  tmElements_t tm;
-  RTC.read(tm);
-  date = String(tmYearToCalendar(tm.Year)) + "/" + String(tm.Month) + "/" + String(tm.Day);
-  time = String(tm.Hour) + ":" + String(tm.Minute) + ":" + String(tm.Second);
-  dateTime = date + " " + time;
-  Serial.print(dateTime);
-  Serial.println();
-}
-
-void clockDisplayTime() {
-  timeDate = "";
-  // digital clock display of the time
-  timeDate += String(year())+"/"+String(month())+"/"+String(day())+" "+String(hour())+":"+String(minute())+":"+String(second());
-  Serial.println(timeDate);
-}
-
-void printDigits(int digits) {
-  // utility function for digital clock display: prints preceding colon and leading 0
-  Serial.print(":");
-  if (digits < 10)
-    Serial.print('0');
-  Serial.print(digits);
-}
-void digitalClockDisplay()
-{
-  // digital clock display of the time
-  Serial.print(hour());
-  printDigits(minute());
-  printDigits(second());
-  Serial.println();
-}
-
+/*Funcion ErrorBuzzer para el error con buzzer*//**
+* int repeat Repeticiones a sonar el buzzer
+* int time Tiempo de espera
+* String error Mensaje para terminal de comandos*/
+void ErrorBuzzer(int repeat, int time, String error){
+  Serial.println(error);
+  for(int i = 0 ; i < repeat ; i++ ){
+    digitalWrite(buzzer, HIGH);
+    delay(time);
+    digitalWrite(buzzer, LOW);
+    delay(time);
+  }
+}
+/*La funcion toggleLed permite prender y apagar un led en un tiempo*//**
+* int pin Pin del arduino
+* int time Tiempo de espera*/
+void toggleLed(int pin, int time){
+  digitalWrite(pin, HIGH);
+  delay(time);
+  digitalWrite(pin, LOW);
+  delay(time);
+}
+
+float getTemperature(){
+  float sensor = analogRead(1);
+  float operatingVoltage = 5.0 * sensor / 1024;
+  return(operatingVoltage);
+}


cleanup of debug messages

cleanup of debug messages

--- sketch_soil_wifi/sketch_soil_wifi.ino
+++ sketch_soil_wifi/sketch_soil_wifi.ino
@@ -26,8 +26,6 @@
             SerialUSB.println(arg);\
         }\
     } while(0)
-
-

 int loopcnt = 0;
 int errcnt = 0;
@@ -58,36 +56,31 @@
   SerialUSB.println(wifi.info());

   delay(5000);
-
   wifi.setMode(0);

-  logDebug(wifi.list());
   while (! wifi.join(WIFI_SSID, WIFI_PASSWORD)) {
     logDebug('wifi_setup(): connecting to WIFI...');
     delay(2000);
   }
-  SerialUSB.print("wifi_setuip(): connected to WIFI. IP: ");
-  SerialUSB.println(wifi.getip());
-  SerialUSB.print("wifi_setup(): connected to WIFI. MAC: ");
-  SerialUSB.println(wifi.getmac());
-  SerialUSB.print("wifi_setup(): IP from my own getip(): ");
-  SerialUSB.println( getIP(true)); // short version of IP, cached
-  SerialUSB.print("wifi_setup(): gethostname(): ");
-  SerialUSB.println(gethostname(true)); // short version of hostname, cached
+  logDebug("connected to WIFI. IP: ");
+  logDebug(wifi.getip());
+  logDebug("connected to WIFI. MAC: ");
+  logDebug(wifi.getmac());
+  logDebug("gethostname(): ");
+  logDebug(gethostname(true)); // short version of hostname, cached

 }

 void sensor_setup(void) {
   pinMode(powerPin, OUTPUT);  // Sensor Power
   pinMode(ledPin, OUTPUT);  // LED when measuring
-  SerialUSB.println("sensor_setup(): done");
+  logDebug("sensor_setup(): done");
 }

 void loop() {
-  SerialUSB.print("loop():  loops (minutes) since restart: ");
-  SerialUSB.println(loopcnt);
+  logDebug("loops (minutes) since restart: " + loopcnt);

   loopcnt++;
   if ((loopcnt % 1) == 0) lg_heartbeat(); // every 1 loops
@@ -122,7 +115,20 @@

  void lg_heartbeat(void) {
   String payload = "{ \"host\": \"" + gethostname(true) + "\", \"loopcount\": " + loopcnt + ", \"errcount\": " + errcnt + " }";
-  String request = "POST /api/collections/heartbeat?user_key=" + String(LG_API_KEY) + " HTTP/1.1\r\n"
+  String url = "/api/collections/heartbeat?user_key=" + String(LG_API_KEY);
+  http_post(url, payload);
+ }
+
+ void lg_sensor(int val) {
+  String payload = "{ \"host\": \"" + gethostname(true) + "\", \"soil\": " + val + " }";
+  String url = "/api/collections/sensor?user_key=" + String(LG_API_KEY);
+  http_post(url, payload);
+ }
+
+ void http_post(String url, String payload) {
+  uint8_t buffer[1024] = {0};
+
+  String request = "POST " + url + " HTTP/1.1\r\n"
     + "Host: " + LG_HOST + "\r\n"
     + "User-Agent: arduino-wino/1.0 \r\n"
     + "Content-Type: application/json \r\n"
@@ -130,35 +136,6 @@
     + "Content-Length: " + payload.length() + "\r\n"
     + "\r\n"
     + payload + "\r\n";
-  http_post(request);
- }
-
- void lg_sensor(int val) {
-  String payload = "{ \"host\": \"" + gethostname(true) + "\", \"soil\": " + val + " }";
-  String request = "POST /api/collections/sensor?user_key=" + String(LG_API_KEY) + " HTTP/1.1\r\n"
-    + "Host: " + LG_HOST + "\r\n"
-    + "User-Agent: arduino-wino/1.0 \r\n"
-    + "Content-Type: application/json \r\n"
-    + "Connection: close \r\n"
-    + "Content-Length: " + payload.length() + "\r\n"
-    + "\r\n"
-    + payload + "\r\n";
-  http_post(request);
- }
-
- void http_post(String url) {
-  uint8_t buffer[1024] = {0};
-
-  SerialUSB.print("host: ");
-  SerialUSB.print(LG_HOST);
-  SerialUSB.print(" - port: ");
-  SerialUSB.println(LG_PORT);
-  SerialUSB.println("=== HTTP request start ===");
-  SerialUSB.println(url);
-
-  SerialUSB.println("=== HTTP request end ===");
-  SerialUSB.print("url.length(): ");
-  SerialUSB.println(url.length());

   if (wifi.connect("TCP", LG_HOST, LG_PORT)) {
     logDebug("tcp connection created");
@@ -167,18 +144,13 @@
   }

-  if (wifi.writeln(url)) {
+  if (wifi.writeln(request)) {
     logDebug("request sent with wifi.writeln(String), lrc = true");
   } else {
     logDebug("request sent with wifi.writeln(String), lrc = false");
   }
   uint32_t len = wifi.read(buffer, sizeof(buffer), 10000);
   if (len > 0) {
-    SerialUSB.print("http_post(): Received: [");
-    for (uint32_t i=0; i<len; i++) {
-      SerialUSB.print((char)buffer[i]);
-    }
-    SerialUSB.println("]");
     logDebug((char *)buffer);
   } else {
     logDebug("<empty response>");
@@ -199,12 +171,10 @@
 int soil_measure(void) {
   int val;

-  digitalWrite(ledPin, HIGH);
   digitalWrite(powerPin, HIGH);
-  delay(2000);
+  delay(1000);
   val = analogRead(A2);
   digitalWrite(powerPin, LOW);
-  digitalWrite(ledPin, LOW);
   return val;
 }


code cleaning mainly

code cleaning mainly

--- sketches/gear_indicator/gear_indicator.ino
+++ sketches/gear_indicator/gear_indicator.ino
@@ -7,6 +7,7 @@
 * - WSWireLib: https://github.com/steamfire/WSWireLib
 * - http://stackoverflow.com/questions/21073085/how-to-send-4-pot-values-via-i2c-from-arduino-to-arduino-how-to-differentiate-t
 * - http://www.gammon.com.au/i2c
+* - http://michael.bouvy.net/blog/en/2013/05/25/arduino-multi-master-to-master-i2c/
 * About SD Cards:
 * - https://learn.adafruit.com/adafruit-micro-sd-breakout-board-card-tutorial/format
 * About MPU6050:
@@ -14,21 +15,31 @@
 * - https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050
 * - http://www.geekmomprojects.com/mpu-6050-redux-dmp-data-fusion-vs-complementary-filter/
 * - http://42bots.com/tutorials/arduino-uno-and-the-invensense-mpu-6050-6dof-imu/
-* Some useful information about Aprilia RSV/SL 1000 bikes work: (See: http://www.aprilia-v60.com/index.php?topic=262315)
+* - Yaw Pitch Roll explained: http://www.geekmomprojects.com/wii-nunchuck-controlled-servo-motors/
+* - Calibration sketch: http://www.i2cdevlib.com/forums/topic/96-arduino-sketch-to-automatically-calculate-mpu6050-offsets/
+* - Kalman filter example: http://www.instructables.com/id/Gyro-Camera-for-Motorcycle/?ALLSTEPS
+* - Better Kalman example: https://github.com/TKJElectronics/Example-Sketch-for-IMU-including-Kalman-filter/tree/master/IMU6DOF/MPU6050
+* About optimization:
+* - https://learn.adafruit.com/memories-of-an-arduino/optimizing-sram
+* Some useful information about Aprilia RSV/SL 1000 bikes sensors: (See: http://www.aprilia-v60.com/index.php?topic=262315)
 * - Speed sensor: purple/green wire=Vcc ~ 9V ? / grey/white: signal ~6.5V, falling to 0V
 * - Engine pulses/revolution: 3 if read from the dashboard wire
 * - Engine pulses/revolution: 6 if crank shaft sensor is used
 * - Wheel pulses/revolution: 5
 */

-#include <SPI.h>
 #include <SD.h>
-//#include <WSWire.h>
+//#include <WSWire.h> // TODO: Test this lib instead of Wire
 #include <Wire.h>
-#include <PinChangeInt.h>
+#include <PinChangeInt.h> // "Pin change" interrupt support

 #include "I2Cdev.h"
 #include "MPU6050_6Axis_MotionApps20.h"
+
+#define VERBOSE 1
+
+#define I2C_ADDRESS_MASTER 0x10 // Current master I2C address
+#define I2C_ADDRESS_ME 0x11 // Current device I2C address

 #define OUTPUT_READABLE_YAWPITCHROLL

@@ -55,9 +66,9 @@

 unsigned long lastmillis;

-const int chipSelect = 4;
-
-uint8_t i2c_values[12];
+const byte chipSelect = 4;
+
+uint8_t i2c_values[12]; // Values to send back to the I2C Master

 MPU6050 mpu;
 // MPU control/status vars
@@ -78,25 +89,26 @@
   mpuInterrupt = true;
 }

-int file_index = FIRST_FILE_INDEX;
+unsigned int file_index = FIRST_FILE_INDEX;
+const char* settings_file_name PROGMEM = "settings.ini";

 void setup() {

   // join I2C bus (I2Cdev library doesn't do this automatically)
   #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
-    Wire.begin();
+    Wire.begin(I2C_ADDRESS_ME); // Verify if it still works
     TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
   #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
     Fastwire::setup(400, true);
   #endif
+
   Serial.begin(115200);
   while (!Serial); // wait for Leonardo enumeration, others continue immediately
+
   // Verify MPU connection
-  Serial.println(F("Testing device connections..."));
-  Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
+  serial_println(mpu.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");

   // load and configure the DMP
-  Serial.println(F("Initializing DMP..."));
   devStatus = mpu.dmpInitialize();

   // supply your own gyro offsets here, scaled for min sensitivity
@@ -105,23 +117,15 @@
   mpu.setZGyroOffset(-85);
   mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

-  // make sure it worked (returns 0 if so)
-  if (devStatus == 0) {
-    // turn on the DMP, now that it's ready
-    Serial.println(F("Enabling DMP..."));
+  if (devStatus == 0) { // = OK
     mpu.setDMPEnabled(true);

-    // enable Arduino interrupt detection
-    Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
-//  attachInterrupt(0, dmpDataReady, RISING);
-//  "Pin change" interrupt instead of the two hardware interrupts, already used for engine rev & wheel rev
+    //  "Pin change" interrupt instead of the two hardware interrupts, already used for engine rev & wheel rev
     pinMode(PIN_INT, INPUT_PULLUP);
     attachPinChangeInterrupt(PIN_INT, dmp_data_ready, RISING);

     mpuIntStatus = mpu.getIntStatus();

-    // set our DMP Ready flag so the main loop() function knows it's okay to use it
-    Serial.println(F("DMP ready! Waiting for first interrupt..."));
     dmpReady = true;

     // get expected DMP packet size for later comparison
@@ -131,9 +135,9 @@
     // 1 = initial memory load failed
     // 2 = DMP configuration updates failed
     // (if it's going to break, usually the code will be 1)
-    Serial.print(F("DMP Initialization failed (code "));
-    Serial.print(devStatus);
-    Serial.println(F(")"));
+    serial_print("DMP Initialization failed (code ");
+    serial_print(devStatus);
+    serial_println(")");
   }

   attachInterrupt(0, rpm_counter, FALLING);
@@ -147,7 +151,6 @@

   lastmillis = 0;

-  Serial.print("Initializing SD card...");
   // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
   // Note that even if it's not used as the CS pin, the hardware SS pin
   // (10 on most Arduino boards, 53 on the Mega) must be left as an output
@@ -155,23 +158,19 @@
   pinMode(10, OUTPUT);

   if (!SD.begin(chipSelect)) {
-    Serial.println("Initialization failed! ");
+    serial_println("SD initialization failed! ");
     return;
   }
-  Serial.println("initialization done.");
-
-  File settings_file = SD.open("settings.ini");
+
+  File settings_file = SD.open(settings_file_name);
   if (settings_file) {
     char* index_ch = readline(settings_file);
     file_index = atoi(index_ch);
-    Serial.print("Index found in file:");
-    Serial.println(file_index);
     file_index++;
-    // close the file:
     settings_file.close();
   }
-  SD.remove("settings.ini");
-  settings_file = SD.open("settings.ini", FILE_WRITE);
+  SD.remove(const_cast<char*>(settings_file_name));
+  settings_file = SD.open(settings_file_name, FILE_WRITE);
   if (settings_file) {
     settings_file.println(file_index);
     settings_file.close();
@@ -226,12 +225,12 @@

   read_mpu();

-  Serial.print("ypr\t");
-  Serial.print(ypr[0] * 180/M_PI);
-  Serial.print("\t");
-  Serial.print(ypr[1] * 180/M_PI);
-  Serial.print("\t");
-  Serial.println(ypr[2] * 180/M_PI);
+  serial_print("ypr\t");
+  serial_print(ypr[0] * 180/M_PI);
+  serial_print("\t");
+  serial_print(ypr[1] * 180/M_PI);
+  serial_print("\t");
+  serial_println(ypr[2] * 180/M_PI);

 }

@@ -248,7 +247,7 @@
   if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
     // reset so we can continue cleanly
     mpu.resetFIFO();
-    Serial.println(F("FIFO overflow!"));
+    serial_println("FIFO overflow!");

   // otherwise, check for DMP data ready interrupt (this should happen frequently)
   } else if (mpuIntStatus & 0x02) {
@@ -342,8 +341,8 @@
     file.println(data);
     file.close();
   } else {
-    Serial.print("Error to open/create file ");
-    Serial.println(file_name);
+    serial_print("Error to open/create file ");
+    serial_println(file_name);
   }
 }

@@ -358,3 +357,29 @@
 void speed_counter() {
   wheel_pulses++;
 }
+
+
+// SERIAL PRINT/PRINTLN
+void serial_print(const char txt[]) {
+  #if VERBOSE
+  Serial.print(txt);
+  #endif
+}
+
+void serial_print(const uint8_t v) {
+  #if VERBOSE
+  Serial.print(v);
+  #endif
+}
+
+void serial_println(unsigned int v) {
+  #if VERBOSE
+  Serial.println(v);
+  #endif
+}
+
+void serial_println(const char txt[]) {
+  #if VERBOSE
+  Serial.println(txt);
+  #endif
+}


convert to hex bytes

convert to hex bytes


Generalizing SSID and PWD names

Generalizing SSID and PWD names

--- examples/ESP8266_Shield_Demo/ESP8266_Shield_Demo.ino
+++ examples/ESP8266_Shield_Demo/ESP8266_Shield_Demo.ino
@@ -33,8 +33,8 @@
 //////////////////////////////
 // Replace these two character strings with the name and
 // password of your WiFi network.
-const char mySSID[] = "PiFi";
-const char myPSK[] = "sparkfun";
+const char mySSID[] = "yourSSIDhere";
+const char myPSK[] = "yourPWDhere";

 //////////////////////////////
 // ESP8266Server definition //


Today/yesterday cumulative runtime.

Today/yesterday cumulative runtime.

--- hvacMonitor.ino
+++ hvacMonitor.ino
@@ -10,14 +10,13 @@
 #define ONE_WIRE_BUS 2
 #include <ArduinoJson.h>

-
 OneWire oneWire(ONE_WIRE_BUS);
 DallasTemperature sensors(&oneWire);

 DeviceAddress ds18b20RA = { 0x28, 0xEF, 0x97, 0x1E, 0x00, 0x00, 0x80, 0x54 }; // Return air probe
 DeviceAddress ds18b20SA = { 0x28, 0xF1, 0xAC, 0x1E, 0x00, 0x00, 0x80, 0xE8 }; // Supply air probe

-char auth[] = "fromBlynkApp";
+char auth[] = "ed06ade587fc4dfea91fb114e08f2104";

 SimpleTimer timer;

@@ -31,7 +30,7 @@
 // HTTP request
 const char WUNDERGROUND_REQ[] =
   //"GET /test.json HTTP/1.1\r\n"  // Keep for test/debug
-  "GET /api/[myAPIkey]/conditions/q/pws:KAZTEMPE29.json HTTP/1.1\r\n"
+  "GET /api/a76b5f288962f088/conditions/q/pws:KAZTEMPE29.json HTTP/1.1\r\n"
   "User-Agent: ESP8266/0.1\r\n"
   "Accept: */*\r\n"
   "Host: " WUNDERGROUND "\r\n"
@@ -41,7 +40,8 @@
 float temp_f;

 WidgetLED led1(V2);
-WidgetLCD lcd(V5);
+WidgetLCD lcd(V5); // Display LCD
+WidgetLCD lcd1(V13); // Diagnostic LCD
 WidgetRTC rtc;
 BLYNK_ATTACH_WIDGET(rtc, V8);

@@ -57,10 +57,17 @@
 int offHour, offHour24, onHour, onHour24, offMinute, onMinute, offSecond, onSecond, offMonth, onMonth,
     offDay, onDay, runTime, tempSplit, secondsCount, alarmTime;

+int currentRuntimeSec; // Blower runtime today in seconds
+int currentRuntimeMin; // Blower runtime today in minutes
+int yesterdayRuntime; // Yesterday's blower runtime in minutes
+
+int dayCountLatch = 0;
+int todaysDate, yesterdaysDate;
+
 void setup()
 {
   Serial.begin(9600);
-  Blynk.begin(auth, "ssid", "pw");
+  Blynk.begin(auth, "0", "keatonhowardkemper2056");

   sensors.begin();
   sensors.setResolution(ds18b20RA, 10);
@@ -76,8 +83,7 @@
   timer.setInterval(5000L, sendHeartbeat); // Blinks Blynk LED to reflect online status
   timer.setInterval(300000L, sendWU); // 5 minutes between Wunderground API calls.
   timer.setInterval(90000L, sendWUtoBlynk); // 1.5 minutes between API data updates to Blynk.
-
-   static char respBuf[4096];
+  timer.setInterval(1000L, countRuntime);  // Counts blower runtime in seconds for daily accumulation display in diagnostics.
 }

 static char respBuf[4096];
@@ -86,7 +92,7 @@

 void sendWUtoBlynk()
 {
-    Blynk.virtualWrite(12, temp_f);
+  Blynk.virtualWrite(12, temp_f);
 }

 void sendWU()
@@ -95,7 +101,7 @@
   Serial.print(F("Connecting to "));
   Serial.println(WUNDERGROUND);

-  // Use WiFiClient class to create TCP connections (A LITTLE WORRIED HOW THIS WILL WORK WITH BLYNK)
+  // Use WiFiClient class to create TCP connections
   WiFiClient httpclient;
   const int httpPort = 80;
   if (!httpclient.connect(WUNDERGROUND, httpPort)) {
@@ -152,8 +158,7 @@
   Serial.println(respLen);
   //Serial.println(respBuf);

-
-// This part will be removed in favor of the timer feature. Probably remove delay_error and just report ERR.
+  // Kept this because I haven't quite figured out how to keep ESP from crashing without it.
   if (showWeather(respBuf)) {
     delay(DELAY_NORMAL);
   }
@@ -165,7 +170,7 @@

 bool showWeather(char *json)
 {
-  StaticJsonBuffer<3*1024> jsonBuffer;
+  StaticJsonBuffer<3 * 1024> jsonBuffer;

   // Skip characters until first '{' found
   // Ignore chunked length, if present
@@ -341,19 +346,19 @@
   }
 }

-void sendHeartbeat()
-{
-  led1.on(); // The ON portion of the LED heartbeat indicator in the Blynk app
-}
-
-void loop() // Typically Blynk tasks should not be placed in void loop(), however these don't run continuously for any reason.
+void sendHeartbeat()  // Blinks a virtual LED in the Blynk app to show the ESP is live and reporting.
+{
+  led1.on();
+}
+
+void loop() // Typically Blynk tasks should not be placed in void loop(), however none of these (Blynk) tasks run continuously for any reason.
 {
   Blynk.run();
   timer.run();

   if (digitalRead(blowerPin) == HIGH) // Runs when blower is OFF.
   {
-    // The following records the time the blower started
+    // The following records the time the blower started to send to the main LCD.
     onHour24 = hour();
     onHour = hourFormat12();
     onMinute = minute();
@@ -372,7 +377,7 @@
   }
   else
   {
-    // The following records the time the blower stopped
+    // The following records the time the blower stopped to send to the main LCD.
     offHour24 = hour();
     offHour = hourFormat12();
     offMinute = minute();
@@ -390,6 +395,7 @@
     offNow = now();
   }

+  // Does the timing for the RA/SA split temperature alarm/notification.
   if (digitalRead(blowerPin) == LOW) // Blower is running.
   {
     secondsCount = (millis() / 1000); // Start the clock that the alarm will reference.
@@ -419,3 +425,61 @@
     alarmTime = 0; // Resets 120s alarm.
   }
 }
+
+void countRuntime()  // Maybe add a midnight Tweet (or replace status) of the day's runtime (timstamped, of course)
+{
+
+  // Sets the date once after reset/boot up, or when the date actually changes.
+  if (dayCountLatch == 0)
+  {
+    todaysDate = day();  // Minute for testing. Day for production.
+    dayCountLatch++;
+  }
+
+  // Runs the blower timer when it's on. *** MIGHT STEAL THIS CODE RUN/OFF LCD DISPLAY.
+  if (digitalRead(blowerPin) == LOW && todaysDate == day())
+  {
+    currentRuntimeSec++;
+  }
+  // Resets the timer on the next day if the blower is running.
+   else if (digitalRead(blowerPin) == LOW && todaysDate != day())
+  {
+    yesterdayRuntime = currentRuntimeMin; // Moves today's runtime to yesterday.
+    dayCountLatch = 0; // Allows today's date to be reset.
+    currentRuntimeSec = 0; // Resets today's timer.
+    lcd1.clear();
+  }
+  // Resets the timer on the next day if the blower isn't running!
+  else if (digitalRead(blowerPin) == HIGH && todaysDate != day())
+  {
+    yesterdayRuntime = currentRuntimeMin;
+    dayCountLatch = 0;
+    currentRuntimeSec = 0;
+    lcd1.clear();
+  }
+
+  // This makes sure the right numberical date for yesterday is shown for the first of any month.
+  if (day() == 1)
+  {
+    if (month() == 3) // The date before 3/1 is 29 (2/29), and so on below.
+    {
+      yesterdaysDate = 29;
+    }
+    else if (month() == 5 || month() == 7 || month() == 10 || month() == 12)
+    {
+      yesterdaysDate = 30;
+    }
+    else if (month() == 1 || month() == 2 || month() == 4 || month() == 6 || month() == 8 || month() == 9 || month() == 11)
+    {
+      yesterdaysDate = 31;
+    }
+  }
+  else
+  {
+    yesterdaysDate = day() - 1; // Subtracts 1 day to get to yesteray unless it's the first of the month (see above)
+  }
+
+  currentRuntimeMin = (currentRuntimeSec / 60);
+  lcd1.print(0, 0, String(month()) + "/" + yesterdaysDate + ": " + yesterdayRuntime + " min");  // Prints yesterday's accumulated runtime.
+  lcd1.print(0, 1, String("Today: ") + currentRuntimeMin + " min");  // Prints today's accumulated runtime.
+}


Fixing more whitespace in the example

Fixing more whitespace in the example

--- examples/mDNSResolver.ino
+++ examples/mDNSResolver.ino
@@ -35,9 +35,10 @@

   // put your setup code here, to run once:
   Serial.print("Resolving ");
-	Serial.println(NAME_TO_RESOLVE);
+  Serial.println(NAME_TO_RESOLVE);

-	resolver.setLocalIP(WiFi.localIP());
+  resolver.setLocalIP(WiFi.localIP());
+
   IPAddress ip = resolver.search(NAME_TO_RESOLVE);
   if(ip != INADDR_NONE) {
     Serial.print("Resolved: ");
@@ -48,6 +49,6 @@
 }

 void loop() {
-	// Required to clear the UDP buffer, as we can't unjoin a multicast group yet
-	resolver.loop();
+  // Required to clear the UDP buffer, as we can't unjoin a multicast group yet
+  resolver.loop();
 }


SR04 will be used to detect obstacles, if an obstacle was detected the robot will turn left or right

--- otto/otto.ino
+++ otto/otto.ino
@@ -1,21 +1,21 @@
 #include <limits.h>
 #include <Servo.h>

-#define RIGHT_ANKLE_POS_MIN     1050
+#define RIGHT_ANKLE_POS_MIN     900
 #define RIGHT_ANKLE_POS_MIDDLE  1510
-#define RIGHT_ANKLE_POS_MAX     1860
-
-#define LEFT_ANKLE_POS_MIN      1140
+#define RIGHT_ANKLE_POS_MAX     1950
+
+#define LEFT_ANKLE_POS_MIN      1050
 #define LEFT_ANKLE_POS_MIDDLE   1490
-#define LEFT_ANKLE_POS_MAX      2190
-
-#define RIGHT_HIP_POS_MIN       950
+#define LEFT_ANKLE_POS_MAX      2200
+
+#define RIGHT_HIP_POS_MIN       960
 #define RIGHT_HIP_POS_MIDDLE    1290
 #define RIGHT_HIP_POS_MAX       1600

 #define LEFT_HIP_POS_MIN        1100
 #define LEFT_HIP_POS_MIDDLE     1500
-#define LEFT_HIP_POS_MAX        1930
+#define LEFT_HIP_POS_MAX        1870

 #define RIGHT_ANKLE_PIN         5
 #define LEFT_ANKLE_PIN          4
@@ -23,9 +23,10 @@
 #define LEFT_HIP_PIN            2
 #define SR04_TRIGGER_PIN        8
 #define SR04_ECHO_PIN           9
-
-#define DELAY 2
-#define STOP_DISTANCE           10
+#define RANDOM_SEED_PIN         A0      // Take noise from unconnected analog pin to seed RNG
+
+#define DELAY                   1500
+#define STOP_DISTANCE           20

 struct Joint
 {
@@ -144,7 +145,7 @@
             joint->setPosition(static_cast<float>(pos));
         }

-        delay(DELAY);
+        delayMicroseconds(DELAY);
     }
 }

@@ -154,7 +155,6 @@
 Joint leftHip(LEFT_HIP_PIN, LEFT_HIP_POS_MIN, LEFT_HIP_POS_MIDDLE, LEFT_HIP_POS_MAX);

 bool started = false;
-bool stop = false;

 long getDistance()
 {
@@ -171,6 +171,112 @@
     return duration * 0.01716;
 }

+void turnLeft()
+{
+    Move leanLeft[] = {
+        Move(&rightAnkle, Joint::POS_MIDDLE, Joint::POS_MIN),
+        Move(&leftAnkle, Joint::POS_MIDDLE, Joint::POS_MIN)
+    };
+
+    Move rotateLeftHip[] = {
+        Move(&rightAnkle, Joint::POS_MIN, Joint::POS_MIDDLE),
+        Move(&leftAnkle, Joint::POS_MIN, Joint::POS_MIDDLE),
+        Move(&leftHip, Joint::POS_MIDDLE, Joint::POS_MAX)
+    };
+
+    Move leanRight[] = {
+        Move(&rightAnkle, Joint::POS_MIDDLE, Joint::POS_MAX),
+        Move(&leftAnkle, Joint::POS_MIDDLE, Joint::POS_MAX)
+    };
+
+    Move rotateRightHip[] = {
+        Move(&rightAnkle, Joint::POS_MAX, Joint::POS_MIDDLE),
+        Move(&leftAnkle, Joint::POS_MAX, Joint::POS_MIDDLE),
+        Move(&rightHip, Joint::POS_MIDDLE, Joint::POS_MAX),
+        Move(&leftHip, Joint::POS_MAX, Joint::POS_MIDDLE)
+    };
+
+    Move rotateBothHips[] = {
+        Move(&rightAnkle, Joint::POS_MIN, Joint::POS_MIDDLE),
+        Move(&leftAnkle, Joint::POS_MIN, Joint::POS_MIDDLE),
+        Move(&rightHip, Joint::POS_MAX, Joint::POS_MIDDLE),
+        Move(&leftHip, Joint::POS_MIDDLE, Joint::POS_MAX)
+    };
+
+    Move finishTurn[] = {
+        Move(&rightAnkle, Joint::POS_MAX, Joint::POS_MIDDLE),
+        Move(&leftAnkle, Joint::POS_MAX, Joint::POS_MIDDLE),
+        Move(&leftHip, Joint::POS_MAX, Joint::POS_MIDDLE)
+    };
+
+    moveJoints(2, leanLeft);
+    moveJoints(3, rotateLeftHip);
+    moveJoints(2, leanRight);
+    moveJoints(4, rotateRightHip);
+    moveJoints(2, leanLeft);
+    moveJoints(4, rotateBothHips);
+    moveJoints(2, leanRight);
+    moveJoints(3, finishTurn);
+}
+
+void turnRight()
+{
+    Move leanRight[] = {
+        Move(&rightAnkle, Joint::POS_MIDDLE, Joint::POS_MAX),
+        Move(&leftAnkle, Joint::POS_MIDDLE, Joint::POS_MAX)
+    };
+
+    Move rotateRightHip[] = {
+        Move(&rightAnkle, Joint::POS_MAX, Joint::POS_MIDDLE),
+        Move(&leftAnkle, Joint::POS_MAX, Joint::POS_MIDDLE),
+        Move(&rightHip, Joint::POS_MIDDLE, Joint::POS_MIN)
+    };
+
+    Move leanLeft[] = {
+        Move(&rightAnkle, Joint::POS_MIDDLE, Joint::POS_MIN),
+        Move(&leftAnkle, Joint::POS_MIDDLE, Joint::POS_MIN)
+    };
+
+    Move rotateLeftHip[] = {
+        Move(&rightAnkle, Joint::POS_MIN, Joint::POS_MIDDLE),
+        Move(&leftAnkle, Joint::POS_MIN, Joint::POS_MIDDLE),
+        Move(&rightHip, Joint::POS_MIN, Joint::POS_MIDDLE),
+        Move(&leftHip, Joint::POS_MIDDLE, Joint::POS_MIN)
+    };
+
+    Move rotateBothHips[] = {
+        Move(&rightAnkle, Joint::POS_MAX, Joint::POS_MIDDLE),
+        Move(&leftAnkle, Joint::POS_MAX, Joint::POS_MIDDLE),
+        Move(&rightHip, Joint::POS_MIDDLE, Joint::POS_MIN),
+        Move(&leftHip, Joint::POS_MIN, Joint::POS_MIDDLE)
+    };
+
+    Move finishTurn[] = {
+        Move(&rightAnkle, Joint::POS_MIN, Joint::POS_MIDDLE),
+        Move(&leftAnkle, Joint::POS_MIN, Joint::POS_MIDDLE),
+        Move(&rightHip, Joint::POS_MIN, Joint::POS_MIDDLE)
+    };
+
+    moveJoints(2, leanRight);
+    moveJoints(3, rotateRightHip);
+    moveJoints(2, leanLeft);
+    moveJoints(4, rotateLeftHip);
+    moveJoints(2, leanRight);
+    moveJoints(4, rotateBothHips);
+    moveJoints(2, leanLeft);
+    moveJoints(3, finishTurn);
+}
+
+void startStepFoward()
+{
+    Move startLeanLeft[] = {
+        Move(&rightAnkle, Joint::POS_MIDDLE, Joint::POS_MIN),
+        Move(&leftAnkle, Joint::POS_MIDDLE, Joint::POS_MIN)
+    };
+
+    moveJoints(2, startLeanLeft);
+}
+
 void stepForward() {
     Move stepLeft[] = {
         Move(&rightAnkle, Joint::POS_MIN, Joint::POS_MIDDLE),
@@ -218,8 +324,18 @@
         };

         moveJoints(2, stepDown);
+
+        if (random(2))
+        {
+            turnLeft();
+        }
+        else
+        {
+            turnRight();
+        }
+
+        startStepFoward();

-        stop = true;
         return;
     }

@@ -236,14 +352,28 @@

         moveJoints(2, stepDown);

-        stop = true;
+        if (random(2))
+        {
+            turnLeft();
+        }
+        else
+        {
+            turnRight();
+        }
+
+        startStepFoward();
+
         return;
     }
 }

-void setup() {
+
+void setup()
+{
     pinMode(SR04_TRIGGER_PIN, OUTPUT);
     pinMode(SR04_ECHO_PIN, INPUT);
+
+    randomSeed(analogRead(RANDOM_SEED_PIN));

     rightAnkle.init();
     leftAnkle.init();
@@ -257,21 +387,11 @@

     if (!started)
     {
-        Move startLeanLeft[] = {
-            Move(&rightAnkle, Joint::POS_MIDDLE, Joint::POS_MIN),
-            Move(&leftAnkle, Joint::POS_MIDDLE, Joint::POS_MIN)
-        };
-
         delay(5000);
-
-        moveJoints(2, startLeanLeft);
-
+        startStepFoward();
         started = true;
     }

-    if (!stop)
-    {
-        stepForward();
-    }
-}
-
+    stepForward();
+}
+


Melhora no cálculo da frequencia.

Melhora no cálculo da frequencia.

--- quad/quad.ino
+++ quad/quad.ino
@@ -12,8 +12,7 @@
 #endif

 #ifdef DEBUG
-long tmBegin;
-long tmEnd;
+long tmCheckpoint;
 #endif

 /* Definição dos canais de entrada. */
@@ -69,9 +68,7 @@

 /* Loop infinito do Arduino. */
 void loop()
-{
-  D(tmBegin = micros());
-
+{
   readRC();

   //  input = ch1v;
@@ -123,8 +120,8 @@
  */
 void telemetry()
 {
-  tmEnd = micros();
-  long tmInterval = tmEnd - tmBegin;
+  long tmInterval = micros() - tmCheckpoint;
+  tmCheckpoint = micros();

   String tmValues;
   tmValues += String(rcThrottle) + ";";


Investigating odd behaviour

Investigating odd behaviour

--- DigitalVFO.ino
+++ DigitalVFO.ino
@@ -42,6 +42,7 @@
 // DEBUG word for debugging program - bitmask values
 //#define DEBUG         (DEBUG_BATT + DEBUG_ACT)
 #define DEBUG         0
+//#define DEBUG         0xff

 // Digital VFO program name & version
 const char *ProgramName = "DigitalVFO";
@@ -1873,9 +1874,9 @@

 void dds_update(Frequency frequency)
 {
-#if (DEBUG & DEBUG_DDS)
-  Serial.printf(F("dds_update: frequency=%ld\n"), frequency);
-#endif
+//#if (DEBUG & DEBUG_DDS)
+//  Serial.printf(F("dds_update: frequency=%ld\n"), frequency);
+//#endif

   // if not online, do nothing
   if (VfoMode != vfo_Online)
@@ -2009,8 +2010,8 @@
     ReHoldClickTime = DefaultHoldClickTime;
     ReDClickTime = DefaultDClickTime;

-    Serial.printf(F("Resetting brightness to %d, contrast to %d and hold time to %d\n"),
-                  LcdBrightness, LcdContrast, ReHoldClickTime);
+    Serial.printf(F("Resetting brightness to %d, contrast to %d and hold/dclick times\n"),
+                  LcdBrightness, LcdContrast);
     Serial.printf(F("Click the RE button to continue...\n"));

     // show user we were reset


Removed some SOC code used to communicate with client Galileo Boards.

--- ServerSketch/ServerSketch.ino
+++ ServerSketch/ServerSketch.ino
@@ -1,11 +1,11 @@
 /*

-Copyright (c) 2013 - Philippe Laulheret, Second Story [http://www.secondstory.com]
-
-This code is licensed under MIT.
-For more information visit  : https://github.com/secondstory/LYT
-
-*/
+ Copyright (c) 2013 - Philippe Laulheret, Second Story [http://www.secondstory.com]
+
+ This code is licensed under MIT.
+ For more information visit  : https://github.com/secondstory/LYT
+
+ */

 #include <Dhcp.h>
 #include <Dns.h>
@@ -53,155 +53,180 @@
 // Process recieved message here....
 //------------------------------------------------------------
 void processTouch(char* in) {
-
+
   Serial.print("input: ");
   Serial.println(in);
   if(String(in) == "trigger"){
-      Serial.println("Trigger found");
-      if(currentLED){
-        digitalWrite(led, LOW);
-        currentLED = false;
-      }else{
-        digitalWrite(led, HIGH);
-        currentLED = true;
-      }
-      //delay(500);
+    Serial.println("Trigger found");
+    if(currentLED){
+      digitalWrite(led, LOW);
+      currentLED = false;
+    }
+    else{
+      digitalWrite(led, HIGH);
+      currentLED = true;
+    }
+    //delay(500);
   }

 }

 /*
 This part of the code is inspired by the stock example coming with libsockets.
-Check it for more details.
-*/
+ Check it for more details.
+ */

 int force_exit = 0;
 enum lyt_protocols {
-	PROTOCOL_HTTP = 0,
-	PROTOCOL_LYT,
-	PROTOCOL_COUNT
+  PROTOCOL_HTTP = 0,
+  PROTOCOL_LYT,
+  PROTOCOL_COUNT
 };

 #define LOCAL_RESOURCE_PATH "/home/root/srv/"

 struct serveable {
-	const char *urlpath;
-	const char *mimetype;
+  const char *urlpath;
+  const char *mimetype;
 };

 static const struct serveable whitelist[] = {
-	{ "/favicon.ico", "image/x-icon" },
-	{ "/img/2s.png", "image/png" },
-        { "/img/splash.png", "image/png" },
-        { "/img/splash2.png", "image/png" },
-        { "/img/placeholder.png", "image/png" },
-        { "/img/placeholder-on.png", "image/png" },
-        { "/css/phone.css", "text/css" },
-        { "/js/jquery-2.0.3.min.js", "application/javascript" },
-        { "/js/phone.js", "application/javascript" },
-        { "/js/pixel.js", "application/javascript" },
-        { "/js/pixelView.js", "application/javascript" },
-        { "/js/socketController.js", "application/javascript" },
-
-	/* last one is the default served if no match */
-	{ "/index.html", "text/html" },
+  {
+    "/favicon.ico", "image/x-icon"   }
+  ,
+  {
+    "/img/2s.png", "image/png"   }
+  ,
+  {
+    "/img/splash.png", "image/png"   }
+  ,
+  {
+    "/img/splash2.png", "image/png"   }
+  ,
+  {
+    "/img/placeholder.png", "image/png"   }
+  ,
+  {
+    "/img/placeholder-on.png", "image/png"   }
+  ,
+  {
+    "/css/phone.css", "text/css"   }
+  ,
+  {
+    "/js/jquery-2.0.3.min.js", "application/javascript"   }
+  ,
+  {
+    "/js/phone.js", "application/javascript"   }
+  ,
+  {
+    "/js/pixel.js", "application/javascript"   }
+  ,
+  {
+    "/js/pixelView.js", "application/javascript"   }
+  ,
+  {
+    "/js/socketController.js", "application/javascript"   }
+  ,
+
+  /* last one is the default served if no match */
+  {
+    "/index.html", "text/html"   }
+  ,
 };

 /* this protocol server (always the first one) just knows how to do HTTP */

 static int callback_http(struct libwebsocket_context *context,
-		struct libwebsocket *wsi,
-		enum libwebsocket_callback_reasons reason, void *user,
-							   void *in, size_t len)
-{
-     //     Serial.println("callback_http()");
-     // WE ARE ALWAYS HITTING THIS POINT
-
-	char buf[256];
-	int n;
-
-	switch (reason) {
-
-	case LWS_CALLBACK_HTTP:
-              lwsl_notice("LWS_CALLBACK_HTTP");
-
-		for (n = 0; n < (sizeof(whitelist) / sizeof(whitelist[0]) - 1); n++)
-			if (in && strcmp((const char *)in, whitelist[n].urlpath) == 0)
-				break;
-
-		sprintf(buf, LOCAL_RESOURCE_PATH"%s", whitelist[n].urlpath);
-
-		if (libwebsockets_serve_http_file(context, wsi, buf, whitelist[n].mimetype))
-			return 1; /* through completion or error, close the socket */
-
-		/*
+struct libwebsocket *wsi,
+enum libwebsocket_callback_reasons reason, void *user,
+void *in, size_t len)
+{
+  //     Serial.println("callback_http()");
+  // WE ARE ALWAYS HITTING THIS POINT
+
+  char buf[256];
+  int n;
+
+  switch (reason) {
+
+  case LWS_CALLBACK_HTTP:
+    lwsl_notice("LWS_CALLBACK_HTTP");
+
+    for (n = 0; n < (sizeof(whitelist) / sizeof(whitelist[0]) - 1); n++)
+      if (in && strcmp((const char *)in, whitelist[n].urlpath) == 0)
+        break;
+
+    sprintf(buf, LOCAL_RESOURCE_PATH"%s", whitelist[n].urlpath);
+
+    if (libwebsockets_serve_http_file(context, wsi, buf, whitelist[n].mimetype))
+      return 1; /* through completion or error, close the socket */
+
+    /*
 		 * notice that the sending of the file completes asynchronously,
-		 * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
-		 * it's done
-		 */
-
-		break;
-
-	case LWS_CALLBACK_HTTP_FILE_COMPLETION:
-
-		lwsl_notice("LWS_FILE_COMPLETION");
-              return 1;
-
-
-	default:
-		break;
-	}
-
-	return 0;
+     		 * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
+     		 * it's done
+     		 */
+
+    break;
+
+  case LWS_CALLBACK_HTTP_FILE_COMPLETION:
+
+    lwsl_notice("LWS_FILE_COMPLETION");
+    return 1;
+
+
+  default:
+    break;
+  }
+
+  return 0;
 }

 /* lyt_protocol*/
 static int
 callback_lyt_protocol(struct libwebsocket_context *context,
-			struct libwebsocket *wsi,
-			enum libwebsocket_callback_reasons reason,
-					       void *user, void *in, size_t len)
-{
-
-        //Serial.println("callback_lyt_protocol()");
-        // WE ARE ALWAYS HITTING THIS POINT
-
-	int n;
-	unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 + LWS_SEND_BUFFER_POST_PADDING];
-	unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
-
-
-
-	switch (reason) {
-
-
-	case LWS_CALLBACK_SERVER_WRITEABLE:
-                sensor1 = analogRead(sensor1Pin);
-		n = sprintf((char *)p, "%d,%d", currentLED, sensor1);//colors);
-                Serial.print("Output Message:");
-                Serial.println(n);
-		n = libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT);
-		if (n < 0) {
-			lwsl_err("ERROR %d writing to socket\n", n);
-			return 1;
-		}
-
-		break;
-
-	case LWS_CALLBACK_RECEIVE:
-
-         processTouch((char*) in);
-
-
-		break;
-
-
-	default:
-		break;
-	}
-
-	return 0;
+struct libwebsocket *wsi,
+enum libwebsocket_callback_reasons reason,
+void *user, void *in, size_t len)
+{
+
+  //Serial.println("callback_lyt_protocol()");
+  // WE ARE ALWAYS HITTING THIS POINT
+
+  int n;
+  unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 + LWS_SEND_BUFFER_POST_PADDING];
+  unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
+
+  switch (reason) {
+
+
+  case LWS_CALLBACK_SERVER_WRITEABLE:
+    sensor1 = analogRead(sensor1Pin);
+    n = sprintf((char *)p, "%d,%d", currentLED, sensor1);//colors);
+    Serial.print("Output Message:");
+    Serial.println(n);
+    n = libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT);
+    if (n < 0) {
+      lwsl_err("ERROR %d writing to socket\n", n);
+      return 1;
+    }
+
+    break;
+
+  case LWS_CALLBACK_RECEIVE:
+
+    processTouch((char*) in);
+
+
+    break;
+
+
+  default:
+    break;
+  }
+
+  return 0;
 }

@@ -209,101 +234,105 @@
 /* list of supported protocols and callbacks */

 static struct libwebsocket_protocols protocols[] = {
-	/* first protocol must always be HTTP handler */
-
-	{
-		"http-only",		/* name */
-		callback_http,		/* callback */
-		0,			/* per_session_data_size */
-		0,			/* max frame size / rx buffer */
-	},
-	{
-		"touchserver-protocol",
-		callback_lyt_protocol,
-		0,
-		128,
-	},
-
-	{ NULL, NULL, 0, 0 } /* terminator */
+  /* first protocol must always be HTTP handler */
+
+  {
+    "http-only",		/* name */
+    callback_http,		/* callback */
+    0,			/* per_session_data_size */
+    0,			/* max frame size / rx buffer */
+  }
+  ,
+  {
+    "touchserver-protocol",
+    callback_lyt_protocol,
+    0,
+    128,
+  }
+  ,
+
+  {
+    NULL, NULL, 0, 0   } /* terminator */
 };

 void sighandler(int sig)
 {
-	force_exit = 1;
+  force_exit = 1;
 }

 static struct option options[] = {

-	{ NULL, 0, 0, 0 }
+  {
+    NULL, 0, 0, 0   }
 };

 int initWebsocket()
 {
-	int n = 0;
-	struct libwebsocket_context *context;
-	int opts = LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME;
-	char interface_name[128] = "wlan0";
-	const char *iface = NULL;
-
-	unsigned int oldus = 0;
-	struct lws_context_creation_info info;
-
-	int debug_level = 7;
-
-	memset(&info, 0, sizeof info);
-	info.port = 80;
-
-
-	signal(SIGINT, sighandler);
-    int syslog_options =  LOG_PID | LOG_PERROR;
-
-	/* we will only try to log things according to our debug_level */
-	setlogmask(LOG_UPTO (LOG_DEBUG));
-	openlog("lwsts", syslog_options, LOG_DAEMON);
-
-	/* tell the library what debug level to emit and to send it to syslog */
-	lws_set_log_level(debug_level, lwsl_emit_syslog);
-
-	info.iface = iface;
-	info.protocols = protocols;
-
-
-	info.extensions = libwebsocket_get_internal_extensions();
-
-
-  	info.ssl_cert_filepath = NULL;
-  	info.ssl_private_key_filepath = NULL;
-
-	info.gid = -1;
-	info.uid = -1;
-	info.options = opts;
-
-	context = libwebsocket_create_context(&info);
-	if (context == NULL) {
-		lwsl_err("libwebsocket init failed\n");
-		return -1;
-	}
-
-	n = 0;
-	while (n >= 0 && !force_exit) {
-		struct timeval tv;
-
-		gettimeofday(&tv, NULL);
-
-		if (((unsigned int)tv.tv_usec - oldus) > 50000) {
-			libwebsocket_callback_on_writable_all_protocol(&protocols[PROTOCOL_LYT]);
-			oldus = tv.tv_usec;
-
-		}
-		n = libwebsocket_service(context, 50);
-
-        loop(); // call  Arduino loop as we have taken over the execution flow :[
-
-
-	}
-	libwebsocket_context_destroy(context);
-	closelog();
-	return 0;
+  int n = 0;
+  struct libwebsocket_context *context;
+  int opts = LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME;
+  char interface_name[128] = "wlan0";
+  const char *iface = NULL;
+
+  unsigned int oldus = 0;
+  struct lws_context_creation_info info;
+
+  int debug_level = 7;
+
+  memset(&info, 0, sizeof info);
+  info.port = 80;
+
+
+  signal(SIGINT, sighandler);
+  int syslog_options =  LOG_PID | LOG_PERROR;
+
+  /* we will only try to log things according to our debug_level */
+  setlogmask(LOG_UPTO (LOG_DEBUG));
+  openlog("lwsts", syslog_options, LOG_DAEMON);
+
+  /* tell the library what debug level to emit and to send it to syslog */
+  lws_set_log_level(debug_level, lwsl_emit_syslog);
+
+  info.iface = iface;
+  info.protocols = protocols;
+
+
+  info.extensions = libwebsocket_get_internal_extensions();
+
+
+  info.ssl_cert_filepath = NULL;
+  info.ssl_private_key_filepath = NULL;
+
+  info.gid = -1;
+  info.uid = -1;
+  info.options = opts;
+
+  context = libwebsocket_create_context(&info);
+  if (context == NULL) {
+    lwsl_err("libwebsocket init failed\n");
+    return -1;
+  }
+
+  n = 0;
+  while (n >= 0 && !force_exit) {
+    struct timeval tv;
+
+    gettimeofday(&tv, NULL);
+
+    if (((unsigned int)tv.tv_usec - oldus) > 50000) {
+      libwebsocket_callback_on_writable_all_protocol(&protocols[PROTOCOL_LYT]);
+      oldus = tv.tv_usec;
+
+    }
+    n = libwebsocket_service(context, 50);
+
+    loop(); // call  Arduino loop as we have taken over the execution flow :[
+
+
+  }
+  libwebsocket_context_destroy(context);
+  closelog();
+  return 0;
 }

@@ -319,7 +348,7 @@
   //ip[0] = IPAddress(192, 168, 0, 11);
   //ip[1] = IPAddress(192, 168, 0, 12);
   //ip[2] = IPAddress(192, 168, 0, 13) ;
-
+
   pinMode(led, OUTPUT);
   digitalWrite(led, LOW);
   //for (int i=0; i < N_PANNEL; i++)
@@ -328,26 +357,26 @@
   //
   //}

-
+
   _udpIn.begin(3333);
   _udpIn.listen();
-
+
   //pthread magic !
-   pthread_t oscThread;
-   pthread_create(&oscThread,NULL,osc_loop,0);
-
+//  pthread_t oscThread;
+//  pthread_create(&oscThread,NULL,osc_loop,0);
+
   //pthread magic end
-
+
   Serial.println("Starting WebSocket");
   initWebsocket();
-
-
-}
-
-
+
+
+}
+
+/*
 int getNextMessage(OSCBundle &b, int* from)
 {
-
+
   int bytes  = _udpIn.parsePacket();
   if (bytes)
   {
@@ -358,14 +387,17 @@
       Serial.println("Overload warning !");
       Serial.println(bytes);
     }
-
+
     *from = -1;
-
+
     for (int i=0; i < N_PANNEL; i++)
     {
-        if (ip[i] == _udpIn.remoteIP()) { *from = i; break; }
-    }
-
+      if (ip[i] == _udpIn.remoteIP()) {
+        *from = i;
+        break;
+      }
+    }
+
     if (bytes >0)
     {
       if (buffer[0] == '#') b.fill(buffer,bytes);
@@ -381,67 +413,69 @@
           delete[] buffer;
           return 0;
         }
-
+
       }
     }
-
+
     delete[] buffer;
     delay(10);
     if (!b.hasError())
     {
-
+
       return 1;
-      }
-
+    }
+
     Serial.println("OSC Message seems to have Error ");
     return 0;
-
+
   }
   return 0;
 }
-
+*/

 //This is an hackish way of processing OSC Message
 // There is no synchronization between the main thread and this one
 // So... If it looks bad on the phone, don't use it :)
+/*
 void *osc_loop(void *dummy)
 {
-
+
   while (!force_exit) {
-  //OSCBundle b;
-  //OSCMessage *m;
-
-  /*int from = -1;
-  while (getNextMessage(b,&from))
-  {
-    if (m = b.getOSCMessage(0))
-    {
-      from = m->getInt(0);
-      if (from != -1) {
-
-       int index = 8*from;
-      sprintf(colors + index+1,"%06x",m->getInt(1));
-      if (from != N_PANNEL -1) colors[index+7] = ',';
-     // sleep(5);
-
-      }
-    }
-    b.empty();
-  }
-  */
-  sensor1 = analogRead(sensor1Pin);
-
-  sleep(500);
-  }
-
+    //OSCBundle b;
+    //OSCMessage *m;
+
+//    int from = -1;
+//     while (getNextMessage(b,&from))
+//     {
+//     if (m = b.getOSCMessage(0))
+//     {
+//     from = m->getInt(0);
+//     if (from != -1) {
+//
+//     int index = 8*from;
+//     sprintf(colors + index+1,"%06x",m->getInt(1));
+//     if (from != N_PANNEL -1) colors[index+7] = ',';
+//     // sleep(5);
+//
+//     }
+//     }
+//     b.empty();
+//     }
+
+    sensor1 = analogRead(sensor1Pin);
+
+    sleep(500);
+  }
+
   return 0;
 }
-
+*/

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


Clean up refactoring.

Clean up refactoring.

--- examples/VWI/CosaVWIclient/CosaVWIclient.ino
+++ examples/VWI/CosaVWIclient/CosaVWIclient.ino
@@ -103,7 +103,7 @@
   Watchdog::begin();
   RTC::begin();

-  // Start virtual wire interface in extended mode; transceiver
+  // Start virtual wire interface in enhanced mode and use the transceiver
   VWI::begin(ADDR, SPEED);
   trx.begin();
 }
@@ -116,9 +116,9 @@
   statistics.update(nr);

   // Send message with battery voltage and statistics every 15 messages
-  if (stat.sent % 15 == 0) {
+  if (statistics.sent % 15 == 0) {
     statistics.voltage = AnalogPin::bandgap(1100);
-    nr = trx.send(&stat, sizeof(stat), STAT_CMD);
+    nr = trx.send(&statistics, sizeof(statistics), STAT_CMD);
     statistics.update(nr);
   }


Removed outdated alltogethertest example sketch

--- examples/alltogethertest/alltogethertest.ino
+++ examples/alltogethertest/alltogethertest.ino
@@ -1,63 +0,0 @@
-#include <Arduino.h>
-#include <Wire.h>
-#include <ArdusatSDK.h>
-#include <util_freeMemory.h> // within SensorSDK library
-
-void setup(void)
-{
-  Serial.begin(9600);
-
-  obcl_begin();	// starts on board communication layer
-  obcl_scan();	// scans the available I2C sensors
-
-  if (!beginOrientationSensor()) {
-    Serial.println("can't init 9dof");
-  }
-
-  if (!beginTemperatureSensor()) {
-    Serial.println("can't init temperature sensor");
-  }
-
-  if (!beginLuminositySensor()) {
-    Serial.println("can't init lum sensor");
-  }
-
-  if (!beginInfraredTemperatureSensor()) {
-    Serial.println("can't init IR sensor");
-  }
-
-  if (!beginUVLightSensor()) {
-    Serial.println("can't init UV sensor");
-  }
-}
-
-void loop(void)
-{
-  temperature_t temp;
-  readTemperature(&temp);
-  Serial.println(temperatureToJSON("temp", &temp));
-
-  temperature_t irtemp;
-  readInfraredTemperature(&irtemp);
-  Serial.println(temperatureToJSON("infrared", &irtemp));
-
-  luminosity_t lum;
-  readLuminosity(&lum);
-  Serial.println(luminosityToJSON("luminosity", &lum));
-
-  uvlight_t uv;
-  readUVLight(&uv);
-  Serial.println(uvlightToJSON("uv", &uv));
-
-  acceleration_t accel;
-  readAcceleration(&accel);
-  Serial.println(accelerationToJSON("acceleration", &accel));
-
-  orientation_t orient;
-  readOrientation(&orient);
-  Serial.println(orientationToJSON("orientation", &orient));
-
-  //Serial.println(anythingFloatToJSON("memory", "bytes", util_freeMemory(), 0));
-
-  delay(1000);
-}


Switch to new interval utility

Switch to new interval utility

--- examples/quadcopter/quadcopter.ino
+++ examples/quadcopter/quadcopter.ino
@@ -110,10 +110,8 @@
 }

 void sendTelemetry(){
-    static uint32_t sendTime = millis();
-    if(sendTime < millis()){
-        sendTime += 50;
-
+    static auto timer = Interval::every(50);
+    if(timer()){
         float voltage  = float(analogRead(67)/1024.l*5.l*10.1f);

         using namespace Protocol;


Debug message

Debug message

--- examples/UbidotsSaveValue/UbidotsSaveValue.ino
+++ examples/UbidotsSaveValue/UbidotsSaveValue.ino
@@ -32,7 +32,7 @@

 void setup() {
   Serial.begin(115200);
-  client.setDebug(true);
+  client.setDebug(true); // Set true to make available debug messages
 }

 void loop() {


maybe last?

maybe last?

--- little-switches/arduino/galoppo/galoppo.ino
+++ little-switches/arduino/galoppo/galoppo.ino
@@ -14,7 +14,8 @@
 #define tamburo 2

 int volo = 400;
-int ciclo = 200;
+int attesaAppoggio = 75;
+int attesaAllungo = 150;

 PS2Keyboard keyboard;
@@ -66,12 +67,16 @@
   Serial.print("weight: ");
   Serial.println(w);

+  volo *= w;
+  attesaAppoggio *= w;
+  attesaAllungo *= w;
+
   if (keyboard.available()) {

     char c = keyboard.read();

     if (c == '1') {
-      galoppo(w);
+      galoppo();
     }
     else if (c == 'p') {
       digitalWrite(piede,HIGH);
@@ -97,22 +102,22 @@
   }
 }

-void galoppo(float v) {
+void galoppo() {
   for (int i=0; i<10; i++) {
   digitalWrite(zampaPS,HIGH);
-  delay(75);
+  delay(attesaAppoggio);
   digitalWrite(zampaPD,HIGH);
-  delay(150);
+  delay(attesaAllungo);
   digitalWrite(zampaAS,HIGH);
-  delay(75);
+  delay(attesaAppoggio);
   digitalWrite(zampaAD,HIGH);
-  delay(400);
+  delay(volo);
   digitalWrite(zampaPS,LOW);
-  delay(75);
+  delay(attesaAppoggio);
   digitalWrite(zampaPD,LOW);
-  delay(150);
+  delay(attesaAllungo);
   digitalWrite(zampaAS,LOW);
-  delay(150);
+  delay(attesaAppoggio);
   digitalWrite(zampaAD,LOW);
   }
 }


'n' != '\n'. d'Oh!

'n' != '\n'. d'Oh!

--- GeheimTuer.ino
+++ GeheimTuer.ino
@@ -416,7 +416,7 @@
     case 'r':
       motorEnable();
       doorState = doorBlocked; break;
-    case 'n':
+    case '\n':
       Serial.print(F("\r\n")); break;
   }
 }


Menu now just adds empty

Menu now just adds empty

--- Weight.ino
+++ Weight.ino
@@ -71,8 +71,8 @@

 //MENU
 char* EMPTY = "                ";
-char* menu[] = {"Calibrate       " ,"Tare           ", "Beersize       ", "Keg Weight      "};
-unsigned int lastItem = 4;
+char* menu[] = {"Calibrate" ,"Tare", "+Beersize", "Keg Weight"};
+unsigned int lastItem = 3;
 unsigned int menuMarker = 0;

 //GUI VARIABLES
@@ -114,7 +114,6 @@
   return btnNONE;  // when all others fail, return this...
 }

-
 int getButtonPressed() {
   lcd_key = read_LCD_buttons();  // read the buttons
   unsigned long now = millis();
@@ -277,6 +276,13 @@
   }
 }

+void printMenuItem(char* &item) {
+   char textItem[50];
+   strcpy(textItem, item);
+   strcat(textItem, EMPTY);
+   lcd.print(textItem);
+}
+
 void printMenu() {
   if (!printGUI){
     return;
@@ -285,21 +291,20 @@
   printMenuMarker(up);
   if (!up) {
     lcd.setCursor(1, 0);
-    lcd.print(menu[menuMarker]);
+    printMenuItem(menu[menuMarker]);
     if (menuMarker < lastItem) {
       lcd.setCursor(1, 1);
-      lcd.print(menu[menuMarker + 1]);
+      printMenuItem(menu[menuMarker + 1]);
     } else {
       lcd.setCursor(1, 1);
       lcd.print(EMPTY);
     }
   } else {
     lcd.setCursor(1, 0);
-    lcd.print(menu[menuMarker - 1]);
+    printMenuItem(menu[menuMarker - 1]);
     lcd.setCursor(1, 1);
-    lcd.print(menu[menuMarker]);
-  }
-
+    printMenuItem(menu[menuMarker]);
+  }
 }

 void doTare() {


Re-request config if no handlers available

--- home-node/home-node.ino
+++ home-node/home-node.ino
@@ -15,6 +15,7 @@
 ProfileHandler* handlers[MAX_HANDLERS];
 char clientId[13];
 char* configTopic;
+unsigned long lastBroadcast = 0;

 WiFiClient wifiClient;
 MQTTClient client(512); //max package size
@@ -66,9 +67,8 @@
       client.subscribe(configTopic);

       delay(100);
-      //Announce ourselves, hopefully someone will reply and will start doing fun stuff
-      Serial.print("Broadcasting..");
-      client.publish("broadcast", clientId);
+
+      checkForConfig(true);
     } else {
       Serial.print("failed, rc=");
       Serial.print(client.connected());
@@ -78,6 +78,27 @@
     }
   }
 };
+
+void checkForConfig(bool force) {
+
+  if ( ! force && handlersCount != 0 ) {
+    return;
+  }
+
+  const unsigned long now = millis();
+
+  //Prevent locking if millis() overflows
+  if (now < lastBroadcast ) {
+    lastBroadcast = now;
+  }
+
+  if ( force || lastBroadcast == 0 || (now - lastBroadcast > 10000) ) {
+    //Announce ourselves, hopefully someone will reply and will start doing fun stuff
+    lastBroadcast = millis();
+    Serial.print("Broadcasting..");
+    client.publish("broadcast", clientId);
+  }
+}

 void loop() {
   // Checks for network and reconnects if it isn't present
@@ -90,6 +111,8 @@
   // Gives the mqtt client cycles to process
   client.loop();

+  checkForConfig(false);
+
   // Gives the handlers cycles to process their on-going tasks
   for(int i = 0 ; i < handlersCount  ; i++) {
     handlers[i]->loop();


LoaderTest: Update comments

LoaderTest: Update comments

--- LoaderTest/LoaderTest.ino
+++ LoaderTest/LoaderTest.ino
@@ -1,5 +1,5 @@

-// Concept tester for loading programs into the
+// Concept tester for interfacing with the
 // Gigatron TTL microcomputer
 // Marcel van Kervinck / Chris Lord
 // May 2018
@@ -18,6 +18,7 @@
 // For example:
 //   python sendGt1.py life3.gt1

+// Todo/idea list:
 // XXX Try higher than 9600 transfer rates again
 // XXX Wild idea: let the ROM communicate back by modulating vPulse
 // XXX Hardware: Put reset line on the DB9 jack
@@ -33,6 +34,10 @@
   #include "Lines.h"    // Draw randomized lines
 };

+/*
+ *  Link to Gigatron using its serial game controller port
+ */
+
 // Arduino AVR    Gigatron Schematic Controller PCB
 // Uno     Name   OUT bit            CD4021     74HC595 (U39)
 // ------- ------ -------- --------- ---------- ----------------
@@ -40,17 +45,7 @@
 // Pin 12  PORTB4 7 vSync  SER_LATCH  0 PAR/SER None
 // Pin 11  PORTB3 6 hSync  SER_PULSE 10 CLOCK   11 SRCLK 12 RCLK

-// Keyboard
-// Pin  4  PS/2 Data
-// Pin  3  PS/2 Clock
-
-#include <PS2Keyboard.h> // Install from the Arduino IDE's Library Manager
-
-// Pins for PS/2 keyboard (Arduino Uno)
-const int keyboardClockPin = 3;  // Pin 2 or 3 for IRQ
-const int keyboardDataPin  = 4;  // Any available free pin
-
-PS2Keyboard keyboard;
+// Game controller button mapping. The kit's controller gives inverted signals.
 #define buttonRight  1
 #define buttonLeft   2
 #define buttonDown   4
@@ -60,10 +55,32 @@
 #define buttonB      64
 #define buttonA      128

+/*
+ *  Loader protocol
+ */
+
 #define N 60 // Payload bytes per transmission frame
-
 byte checksum; // Global is simplest

+/*
+ *  PS/2 keyboard hookup to Arduino
+ */
+
+#include <PS2Keyboard.h> // Install from the Arduino IDE's Library Manager
+
+PS2Keyboard keyboard;
+
+// Pins for PS/2 keyboard (Arduino Uno)
+const int keyboardClockPin = 3;  // Pin 2 or 3 for IRQ
+const int keyboardDataPin  = 4;  // Any available free pin
+
+// Keyboard
+// Pin  4  PS/2 Data
+// Pin  3  PS/2 Clock
+
+/*
+ *  Setup runs once when the Arduino wakes up
+ */
 void setup()
 {
   // Enable output pin (pins are set to input by default)
@@ -84,6 +101,9 @@
   prompt();
 }

+/*
+ *  Loop runs repeatedly
+ */
 void loop()
 {
   static char line[20];
@@ -134,10 +154,11 @@
   while (millis() < timeout)
     T[(PINB >> PORTB3) & 3]++; // capture PORTB3 and PORTB4

-  float S = T[0] + T[1] + T[2] + T[3];
-  float vSync = (T[0] + T[1]) / ( 8 * S / 521); // Gigatron VGA
-  float hSync = (T[0] + T[2]) / (96 * S / 800); // Default VGA
-
+  float S = T[0] + T[1] + T[2] + T[3] + .1; // Avoid zero division (pedantic)
+  float vSync = (T[0] + T[1]) / ( 8 * S / 521); // Adjusted vSync signal
+  float hSync = (T[0] + T[2]) / (96 * S / 800); // Standard hSync signal
+
+  // Check that vSync and hSync characteristics look normal
   return 0.95 <= vSync && vSync <= 1.20 && 0.95 <= hSync && hSync <= 1.05;
 }


Made sleep state a single slowly-pulsing pixel in the center of the grid.

--- xy.ino
+++ xy.ino
@@ -102,14 +102,14 @@
 void setup() {
    int t;
    unsigned long desiredDuration = 3600 * 1000; // total desired run time, milliseconds
-
-  strip.begin();
-  // clearStrip();
-  strip.show();
-  setupRotatingColorAxes();
-
-  while (millis() < desiredDuration)
-     rotatingColorAxes();
+
+   strip.begin();
+   // clearStrip();
+   strip.show();
+   setupRotatingColorAxes();
+
+   while (millis() < desiredDuration)
+      rotatingColorAxes();

    clearStrip();
 }
@@ -138,11 +138,35 @@
 {
    struct point pt;
    struct rgbTriple rgb;
-
-   rgb = hsl2rgb( 5, 1.0, 0.1);
+   float dLightness   = 1.0 / 300.0;
+   float exponent     = 1.0;
+   float minLightness = 0.03;
+   float maxLightness = 0.9;
+   int delayTime      = 5;
+   int hue;
+   float lightness;
+   float lit;
+
    pt = {2,2 } ;
-   strip.setPixelColor( point2seq( pt, org, gridSize), Color( rgb.r, rgb.g, rgb.b));
-   strip.show();
+   for (hue = 0; hue < 360; hue++)
+   {
+      for (lightness = minLightness; lightness <= maxLightness; lightness += dLightness)
+      {
+         lit = pow( lightness, exponent);
+         rgb = hsl2rgb( hue, 1.0, lit);
+         strip.setPixelColor( point2seq( pt, org, gridSize), Color( rgb.r, rgb.g, rgb.b));
+         strip.show();
+         delay( delayTime);
+      }
+      for (lightness = maxLightness; lightness >= minLightness; lightness -= dLightness)
+      {
+         lit = pow( lightness, exponent);
+         rgb = hsl2rgb( hue, 1.0, lit);
+         strip.setPixelColor( point2seq( pt, org, gridSize), Color( rgb.r, rgb.g, rgb.b));
+         strip.show();
+         delay( delayTime);
+      }
+   }
 }


Added isInitialized for redundancy

Added isInitialized for redundancy

--- src/microController/microController.ino
+++ src/microController/microController.ino
@@ -8,7 +8,7 @@
 #define X1_STEP_PIN          54 //X1->X
 #define X1_DIR_PIN           55
 #define X1_ENABLE_PIN        38
-
+
 #define X2_STEP_PIN          46 //X2->Z
 #define X2_DIR_PIN           48
 #define X2_ENABLE_PIN        62
@@ -53,11 +53,11 @@

 #define OOB_MOD_LENGTH       0.16   //Out of bound mod length for when ball is near edge of table

-#define X_MIN_OFFSET         920  //Steps from min X end stop to edge of pool table
-#define X_MAX_OFFSET         940  //Steps from max X end stop to edge of pool table
+#define X_MIN_OFFSET         950  //Steps from min X end stop to edge of pool table
+#define X_MAX_OFFSET         885  //Steps from max X end stop to edge of pool table
 #define Y_MIN_OFFSET         2600 //Steps from min Y end stop to edge of pool table
-#define Y_MAX_OFFSET         2745 //Steps from max Y end stop to edge of pool table
-#define R_OFFSET             230  //Steps from R initialization point to zero angle
+#define Y_MAX_OFFSET         2785 //Steps from max Y end stop to edge of pool table
+#define R_OFFSET             242  //Steps from R initialization point to zero angle

 #define MICRODELAY           800  //Pause between stepper motor steps
 #define SLOWSTEP             300  //300 is normal slow, 0 is off
@@ -90,6 +90,8 @@

 int previousTime = millis(); //Used for button de-bounce
 int currentTime;
+
+int isInitialized = 0; //Has the system finished initialization?

 // Setup  /////////////////////////////////////////////////////////////////////////////////

@@ -171,6 +173,7 @@
   currentR = 0;
   MoveXYR();
   currentR = 0;
+  isInitialized = 2;

 }

@@ -265,7 +268,7 @@

 void MapCoordinates(double serialX, double serialY, double serialR) //Map from real coordinates to step coordinates
 {
-
+
   serialX -= OOB_MOD_LENGTH*cos(serialR);
   serialY -= OOB_MOD_LENGTH*sin(serialR);

@@ -479,6 +482,8 @@
 void UserButton3() //User turn, machine turn
 {

+  if(isInitialized == 1) return;
+  if(isInitialized == 0) isInitialized = 1;
   if(userThreeHeld) return;

   userThreeHeld = true;


Make Screen a class

Make Screen a class

--- moros/moros.ino
+++ moros/moros.ino
@@ -55,26 +55,24 @@
   }
 };

-typedef struct {
-  unsigned int cs_pin;
-  unsigned int dc_pin;
-  unsigned int rst_pin;
+class Screen {
+public:
   TFT *tft;
-} Screen;
+  Screen(unsigned int cs_pin, unsigned int dc_pin, unsigned int rst_pin) {
+    tft = new TFT(cs_pin, dc_pin, rst_pin);
+  };
+  void init() {
+    tft->begin();
+    tft->background(0,0,0);
+    tft->stroke(255,255,255);
+    tft->fill(0,0,0);
+    tft->setTextSize(DISPLAY_FONT_SIZE);
+  };
+};

-Screen screens[2] = {
-  {
-    .cs_pin = 4,
-    .dc_pin = 5,
-    .rst_pin = 6,
-    .tft = NULL
-  },
-  {
-    .cs_pin = 7,
-    .dc_pin = 8,
-    .rst_pin = 9,
-    .tft = NULL
-  }
+Screen *screens[2] = {
+  new Screen(4,5,6),
+  new Screen(7,8,9)
 };

 typedef struct {
@@ -96,25 +94,19 @@
     .display_width_chars = 0,
     .clock = new Clock,
     .button = &buttons[0],
-    .screen = &screens[0]
+    .screen = screens[0]
   },
   {
     .display_time = {},
     .display_width_chars = 0,
     .clock = new Clock,
     .button = &buttons[1],
-    .screen = &screens[1]
+    .screen = screens[1]
   }
 };

 void init_player(Player *p) {
-  Screen *screen = p->screen;
-  screen->tft = new TFT(screen->cs_pin, screen->dc_pin, screen->rst_pin);
-  screen->tft->begin();
-  screen->tft->background(0,0,0);
-  screen->tft->stroke(255,255,255);
-  screen->tft->fill(0,0,0);
-  screen->tft->setTextSize(DISPLAY_FONT_SIZE);
+  p->screen->init();
   Clock *clock = p->clock;
   clock->time_remaining_ms = INITIAL_TIME_MS;
   clock->last_update_ms = 0;


Updated to transmit encoder count

Updated to transmit encoder count

--- RotaryEncoderAnalog/RotaryEncoderAnalog.ino
+++ RotaryEncoderAnalog/RotaryEncoderAnalog.ino
@@ -1,8 +1,8 @@
 #include <arduino2.h>

-#define c_EncoderPinA A0
-#define c_EncoderPinB A1
-#define c_EncoderPinZ A2
+#define c_EncoderPinA A1
+#define c_EncoderPinB A2
+#define c_EncoderPinZ A0

 #define d_EncoderPinZ 2
 #define d_EncoderPinA 3
@@ -12,7 +12,7 @@
 #define d_EncoderInterruptA 1

 volatile bool _EncoderBSet;
-volatile long _EncoderTicks = 0;
+volatile int _EncoderTicks = 0;
 long _last = 0;
 double _speed = 0;
 long _CentreCount = 0;
@@ -34,7 +34,6 @@
   digitalWrite(A2, HIGH);

   attachInterrupt(d_EncoderInterruptA, HandleInterruptA, RISING);
-  attachInterrupt(d_EncoderInterruptZ, HandleInterruptZ, RISING);
 }

 void loop()
@@ -45,9 +44,10 @@
   uint32_t start = micros();
   while ( Serial.available() == 0 )
   {
-    Serial.write(analogRead(A0)/4);
-    Serial.write(analogRead(A1)/4);
-    Serial.write(analogRead(A2)/4);
+    Serial.write(analogRead(c_EncoderPinA)/4);
+    Serial.write(analogRead(c_EncoderPinB)/4);
+    //Serial.write(analogRead(c_EncoderPinZ)/4);
+    send_ticks();
     n++;
   }
   Serial.flush();
@@ -64,8 +64,20 @@

   // and adjust counter + if A leads B
     _EncoderTicks += _EncoderBSet ? -1 : +1;
-
-    long us = micros();
-    if(_last != 0) _speed = 5000.0f/(double)(us-_last);
-    _last = us;
 }
+
+char *int2str( int num ) {
+    static char retnum[11];       // Enough for 20 digits plus NUL from a 64-bit uint.
+    sprintf( retnum, "%l", num );
+    return retnum;
+}
+
+void send_ticks ()
+{
+  // get access to the float as a byte-array:
+  byte * data = (byte *) &_EncoderTicks;
+  // write the data to the serial
+  Serial.write (data, 2);
+  //_EncoderTicks++;
+}
+