calculate number lengths

calculate number lengths

--- main/main.ino
+++ main/main.ino
@@ -1,15 +1,9 @@
 #include <mcp_can.h>
 #include <mcp_can_dfs.h>
-
-
-#include <global.h>
 #include <LiquidCrystal.h>
-#include <math.h>

 //RS,EN,DB4,DB5,DB6,DB7
 LiquidCrystal lcd(14, 3, 4, 5, 6, 7);
-
-int brightness = 255;

 byte fill1[8] = {
   B10000,
@@ -96,17 +90,9 @@
 EngineVariable engine_tcr   = {"TCR", 0.0, 0.0, 0.0, 50.0, 1};
 EngineVariable engine_lct   = {"LCT", 0.0, 0.0, 0.0, 100.0, 1};

-long startTime;
-long endTime;
-
-double afr;
-double tgt;
-
 unsigned long interval = 100;
 unsigned long lastMillis = 0;
 unsigned long currentMillis = 0;
-
-int messageReceived;

 unsigned long goodDataCount = 0;
 unsigned long badDataCount = 0;
@@ -124,7 +110,7 @@
   lcd.createChar(4, fill5);

   lcd.begin(20, 4);
-  lcd.print(engine_bat.shortLabel);
+  lcd.print(engine_rpm.shortLabel);
   lcd.setCursor(0, 2);
   lcd.print(engine_afr.shortLabel);

@@ -135,131 +121,171 @@
           Serial.println(" Init CAN BUS Shield again");
           delay(100);
       }
-  Serial.println("CAN BUS Shield init ok!");
+  Serial.println("COMM OK");
 }

 void loop() {
+  load_from_can();
+
   currentMillis = millis();
   if(currentMillis - lastMillis >= interval) {
     lastMillis = currentMillis;
-
-    if(engine_bat.currentValue != engine_bat.previousValue) {
+    if(engine_rpm.currentValue != engine_rpm.previousValue) {
       lcd.setCursor(4, 0);
-      if(((int)engine_bat.currentValue % 100) < ((int)engine_bat.previousValue % 100)) {
+      if(is_current_value_shorter(engine_rpm)) {
         lcd.print("     ");
         lcd.setCursor(4, 0);
       }
-      lcd.print(engine_bat.currentValue, engine_bat.decimalPlaces);
-      draw_bar(engine_bat, 1);
-    }
-
+      lcd.print(engine_rpm.currentValue, engine_rpm.decimalPlaces);
+      draw_bar(engine_rpm, 1);
+    }
     if(engine_afr.currentValue != engine_afr.previousValue) {
       lcd.setCursor(4, 2);
       lcd.print(engine_afr.currentValue);
       draw_bar(engine_afr, 3);
     }
-
-
-  }
-
+  }
+}
+
+void load_from_can() {
   unsigned char len = 0;
   unsigned char buf[8];
-
-
   if(CAN_MSGAVAIL == CAN.checkReceive())            // check if data coming
   {
-        CAN.readMsgBuf(&len, buf);    // read data,  len: data length, buf: data buf
-
-        unsigned int canId = CAN.getCanId();
+    CAN.readMsgBuf(&len, buf);    // read data,  len: data length, buf: data buf
+
+    unsigned int canId = CAN.getCanId();
+
+    switch(canId) {
+      case 1512:
+        engine_map.previousValue = engine_map.currentValue;
+        engine_map.currentValue = ((buf[0] * 256) + buf[1]) / 10.0;
+
+        engine_rpm.previousValue = engine_rpm.currentValue;
+        engine_rpm.currentValue = buf[2] * 256 + buf[3];
+
+        engine_clt.previousValue = engine_clt.currentValue;
+        engine_clt.currentValue = (buf[4] * 256 + buf[5]) / 10.0;
+
+        engine_tps.previousValue = engine_tps.currentValue;
+        engine_tps.currentValue = (buf[6] * 256 + buf[7]) / 10.0;

-        switch(canId) {
-          case 1512:
-            engine_map.previousValue = engine_map.currentValue;
-            engine_map.currentValue = ((buf[0] * 256) + buf[1]) / 10.0;
-
-            engine_rpm.previousValue = engine_rpm.currentValue;
-            engine_rpm.currentValue = buf[2] * 256 + buf[3];
-
-            engine_clt.previousValue = engine_clt.currentValue;
-            engine_clt.currentValue = (buf[4] * 256 + buf[5]) / 10.0;
-
-            engine_tps.previousValue = engine_tps.currentValue;
-            engine_tps.currentValue = (buf[6] * 256 + buf[7]) / 10.0;
-
-            break;
-          case 1513:
-            engine_pw1.previousValue = engine_pw1.currentValue;
-            engine_pw1.currentValue = (buf[0] * 256 + buf[1]) / 1000.0;
-
-            engine_pw2.previousValue = engine_pw2.currentValue;
-            engine_pw2.currentValue = (buf[2] * 256 + buf[3]) / 1000.0;
-
-            engine_iat.previousValue = engine_iat.currentValue;
-            engine_iat.currentValue = (buf[4] * 256 + buf[5]) / 10.0;
-
-            engine_adv.previousValue = engine_adv.currentValue;
-            engine_adv.currentValue = (buf[6] * 256 + buf[7]) / 10.0;
-
-            break;
-          case 1514:
-            engine_tgt.previousValue = engine_tgt.currentValue;
-            engine_tgt.currentValue = (double)buf[0] / 10.0;
-
-            engine_afr.previousValue = engine_afr.currentValue;
-            engine_afr.currentValue = (double)buf[1] / 10.0;
-
-            engine_ego.previousValue = engine_ego.currentValue;
-            engine_ego.currentValue = (buf[2] * 256 + buf[3]) / 10.0;
-
-            engine_egt.previousValue = engine_egt.currentValue;
-            engine_egt.currentValue = (buf[4] * 256 + buf[5]) / 10.0;
-
-            engine_pws.previousValue = engine_pws.currentValue;
-            engine_pws.currentValue = (buf[6] * 256 + buf[7]) / 1000.0;
-
-            break;
-          case 1515:
-            engine_bat.previousValue = engine_bat.currentValue;
-            engine_bat.currentValue = (buf[0] * 256 + buf[1]) / 10.0;
-
-            //not tested
-            engine_sr1.previousValue = engine_sr1.currentValue;
-            engine_sr1.currentValue = (buf[2] * 256 + buf[3]) / 10.0;
-
-            //not tested
-            engine_sr2.previousValue = engine_sr2.currentValue;
-            engine_sr2.currentValue = (buf[4] * 256 + buf[5]) / 10.0;
-
-            //not tested
-            engine_knk.previousValue = engine_knk.currentValue;
-            engine_knk.currentValue = (buf[6] * 256) / 10.0;
-
-            break;
-          case 1516:
-            //not tested
-            engine_vss.previousValue = engine_vss.currentValue;
-            engine_vss.currentValue = (buf[0] * 256 + buf[1]) / 10.0;
-
-            //not tested
-            engine_tcr.previousValue = engine_tcr.currentValue;
-            engine_tcr.currentValue = (buf[2] * 256 + buf[3]) / 10.0;
-
-            engine_lct.previousValue = engine_lct.currentValue;
-            engine_lct.previousValue = (buf[4] * 256 + buf[5]) / 10.0;
-
-            break;
-          default:
-            //do nothing
-            break;
-        }
-  }
-
-
+        break;
+      case 1513:
+        engine_pw1.previousValue = engine_pw1.currentValue;
+        engine_pw1.currentValue = (buf[0] * 256 + buf[1]) / 1000.0;
+
+        engine_pw2.previousValue = engine_pw2.currentValue;
+        engine_pw2.currentValue = (buf[2] * 256 + buf[3]) / 1000.0;
+
+        engine_iat.previousValue = engine_iat.currentValue;
+        engine_iat.currentValue = (buf[4] * 256 + buf[5]) / 10.0;
+
+        engine_adv.previousValue = engine_adv.currentValue;
+        engine_adv.currentValue = (buf[6] * 256 + buf[7]) / 10.0;
+
+        break;
+      case 1514:
+        engine_tgt.previousValue = engine_tgt.currentValue;
+        engine_tgt.currentValue = (double)buf[0] / 10.0;
+
+        engine_afr.previousValue = engine_afr.currentValue;
+        engine_afr.currentValue = (double)buf[1] / 10.0;
+
+        engine_ego.previousValue = engine_ego.currentValue;
+        engine_ego.currentValue = (buf[2] * 256 + buf[3]) / 10.0;
+
+        engine_egt.previousValue = engine_egt.currentValue;
+        engine_egt.currentValue = (buf[4] * 256 + buf[5]) / 10.0;
+
+        engine_pws.previousValue = engine_pws.currentValue;
+        engine_pws.currentValue = (buf[6] * 256 + buf[7]) / 1000.0;
+
+        break;
+      case 1515:
+        engine_bat.previousValue = engine_bat.currentValue;
+        engine_bat.currentValue = (buf[0] * 256 + buf[1]) / 10.0;
+
+        //not tested
+        engine_sr1.previousValue = engine_sr1.currentValue;
+        engine_sr1.currentValue = (buf[2] * 256 + buf[3]) / 10.0;
+
+        //not tested
+        engine_sr2.previousValue = engine_sr2.currentValue;
+        engine_sr2.currentValue = (buf[4] * 256 + buf[5]) / 10.0;
+
+        //not tested
+        engine_knk.previousValue = engine_knk.currentValue;
+        engine_knk.currentValue = (buf[6] * 256) / 10.0;
+
+        break;
+      case 1516:
+        //not tested
+        engine_vss.previousValue = engine_vss.currentValue;
+        engine_vss.currentValue = (buf[0] * 256 + buf[1]) / 10.0;
+
+        //not tested
+        engine_tcr.previousValue = engine_tcr.currentValue;
+        engine_tcr.currentValue = (buf[2] * 256 + buf[3]) / 10.0;
+
+        engine_lct.previousValue = engine_lct.currentValue;
+        engine_lct.previousValue = (buf[4] * 256 + buf[5]) / 10.0;
+
+        break;
+      default:
+        //do nothing
+        break;
+    }
+  }
+}
+
+bool is_current_value_shorter(EngineVariable engine) {
+  int currentLength;
+  if(engine.currentValue >= 10000) {
+    currentLength = 5;
+  }
+  else if(engine.currentValue >= 1000) {
+    currentLength = 4;
+  }
+  else if(engine.currentValue >= 100) {
+    currentLength = 3;
+  }
+  else if(engine.currentValue >= 10) {
+    currentLength = 2;
+  }
+  else {
+    currentLength = 1;
+  }
+  if(engine.decimalPlaces > 0) {
+    currentLength++;
+    currentLength+= engine.decimalPlaces;
+  }
+
+  int previousLength;
+  if(engine.previousValue >= 10000) {
+    previousLength = 5;
+  }
+  else if(engine.previousValue >= 1000) {
+    previousLength = 4;
+  }
+  else if(engine.previousValue >= 100) {
+    previousLength = 3;
+  }
+  else if(engine.previousValue >= 10) {
+    previousLength = 2;
+  }
+  else {
+    previousLength = 1;
+  }
+  if(engine.decimalPlaces > 0) {
+    previousLength++;
+    previousLength += engine.decimalPlaces;
+  }
+
+  return currentLength < previousLength;
 }

 void draw_bar(EngineVariable engineVar, int row) {
-
-
   if(engineVar.currentValue == engineVar.previousValue) {
     //relax homeboy
   }
@@ -290,8 +316,6 @@
     if(partialBars > 0) {
       lcd.write(byte(partialBars - 1));
     }
-  }
-
-
-}
-
+  }
+}
+


debounce button

debounce button

--- main/main.ino
+++ main/main.ino
@@ -156,14 +156,15 @@
 bool octoModeIndex = 0;
 bool inError = false;

-bool currentModeButton = 1; //default to high, 0 when pressed
+bool currentModeButton = 1;
 bool previousModeButton = 1;
+unsigned long modeButtonMillis = 0;

 MCP_CAN CAN(SPI_CS_PIN);

 void setup() {

-  currentMode = octo;
+  currentMode = quad;

   pinMode(LED_PIN, OUTPUT);
   pinMode(MODE_PIN, INPUT_PULLUP);
@@ -226,6 +227,11 @@
   }

   lcd.clear();
+
+  /*currentModeButton = digitalRead(MODE_PIN);
+  previousModeButton = currentModeButton;
+  Serial.println(currentModeButton);
+  Serial.println(previousModeButton);*/
 }

 void loop() {
@@ -257,9 +263,18 @@

   previousModeButton = currentModeButton;
   currentModeButton = digitalRead(MODE_PIN);
+  /*Serial.println("=====");
+  Serial.println(currentModeButton);
+  Serial.println(previousModeButton);*/
   if(currentModeButton != previousModeButton) {
     if(currentModeButton == 0) {
+      modeButtonMillis = currentMillis;
       next_mode();
+    }
+    else {
+      if((currentMillis - modeButtonMillis) < 250) {
+        currentModeButton = 0;
+      }
     }
   }


Now the logistic growth function is working.  This is very nearly complete.  Now I just need to add the music functionality for the alarm. Also, the non-volatile ram that's usually associated with DS1307 chips does not appear to be working at all.  That could be because I'm using a DS3231 chip instead and the breakout board may not have the same memory chip.

--- SunriseAlarm.ino
+++ SunriseAlarm.ino
@@ -180,7 +180,7 @@
 const int TimeButton = 9;
 const int TimeLED = 13;
 const int OffButton = A0;
-const int AlarmEnabledButton = 5;
+const int AlarmEnabledSwitch = 5;

 #define NUM_LED 32
 #define LED_PIN 6
@@ -224,7 +224,7 @@
 uint8_t raw_d = 0x5E;
 uint8_t dot_bit = 0x80;

-RTC_DS1307 RTC;
+RTC_DS3231 RTC;
 unsigned long synchronized_clock_millis;
 ClockTime synchronized_clock_time;
 ClockTime current_clock_time;
@@ -385,6 +385,23 @@
 {
   uint16_t stepNumber = (totalDimmerSteps*milliseconds)/millisecondsIn30Minutes;
   linearBrightOfStep(stepNumber);
+}
+
+void logisticBrightOfStep(uint16_t step)
+{
+  float p = ((float)step)/((float)totalDimmerSteps);
+  float L = 1.0;
+  float k = 20.0;
+  float x0 = 0.5;
+  float logisticP = L/(1+exp(-k*(p-x0)));
+  uint16_t logisticStep = logisticP*totalDimmerSteps;
+  linearBrightOfStep(logisticStep);
+}
+
+void logisticBrightOfMilliseconds(unsigned long milliseconds)
+{
+  uint16_t stepNumber = (totalDimmerSteps*milliseconds)/millisecondsIn30Minutes;
+  logisticBrightOfStep(stepNumber);
 }

 void turnLightOn() {
@@ -529,6 +546,7 @@
   //pinMode(LEDpinA,OUTPUT); digitalWrite(LEDpinA,0);
   pinMode(AlarmButton,INPUT_PULLUP);
   pinMode(TimeButton,INPUT_PULLUP);
+  pinMode(AlarmEnabledSwitch, INPUT_PULLUP);
   pinMode(OffButton,INPUT);
   pinMode(AlarmLED, OUTPUT);
   pinMode(TimeLED, OUTPUT);
@@ -573,12 +591,13 @@
 }

 unsigned long alarmStartMillis = 0;
-const unsigned lightUpdateInterval = 200;
+const unsigned lightUpdateInterval = 50;
 unsigned long lastLightUpdate = millis();
 void updateLight() {
   if (!isTimeNow(lastLightUpdate,lightUpdateInterval)) {
     return;
   }
+  if (digitalRead(AlarmEnabledSwitch) == LOW) return;
   ClockTime current = current_clock_time;
   int32_t seconds = secondsBtwDates(current,startTime);
   if ((seconds < 0) || (seconds >= maxTime)) {
@@ -595,14 +614,14 @@
   if (!alarmActive)
   {
     setColorForSunRise();
-    alarmStartMillis = millis();
+    alarmStartMillis = static_cast<unsigned long>(millis()-1000*seconds);
     alarmActive = true;
   }
   if (seconds >= thirtyminutes) {
     linearBrightOfStep(totalDimmerSteps);
     return;
   }
-  linearBrightOfMilliseconds(millis()-alarmStartMillis);
+  logisticBrightOfMilliseconds(static_cast<unsigned long>(millis()-alarmStartMillis));
 }

@@ -749,7 +768,7 @@
   }
   else {
     unsigned long temp = totalDimmerSteps - totalDimmerSteps*delta/finalMillis;
-    linearBrightOfStep(temp);
+    logisticBrightOfStep(temp);
   }
 }


Code re-organization

Code re-organization

--- Event_Printer/Event_Printer.ino
+++ Event_Printer/Event_Printer.ino
@@ -39,7 +39,7 @@
 void setup()
 {
   Serial.begin(115200);
-  setup_CAN_Bus_Filters();
+  init_CAN_bus();
   init_display();
 }

@@ -56,86 +56,7 @@
   tft.fillScreen(ST7735_BLACK);
 }

-void print_status()
-{
-  String text = "";
-
-  text += "Throttle: ";
-  text += motorcycle_state.throttle_position;
-  text += "%\n";
-
-  text += "Heated Grips: ";
-  if ( motorcycle_state.heated_grips == K25_Heated_Grips_State_off ) text += "OFF";
-  else if ( motorcycle_state.heated_grips == K25_Heated_Grips_State_low ) text += "LOW";
-  else if ( motorcycle_state.heated_grips == K25_Heated_Grips_State_high ) text += "HIGH";
-  else text += "Unknown";
-  text += "\n";
-
-  text += "Turn Signals: ";
-  if ( motorcycle_state.turn_signals == K25_Turn_Signals_State_off ) text += "OFF";
-  else if ( motorcycle_state.turn_signals == K25_Turn_Signals_State_left ) text += "LEFT";
-  else if ( motorcycle_state.turn_signals == K25_Turn_Signals_State_right ) text += "RIGHT";
-  else if ( motorcycle_state.turn_signals == K25_Turn_Signals_State_both ) text += "HAZARDS";
-  else text += "Unknown";
-  text += "\n";
-
-  text += "High Beam: ";
-  if ( motorcycle_state.high_beam == K25_High_Beam_State_off ) text += "OFF";
-  else if ( motorcycle_state.high_beam == K25_High_Beam_State_on ) text += "ON";
-  else text += "Unknown";
-  text += "\n";
-
-  /* INFO BUTTON CURRENTLY NOT WORKING
-  text += "Info Button: ";
-  if ( motorcycle_state.info_button == K25_Info_Button_State_short_press ) text += "SHORT";
-  else if ( motorcycle_state.info_button == K25_Info_Button_State_long_press ) text += "LONG";
-  else text += "Unknown";
-  text += "\n";
-  */
-
-  text += "Clutch: ";
-  if ( motorcycle_state.clutch == K25_Clutch_Lever_State_out ) text += "OUT";
-  else if ( motorcycle_state.clutch == K25_Clutch_Lever_State_in ) text += "IN";
-  else text += "Unknown";
-  text += "\n";
-
-  text += "Brakes: ";
-  if ( motorcycle_state.brake_levers == K25_Brake_Lever_State_none ) text += "NONE";
-  else if ( motorcycle_state.brake_levers == K25_Brake_Lever_State_front ) text += "FRONT";
-  else if ( motorcycle_state.brake_levers == K25_Brake_Lever_State_rear ) text += "REAR";
-  else text += "Unknown";
-  text += "\n";
-
-  text += "ABS: ";
-  if ( motorcycle_state.abs_system == K25_ABS_State_off ) text += "OFF";
-  else if ( motorcycle_state.abs_system == K25_ABS_State_on ) text += "ON";
-  else text += "Unknown";
-  text += "\n";
-
-  text += "ALS: ";
-  if ( motorcycle_state.als == K25_ALS_State_dark ) text += "DARK";
-  else if ( motorcycle_state.als == K25_ALS_State_light ) text += "LIGHT";
-  else text += "Unknown";
-  text += "\n";
-
-#if PRINT_TO_SERIAL_CONSOLE
-  Serial.println(text);
-#endif
-
-#if PRINT_TO_TFT
-  tft.fillScreen(ST7735_BLACK);
-  draw_text(&text, ST7735_WHITE);
-#endif
-}
-
-void draw_text(String *text, uint16_t color) {
-  tft.setCursor(0, 0);
-  tft.setTextColor(color);
-  tft.setTextWrap(true);
-  tft.print(text->c_str());
-}
-
-void setup_CAN_Bus_Filters()
+void init_CAN_bus()
 {
   while (CAN_OK != CAN.begin(CAN_500KBPS)) {
     DEBUG_PRINT_LN("Failed to initialize CAN");
@@ -218,3 +139,82 @@
         }
      }
 }
+
+void print_status()
+{
+  String text = "";
+
+  text += "Throttle: ";
+  text += motorcycle_state.throttle_position;
+  text += "%\n";
+
+  text += "Heated Grips: ";
+  if ( motorcycle_state.heated_grips == K25_Heated_Grips_State_off ) text += "OFF";
+  else if ( motorcycle_state.heated_grips == K25_Heated_Grips_State_low ) text += "LOW";
+  else if ( motorcycle_state.heated_grips == K25_Heated_Grips_State_high ) text += "HIGH";
+  else text += "Unknown";
+  text += "\n";
+
+  text += "Turn Signals: ";
+  if ( motorcycle_state.turn_signals == K25_Turn_Signals_State_off ) text += "OFF";
+  else if ( motorcycle_state.turn_signals == K25_Turn_Signals_State_left ) text += "LEFT";
+  else if ( motorcycle_state.turn_signals == K25_Turn_Signals_State_right ) text += "RIGHT";
+  else if ( motorcycle_state.turn_signals == K25_Turn_Signals_State_both ) text += "HAZARDS";
+  else text += "Unknown";
+  text += "\n";
+
+  text += "High Beam: ";
+  if ( motorcycle_state.high_beam == K25_High_Beam_State_off ) text += "OFF";
+  else if ( motorcycle_state.high_beam == K25_High_Beam_State_on ) text += "ON";
+  else text += "Unknown";
+  text += "\n";
+
+  /* INFO BUTTON CURRENTLY NOT WORKING
+  text += "Info Button: ";
+  if ( motorcycle_state.info_button == K25_Info_Button_State_short_press ) text += "SHORT";
+  else if ( motorcycle_state.info_button == K25_Info_Button_State_long_press ) text += "LONG";
+  else text += "Unknown";
+  text += "\n";
+  */
+
+  text += "Clutch: ";
+  if ( motorcycle_state.clutch == K25_Clutch_Lever_State_out ) text += "OUT";
+  else if ( motorcycle_state.clutch == K25_Clutch_Lever_State_in ) text += "IN";
+  else text += "Unknown";
+  text += "\n";
+
+  text += "Brakes: ";
+  if ( motorcycle_state.brake_levers == K25_Brake_Lever_State_none ) text += "NONE";
+  else if ( motorcycle_state.brake_levers == K25_Brake_Lever_State_front ) text += "FRONT";
+  else if ( motorcycle_state.brake_levers == K25_Brake_Lever_State_rear ) text += "REAR";
+  else text += "Unknown";
+  text += "\n";
+
+  text += "ABS: ";
+  if ( motorcycle_state.abs_system == K25_ABS_State_off ) text += "OFF";
+  else if ( motorcycle_state.abs_system == K25_ABS_State_on ) text += "ON";
+  else text += "Unknown";
+  text += "\n";
+
+  text += "ALS: ";
+  if ( motorcycle_state.als == K25_ALS_State_dark ) text += "DARK";
+  else if ( motorcycle_state.als == K25_ALS_State_light ) text += "LIGHT";
+  else text += "Unknown";
+  text += "\n";
+
+#if PRINT_TO_SERIAL_CONSOLE
+  Serial.println(text);
+#endif
+
+#if PRINT_TO_TFT
+  tft.fillScreen(ST7735_BLACK);
+  draw_text(&text, ST7735_WHITE);
+#endif
+}
+
+void draw_text(String *text, uint16_t color) {
+  tft.setCursor(0, 0);
+  tft.setTextColor(color);
+  tft.setTextWrap(true);
+  tft.print(text->c_str());
+}


Made it dance a little more.

Made it dance a little more.

--- LED/Array_Blink/Array_Blink.ino
+++ LED/Array_Blink/Array_Blink.ino
@@ -1,18 +1,22 @@
-const unsigned long BLINK_MILLIS = 100;
+const unsigned long BLINK_MILLIS = 50;
 const int NUM_LEDS = 6;
-const int LEDS[NUM_LEDS] = {13, 12, 11, 10, 9, 8};
+const int LEDS[NUM_LEDS] = {13, 12, 8, 7, 4, 2};
+//                          0   1   2  3  4  5

 int led(int ledNumber)
 {
   return LEDS[ledNumber];
 }

-void blink(int ledNumber, int millisOn)
+void blink(int ledNumber, int millisOn, int times)
 {
-  int pin = led(ledNumber);
-  digitalWrite(pin, HIGH);
-  delay(millisOn);
-  digitalWrite(pin, LOW);
+  for(int i = 0; i < times; i++)
+  {
+    int pin = led(ledNumber);
+    digitalWrite(pin, HIGH);
+    delay(millisOn);
+    digitalWrite(pin, LOW);
+  }
 }

 void setup(void)
@@ -27,12 +31,13 @@
 {
   for(int i = 0; i < NUM_LEDS; i++)
   {
-    blink(i, BLINK_MILLIS);
+    blink(i, BLINK_MILLIS, 2);
     delay(BLINK_MILLIS);
-    blink(i, BLINK_MILLIS);
+  }
+
+  for(int i = NUM_LEDS - 1; i >= 0; i--)
+  {
+    blink(i, BLINK_MILLIS, 2);
     delay(BLINK_MILLIS);
-    blink(i, BLINK_MILLIS);
-
-    delay(1000);
   }
 }


comentando o envio de sinais para testar se a parte botao+led_status funciona corretamente, e funciona

--- codigo.ino
+++ codigo.ino
@@ -18,7 +18,7 @@
 #include <IRremote.h>

 int RECV_PIN = 11;
-int FIRST_BUTTON_PIN = 2;
+int FIRST_BUTTON_PIN = 12;
 //================================================================================================================================
 // int SECOND_BUTTON_PIN = 3; //@Lanchinho : nao necessariamente neste pino/ casa, pode ser qlqer outra que esteja livre
 // int THIRD_BUTTON_PIN = 4;  //@Lanchinho: Vou deixar todas as cagadas, digo alterações feitas por mim separadas por um "========="
@@ -206,8 +206,8 @@

 //============================================================
-int lastBtnStateOfBtn2;
-int lastBtnStateOfBtn3;
+// int lastBtnStateOfBtn2;
+// int lastBtnStateOfBtn3;
 //============================================================

 void loop()
@@ -223,24 +223,24 @@
     if (lastButtonState == HIGH && firstButtonState == LOW)
     {
         Serial.println("Released");
-        irrecv.enableIRIn(); // Re-enable receiver
+        // irrecv.enableIRIn(); // Re-enable receiver
     }

     if (firstButtonState)
     {
         Serial.println("Pressed, sending");
         digitalWrite(STATUS_PIN, HIGH);
-        sendCode(lastButtonState == firstButtonState);
+        // sendCode(lastButtonState == firstButtonState);
         digitalWrite(STATUS_PIN, LOW);
         delay(50); // Wait a bit between retransmissions
     }
-    else if (irrecv.decode(&results))
-    {
-        digitalWrite(STATUS_PIN, HIGH);
-        storeCode(&results);
-        irrecv.resume(); // resume receiver
-        digitalWrite(STATUS_PIN, LOW);
-    }
+    // else if (irrecv.decode(&results))
+    // {
+    //     digitalWrite(STATUS_PIN, HIGH);
+    //     storeCode(&results);
+    //     irrecv.resume(); // resume receiver
+    //     digitalWrite(STATUS_PIN, LOW);
+    // }
     lastButtonState = firstButtonState;

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


comentando os outros botoes, vamos fazer com um so primeiro, e colocando variavel do ultimo botao apertado

--- codigo.ino
+++ codigo.ino
@@ -20,23 +20,32 @@
 int RECV_PIN = 11;
 int FIRST_BUTTON_PIN = 2;
 //================================================================================================================================
-int SECOND_BUTTON_PIN = 3; //@Lanchinho : nao necessariamente neste pino/ casa, pode ser qlqer outra que esteja livre
-int THIRD_BUTTON_PIN = 4;  //@Lanchinho: Vou deixar todas as cagadas, digo alterações feitas por mim separadas por um "========="
+// int SECOND_BUTTON_PIN = 3; //@Lanchinho : nao necessariamente neste pino/ casa, pode ser qlqer outra que esteja livre
+// int THIRD_BUTTON_PIN = 4;  //@Lanchinho: Vou deixar todas as cagadas, digo alterações feitas por mim separadas por um "========="
 //================================================================================================================================
 int STATUS_PIN = 13;

 IRrecv irrecv(RECV_PIN);
-IRsend irsend;
+IRsend irsend; //lembrar de por PWM 3 como o IR LED

 decode_results results;
+
+//=====================
+//VARIAVEIS GLOBAIS
+//=====================
+int ultimo_botao_press = FIRST_BUTTON_PIN; //por default o ultimo botao pressionado vai ser o primeiro
+//=====================
+//VARIAVEIS GLOBAIS - FIM
+//=====================
+

 void setup()
 {
     Serial.begin(9600);
     irrecv.enableIRIn(); // Start the receiver
     pinMode(FIRST_BUTTON_PIN, INPUT);
-    pinMode(SECOND_BUTTON_PIN, INPUT);
-    pinMode(THIRD_BUTTON_PIN, INPUT);
+    // pinMode(SECOND_BUTTON_PIN, INPUT);
+    // pinMode(THIRD_BUTTON_PIN, INPUT);
     pinMode(STATUS_PIN, OUTPUT);
 }

@@ -205,12 +214,12 @@
 {
     // If button pressed, send the code.
     int firstButtonState = digitalRead(FIRST_BUTTON_PIN);
-
+
     //========================================================
-    int secondButtonState = digitalRead(SECOND_BUTTON_PIN);
-    int thirdButtonState = digitalRead(THIRD_BUTTON_PIN);
+    // int secondButtonState = digitalRead(SECOND_BUTTON_PIN);
+    // int thirdButtonState = digitalRead(THIRD_BUTTON_PIN);
     //========================================================
-
+
     if (lastButtonState == HIGH && firstButtonState == LOW)
     {
         Serial.println("Released");
@@ -233,60 +242,60 @@
         digitalWrite(STATUS_PIN, LOW);
     }
     lastButtonState = firstButtonState;
-
+
 //==========================================================================
 //Btn2
-    if (lastBtnStateOfBtn2 == HIGH && secondButtonState == LOW)
-    {
-        Serial.println("Released");
-        irrecv.enableIRIn(); // Re-enable receiver
-    }
-
-    if (secondButtonState)
-    {
-        Serial.println("Pressed, sending");
-        digitalWrite(STATUS_PIN, HIGH);
-        sendCode(lastBtnStateOfBtn2 == secondButtonState);
-        digitalWrite(STATUS_PIN, LOW);
-        delay(50); // Wait a bit between retransmissions
-    }
-    else if (irrecv.decode(&results))
-    {
-        digitalWrite(STATUS_PIN, HIGH);
-        storeCode(&results);
-        irrecv.resume(); // resume receiver
-        digitalWrite(STATUS_PIN, LOW);
-    }
-    lastBtnStateOfBtn2 = lastBtnStateOfBtn2;
-
-    //Btn 3
-    if (lastBtnStateOfBtn3 == HIGH && thirdButtonState == LOW)
-    {
-        Serial.println("Released");
-        irrecv.enableIRIn(); // Re-enable receiver
-    }
-
-    if (thirdButtonState)
-    {
-        Serial.println("Pressed, sending");
-        digitalWrite(STATUS_PIN, HIGH);
-        sendCode(lastBtnStateOfBtn3 == thirdButtonState);
-        digitalWrite(STATUS_PIN, LOW);
-        delay(50); // Wait a bit between retransmissions
-    }
-    else if (irrecv.decode(&results))
-    {
-        digitalWrite(STATUS_PIN, HIGH);
-        storeCode(&results);
-        irrecv.resume(); // resume receiver
-        digitalWrite(STATUS_PIN, LOW);
-    }
-    lastBtnStateOfBtn3 = thirdButtonState;
-//===========================================================
-
-
-
-
-
-
-}
+    // if (lastBtnStateOfBtn2 == HIGH && secondButtonState == LOW)
+    // {
+    //     Serial.println("Released");
+    //     irrecv.enableIRIn(); // Re-enable receiver
+    // }
+
+    // if (secondButtonState)
+    // {
+    //     Serial.println("Pressed, sending");
+    //     digitalWrite(STATUS_PIN, HIGH);
+    //     sendCode(lastBtnStateOfBtn2 == secondButtonState);
+    //     digitalWrite(STATUS_PIN, LOW);
+    //     delay(50); // Wait a bit between retransmissions
+    // }
+    // else if (irrecv.decode(&results))
+    // {
+    //     digitalWrite(STATUS_PIN, HIGH);
+    //     storeCode(&results);
+    //     irrecv.resume(); // resume receiver
+    //     digitalWrite(STATUS_PIN, LOW);
+    // }
+    // lastBtnStateOfBtn2 = lastBtnStateOfBtn2;
+
+    // //Btn 3
+    // if (lastBtnStateOfBtn3 == HIGH && thirdButtonState == LOW)
+    // {
+    //     Serial.println("Released");
+    //     irrecv.enableIRIn(); // Re-enable receiver
+    // }
+
+    // if (thirdButtonState)
+    // {
+    //     Serial.println("Pressed, sending");
+    //     digitalWrite(STATUS_PIN, HIGH);
+    //     sendCode(lastBtnStateOfBtn3 == thirdButtonState);
+    //     digitalWrite(STATUS_PIN, LOW);
+    //     delay(50); // Wait a bit between retransmissions
+    // }
+    // else if (irrecv.decode(&results))
+    // {
+    //     digitalWrite(STATUS_PIN, HIGH);
+    //     storeCode(&results);
+    //     irrecv.resume(); // resume receiver
+    //     digitalWrite(STATUS_PIN, LOW);
+    // }
+    // lastBtnStateOfBtn3 = thirdButtonState;
+//===========================================================
+
+
+
+
+
+
+}


added micro-forward-space

added micro-forward-space

--- beanWheelwriterControl/beanWheelwriterControl.ino
+++ beanWheelwriterControl/beanWheelwriterControl.ino
@@ -94,58 +94,58 @@
                   charCount = printAllChars(buffer, bufferPos, bytesRead, bytesToPrint, charCount);
               }
           }
+      }
+      // button for testing
+      byte digital1 = digitalRead(d1);
+      if (digital1 == 0) {
+        forwardSpaces(5);
+        //fastText("this is really fast");
+        //send_letter(0b000000001); // 'a'
+        //send_letter(0b001011001); // 'b'
+        //send_letter(0b000000100); // 'm'
+        //send_letter();
+
+        //print_str("aaaaaaaaaaaa");

-          byte digital1 = digitalRead(d1);
-          if (digital1 == 0) {
-            forwardSpaces(5);
-            //fastText("this is really fast");
-            //send_letter(0b000000001); // 'a'
-            //send_letter(0b001011001); // 'b'
-            //send_letter(0b000000100); // 'm'
-            //send_letter();
-
-            //print_str("aaaaaaaaaaaa");
-
-            /*print_str("This is the symphony that schubert never finished!");
-            send_return(50);
-
-            print_str("\"the quick brown fox jumps over the lazy dog.\"");
-            send_return(46);*/
-
-            /*print_str("ABC");
-            send_return(3);
-
-            print_str("55555");
-            send_return(5);
-
-            print_str("1234567890");
-            send_return(10);
-
-            print_str("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
-            send_return(26);
-
-            print_str("1234567890");
-            send_return(10);
-
-            print_str(",./?");
-            send_return(4);*/
-
-            //print_str("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
-            //send_return(52);
-
-            //print_str("done.");
-            //send_return(5);
-
-            //print_strln("The quick brown fox jumps over the lazy dog.");
-            /*
-            sendByteOnPin(0b00000000);
-            delayMicroseconds(60);*/
-            /////////////
-            //PORTD &= 0b11111011;
-            Bean.setLed(255, 0, 0);
-            Bean.sleep(10);
-            Bean.setLed(0,0,0);
-          }
+        /*print_str("This is the symphony that schubert never finished!");
+        send_return(50);
+
+        print_str("\"the quick brown fox jumps over the lazy dog.\"");
+        send_return(46);*/
+
+        /*print_str("ABC");
+        send_return(3);
+
+        print_str("55555");
+        send_return(5);
+
+        print_str("1234567890");
+        send_return(10);
+
+        print_str("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
+        send_return(26);
+
+        print_str("1234567890");
+        send_return(10);
+
+        print_str(",./?");
+        send_return(4);*/
+
+        //print_str("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
+        //send_return(52);
+
+        //print_str("done.");
+        //send_return(5);
+
+        //print_strln("The quick brown fox jumps over the lazy dog.");
+        /*
+        sendByteOnPin(0b00000000);
+        delayMicroseconds(60);*/
+        /////////////
+        //PORTD &= 0b11111011;
+        Bean.setLed(255, 0, 0);
+        Bean.sleep(10);
+        Bean.setLed(0,0,0);
       }
       Bean.sleep(10);
 }
@@ -405,8 +405,6 @@
     sendByte(0b000000011);
     sendByte(letter);
     sendByte(0b000001010);
-
-
     delay(LETTER_DELAY); // before next character
 }

@@ -444,12 +442,12 @@
     sendByte(0b000000110);
     sendByte(0b000000000);
     sendByte(0b000001010);
-    sendByte(0b100100001);
+    /*sendByte(0b100100001);

     // send one more byte but don't wait explicitly for the response
     // of 0b000000100
-    sendByteOnPin(0b000001011);
+    sendByteOnPin(0b000001011);*/
     delay(LETTER_DELAY * 2); // a bit more time
 }

@@ -493,13 +491,15 @@
     }

     sendByte(0b000000101);
-    sendByte(0b010010000); //
+    sendByte(0b010010000);
+
+    /*
     sendByte(0b100100001);

     // send one more byte but don't wait explicitly for the response
     // of 0b001010000
-    sendByteOnPin(0b000001011);
+    sendByteOnPin(0b000001011);*/

     // wait for carriage
     delay(CARRIAGE_WAIT_BASE + CARRIAGE_WAIT_MULTIPLIER * numChars);
@@ -537,12 +537,13 @@
     sendByte(0b000000110);
     sendByte(0b000000000);
     sendByte(0b000000010);
+    /*
     sendByte(0b100100001);

     // send one more byte but don't wait explicitly for the response
     // of 0b000000100
-    sendByteOnPin(0b000001011);
+    sendByteOnPin(0b000001011);*/
 }

 void forwardSpaces(int num_spaces) {
@@ -557,12 +558,17 @@
     sendByte(0b100100001);
     sendByte(0b000000110);

-    //sendByte(0b010000001);
     sendByte(0b010000000);
-
-    sendByte(0b001111100);
+    //sendByte(0b001111100);
+    sendByte(0b000000010);
+}
+
+void spin() {
     sendByte(0b100100001);
     sendByte(0b000000111);
+}
+
+void unknownCommand() {
     sendByte(0b100100001);
     sendByte(0b000001001);
     sendByte(0b010000000);


Including Servo.h make the sketch compile with the library under the Arduino GUI

--- src/Full_decoder.ino
+++ src/Full_decoder.ino
@@ -1,3 +1,5 @@
+#include <Servo.h>
+
 /*
 If serial output is desired uncommment the #undef line. For production, i.e.
 without computer connected this line should be commented out.


complete pseudocode and state map

complete pseudocode and state map

--- src/colorpicker_v0/colorpicker_v0.ino
+++ src/colorpicker_v0/colorpicker_v0.ino
@@ -1,5 +1,5 @@
 /*
-
+]
                                             initialize
                                                 v
                             --------------->  ready <--------------------------
@@ -19,24 +19,22 @@
     previewColor = black
 ready:
   enter:
-    set animation to pulse single
+    Animation.setAnim(picker_pulse_single); // fade in and out a sinlge pixel, rainbow if this->color == black
   update:
-    pulse neopixels (color cycle if none set)
-    button.update
-    if button.fallingEdge {
-      Sensor.enable()
-    }
-    if button.risingEdge {
-      Sensor.disable()
-    }
     if ( Sensor.color() != this->color && Sensor.color() != black ) {
       this->previewColor = Sensor.color();
       goto state preview
     }
+    button.update
+    if button.risingEdge {
+      Sensor.disable()
+    } else if button.fallingEdge {
+      Sensor.enable()
+    }

 preview:
   enter:
-    set animation sequence(picker_init_preview, solid) (fill display with this->previewColor, then hold preview color)
+    Animation.setSequence(picker_init_preview, picker_solid) (fill display with this->previewColor, then hold preview color)
       (animation internally sets animation.transitioning = true)
     reset timeout timer
   update:
@@ -45,13 +43,17 @@
     }
     button.update
     if button.pressed = false && timeout.expired {
-      goto reset
+      Animation.setSequence(picker_reset, picker_pulse_single) // clear display and set back to single pixel of this->color
+      goto state ready
     }
     // todo problem here.  on falling edge, set reset timer for 250 millis.  enable or confirm after 250 millis
     if button.fallingEdge {
       if button pushed for more than 250 millis {
-        if button.isDoubleClick {
-          goto confirm
+        if button.isDoubleClick { // confirm selection
+          this->color = this->previewColor
+          Network.publish(this->color) // initiate network sendWithAck event; Maybe include some retry logic?
+          Animation.setSequence(picker_transmit, picker_pulse_single) // perform cool "broadcasting" animation, then settle in to a single pixel
+          goto state ready
         } else {
           Sensor.enable()
           set animation to solid
@@ -64,35 +66,15 @@
       reset timeout timer
     }

-
-  reset:
-    enter:
-      set animation to reset (clear display and set back to this->color)
-        (animation internally sets animation.transitioning = true)
-    update:
-      clearing display, going back to single pixel
-      if !animation.Transitioning() { // updated when display has been emptied to only a single pixel
-        goto ready
-      }
-
-  confirm
-    enter:
-      this->color = this->previewColor
-      Network.publish(this->color) // initiate network sendWithAck event
-      set animation to picker_confirm
-    update:
-
-
-
-
-
-
   loop{
     Animation.update()
     Sensor.update()
     Network.update()
-    state.update()
+    picker.update() // execute update() for current state
   }
+
+
+

   // set a sequence of transitional animatinos, ending with a stable one.


Update ReadSensorData.ino

Update ReadSensorData.ino

--- examples/ReadSensorData.ino
+++ examples/ReadSensorData.ino
@@ -1,4 +1,5 @@
-#include <I2CSoilMoistureSensor.h>
+// This #include statement was automatically added by the Particle IDE.
+#include "I2CSoilMoistureSensor/I2CSoilMoistureSensor.h"

 I2CSoilMoistureSensor sensor;

@@ -7,8 +8,8 @@

   sensor.begin(); // reset sensor
   delay(1000); // give some time to boot up
-  string address = sensor.getAddress();
-  string version = sensor.getVersion();
+  String address = String(sensor.getAddress());
+  String version = String(sensor.getVersion());

   // publish sensors info
   Particle.publish("setup", "I2C Soil Moisture Sensor Address: " + address, 300, PRIVATE);
@@ -16,8 +17,8 @@
 }

 void loop() {
-  float moisvalue = sensor.getCapacitance()
-  float tempvalue = sensor.getTemperature()/(float)10
+  float moisvalue = sensor.getCapacitance();
+  float tempvalue = sensor.getTemperature()/(float)10;

   String s_moisvalue = String(moisvalue);
   String s_tempvalue = String(tempvalue);


Sketch: Move visual feedback after data sent

--- sketchbook/thcheckinhw/thcheckinhw.ino
+++ sketchbook/thcheckinhw/thcheckinhw.ino
@@ -216,6 +216,11 @@
       announce += ',';
       announce += checkInOut;
       Serial.println(announce);
+      if (checkInOut == CHECKIN) {
+        fastBlink(checkInLED, 50, 20);
+      } else if (checkInOut == CHECKOUT) {
+        fastBlink(checkOutLED, 50, 20);
+      }
     }
   }
   delay(10);
@@ -227,10 +232,8 @@
     checkInState = digitalRead(checkInButton);
     checkOutState = digitalRead(checkOutButton);
     if (checkInState == HIGH) {
-      fastBlink(checkInLED, 50, 20);
       return(CHECKIN);
     } else if (checkOutState == HIGH) {
-      fastBlink(checkOutLED, 50, 20);
       return(CHECKOUT);
     }
     if (checkInOutCounter % 10 == 0) {


use a normal buffer

use a normal buffer

--- examples/analogReadIntervalTimer/analogReadIntervalTimer.ino
+++ examples/analogReadIntervalTimer/analogReadIntervalTimer.ino
@@ -21,8 +21,7 @@

-#include "ADC.h"
-#include "RingBuffer.h"
+#include <ADC.h>
 // and IntervalTimer
 #include <IntervalTimer.h>

@@ -40,8 +39,16 @@

 IntervalTimer timer0, timer1; // timers

-RingBuffer *buffer0 = new RingBuffer; // buffers to store the values
-RingBuffer *buffer1 = new RingBuffer;
+#define BUFFER_SIZE 500
+
+uint16_t buffer_0[BUFFER_SIZE];
+uint16_t buffer_0_count = 0xffff;
+uint32_t delta_time_0 = 0;
+uint16_t buffer_1[BUFFER_SIZE];
+uint16_t buffer_1_count = 0xffff;
+uint32_t delta_time_1 = 0;
+
+elapsedMillis timed_read_elapsed;

 int startTimerValue0 = 0, startTimerValue1 = 0;

@@ -108,16 +115,9 @@
             Serial.println("Timer1 setup failed");
     }

-    if(!buffer0->isEmpty()) { // read the values in the buffer
-        Serial.print("Read pin 0: ");
-        Serial.println(buffer0->read()*3.3/adc->adc0->getMaxValue());
-        //Serial.println("New value!");
-    }
-    if(!buffer1->isEmpty()) { // read the values in the buffer
-        Serial.print("Read pin 1: ");
-        Serial.println(buffer1->read()*3.3/adc->adc0->getMaxValue());
-        //Serial.println("New value!");
-    }
+    // See if we have a timed read test that finished.
+    if (delta_time_0) printTimedADCInfo(ADC_0, buffer_0, delta_time_0);
+    if (delta_time_1) printTimedADCInfo(ADC_0, buffer_1, delta_time_1);

     if (Serial.available()) {
         c = Serial.read();
@@ -138,6 +138,30 @@
     delayMicroseconds(readPeriod);
 }

+void printTimedADCInfo(uint8_t adc_num, uint16_t *buffer, uint32_t &delta_time) {
+  uint32_t min_value = 0xffff;
+  uint32_t max_value = 0;
+  uint32_t sum = 0;
+  for (int i = 0; i < BUFFER_SIZE; i++) {
+    if (buffer[i] < min_value) min_value = buffer[i];
+    if (buffer[i] > max_value) max_value = buffer[i];
+    sum += buffer[i];
+  }
+  float average_value = (float)sum / BUFFER_SIZE; // get an average...
+  float sum_delta_sq = 0;
+  for (int i = 0; i < BUFFER_SIZE; i++) {
+    int delta_from_center = (int)buffer[i] - average_value;
+    sum_delta_sq += delta_from_center * delta_from_center;
+  }
+  int rms = sqrt(sum_delta_sq / BUFFER_SIZE);
+  Serial.printf("ADC:%d delta time:%d freq:%d - min:%d max:%d avg:%d rms:%d\n", adc_num,
+                delta_time, (1000 * BUFFER_SIZE) / delta_time,
+                min_value, max_value, (int)average_value, rms);
+
+  delta_time = 0;
+
+}
+
 // This function will be called with the desired frequency
 // start the measurement
 // in my low-res oscilloscope this function seems to take 1.5-2 us.
@@ -177,13 +201,19 @@
     // add value to correct buffer
     if(pin==readPin0) {
         digitalWriteFast(ledPin+3, HIGH);
-        buffer0->write(adc->adc0->readSingle());
+        uint16_t adc_val = adc->adc0->readSingle();
+        if (buffer_0_count < BUFFER_SIZE) {
+          buffer_0[buffer_0_count++] = adc_val;
+          if (buffer_0_count == BUFFER_SIZE) delta_time_0 = timed_read_elapsed;
+        }
         digitalWriteFast(ledPin+3, LOW);
+
     } else if(pin==readPin1) {
         digitalWriteFast(ledPin+4, HIGH);
-        buffer1->write(adc->adc0->readSingle());
-        if(adc->adc0->isConverting()) {
-            digitalWriteFast(LED_BUILTIN, 1);
+        uint16_t adc_val = adc->adc0->readSingle();
+        if (buffer_1_count < BUFFER_SIZE) {
+          buffer_1[buffer_1_count++] = adc_val;
+          if (buffer_1_count == BUFFER_SIZE) delta_time_1 = timed_read_elapsed;
         }
         digitalWriteFast(ledPin+4, LOW);
     } else { // clear interrupt anyway
@@ -201,4 +231,8 @@

     //digitalWriteFast(ledPin+2, !digitalReadFast(ledPin+2));

+    #if defined(__IMXRT1062__)  // Teensy 4.0
+        asm("DSB");
+    #endif
+
 }


minor fix

minor fix

--- server/hook_api/arduino_client/arduino_client.ino
+++ server/hook_api/arduino_client/arduino_client.ino
@@ -11,9 +11,9 @@
     ; // wait for serial port to connect. Needed for Leonardo only
   }
   mainServo.attach(7);
+  mainServo.write(80);
+  delay(30);
   mainServo.write(180);
-  delay(30);
-  mainServo.write(80);
   delay(30);
 }


Code cleanup

Code cleanup

--- otto/otto.ino
+++ otto/otto.ino
@@ -4,6 +4,14 @@
 #define LEFT_ANKLE_PIN  4
 #define RIGHT_HIP_PIN   3
 #define LEFT_HIP_PIN    2
+
+#define RIGHT_ANKLE_MIDDLE  1500
+#define LEFT_ANKLE_MIDDLE   1500
+#define RIGHT_HIP_MIDDLE    1300
+#define LEFT_HIP_MIDDLE     1500
+#define MOVE                350
+#define FACTOR              2
+#define DELAY               2

 Servo rightAnkle;
 Servo leftAnkle;
@@ -18,68 +26,62 @@
     rightHip.attach(RIGHT_HIP_PIN);
     leftHip.attach(LEFT_HIP_PIN);

-    rightAnkle.writeMicroseconds(1060);
-    leftAnkle.writeMicroseconds(1300);
-    rightHip.writeMicroseconds(1300);
-    leftHip.writeMicroseconds(1500);
+    rightAnkle.writeMicroseconds(RIGHT_ANKLE_MIDDLE);
+    leftAnkle.writeMicroseconds(LEFT_ANKLE_MIDDLE);
+    rightHip.writeMicroseconds(RIGHT_HIP_MIDDLE);
+    leftHip.writeMicroseconds(LEFT_HIP_MIDDLE);
 }

 bool running = false;
-int d = 2;
-int factor = 2;
-int factor2 = 3;
-int diff = 350;
-int rightAnkleMiddle = 1100;
-int leftAnkleMiddle = 1300;
-int rightHipMiddle = 1300;
-int leftHipMiddle = 1500;

 void loop() {
     int i = 0;

     if (!running) {
         delay(5000);
-
-        for (i = 0; i < diff; ++i) {
-            rightAnkle.writeMicroseconds(rightAnkleMiddle-i*factor);
-            leftAnkle.writeMicroseconds(leftAnkleMiddle-i);
-            delay(d);
+
+        // lean left
+        for (i = 0; i < MOVE; ++i) {
+            rightAnkle.writeMicroseconds(RIGHT_ANKLE_MIDDLE-i*FACTOR);
+            leftAnkle.writeMicroseconds(LEFT_ANKLE_MIDDLE-i);
+            delay(DELAY);
+        }
+
+        // rotate hip forward
+        for (i = 0; i < MOVE; ++i) {
+            leftHip.writeMicroseconds(LEFT_HIP_MIDDLE+i);
+            delay(DELAY);
         }

-        for (i = 0; i < diff; ++i) {
-            leftHip.writeMicroseconds(leftHipMiddle+i);
-            delay(d);
+        for (i = 0; i < MOVE; ++i) {
+            rightAnkle.writeMicroseconds(RIGHT_ANKLE_MIDDLE - MOVE*FACTOR+i*FACTOR);
+            leftAnkle.writeMicroseconds(LEFT_ANKLE_MIDDLE - MOVE+i);
+            delay(DELAY);
         }

-        for (i = 0; i < diff; ++i) {
-            rightAnkle.writeMicroseconds(rightAnkleMiddle - diff*factor+i*factor);
-            leftAnkle.writeMicroseconds(leftAnkleMiddle - diff+i);
-            delay(d);
+        for (i = 0; i < MOVE; ++i) {
+            rightAnkle.writeMicroseconds(RIGHT_ANKLE_MIDDLE+i);
+            leftAnkle.writeMicroseconds(LEFT_ANKLE_MIDDLE+i*FACTOR);
+            leftHip.writeMicroseconds(LEFT_HIP_MIDDLE+MOVE-i);
+            delay(DELAY);
         }

-        for (i = 0; i < diff; ++i) {
-            rightAnkle.writeMicroseconds(rightAnkleMiddle+i);
-            leftAnkle.writeMicroseconds(leftAnkleMiddle+i*factor2);
-            leftHip.writeMicroseconds(leftHipMiddle+diff-i);
-            delay(d);
+        for (i = 0; i < MOVE; ++i) {
+            rightHip.writeMicroseconds(RIGHT_HIP_MIDDLE-i);
+            leftHip.writeMicroseconds(LEFT_HIP_MIDDLE-i);
+            delay(DELAY);
         }

-        for (i = 0; i < diff; ++i) {
-            rightHip.writeMicroseconds(rightHipMiddle-i);
-            leftHip.writeMicroseconds(leftHipMiddle-i);
-            delay(d);
+        for (i = 0; i < MOVE; ++i) {
+            rightAnkle.writeMicroseconds(RIGHT_ANKLE_MIDDLE+MOVE-i);
+            leftAnkle.writeMicroseconds(LEFT_ANKLE_MIDDLE+MOVE*FACTOR-i*FACTOR);
+            delay(DELAY);
         }

-        for (i = 0; i < diff; ++i) {
-            rightAnkle.writeMicroseconds(rightAnkleMiddle+diff-i);
-            leftAnkle.writeMicroseconds(leftAnkleMiddle+diff*factor2-i*factor2);
-            delay(d);
-        }
-
-        for (i = 0; i < diff; ++i) {
-            rightAnkle.writeMicroseconds(rightAnkleMiddle-i*factor2);
-            leftAnkle.writeMicroseconds(leftAnkleMiddle-i);
-            delay(d);
+        for (i = 0; i < MOVE; ++i) {
+            rightAnkle.writeMicroseconds(RIGHT_ANKLE_MIDDLE-i*FACTOR);
+            leftAnkle.writeMicroseconds(LEFT_ANKLE_MIDDLE-i);
+            delay(DELAY);
         }

         running = true;
@@ -91,44 +93,44 @@
 void stepForward() {
     int i = 0;

-    for (i = 0; i < diff; ++i) {
-        rightHip.writeMicroseconds(rightHipMiddle - diff + i);
-        leftHip.writeMicroseconds(leftHipMiddle - diff + i);
-        delay(d);
+    for (i = 0; i < MOVE; ++i) {
+        rightHip.writeMicroseconds(RIGHT_HIP_MIDDLE - MOVE + i);
+        leftHip.writeMicroseconds(LEFT_HIP_MIDDLE - MOVE + i);
+        delay(DELAY);
     }

-    for (i = 0; i < diff; ++i) {
-        rightHip.writeMicroseconds(rightHipMiddle + i);
-        leftHip.writeMicroseconds(leftHipMiddle + i);
-        rightAnkle.writeMicroseconds(rightAnkleMiddle - diff * factor2 + i * factor2);
-        leftAnkle.writeMicroseconds(leftAnkleMiddle - diff + i);
-        delay(d);
+    for (i = 0; i < MOVE; ++i) {
+        rightHip.writeMicroseconds(RIGHT_HIP_MIDDLE + i);
+        leftHip.writeMicroseconds(LEFT_HIP_MIDDLE + i);
+        rightAnkle.writeMicroseconds(RIGHT_ANKLE_MIDDLE - MOVE * FACTOR + i * FACTOR);
+        leftAnkle.writeMicroseconds(LEFT_ANKLE_MIDDLE - MOVE + i);
+        delay(DELAY);
     }

-    for (i = 0; i < diff; ++i) {
-        rightAnkle.writeMicroseconds(rightAnkleMiddle + i);
-        leftAnkle.writeMicroseconds(leftAnkleMiddle + i * factor2);
-        delay(d);
+    for (i = 0; i < MOVE; ++i) {
+        rightAnkle.writeMicroseconds(RIGHT_ANKLE_MIDDLE + i);
+        leftAnkle.writeMicroseconds(LEFT_ANKLE_MIDDLE + i * FACTOR);
+        delay(DELAY);
     }

-    for (i = 0; i < diff; ++i) {
-        rightHip.writeMicroseconds(rightHipMiddle + diff - i);
-        leftHip.writeMicroseconds(leftHipMiddle + diff - i);
-        delay(d);
+    for (i = 0; i < MOVE; ++i) {
+        rightHip.writeMicroseconds(RIGHT_HIP_MIDDLE + MOVE - i);
+        leftHip.writeMicroseconds(LEFT_HIP_MIDDLE + MOVE - i);
+        delay(DELAY);
     }

-    for (i = 0; i < diff; ++i) {
-        rightHip.writeMicroseconds(rightHipMiddle - i);
-        leftHip.writeMicroseconds(leftHipMiddle - i);
-        rightAnkle.writeMicroseconds(rightAnkleMiddle + diff - i);
-        leftAnkle.writeMicroseconds(leftAnkleMiddle + diff * factor2 - i * factor2);
-        delay(d);
+    for (i = 0; i < MOVE; ++i) {
+        rightHip.writeMicroseconds(RIGHT_HIP_MIDDLE - i);
+        leftHip.writeMicroseconds(LEFT_HIP_MIDDLE - i);
+        rightAnkle.writeMicroseconds(RIGHT_ANKLE_MIDDLE + MOVE - i);
+        leftAnkle.writeMicroseconds(LEFT_ANKLE_MIDDLE + MOVE * FACTOR - i * FACTOR);
+        delay(DELAY);
     }

-    for (i = 0; i < diff; ++i) {
-        rightAnkle.writeMicroseconds(rightAnkleMiddle - i * factor2);
-        leftAnkle.writeMicroseconds(leftAnkleMiddle - i);
-        delay(d);
+    for (i = 0; i < MOVE; ++i) {
+        rightAnkle.writeMicroseconds(RIGHT_ANKLE_MIDDLE - i * FACTOR);
+        leftAnkle.writeMicroseconds(LEFT_ANKLE_MIDDLE - i);
+        delay(DELAY);
     }
 }


src: add abitility to get tank metrics

src: add abitility to get tank metrics

Signed-off-by: Michael Dawson <697f19bdc6386e09c0d34238f49474ef87a73bae@devrus.com>

--- WaterTankSensor/WaterTankSensor.ino
+++ WaterTankSensor/WaterTankSensor.ino
@@ -27,6 +27,7 @@
 void callback(char* topic, uint8_t* message, unsigned int length);

 ESP8266WiFiGenericClass wifi;
+ESP8266WebServer server(80);

 #ifdef USE_CERTS
 // if certs are used the following must be defined in WirelessConfig.h
@@ -51,6 +52,17 @@
 int counter = 0;
 int fullIntervalCount = 0;
 char macAddress[] = "00:00:00:00:00:00";
+
+void provideMetrics() {
+  char tempMessage[MAX_MESSAGE_SIZE];
+  String ptr = "";
+  for (int i=0; i<NUM_SENSORS; i++) {
+      int sensorValue = digitalRead(SENSOR_PINS[i]);
+      snprintf(tempMessage, MAX_MESSAGE_SIZE, "Tank status%d %d\n", i, sensorValue);
+      ptr+= tempMessage;
+  }
+  server.send(200, "text/plain", ptr);
+}

 void setup() {
   delay(1000);
@@ -86,6 +98,9 @@
           macRaw[3],
           macRaw[4],
           macRaw[5]);
+
+  server.on("/metrics", provideMetrics);
+  server.begin();
 }

 void callback(char* topic, uint8_t* message, unsigned int length) {
@@ -137,4 +152,6 @@
     };
     counter = 0;
   }
+
+  server.handleClient();
 }


modify imu pub

modify imu pub

--- arduino/opencr_arduino/opencr/libraries/turtlebot3/turtlebot_burger/turtlebot3_core/turtlebot3_core.ino
+++ arduino/opencr_arduino/opencr/libraries/turtlebot3/turtlebot_burger/turtlebot3_core/turtlebot3_core.ino
@@ -268,7 +268,7 @@
   tfs_msg.transform.rotation.y = imu.quat[2];
   tfs_msg.transform.rotation.z = imu.quat[3];

-  tfs_msg.transform.translation.x = 0.0;
+  tfs_msg.transform.translation.x = -0.032;
   tfs_msg.transform.translation.y = 0.0;
   tfs_msg.transform.translation.z = 0.068;


move big strings into flash memory

move big strings into flash memory

--- drone/WebServerESC/WebServerESC.ino
+++ drone/WebServerESC/WebServerESC.ino
@@ -3,6 +3,7 @@
  * The request happens through a GET http method.
  */

+#include <avr/pgmspace.h>
 #include <Servo.h>
 #include <WiServer.h>

@@ -38,6 +39,10 @@
 unsigned char ssid_len;
 unsigned char security_passphrase_len;
 // End of wireless configuration parameters ----------------------------------------
+
+// Webpage in flash memory
+const prog_char htmlHead[] PROGMEM = {"<meta http-equiv=""content-type"" content=""text/html; charset=utf-8"" /><title>OneButtonAlert Device</title>"};
+const prog_char htmlMotor[] PROGMEM = {"<select name=""OPERATION"" id=""OPERATION"" style=""font-size:50px""><option value=""OFF"">Turn ON</option><option value=""ON"">Turn OFF</option><option value=""90"">90</option></select>
<input type=submit value=SUBMIT style=""font-size:50px"">
</form>

"};

 // This is our page serving function that generates web pages
 boolean sendMyPage(char* URL)
@@ -131,22 +136,9 @@

 void _webpageHelper()
 {
-    WiServer.print ("");
-    WiServer.print ("");
-    WiServer.print ("<meta http-equiv=""content-type"" content=""text/html; charset=utf-8"" />");
-    //WiServer.print ("<meta http-equiv=""refresh"" content=""25;url=http://192.168.1.60"" />");
-    WiServer.print ("<title>OneButtonAlert Device</title>");
-    //WiServer.print ("<link rel=""stylesheet"" type=""text/css"" media=""One Button Alert"" href=""http://onebuttonalert.com/buttonpressed/demo.css"" />");
-
-    WiServer.print ("");
-
+    WiServer.print_P(htmlHead);
+
     WiServer.print ("
");
-
-
-
-    // WiServer.print ("

");
-    WiServer.print ("
");
-    WiServer.print ("
");
     WiServer.print ("Device Local IP Address Status
");
     WiServer.print ("");
     WiServer.print (local_ip[0], DEC);
@@ -156,27 +148,21 @@
     WiServer.print (local_ip[2], DEC);
     WiServer.print (".");
     WiServer.print (local_ip[3], DEC);
-
     WiServer.print ("
");

     if (thestart == 0) {
-	    WiServer.print ("
<form>Engine Motor - ON
");
-	    WiServer.print ("<method=GET>");
-        WiServer.print ("<select name=""OPERATION"" id=""OPERATION"" style=""font-size:50px""><option value=""OFF"">Turn ON</option><option value=""ON"">Turn OFF</option><option value=""90"">90</option></select>");
-	    WiServer.print ("
<input type=submit value=SUBMIT style=""font-size:50px"">
</form>

");
-	}
+        WiServer.print("
<form> Engine Motor - OFF
");
+        WiServer.print("<method=GET>");
+        WiServer.print_P(htmlMotor);
+    }
     else {
-	    WiServer.print ("
<form> Engine Motor - OFF
");
-	    WiServer.print ("<method=GET>");
-        WiServer.print ("<select name=""OPERATION"" id=""OPERATION"" style=""font-size:50px""><option value=""OFF"">Turn ON</option><option value=""ON"">Turn OFF</option><option value=""90"">90</option></select>");
-        // WiServer.print ("<select name=""OPERATION"" id=""OPERATION"" style=""font-size:50px""><option value=""OFF"">Turn OFF</option><option value=""90"">POWER UP</option></select>");
-	    WiServer.print ("<input type=submit value=SUBMIT ></form>

");
-	}
-
-
-	WiServer.print ("
");
+        WiServer.print("
<form> Engine Motor - ON
");
+        WiServer.print("<method=GET>");
+        WiServer.print_P(htmlMotor);
+    }
+
+    WiServer.print ("
");
 }
-

 void move_to_start()


general code cleanup

general code cleanup

--- drone/WebServerESC/WebServerESC.ino
+++ drone/WebServerESC/WebServerESC.ino
@@ -39,93 +39,62 @@
 unsigned char security_passphrase_len;
 // End of wireless configuration parameters ----------------------------------------

-
 // This is our page serving function that generates web pages
-boolean sendMyPage(char* URL) {
-
+boolean sendMyPage(char* URL)
+{
+
     // Check if the requested URL matches "/"
     if (strcmp(URL, "/") == 0) {
-        Invia_Pagina_Web();
+        _webpageHelper();
         // URL was recognized
         return true;
     }
-
-

-	  if (strcmp (URL, "/?OPERATION=OFF") == 0) {
-           thestart = 1;
-           Invia_Pagina_Web();
-	   move_to_start();
-
-
+    if (strcmp (URL, "/?OPERATION=OFF") == 0) {
+        thestart = 1;
+        _webpageHelper();
+	    move_to_start();
 	    return (true);
-	  }
+    }

-	  if (strcmp (URL, "/?OPERATION=ON") == 0) {
-	    thestart = 0;
-            Invia_Pagina_Web();
+	if (strcmp (URL, "/?OPERATION=ON") == 0) {
+        thestart = 0;
+        _webpageHelper();
 	    move_to_end();
 	    return (true);
-	  }
+    }

-	  if (strcmp (URL, "/?OPERATION=90") == 0) {
+    if (strcmp (URL, "/?OPERATION=90") == 0) {
 	    thestart = 0;
-	    Invia_Pagina_Web();
-            move_to_ninty();
+	    _webpageHelper();
+        move_to_ninty();
 	    return (true);
-	  }
-
-
-
-
+	}
+
     // URL not found
     return false;
 }

-
-
-int PIN_BLUEII = 8;
-int PIN_RED = 7;
-
-int greenVal = 1;   // Initial values are Red full, Green and Blue off
 int i = 0;     // Loop counter

-int ledPin = 13; // pin for the LED
-int buttonPin = 6; // input pin of pushbutton
-int val = 0; // variable for reading the pin status
-
-
-
-
-
-// IP Address for www.weather.gov
-uint8 ip[] = {184,168,17,1};
-
 // This is our motor.
 Servo myMotor;

-// This is the final output
-// written to the motor.
-String incomingString;
-
 void arm(){
-  // arm the speed controller, modify as necessary for your ESC
-  setSpeed(0);
-  delay(3000); //delay 1 second,  some speed controllers may need longer
+    // arm the speed controller, modify as necessary for your ESC
+    setSpeed(0);
+    delay(3000); //delay 1 second,  some speed controllers may need longer
 }

 void setSpeed(int speed){
-  // speed is from 0 to 100 where 0 is off and 100 is maximum speed
-  //the following maps speed values of 0-100 to angles from 0-180,
-  // some speed controllers may need different values, see the ESC instructions
-  int angle = map(speed, 0, 100, 0, 180);
-  myMotor.write(angle);
+      // speed is from 0 to 100 where 0 is off and 100 is maximum speed
+      //the following maps speed values of 0-100 to angles from 0-180,
+     // some speed controllers may need different values, see the ESC instructions
+     int angle = map(speed, 0, 100, 0, 180);
+     myMotor.write(angle);
 }
-
-
-

 void setup() {

@@ -147,10 +116,6 @@
   WiServer.enableVerboseMode(false);
 }

-
-
-
-
 void loop()
 {
   // Run WiServer
@@ -159,81 +124,69 @@
 }

-
-
-	void Invia_Pagina_Web() {
-	  // Usando le funzioni WiServer.print trasmette al pagina Web da visualizzare
-	  WiServer.print ("");
-	  WiServer.print ("");
-WiServer.print ("<meta http-equiv=""content-type"" content=""text/html; charset=utf-8"" />");
-//WiServer.print ("<meta http-equiv=""refresh"" content=""25;url=http://192.168.1.60"" />");
-WiServer.print ("<title>OneButtonAlert Device</title>");
-//WiServer.print ("<link rel=""stylesheet"" type=""text/css"" media=""One Button Alert"" href=""http://onebuttonalert.com/buttonpressed/demo.css"" />");
-
-
-
-	  WiServer.print ("");
-	  WiServer.print ("
");
+void _webpageHelper()
+{
+	WiServer.print ("");
+	WiServer.print ("");
+    WiServer.print ("<meta http-equiv=""content-type"" content=""text/html; charset=utf-8"" />");
+    //WiServer.print ("<meta http-equiv=""refresh"" content=""25;url=http://192.168.1.60"" />");
+    WiServer.print ("<title>OneButtonAlert Device</title>");
+    //WiServer.print ("<link rel=""stylesheet"" type=""text/css"" media=""One Button Alert"" href=""http://onebuttonalert.com/buttonpressed/demo.css"" />");
+
+	WiServer.print ("");
+    WiServer.print ("
");

-	 // WiServer.print ("

");
-	  WiServer.print ("
");
-	  WiServer.print ("
");
-	  WiServer.print ("Device Local IP Address Status
");
-	  WiServer.print ("");
+	// WiServer.print ("

");
+	WiServer.print ("
");
+	WiServer.print ("
");
+    WiServer.print ("Device Local IP Address Status
");
+    WiServer.print ("");

-          WiServer.print (local_ip[0], DEC);
-	  WiServer.print (".");
-	  WiServer.print (local_ip[1], DEC);
-	  WiServer.print (".");
-	  WiServer.print (local_ip[2], DEC);
-	  WiServer.print (".");
-	  WiServer.print (local_ip[3], DEC);
+    WiServer.print (local_ip[0], DEC);
+	WiServer.print (".");
+    WiServer.print (local_ip[1], DEC);
+	WiServer.print (".");
+    WiServer.print (local_ip[2], DEC);
+	WiServer.print (".");
+    WiServer.print (local_ip[3], DEC);

-          WiServer.print ("
");
+    WiServer.print ("
");

-	  if (thestart == 0) {
-	   WiServer.print ("
<form>Engine Motor - ON
");
-	   WiServer.print ("<method=GET>");
-           WiServer.print ("<select name=""OPERATION"" id=""OPERATION"" style=""font-size:50px""><option value=""OFF"">Turn ON</option><option value=""ON"">Turn OFF</option><option value=""90"">90</option></select>");
-	   WiServer.print ("
<input type=submit value=SUBMIT style=""font-size:50px"">
</form>

");
-	 }
-	  else {
-	   WiServer.print ("
<form> Engine Motor - OFF
");
-	   WiServer.print ("<method=GET>");
-           WiServer.print ("<select name=""OPERATION"" id=""OPERATION"" style=""font-size:50px""><option value=""OFF"">Turn ON</option><option value=""ON"">Turn OFF</option><option value=""90"">90</option></select>");
-          // WiServer.print ("<select name=""OPERATION"" id=""OPERATION"" style=""font-size:50px""><option value=""OFF"">Turn OFF</option><option value=""90"">POWER UP</option></select>");
-	   WiServer.print ("<input type=submit value=SUBMIT ></form>

");
-	 }
+    if (thestart == 0) {
+	    WiServer.print ("
<form>Engine Motor - ON
");
+	    WiServer.print ("<method=GET>");
+        WiServer.print ("<select name=""OPERATION"" id=""OPERATION"" style=""font-size:50px""><option value=""OFF"">Turn ON</option><option value=""ON"">Turn OFF</option><option value=""90"">90</option></select>");
+	    WiServer.print ("
<input type=submit value=SUBMIT style=""font-size:50px"">
</form>

");
+	}
+    else {
+	    WiServer.print ("
<form> Engine Motor - OFF
");
+	    WiServer.print ("<method=GET>");
+        WiServer.print ("<select name=""OPERATION"" id=""OPERATION"" style=""font-size:50px""><option value=""OFF"">Turn ON</option><option value=""ON"">Turn OFF</option><option value=""90"">90</option></select>");
+        // WiServer.print ("<select name=""OPERATION"" id=""OPERATION"" style=""font-size:50px""><option value=""OFF"">Turn OFF</option><option value=""90"">POWER UP</option></select>");
+	    WiServer.print ("<input type=submit value=SUBMIT ></form>

");
+	}

-	  WiServer.print ("
");
-	}
+	WiServer.print ("
");
+}

-	void move_to_start() {
-
-         myMotor.write(80);
-
-
-
-//delay(500); // delay 1000ms, this allows the previous instruction to be finished.
-
-	}
+void move_to_start()
+{
+    myMotor.write(80);
+    //delay(500); // delay 1000ms, this allows the previous instruction to be finished.
+}

-	void move_to_end() {
+void move_to_end()
+{
+    myMotor.write(70);
+}

-         myMotor.write(70);
-
-
-	}
-
-	void move_to_ninty() {
-
-         myMotor.write(90);
-
-
-	}
+void move_to_ninty()
+{
+    myMotor.write(90);
+}


tinyTempNode: cleanup

tinyTempNode: cleanup

--- nodes/tinyTempNode/tinyTempNode.ino
+++ nodes/tinyTempNode/tinyTempNode.ino
@@ -180,6 +180,36 @@
   return result;
 }

+// read OneWire data
+void readOneWire() {
+  // power on sensor
+  digitalWrite(ONE_WIRE_POWER_PIN, HIGH);
+
+  // allow 5ms for the sensor to be ready
+  delay(5);
+
+  // start up temp sensor
+  sensors.begin();
+
+  // get the temperature
+  sensors.requestTemperatures();
+
+  // temperature value is send in payload on 10bits, so we keep only temperatures between -51.2 and 51.2
+  short int temp = (sensors.getTempCByIndex(0)*10);
+
+  if (temp > 512) {
+    temp = 512;
+  }
+  if (temp < -512) {
+    temp = -512;
+  }
+
+  payload.temp = temp;
+
+  // power off sensor
+  digitalWrite(ONE_WIRE_POWER_PIN, LOW);
+}
+

 //
 // Main
@@ -207,32 +237,8 @@
 }

 void loop() {
-  // power on sensor
-  digitalWrite(ONE_WIRE_POWER_PIN, HIGH);
-
-  // allow 5ms for the sensor to be ready
-  delay(5);
-
-  // start up temp sensor
-  sensors.begin();
-
-  // get the temperature
-  sensors.requestTemperatures();
-
-  // temperature value is send in payload on 10bits, so we keep only temperatures between -51.2 and 51.2
-  short int temp = (sensors.getTempCByIndex(0)*10);
-
-  if (temp > 512) {
-    temp = 512;
-  }
-  if (temp < -512) {
-    temp = -512;
-  }
-
-  payload.temp = temp;
-
-  // power off sensor
-  digitalWrite(ONE_WIRE_POWER_PIN, LOW);
+  // read sensor
+  readOneWire();

   // get supply voltage
   payload.vcc = readVcc();


Fixed some checks and logic for inner loop

--- gcn_controller_v5/gcn_controller_v5.ino
+++ gcn_controller_v5/gcn_controller_v5.ino
@@ -310,6 +310,7 @@
       timesToLoop = 0;
       loopCounter = 0;
       howManyInnerLoopsMacroHas = 0;
+      macroMetadataIndex = 0;
       isInputting = true;
       isInputtingDelayed = false;
       previousInputDelay = millis();
@@ -327,6 +328,7 @@
           timesToLoop = 0;
           loopCounter = 0;
           howManyInnerLoopsMacroHas = 0;
+          macroMetadataIndex = 0;
           //isInputting = false;
           isInputtingDelayed = false;
           macroIndex = serial_rx_buffer[0] - startingMacroIndex;
@@ -347,6 +349,7 @@
       timesToLoop = 0;
       loopCounter = 0;
       howManyInnerLoopsMacroHas = 0;
+      macroMetadataIndex = 0;
       isInputtingDelayed = false;
       isInputting = false;
       macroInputsToRun = serial_rx_buffer[1];
@@ -359,7 +362,9 @@
       if (howManyInnerLoopsMacroHas > 0) {
         Serial.println("TEST ABC");
         macroMetadataIndex = 0;
+        // Check if the first inner loop metadata is valid, if it is, use that, if not, disregard and don't do anything
         if (inner_loop_metadata[0][1] > 0 && inner_loop_metadata[0][3] > 0) {
+          // Accept inner loop metadata if first inner loop metadata is valid
           Serial.println("TEST DEF");
           macroMetadataIndex = 0;
           for (uint8_t macroMetadataIndexInner = 0; macroMetadataIndexInner < howManyInnerLoopsMacroHas; macroMetadataIndexInner++) {
@@ -367,6 +372,30 @@
             Serial.println(macroMetadataIndexInner);
             inner_loop_metadata[macroMetadataIndexInner][2] = 0; // Reset current input index for inner loop
             inner_loop_metadata[macroMetadataIndexInner][4] = 0; // Reset current repeat counter for inner loop
+            Serial.print("AFTER macroMetadataIndexInner = ");
+            Serial.println(macroMetadataIndexInner);
+          }
+        }
+        if (inner_loop_metadata[0][1] <= 0 || inner_loop_metadata[0][3] <= 0) {
+          // Clear all inner loop metadata if first inner loop metadata is invalid
+          macroMetadataIndex = 0;
+          howManyInnerLoopsMacroHas = 0;
+          Serial.println("TEST GHI");
+          for (uint8_t macroMetadataIndexInner = 0; macroMetadataIndexInner < macroMetadataSize; macroMetadataIndexInner++) {
+            Serial.print("BEFORE macroMetadataIndexInner = ");
+            Serial.println(macroMetadataIndexInner);
+            inner_loop_metadata[macroMetadataIndexInner][0] = 0;
+            inner_loop_metadata[macroMetadataIndexInner][1] = 0;
+            inner_loop_metadata[macroMetadataIndexInner][2] = 0;
+            inner_loop_metadata[macroMetadataIndexInner][3] = 0;
+            inner_loop_metadata[macroMetadataIndexInner][4] = 0;
+            inner_loop_metadata[macroMetadataIndexInner][5] = 0;
+            inner_loop_metadata[macroMetadataIndexInner][6] = 0;
+            inner_loop_metadata[macroMetadataIndexInner][7] = 0;
+            inner_loop_metadata[macroMetadataIndexInner][8] = 0;
+            inner_loop_metadata[macroMetadataIndexInner][9] = 0;
+            inner_loop_metadata[macroMetadataIndexInner][10] = 0;
+            inner_loop_metadata[macroMetadataIndexInner][11] = 0;
             Serial.print("AFTER macroMetadataIndexInner = ");
             Serial.println(macroMetadataIndexInner);
           }
@@ -393,14 +422,14 @@
           macroMetadataIndex = serial_rx_buffer[0] - startingMacroMetadataIndex;
           /*
             inner_loop_metadata[macroMetadataIndex][0] = 0; // Preamble
-            inner_loop_metadata[macroMetadataIndex][1] = 0; // Inputs to execute (number of inputs that should be executed in this inner loop) (Use same logic as [5] here instead?)
+            inner_loop_metadata[macroMetadataIndex][1] = 0; // Inputs to execute (number of inputs that should be executed in this inner loop)
             inner_loop_metadata[macroMetadataIndex][2] = 0; // Current input index
             inner_loop_metadata[macroMetadataIndex][3] = 0; // Times to repeat (number of times this inner loop should be executed, before going to the next inner loop, if any)
             inner_loop_metadata[macroMetadataIndex][4] = 0; // Repeat counter (number of times this inner loop was executed)
-            inner_loop_metadata[macroMetadataIndex][5] = 0; // Where is the next inner loop's first input (index 0 input for the next inner loop, aka the index for the input in the macro_buffer array) (Continue normally if value is 0, or do nothing if there are no more inputs to be executed) // Current unused, apply logic to this
+            inner_loop_metadata[macroMetadataIndex][5] = 0; // Where is the next inner loop's first input (index 0 input for the next inner loop, aka the index for the input in the macro_buffer array) (Continue normally if value is 0, or do nothing if there are no more inputs to be executed) // Current unused, apply logic to this // Is this really needed? (maybe for as a failsafe?)
             inner_loop_metadata[macroMetadataIndex][6] = 0; // Where to start (index of the starting input) (Inclusive)
             inner_loop_metadata[macroMetadataIndex][7] = 0; // Where to end (index of the ending input) (Inclusive)
-            inner_loop_metadata[macroMetadataIndex][8] = 0; // How many inner loops that should be executed after this (if <=0, don't execute inner loops any inner loops after this, and move on as normal, if there are normal inputs to be exeucuted, execute those, if there's nothing else to do, go back to the beginning of the larger loop, if > 0, execute n inner loops after this) // Currently unused, apply logic to this
+            inner_loop_metadata[macroMetadataIndex][8] = 0; // How many inner loops that should be executed after this (if <=0, don't execute inner loops any inner loops after this, and move on as normal, if there are normal inputs to be exeucuted, execute those, if there's nothing else to do, go back to the beginning of the larger loop, if > 0, execute n inner loops after this) // Currently unused, apply logic to this // Is this really needed? (maybe for as a failsafe?)
             inner_loop_metadata[macroMetadataIndex][9] = 0; // Unused?
             inner_loop_metadata[macroMetadataIndex][10] = 0; // Unused?
             inner_loop_metadata[macroMetadataIndex][11] = 0; // Postamble
@@ -411,7 +440,6 @@
             //Serial.println(macroMetadataIndex);
             //Serial.print("macroInputMetadataIndex = ");
             //Serial.println(macroInputMetadataIndex);
-            Serial.println("Toast");
             Serial.println(inner_loop_metadata[macroMetadataIndex][macroInputMetadataIndex]);
           }
           //Serial.println("");
@@ -504,13 +532,13 @@
       if (currentMacroIndexRunning < macroInputsToRun) {
         //Serial.print("A BEFORE currentMacroIndexRunning = ");
         //Serial.println(currentMacroIndexRunning);
-        if (howManyInnerLoopsMacroHas <= 0) {
+        if (howManyInnerLoopsMacroHas <= macroMetadataIndex) {
           // Do stuff normally
-          Serial.println("This macro does not have inner loops");
+          Serial.println("This macro does not have inner loops OR we reached the end of inner loops");
           currentMacroIndexRunning++;
         }
-        if (howManyInnerLoopsMacroHas > 0) {
-          // This is where inner loop logic goes (???)
+        if (howManyInnerLoopsMacroHas > macroMetadataIndex) {
+          // This is where inner loop logic goes
           Serial.println("This macro has inner loops");
           if (inner_loop_metadata[macroMetadataIndex][1] > 0 && inner_loop_metadata[macroMetadataIndex][3] > 0) {
             // Do something
@@ -600,7 +628,9 @@
           if (howManyInnerLoopsMacroHas > 0) {
             Serial.println("TEST ABC");
             macroMetadataIndex = 0;
+            // Check if the first inner loop metadata is valid, if it is, use that, if not, disregard and don't do anything
             if (inner_loop_metadata[0][1] > 0 && inner_loop_metadata[0][3] > 0) {
+              // Accept inner loop metadata if first inner loop metadata is valid
               Serial.println("TEST DEF");
               macroMetadataIndex = 0;
               for (uint8_t macroMetadataIndexInner = 0; macroMetadataIndexInner < howManyInnerLoopsMacroHas; macroMetadataIndexInner++) {
@@ -608,6 +638,30 @@
                 Serial.println(macroMetadataIndexInner);
                 inner_loop_metadata[macroMetadataIndexInner][2] = 0; // Reset current input index for inner loop
                 inner_loop_metadata[macroMetadataIndexInner][4] = 0; // Reset current repeat counter for inner loop
+                Serial.print("AFTER macroMetadataIndexInner = ");
+                Serial.println(macroMetadataIndexInner);
+              }
+            }
+            if (inner_loop_metadata[0][1] <= 0 || inner_loop_metadata[0][3] <= 0) {
+              // Clear all inner loop metadata if first inner loop metadata is invalid
+              macroMetadataIndex = 0;
+              howManyInnerLoopsMacroHas = 0;
+              Serial.println("TEST GHI");
+              for (uint8_t macroMetadataIndexInner = 0; macroMetadataIndexInner < macroMetadataSize; macroMetadataIndexInner++) {
+                Serial.print("BEFORE macroMetadataIndexInner = ");
+                Serial.println(macroMetadataIndexInner);
+                inner_loop_metadata[macroMetadataIndexInner][0] = 0;
+                inner_loop_metadata[macroMetadataIndexInner][1] = 0;
+                inner_loop_metadata[macroMetadataIndexInner][2] = 0;
+                inner_loop_metadata[macroMetadataIndexInner][3] = 0;
+                inner_loop_metadata[macroMetadataIndexInner][4] = 0;
+                inner_loop_metadata[macroMetadataIndexInner][5] = 0;
+                inner_loop_metadata[macroMetadataIndexInner][6] = 0;
+                inner_loop_metadata[macroMetadataIndexInner][7] = 0;
+                inner_loop_metadata[macroMetadataIndexInner][8] = 0;
+                inner_loop_metadata[macroMetadataIndexInner][9] = 0;
+                inner_loop_metadata[macroMetadataIndexInner][10] = 0;
+                inner_loop_metadata[macroMetadataIndexInner][11] = 0;
                 Serial.print("AFTER macroMetadataIndexInner = ");
                 Serial.println(macroMetadataIndexInner);
               }


working

working

--- tests/DMX_Solenoid_Lights/DMX_Solenoid_Lights.ino
+++ tests/DMX_Solenoid_Lights/DMX_Solenoid_Lights.ino
@@ -13,7 +13,7 @@
 #include <Metro.h>
 #include <Streaming.h>

-
+#define LED 9

 #define FLAME_CHANS 2 // should read "001"
 void lamp1On() { DmxSimple.write(1, 255); }
@@ -43,6 +43,7 @@
   delay(1000);

   pinMode(3, OUTPUT);
+  pinMode(LED, OUTPUT);

   /* The most common pin for DMX output is pin 3, which DmxSimple
   ** uses by default. If you need to change that, do it here. */
@@ -87,5 +88,12 @@
   else if(color==2) FOR_ALL_LAMPS blue(l,255); //for(byte i=0;i<=LAMP_N;i++) blue(i,255);
   if(color==3) FOR_ALL_LAMPS white(l,255); //for(byte i=0;i<=LAMP_N;i++) white(i,255);

+  static boolean ledState = false;
+  ledState = !ledState;
+  digitalWrite(LED, ledState);
+
+  if(ledState) lamp2On();
+  else lamp2Off();
+
   delay(1000);
 }


COH-71

--- Arduino/COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
+++ Arduino/COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
@@ -1246,11 +1246,7 @@
 #endif

   // Have 32678Hz clock at least running before going any further.
-#if defined(ENABLE_WAKEUP_32768HZ_XTAL)
   if(!::OTV0P2BASE::HWTEST::check32768HzOsc()) { panic(F("xtal")); } // Async clock not running correctly.
-#else
-  DEBUG_SERIAL_PRINTLN_FLASHSTRING("(No xtal.)");
-#endif

 //  // Signal that xtal is running AND give it time to settle.
 //  posPOST(0 /*, F("about to test radio module") */);


Fixed serial on TX

Fixed serial on TX

--- crossbow.ino
+++ crossbow.ino
@@ -172,6 +172,11 @@
     pinMode(RX_ADC_PIN_1, INPUT);
     pinMode(RX_ADC_PIN_2, INPUT);
     pinMode(RX_ADC_PIN_3, INPUT);
+
+    /*
+     * Prepare Serial1 for S.Bus processing
+     */
+    Serial1.begin(100000, SERIAL_8E2);
 #endif

 #ifdef DEVICE_MODE_TX
@@ -196,6 +201,11 @@

     //Play single tune to indicate power up
     buzzerSingleMode(BUZZER_MODE_CHIRP, &buzzer);
+
+    /*
+     * Prepare Serial1 for S.Bus processing
+     */
+    Serial1.begin(100000, SERIAL_8N2);
 #endif

     pinMode(LED_BUILTIN, OUTPUT);
@@ -207,11 +217,6 @@
     qsp.debugConfig |= DEBUG_FLAG_LED;
 #endif

-    /*
-     * Prepare Serial1 for S.Bus processing
-     */
-    Serial1.begin(100000, SERIAL_8N2);
-    // sBus.begin();
 }

 uint8_t currentSequenceIndex = 0;


Added current way point to display

Added current way point to display

--- gps_arduino/gps_arduino.ino
+++ gps_arduino/gps_arduino.ino
@@ -255,6 +255,7 @@
          distance = getDistance(mCurrentWayPoint, flat, flon);

          lcd.print(" ");
+         lcd.print(mCurrentWayPoint);
          //Check if distance is less then 2 meters
          if(distance < 2){
            //Advance to next way point


added ArduinoOTA

added ArduinoOTA

--- sonoff-homie-s20/sonoff-homie-s20.ino
+++ sonoff-homie-s20/sonoff-homie-s20.ino
@@ -1,4 +1,5 @@
 #include <Homie.h>
+#include <ArduinoOTA.h>

 #define PIN_LED     13      // PIN 12 / HSPI_MOSI; UART0_CTS MTCK
 #define PIN_RELAY   12      // PIN 10 / HSPI_MISO MTDI
@@ -48,6 +49,7 @@
     }
     lastButtonState = buttonState;
   }
+  ArduinoOTA.handle();
 }

 void setup() {
@@ -66,6 +68,8 @@
   Homie.setResetTrigger(PIN_BUTTON, LOW, 5000);
   Homie.setLoopFunction(loopHandler);
   Homie.setup();
+  ArduinoOTA.setHostname(Homie.getConfiguration().deviceId);
+  ArduinoOTA.begin();
 }

 void loop() {


a working concept

a working concept

--- Arduino/sketches/Gimbal_V1.0/Sensor_Module_IMU.ino
+++ Arduino/sketches/Gimbal_V1.0/Sensor_Module_IMU.ino
@@ -59,7 +59,7 @@
 volatile uint8_t motorUpdateTick = 0;
 volatile uint8_t motorUpdate = 0;
 volatile uint8_t motorSpeedUpdateTick = 0;
-volatile uint8_t motorSpeed = 7;
+volatile uint8_t motorSpeed = 50;

 void setupInterupt()
 {
@@ -89,7 +89,7 @@
   initSensors();        //initilizes sensors for sepecifics see Sensors.ino
   delay(100);
   Serial.begin(115200); //initilize serial communication with 115200 baudrate
-  //setupInterupt();
+  setupInterupt();
   delay(100);
   calcSinArray();

@@ -164,7 +164,11 @@
       rollAngle = 180 + (rollAngle + 180);

     serialPrintDebug(pitchAccel); //prints to Serial for debug
-
+    if(motorUpdate == 1)
+  {
+    motorUpdate = 0;
+    runMotor(tStep);
+  }
 }
 // ************************************************************************************************************
 // Helper Functions
@@ -243,7 +247,7 @@
         Serial.read();
       }

-      //Serial.print(pitchAngle);
+      Serial.println(pitchAngle);
       //Serial.print("\t\t");
       //Serial.print(deltaGyroAngle[0]);
       //Serial.print("\t\t");
@@ -271,7 +275,7 @@
   pwmA = sinArray[Step];
   pwmB = sinArray[(Step + phaseOffset1) % SIN_ARRAY_SIZE];
   pwmC = sinArray[(Step + phaseOffset2) % SIN_ARRAY_SIZE];
-
+  controlWithImu();
 }

 ISR(TIMER2_COMPA_vect){//timer1 interrupt 64 kHz
@@ -294,5 +298,13 @@
       tStep--;
     motorSpeedUpdateTick = 0;
   }
-
-}
+}
+
+void controlWithImu()
+{
+  if(pitchAngle > 0)
+    motorDirection = -1;
+  else
+    motorDirection = 1;
+  motorSpeed = map(abs(pitchAngle),0,90,1000,100);
+}


a snowy day configuration

a snowy day configuration

--- init.ino
+++ init.ino
@@ -69,12 +69,14 @@

 void led_man_queue() {
 	// manually queue animations for startup
+	//thread_handler.queue(new Animation_Simple_DeskWhitePurpleFade());
 	thread_handler.queue(new Animation_Static_DeskThirdDimAmbient());
-	//thread_handler.queue(new Animation_Simple_DeskWhitePurpleFade());
+	thread_handler.queue(new Animation_Simple_Indiv_Rainbow(&desk1));
+	thread_handler.queue(new Animation_Simple_Indiv_Rainbow(&desk2));
 	//thread_handler.queue(new Animation_Holiday_Halloween_WinAllHalloweenSparkle());
-	thread_handler.queue(new Animation_Simple_Indiv_ColorFade(&window1, COLOR_RED));
+	thread_handler.queue(new Animation_Seasonal_Winter_WindowSnow(&window1));
 	//thread_handler.queue(new Animation_Simple_Win2RainbowWipe());
-	thread_handler.queue(new Animation_Seasonal_Winter_Snow_Win2());
+	thread_handler.queue(new Animation_Simple_Indiv_RainbowCycle(&window2));
 	//thread_handler.queue(new Animation_Simple_WinAllPurpleFade());
-	thread_handler.queue(new Animation_Simple_Indiv_ColorFade(&window3, COLOR_BLUE));
+	thread_handler.queue(new Animation_Seasonal_Winter_WindowSnow(&window3));
 }


Made one-to-one example a bit clearer

Made one-to-one example a bit clearer

--- examples/send/send.ino
+++ examples/send/send.ino
@@ -23,6 +23,7 @@
 	else
 	{
 		// set our address
+		// note the address of the received, we'll need it later on!
 		radio.setAddress(0xD2);
 		radio.startListening();
 	}
@@ -36,7 +37,7 @@
 	if (tx)
 	{
 		Serial.print(F("Sending.. "));
-		bool sent = radio.send(0xD2, "Hello 0xEE!");
+		bool sent = radio.send(0xD2, "Hello there receiver 0xD2!");	// make sure the first parameter matches the receiver's address
 		Serial.println(sent ? "OK" : "failed");
 		delay(1000);
 	}


Changed right encoder pin B number

Changed right encoder pin B number

--- arduino/AStarRPiSlaveRPB202.ino
+++ arduino/AStarRPiSlaveRPB202.ino
@@ -41,7 +41,7 @@
 const byte encoderLeftPinA = 8;    // PCINT4
 const byte encoderLeftPinB = 16;   // PCINT2
 const byte encoderRightPinA = 7;   // INT6
-const byte encoderRightPinB = 1;   // INT3
+const byte encoderRightPinB = 0;   // INT2

 static volatile bool lastLeftA;
 static volatile bool lastLeftB;
@@ -64,6 +64,7 @@
   lastLeftB = newLeftB;
 }

+// ISR for right encoder pins A & B (INT6 & INT2)
 static void rightISR()
 {
   bool newRightA = FastGPIO::Pin<encoderRightPinA>::isInputHigh();


scanner_stepper.ino: Uses long instead of float.

--- scanner_stepper/scanner_stepper.ino
+++ scanner_stepper/scanner_stepper.ino
@@ -26,17 +26,17 @@
 }

 void playNote(int frequency, int duration) {
-  float revolutionsPerMinute = frequency * 60.0 / stepsPerRevolution;
-  float steps = 1.0 * frequency * duration / 1000.0;
+  long revolutionsPerMinute = frequency * 60L / stepsPerRevolution;
+  long steps = ((long) frequency) * duration / 1000L;

   Serial.print("F: ");
   Serial.println(frequency);
   Serial.print("T: ");
   Serial.println(duration);
   Serial.print("RPM: ");
-  Serial.println((int) revolutionsPerMinute);
+  Serial.println(revolutionsPerMinute);
   Serial.print("s: ");
-  Serial.println((int) steps);
+  Serial.println(steps);

   if (revolutionsPerMinute > maxRpm) {
     Serial.println("Max RPM exceeded.");


Delete am2315test.ino

Delete am2315test.ino

--- am2315test.ino
+++ am2315test.ino
@@ -1,43 +0,0 @@
-#include <stdint.h>
-#include <spark_wiring_i2c.h>
-#include <Adafruit_AM2315.h>
-
-/***************************************************
-  This is an example for the AM2315 Humidity + Temp sensor
-
-  Designed specifically to work with the Adafruit BMP085 Breakout
-  ----> https://www.adafruit.com/products/1293
-
-  These displays use I2C to communicate, 2 pins are required to
-  interface
-  Adafruit invests time and resources providing this open source code,
-  please support Adafruit and open-source hardware by purchasing
-  products from Adafruit!
-
-  Written by Limor Fried/Ladyada for Adafruit Industries.
-  BSD license, all text above must be included in any redistribution
- ****************************************************/
-
-// Connect RED of the AM2315 sensor to 5.0V
-// Connect BLACK to Ground
-// Connect WHITE to i2c clock - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 5
-// Connect YELLOW to i2c data - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 4
-
-Adafruit_AM2315 am2315;
-
-void setup() {
-  Serial.begin(9600);
-  Serial.println("AM2315 Test!");
-
-  if (! am2315.begin()) {
-     Serial.println("Sensor not found, check wiring & pullups!");
-     while (1);
-  }
-}
-
-void loop() {
-  Serial.print("Hum: "); Serial.println(am2315.readHumidity());
-  Serial.print("Temp: "); Serial.println(am2315.readTemperature());
-
-  delay(1000);
-}


fixed missing content-type header - now getting response from lg api server

--- sketch_soil_wifi/sketch_soil_wifi.ino
+++ sketch_soil_wifi/sketch_soil_wifi.ino
@@ -125,6 +125,7 @@
   String request = "POST /api/collections/heartbeat?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"


update to use new feature report API in USBHID library

--- gamecubecontroller.ino
+++ gamecubecontroller.ino
@@ -81,7 +81,7 @@
   USBHID.setSerial(0);
 #endif
   USBHID.begin(reportDescription,sizeof(reportDescription),0,0x25);
-  USBHID.setBuffers(HID_REPORT_TYPE_FEATURE, &fb, 1);
+  USBHID.addFeatureBuffer(&fb);
   Joystick.setManualReportMode(true);
   delay(500);
 }


Everything is finish, LCD print left

Everything is finish, LCD print left

--- BiotechHardware/dcs/dcs.ino
+++ BiotechHardware/dcs/dcs.ino
@@ -13,21 +13,22 @@

 EthernetServer server(80);
 boolean device_status = true;
+boolean isInputting = false;

 const byte ROWS = 4;
 const byte COLS = 3;
 char keys[ROWS][COLS] = {
   {
-    '1','2','3'  }
+    '1','2','3'    }
   ,
   {
-    '4','5','6'  }
+    '4','5','6'    }
   ,
   {
-    '7','8','9'  }
+    '7','8','9'    }
   ,
   {
-    '*','0','#'  }
+    '*','0','#'    }
 };

 byte rowPins[ROWS] = {
@@ -39,17 +40,22 @@
 LiquidCrystal_I2C lcd(0x27,20,4);
 Servo myservo;

-char pass[16];
+char pass[10];
 int attempt = 0;
 int count = 0;
-int max_attempt = 3;

 const int sensor = A2;
 const int push_btn = A3;
 const int servo = 9;

+long prevTime = 0;
+long idleTime = 0;
+long interval_reset = 180000;
+long interval_idle = 20000;
+
 void setup(){
   Serial.begin(9600);
+  myservo.attach(9);
   Ethernet.begin(mac, ip);
   server.begin();
   pinMode(sensor, INPUT);
@@ -57,7 +63,7 @@
   pinMode(push_btn, INPUT);
   digitalWrite(push_btn, HIGH);
   myservo.write(70);
-  Serial.println("ready");
+  Serial.println("Ready");
 }

 void loop(){
@@ -74,6 +80,7 @@
               client.println("Content-Type: application/json");
               client.println();
               client.print("{\"response\":\"open\"}");
+              open_door();
             }
             else if(type == 's'){
               int val = client.parseInt();
@@ -121,6 +128,13 @@
                 client.print("{\"response\":\"non-active\"}");
               }
             }
+            else if(type == 'f') {
+              client.println("HTTP/1.1 200 OK");
+              client.println("Content-Type: application/json");
+              client.println();
+              client.print("{\"response\":\"false\"}");
+              wrong_password();
+            }
             else {
               Serial.print("Unexpected type ");
               Serial.print(type);
@@ -137,18 +151,21 @@
     delay(10);
     client.stop();
   }
+
   if(digitalRead(push_btn) == LOW){
     auth_user("keluar");
     open_door();
   }
-
-  if(device_status){
+
+  if(device_status && !device_isLock()){
     char key = keypad.getKey();
-    if (key != NO_KEY && key != '*'){
+    if (key != NO_KEY && key != '*' && key != '#'){
+      isInputting = true;
       pass[count] = key;
       count++;
     }
     if(key == '*'){
+      isInputting = false;
       attempt++;
       auth_user(pass);
       sys_init();
@@ -156,22 +173,45 @@
     if(key == '#'){
       sys_init();
     }
+    if(count > 9){
+      auth_user(pass);
+      sys_init();
+    }
+  }
+  else{
+    //Device Non-Active
+  }
+
+  unsigned long curTime = millis();
+  if(curTime - idleTime > interval_idle){
+    idleTime = curTime;
+    isInputting = false;
+    sys_init();
+  }
+
+  if(!isInputting){
+    if(curTime - prevTime > interval_reset){
+      prevTime = curTime;
+      attempt = 0;
+    }
   }
 }

 void sys_init(){
-  memset(pass, 0, sizeof pass);
+  Serial.println("sys_init()");
+  Serial.println(pass);
+  memset(pass, 0, 10);
   count = 0;
+  Serial.println(pass);
 }

 void auth_user(char user_input[]){
   EthernetClient client;
-  Serial.println("Sending");
+  Serial.println(user_input);
   if (client.connect(server_addr,80))
   {
     client.print("GET /api/dcs/dcs_auth/");
     client.print(user_input);
-    Serial.println(user_input);
     client.print(" HTTP/1.1\n");
     client.print("Host: 192.168.2.4\n");
     client.print("Connection: close\n\n");
@@ -179,11 +219,42 @@
   }
   else{
     Serial.println("Sending failed");
+    String pass(user_input);
+    if(pass == "123"){
+      if(pass != "keluar"){
+        open_door();
+      }
+    }
+    else{
+      wrong_password();
+    }
   }
 }

 void open_door(){
   Serial.println("Door open");
+  attempt = 0;
+  myservo.write(30);
+  delay(3000);
+  while(digitalRead(sensor) == HIGH);
   delay(1000);
-}
-
+  myservo.write(70);
+  Serial.println("Door closed");
+  idleTime = millis();
+}
+
+boolean device_isLock(){
+  if(attempt >= 3){
+    //Serial.println("Device lock");
+    return true;
+  }
+  else{
+    //Serial.println("Device unlock");
+    return false;
+  }
+}
+
+void wrong_password(){
+  Serial.println("Wrong Password");
+  idleTime = millis();
+}


Improving the MQTT and DS18B20 example sketch; publish three sensors.

--- examples/IoT/MQTT/CosaMQTTtemperature/CosaMQTTtemperature.ino
+++ examples/IoT/MQTT/CosaMQTTtemperature/CosaMQTTtemperature.ino
@@ -31,14 +31,14 @@
  * (D2)-----[ ]-------56-|IRQ         |
  *                       +------------+
  *
- *                       DS18B20/sensor
- *                       +------------+
- * (GND)---------------1-|GND         |
- * (D14)-----+---------2-|DQ          |
- *           |       +-3-|VDD         |
- *          4K7      |   +------------+
+ *                           DS18B20/3
+ *                       +------------+++
+ * (GND)---------------1-|GND         |||\
+ * (D7)------+---------2-|DQ          ||| |
+ *           |       +-3-|VDD         |||/
+ *          4K7      |   +------------+++
  *           |       |
- * (VCC)-----+-------+
+ * (VCC)-----+       +---(VCC/GND)
  *
  * This file is part of the Arduino Che Cosa project.
  */
@@ -50,9 +50,26 @@
 #include "Cosa/OWI/Driver/DS18B20.hh"
 #include "Cosa/Socket/Driver/W5100.hh"

+// Disable SD on Ethernet Shield
+#define USE_ETHERNET_SHIELD
+#if defined(USE_ETHERNET_SHIELD)
+#include "Cosa/OutputPin.hh"
+OutputPin sd(Board::D4, 1);
+#endif
+
 // One-wire pin and connected DS18B20 device
-OWI owi(Board::D14);
-DS18B20 sensor(&owi);
+OWI owi(Board::D7);
+
+// The devices connected to the one-wire bus
+DS18B20 outdoors(&owi);
+DS18B20 indoors(&owi);
+DS18B20 basement(&owi);
+
+DS18B20* thermometer[] = {
+  &outdoors,
+  &indoors,
+  &basement
+};

 // Network configuration
 #define MOSQUITTO "test.mosquitto.org"
@@ -72,10 +89,12 @@
 {
   Watchdog::begin();

-  // Connect the sensor and set resolution to 10-bits
-  sensor.connect(0);
-  sensor.set_resolution(10);
-  sensor.write_scratchpad();
+  // Connect the sensors and set resolution to 10-bits
+  for (uint8_t i = 0; i < membersof(thermometer); i++) {
+    thermometer[i]->connect(i);
+    thermometer[i]->set_resolution(10);
+    thermometer[i]->write_scratchpad();
+  }

   // Start ethernet controller and request network address for hostname
   ethernet.begin_P(CLIENT);
@@ -83,23 +102,35 @@
   // Start MQTT client with socket and connect to server
   client.begin(ethernet.socket(Socket::TCP));
   client.connect(SERVER, CLIENT);
-
-  // Publish data with the different quality of service levels
   client.publish_P(PSTR("public/cosa/client"), CLIENT, sizeof(CLIENT));
 }

 void loop()
 {
+  static uint8_t i = 0;
+
+  // Select the topic path for the current thermometer
+  str_P topic;
+  switch (i) {
+  case 0: topic = PSTR("public/cosa/temperature/outdoors"); break;
+  case 1: topic = PSTR("public/cosa/temperature/indoors"); break;
+  case 2: topic = PSTR("public/cosa/temperature/basement"); break;
+  };
+
   // Request a conversion and read the temperature
-  sensor.convert_request();
-  sensor.read_scratchpad();
+  thermometer[i]->convert_request();
+  thermometer[i]->read_scratchpad();

-  // Use an iobuffer and iostream to convert temperature to a string
-  IOBuffer<16> buf;
+  // Use an iobuffer and iostream to convert temperature value to a string
+  IOBuffer<32> buf;
   IOStream cout(&buf);
-  cout << sensor << PSTR(" C") << ends;
+  cout << *thermometer[i] << PSTR(" C") << ends;

   // Publish the value to the MQTT server and take a nap
-  client.publish(PSTR("public/cosa/temperature"), buf, buf.available());
+  client.publish(topic, buf, buf.available());
+  i += 1;
+  if (i == membersof(thermometer)) i = 0;
+
+  // Take a nap
   sleep(5);
 }


non-blocking blink

non-blocking blink

--- src/arduino/bear.ino
+++ src/arduino/bear.ino
@@ -16,10 +16,13 @@

 const int SERVO_MAX_ANGLE = 45;

+const int BLINK_INTERVAL = 150; // in milliseconds

 Servo myservo; // create servo object to control a servo
 bool servo_count = false;
 int current_bpm = 120;
+unsigned long previous_blink_downbeat = 0;
+unsigned long previous_blink_upbeat = 0;

 IRrecv irrecv(IR_RECEIVER);     // create instance of 'irrecv'
 decode_results results;      // create instance of 'decode_results'
@@ -52,35 +55,37 @@

 // the loop function runs over and over again forever
 void loop() {
+  unsigned long current_millis = millis();
+
   // catch signal
   if (Serial.available()) {
     // read serial input
     char x = Serial.read();
     switch (x) {
-      case 0: flash_beat(true); break;
-      case 1: flash_beat(false); break;
+      case 0: flash_beat(true, current_millis); break;
+      case 1: flash_beat(false, current_millis); break;
       default: if (x > 1) current_bpm = x; break;
     }
   } else if (irrecv.decode(&results)) {
     switch (translate_ir()) {
-      case 1: flash_beat(true); break;
-      case 2: flash_beat(false); break;
+      case 1: flash_beat(true, current_millis); break;
+      case 2: flash_beat(false, current_millis); break;
 //      case 7: test_speed(75); break;
       default: break;
     }
     irrecv.resume();
+  } else {
+    if (previous_blink_downbeat && current_millis - previous_blink_downbeat >= BLINK_INTERVAL) stop_blink(true, current_millis);
+    if (previous_blink_upbeat && current_millis - previous_blink_upbeat >= BLINK_INTERVAL) stop_blink(false, current_millis);
   }
 }

-void flash_beat(bool is_downbeat) {
+void flash_beat(bool is_downbeat, unsigned long current_millis) {
   digitalWrite(LED_BUILTIN, HIGH);
   digitalWrite(is_downbeat ? RED : BLUE, HIGH);
   digitalWrite(is_downbeat ? LED_1 : LED_2, HIGH);
-  delay(150);
-  digitalWrite(LED_BUILTIN, LOW);
-  digitalWrite(is_downbeat ? RED : BLUE, LOW);
-  digitalWrite(is_downbeat ? LED_1 : LED_2, LOW);
   switch_servo();
+  (is_downbeat ? previous_blink_downbeat : previous_blink_upbeat) = current_millis;
 }

 void stop_beat() {
@@ -90,7 +95,13 @@
   digitalWrite(BLUE, LOW);
   digitalWrite(LED_1, LOW);
   digitalWrite(LED_2, LOW);
-  switch_servo();
+}
+
+void stop_blink(bool is_downbeat, unsigned long current_millis) {
+  digitalWrite(LED_BUILTIN, LOW);
+  digitalWrite(is_downbeat ? RED : BLUE, LOW);
+  digitalWrite(is_downbeat ? LED_1 : LED_2, LOW);
+  (is_downbeat ? previous_blink_downbeat : previous_blink_upbeat) = current_millis;
 }

 void switch_servo() {


Retrieve packet length with getDynamicPayloadSize() for each individual packet

--- gripper/gripper.ino
+++ gripper/gripper.ino
@@ -36,9 +36,9 @@
     uint8_t buf[32];

     if (rf.available()) {
-        int len = rf.getDynamicPayloadSize();
         boolean done = false;
         while (!done) {
+            int len = rf.getDynamicPayloadSize();
             done = rf.read(buf, len);
             memcpy(line, (const char *) buf, len);
             line[len] = 0;