basic stopwatch implemented

basic stopwatch implemented

--- TrinketWatch.ino
+++ TrinketWatch.ino
@@ -57,7 +57,6 @@
 int hours = 9;
 int minutes = 50;

-unsigned long uptime = millis();
 unsigned long stopWatchStart = -1;

 void setup() {
@@ -69,17 +68,16 @@
   delay(200);
   display.clearDisplay();
   // text display tests
-  display.setTextSize(4);
   display.setTextColor(WHITE);
 }

 void loop() {
-  uptime = millis();
   demo();
 }

 void demo() {
   display.clearDisplay();
+  display.setTextSize(4);
   if (minutes >= 60) {
     hours++;
     minutes = 0;
@@ -104,7 +102,54 @@

 void stopwatch() {
   display.clearDisplay();
+  display.setTextSize(2);
   if (stopWatchStart != -1) {
-    unsigned long stopTime = uptime - stopWatchStart;
+    unsigned long stopTime = millis() - stopWatchStart;
+
+    int days, hours, mins, secs;
+    int fractime;
+    unsigned long inttime;
+
+    inttime  = stopTime / 1000;
+    fractime = stopTime % 1000;
+    // inttime is the total number of number of seconds
+    // fractimeis the number of thousandths of a second
+
+    // number of days is total number of seconds divided by 24 divided by 3600
+    days     = inttime / (24*3600);
+    inttime  = inttime % (24*3600);
+
+    // Now, inttime is the remainder after subtracting the number of seconds
+    // in the number of days
+    hours    = inttime / 3600;
+    inttime  = inttime % 3600;
+
+    // Now, inttime is the remainder after subtracting the number of seconds
+    // in the number of days and hours
+    mins     = inttime / 60;
+    inttime  = inttime % 60;
+
+    // Now inttime is the number of seconds left after subtracting the number
+    // in the number of days, hours and minutes. In other words, it is the
+    // number of seconds.
+    secs = inttime;
+
+    display.setCursor(5,10);
+    if (mins < 10)
+      display.print("0");
+    display.print(mins, DEC);
+    display.print(":");
+    if (secs < 10)
+      display.print("0");
+    display.print(secs, DEC);
+    display.print(":");
+    int centisec = (int)floor(fractime / 10);
+    if (centisec < 10)
+      display.print("0");
+    display.print(centisec);
+    display.println();
+    display.display();
   }
 }
+
+


Remap PWM pins to fit within address space

--- hardware/impeeduino/arduino/impeeduino/impeeduino.ino
+++ hardware/impeeduino/arduino/impeeduino/impeeduino.ino
@@ -24,6 +24,8 @@
 #define MASK_ANALOG_W 0x08
 #define MASK_ANALOG_ADDR 0x07
 #define MASK_CALL 0x1F
+
+const int PWM_PINMAP[6] = {3, 5, 6, 9, 10, 11};

 unsigned int rxByte = 0;
 unsigned int rxOp = 0;
@@ -106,7 +108,7 @@
                     // Higest order bits (7-4)
                     value = value | ((Serial.read() & 0x0F) << 4);
                     //Serial.write(value);
-                    analogWrite(addr, value);
+                    analogWrite(PWM_PINMAP[addr], value);
                 } else {
                     Serial.write(rxByte);
                     int analogvalue = analogRead(rxByte & MASK_ANALOG_ADDR);


button

button

--- examples/Unit/DUAL_BUTTON/DUAL_BUTTON.ino
+++ examples/Unit/DUAL_BUTTON/DUAL_BUTTON.ino
@@ -21,8 +21,8 @@
 void setup() {
   M5.begin(); //Init M5Stack.  初始化M5Stack
   M5.Power.begin(); //Init power  初始化电源模块
-  pinMode(21, INPUT); //set pin mode to input.设置引脚模式为输入模式
-  pinMode(22, INPUT);
+  pinMode(36, INPUT); //set pin mode to input.设置引脚模式为输入模式
+  pinMode(26, INPUT);
   M5.Lcd.setTextColor(YELLOW);  //Set the font color to yellow.  设置字体颜色为黄色
   M5.Lcd.setTextSize(2);  //Setting the Font size.  设置字号大小
   M5.Lcd.setCursor(80, 0);  //Set the cursor position to (80,0).  将光标位置设置为(80,0)
@@ -31,8 +31,8 @@
 }

 void loop() {
-  cur_value1 = digitalRead(22); // read the value of BUTTON.  读取22号引脚的值
-  cur_value2 = digitalRead(21);
+  cur_value1 = digitalRead(36); // read the value of BUTTON.  读取22号引脚的值
+  cur_value2 = digitalRead(26);
   M5.Lcd.setCursor(90,25); M5.Lcd.print("Btn.1  Btn.2");
   M5.Lcd.setCursor(0,45); M5.Lcd.print("Value: ");
   M5.Lcd.setCursor(0,85); M5.Lcd.print("State: ");


Fix overtiny buffer

Fix overtiny buffer

--- esp8266-arm-swd.ino
+++ esp8266-arm-swd.ino
@@ -210,7 +210,7 @@
             addr = strtol((char*) addrString, 0, 0);
         }

-        uint8_t valueString[10];
+        uint8_t valueString[64];
         server.arg(i).getBytes(valueString, sizeof valueString, 0);
         uint32_t value = strtol((char*) valueString, 0, 0);


Stop clearing request's memory

Stop clearing request's memory

Clearing packetbuf wipes out data for the request packet. After memset
the request token is lost and it cannot be copied to the response.

--- microcoap.ino
+++ microcoap.ino
@@ -83,7 +83,6 @@
             coap_packet_t rsppkt;
             coap_handle_req(&scratch_buf, &pkt, &rsppkt);

-            memset(packetbuf, 0, UDP_TX_PACKET_MAX_SIZE);
             if (0 != (rc = coap_build(packetbuf, &rsplen, &rsppkt)))
             {
                 Serial.print("coap_build failed rc=");


state ip address on checkin

state ip address on checkin

--- src/neurite.ino
+++ src/neurite.ino
@@ -1135,6 +1135,9 @@
 			dbg_assert(payload_buf);
 			sprintf(payload_buf, "checkin: %s", nd->uid);
 			mqtt_cli.publish(topic_to, (const char *)payload_buf);
+			__bzero(payload_buf, sizeof(payload_buf));
+			sprintf(payload_buf, "ip: %s", WiFi.localIP().toString().c_str());
+			mqtt_cli.publish(topic_to, (const char *)payload_buf);

 			start_ticker_led_breath(nd);
 			start_ticker_mon(nd);


Nano talks with Uno v3

Nano talks with Uno v3

--- Arduino/_firmware2/_firmware2.ino
+++ Arduino/_firmware2/_firmware2.ino
@@ -549,11 +549,19 @@
 //      counter++;
 //    }

-  Serial.println("DATA = " + data);
-  Serial.println("MIC = " + data_mic);
-  Serial.println("X = " + data_x);
-  Serial.println("Y = " + data_y);
-  Serial.println("Z = " + data_z);
+//  Serial.println("DATA = " + data);
+//  Serial.println("MIC = " + data_mic);
+//  Serial.println("X = " + data_x);
+//  Serial.println("Y = " + data_y);
+//  Serial.println("Z = " + data_z);
+
+
+  Serial.print(data);
+  Serial.print(data_mic);
+  Serial.print(data_x);
+  Serial.print(data_y);
+  Serial.print(data_z);
+
 //  //This loop prints the data from the FFT. The waits
 //for (int i = 0; i < 50; i++){
 //    while(mySerial.available()){


Initialize greetings to 16 space strings.

--- firmware/sentry.ino
+++ firmware/sentry.ino
@@ -126,8 +126,8 @@
 }

 void checkCode(int code) {
-  char line1[17];
-  char line2[17];
+  char line1[17] = "                ";
+  char line2[17] = "                ";

   // Prevent double scans by ignoring the same card within a short period.
   if ((code == lastCode) && (millis() < lastCodeCanRescanAt)) {


Removed initialisation to prevent blue blink at startup

--- arduino/arduino.ino
+++ arduino/arduino.ino
@@ -86,16 +86,9 @@
   //Create Neopixels strip and init
   strip = &Adafruit_NeoPixel(ledCount, neopixelsPin, NEO_GRB + NEO_KHZ800);
   strip->begin();
-
-  //Apply red to green gradient
-  for(int i=0; i<60; i++) {
-    strip->setPixelColor(i, 0, 0, 255);
-
-  }

   //show the gradient
   strip->setBrightness(EEPROM.read(EEPROM_CURRENT_BRIGHTNESS));
-  strip->show();

   //Load current profile
   applyProfile();


Minor changes

Minor changes

--- frmwr/src/frmwr.ino
+++ frmwr/src/frmwr.ino
@@ -251,14 +251,17 @@
   {
     Serial.println("Starting OTA updates...");
   });
+
   ArduinoOTA.onEnd([]()
   {
     Serial.println("Stopping OTA updates...");
   });
+
   ArduinoOTA.onProgress([](unsigned int progress, unsigned int total)
   {
     Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
   });
+
   ArduinoOTA.onError([](ota_error_t error)
   {
     Serial.printf("Error[%u]: ", error);
@@ -273,25 +276,25 @@
     }
     else if (error == OTA_CONNECT_ERROR)
     {
-      Serial.println("Connect Failed");
+      Serial.println("Connect failed!");
     }
     else if (error == OTA_RECEIVE_ERROR)
     {
-      Serial.println("Receive Failed");
+      Serial.println("Receive failed!");
     }
     else if (error == OTA_END_ERROR)
     {
-      Serial.println("End Failed");
+      Serial.println("End failed!");
     }
   });
 #endif DEBUG

   ArduinoOTA.setHostname(HOSTNAME);
   ArduinoOTA.setPassword(OTA_PASSWORD);
-
   ArduinoOTA.begin();

   Cytrill.begin();
+
   Cytrill.setLed(LED_0, 0x00, 0x00, 0x00, 31);
   Cytrill.setLed(LED_1, 0x00, 0x00, 0x00, 31);


resolvido erro do reset, ciclo dinâmico completamente funcional, fixes #17

--- EMP-B-Due.ino
+++ EMP-B-Due.ino
@@ -228,18 +228,16 @@
   unsigned long minimo = inicio_ciclo + ciclo_minimo;
   unsigned long maximo = inicio_ciclo + ciclo_maximo;
   sensorReset();
-  if (sensor_resetou || tempo_atual >= maximo) {
-    conta_ciclos++;
-    escreveSerial((String)conta_ciclos + ": " +
-                    (String)(tempo_atual - inicio_ciclo) + " / R:" +
-                    (String)ciclo_padrao);
-    soma_ciclos += tempo_atual - inicio_ciclo;
-    reiniciaCiclo();
-  }
-  if (tempo_atual < minimo && reset_liberado){
-    reset_liberado = FALSO;
-  } else if (tempo_atual > minimo && !reset_liberado){
+  if (tempo_atual >= minimo){
     reset_liberado = VERDADEIRO;
+    if (sensor_resetou || tempo_atual >= maximo) {
+      conta_ciclos++;
+      escreveSerial((String)conta_ciclos + ": " +
+                      (String)(tempo_atual - inicio_ciclo) + " / R:" +
+                      (String)ciclo_padrao);
+      soma_ciclos += tempo_atual - inicio_ciclo;
+      reiniciaCiclo();
+    }
   }
 }

@@ -247,6 +245,7 @@
   inicio_ciclo = millis();
   cicloMedio();
   ciclo_resetado = VERDADEIRO;
+  reset_liberado = FALSO;
   sensor_resetou = FALSO;
   fotocelula_liberada = FALSO;
   fotocelula_cortou = FALSO;


add fona ; switch to smaller fat16 lib

add fona ; switch to smaller fat16 lib

--- heatseek_sensor.ino
+++ heatseek_sensor.ino
@@ -7,11 +7,10 @@

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

-//#include <Adafruit_Sensor.h>
 #include <Wire.h>
 #include "RTClib.h"
 #include "DHT.h"
-#include <SD.h>
+#include "Fat16.h"

 #ifdef TRANSMITTER_WIFI
   #include <libmaple/iwdg.h>
@@ -28,9 +27,9 @@
 #endif

 #ifdef TRANSMITTER_GSM
-//  #include <avr/wdt.h>
-//  #include "Adafruit_FONA.h"
-//  #include <SoftwareSerial.h>
+  #include "Adafruit_FONA.h"
+  #include <SoftwareSerial.h>
+  #include <Adafruit_SleepyDog.h>

   #define DHT_DATA  A2
   #define DHT_VCC   A1
@@ -50,10 +49,13 @@
 #define HUB                "00000000test0001"
 #define CELL               "Test0000cell0007"

-#define READING_DELAY_MS   (2 * 1000)
+#define READING_INTERVAL_S   (60)

 RTC_PCF8523 rtc;
+SdCard sd_card;
+Fat16 data_file;
+Fat16 last_reading_file;
 DHT dht(DHT_DATA, DHT_TYPE);

 #ifdef TRANSMITTER_WIFI
@@ -63,12 +65,12 @@
 #endif

 #ifdef TRANSMITTER_GSM
-//  SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
-//  SoftwareSerial *fonaSerial = &fonaSS;
-
-//  Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
+  SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
+  SoftwareSerial *fonaSerial = &fonaSS;
+
+  Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
+  bool gsmConnected = false;
 #endif
-

 void setup() {
   watchdog_init();
@@ -81,15 +83,11 @@
   pinMode(DHT_GND, OUTPUT);
   digitalWrite(DHT_VCC, HIGH);
   digitalWrite(DHT_GND, LOW);
-
-  if (!SD.begin(SD_CS)) {
-    Serial.println("failed to initialize SD card");
-    while (true); // watchdog will reboot
-  }
-
+
+  initialize_sd();
   initialize_rtc();

-//  dht.begin();
+  dht.begin();

   watchdog_feed();
 }
@@ -100,68 +98,75 @@
   float heat_index;

   uint32_t current_time = rtc.now().unixtime();
+  Serial.print("current_time: ");
+  Serial.println(current_time);
+//  uint32_t last_reading_time = get_last_reading_time();
+
+//  if (current_time - last_reading_time < READING_INTERVAL_S) {
+//    Serial.print("waiting to take next reading... time since last reading: ");
+//    Serial.print(current_time - last_reading_time);
+//    Serial.print(", current_time: ");
+//    Serial.print(current_time);
+//    Serial.print(", last_reading_time: ");
+//    Serial.print(last_reading_time);
+//    Serial.print(", reading_interval: ");
+//    Serial.println(60000);
+//    delay(1000);
+//    return;
+//  } else {
+//
+//  }
+
   read_temperatures(&temperature_f, &humidity, &heat_index);
   log_to_sd(temperature_f, humidity, heat_index, current_time);
+  update_last_reading_time(current_time);
   watchdog_feed();

   transmit(temperature_f, humidity, heat_index, current_time);

   watchdog_feed();
-  delay(READING_DELAY_MS);
+
+  delay(2000);
 }

 void read_temperatures(float *temperature_f, float *humidity, float *heat_index) {
-//  while (true) {
-//    sensors_event_t event;
-//    bool success = true;
-//
-//    dht.temperature().getEvent(&event);
-//
-//    if (!isnan(event.temperature)) {
-//      *temperature_f = dht_util.convertCtoF(event.temperature);
-//    } else {
-//      success = false;
-//    }
-//
-//    dht.humidity().getEvent(&event);
-//
-//    if (!isnan(event.temperature)) {
-//      *humidity = event.relative_humidity;
-//    } else {
-//      success = false;
-//    }
-//
-//    if (success) {
-//      *heat_index = dht_util.computeHeatIndex(*temperature_f, *humidity);
-//
-//      Serial.print("Temperature: ");
-//      Serial.print(*temperature_f);
-//      Serial.println(" *F");
-//
-//      Serial.print("Humidity: ");
-//      Serial.print(*humidity);
-//      Serial.println("%");
-//
-//      Serial.print("Heat index: ");
-//      Serial.println(*heat_index);
-//
-//      return;
-//
-//    } else {
-//      Serial.println("Error reading temperatures!");
-//    }
-//
-//    delay(2000);
-//
-//    // if we continue to fail to read a temperature, the watchdog will
-//    // eventually cause a reboot
-//  }
+  while (true) {
+    bool success = true;
+
+    *temperature_f = dht.readTemperature(true);
+    *humidity = dht.readHumidity();
+
+    if (!isnan(*temperature_f) && !isnan(*humidity)) {
+      *heat_index = dht.computeHeatIndex(*temperature_f, *humidity);
+
+      Serial.print("Temperature: ");
+      Serial.print(*temperature_f);
+      Serial.println(" *F");
+
+      Serial.print("Humidity: ");
+      Serial.print(*humidity);
+      Serial.println("%");
+
+      Serial.print("Heat index: ");
+      Serial.println(*heat_index);
+
+      return;
+
+    } else {
+      Serial.println("Error reading temperatures!");
+    }
+
+    delay(2000);
+
+    // if we continue to fail to read a temperature, the watchdog will
+    // eventually cause a reboot
+  }
 }

 void log_to_sd(float temperature_f, float humidity, float heat_index, uint32_t current_time) {
-  File data_file;
-
-  if (data_file = SD.open("data.csv", FILE_WRITE)) {
+  Serial.println("writing to SD card...");
+
+  if (data_file.open("data.csv", O_CREAT | O_APPEND | O_WRITE)) {
     data_file.print(current_time); data_file.print(",");
     data_file.print(temperature_f); data_file.print(",");
     data_file.print(humidity); data_file.print(",");
@@ -176,40 +181,80 @@

 #ifdef TRANSMITTER_GSM
   void transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time) {
-//    // POST example based on:
-//    // https://github.com/adafruit/Adafruit_FONA/blob/d3d047bf9c47f4f4a2151525d48b5c044daba2e3/Adafruit_FONA.cpp#L1622
-//
-//    connect_to_fona();
-//
-//    if (!fona.enableGPRS(true)) {
-//      Serial.println(F("Failed to turn on"));
-//      while(true);
-//    }
-//
-//    uint16_t statuscode;
-//    int16_t length;
-//    char *url = "requestb.in/1bl66u81";
-//    char *data = "test1=true&test2=false&float=123.3";
-//
-//    if (!fona.HTTP_POST_start(url, F("text/plain"), (uint8_t *) data, strlen(data), &statuscode, (uint16_t *)&length)) {
-//      Serial.println("Failed!");
-//      while(true);
-//    }
-//
-//    if (statuscode != 200) {
-//      Serial.println("status not 200!");
-//    }
-//
-//    fona.HTTP_POST_end();
-  }
-
-//  void connect_to_fona() {
-//    fonaSerial->begin(4800);
-//    if (! fona.begin(*fonaSerial)) {
-//      Serial.println(F("Couldn't find FONA"));
-//      while(true); // watchdog will reboot
-//    }
-//  }
+    // POST example based on:
+    // https://github.com/adafruit/Adafruit_FONA/blob/d3d047bf9c47f4f4a2151525d48b5c044daba2e3/Adafruit_FONA.cpp#L1622
+
+    if (!gsmConnected) connect_to_fona();
+
+    while (!fona_post(temperature_f, humidity, heat_index, current_time)) {
+      Serial.println("failed to POST, trying again...");
+      delay(500);
+    }
+  }
+
+  bool fona_post(float temperature_f, float humidity, float heat_index, uint32_t current_time) {
+    fona.HTTP_POST_end();
+
+    uint16_t statuscode;
+    int16_t length;
+    char *url = "requestb.in/1i65ku31";
+
+    char data[200];
+
+    char temperature_buffer[10];
+    char humidity_buffer[10];
+    char heat_index_buffer[10];
+
+    dtostrf(temperature_f, 4, 3, temperature_buffer);
+    dtostrf(humidity, 4, 3, humidity_buffer);
+    dtostrf(heat_index, 4, 3, heat_index_buffer);
+
+    sprintf(data, "temp=%s&humidity=%s&heat_index=%s&hub=%s&cell=%s&time=%d", temperature_buffer, humidity_buffer, heat_index_buffer, HUB, CELL, current_time);
+
+    while (!fona.HTTP_POST_start(url, F("application/x-www-form-urlencoded"), (uint8_t *) data, strlen(data), &statuscode, (uint16_t *)&length)) {
+      return false;
+    }
+
+    if (statuscode != 200) {
+      Serial.print("status not 200: ");
+      Serial.println(statuscode);
+      return false;
+    }
+
+    fona.HTTP_POST_end();
+    return true;
+  }
+
+  void connect_to_fona() {
+    Serial.println('starting fona serial');
+    fonaSerial->begin(4800);
+
+    Serial.println('starting fona serial 2');
+    if (!fona.begin(*fonaSerial)) {
+      Serial.println("Couldn't find FONA");
+      while(true); // watchdog will reboot
+    }
+
+    delay(2000);
+
+    Serial.println('enabling FONA GPRS');
+
+    uint32_t start = millis();
+
+    while (!fona.enableGPRS(true)) {
+      delay(1000);
+      watchdog_feed();
+
+      if (millis() - start > 30000) {
+        Serial.println('failed to start FONA GPRS after 30 sec');
+        while (true);
+      }
+    }
+
+    Serial.println("Enabled FONA GRPS");
+
+    gsmConnected = true;
+  }
 #endif

 #ifdef TRANSMITTER_WIFI
@@ -295,30 +340,47 @@

   if (!rtc.initialized()) {
     Serial.println("RTC is NOT running!");
-    // following line sets the RTC to the date & time this sketch was compiled
     // TODO - this could make a web request to set and continually update the RTC

     char timestamp[50];
     int i = 0;
     bool timestamp_input = false;

-    Serial.println("RTC needs to be set, enter the current unix timestamp");
-
     while (true) {
-      if (Serial.available()) {
+      Serial.println("RTC needs to be set, enter the current unix timestamp");
+      while (Serial.available()) {
         char c = Serial.read();
         Serial.print("read: ");
         Serial.println(c);
         if (c == '\n') {
           Serial.println("done setting");
+          timestamp_input = true;
           break;
         } else {
           timestamp[i++] = c;
         }
       }
-    }
-
-    rtc.adjust(DateTime(atoi(timestamp)));
+      if (timestamp_input) break;
+      delay(1000);
+    }
+
+    Serial.print("setting timestamp to: ");
+    Serial.println(strtoul(timestamp, NULL, 0));
+
+    rtc.adjust(DateTime(strtoul(timestamp, NULL, 0)));
+    update_last_reading_time(0);
+  }
+}
+
+void initialize_sd() {
+  if (!sd_card.begin(SD_CS)) {
+    Serial.println("failed to initialize SD card");
+    while (true); // watchdog will reboot
+  }
+
+  if (!Fat16::init(&sd_card)) {
+    Serial.println("failed to initialize FAT 16");
+    while (true); // watchdog will reboot
   }
 }

@@ -328,7 +390,7 @@
   #endif

   #ifdef TRANSMITTER_GSM
-//    wdt_enable(WDTO_8S);
+//    Watchdog.enable(8000);
   #endif
 }

@@ -338,7 +400,35 @@
   #endif

   #ifdef TRANSMITTER_GSM
-//    wdt_reset();
+    Watchdog.reset();
   #endif
 }

+void update_last_reading_time(uint32_t timestamp) {
+  if (last_reading_file.open("reading.txt", O_CREAT | O_WRITE)) {
+    last_reading_file.print(timestamp);
+    last_reading_file.close();
+    Serial.println("updated last reading time");
+  } else {
+    Serial.println("unable to write last_reading.txt");
+    while(true); // watchdog will reboot
+  }
+}
+
+uint32_t get_last_reading_time() {
+  char buf[40];
+  int i = 0;
+  char c;
+
+  if (last_reading_file.open("reading.txt", O_READ)) {
+    while ((c = last_reading_file.read()) > 0) {
+      buf[i] = c;
+    }
+    last_reading_file.close();
+  } else {
+    Serial.println("unable to read reading.csv");
+    while(true); // watchdog will reboot
+  }
+
+  return (uint32_t)strtoul(buf, NULL, 0);
+}


Fix typo

Fix typo


Switched speed/direction control to scheduler

--- Pan_Tilt_laser/Pan_Tilt_laser.ino
+++ Pan_Tilt_laser/Pan_Tilt_laser.ino
@@ -19,6 +19,7 @@
     v1.3.1 - Changed probability polling frequency to once a second
     v1.4.0 - Added ON/OFF Missile Switch from Sparkfun
     v1.5.0 - Added scheduler and gaussian library for random values
+    v1.5.1 - Converted speed and direction function to scheduled task
 */
 /**************************************************************************/

@@ -48,7 +49,9 @@

 #define DIRECTION_CHANGE_PROBABILITY 15

-int sleepState = 0;
+
+int markovShakeState =1;
+int changeVal;

 StuGauss gauss;

@@ -68,8 +71,15 @@
 Task pauseTask(&pauseCB);
 Task restTask(&restCB);
 Task sleepTask(&sleepCB);
+Task speedAndDirTask(&updateSpeedAndDir, 750);

 StuScheduler schedule;
+
+void updateSpeedAndDir(){
+  changeVal = getMarkovSpeed(changeVal);
+  markovShakeState = markovState(5, 30);
+
+}

 //halt laser at certain spot for a few moments at this time
 void setNextPauseTime(unsigned long avg_sec_to_pause=15, double variance=12){
@@ -140,6 +150,7 @@
   schedule.addTask(&pauseTask);
   schedule.addTask(&restTask);
   schedule.addTask(&sleepTask);
+  schedule.addTask(&speedAndDirTask);
   randomSeed(analogRead(5));

   mSwitch.heartBeat(3);
@@ -184,15 +195,11 @@
   setNextSleepTime();
 }

-
-
 void loop() {
-  static unsigned long timePassed;
-  static int changeVal;
-  static int markovShakeState;

   schedule.run();

+  //check if switch is on or off and pause if off
   if(!mSwitch.switchState()){
     laser.fire(0);
     mSwitch.ledState(0);
@@ -222,21 +229,13 @@
     shake();
   }

-  //check for rollovers
-  if(timePassed > millis()){
-    timePassed = millis();
-  }
-
-if(millis() - timePassed >= 1200){
-
-    changeVal = getMarkovSpeed(changeVal);
-    markovShakeState = markovState(5, 30);
-    timePassed = millis();
-}

   laser.fire(1);
   delay(5);
 }
+
+
+

 int getMarkovDirection(panTiltPos_t *pt, int changeProb){


Added semicolon

Added semicolon

--- Pan_Tilt_laser/Pan_Tilt_laser.ino
+++ Pan_Tilt_laser/Pan_Tilt_laser.ino
@@ -97,7 +97,7 @@

   if(random(10001) < 2){
     laser.fire(0);
-    delay(random(1000, 5000))
+    delay(random(1000, 5000));

   }


Updated heartbeat interval

Updated heartbeat interval

--- Pan_Tilt_laser/Pan_Tilt_laser.ino
+++ Pan_Tilt_laser/Pan_Tilt_laser.ino
@@ -336,7 +336,7 @@
   unsigned long startTime = millis();
   for(unsigned long i = 0; i < delayVal; i++){
     while(millis() - startTime < 1000){
-      heartBeat(millis(), 10000);
+      heartBeat(millis(), 5000);
       if(startTime > millis()){ //check for rollovers
         startTime = millis();
         break;


Updated robot architecture

Updated robot architecture

--- RobotBase.ino
+++ RobotBase.ino
@@ -6,14 +6,12 @@
 #define LED_PIN 13
 #define RC_RX_PIN 12
 #define RC_TX_PIN 11
-#define SSC_RX_PIN 2
-#define SSC_TX_PIN 3
+#define SSC_RX_PIN 10
+#define SSC_TX_PIN 9
 // power management //
 #define SERVO_PIN 6
-#define AUX_PIN 7
-#define MOTORS_PIN 8
-#define UPS_PIN 9
-#define BATTERY_PIN 10
+#define POWER_PIN 7
+#define MOTOR_PIN 8

 // host communication //
 #define MAX_COMMAND 16
@@ -59,18 +57,12 @@

   // power management pins //
   pinMode(SERVO_PIN, OUTPUT);
-  pinMode(AUX_PIN, OUTPUT);
-  pinMode(MOTORS_PIN, OUTPUT);
-  pinMode(UPS_PIN, OUTPUT);
-  pinMode(BATTERY_PIN, OUTPUT);
+  pinMode(POWER_PIN, OUTPUT);
+  pinMode(MOTOR_PIN, OUTPUT);
   digitalWrite(SERVO_PIN, LOW);
-  digitalWrite(AUX_PIN, LOW);
-  digitalWrite(MOTORS_PIN, LOW);
-  digitalWrite(UPS_PIN, LOW);
-  digitalWrite(BATTERY_PIN, LOW);
-  // enable AUX power
-  pulsePin(AUX_PIN, 20);
-
+  digitalWrite(POWER_PIN, LOW);
+  digitalWrite(MOTOR_PIN, LOW);
+
   // host communication //
   Serial.begin(38400);

@@ -311,14 +303,18 @@
 {
   if (action)
   {
-    pm();
-    driveUART(true);
-    lastDriveCommandTime = millis();
-  }
-  else
-  {
-    driveUART(false);
-    pm();
+    if (!driveEnabled) {
+      pm();
+      driveUART(true);
+      lastDriveCommandTime = millis();
+    }
+  }
+  else
+  {
+    if (driveEnabled) {
+      driveUART(false);
+      pm();
+    }
   }
 }

@@ -370,7 +366,7 @@
   channel = bctoi(2, 2);
   value = bctoi16(4, 4);

-  if (channel >= 18) // channels 18 and above mean all servos
+  if (channel >= 18) // channels 18 and above = all servos
   {
     if (cmd == 's') // servo speed
     {
@@ -470,40 +466,35 @@
 void power()
 {
   cmd = buf[1];
-  if (cmd == 'a') pa();
-  else
   if (cmd == 'm') pm();
   else
-  if (cmd == 'u') pu();
+  if (cmd == 'p') pp();
   else
     nak();
 }

-void pa()
-{
-  pulsePin(AUX_PIN, 20);
-  delay(3000);
-  pulsePin(AUX_PIN, 20);
-}
-
 void pm()
-{ pulsePin(MOTORS_PIN, 20); }
-
-void pu()
-{ pulsePin(UPS_PIN, 5500); }
+{ pulsePin(MOTOR_PIN, 20); }
+
+void pp()
+{
+  pulsePin(POWER_PIN, 20);
+  if (driveEnabled) pm();
+}
+
+//=======================================

 // 'battery voltage' command
 // ex: B
 // result in mV
 void battery()
 {
-  digitalWrite(BATTERY_PIN, HIGH);
-  delay(20);
-  unsigned long voltage = (unsigned long)analogRead(0) * 625 >> 7;
-  digitalWrite(BATTERY_PIN, LOW);
+  unsigned long voltage = (unsigned long)14800;
   Serial.write('b');
   Serial.println(voltage);
 }
+
+//=======================================

 // 'digitalWrite' command
 // ex: W031 - set pin 3 HIGH, W100 - set pin 10 LOW
@@ -558,7 +549,13 @@

 //=======================================
 //
+//
+//
+//
 // helper functions
+//
+//
+//
 //
 //=======================================


Add start and parse on-off cycle

Add start and parse on-off cycle

--- blinker/blinker.ino
+++ blinker/blinker.ino
@@ -4,12 +4,12 @@
 #define RELAY_ON  LOW
 #define RELAY_OFF HIGH

-#define TIME_WAIT  6000
-#define TIME_ON    1000
-#define TIME_OFF   2000
-#define TIME_DOT   1000
-#define TIME_DASH  2000
-#define TIME_MORSE 400
+#define TIME_WAIT  3000
+#define TIME_ON    500
+#define TIME_OFF   300
+#define TIME_DOT   500
+#define TIME_DASH  1000
+#define TIME_MORSE 300

 #define SEQ_WAIT  "w"
 #define SEQ_BLINK "b"
@@ -22,10 +22,7 @@
 void setup() {
   Serial.begin(SERIAL_BAUD);
   pinMode(RELAY_PIN, OUTPUT);
-
-  digitalWrite(RELAY_PIN, RELAY_ON);
-  delay(2000);
-  digitalWrite(RELAY_PIN, RELAY_OFF);
+  ack();
 }

 void loop() {
@@ -59,7 +56,17 @@
   case '7': speed = 7; break;
   case '8': speed = 8; break;
   case '9': speed = 9; break;
+  default : return;
   }
+  ack();
+}
+
+void ack() {
+  delay(200);
+  digitalWrite(RELAY_PIN, RELAY_ON);
+  delay(2000);
+  digitalWrite(RELAY_PIN, RELAY_OFF);
+  delay(200);
 }

 void wait() {


some code reorganization

some code reorganization

--- Memory/FlashReader/FlashReader.ino
+++ Memory/FlashReader/FlashReader.ino
@@ -94,6 +94,127 @@
   eeprom.setType(eepromType);
 }

+
+/**  */
+void loop() {
+
+#ifdef TEST
+  testCode();
+#endif // TEST
+
+#if (INTERACTIVE != 0)
+  loopInteractive();
+#else
+  loopNonInteractive();
+#endif // INTERACTIVE
+}
+
+#if (INTERACTIVE == 0)
+ // Calculated based on max input size expected for one command
+ #define INPUT_SIZE   64
+ // Maximum number of options expected
+ #define MAX_OPTIONS   3
+
+char inputLine[INPUT_SIZE+1] = { 0 };
+int lineLength = 0;
+bool lineComplete = false;
+
+/** loop() function for the non-interactive version. */
+void loopNonInteractive() {
+
+  // read characters from serial interface and put them in input buffer until EOL
+  int ch = Serial.read();
+
+  if ( ch == -1 ) return;
+
+  // check for LF or add character to inputLine
+  if ( ch == 0x0a || ch == 0x0d ) {
+    lineComplete = true;
+  }
+  else {
+    // Add the final 0 to end the C string
+    inputLine[lineLength++] = ch;
+    inputLine[lineLength] = 0;
+
+    // too many chars entered? clear line buffer and issue warning
+    if ( lineLength == INPUT_SIZE ) {
+      lineLength = 0;
+      inputLine[lineLength] = 0;
+      Serial << F("ERR: max. line length exceeded!") << endl;
+    }
+  }
+
+  //
+  // valid commands:
+  // 't ?' - get E(E)PROM type
+  // 't <t>' - set E(E)PROM type
+  // 'r <addr> <len>' - read <len> bytes starting from address <addr>
+  // 'w <addr> <bytes>' - write <bytes> (in IHEX format) to address <addr>
+  //
+  if ( lineComplete ) {
+
+    Serial << strlen(inputLine) << " '" << inputLine << "'" << endl;
+
+    char *command = NULL;
+    int nopts = 0;
+    char* token = strtok(inputLine, " ");
+    char *option[MAX_OPTIONS];
+    bool err = false;
+
+    while ( token && !err ) {
+
+      // 'command' token must have length of 1
+      if ( strlen(token) == 1 && !command ) {
+        command = token;
+      }
+      // 'command' token found, now check for options
+      else if ( command ) {
+        if ( nopts == MAX_OPTIONS ) {
+          err = true;
+          Serial << F("ERR: maximum number of options exceeded") << endl;
+        }
+        option[nopts++] = token;
+      }
+      else if ( !command ) {
+        Serial << F("ERR: no command found!") << endl;
+        err = true;
+      }
+
+      // find next token
+      token = strtok(0, " ");
+    }
+
+    // final control output after tokenisation
+    if ( command && !err ) {
+      Serial << F("command= '") << command << "'" << endl;
+      for ( int i=0; i<nopts; ++i )
+        Serial << F("option[") << i << F("]= '") << option[i] << "'" << endl;
+    }
+
+    if ( !err ) {
+      switch ( command[0] ) {
+        case 't': break;
+        case 'r': break;
+        case 'w': break;
+        case '?': break;
+        default:
+          Serial << F("ERR: unknown command entered!") << endl;
+          err = true;
+      }
+    }
+
+    if ( !err ) {
+      Serial << F("OK") << endl;
+    }
+
+    lineLength = 0;
+    inputLine[lineLength] = 0;
+
+    lineComplete = false;
+  }
+}
+#endif // INTERACTIVE
+
 #if (INTERACTIVE != 0)
 //
 // flash strings for the main menu
@@ -107,56 +228,12 @@
         "t    - set EPROM <t>ype\n"
         "h, ? - display this <h>elp\n"
       /*  "Ctrl-] - leave miniterm.py\n" */ );
-#endif // INTERACTIVE
-
-#if (INTERACTIVE == 0)
- // Calculate based on max input size expected for one command
- #define INPUT_SIZE 64
-
-char inputLine[INPUT_SIZE+1] = { 0 };
-int lineLength = 0;
-bool lineComplete = false;
-#endif // INTERACTIVE
-
-/**  */
-void loop() {
-
-  static bool first = true;
-#if (INTERACTIVE == 0)
-  static byte output_format = 1;
-#else
+
+/** loop() function for the interactive programm version. */
+void loopInteractive() {
+
   static byte output_format = 0;
-#endif // INTERACTIVE
-
-#if (INTERACTIVE == 0)
-
-  int ch = Serial.read();
-
-  if ( ch == -1 ) return;
-
-  // check for LF or add character to inputLine
-  if ( ch == 0x0a || ch == 0x0d ) {
-    lineComplete = true;
-  }
-  else {
-    // Add the final 0 to end the C string
-    inputLine[lineLength++] = ch;
-    inputLine[lineLength] = 0;
-
-    // too many chars entered? clear line buffer and issue warning
-    if ( lineLength == INPUT_SIZE ) {
-      lineLength = 0;
-      inputLine[lineLength] = 0;
-      Serial << F("ERR: max. line length exceeded!") << endl;
-    }
-  }
-#endif // INTERACTIVE
-
-#ifdef TEST
-  testCode();
-#endif // TEST
-
-#if (INTERACTIVE != 0)
+
   uint32_t total_length = 64;
   uint32_t i, len, nBytes;

@@ -195,13 +272,13 @@
       case 'f':  // --- toggle output format
       case 'F':
           if ( output_format == 0 ) {
-	          output_format = 1;
-	          Serial.println(F("Switched to IHEX output format!"));
-	        }
-	        else {
-	          output_format = 0;
-	          Serial.println(F("Switched to DUMP output format!"));
-      	  }
+            output_format = 1;
+            Serial.println(F("Switched to IHEX output format!"));
+          }
+          else {
+            output_format = 0;
+            Serial.println(F("Switched to DUMP output format!"));
+          }
         break;

       case 'l':  // --- set the length
@@ -221,7 +298,7 @@
             len -= nBytes;

             eeprom.read(eepromAddr, eepromData, nBytes);
-	          if ( output_format == 0 )
+            if ( output_format == 0 )
               dumpHex(eepromData, nBytes, eepromAddr);
             else
               writeIhexData(Serial, eepromData, nBytes, eepromAddr);
@@ -282,82 +359,10 @@
           Serial << "?" << endl;
     }
   }
+}
 #endif // INTERACTIVE

-#if (INTERACTIVE == 0)
-  #define MAX_OPTIONS   5
-  //
-  // valid commands:
-  // 't ?' - get E(E)PROM type
-  // 't <t>' - set E(E)PROM type
-  // 'r <addr> <len>' - read <len> bytes starting from address <addr>
-  // 'w <addr> <bytes>' - write <bytes> (in IHEX format) to address <addr>
-  //
-  if ( lineComplete ) {
-
-    Serial << strlen(inputLine) << " '" << inputLine << "'" << endl;
-
-    char *command = NULL;
-    int nopts = 0;
-    char* token = strtok(inputLine, " ");
-    char *option[MAX_OPTIONS];
-    bool err = false;
-
-    while ( token && !err ) {
-
-      // 'command' token must have length of 1
-      if ( strlen(token) == 1 && !command ) {
-        command = token;
-      }
-      // 'command' token found, now check for options
-      else if ( command ) {
-        if ( nopts == MAX_OPTIONS ) {
-          err = true;
-          Serial << F("ERR: maximum number of options exceeded") << endl;
-        }
-        option[nopts++] = token;
-      }
-      else if ( !command ) {
-        Serial << F("ERR: no command found!") << endl;
-        err = true;
-      }
-
-      // find next token
-      token = strtok(0, " ");
-    }
-
-    // final control output after tokenisation
-    if ( command && !err ) {
-      Serial << F("command= '") << command << "'" << endl;
-      for ( int i=0; i<nopts; ++i )
-        Serial << F("option[") << i << F("]= '") << option[i] << "'" << endl;
-    }
-
-    if ( !err ) {
-      switch ( command[0] ) {
-        case 't': break;
-        case 'r': break;
-        case 'w': break;
-        case '?': break;
-        default:
-          Serial << F("ERR: unknown command entered!") << endl;
-          err = true;
-      }
-    }
-
-    if ( !err ) {
-      Serial << F("OK") << endl;
-    }
-
-    lineLength = 0;
-    inputLine[lineLength] = 0;
-
-    lineComplete = false;
-  }
-#endif // INTERACTIVE
-}
-
-
+/** Read unsigned integer, 32 bits from console (experimental). */
 uint32_t readUInt32(void) {

   byte line[20];


Renaming buttons for better code readability

--- Arduino_Thermostat/Arduino_Thermostat.ino
+++ Arduino_Thermostat/Arduino_Thermostat.ino
@@ -16,8 +16,8 @@
 const byte REL_1 = 8;

 // Buttons
-const byte BTN_DOWN = A1;
-const byte BTN_UP = A2;
+const byte BTN_LEFT = A1;
+const byte BTN_RIGHT = A2;

 // LCD display pins
 const byte LCD_RS = 12;
@@ -36,11 +36,13 @@
 // Temperature sensors
 TempSensor *temps1;

-Button *btnDown;
-Button *btnUp;
-
 // Relays
 Relay *relay1;      // relay 1
+
+// Buttons
+Button *btnLeft;
+Button *btnRight;
+

 //
 byte mode = 0;
@@ -84,9 +86,11 @@
   lcd->createChar(0, bkslash);

   temps1 = new TempSensor(TEMPS_1);
-  btnDown = new Button(BTN_DOWN);
-  btnUp = new Button(BTN_UP);
   relay1 = new Relay(REL_1);
+
+  btnLeft = new Button(BTN_LEFT);
+  btnRight = new Button(BTN_RIGHT);
+
   lcd->begin(16, 2);

   lcd->setCursor(0, 0);
@@ -186,10 +190,10 @@

   // manage buttons ------------------------------
   // check if any of buttons has been released
-  bool b1 = btnDown->check(LOW);
-  bool b2 = btnUp->check(LOW);
-
-  if (!b1 && !b2)
+  bool bLeft = btnLeft->check(LOW);
+  bool bRight = btnRight->check(LOW);
+
+  if (!bLeft && !bRight)
     switch (mode) {
       modeEnd = millis()+MODE_DURATION;
       case MODE_NORMAL:
@@ -213,15 +217,15 @@
     cfg.print();
   }

-  if (btnUp->isDown() || btnDown->isDown()){
+  if (btnLeft->isDown() || btnRight->isDown()){
     switch (mode) {
       case MODE_CONFIG_TEMP:
-        if (btnDown->isDown()) {
+        if (btnLeft->isDown()) {
           cfg.data.temp -= tempDelta;
           dp("-");
         }

-        if (btnUp->isDown()) {
+        if (btnRight->isDown()) {
           cfg.data.temp += tempDelta;
           dp("+");
         }


136 bytes

136 bytes

--- arduboy-game/arduboy-game.ino
+++ arduboy-game/arduboy-game.ino
@@ -345,18 +345,17 @@

     arduboy.display();

-
     if (delayTimer) {
-      arduboy.tunes.tone(100, delayTimer - 10);
+      playTone(100, delayTimer - 10);
       delay(delayTimer);
     }
   }

   if (delayTimer) {
-      arduboy.tunes.tone(800, 15);
+      playTone(800, 15);
       delay(15);
-      arduboy.tunes.tone(1200, 30);
+      playTone(1200, 30);
       delay(40);
   }
 }


Moved clr function in with other utility functions.


Use long on Arduino

Use long on Arduino

long == int32 on Arduino.  Tested to 30k pulses/sec :)

--- RightpointLabs.Pourcast.Arduino/Pourcast.ino
+++ RightpointLabs.Pourcast.Arduino/Pourcast.ino
@@ -1,6 +1,6 @@
-volatile int _tap1Pulses = 0;
-volatile int _tap2Pulses = 0;
-const int _startThreshold = 50;
+volatile long _tap1Pulses = 0;
+volatile long _tap2Pulses = 0;
+const long _startThreshold = 50;

 // prep - initialize serial (TX on pin 1) and wire up the interrupts for pulses from the taps (pins 2 and 3)
 void setup() {
@@ -12,14 +12,14 @@

 // handle interrupt pulses from the taps and send the START message
 void tap1Pulse() {
-  int pulses = ++_tap1Pulses;
+  long pulses = ++_tap1Pulses;
   if(pulses == _startThreshold) {
     Serial.print("START 1 ");
     Serial.println(pulses, DEC);
   }
 }
 void tap2Pulse() {
-  int pulses = ++_tap2Pulses;
+  long pulses = ++_tap2Pulses;
   if(pulses == _startThreshold) {
     Serial.print("START 2 ");
     Serial.println(pulses, DEC);
@@ -29,10 +29,10 @@
 // main loop - once a second, check the accumulated pulse counts and send the STOP/CONTINUE/IGNORE message as necessary
 // send an ALIVE message every loop to assist debugging
 void loop() {
-  int lastTap1Pulses = 0;
-  int lastTap2Pulses = 0;
+  long lastTap1Pulses = 0;
+  long lastTap2Pulses = 0;
   while(true) {
-    int tap1Pulses = _tap1Pulses;
+    long tap1Pulses = _tap1Pulses;
     if(lastTap1Pulses != 0 && lastTap1Pulses == tap1Pulses) {
       // complete
       _tap1Pulses = 0;
@@ -55,7 +55,7 @@
       }
     }

-    int tap2Pulses = _tap2Pulses;
+    long tap2Pulses = _tap2Pulses;
     if(lastTap2Pulses != 0 && lastTap2Pulses == tap2Pulses) {
       // complete
       _tap2Pulses = 0;
@@ -82,4 +82,3 @@
     delay(1000);
   }
 }
-


Use the Carriots and InitialState connector

--- bottleopener/bottleopener.ino
+++ bottleopener/bottleopener.ino
@@ -4,14 +4,18 @@

 /////////////////////////////////////////////
 // Include of Iot Platform's connectors
+
 #include "thingspeakSender.h"
 ThingspeakSender thingspeakSender;

 #include "shiftrConnector.h"
 ShiftrConnector shiftrConnector;

-//#include "carriotsConnector.h"
-//CarriotsConnector carriotsConnector;
+#include "carriotsConnector.h"
+CarriotsConnector carriotsConnector;
+
+#include "initialStateConnector.h"
+InitialStateConnector initialStateConnector;
 /////////////////////////////////////////////

 #define PIN_BUTTON   10
@@ -32,7 +36,8 @@
   logger->log("Start setup connection with IoT platforms...\n");
   thingspeakSender.init();
   shiftrConnector.init();
-  //carriotsConnector.init();
+  carriotsConnector.init();
+  initialStateConnector.init();

   //Everything seems to be ok, let's start !
   logger->log("\nBottle Opener up, Let's start to play :) !!!\n");
@@ -63,7 +68,8 @@
 void sendCounter() {
   thingspeakSender.sendMessage("Gwen", counter);
   shiftrConnector.sendMessage("Gwen", counter);
-  //carriotsConnector.sendMessage("Gwen", counter);
+  carriotsConnector.sendMessage("Gwen", counter);
+  initialStateConnector.sendMessage("Gwen", counter);
 }

 /**


remove subscribe & callback

remove subscribe & callback

--- _03-hx711-scale/_03-hx711-scale-v3-adaptor/_03-hx711-scale-esp-12/_03-hx711-scale-esp-12.ino
+++ _03-hx711-scale/_03-hx711-scale-v3-adaptor/_03-hx711-scale-esp-12/_03-hx711-scale-esp-12.ino
@@ -218,9 +218,7 @@
     if (!client.connected()) {
       if  (
         client.connect(MQTT::Connect((char*) clientName.c_str()).set_clean_session().set_keepalive(120))) {
-        client.subscribe(subtopic);
         client.publish(hellotopic, "hello from ESP8266 s06");
-        client.set_callback(callback);
       }
     }


Add Over The Air update

Add Over The Air update

--- ESP8266HueEmulator/ESP8266HueEmulator.ino
+++ ESP8266HueEmulator/ESP8266HueEmulator.ino
@@ -4,6 +4,9 @@
  **/

 #include <ESP8266WiFi.h>
+#include <ESP8266mDNS.h>
+#include <WiFiUdp.h>
+#include <ArduinoOTA.h>
 #include <NeoPixelBus.h>
 #include <NeoPixelAnimator.h> // instead of NeoPixelAnimator branch
 #include "LightService.h"
@@ -120,7 +123,35 @@
     infoLight(red);
     while (1) delay(100);
   }
+
+  // Port defaults to 8266
+  // ArduinoOTA.setPort(8266);

+  // Hostname defaults to esp8266-[ChipID]
+  // ArduinoOTA.setHostname("myesp8266");
+
+  // No authentication by default
+  // ArduinoOTA.setPassword((const char *)"123");
+
+  ArduinoOTA.onStart([]() {
+    Serial.println("Start");
+  });
+  ArduinoOTA.onEnd([]() {
+    Serial.println("\nEnd");
+  });
+  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
+    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
+  });
+  ArduinoOTA.onError([](ota_error_t error) {
+    Serial.printf("Error[%u]: ", error);
+    if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
+    else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
+    else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
+    else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
+    else if (error == OTA_END_ERROR) Serial.println("End Failed");
+  });
+  ArduinoOTA.begin();
+
   // Show that we are connected
   infoLight(green);


Fixed variable bugs in calibrateRC

Fixed variable bugs in calibrateRC

--- Elcano_C2_LowLevel/Elcano_C2_LowLevel.ino
+++ Elcano_C2_LowLevel/Elcano_C2_LowLevel.ino
@@ -2,6 +2,7 @@

 #include <SPI.h>
 #include <Elcano_Serial.h>
+#include <Servo.h>

 //#include <SoftwareSerial.h>
 // @ToDo: Are these specific to some particular setup or trike? If so,
@@ -16,9 +17,11 @@
 // @ToDo: This has changed. Is it specific to some particular setup or trike?
 // If so, it should be moved to Settings.h.
 #define s7s Serial2
+Servo STEER_SERVO;

 #define LOOP_TIME_MS 400
-#define ERROR_HISTORY 20 //number of errors to accumulate
+#define ERROR_HISTORY 20 //number of errors to accumulate
+#define TEN_SECONDS_IN_MICROS 10000000

 /*================ReadTurnAngle ================*/
 // @ToDo: Are these specific to a particular trike? If so, move them to Settings.h.
@@ -70,6 +73,11 @@
 float HubSpeed_kmPh;
 const float  HubSpeed2kmPh = 13000000;
 const unsigned long HubAtZero = 1159448;
+
+int max_rc = MAX_RC;
+int mid = MIDDLE;
+int min_rc = MIN_RC;
+#define LED_PIN_OUT
 //==========================================================================================
 void ISR_TURN_rise() {
   noInterrupts();
@@ -424,36 +432,36 @@
     //Step 1: Wait for controller to turn on, and leave joysticks in neutral
 //    while (micros() < TEN_SECONDS_IN_MICROS ||
 //    ~((RC_Done[RC_ESTP]) && (RC_Done[RC_GO]) && (RC_Done[RC_TURN]) ))
-    digitalWrite(LED_PIN_OUT, HIGH); //wait for 10 seconds to receive radio signal to Calibrate Neutral Positions on RC controller, otherwise proceed
+//    digitalWrite(LED_PIN_OUT, HIGH); //wait for 10 seconds to receive radio signal to Calibrate Neutral Positions on RC controller, otherwise proceed

     //Step 2: Calibrate MIDDLE
     Serial.println(RC_elapsed[RC_GO]);
-    MIDDLE = RC_elapsed[RC_GO];
+    mid = RC_elapsed[RC_GO];
     Serial.print("MIDDLE \t");
-    Serial.println(MIDDLE);
+    Serial.println(mid);
     mic = micros();

     //Step 3: Turn on LED and wait for Right joystick DOWN
-    digitalWrite(LED_PIN_OUT, HIGH);
+    //digitalWrite(LED_PIN_OUT, HIGH);
     while(micros() < (mic + (TEN_SECONDS_IN_MICROS/4)))
-    digitalWrite(LED_PIN_OUT, HIGH);//wait
+    //digitalWrite(LED_PIN_OUT, HIGH);//wait
     //if
-    digitalWrite(LED_PIN_OUT, LOW);
+    //digitalWrite(LED_PIN_OUT, LOW);
     //Set MIN_RC
-    MIN_RC = RC_elapsed[RC_GO];
+    min_rc = RC_elapsed[RC_GO];
     Serial.print("MIN_RC \t");
-    Serial.println(MIN_RC);
+    Serial.println(min_rc);
     mic = micros();

     //Step 4:Turn on LED again and wait for Right joystick UP
-    digitalWrite(LED_PIN_OUT, HIGH);
+    //digitalWrite(LED_PIN_OUT, HIGH);
     while(micros() < (mic + (TEN_SECONDS_IN_MICROS/4)))
-    digitalWrite(LED_PIN_OUT, HIGH);//wait
-
-    MAX_RC = RC_elapsed[RC_GO];
+    //digitalWrite(LED_PIN_OUT, HIGH);//wait
+
+    max_rc = RC_elapsed[RC_GO];
     Serial.print("MAX_RC \t");
-    Serial.println(MAX_RC);
-    digitalWrite(LED_PIN_OUT, LOW);
+    Serial.println(max_rc);
+    //digitalWrite(LED_PIN_OUT, LOW);
 }

 /*---------------------------------------------------------------------------------------*/


Update HC05_BT_config.ino

Update HC05_BT_config.ino

--- HC05_BT_config/HC05_BT_config.ino
+++ HC05_BT_config/HC05_BT_config.ino
@@ -1,32 +1,37 @@
-/*
-ConfigBluetooth HC-05 from Arduino.
-Change name, password and baud using serial port with AT commands, only configurate one time
-After upload the sketch connect your module, the LED should blinking every 2 seconds.
-If LED is blinking too fast, you need to disconnect and connect again but this time pressing the reset little button of the BT module
-Then you can open your serial (Both NL & CR 9600 baud) and should appear and "OK" message means is ready to recieve AT commands. (AT+NAME=)
-After setup you can pair your module
-*/
-#include <SoftwareSerial.h>
-
-SoftwareSerial BTSerial(10, 11); // RX | TX
-
-void setup()
-{
-  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
-  digitalWrite(9, HIGH);
-  Serial.begin(9600);
-  Serial.println("Enter AT commands:");
-  BTSerial.begin(38400);  // HC-05 default speed in AT command more
-}
-
-void loop()
-{
-
-  // Keep reading from HC-05 and send to Arduino Serial Monitor
-  if (BTSerial.available())
-    Serial.write(BTSerial.read());
-
-  // Keep reading from Arduino Serial Monitor and send to HC-05
-  if (Serial.available())
-    BTSerial.write(Serial.read());
+/*
+ConfigBluetooth HC-05 from Arduino.
+Change name, password and baud using serial port with AT commands, only configurate one time
+After upload the sketch connect your module, the LED should blinking every 2 seconds.
+If LED is blinking too fast, you need to disconnect and connect again but this time pressing the reset little button of the BT module
+Then you can open your serial (Both NL & CR 9600 baud) and should appear and "OK" message means is ready to recieve AT commands. (AT+NAME=)
+After setup you can pair your module
+HC-05 GND --- Arduino GND Pin
+HC-05 VCC (5V) --- Arduino 5V
+HC-05 TX --- Arduino Pin 10 (soft RX)
+HC-05 RX --- Arduino Pin11 (soft TX)
+HC-05 Key (PIN 34) --- Arduino Pin 9
+*/
+#include <SoftwareSerial.h>
+
+SoftwareSerial BTSerial(10, 11); // RX | TX
+
+void setup()
+{
+  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
+  digitalWrite(9, HIGH);
+  Serial.begin(9600);
+  Serial.println("Enter AT commands:");
+  BTSerial.begin(38400);  // HC-05 default speed in AT command more
 }
+
+void loop()
+{
+
+  // Keep reading from HC-05 and send to Arduino Serial Monitor
+  if (BTSerial.available())
+    Serial.write(BTSerial.read());
+
+  // Keep reading from Arduino Serial Monitor and send to HC-05
+  if (Serial.available())
+    BTSerial.write(Serial.read());
+}


Use pin names

Use pin names

--- computer_box/computer_box.ino
+++ computer_box/computer_box.ino
@@ -61,8 +61,8 @@
       int pin_status = Serial.parseInt();

       switch(pin_num){
-        case 4:
-        case 13:
+        case fan_pin:
+        case led_pin:
           digitalWrite(pin_num, pin_status);
           break;
       }


With Basic test loop over layers and columns

--- src/Arduino/LED_CUBE/LED_CUBE.ino
+++ src/Arduino/LED_CUBE/LED_CUBE.ino
@@ -57,10 +57,16 @@
   digitalWrite(MR_pin, LOW);
   digitalWrite(MR_pin, HIGH);

-  // DO some magic
-
-  writeShift();
-  delay(500);
+  for(int i = 27; i < 32; i++){
+    shiftRegValues[i] = HIGH;
+    for(int j = 0; j < 27; j++){
+     shiftRegValues[j] = HIGH;
+       writeShift();
+       delay(500);
+     shiftRegValues[j] = LOW;
+   }
+   shiftRegValues[i] = LOW;
+  }

 }


Minor update 2

Minor update 2

* 修复少量bug
* 默认打开自动模式
* 用sscanf进行串口数据判断，更省内存而且可以兼容老sdk
* rtc微调改用RTClib的TimeSpan，省去大坨计算和判断

使用Arduino IDE 1.6.13编译
Sketch uses 17,342 bytes (53%) of program storage space. Maximum is
32,256 bytes.
Global variables use 565 bytes (27%) of dynamic memory, leaving 1,483
bytes for local variables. Maximum is 2,048 bytes.

--- smart_666.ino
+++ smart_666.ino
@@ -4,8 +4,8 @@
 int RECV_PIN = 11;
 IRrecv irrecv(RECV_PIN);
 decode_results results;*/
-bool autoC = false;
-bool noAuto = false;
+bool autoC = true;
+bool noAuto = false; bool no522 = false;
 bool atMain = true;
 unsigned int mainLoop = 0; unsigned short countLoop = 60;
 bool atCount = false; bool showGK = true;
@@ -17,7 +17,6 @@
 #include <Wire.h>
 #include "RTClib.h"
 RTC_DS3231 rtc;
-//char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

 // MFRC522
 #include <SPI.h>
@@ -45,17 +44,17 @@
   Serial.println(F("----------------------------------"));
   Serial.println(F("Serial successfully opened @ 115200"));
   pinMode(4,OUTPUT);
-  // digitalWrite(4, HIGH);
+  digitalWrite(3, HIGH); // for emergency backup
   Serial.print(F("Configured D")); Serial.print(AUDIO_CONTROL); Serial.println(F(" for audio control."));
   delay(200);
   Serial.println(F("Initializing I2C driver ..."));
   if (!rtc.begin()) {
-    Serial.println(F("[x] Couldn't find RTC module.")); noAuto = true;
+    Serial.println(F("[x] Couldn't find RTC module.")); noAuto = true; autoC = false;
   } else {
     if (rtc.lostPower()) {
       Serial.println(F("[!] RTC lost power. Resetting..."));
       rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
-      noAuto = true;
+      noAuto = true; autoC = false;
     }
     DateTime now = rtc.now();
     temp = rtc.getTemperature();
@@ -76,7 +75,7 @@
     mfrc522.PCD_Init(); // Init MFRC522 card
     Serial.println(F("[OK] MFRC522 using SPI Bus."));
   } else {
-    Serial.println(F("[x] Unable to config MFRC522."));
+    Serial.println(F("[x] Unable to config MFRC522.")); no522 = true;
   }
   delay(200);
   /*Serial.println("Initializing IRemote driver ...");
@@ -134,57 +133,77 @@
     delay(2);
   }
   if (ttl.length() > 0) {
-    if (ttl == F("[BN:1]\r\n")) { // manual on, [BN:1]
-      autoC = false;
-      on();
-    } else if (ttl == F("[BN:2]\r\n")) { // manual off, [BN:2]
-      autoC = false;
-      off();
-    } else if (ttl == F("[BN:3]\r\n")) { // auto mode, [BN:3]
-      autoC = !autoC;
-    }
     if (ttl != "OK" /*|| ttl != "\r\nOK" || ttl != "\r\nOK\r\n" || ttl != "OK\r\n" || ttl != "OKOK" */) {
-      if (ttl == F("[BN:32]\r\n")) atMain = true; else atMain = false;
-      if (ttl == F("[BN:31]\r\n") || ttl == F("[BN:1]\r\n") || ttl == F("[BN:2]\r\n") || ttl == F("[BN:3]\r\n")) atCtrl = true; else atCtrl = false;
-      if (ttl == F("[BN:29]\r\n")) atCard = true; else atCard = false;
-      if (ttl == F("[BN:25]\r\n") || ttl == F("[BN:22]\r\n") || ttl == F("[BN:21]\r\n") || ttl == F("[BN:20]\r\n")
-       || ttl == F("[BN:19]\r\n") || ttl == F("[BN:18]\r\n") || ttl == F("[BN:17]\r\n") || ttl == F("[BN:16]\r\n")) {
+      int bn = 0;
+      sscanf(ttl.c_str(), "[BN:%d]\r\n", &bn);
+      //Serial.println(bn,DEC);
+      if (bn == 32) atMain = true; else atMain = false;
+      if (bn == 31 || bn == 1 || bn == 2 || bn == 3) {
+        atCtrl = true;
+        if (bn == 1) {
+          autoC = false; on();
+        } else if (bn == 2) {
+          autoC = false; off();
+        } else if (bn == 3) {
+          autoC = !autoC;
+        }
+      } else atCtrl = false;
+      if (bn == 29) atCard = true; else atCard = false;
+      if (bn == 25 || bn == 22 || bn == 21 || bn == 20 || bn == 19 || bn == 18 || bn == 17 || bn == 16) {
         atRTC = true;
         DateTime now = rtc.now();
-        int d1, d2, d3, e1, e2, e3;
-        d1 = (showTime) ? now.hour() : now.year();
-        d2 = (showTime) ? now.minute() : now.month();
-        d3 = (showTime) ? now.second() : now.day();
-        e1 = (!showTime) ? now.hour() : now.year();
-        e2 = (!showTime) ? now.minute() : now.month();
-        e3 = (!showTime) ? now.second() : now.day();
-        if (ttl == F("[BN:16]\r\n")) { // switch datetime, 16
+        DateTime adj;
+        if (bn == 16) { // switch datetime, 16
           showTime = !showTime;
         } else {
-          if (ttl == F("[BN:22]\r\n")) { // up1
-             d1++;
-          } else if (ttl == F("[BN:21]\r\n")) { // down1
-            d1--;
-          } else if (ttl == F("[BN:20]\r\n")) { // up2
-            d2++;
-          } else if (ttl == F("[BN:19]\r\n")) { // down2
-            d2--;
-          } else if (ttl == F("[BN:18]\r\n")) { // up3
-            d3++;
-          } else if (ttl == F("[BN:17]\r\n")) { // down3
-            d3--;
+          if (bn == 22) { // up1
+            if (showTime) { // hh
+              adj = DateTime(now + TimeSpan(3600));
+            } else { // YYYY
+              adj = DateTime(now + TimeSpan(365, 0, 0, 0));
+            }
+          } else if (bn == 21) { // down1
+            if (showTime) { // hh
+              adj = DateTime(now - TimeSpan(3600));
+            } else { // YYYY
+              adj = DateTime(now - TimeSpan(365, 0, 0, 0));
+            }
+          } else if (bn == 20) { // up2
+            if (showTime) { // mm
+              adj = DateTime(now + TimeSpan(60));
+            } else { // MM
+              adj = DateTime(now + TimeSpan(30, 0, 0, 0));
+            }
+          } else if (bn == 19) { // down2
+            if (showTime) { // mm
+              adj = DateTime(now - TimeSpan(60));
+            } else { // MM
+              adj = DateTime(now - TimeSpan(30, 0, 0, 0));
+            }
+          } else if (bn == 18) { // up3
+            if (showTime) { // ss
+              adj = DateTime(now + TimeSpan(1)); // +1s
+            } else { // DD
+              adj = DateTime(now + TimeSpan(1, 0, 0, 0));
+            }
+          } else if (bn == 17) { // down3
+            if (showTime) { // ss
+              adj = DateTime(now - TimeSpan(1));
+            } else { // DD
+              adj = DateTime(now - TimeSpan(1, 0, 0, 0));
+            }
           }
-          if (showTime) rtc.adjust(DateTime(e1, e2, e3, d1, d2, d3)); else rtc.adjust(DateTime(d1, d2, d3, e1, e2, e3));
+          rtc.adjust(adj);
         }
       } else {
         if (atRTC) {
-          if (ttl != F("[BN:0]\r\n")) atRTC = false;
+          if (bn != 0) atRTC = false;
         }
       }

-      if (ttl == F("[BN:30]\r\n")) {
+      if (bn == 30) {
         if (noAuto) {
-          Serial.println(F("RTC\xC4\xA3\xBF\xE9\xB9\xCA\xD5\xCF")); //RTC模块故障
+          Serial.println("DS12(0,0,'RTC\xC4\xA3\xBF\xE9\xB9\xCA\xD5\xCF',1);"); //DS12(0,0,'RTC模块故障',1);
         } else {
           atCount = true; countLoop = 59;
         }
@@ -235,7 +254,7 @@
       Serial.print(F("SBC(58);DS16(126,63,'\xD7\xD4\xB6\xAF\xC4\xA3\xCA\xBD',0,0);")); //DS16(126,63,'自动模式',0,0);
     }
     if (noAuto) {
-      Serial.println(F("RTC\xC4\xA3\xBF\xE9\xB9\xCA\xD5\xCF")); //RTC模块故障
+      Serial.println(F("DS12(0,0,'RTC\xC4\xA3\xBF\xE9\xB9\xCA\xD5\xCF',1);")); //DS12(0,0,'RTC模块故障',1);
     } else {
       DateTime now = rtc.now();
       Serial.print(F("SBC(53);DS12(133,152,'"));
@@ -245,17 +264,21 @@
     }
   }
   if (atRTC) {
-    DateTime now = rtc.now();
-    Serial.print(F("SBC(0);CBOF(0,32,220,65,5,0);"));
-    if (showTime) {
-      Serial.print(F("DS32(56,32,'"));
-      if (now.hour() < 10) { Serial.print(0); Serial.print(now.hour()); } else Serial.print(now.hour()); Serial.print(F("',1,0);DS32(90,32,'/',1,0);DS32(102,32,'"));
-      if (now.minute() < 10) { Serial.print(0); Serial.print(now.minute()); } else Serial.print(now.minute()); Serial.print(F("',1,0);DS32(135,32,'/',1,0);DS32(146,32,'"));
-      if (now.second() < 10) { Serial.print(0); Serial.print(now.second()); } else Serial.print(now.second()); Serial.println(F("',1,0);"));
+    if (noAuto) {
+      Serial.println(F("DS12(0,0,'RTC\xC4\xA3\xBF\xE9\xB9\xCA\xD5\xCF',1);")); //DS12(0,0,'RTC模块故障',1);
     } else {
-      Serial.print(F("DS32(30,32,'")); Serial.print(now.year()); Serial.print(F("',1,0);DS32(90,32,'/',1,0);DS32(102,32,'"));
-      Serial.print(now.month()); Serial.print(F("',1,0);DS32(135,32,'/',1,0);DS32(146,32,'"));
-      Serial.print(now.day()); Serial.println(F("',1,0);"));
+      DateTime now = rtc.now();
+      Serial.print(F("SBC(0);CBOF(0,32,220,65,5,0);"));
+      if (showTime) {
+        Serial.print(F("DS32(56,32,'"));
+        if (now.hour() < 10) { Serial.print(0); Serial.print(now.hour()); } else Serial.print(now.hour()); Serial.print(F("',1,0);DS32(90,32,'/',1,0);DS32(102,32,'"));
+        if (now.minute() < 10) { Serial.print(0); Serial.print(now.minute()); } else Serial.print(now.minute()); Serial.print(F("',1,0);DS32(135,32,'/',1,0);DS32(146,32,'"));
+        if (now.second() < 10) { Serial.print(0); Serial.print(now.second()); } else Serial.print(now.second()); Serial.println(F("',1,0);"));
+      } else {
+        Serial.print(F("DS32(30,32,'")); Serial.print(now.year()); Serial.print(F("',1,0);DS32(90,32,'/',1,0);DS32(102,32,'"));
+        Serial.print(now.month()); Serial.print(F("',1,0);DS32(135,32,'/',1,0);DS32(146,32,'"));
+        Serial.print(now.day()); Serial.println(F("',1,0);"));
+      }
     }
   }
   if (atCard) {
@@ -326,11 +349,13 @@
       case 12: if (tc >= 0503 && tc <= 0600 || tc >= 5500) off(); else on(); break;
       case 13: off(); break;
       case 14: if (tc >= 0000 && tc <= 2000) off(); else on(); break;
-      case 15: if (tc >= 0503 && tc <= 0530) off(); else on(); break;
+      case 15: if (tc >= 0503 && tc <= 0630) off(); else on(); break;
       case 16: if (tc >= 0003 && tc <= 0100 || tc >= 5003 && tc <= 5100) off(); else on(); break;
       case 17: if (tc >= 1000 && tc <= 2000) off(); else on(); break;
-      case 22: off(); break;
-      case 18: case 19: case 20: case 21: case 23: on(); break;
+      case 18: if (tc >= 5000) off(); else on(); break;
+      case 20: if (tc >= 2003 && tc <= 2100) off(); else on(); break;
+      case 19: case 22: off(); break;
+      case 21: case 23: on(); break;
     }
   }


I've managed to make it worse.

I've managed to make it worse.

--- arduino/tachometer/tachometer.ino
+++ arduino/tachometer/tachometer.ino
@@ -3,10 +3,8 @@

 float conversion_factor = 1.0;

-volatile int pulse_count[2] = {
-  0};
-volatile int ring_buffer[2][BUF_LEN] = {
-  0};
+volatile int pulse_count[2] = {0};
+volatile int ring_buffer[2][BUF_LEN] = {0};

 void setup()
 {
@@ -29,16 +27,26 @@
   int counts[2][BUF_LEN];

   cli();
+
+  tach_0 = pulse_count[0];
+  tach_1 = pulse_count[1];
+
   for(int i = 0; i < 2; i++)
+  {
     for(int j = 0; j < BUF_LEN; j++)
+    {
       counts[i][j] = ring_buffer[i][j];
+    }
+  }
+
   sei();

-  //  qsort(counts[IRQ_0][0], BUF_LEN, sizeof(int), cmp<int>);
-  //  qsort(counts[IRQ_1][0], BUF_LEN, sizeof(int), cmp<int>);
+  qsort(counts[IRQ_0], BUF_LEN, sizeof(int), cmp<int>);
+  qsort(counts[IRQ_1], BUF_LEN, sizeof(int), cmp<int>);

   // report the median
-  send(counts[IRQ_0][BUF_LEN / 2], counts[IRQ_1][BUF_LEN / 2]);
+  // send(counts[IRQ_0][BUF_LEN / 2], counts[IRQ_1][BUF_LEN / 2]);
+  send(tach_0, tach_1);

   digitalWrite(LED, !digitalRead(LED));
   delay(1000 / HZ);
@@ -54,18 +62,20 @@
   Serial.println();
 }

-// ISR
-
 void timer_isr()
 {
   static int idx = -1;
-  idx = idx++ % BUF_LEN;
+  idx = ++idx % BUF_LEN;

-  ring_buffer[IRQ_0][idx] = pulse_count[IRQ_0];
-  ring_buffer[IRQ_1][idx] = pulse_count[IRQ_1];
+  for(int i =0;i < 2; i++)
+  {
+    ring_buffer[i][idx] = pulse_count[i];
+  }

   for(int i =0; i < 2; i++)
+  {
     pulse_count[i] = 0;
+  }
 }

 void tach_0_isr()
@@ -78,3 +88,7 @@
   pulse_count[IRQ_1]++;
 }

+
+
+
+


Update SoftwareSerialExample.ino

Update SoftwareSerialExample.ino

Also includes Micros per https://www.arduino.cc/en/Reference/SoftwareSerial

--- hardware/arduino/avr/libraries/SoftwareSerial/examples/SoftwareSerialExample/SoftwareSerialExample.ino
+++ hardware/arduino/avr/libraries/SoftwareSerial/examples/SoftwareSerialExample/SoftwareSerialExample.ino
@@ -13,7 +13,7 @@
  so only the following can be used for RX:
  10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69

- Not all pins on the Leonardo support change interrupts,
+ Not all pins on the Leonardo and Micro support change interrupts,
  so only the following can be used for RX:
  8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).


Enlarge P1 buffer to hold a full telegram to avoid missing data (somehow)

--- client_arduino/arduino_client.ino
+++ client_arduino/arduino_client.ino
@@ -11,7 +11,7 @@

 #define SERIAL_RX_PIN D5
 #define LED_PIN D4
-#define P1_BUFFER_SIZE_BYTES 64
+#define P1_BUFFER_SIZE_BYTES 4096

 #define READ_TIMEOUT_MILLIS 5000


add animation cycling every 30 secs

add animation cycling every 30 secs

--- xmas-pixels.ino
+++ xmas-pixels.ino
@@ -8,6 +8,7 @@

 #define PIN 6
 #define BUTTON_PIN 2
+#define ANIMATION_CYCLE_INTERVAL 30000

 Adafruit_NeoPixel strip = Adafruit_NeoPixel(12, PIN);
 FadeAnimation fadeAnimation(&strip, 150, 150, 255);
@@ -16,9 +17,12 @@
 TheaterChaseAnimation theaterChaseAnimation(&strip);
 RainbowCycleAnimation rainbowCycleAnimation(&strip);
 NeoPixelAnimation *animations[] = {&rainbowAnimation, &fadeAnimation, &sparksAnimation, &theaterChaseAnimation, &rainbowCycleAnimation};
+byte animationCount = (sizeof(animations) / sizeof(NeoPixelAnimation *));

 bool buttonPreviousState = HIGH;
 byte animationIndex = 0;
+unsigned long timeForNextAnimation = 0;
+bool cycleAnimations = true;

 void setup() {
   pinMode(BUTTON_PIN, INPUT_PULLUP);
@@ -26,9 +30,14 @@
   strip.begin();
   strip.setBrightness(20);
   strip.show();
+
+  timeForNextAnimation = millis() + ANIMATION_CYCLE_INTERVAL;
 }

 void loop() {
+  if (cycleAnimations) {
+    checkTimeForNextAnimation();
+  }
   checkButton();
   animations[animationIndex]->nextFrame();
 }
@@ -41,13 +50,38 @@
     // Check if button is still low after debounce.
     buttonNewState = digitalRead(BUTTON_PIN);
     if (buttonNewState == LOW) {
-      animationIndex++;
-      if (animationIndex >= (sizeof(animations) / sizeof(NeoPixelAnimation *))) {
-        animationIndex = 0;
-      }
-      animations[animationIndex]->reset();
+      buttonPressed();
+      delay(20);
     }
   }
   buttonPreviousState = buttonNewState;
 }

+void buttonPressed() {
+  if(cycleAnimations) {
+    cycleAnimations = false;
+    return;
+  }
+  if (animationIndex == animationCount - 1) { //last animation
+    cycleAnimations = true;
+    timeForNextAnimation = millis() + ANIMATION_CYCLE_INTERVAL;
+  }
+  nextAnimation();
+}
+
+void checkTimeForNextAnimation() {
+  unsigned long currentTime = millis();
+  if (currentTime >= timeForNextAnimation) {
+    nextAnimation();
+    timeForNextAnimation = millis() + ANIMATION_CYCLE_INTERVAL;
+  }
+}
+
+void nextAnimation() {
+  animationIndex++;
+  if (animationIndex >= animationCount) {
+    animationIndex = 0;
+  }
+  animations[animationIndex]->reset();
+}
+


Update 2018-Firefighter.ino

Update 2018-Firefighter.ino

--- 2018-Firefighter/2018-Firefighter.ino
+++ 2018-Firefighter/2018-Firefighter.ino
@@ -116,16 +116,19 @@
   } else {
     digitWrite(FLAME_LED, LOW);
   }
+
   if (usingCamera()){
     digitalWrite(CAMERA_LED, HIGH);
   } else {
     digitalWrite(CAMERA_LED, LOW);
   }
+
   if(detectBaby()){
     digitalWrite(BABY_LED, HIGH);
   } else {
     digitalWrite(BABY_LED, LOW);
   }
+
   if(detectSound()){
     digitalWrite(MIC_LED, HIGH);
   } else {


Don't switch to the old state, switch to the new state.

--- shofanduino2/shofanduino2.ino
+++ shofanduino2/shofanduino2.ino
@@ -165,7 +165,7 @@

   if (new_state != state) {
     // switch the relays!
-    switch (state) {
+    switch (new_state) {
       case FAN_OFF:
         // because we don't know the status of the 3-way switch, we switch both
         // relays at the same time and hope there is no short circuit. This should


Added a comment expalining magnetometerDemo.

--- examples/Demo/Demo.ino
+++ examples/Demo/Demo.ino
@@ -342,6 +342,10 @@
   }
 }

+// Print the raw readings from the X and Y axes on the
+// magnetometer.  (The magnetometer also has a Z axis which we do
+// not display because it would not fit and is less likely to be
+// useful.)
 void magnetometerDemo()
 {
   displayBackArrow();


Formatted example file

Formatted example file

--- examples/FTDebouncer_demo.ino
+++ examples/FTDebouncer_demo.ino
@@ -1,5 +1,7 @@
 #include "FTDebouncer.h"
+
 FTDebouncer pinDebouncer(30);
+
 void setup(){
 	Serial.begin(57600);
 	pinDebouncer.addPin(2, HIGH, PinMode::InputPullup);
@@ -32,11 +34,11 @@
 	usElapsed = micros() - us;
 	Serial.println(usElapsed);
 }
-void pinActivated(uint8_t _pinNr){
+void pinActivated(uint8_t pinNr){
 	Serial.print("Pin activated: ");
-	Serial.println(_pinNr);
+	Serial.println(pinNr);
 }
-void pinDeactivated(uint8_t _pinNr){
+void pinDeactivated(uint8_t pinNr){
 	Serial.print("Pin deactivated: ");
-	Serial.println(_pinNr);
+	Serial.println(pinNr);
 }


angle

angle

--- examples/Unit/ANGLE/ANGLE.ino
+++ examples/Unit/ANGLE/ANGLE.ino
@@ -1,43 +1,37 @@
 /*
 *******************************************************************************
 * Copyright (c) 2021 by M5Stack
-*                  Equipped with M5Stick-C sample source code
-*                          配套  M5Stick-C 示例源代码
-* Visit the website for more information：https://docs.m5stack.com/en/core/m5stickc
-* 获取更多资料请访问：https://docs.m5stack.com/zh_CN/core/m5stickc
+*                  Equipped with M5Core sample source code
+*                          配套  M5Core 示例源代码
+* Visit the website for more information：https://docs.m5stack.com/en/core/gray
+* 获取更多资料请访问：https://docs.m5stack.com/zh_CN/core/gray
 *
-* describe：WiFi connect.  wifi连接
-* date：2021/7/27
+* describe：Angle.  角度计
+* date：2021/8/9
 *******************************************************************************
-*/
-
-/*
-    Description: Read ANGLE Unit input analog quantity, and convert to 12-bit digital quantity for display
+  Description: Read the Angle of the angometer and convert it to digital display
+  读取角度计的角度，并转换为数字量显示
 */

 #include <M5Stack.h>
-// select the input pin for the potentiometer
-int sensorPin = 36;
-// last variable to store the value coming from the sensor
-int last_sensorValue = 100;
-// current variable to store the value coming from the sensor
-int cur_sensorValue = 0;
+int sensorPin = 36; // set the input pin for the potentiometer.  设置角度计的输入引脚
+
+int last_sensorValue = 100; // Stores the value last read by the sensor.  存储传感器上次读取到的值
+int cur_sensorValue = 0;  // Stores the value currently read by the sensor.  存储传感器当前读取到的值

 void setup() {
-  M5.begin();
-  M5.Power.begin();
-  pinMode(sensorPin, INPUT);
+  M5.begin(); //Init M5Stack.  初始化M5Stack
+  M5.Power.begin(); //Init power  初始化电源模块
+  pinMode(sensorPin, INPUT);  //Sets the specified pin to input mode.  设置指定引脚为输入模式
   dacWrite(25, 0);
-  M5.Lcd.setTextSize(2);
-  M5.Lcd.setCursor(0, 0);
+  M5.Lcd.setTextSize(2);  //Set the font size to 2.  设置字体大小为2
   M5.Lcd.print("the value of ANGLE: ");
 }

 void loop() {
-  // read the value from the sensor:
-  cur_sensorValue = analogRead(sensorPin);
-  M5.Lcd.setCursor(0, 25);
-  if(abs(cur_sensorValue - last_sensorValue) > 10){//debaunce
+  cur_sensorValue = analogRead(sensorPin);  // read the value from the sensor.  读取当前传感器的值
+  M5.Lcd.setCursor(0, 25);  //Place the cursor at (0,25).  将光标固定在(0,25)
+  if(abs(cur_sensorValue - last_sensorValue) > 10){ //debaunce
     M5.Lcd.fillRect(0, 25, 100, 25, BLACK);
     M5.Lcd.print(cur_sensorValue);
     last_sensorValue = cur_sensorValue;


Using only one strip leds, keep things simples

--- wellnessmirror/wellnessmirror.ino
+++ wellnessmirror/wellnessmirror.ino
@@ -12,19 +12,15 @@
 int alpha;
 int periode = 2000;
 int totalStrips = TOTAL_STRIPS;
-Adafruit_NeoPixel strip1 = Adafruit_NeoPixel(28, 6, NEO_GRB + NEO_KHZ800);
-Adafruit_NeoPixel strip2 = Adafruit_NeoPixel(74, 5, NEO_GRB + NEO_KHZ800);
-Adafruit_NeoPixel strips[2] = {strip1, strip2};
+Adafruit_NeoPixel strip = Adafruit_NeoPixel(102, 5, NEO_GRB + NEO_KHZ800);

 void setup() {
   initLeds();
 }

 void initLeds(){
-  for(int i = 0; i<totalStrips; i++){
-      strips[i].begin();
-      strips[i].show();
-  }
+  strip.begin();
+  strip.show();
 }
 void loop() {
   fadeSlow(0, 0, 255);
@@ -46,12 +42,10 @@
 }

 void tintPixels(int r, int g, int b, int a){
- for(int s = 0; s<totalStrips; s++){
-    strips[s].setBrightness(a);
-    for(uint16_t i=0; i<strips[s].numPixels(); i++) {
-        uint32_t c = strips[s].Color(r, g, b);
-        strips[s].setPixelColor(i,c);
-    }
-    strips[s].show();
+  strip.setBrightness(a);
+  for(uint16_t i=0; i<strip.numPixels(); i++) {
+      uint32_t c = strip.Color(r, g, b);
+      strip.setPixelColor(i,c);
   }
+  strip.show();
 }


Minor change for the custom commands

Minor change for the custom commands

Added a carriage sent to Dongle before SMARTY commands to make sure last
command in the queue was sent (clear the queue)
Added a prototype function to make Go Pro ready for USB mode (using a
Serial command '^', not yet available)


some fixes

some fixes

--- f-preform-02/f-preform-02.ino
+++ f-preform-02/f-preform-02.ino
@@ -53,6 +53,8 @@
 #define L210_PIN 25
 #define L211_PIN 27
 #define L212_PIN 22
+#define LMIN_PIN 22
+#define LMAX_PIN 45
 #define L1R_PIN 2
 #define L1G_PIN 3
 #define L1B_PIN 4
@@ -244,12 +246,12 @@
     // Print a message to the LCD.
     lcd.backlight();
     // lcd.setCursor(0, 1); lcd.print(field[8][2]);
-    for (int i = 22; i <= 45; i++)
+    for (int i = LMIN_PIN i <= LMAX_PIN; i++)
     {
         // init common leds
         pinMode(i, OUTPUT);
     }
-    for (int i = 2; i <= 13; i++)
+    for (int i = L1R_PIN; i <= L4B_PIN; i++)
     {
         // init rgb leds
         pinMode(i, OUTPUT);
@@ -292,13 +294,13 @@
     reset_buttons_flagClick;
     for (int j = random(100, 1000); j > 0; j = j - 100)
     {
-        for (int i = 2; i <= 13; i++)
+        for (int i = L1R_PIN; i <= L4B_PIN; i++)
         {
             // init rgb leds
             digitalWrite(i, HIGH);
         }
         delay(j);
-        for (int i = 2; i <= 13; i++)
+        for (int i = L1R_PIN; i <= L4B_PIN; i++)
         {
             // init rgb leds
             // lcd.setCursor(12, 1); lcd.print(analogRead(b11));


Haven't been able to fix the read/write problem. We are reverting back, but keeping the code in the file. We will work on running the program, while the tablet is not connected.

--- BackEnd/BackEnd.ino
+++ BackEnd/BackEnd.ino
@@ -469,7 +469,7 @@
 //------------------------------------------------------------
 void initBoardStateFromFile(char* _sFullFilePath) {

-  Serial.println("Init from board file");
+//  Serial.println("Init from board file");
   // Open File
   FILE *fp;
   char sJsonFile[CONFIG_FILE_MAX_SIZE];
@@ -481,11 +481,17 @@
   {
     Serial.print("Empty file: ");
     Serial.println(_sFullFilePath);
-  }
+
+    // The file is empty for some reason. Let's use the standard init function
+    initBoardState();
+    return;
+  }
+  /*
   else
   {
     Serial.println(sJsonFile);
   }
+  */
 //  Serial.println("File Close");
   fclose(fp);

@@ -512,7 +518,7 @@
     aJsonObject *pJsonConnections = aJson.getObjectItem(poMsg, "connections");
     if( pJsonConnections )  // Check if there is pin info
     {
-       Serial.println("Processing Connections");
+//       Serial.println("Processing Connections");
       procConnMsg( pJsonConnections );
     }
     else
@@ -1533,9 +1539,11 @@
     if( Output )
     {
       // Write the state
-      Serial.println("Board State:");
-      Serial.println(sTempString);
-
+//      Serial.println("Board State:");
+ //     Serial.println(sTempString);
+
+      fputs((char *)buf, Output);
+/*
       if( fputs((char *)buf, Output) )
       {
         Serial.println("Write success to file. ");
@@ -1544,6 +1552,7 @@
       {
         Serial.println("ERROR printing to file");
       }
+      */
     }
     else
     {
@@ -1673,8 +1682,8 @@

   // Initialize HW and JSON protocol code
   //Serial.println("Initilize Hardware");
-//  initBoardState(); // Assure a state
-  initBoardStateFromFile(BOARD_CONFIG_FILE_FULL_PATH); // Replace the state with the file, if available
+  initBoardState(); // Assure a state
+//  initBoardStateFromFile(BOARD_CONFIG_FILE_FULL_PATH); // Replace the state with the file, if available
   //delay(1000);

   //Serial.println("Starting WebSocket");
@@ -1686,21 +1695,26 @@
 int g_iCatNumber = 0;
 int g_iChangeSsid = 1;
 int g_iWriteToFile = 1;
+int g_iSkipFirstWrite = 0;

 void loop()
 {

 // TESTING
-  getSerialCommand();
-
-  if (millis() - last_print > 1000)
-  {
+//  getSerialCommand();
+
+  if (millis() - last_print > 5000)
+  {
+    /*
     // Save board state every ~1 sec
-//   writeBoardStateToFile(BOARD_CONFIG_FILE_FULL_PATH);
+    if(g_iSkipFirstWrite)
+      writeBoardStateToFile(BOARD_CONFIG_FILE_FULL_PATH);

-    // Flush serial buffer
-    //Serial.flush();
-
+    // Flush serial buffer to prevent crashes
+    Serial.flush();
+
+    g_iSkipFirstWrite = 1;
+    */
     last_print = millis();
   }


fix the PWM sync

fix the PWM sync

--- examples/RF12/ledNode/ledNode.ino
+++ examples/RF12/ledNode/ledNode.ino
@@ -79,9 +79,15 @@
 }

 void setup () {
+  // fix timer 1 so it also runs in fast PWM mode, to match timer 0
+  bitSet(TCCR1B, WGM12);
+  // set up the default ramps
   for (byte i = 0; i < sizeof stdRamps / sizeof *stdRamps; ++i)
     saveRamp(i, stdRamps + i);
+  // intialize wireless
   rf12_initialize(1, RF12_868MHZ, 19);
+  // test code: start up with ramp #1
+  //loadRamp(1);
 }

 void loop () {


add log

add log

--- arduino/opencr_arduino/opencr/libraries/turtlebot3/examples/turtlebot3_burger/turtlebot3_core/turtlebot3_core.ino
+++ arduino/opencr_arduino/opencr/libraries/turtlebot3/examples/turtlebot3_burger/turtlebot3_core/turtlebot3_core.ino
@@ -177,8 +177,20 @@

 void resetCallback(const std_msgs::Empty& reset_msg)
 {
+  char log_msg[50];
+
+  sprintf(log_msg, "Start Calibration of Gyro");
+  nh.loginfo(log_msg);
+
   sensors.calibrationGyro();
+
+  sprintf(log_msg, "Calibration End");
+  nh.loginfo(log_msg);
+
   initOdom();
+
+  sprintf(log_msg, "Reset Odometry");
+  nh.loginfo(log_msg);
 }

 /*******************************************************************************


Update comments

Update comments

--- Arduino/Arduino.ino
+++ Arduino/Arduino.ino
@@ -10,17 +10,18 @@
 Servo leftRight;
 Servo upDown;

+// VARIABLES
 int pos = 90;       // variable to store the servo position
 int ByteReceived;   // store byte recieved via serial

-
+// INITIALIZE
 void setup() {
   throttle.attach(9);  // attaches the servo on pin 9 to the servo object
   Serial.begin(9600);
   throttle.write(pos);
 }

-
+// UPDATE
 void loop() {
   if (Serial.read() != -1) {
     ByteReceived = Serial.read();


added EEPROM-Erase

added EEPROM-Erase

--- InitApp/App/App.ino
+++ InitApp/App/App.ino
@@ -24,10 +24,6 @@
 char MAC_char[18];

 static int LED = LED_BUILTIN;
-
-/*char *ssid = "HUAWEI-BF71";
-char *pass = "r6b0n8f5\0\0\0\0\0\0\0\0";
-*/

 void setup()
 {
@@ -190,6 +186,18 @@
     return false;
 }

+void EraseEEPROM(){
+    EEPROM.begin(512);
+    // write a 0 to all 512 bytes of the EEPROM
+    for (int i = 0; i < 512; i++)
+      EEPROM.write(i, 0);
+
+    // turn the LED on when we're done
+    pinMode(13, OUTPUT);
+    digitalWrite(13, HIGH);
+    EEPROM.end();
+}
+
 void LoadConfig(int sizeEEPROM)
 {
     int c = 0;


final bluetooth control building without ethernet shield

--- Sketches/Bluetooth_Building_Control_System_fuzzy_IR_Ethernet_Mega/Bluetooth_Building_Control_System_fuzzy_IR_Ethernet_Mega.ino
+++ Sketches/Bluetooth_Building_Control_System_fuzzy_IR_Ethernet_Mega/Bluetooth_Building_Control_System_fuzzy_IR_Ethernet_Mega.ino
@@ -34,7 +34,7 @@
 #define IRreceiver 2
 #define Buzzer 11
 #define led1 8
-//#define Relay1 9
+#define Relay1 3
 #define Relay2 10

@@ -84,7 +84,7 @@
   lcd.print("   Control Center   ");
   //pinmode settings
   pinMode(led1, OUTPUT);
-  //pinMode(Relay1, OUTPUT);
+  pinMode(Relay1, OUTPUT);
   pinMode(Relay2, OUTPUT);
   pinMode(Buzzer, OUTPUT);

@@ -312,7 +312,7 @@
   }

   //Checking fuzzy levels for humidity
-  if (H > 60)
+  if (H > 70)
   {
     for (int i = 1; i < 5; i++)
     {
@@ -325,7 +325,7 @@
       funShowFuzzyResult();
     }
   }
-  else if ((H >= 50) && (H < 60))
+  else if ((H >= 60) && (H < 70))
   {
     hflag[0] = 0;
     hflag[2] = 0;
@@ -339,7 +339,7 @@
       funShowFuzzyResult();
     }
   }
-  else if ((H >= 40) && (H < 50))
+  else if ((H >= 40) && (H < 60))
   {
     hflag[0] = 0;
     hflag[1] = 0;
@@ -449,8 +449,7 @@
   lcd.clear();
   switch (stemperature)
   {
-    case 1: lcd.setCursor(0, 0); lcd.print("Temp:     Very Cold");
-      lcd.setCursor(0, 1); lcd.print("Fuzzy 1"); break;
+    case 1: lcd.setCursor(0, 0); lcd.print("Temp:     Very Cold");  break;
     case 2: lcd.setCursor(0, 0); lcd.print("Temp:     Cold");       break;
     case 3: lcd.setCursor(0, 0); lcd.print("Temp:     Normal");     break;
     case 4: lcd.setCursor(0, 0); lcd.print("Temp:     Hot");        break;
@@ -459,12 +458,25 @@
   lcd.setCursor(0, 1); lcd.print(t1); lcd.print(" *C");
   switch (shumidity)
   {
-    case 1: lcd.setCursor(0, 2); lcd.print("Humidity: Very Humid");    break;
-    case 2: lcd.setCursor(0, 2); lcd.print("Humidity: Humid");         break;
-    case 3: lcd.setCursor(0, 2); lcd.print("Humidity: Normal");        break;
-    case 4: lcd.setCursor(0, 2); lcd.print("Humidity: Dry");           break;
-    case 5: lcd.setCursor(0, 2); lcd.print("Humidity: Very Dry");      break;
-  }
+    case 1: lcd.setCursor(0, 2); lcd.print("Humidity: Very Humid");   digitalWrite(Relay2,HIGH);  digitalWrite(Relay1,HIGH); break;
+    case 2: lcd.setCursor(0, 2); lcd.print("Humidity: Humid");        digitalWrite(Relay2,HIGH);  digitalWrite(Relay1,LOW); break;
+    case 3: lcd.setCursor(0, 2); lcd.print("Humidity: Normal");       digitalWrite(Relay2,LOW);  digitalWrite(Relay1,LOW); break;
+    case 4: lcd.setCursor(0, 2); lcd.print("Humidity: Dry");          digitalWrite(Relay2,LOW);  digitalWrite(Relay1,LOW); break;
+    case 5: lcd.setCursor(0, 2); lcd.print("Humidity: Very Dry");     digitalWrite(Relay2,LOW);  digitalWrite(Relay1,LOW); break;
+  }
+
+  /*
+  switch(stemperature+(5-shumidity))
+  {
+    case 5:   Serial.println("case 7"); digitalWrite(Relay2,HIGH);  digitalWrite(Relay1,HIGH);   break;
+    case 6:   Serial.println("case 7"); digitalWrite(Relay2,HIGH);  digitalWrite(Relay1,HIGH);   break;
+    case 7:   Serial.println("case 7"); digitalWrite(Relay2,HIGH);  digitalWrite(Relay1,HIGH);   break;
+    case 8:   Serial.println("case 8"); digitalWrite(Relay2,HIGH);  digitalWrite(Relay1,HIGH);  break;
+    case 9:   Serial.println("case 9"); digitalWrite(Relay2,HIGH);  digitalWrite(Relay1,HIGH);  break;
+    case 10:  Serial.println("case 10"); digitalWrite(Relay2,HIGH);  digitalWrite(Relay1,HIGH);  break;
+    default:  Serial.println("case 2-4"); digitalWrite(Relay2,LOW);   digitalWrite(Relay1,LOW);  break;
+  }
+  */
   lcd.setCursor(0, 3); lcd.print(h); lcd.print(" %");
   funFuzzyControlAircon(stemperature + shumidity);
   funBuzzerLed();


Remove verbose flag

Remove verbose flag

--- OS_moveToTarget.ino
+++ OS_moveToTarget.ino
@@ -9,7 +9,7 @@
 // **  You will need to change the speed and step sizes in this file for your motors **
 void moveToTarget(float target[]){

- byte verbose=1;
+ byte verbose=0;
  int ii; //for loop counter
  // Serial.println("Entering moveToTarget");
  float intendedMove[numAxes]; //How far to move on each axis.


Bug fix

Bug fix

bug fix

--- RoverRefactored/RoverRefactored.ino
+++ RoverRefactored/RoverRefactored.ino
@@ -113,7 +113,7 @@
 ****************************************************************************
 */
 void setup() {
-/*//TODO DL ALTERNATIVE A FOR SETUP
+  //TODO DL ALTERNATIVE A FOR SETUP
   // initialize serial communication:
   Serial.begin(9600);

@@ -141,7 +141,7 @@

   //Inizializzazione variabili line follower
   pinMode(LineTrackingSensor, INPUT);
-  left = true;*/
+  left = true;
 }

@@ -192,7 +192,7 @@
 //  Serial.print(rgb.G);
 //  Serial.print(", B: ");
 //  Serial.println(rgb.B);
-
+
   //RFID
   long id = rfidReader->GetUID();


Sending real packet for testing

Sending real packet for testing

--- SerialBuster/examples/send/send.ino
+++ SerialBuster/examples/send/send.ino
@@ -1,28 +1,28 @@
 #include "SerialBuster.h"
 #include "Buffer.h"

-SerialBuster sb = SerialBuster(512, 512);
+SerialBuster sb = SerialBuster(256, 256, 128);
 long mover = 0;

 void setup() {
   pinMode(13, OUTPUT);
   digitalWrite(13, LOW);
-  sb.init(115200);
+  sb.init(9600);
   //sb.setCallback(incomingPacket);
   delay(50);
 }

 void loop() {
   sb.update();
-  if(mover++ % 4000 == 0) {
+  if(mover++ % 10000 == 0) {

-    const uint8_t * payload = (const uint8_t *)"Hello from Arduino.";
-    sb.sendPacket(254, payload, 19);
-
-    int a = availableMemory();
-    float percent = ((float)a) / 2048.0;
-    Serial.print("mem: ");
-    Serial.println(percent * 100);
+    const uint8_t * payload = (const uint8_t *)"An end (\x03) char!";
+    sb.sendPacket(255, payload, strlen((const char *)payload));
+
+//    int a = availableMemory();
+//    float percent = ((float)a) / 2048.0;
+//    Serial.print("mem: ");
+//    Serial.println(percent * 100);
   }
 }


Don't read inexistent bit

Don't read inexistent bit

--- SDPArduinoCode/SDPArduinoCode.ino
+++ SDPArduinoCode/SDPArduinoCode.ino
@@ -473,7 +473,7 @@
       // need to check if signuture is our teams first!
       // avoids unessacary computation on the arduino if it is not a message for out team.
       int sig = getSig(c);
-      int seqNo = getSeqNo(c);
+      //int seqNo = getSeqNo(c);

       // Quits if sig belongs to other teams
       // OR if command is redundant (i.e. already executed)


cleanup

cleanup

--- testing/arduino/omniwheel4_EncoderC.ino
+++ testing/arduino/omniwheel4_EncoderC.ino
@@ -15,54 +15,7 @@
 int motorPin3_speed = 9;
 int motorPin3_A = A5;

-int globalSpeedInit = 255;
-int reducedSpeed = globalSpeedInit * 0.09;
-
-void setup()
-{
-    Serial.begin(9600);
-    while (!Serial)
-        ;
-    Serial.println("Init");
-
-    pinMode(motorPin1_1, OUTPUT);
-    pinMode(motorPin1_2, OUTPUT);
-    pinMode(motorPin1_speed, OUTPUT);
-    pinMode(motorPin1_A, INPUT);
-
-    pinMode(motorPin2_1, OUTPUT);
-    pinMode(motorPin2_2, OUTPUT);
-    pinMode(motorPin2_speed, OUTPUT);
-    pinMode(motorPin2_A, INPUT);
-
-    pinMode(motorPin3_1, OUTPUT);
-    pinMode(motorPin3_2, OUTPUT);
-    pinMode(motorPin3_speed, OUTPUT);
-    pinMode(motorPin3_A, INPUT);
-
-}
-
-
-void SetMotor(int pinSpeed, int pin1, int pin2, int speed)
-{
-    analogWrite(pinSpeed, abs(speed));
-    if (speed < 0)
-    {
-        analogWrite(pin1, 0);
-        analogWrite(pin2, 255);
-    }
-    else
-    {
-        analogWrite(pin1, 255);
-        analogWrite(pin2, 0);
-    }
-
-    if (speed == 0)
-    {
-        analogWrite(pin1, 0);
-        analogWrite(pin2, 0);
-    }
-}
+// ----------

 int motor1_RPMCount = 0;
 int motor1_State = 0;
@@ -77,11 +30,9 @@
 int motor3_RPMCount = 0;
 int motor3_State = 0;
 int motor3_Lookup[55];
-
-unsigned long time = 0;
-
-
-
+int motor3_MaxRPM = 0;
+
+// ----------

 typedef struct SpeedMappingEntity {
   int RPM;
@@ -93,30 +44,62 @@
 SpeedMappingEntity SpeedMapping_Motor2[255];
 SpeedMappingEntity SpeedMapping_Motor3[255];

+// ----------
+
+unsigned long time = 0;

 int init = 0;
 unsigned long initTimestamp = 0;
 int initSpeed = 255;

-
-// 1 Rotation == 80 Gearbox Ratio ==
-//      4 CPR (counts per revolution) * 80 == 320 Counts per Rotation
-int pulsesPerRotation = 320
-
-
-
-
-
-void loop()
-{
-    time = millis();
-
-    UpdateRPM();
-
-    Calibration();
-
-
-}
+// ----------
+// ----------
+
+void setup()
+{
+    Serial.begin(9600);
+    while (!Serial)
+        ;
+    Serial.println("Init");
+
+    pinMode(motorPin1_1, OUTPUT);
+    pinMode(motorPin1_2, OUTPUT);
+    pinMode(motorPin1_speed, OUTPUT);
+    pinMode(motorPin1_A, INPUT);
+
+    pinMode(motorPin2_1, OUTPUT);
+    pinMode(motorPin2_2, OUTPUT);
+    pinMode(motorPin2_speed, OUTPUT);
+    pinMode(motorPin2_A, INPUT);
+
+    pinMode(motorPin3_1, OUTPUT);
+    pinMode(motorPin3_2, OUTPUT);
+    pinMode(motorPin3_speed, OUTPUT);
+    pinMode(motorPin3_A, INPUT);
+}
+
+
+void SetMotor(int pinSpeed, int pin1, int pin2, int speed)
+{
+    analogWrite(pinSpeed, abs(speed));
+    if (speed < 0)
+    {
+        analogWrite(pin1, 0);
+        analogWrite(pin2, 255);
+    }
+    else
+    {
+        analogWrite(pin1, 255);
+        analogWrite(pin2, 0);
+    }
+
+    if (speed == 0)
+    {
+        analogWrite(pin1, 0);
+        analogWrite(pin2, 0);
+    }
+}
+

 void Calibration()
 {
@@ -132,40 +115,48 @@
         motor3_RPMCount = 0;

         initSpeed = 255;
-
         SetWheelsTo(initSpeed);
+        delay(1000);
+
         initTimestamp = time;
         init = 1;
         return;
     }

-    if (initTimestamp + 250 <= time && initSpeed == 255)
-    {
-
-    }
-
-    if (initTimestamp + 250 <= time && initSpeed > 0)
-    {
-        //motor1_Lookup[motor1_RPMCount] = initSpeed;
-        //motor2_Lookup[motor2_RPMCount] = initSpeed;
-        //motor3_Lookup[motor3_RPMCount] = initSpeed;
-
-
+    int delta = 250;
+    if (initTimestamp + delta <= time && initSpeed == 255)
+    {
+        motor1_MaxRPM = motor1_RPMCount;
+        motor2_MaxRPM = motor2_RPMCount;
+        motor3_MaxRPM = motor3_RPMCount;
+    }
+
+    if (initTimestamp + delta <= time && initSpeed > 0)
+    {
         SpeedMapping_Motor1[initSpeed].RPM = motor1_RPMCount
-        SpeedMapping_Motor1[initSpeed]Speed = initSpeed
-        SpeedMapping_Motor1[initSpeed]MappedSpeed =
-
-        // 255 - 245 - 235 - 225 - 215 - 205 - 195 - 185 - 175 - 165 - 155 - 145
+        SpeedMapping_Motor1[initSpeed].Speed = initSpeed
+        SpeedMapping_Motor1[initSpeed].MappedSpeed = 255 / motor1_MaxRPM * motor1_RPMCount
+
+        SpeedMapping_Motor2[initSpeed].RPM = motor2_RPMCount
+        SpeedMapping_Motor2[initSpeed].Speed = initSpeed
+        SpeedMapping_Motor2[initSpeed].MappedSpeed = 255 / motor2_MaxRPM * motor2_RPMCount
+
+        SpeedMapping_Motor3[initSpeed].RPM = motor3_RPMCount
+        SpeedMapping_Motor3[initSpeed].Speed = initSpeed
+        SpeedMapping_Motor3[initSpeed].MappedSpeed = 255 / motor3_MaxRPM * motor3_RPMCount
+
+
+        // 12:  255 - 245 - 235 - 225 - 215 - 205 - 195 - 185 - 175 - 165 - 155 - 145
         if (initSpeed > 150)
         {
             initSpeed -= 10;
         }
-        // 140 - 135 - 130 - 125 - 120 - 115 - 110 - 105 - 100 - 95 - 90 - 85 - 80 - 75
+        // 14:  140 - 135 - 130 - 125 - 120 - 115 - 110 - 105 - 100 - 95 - 90 - 85 - 80 - 75
         else if(initSpeed > 75)
         {
             initSpeed -= 5;
         }
-        // 75 - 0
+        // 76:  75 - 0
         else
         {
             initSpeed -= 1;
@@ -177,13 +168,23 @@
         motor1_RPMCount = 0;
         motor2_RPMCount = 0;
         motor3_RPMCount = 0;
+
         return;
     }
     else if (initSpeed <= 0)
     {
         init = 2;
-    }
-}
+        SetWheelsTo(0);
+
+        for(uint8_t i = 0; i < sizeof(SpeedMapping_Motor3); ++i) {
+            Serial.println("----------");
+            Serial.println(SpeedMapping_Motor1[i].value);
+            Serial.println(SpeedMapping_Motor2[i].value);
+            Serial.println(SpeedMapping_Motor3[i].value);
+        }
+    }
+}
+

 void SetWheelsTo(int speed)
 {
@@ -193,7 +194,6 @@
 }

-
 void UpdateRPM()
 {
     time = millis();
@@ -220,3 +220,22 @@
     }
 }

+
+
+
+
+
+
+void loop()
+{
+    time = millis();
+
+    UpdateRPM();
+
+    Calibration();
+
+
+}
+
+
+


time adjustments

time adjustments

--- garage_status.ino
+++ garage_status.ino
@@ -15,7 +15,7 @@

 // don't run during "the day", define what that means here
 int blackoutStart = 3;  // 3am
-int blackoutEnd  = 21; // 6pm
+int blackoutEnd  = 18;  // 6pm
 // I'd love to use the positive inflection here but it's too hard to
 // implement without a real time/date library.  You can't easily
 // represent like 3am -- meaning the next day with a number.
@@ -24,7 +24,7 @@
 void setup() {
   // Serial.begin(9600);

-  Time.zone(-7);  // PDT
+  Time.zone(-7);  // PDT, be wary of daylight savings adjustments.  :(

   strip.begin();
   strip.show(); // Initialize all pixels to 'off'


Remove settin wakeup button from poserOFF example

--- examples/Basics/PowerOFF/PowerOFF.ino
+++ examples/Basics/PowerOFF/PowerOFF.ino
@@ -9,9 +9,6 @@
   // Lcd display
   M5.Lcd.println("This is software power off demo");
   M5.Lcd.println("Press the button A to power off.");
-
-  // Set the wakeup button
-  M5.Power.setWakeupButton(BUTTON_A_PIN);
 }

 // the loop routine runs over and over again forever


Perform pre-erase in smaller blocks. Some SD cards have limits on erase size.

--- SdFatSDIO_low_latency_logger.ino
+++ SdFatSDIO_low_latency_logger.ino
@@ -139,10 +139,15 @@
             last_error = E_create_contiguous;
             return false;
         }
-        if(!sd_fat.card()->erase(first_sector, last_sector)) {
-            log("PreallocatedFile: erase() failed");
-            last_error = E_erase;
-            return false;
+        uint32_t first_erase_sector = first_sector;
+        const size_t erase_count = 64 * 1024; // number of sectors to erase at once
+        while(first_erase_sector <= last_sector) {
+            if(!sd_fat.card()->erase(first_erase_sector, std::min(first_erase_sector+erase_count, last_sector))) {
+                log("PreallocatedFile: erase() failed");
+                last_error = E_erase;
+                return false;
+            }
+            first_erase_sector += erase_count;
         }
         log("First sector: %u     last sector: %u\n", first_sector, last_sector);
         this->first_sector = first_sector;
@@ -359,4 +364,4 @@
     delay(200);
     digitalWrite(LED_BUILTIN, LOW);
     delay(200);
-}
+}


Code cleaning and refactoring.

Code cleaning and refactoring.

Now the sketch only contains the code for the reading TAG part
meanwhile all the authorizing part goes in ther own library.


tweaking the playground and fixing a small initialization bug

--- examples/NoisePlayground/NoisePlayground.ino
+++ examples/NoisePlayground/NoisePlayground.ino
@@ -21,19 +21,19 @@
 uint8_t hue_octaves=2;

 // the 'distance' between points on the x and y axis
-int xscale=131;
-int yscale=yscale;
+int xscale=301;
+int yscale=301;

 // the 'distance' between x/y points for the hue noise
 int hue_scale=11;

 // how fast we move through time & hue noise
 int time_speed=101;
-int hue_speed=2;
+int hue_speed=3;

 // adjust these values to move along the x or y axis between frames
 int x_speed=0;
-int y_speed=0;
+int y_speed=1;

 void loop() {
   // fill the led array 2/16-bit noise values
@@ -52,16 +52,16 @@

 void setup() {
+  // initialize the x/y and time values
+  random16_set_seed(18934);
+  random16_add_entropy(analogRead(3));
+
   Serial.begin(38400);
   Serial.println("resetting!");

   delay(3000);
   LEDS.addLeds<WS2811,5,GRB>(leds,NUM_LEDS);
-  LEDS.setBrightness(48);
-
-  // initialize the x/y and time values
-  random16_set_seed(8934);
-  random16_add_entropy(analogRead(3));
+  LEDS.setBrightness(32);

   x = (uint32_t)((uint32_t)random16() << 16) | random16();
   y = (uint32_t)((uint32_t)random16() << 16) | random16();


debugging 0x90 messages

debugging 0x90 messages

--- examples/StandardFirmata/StandardFirmata.ino
+++ examples/StandardFirmata/StandardFirmata.ino
@@ -140,6 +140,7 @@
   portValue = portValue & portConfigInputs[portNumber];
   // only send if the value is different than previously sent
   if(forceSend || previousPINs[portNumber] != portValue) {
+    Serial.println(F("Sending update"));
     BLE_Firmata.sendDigitalPort(portNumber, portValue);
     previousPINs[portNumber] = portValue;
   }
@@ -153,22 +154,14 @@
   /* Using non-looping code allows constants to be given to readPort().
    * The compiler will apply substantial optimizations if the inputs
    * to readPort() are compile-time constants. */
-  if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false);
-  if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false);
-  if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false);
-  if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false);
-  if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false);
-  if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false);
-  if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false);
-  if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false);
-  if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false);
-  if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false);
-  if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false);
-  if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false);
-  if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false);
-  if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false);
-  if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false);
-  if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false);
+  for (uint8_t i=0; i<TOTAL_PORTS; i++) {
+    if (reportPINs[i]) {
+    //  Serial.print("Reporting on port"); Serial.println(i);
+      uint8_t x = readPort(i, portConfigInputs[i]);
+    //  Serial.print("Read 0x"); Serial.println(x, HEX);
+      outputPort(i, x, false);
+    }
+  }
 }

 // -----------------------------------------------------------------------------
@@ -208,9 +201,16 @@
     break;
   case INPUT:
     if (IS_PIN_DIGITAL(pin)) {
+      Serial.println("input");
       pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver
       digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups
       pinConfig[pin] = INPUT;
+
+      // MEME update so we have an update report
+      uint8_t tempport = pin/8;
+      uint8_t temppin = reportPINs[tempport];
+      reportDigitalCallback(tempport, temppin | (1<<(pin % 8)));
+      //
     }
     break;
   case OUTPUT:
@@ -243,7 +243,7 @@
     }
     break;
   default:
-    BLE_Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM
+    Serial.print(F("Unknown pin mode")); // TODO: put error msgs in EEPROM
   }
   // TODO: save status to EEPROM here, if changed
 }
@@ -286,6 +286,7 @@
       }
       mask = mask << 1;
     }
+    Serial.println(F("Write digital"));
     writePort(port, (byte)value, pinWriteMask);
   }
 }
@@ -311,6 +312,7 @@
 void reportDigitalCallback(byte port, int value)
 {
   if (port < TOTAL_PORTS) {
+    Serial.print("Report 0x"); Serial.print(value, HEX); Serial.print(" digital on "); Serial.println(port);
     reportPINs[port] = (byte)value;
   }
   // do not disable analog reporting on these 8 pins, to allow some
@@ -636,6 +638,8 @@
   Serial.println("Begin firmata");
   BLE_Firmata.begin();
   systemResetCallback();  // reset to default config
+
+
 }

 /*==============================================================================
@@ -646,9 +650,20 @@
   BLEserial.pollACI();
   if (BLEserial.getState() != ACI_EVT_CONNECTED) {
       Serial.print("!");
+      delay(100);
       return;
   }

+  if (Serial.available()) {
+    BLEserial.write(Serial.read());
+
+  }
+  pinMode(4, INPUT);
+  if (! digitalRead(4)) {
+     uint8_t foo[3] = {'a', 'b', 'c'};
+     BLEserial.write(foo, 3);
+    delay(500);
+  }
   byte pin, analogPin;

   /* DIGITALREAD - as fast as possible, check for changes and output them to the


Detection: maj code detection pour la nouvelle carte capteurs


Disabled slow start

Disabled slow start

--- Watering/Watering.ino
+++ Watering/Watering.ino
@@ -43,14 +43,15 @@
 }

 void startMotor() {
+  digitalWrite(greenLED, HIGH);
   motorOn = true;
-  outputValue = 0;
+  /*outputValue = 0;
   while (outputValue < 256) {
     analogWrite(gatePin, outputValue);
     outputValue++;
     delay(10);
-  }
-  digitalWrite(greenLED, HIGH);
+  }*/
+  digitalWrite(gatePin, HIGH);
 }

 void readTemp() {


updated the FSM to correctly message the armed state

--- sploder.ino
+++ sploder.ino
@@ -138,11 +138,11 @@
   armedStatus();
   digitalWrite(ARMED_LED, HIGH);
   if (!armed) {
+    blePrint("disarmed");
     stateMachine.transitionTo(readyState);
   }
 }
 void leaveArmedState() {
-  blePrint("disarmed");
   digitalWrite(ARMED_LED, LOW);
 }

@@ -155,7 +155,7 @@
 }
 void updateFiringState() {
   if(isTimerExpired(timerFiringState, 1000)) {
-    stateMachine.transitionTo(readyState);
+    stateMachine.transitionTo(armedState);
   }
 }
 void leaveFiringState() {


Update comments.

Update comments.

--- examples/send_Blink/send_Blink.ino
+++ examples/send_Blink/send_Blink.ino
@@ -27,8 +27,8 @@

 void loop()
 {   Serial.println("In loop");
-    // send data:  id = 0x00, standard frame, data len = 8, stmp: data buf
-    CAN.sendMsgBuf(0x70,0, 8, stmp);
+    // send data:  id = 0x70, standard frame, data len = 8, stmp: data buf
+    CAN.sendMsgBuf(0x70, 0, 8, stmp);
     delay(1000);                       // send data once per second
 }


Update SparkCore.ino

Update SparkCore.ino

--- firmware/examples/Transports/SparkCore/SparkCore.ino
+++ firmware/examples/Transports/SparkCore/SparkCore.ino
@@ -15,7 +15,7 @@
  **************************************************************/
 //#define BLYNK_DEBUG // Uncomment this to see debug prints
 #define BLYNK_PRINT Serial
-#include "blynk/BlynkSimpleSparkCore.h"
+#include "blynk.h"

 // You should get Auth Token in the Blynk App.
 // Go to the Project Settings (nut icon).