fix init of feed pointer

fix init of feed pointer

--- ardesp/waterelf32-nepal-lora-receiver/waterelf32-nepal-lora-receiver.ino
+++ ardesp/waterelf32-nepal-lora-receiver/waterelf32-nepal-lora-receiver.ino
@@ -363,7 +363,7 @@
 AdafruitIO_WiFi *io_p;
 String IO_USERNAME;
 String IO_KEY;
-AdafruitIO_Feed *airtfeed = io_p->feed("AirTemperature");
+AdafruitIO_Feed *airtfeed_p;

 /////////////////////////////////////////////////////////////////////////////
 // setup ////////////////////////////////////////////////////////////////////
@@ -399,6 +399,7 @@
     IO_USERNAME.toCharArray(iouserchars, IO_USERNAME.length()+1);
     IO_KEY.toCharArray(iokeychars, IO_KEY.length()+1);
     io_p = new AdafruitIO_WiFi(iouserchars, iokeychars, "", "");
+    airtfeed_p = io_p->feed("AirTemperature");
     // connect to io.adafruit.com
     io_p->connect();

@@ -1077,7 +1078,7 @@
 void pushAdafruitIOData(monitor_t *monitorData) {
   dln(adaDBG, "\npushAdafruitIOData");
   dln(adaDBG, monitorData->airCelsius);
-  airtfeed->save(monitorData->airCelsius);
+  airtfeed_p->save(monitorData->airCelsius);
 }

 void formatMonitorEntry(monitor_t *m, String* buf, bool JSON) {


Fixed println

Fixed println

--- arduino/fasnacht/fasnacht.ino
+++ arduino/fasnacht/fasnacht.ino
@@ -96,22 +96,22 @@
     if( (ValueFrq > 140) && (ValueFrq <= 160) ) {
       digitalWrite(3, 0); //B
       digitalWrite(5, 0); //D
-      Serial.print("B OFF D OFF ");
+      Serial.println("B OFF D OFF ");
     }
     if( (ValueFrq > 240) && (ValueFrq <= 260) ) {
       digitalWrite(3, 1); //B
       digitalWrite(5, 0); //D
-      Serial.print("B ON  D OFF ");
+      Serial.println("B ON  D OFF ");
     }
     if( (ValueFrq > 340) && (ValueFrq <= 360) ) {
       digitalWrite(3, 0); //B
       digitalWrite(5, 1); //D
-      Serial.print("B OFF D ON  ");
+      Serial.println("B OFF D ON  ");
     }
     if( (ValueFrq > 440) && (ChannelFrq <= 460) ) {
       digitalWrite(3, 1); //B
       digitalWrite(5, 1); //D
-      Serial.print("B ON  D ON  ");
+      Serial.println("B ON  D ON  ");
     }

     //get channel data and write output RIGHT AUIO CHANNEL


Use created analogComp library. Overclocked Arduino Pro Mini 3.3V 16MHz support.

--- j_VideoMotionDetect.ino
+++ j_VideoMotionDetect.ino
@@ -20,18 +20,7 @@
 //   D7 (AIN1) : Analog comparator negative input. (voltage to compare)
 //   D9 (PWM)  : Constant reference PWM voltage for brightness threshold.

-#if defined(__MK20DX256__) // Teensy 3.1
-
-// No library exists for Freescale MK20DX256 processor's
-// built-in CMP module, so we need to do it in low level...
-#define CMP_SCR_DMAEN   ((uint8_t)0x40) // DMA Enable Control
-#define CMP_SCR_IER     ((uint8_t)0x10) // Comparator Interrupt Enable Rising
-#define CMP_SCR_IEF     ((uint8_t)0x08) // Comparator Interrupt Enable Falling
-#define CMP_SCR_CFR     ((uint8_t)0x04) // Analog Comparator Flag Rising
-#define CMP_SCR_CFF     ((uint8_t)0x02) // Analog Comparator Flag Falling
-#define CMP_SCR_COUT    ((uint8_t)0x01) // Analog Comparator Output
-
-#elif defined(REL_GR_KURUMI) // GR-KURUMI
+#if defined(REL_GR_KURUMI) // GR-KURUMI

 // Renesas RL78/G13 has 10 external interrupts (INTP0-INTP6, INTP8, INTP9, INTKR)
 // but GR-KURUMI made all of these pins unusable except
@@ -46,16 +35,17 @@
 // In order to use D4 as an interrupt pin we need to do it low level. (sigh..)
 // "How To Do It" documents about GR-KURUMI should be prepared...

-#else // Arduino Pro Mini
+#else // Arduino Pro Mini or Teensy 3.1

 // The part of code utilizes the following library. Please download and install.
-//   https://github.com/leomil72/analogComp
-//#include "analogComp.h" // *** please comment out this line if Teensy 3.1 or GR-KURUMI ***
+//   https://github.com/orangkucing/analogComp
+//#include "analogComp.h" // *** please comment out this line if GR-KURUMI ***

 #endif

 // Bulk motion detection:
 // volatile variables
+
 volatile uint16_t interlace;
 volatile uint16_t currentLine;
 volatile uint16_t lastHsyncTime;
@@ -91,11 +81,22 @@

 #else // Arduino Pro Mini

+#if F_CPU == 16000000
+const int SCANLINE_OFFSET = 110;
+const int MAX_SCANLINES = 70;
+typedef uint16_t image_t; // 1 word = 16 bits
+#define SIZE_OF_IMAGE_T 2
+// overclocked Arduino Pro Mini
+// GoPro needs 3.3V logic. Running 16MHz on ATmega 328P is not recommended at 3.3V.
+// (Note: ATmega 328P can run 20MHz but it is not supported by Arduino IDE)
+const int WORD_PER_LINE = 1; // 2^1 words = 32 bits
+#else // F_CPU == 8000000
 const int SCANLINE_OFFSET = 94;
 const int MAX_SCANLINES = 100;
 typedef uint16_t image_t; // 1 word = 16 bits
 #define SIZE_OF_IMAGE_T 2
 const int WORD_PER_LINE = 0; // 2^0 words = 16 bits
+#endif

 // set brightnessThreshold between 23: very sensitive and 77: not sensitive.
 const int brightnessThreshold = 50; // CHANGE ME!!
@@ -207,17 +208,16 @@

 #if defined(__MK20DX256__) // Teensy 3.1

-void cmp1_isr()
+void changeHandler()
 {
   uint16_t x;

   x = (uint16_t)micros() - lastHsyncTime;

-  CMP1_SCR |= CMP_SCR_CFR | CMP_SCR_CFF; // clear CFR and CFF
   // HSync period is 63.56μs and sync-to-blanking-end 9.48μs
   if (x <= 64 && x >= 10) {
     x -= 10;
-    if ((CMP1_SCR & CMP_SCR_COUT)) { // store 2 bit per interrupt
+    if ((CMP1_SCR & 1)) { // check CMP_SCR_COUT and store 2 bit per interrupt
       // INP > INM
       line[x >> 4] |= (image_t)1 << ((x & B1111) << 1);
     } else {
@@ -230,22 +230,12 @@
 void _resetCMP()
 {
   // prepare capturing video frames.
-  // set the reference analog voltage.
+  // set the ref8erence analog voltage.
   analogWriteResolution(12);
   analogWrite(A14, brightnessThreshold);

-  // set CMP1 interrupt vector before enabling CMP1
-  NVIC_SET_PRIORITY(IRQ_CMP1, 64); // 0 = highest priority, 255 = lowest
-  NVIC_ENABLE_IRQ(IRQ_CMP1); // handler is now cmp1_isr()
-
-  // comparator settings
-  SIM_SCGC4 |= SIM_SCGC4_CMP; // comparator clock set on. it is off by default for conserving power.
-  CORE_PIN23_CONFIG = PORT_PCR_MUX(0); // pin function set to comparator
-  CMP1_CR1 = 0; // set CMP1_CR1 to a known state
-  CMP1_CR0 = 0; // set CMP1_CR0 to a known state
-  CMP1_CR1   = B00000001; // enable comparator
-  CMP1_MUXCR = B00011000; // set comparator input PSEL=IN3 (DAC0_OUT) / MSEL=IN0 (D23)
-  CMP1_SCR   = CMP_SCR_IER | CMP_SCR_IEF; // set triggering edge to both rising and falling.
+  analogComparator1.setOn(3, 0); // set comparator input PSEL=IN3 (DAC0_OUT) / MSEL=IN0 (D23)
+  analogComparator1.enableInterrupt(changeHandler, CHANGE);
 }

 #elif defined(REL_GR_KURUMI) // GR-KURUMI
@@ -301,9 +291,19 @@
   // subtract the amount for sync-to-blanking-end 9.48μs.
   x -= 10;

-  // on 8MHz Arduinos micros() has a resolution of 8μs.
+  // on 8MHz/16MHz Arduinos micros() has a resolution of 8μs/4μs respectively.
   // actual brightness information Arduino Pro Mini 8MHz can capture from each scan line is only 5 (or 6) samples.
-  x >>= 2;
+  x >>= 2;
+#if F_CPU == 16000000 // overclocked Arduino Pro Mini
+  // store two bit per interrupt.
+  if ((ACSR & (1 << ACO))) {
+      // AIN+ > AIN-
+      line[x >> 3] |= (image_t)1 << ((x & B111) << 1);
+  } else {
+      // AIN+ > AIN-
+      line[x >> 3] |= (image_t)1 << (((x & B111) << 1) | 1);
+  }
+#else // F_CPU == 8000000
   // store two bit per interrupt.
   if ((ACSR & (1 << ACO))) {
     // AIN+ > AIN-
@@ -312,6 +312,7 @@
     // AIN+ < AIN-
     line[0] |= (1 << (x | 1));    // store B10
   }
+#endif
 }

 void _resetCMP()


Revert "."

Revert "."

This reverts commit 82f5e76db000f500265893462cf93246f85894ba.

--- lampka.ino
+++ lampka.ino
@@ -425,10 +425,9 @@
     for (uint8_t index=0; index < PIXELS; index++) {
         if (constant_eq_1) {
             if (constant_color_index == 8) { //white
-                memset(&led_colors[index], 255, 3);
-                //led_colors[index][0]=255;
-                //led_colors[index][1]=255;
-                //led_colors[index][2]=255;
+                led_colors[index][0]=255;
+                led_colors[index][1]=255;
+                led_colors[index][2]=255;
             } else {
                 hue_to_compute = (256/8) * constant_color_index;
                 hsv2rgb_rainbow(hue_to_compute, led_colors[index]);


Update _03-hx711-scale-esp-12.ino

Update _03-hx711-scale-esp-12.ino

--- _03-hx711-scale/_03-hx711-scale-v2-battery-external-Interrupt-02/_03-hx711-scale-esp-12/_03-hx711-scale-esp-12.ino
+++ _03-hx711-scale/_03-hx711-scale-v2-battery-external-Interrupt-02/_03-hx711-scale-esp-12/_03-hx711-scale-esp-12.ino
@@ -137,7 +137,7 @@
   Serial.println(y);

-  if ( x == 65535 ) {
+  if ( x >= 10000 ) {
     Serial.println("scale is sleeping");
     return;
   } else {


Separated inputs and outputs

Separated inputs and outputs

--- sequencer.ino
+++ sequencer.ino
@@ -1,24 +1,14 @@
 const int DIFFERENT_VALUES = 4;
-const int MAX_LENGTH = 20;
+const int MAX_LENGTH = 40;
 const int SHOW_DELAY = 1000;
 const int BLINK_DELAY = 300;
-const int DEBOUNCE_DELAY = 50;
+const int DEBOUNCE_DELAY = 200;
+const int READ_WAITING_DELAY = 200;
+const int FIRST_INPUT = 2;
+const int FIRST_OUTPUT = 6;

 int sequence[MAX_LENGTH];
 int currentLength = 0;
-
-// Set every pin to specified mode
-void setMode(int mode) {
-  for (int i = 0; i < DIFFERENT_VALUES; i++) {
-    pinMode(i, mode);
-  }
-  // To show current mode
-  if (mode == OUTPUT) {
-    digitalWrite(13, LOW);
-  } else {
-    digitalWrite(13, HIGH);
-  }
-}

 // Increase the random sequence in one element
 void newElement() {
@@ -30,21 +20,22 @@
 void cleanOutput() {
   // Switch off all outputs
   for (int i = 0; i < DIFFERENT_VALUES; i++) {
-    digitalWrite(i, LOW);
+    digitalWrite(i + FIRST_OUTPUT, LOW);
   }
 }

 // Show the current sequence (up to current length)
 void showSequence() {
-  setMode(OUTPUT);
+  digitalWrite(13, LOW);
   for (int i = 0; i < currentLength; i++) {
     cleanOutput();
     delay(SHOW_DELAY);
     // Switch on current output
-    digitalWrite(sequence[i], HIGH);
+    digitalWrite(sequence[i] + FIRST_OUTPUT, HIGH);
     delay(SHOW_DELAY);
   }
   cleanOutput();
+  delay(SHOW_DELAY * 3);
 }

 void waitForUnpush() {
@@ -52,13 +43,15 @@
   while (allInputsAreUnpushed == 0) {
     allInputsAreUnpushed = 1;
     for (int i = 0; i < DIFFERENT_VALUES; i++) {
-      if (digitalRead(i) ==  HIGH) {
+      // Value to check must be LOW, because input is pull up
+      if (digitalRead(i + FIRST_INPUT) ==  LOW) {
         // At least one input is not unpushed
         allInputsAreUnpushed = 0;
         // Doesn't read other inputs
         break;
       }
     }
+    delay(READ_WAITING_DELAY);
   }
 }

@@ -67,38 +60,39 @@
   int pushedElement = -1;
   while (pushedElement == -1) {
     for (int i = 0; i < DIFFERENT_VALUES; i++) {
-      if (digitalRead(i) ==  HIGH) {
+      // Value to check must be LOW, because input is pull up
+      if (digitalRead(i + FIRST_INPUT) ==  LOW) {
         // Waits some milliseconds to prevent bouncing
         delay(DEBOUNCE_DELAY);
-
-        waitForUnpush();
-
-        pushedElement = i;
-        // Doesn't read other inputs
-        break;
+        // Pusher is still pushed
+        if (digitalRead(i + FIRST_INPUT) ==  LOW) {
+          pushedElement = i;
+          waitForUnpush();
+          // Doesn't read other inputs
+          break;
+        }
       }
     }
+    delay(READ_WAITING_DELAY);
   }
   return pushedElement;
 }

 void blinkCorrectElement(int element) {
-  setMode(OUTPUT);
   while (true) {
-    digitalWrite(element, HIGH);
+    digitalWrite(element + FIRST_OUTPUT, HIGH);
     delay(BLINK_DELAY);
-    digitalWrite(element, LOW);
+    digitalWrite(element + FIRST_OUTPUT, LOW);
     delay(BLINK_DELAY);
   }
 }

 void readSequence() {
-  setMode(INPUT);
+  digitalWrite(13, HIGH);
   for (int i = 0; i < currentLength; i++) {
     int pushed = readFirstPushed();
     if (sequence[i] != pushed) {
       // Wrong element, game over
-      Serial.begin(9600);
       Serial.println("Game over");
       Serial.print("Sequence was ");
       Serial.print(sequence[i]);
@@ -117,8 +111,18 @@
   // different seed numbers each time the sketch runs.
   // randomSeed() will then shuffle the random function.
   randomSeed(analogRead(0));
+  // Set mode in all inputs as pullup
+  for (int i = 0; i < DIFFERENT_VALUES; i++) {
+    pinMode(i + FIRST_INPUT, INPUT_PULLUP);
+  }
+  // Set mode in all outputs
+  for (int i = 0; i < DIFFERENT_VALUES; i++) {
+    pinMode(i + FIRST_OUTPUT, OUTPUT);
+  }
   // Will show input/output state
   pinMode(13, OUTPUT);
+  // Initialize serial
+  Serial.begin(9600);
 }

 void loop() {


Keep track of bills

Keep track of bills

--- magicwallet_rx/magicwallet_rx.ino
+++ magicwallet_rx/magicwallet_rx.ino
@@ -8,23 +8,14 @@

 enum pins {
 	RECEIVE_PIN = 11,
-	LED1_PIN = 13,
 };

+enum { MAX_BILLS = 4 };
+
 RH_ASK radio(2000, RECEIVE_PIN, NULL);
-
-static void led1_on(void) {
-	digitalWrite(LED1_PIN, HIGH);
-}
-
-static void led1_off(void) {
-	digitalWrite(LED1_PIN, LOW);
-}
-
-static void led1_toggle(void) {
-	int x = digitalRead(LED1_PIN);
-	digitalWrite(LED1_PIN, !x);
-}
+uint8_t bills[MAX_BILLS];
+uint8_t bills_count;
+uint8_t prev_bill;

 void setup() {
 #	ifdef DEBUG
@@ -32,9 +23,16 @@
 	Serial.println("Initializing radio");
 #	endif

-	pinMode(LED1_PIN, OUTPUT);
+	lcd_init();
+	lcd_cursor_off();
+	lcd_clear();
+	lcd_printf("Ready");

-	led1_off();
+	for (uint8_t i = 0; i < MAX_BILLS; i++) {
+		bills[i] = 0;
+	}
+	bills_count = 0;
+	prev_bill = 0;

 	if (!radio.init()) {
 #		ifdef DEBUG
@@ -49,17 +47,22 @@
 	uint8_t buflen = sizeof(buf);

 	if (radio.recv(buf, &buflen)) {
+		uint8_t n = atoi((const char *) buf);
+		if (n != prev_bill) {
+			bills[bills_count] = n;
+			lcd_clear();
+			lcd_printf("%2d%2d%2d%2d", bills[0], bills[1], bills[2], bills[3]);
+			bills_count = (bills_count + 1) % MAX_BILLS;
+			prev_bill = n;
+		}
 #		ifdef DEBUG
 		radio.printBuffer("Received:", buf, buflen);
+		Serial.println("bills:");
+		Serial.println(bills[0]);
+		Serial.println(bills[1]);
+		Serial.println(bills[2]);
+		Serial.println(bills[3]);
+		Serial.println();
 #		endif
-		if (strncmp((const char *) buf, msg1, buflen)) {
-			led1_on();
-			delay(500);
-			led1_off();
-		} else if (strncmp((const char *) buf, msg2, buflen)) {
-			led1_on();
-			delay(500);
-			led1_off();
-		}
 	}
 }


Version 4.1a - 30th December 2021

Version 4.1a - 30th December 2021

Fix format error message.

--- ulisp.ino
+++ ulisp.ino
@@ -1,5 +1,5 @@
-/* uLisp AVR Version 4.1 - www.ulisp.com
-   David Johnson-Davies - www.technoblogy.com - 14th December 2021
+/* uLisp AVR Version 4.1a - www.ulisp.com
+   David Johnson-Davies - www.technoblogy.com - 30th December 2021

    Licensed under the MIT license: https://opensource.org/licenses/MIT
 */
@@ -3501,7 +3501,7 @@
 void formaterr (object *formatstr, PGM_P string, uint8_t p) {
   pln(pserial); indent(4, ' ', pserial); printstring(formatstr, pserial); pln(pserial);
   indent(p+5, ' ', pserial); pserial('^');
-  errorsub(FORMAT, string);
+  error2(FORMAT, string);
   pln(pserial);
   GCStack = NULL;
   longjmp(exception, 1);


Adding sleep functions

Adding sleep functions

--- software/rectangle_rag/rectangle_rag.ino
+++ software/rectangle_rag/rectangle_rag.ino
@@ -1,7 +1,18 @@
 /*
+
+ Used Watchdog Sleep Examples
+ * KHM 2008 / Lab3/  Martin Nawrath nawrath@khm.de
+ * Kunsthochschule fuer Medien Koeln
+ * Academy of Media Arts Cologne
+ *
+ * Modified on 5 Feb 2011 by InsideGadgets (www.insidegadgets.com)
+ * to suit the ATtiny85 and removed the cbi( MCUCR,SE ) section
+
 */

 #include <avr/pgmspace.h>
+#include <avr/sleep.h>
+#include <avr/wdt.h>

 #define RED_PIN 1
 #define AMBER_PIN 3
@@ -23,8 +34,9 @@
 #define FLASH_INTERVAL_MILLIS 375
 #define FLASH_ON 255

-#define SEQUENCE_TYPES 6
+#define SEQUENCE_TYPES 7
 #define MAX_STEPS 30
+#define TEST_PATTERN_FIRST_POWERED 6
 // see http://www.arduino.cc/en/Reference/PROGMEM
 // https://github.com/lilspikey/arduino_sketches/blob/master/attiny/xmas/xmas.ino
 // bitrate = pgm_read_word_near ( &(bitrate_table[temp][row_num]) );
@@ -129,23 +141,47 @@
     {RED, 3},
     {END_SEQUENCE, 1},
   },
+  { // TEST_PATTERN_FIRST_POWERED
+    {GREEN, 1},
+    {AMBER, 1},
+    {RED, 1},
+    {RED_FLASH + AMBER_FLASH + GREEN_FLASH, 3},
+    {END_SEQUENCE, 1},
+  },
+
 };
+
+// Used by Sleep Function
+#ifndef cbi
+#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
+#endif
+#ifndef sbi
+#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
+#endif
+volatile boolean f_wdt = 1;

 void setup() {
   // initialize the digital pin as an output.
   pinsToOutput();
   pinMode(BUTTON_PIN, INPUT_PULLUP);
+  doSequence(TEST_PATTERN_FIRST_POWERED);
+  setup_watchdog(8); // approximately 4 seconds sleep
+
 }

 void loop() {
-
   uint8_t presses = 0;
-  if(pressed())  {
-    presses = getPresses(1, 1, 5, MAX_LOOPS);
-    doSequence(presses-1);
+  if (f_wdt==1) {  // wait for timed out watchdog / flag is set when a watchdog timeout occurs
+    f_wdt=0;       // reset flag
+    if(pressed())  {
+      pinsToOutput();
+      presses = getPresses(1, 1, SEQUENCE_TYPES, MAX_LOOPS);
+      doSequence(presses-1);
+    }
+    powerDown();
+    system_sleep();
   }
-

 }

@@ -218,3 +254,52 @@
   pinMode(GREEN_PIN, OUTPUT);
 }

+void pinsToInput()  {
+  pinMode(RED_PIN,   INPUT);
+  pinMode(AMBER_PIN, INPUT);
+  pinMode(GREEN_PIN, INPUT);
+}
+
+void powerDown()  {
+  writeLEDs(ALL_OFF, ALL_OFF);
+  pinsToInput();
+}
+
+// set system into the sleep state
+// system wakes up when wtchdog is timed out
+void system_sleep() {
+  cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF
+
+  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
+  sleep_enable();
+
+  sleep_mode();                        // System sleeps here
+
+  sleep_disable();                     // System continues execution here when watchdog timed out
+  sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
+}
+
+// 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms
+// 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec
+void setup_watchdog(int ii) {
+
+  byte bb;
+  int ww;
+  if (ii > 9 ) ii=9;
+  bb=ii & 7;
+  if (ii > 7) bb|= (1<<5);
+  bb|= (1<<WDCE);
+  ww=bb;
+
+  MCUSR &= ~(1<<WDRF);
+  // start timed sequence
+  WDTCR |= (1<<WDCE) | (1<<WDE);
+  // set new watchdog timeout value
+  WDTCR = bb;
+  WDTCR |= _BV(WDIE);
+}
+
+// Watchdog Interrupt Service / is executed when watchdog timed out
+ISR(WDT_vect) {
+  f_wdt=1;  // set global flag
+}


Updated morse integer array in arduino sketch.


load cell reading issue starts

load cell reading issue starts

--- send/send.ino
+++ send/send.ino
@@ -51,16 +51,26 @@
     Serial.println();

     // encoder information is read from buf[4] and buf[5] and converted to decimal
-        data = buf[4];
-        data <<= 8;
-        data = data | buf[5];
+    enconder_data = buf[4];
+    enconder_data <<= 8;
+    enconder_data = data | buf[5];

-    // if (buf[1] >= 128) {
-    //        data = data - 16777216;
-    // }
+    // load cell information is read from buf[1], buf[2] and buf[3] and converted to decimal
+    loadcell_data = buf[1];
+    loadcell_data <<= 8;
+    loadcell_data = data | buf[2];
+    loadcell_data <<= 8;
+    loadcell_data = data | buf[3];
+
+    if (buf[1] >= 128) {
+           laodcell_data = loadcell_data - 16777216;
+    }

-    Serial.print("Data: ");
-    Serial.println(data, DEC);
+    Serial.print("Encoder: ");
+    Serial.println(encoder_data, DEC);
+
+    Serial.print("Loadcell: ");
+    Serial.println(laodcell_data, DEC);

     delay(400);
   }


fix bug in reading Serial data logic, add new commands

--- Arduino/chorus-rf-laptimer/chorus-rf-laptimer.ino
+++ Arduino/chorus-rf-laptimer/chorus-rf-laptimer.ino
@@ -32,12 +32,13 @@
     when CONTROL_DATA_REQUEST is being processed, i.e. all data items are sent in sequence,
     and either external or external logic decides to send an individual item,
     then the latter just breaks execution of CONTROL_DATA_REQUEST and data is not sent completely
-
-TODO: when implement send queue, there's possible optimization:
+    This behavior should not occur in case of normal send queue processing.
+
+TODO: there's possible optimization in send queue:
     remove already existing items from queue
 */

-#define API_VERSION 1 // version number to be increased with each API change (int16)
+#define API_VERSION 2 // version number to be increased with each API change (int16)

 // #define DEBUG

@@ -84,13 +85,15 @@
 #define CONTROL_MONITOR_OFF     'v'
 #define CONTROL_SET_SKIP_LAP0   'F'
 #define CONTROL_GET_VOLTAGE     'Y'
+#define CONTROL_GET_RSSI        'E'
 #define CONTROL_GET_API_VERSION '#'
-// input control byte constants for uint16 "set value" commands
-#define CONTROL_SET_FREQUENCY   'Q'
-// input control byte constants for long "set value" commands
+// input control byte constants for uint8 "set value" commands
 #define CONTROL_SET_MIN_LAP     'L'
 #define CONTROL_SET_CHANNEL     'H'
 #define CONTROL_SET_BAND        'N'
+// input control byte constants for uint16 "set value" commands
+#define CONTROL_SET_FREQUENCY   'Q'
+#define CONTROL_SET_MON_DELAY   'd'

 // output id byte constants
 #define RESPONSE_CHANNEL        'C'
@@ -109,6 +112,7 @@
 #define RESPONSE_IS_CONFIGURED  'P'
 #define RESPONSE_VOLTAGE        'Y'
 #define RESPONSE_FREQUENCY      'Q'
+#define RESPONSE_MONITOR_DELAY  'd'
 #define RESPONSE_API_VERSION    '#'

 // send item byte constants
@@ -126,8 +130,9 @@
 #define SEND_LAP0_STATE     9
 #define SEND_IS_CONFIGURED  10
 #define SEND_FREQUENCY      11
-#define SEND_API_VERSION    12
-#define SEND_END_SEQUENCE   13
+#define SEND_MONITOR_DELAY  12
+#define SEND_API_VERSION    13
+#define SEND_END_SEQUENCE   14
 // following items don't participate in "send all items" response
 #define SEND_LAST_LAPTIMES  100
 #define SEND_CALIBR_TIME    101
@@ -148,7 +153,9 @@
 #define THRESHOLD_ARRAY_SIZE  100
 uint16_t rssiThresholdArray[THRESHOLD_ARRAY_SIZE];

-#define MAX_RSSI_MONITOR_DELAY_CYCLES 1000 //each 100ms, if cycle takes 100us
+#define DEFAULT_RSSI_MONITOR_DELAY_CYCLES 1000 //each 100ms, if cycle takes 100us
+#define MIN_RSSI_MONITOR_DELAY_CYCLES 10 //each 1ms, if cycle takes 100us, to prevent loss of communication
+uint16_t rssiMonitorDelayCycles = DEFAULT_RSSI_MONITOR_DELAY_CYCLES;

 //----- Voltage monitoring -------------------------
 #define VOLTAGE_READS 3 //get average of VOLTAGE_READS readings
@@ -249,6 +256,8 @@
     DEBUG_CODE(
         pinMode(serialTimerPin, OUTPUT);
         pinMode(loopTimerPin, OUTPUT);
+        pinMode(bufferBusyPin, OUTPUT);
+        pinMode(sequencePin, OUTPUT);
     );
 }
 // ----------------------------------------------------------------------------
@@ -371,14 +380,19 @@
                     onItemSent();
                 }
                 break;
-            case 12: // SEND_API_VERSION
+            case 12: // SEND_MONITOR_DELAY
+                if (sendIntToSerial(RESPONSE_MONITOR_DELAY, rssiMonitorDelayCycles)) {
+                    onItemSent();
+                }
+                break;
+            case 13: // SEND_API_VERSION
                 if (sendIntToSerial(RESPONSE_API_VERSION, API_VERSION)) {
                     onItemSent();
                 }
                 break;
             // Below is a termination case, to notify that data for CONTROL_DATA_REQUEST is over.
             // Must be the last item in the sequence!
-            case 13: // SEND_END_SEQUENCE
+            case 14: // SEND_END_SEQUENCE
                 if (send4BitsToSerial(RESPONSE_END_SEQUENCE, 1)) {
                     onItemSent();
                     isSendingData = 0;
@@ -440,7 +454,7 @@

     if (rssiMonitor) {
         rssiMonitorDelayExpiration++;
-        if (rssiMonitorDelayExpiration > MAX_RSSI_MONITOR_DELAY_CYCLES) {
+        if (rssiMonitorDelayExpiration >= rssiMonitorDelayCycles) {
             addToSendQueue(SEND_CURRENT_RSSI);
             rssiMonitorDelayExpiration = 0;
         }
@@ -560,6 +574,11 @@
             case CONTROL_SET_FREQUENCY: // set frequency
                 frequency = setModuleFrequency(HEX_TO_UINT16(&controlData[1]));
                 addToSendQueue(SEND_FREQUENCY);
+                isConfigured = 1;
+                break;
+            case CONTROL_SET_MON_DELAY: // set frequency
+                rssiMonitorDelayCycles = setRssiMonitorDelay(HEX_TO_UINT16(&controlData[1]));
+                addToSendQueue(SEND_MONITOR_DELAY);
                 isConfigured = 1;
                 break;
         }
@@ -591,6 +610,9 @@
                 addToSendQueue(SEND_RACE_STATE);
                 isConfigured = 1;
                 break;
+            case CONTROL_GET_RSSI: // get current RSSI value
+                addToSendQueue(SEND_CURRENT_RSSI);
+                break;
             case CONTROL_DEC_MIN_LAP: // decrease minLapTime
                 decMinLap();
                 playClickTones();
@@ -691,8 +713,11 @@
 }
 // ----------------------------------------------------------------------------
 void readSerialDataChunk () {
+    // don't read anything if we have something not sent in proxyBuf
+    if (proxyBufDataSize != 0) return;
+
     uint8_t availBytes = Serial.available();
-    if (availBytes && proxyBufDataSize == 0) {
+    if (availBytes) {
         uint8_t freeBufBytes = READ_BUFFER_SIZE - readBufFilledBytes;

         //reset buffer if we couldn't find delimiter in its contents in prev step
@@ -705,7 +730,9 @@
         uint8_t canGetBytes = availBytes > freeBufBytes ? freeBufBytes : availBytes;
         Serial.readBytes(&readBuf[readBufFilledBytes], canGetBytes);
         readBufFilledBytes += canGetBytes;
-
+    }
+
+    if (readBufFilledBytes) {
         //try finding a delimiter
         uint8_t foundIdx = 255;
         for (uint8_t i = 0; i < readBufFilledBytes; i++) {
@@ -716,7 +743,7 @@
         }

         uint8_t shouldPassMsgFurther = 1;
-        //if delimiter found
+        //if delimiter found then process the command or send it further
         if (foundIdx < READ_BUFFER_SIZE) {
             switch (readBuf[0]) {
                 case 'R': //read data from module
@@ -761,6 +788,7 @@
     if (proxyBufDataSize && Serial.availableForWrite() > proxyBufDataSize) {
         Serial.write(proxyBuf, proxyBufDataSize);
         Serial.write(SERIAL_DATA_DELIMITER);
+
         proxyBufDataSize = 0;
     }
 }
@@ -863,6 +891,10 @@
     } else {
         playClearThresholdTones();
     }
+}
+// ----------------------------------------------------------------------------
+uint16_t setRssiMonitorDelay(uint16_t delay) {
+    return delay < MIN_RSSI_MONITOR_DELAY_CYCLES ? MIN_RSSI_MONITOR_DELAY_CYCLES : delay;
 }
 // ----------------------------------------------------------------------------
 uint16_t getFilteredRSSI() {


SCS Update

SCS Update

--- BiotechHardware/scs/scs.ino
+++ BiotechHardware/scs/scs.ino
@@ -17,7 +17,7 @@

 byte mac[] = {0x90, 0xA2, 0xDA, 0x0E, 0xF5, 0x30 };
 const char server[] = "192.168.1.3";
-IPAddress ip(192,168,4,3);
+IPAddress ip(192,168,3,5);

 OneWire oneWire(temp_pin);
 DallasTemperature temp_sensor(&oneWire);


Steps

Steps

--- Code/OricKeyboardReader.ino
+++ Code/OricKeyboardReader.ino
@@ -48,6 +48,8 @@

 void loop()
 {
+	// 1. Scan
+
 	for (int row = 0; row <= 7; row++)
 	{
 		matrix[row]=scan(row);
@@ -57,6 +59,13 @@
 		Serial.print("\t");
 	}
 	Serial.println();
+
+	// 2. Assign to keys
+
+	// 3. Debounce
+
+	// 4. Output
+

 	delay(10);
 }


show status by led

show status by led

--- sketch_radar_detecting/sketch_radar_detecting.ino
+++ sketch_radar_detecting/sketch_radar_detecting.ino
@@ -5,6 +5,7 @@
 #include <MQTTClient.h>

 #define JSON_BUF_SIZE 1024
+#define LED_PIN 13

 typedef enum {
   STATUS_INVALID,
@@ -36,6 +37,11 @@
 static unsigned long g_last_report_ms = 0;

 static unsigned long g_check_net_ms = 0;
+
+static unsigned long g_last_led_ms = 0;
+static long g_led_interval = 1000;
+static int g_led_state = LOW;
+static int g_led_fast = 0;

 static bool get_ip_port(const char *url, char *ip, uint16_t *port) {
   char *p = strstr(url, "tcp://");
@@ -227,6 +233,8 @@
   Serial.println("publish: " + json);
   g_mqtt_client.publish(g_report_topic, json);

+  g_led_interval = 50;
+  g_led_fast = 0;
   g_need_report = false;
 }

@@ -248,10 +256,10 @@
 }

 void extMessageReceived(EXTED_CMD cmd, int status, String payload, unsigned int length) {
-  //  Serial.println("ext msg: " + String(cmd) + ", " + payload);
-}
-
-void init_reset_cnt() {
+//  Serial.println("ext msg: " + String(cmd) + ", " + payload);
+}
+
+static void init_reset_cnt() {
   uint32_t cnt = 0;
   *((uint8_t *)&cnt + 0) = EEPROM.read(0);
   *((uint8_t *)&cnt + 1) = EEPROM.read(1);
@@ -268,10 +276,38 @@
   EEPROM.write(3, *((uint8_t *)&cnt + 3));
 }

+static void handle_led() {
+  unsigned long now = millis();
+
+  if (now - g_last_led_ms >= g_led_interval) {
+    // save the last time you blinked the LED
+    g_last_led_ms = now;
+
+    // if the LED is off turn it on and vice-versa:
+    if (g_led_state == LOW) {
+      g_led_state = HIGH;
+    } else {
+      g_led_state = LOW;
+    }
+
+    if (g_led_interval = 50) {
+      g_led_fast += 1;
+      if (g_led_fast >= 10) {
+        g_led_interval = 1000;
+      }
+    }
+    digitalWrite(LED_PIN, g_led_state);
+  }
+}
+
 void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println("setup...");
+
+  pinMode(LED_PIN, OUTPUT);
+  digitalWrite(LED_PIN, g_led_state);
+  g_last_led_ms = millis();

   init_reset_cnt();
   g_status = STATUS_INIT_GPRS;
@@ -292,6 +328,7 @@
       check_need_report();
       handle_report();
       check_network();
+      handle_led();
       break;
     default:
       Serial.println("unknown status: " + g_status);


examples-ltc: basicthreads: use createThreadFromHeap

This function is now provided by ltc-compiler, so use it instead of
implementing a confusing version in the browser.

Signed-off-by: Sean Cross <d7e19930cc1f42c2d0781f4d9e6f1fe5891bf9cf@xobs.io>

--- examples-ltc/B.Threads/BasicThreads/BasicThreads.ino
+++ examples-ltc/B.Threads/BasicThreads/BasicThreads.ino
@@ -43,20 +43,6 @@
 };
 static fade_thread_config thread_config[NUMBER_OF_THREADS];

-static thread_t *fade_threads[NUMBER_OF_THREADS];
-
-// this magic function creates a Thread from heap
-static thread_t *runThread(tfunc_t pf, void *arg) {
-  thread_t *thr = (thread_t *)malloc(THD_WORKING_AREA_SIZE(THREAD_MEMORY));
-  createThread((void *)thr, THD_WORKING_AREA_SIZE(THREAD_MEMORY), THREAD_PRIORITY, pf, arg);
-
-  /* Mark thr->p_flags as CH_FLAG_MODE_HEAP, so ChibiOS will call free()
-   * on the memory after it exits.
-   */
-  ((uint8_t *)thr)[0x1d] = 1;
-  return thr;
-}
-
 // You'll recognize this code from the "fade" demo!
 void fade_code(void *config) {
   struct fade_thread_config *cfg = (struct fade_thread_config *)config;
@@ -95,12 +81,14 @@
   // we don't want to keep on starting threads over and over again!

   // The first thread starts running after this line of code.
-  fade_threads[0] = runThread(fade_code, &thread_config[0]);
+  createThreadFromHeap(THD_WORKING_AREA_SIZE(THREAD_MEMORY), THREAD_PRIORITY,
+                       fade_code, &thread_config[0]);

   delay(1000); // this will delay the start of the second thread by 1 second

   // The second thread starts running after this line of code.
-  fade_threads[1] = runThread(fade_code, &thread_config[1]);
+  createThreadFromHeap(THD_WORKING_AREA_SIZE(THREAD_MEMORY), THREAD_PRIORITY,
+                       fade_code, &thread_config[1]);
 }

 void loop(void) {


Make sure the SD card gets disabled

Make sure the SD card gets disabled

--- src/du_ethernet.ino
+++ src/du_ethernet.ino
@@ -9,24 +9,28 @@

 Dino dino;
 EthernetServer server(port);
-// String url = "";
 char request[8];
+char c;
 int index = 0;
 String response = "";

+
 void setup() {
+  // Explicitly disable the SD card.
+  pinMode(4,OUTPUT);
+  digitalWrite(4,HIGH);
+
   // Start up the network connection and server.
   Ethernet.begin(mac, ip);
   server.begin();
-
+
   // Start serial for debugging.
   Serial.begin(115200);
-  Serial.print("Dino TCP client started at ");
+  Serial.print("Dino::TCP started at ");
   Serial.print(Ethernet.localIP());
   Serial.print(" on port ");
   Serial.println(port);
 }
-

 void loop() {
@@ -39,7 +43,7 @@
     response = "";
     while (client.connected()) {
       if (client.available()) {
-        char c = client.read();
+        c = client.read();

         // Reset the request and response when the beginning delimiter is received.
         if (c == '!') {


Correct SunRise/NightLight with Color Fade (#710)

--- wled00/wled08_led.ino
+++ wled00/wled08_led.ino
@@ -231,15 +231,15 @@
       nightlightDelayMs = (int)(nightlightDelayMins*60000);
       nightlightActiveOld = true;
       briNlT = bri;
-      for (byte i=0; i<4; i++) colNlT[i] = col[i];                                    // remember starting color
+      for (byte i=0; i<4; i++) colNlT[i] = colT[i];                                     // remember starting color
     }
     float nper = (millis() - nightlightStartTime)/((float)nightlightDelayMs);
     if (nightlightFade)
     {
       bri = briNlT + ((nightlightTargetBri - briNlT)*nper);
-      if (nightlightColorFade)                                                        // color fading only is enabled with "NF=2"
+      if (nightlightColorFade)                                                          // color fading only is enabled with "NF=2"
       {
-        for (byte i=0; i<4; i++) col[i] = colNlT[i]+ ((colSec[i] - colNlT[i])*nper);  // fading from actual color to secondary color
+        for (byte i=0; i<4; i++) colT[i] = colNlT[i]+ ((colSecT[i] - colNlT[i])*nper);  // fading from actual color to secondary color
       }
       colorUpdated(NOTIFIER_CALL_MODE_NO_NOTIFY);
     }


Update previousMillis in example

Update previousMillis in example

--- libraries/CurieBle/examples/BatteryMonitorNewAPI/BatteryMonitorNewAPI.ino
+++ libraries/CurieBle/examples/BatteryMonitorNewAPI/BatteryMonitorNewAPI.ino
@@ -82,6 +82,7 @@
       unsigned long currentMillis = millis();

       if (currentMillis - previousMillis >= 200) {
+        previousMillis = currentMillis;
         updateBatteryLevel();
       }
     }


Update reset logic: reset if 10 mqtt pubs failed in a row

--- zg01_esp/zg01_esp.ino
+++ zg01_esp/zg01_esp.ino
@@ -69,6 +69,7 @@

 void loop(void)
 {
+    static int errors = 0;
     static bool prev_clk = false;
     char valstr[16];
     int temp10;
@@ -90,18 +91,30 @@
             case 'P':
                 // CO2
                 snprintf(valstr, sizeof(valstr), "%d PPM", value);
-                mqtt_send(TOPIC_CO2, valstr, true);
+                if (mqtt_send(TOPIC_CO2, valstr, true)) {
+                    errors = 0;
+                } else {
+                    errors++;
+                }
                 break;
             case 'A':
                 // humidity
                 snprintf(valstr, sizeof(valstr), "%d.%02d %%", value / 100, value % 100);
-                mqtt_send(TOPIC_HUMIDITY, valstr, true);
+                if (mqtt_send(TOPIC_HUMIDITY, valstr, true)) {
+                    errors = 0;
+                } else {
+                    errors++;
+                }
                 break;
             case 'B':
                 // temperature
                 temp10 = (5 * value - 21848) / 8;
                 snprintf(valstr, sizeof(valstr), "%d.%d °C", temp10 / 10, abs(temp10) % 10);
-                mqtt_send(TOPIC_TEMPERATURE, valstr, true);
+                if (mqtt_send(TOPIC_TEMPERATURE, valstr, true)) {
+                    errors = 0;
+                } else {
+                    errors++;
+                }
                 break;
             default:
                 // ignore unhandled packet
@@ -114,8 +127,8 @@
     // keep mqtt alive
     mqttClient.loop();

-    // verify network connection and reboot on failure
-    if (WiFi.status() != WL_CONNECTED) {
+    // reboot on too many errors
+    if (errors > 10) {
         Serial.println("Restarting ESP...");
         ESP.restart();
     }


Added delay after SAMSUNG2 repeat in example.

The is needed for the received to actually respond. Otherwise the
receiver tends to not respond at all.

--- examples/SamsungSamsung2Demo/SamsungSamsung2Demo.ino
+++ examples/SamsungSamsung2Demo/SamsungSamsung2Demo.ino
@@ -24,6 +24,7 @@
   irsend.sendSamsung2(Samsung2Address,Samsung2Power); // This should turn your TV on and off

   irsend.sendSamsung(REPEAT, 32); // Some receivers seem to respond a lot faster when a repeat is sent before the actual command.
+  delay(35); //This delay is needed for optimal response.
   irsend.sendSamsung(Samsung, 32); // hex value, 32 bits
   delayMicroseconds(50);
 }


Fix for constrained RSSI readings before being used to compare best diversity module.

--- src/rx5808-pro-diversity/rx5808-pro-diversity.ino
+++ src/rx5808-pro-diversity/rx5808-pro-diversity.ino
@@ -1000,14 +1000,9 @@
 #endif
     }

-
-    rssiA = constrain(rssiA, rssi_min_a, rssi_max_a);    //original 90---250
-    rssiA=rssiA-rssi_min_a; // set zero point (value 0...160)
-    rssiA = map(rssiA, 0, rssi_max_a-rssi_min_a , 1, 100);   // scale from 1..100%
-#ifdef USE_DIVERSITY
-    rssiB = constrain(rssiB, rssi_min_b, rssi_max_b);    //original 90---250
-    rssiB=rssiB-rssi_min_b; // set zero point (value 0...160)
-    rssiB = map(rssiB, 0, rssi_max_b-rssi_min_b , 1, 100);   // scale from 1..100%
+    rssiA = map(rssiA, rssi_min_a, rssi_max_a , 1, 100);   // scale from 1..100%
+#ifdef USE_DIVERSITY
+    rssiB = map(rssiB, rssi_min_b, rssi_max_b , 1, 100);   // scale from 1..100%
     if(receiver == -1) // no receiver was chosen using diversity
     {
         switch(diversity_mode)
@@ -1059,7 +1054,7 @@
         rssi = rssiB;
     }
 #endif
-    return (rssi);
+    return constrain(rssi,1,100); // clip values to only be within this range.
 }

 void setReceiver(uint8_t receiver) {


converted to HTTP/1.1 and the client point to the arduino ascii logo

--- libraries/GSM/examples/GsmWebClient/GsmWebClient.ino
+++ libraries/GSM/examples/GsmWebClient/GsmWebClient.ino
@@ -2,8 +2,8 @@
   Web client

  This sketch connects to a website through a GSM shield. Specifically,
- this example downloads the URL "http://arduino.cc/" and prints it
- to the Serial monitor.
+ this example downloads the URL "http://arduino.cc/asciilogo.txt" and
+ prints it to the Serial monitor.

  Circuit:
  * GSM shield attached to an Arduino
@@ -34,7 +34,7 @@

 // URL, path & port (for example: arduino.cc)
 char server[] = "arduino.cc";
-char path[] = "/";
+char path[] = "/asciilogo.txt";
 int port = 80; // port 80 is the default for HTTP

 void setup()
@@ -48,13 +48,13 @@
   Serial.println("Starting Arduino web client.");
   // connection state
   boolean notConnected = true;
-
+
   // After starting the modem with GSM.begin()
   // attach the shield to the GPRS network with the APN, login and password
   while(notConnected)
   {
     if((gsmAccess.begin(PINNUMBER)==GSM_READY) &
-        (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
+      (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
       notConnected = false;
     else
     {
@@ -72,10 +72,10 @@
     // Make a HTTP request:
     client.print("GET ");
     client.print(path);
-    client.println(" HTTP/1.0");
-    client.println();
-    client.print("HOST: ");
+    client.println(" HTTP/1.1");
+    client.print("Host: ");
     client.println(server);
+    client.println("Connection: close");
     client.println();
   }
   else
@@ -94,7 +94,7 @@
     char c = client.read();
     Serial.print(c);
   }
-
+
   // if the server's disconnected, stop the client:
   if (!client.available() && !client.connected())
   {


Calibrate sensor readings

Calibrate sensor readings

--- src/main/main.ino
+++ src/main/main.ino
@@ -40,12 +40,68 @@
 		0x2 << 2 | // 1000 degrees per second
 		0x0);

+	calibrate_sensors();
+
 	ahrs.begin((float) SAMPLE_FREQUENCY);
+}
+
+int acc_x_offset;
+int acc_y_offset;
+int acc_z_offset;
+
+int gyro_x_offset;
+int gyro_y_offset;
+int gyro_z_offset;
+
+void calibrate_sensors()
+{
+	int samples_count = 0;
+
+	int64_t acc_x_sum = 0;
+	int64_t acc_y_sum = 0;
+	int64_t acc_z_sum = 0;
+
+	int64_t gyro_x_sum = 0;
+	int64_t gyro_y_sum = 0;
+	int64_t gyro_z_sum = 0;
+
+	// Collect sensor data for a second
+	while(micros() < MICROS_PER_SEC)
+	{
+		imu.read();
+
+		acc_x_sum += imu.a.x;
+		acc_y_sum += imu.a.y;
+		acc_z_sum += imu.a.z;
+
+		gyro_x_sum += imu.g.x;
+		gyro_y_sum += imu.g.y;
+		gyro_z_sum += imu.g.z;
+
+		++samples_count;
+	}
+
+	// Should I use floats here?
+	acc_x_offset = acc_x_sum / samples_count;
+	acc_y_offset = acc_y_sum / samples_count;
+	acc_z_offset = acc_z_sum / samples_count - gScale;
+
+	gyro_x_offset = gyro_x_sum / samples_count;
+	gyro_y_offset = gyro_y_sum / samples_count;
+	gyro_z_offset = gyro_z_sum / samples_count;
 }

 void read_sensors()
 {
 	imu.read();
+
+	imu.a.x -= acc_x_offset;
+	imu.a.y -= acc_y_offset;
+	imu.a.z -= acc_z_offset;
+
+	imu.g.x -= gyro_x_offset;
+	imu.g.y -= gyro_y_offset;
+	imu.g.z -= gyro_z_offset;
 }

 void update_ahrs()
@@ -63,6 +119,8 @@

 char report[80];

+int cyclesPerSecond = 0;
+
 void print_info()
 {
 	float gyroX = imu.g.x / dpsScale;
@@ -72,6 +130,10 @@
 	float accX = imu.a.x / gScale;
 	float accY = imu.a.y / gScale;
 	float accZ = imu.a.z / gScale;
+
+	Serial.print(cyclesPerSecond * PRINT_FREQUENCY);
+	Serial.print("\t");
+	cyclesPerSecond = 0;

 	Serial.print("ACC: ");
 	Serial.print(accX);
@@ -110,12 +172,9 @@
 	if(currentMicros - lastSampleMicros >= MICROS_PER_SEC / SAMPLE_FREQUENCY)
 	{
 		read_sensors();
+		update_ahrs();

-		if(currentMicros < MICROS_PER_SEC)
-		{
-			// calibrate sensors
-		}
-		else update_ahrs();
+		++cyclesPerSecond;

 		lastSampleMicros = currentMicros;
 	}


D21FM: moving tests down to base lib.

D21FM: moving tests down to base lib.

--- test/test.ino
+++ test/test.ino
@@ -585,6 +585,25 @@

 // BASE

+// Test elements of RTC time persist/restore (without causing more EEPROM wear, if working correctly).
+static void testRTCPersist()
+  {
+  Serial.println("RTCPersist");
+  // Perform with interrupts shut out to avoid RTC ISR interferring.
+  // This will effectively stall the RTC.
+  bool minutesPersistOK;
+  ATOMIC_BLOCK (ATOMIC_RESTORESTATE)
+    {
+    const uint_least16_t mb = OTV0P2BASE::getMinutesSinceMidnightLT();
+    OTV0P2BASE::persistRTC();
+    OTV0P2BASE::restoreRTC();
+    const uint_least16_t ma = OTV0P2BASE::getMinutesSinceMidnightLT();
+    // Check that persist/restore did not change live minutes value at least, within the 15-minute quantum used.
+    minutesPersistOK = (mb/15 == ma/15);
+    }
+    AssertIsTrue(minutesPersistOK);
+  }
+
 // Self-test of EEPROM functioning (and smart/split erase/write).
 // Will not usually perform any wear-inducing activity (is idempotent).
 static void testEEPROM()
@@ -777,6 +796,7 @@
   testCurrentSenseValveMotorDirect();

   // OTV0p2Base
+  testRTCPersist();
   testEEPROM();
   testSleep();
   testRNG8();


_06_kidSerie_sketch_04.Adafruit_final_feeds.ino -  Final Code

_06_kidSerie_sketch_04.Adafruit_final_feeds.ino -  Final Code

--- _06_kidSerie_sketch_02.Adafruit_fake_feeds.ino
+++ _06_kidSerie_sketch_02.Adafruit_fake_feeds.ino
@@ -79,9 +79,11 @@
 // Setup a feed called 'photocell' for publishing.
 // Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
 Adafruit_MQTT_Publish temp_topic = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/temp");
+Adafruit_MQTT_Publish humid_topic = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/humid");
 /****************************** Subscriptions*********************************/
 // Setup a feed called 'photocell' for subscribing to changes.
 Adafruit_MQTT_Subscribe temp_subscription = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/temp");
+Adafruit_MQTT_Subscribe humid_subscription = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/humid");

 /***************************  MQTT Conn   ************************************/

@@ -98,7 +100,7 @@
 // higher the value.  The default for a 16mhz AVR is a value of 6.  For an
 // Arduino Due that runs at 84mhz a value of 30 works.
 // This is for the ESP8266 processor on ESP-01
-DHT dht(DHTPIN, DHTTYPE, 11); // 11 works fine for ESP8266
+DHT dht(DHTPIN, DHTTYPE, 15); // 11 works fine for ESP8266
 /*************************** DHT Data   **************************************/
 //float humidity, temp_f;  // Values read from sensor Fahrenheit
 float humidity, temp_c;  // Values read from sensor as Celsius
@@ -132,6 +134,8 @@

   // Setup MQTT subscription for onoff feed.
   mqtt.subscribe(&temp_subscription);
+  delay(1000);
+  mqtt.subscribe(&humid_subscription);
 }

 //uint32_t x=0;    // Mock data
@@ -153,6 +157,10 @@
     if (subscription == &temp_subscription) {
       Serial.print(F("Got: "));
       Serial.println((char *)temp_subscription.lastread);
+    }
+    else {
+      Serial.print(F("Got humid: "));
+      Serial.println((char *)humid_subscription.lastread);
     }
   }
  /****************************** Publish  **********************************/
@@ -161,6 +169,15 @@
   Serial.print(temp_c);
   Serial.print("...");
   if (! temp_topic.publish(temp_c)) {
+    Serial.println(F("Failed"));
+  } else {
+    Serial.println(F("OK!"));
+  }
+
+  Serial.print(F("\nSending humid val "));
+  Serial.print(humidity);
+  Serial.print("...");
+  if (! humid_topic.publish(humidity)) {
     Serial.println(F("Failed"));
   } else {
     Serial.println(F("OK!"));
@@ -215,12 +232,12 @@

     // Reading temperature for humidity takes about 250 milliseconds!
     // Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor)
-    //humidity = dht.readHumidity();          // Read humidity (percent)
+    humidity = dht.readHumidity();          // Read humidity (percent)
     //temp_f = dht.readTemperature(true);     // Read temperature as Fahrenheit
     temp_c = dht.readTemperature();    // Read temperature as Celsius
     // Check if any reads failed and exit early (to try again).
     if (isnan(temp_c) || temp_c != 0 )
-      if (isnan(temp_c)) {
+      if (isnan(temp_c) || isnan(humidity) || temp_c != 0 || humidity != 0 ) {
         Serial.println("Failed to read from DHT sensor!");
         return;
         }


ESP8266 as a Shield stability improvement

--- examples/BoardsAndShields/ESP8266_Shield_SoftSer/ESP8266_Shield_SoftSer.ino
+++ examples/BoardsAndShields/ESP8266_Shield_SoftSer/ESP8266_Shield_SoftSer.ino
@@ -21,6 +21,8 @@
  *       Firmware version 1.0.0 (AT v0.22) or later is needed.
  *       Set ESP baud rate to 9600. Connect to AT console and call:
  *           AT+UART_DEF=9600,8,1,0,0
+ *       In general, Soft Serial is unstable.
+ *       It is highly recommended to switch to Hard Serial.
  *
  * Change WiFi ssid, pass, and Blynk auth token to run :)
  * Feel free to apply it to any other example. It's simple!


Update soil_moisture_sensor_st.ino

Update soil_moisture_sensor_st.ino

--- ESP8266-Mosture-Sensor/soil_moisture_sensor_st.ino
+++ ESP8266-Mosture-Sensor/soil_moisture_sensor_st.ino
@@ -9,17 +9,12 @@
 1.0.3 - added OTA update capability
 1.0.4 - control power supply to sensor via GPIO12 = D6
 1.0.5 - accept SmartThings hub IP & port setup during Wifi setup. Execute everything in the setup, as loop is not req
-1.0.6 - minor code update, to check if st_port and st_ip is not empty, otherwise go back to wifi setup mode
-
-Todo software:
+1.0.6 - minor code update, to check if st_port and st_ip is not empty, otherwise go back to setup mode
+
+Todo:
 1. Ability to define Wake up freq at runtime
 2. Blink green LED when upload success, red when failed
 3. Customize URL for OTA
-
-Todo hardware:
-1. Add Power supervisor KA75330, so if voltage too low, it will not reset (after deep sleep) and goes into zombie mode
-2. Add POLOLU-2563 Pololu 3.3V Step-Up Voltage Regulator U1V10F3/FBA - if using 2x AA battery
-3. Add reed switch to pull up / down a GPIO to trigger the OTA, otherwise don't check for OTA

 References:
 ===========
@@ -50,14 +45,24 @@
 //Ticker ticker;

 //set pin for moisture sensor, A0 is an analog pin on nodemcu, to read analog value from moisture sensor
-#define sensorPin   A0
+#define sensorPin A0

 //provide power to the sensor, so it's not always on as the sensor will eroded fast
-const int powerPin = 12; //GPIO12 = D6
+#define powerPin 12 //GPIO12 = D6
+
+//D2/GPIO04 Green (success), D1/GPIO05 (failed) Red
+#define greenLed 04
+#define redLed 05
+
+//check frequency
+int checkFreq = 10; //in mins - wake interval
+
+//current firmware version
+const int FW_VERSION = 1005;

 // Smartthings hub information
 IPAddress hubIp; // smartthings hub ip
-unsigned int hubPort = 39500; // smartthings hub port
+int hubPort = 39500; // smartthings hub port

 int char2int (char *array, size_t n);

@@ -68,9 +73,6 @@
 //flag for saving data using wifi manager page
 bool shouldSaveConfig = false;

-//current firmware version
-const int FW_VERSION = 1003;
-
 //firmware location
 const char* fwUrlBase = "http://192.168.0.26/esp8266/ota/";

@@ -78,11 +80,7 @@
 WiFiClient client; //client
 String readString;

-//check frequency
-int checkFreq = 5; //in mins - wake interval
-
 void setup() {
-    // put your setup code here, to run once:
     Serial.begin(115200);
     delay(1);

@@ -90,16 +88,14 @@

     //moisture sensor pin
     pinMode(sensorPin, INPUT);
-
     //pin to provide power to sensor
     pinMode(powerPin, OUTPUT);
-
+    //pin to flash the upload status
+    pinMode(greenLed, OUTPUT);
+    pinMode(redLed, OUTPUT);
+
     //read from FS
     readFS();
-
-//    WiFiManager wifiManager;
-//    wifiManager.autoConnect("AutoConnectAP");
-//    Serial.println("connected...yeey :)");

     //connect to wifi
     wificonnect();
@@ -111,15 +107,21 @@
     if (sendNotify()) {
       Serial.println("sendNotify completed");
       sendStatusToWeb("sendNotify_completed");
+      digitalWrite(greenLed, HIGH);   // turn the LED on (HIGH is the voltage level)
+      delay(100);                       // wait for a second
+      digitalWrite(greenLed, LOW);    // turn the LED off by making the voltage LOW
     }
     else {
       Serial.println("sendNotify have issue");
+
       sendStatusToWeb("sendNotify_failed");
+      digitalWrite(redLed, HIGH);   // turn the LED on (HIGH is the voltage level)
+      delay(100);                       // wait for a second
+      digitalWrite(redLed, LOW);    // turn the LED off by making the voltage LOW
     }

     // Deep sleep mode for 30 seconds
     //the ESP8266 wakes up by itself when GPIO 16 (D0 in NodeMCU/Wemos board) is connected to the RESET pin
-
     Serial.print("I'm going into deep sleep mode for ");
     Serial.print(checkFreq);
     Serial.println(" mins");
@@ -133,7 +135,6 @@

 void loop() {
     // put your main code here, to run repeatedly:
-
 }

 //gets called when WiFiManager enters configuration mode
@@ -148,7 +149,7 @@

 void readFS(){
   //read configuration from FS json
-  Serial.println("mounting FS...");
+    Serial.println("mounting FS...");

   if (SPIFFS.begin()) {
     Serial.println("mounted file system");
@@ -168,7 +169,6 @@
         json.printTo(Serial);
         if (json.success()) {
           Serial.println("\nparsed json");
-
           strcpy(st_hub, json["st_hub"]);
           strcpy(st_port, json["st_port"]);

@@ -186,12 +186,6 @@

 void wificonnect(){
-//  WiFi.forceSleepWake();
-//  delay(100);
-  //Disable the WiFi persistence.  The ESP8266 will not load and save WiFi settings in the flash memory.
-//  WiFi.persistent( true );
-//  WiFi.mode (WIFI_STA);
-
 //  //set led pin as output
 //  pinMode(BUILTIN_LED, OUTPUT);
 //  // start ticker with 0.5 because we start in AP mode and try to connect
@@ -213,8 +207,6 @@
   //add all your parameters here
   wifiManager.addParameter(&custom_st_hub);
   wifiManager.addParameter(&custom_st_port);
-
-//  wifiManager.autoConnect("Soil_Moisture_Sensor", "configme");

   //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
   wifiManager.setAPCallback(configModeCallback);
@@ -272,15 +264,6 @@
     //end save
   }

-//  WiFi.begin(ssid, password);
-//  Serial.print("Connecting to wifi...");
-//  while (WiFi.status() != WL_CONNECTED) {
-//    delay(500);
-//    Serial.print(".");
-//  }
-//  Serial.println("Connected!");
-//  Serial.print( "Assigned IP address: " );
-//  Serial.println( WiFi.localIP() );
 }

@@ -461,9 +444,7 @@

   httpClient.begin( url );

-  int httpCode = httpClient.GET();
-//  Serial.println( "sending to " );
-
+  int httpCode = httpClient.GET();

   httpClient.end();


Fixed bug where 'F' would only be sent if there was an error when withdrawing - should always send 'F' when concluding communication without error

--- VendingMachineRFID.ino
+++ VendingMachineRFID.ino
@@ -198,9 +198,9 @@
             // Could not update machine credits - attempt to save credits to card again!
             card.credits = current_credits;
             updateAndVerify(addr, card);
-            Serial.write('F'); // finish communication
             BEEP(4);
           }// else {BEEP(1);}
+          Serial.write('F'); // finish communication
         } else {
           // ERR Beep + display "ERR  EEPROM BAD" ?
           //Serial.println("ERR  EEPROM BAD");


correct title

correct title

--- cmdMULTIsens/src/sketch.ino
+++ cmdMULTIsens/src/sketch.ino
@@ -1,5 +1,5 @@
 /*
-  cmdMULTI sketch
+  cmdMULTIsens sketch

 */


RFID-MRC522-SoftSPI

RFID-MRC522-SoftSPI

created a new "printRdid" function. minor improvements from previous code.

--- RFID_MRC522_SoftSPI.ino
+++ RFID_MRC522_SoftSPI.ino
@@ -24,8 +24,7 @@

 #define SS_PIN 8
 #define RST_PIN 4
-#define RX 11
-#define TX 10
+
 RFID rfid(SS_PIN, RST_PIN); //create an instance rfid for the class RFID

 // varables to store data
@@ -42,7 +41,8 @@

 void loop()
 {
-  readRfid();
+ readRfid();
+ printRfid();
 }

 void readRfid()
@@ -51,19 +51,27 @@
   {
     if (rfid.readCardSerial())
     {
-      Serial.println("Card found");
-      Serial.print("Cardnumber: ");
       for (int i=0; i<=4; i++)//card value: "xyz xyz xyz xyz xyz" (15 digits maximum; 5 pairs of xyz)hence 0<=i<=4 //
       {
         RFID = rfid.serNum[i];
         cardNum += RFID; // store RFID value into string "cardNum" and concatinate it with each iteration
       }
-      Serial.println(cardNum);
-      cardNum.remove(0);//This is an arduino function.
-  //remove the stored value after printing. else the new card value that is read
-  // will be concatinated with the previous string.
-      delay(500);
     }
   }
   rfid.halt();
 }
+
+void printRfid()
+{
+ if (cardNum != '\0')//if string cardNum is not empty, print the value
+ {
+    Serial.println("Card found");
+    Serial.print("Cardnumber: ");
+    Serial.println(cardNum);
+    cardNum.remove(0);
+   //This is an arduino function.
+  //remove the stored value after printing. else the new card value that is read
+  // will be concatinated with the previous string.
+  delay(500);
+ }
+}


Move back to header prints in each endpoint until function method can be fixed

--- weather_station/dashboard/arduino/weather_station_02.ino
+++ weather_station/dashboard/arduino/weather_station_02.ino
@@ -69,7 +69,10 @@
     request.trim();   //kill whitespace

     if (request == "tempf") {
-      remoteJSONHeaders();
+      client.println("Status: 200");
+      client.println("Content-type: application/json");
+      client.println("Access-Control-Allow-Origin: *");
+      client.println(); //mandatory blank line

       // JSON response
       client.print("{\"type\":\"temperature\",");
@@ -81,7 +84,10 @@
     }

     if (request == "tempc") {
-      remoteJSONHeaders();
+      client.println("Status: 200");
+      client.println("Content-type: application/json");
+      client.println("Access-Control-Allow-Origin: *");
+      client.println(); //mandatory blank line

       // JSON response
       client.print("{\"type\":\"temperature\",");
@@ -93,7 +99,10 @@
     }

     if (request == "tempk") {
-      remoteJSONHeaders();
+      client.println("Status: 200");
+      client.println("Content-type: application/json");
+      client.println("Access-Control-Allow-Origin: *");
+      client.println(); //mandatory blank line

       // JSON response
       client.print("{\"type\":\"temperature\",");
@@ -105,7 +114,10 @@
     }

     if (request == "hum") {
-      remoteJSONHeaders();
+      client.println("Status: 200");
+      client.println("Content-type: application/json");
+      client.println("Access-Control-Allow-Origin: *");
+      client.println(); //mandatory blank line

       // JSON response
       client.print("{\"type\":\"humidity\",");
@@ -117,7 +129,10 @@
     }

     if (request == "hif") {
-      remoteJSONHeaders();
+      client.println("Status: 200");
+      client.println("Content-type: application/json");
+      client.println("Access-Control-Allow-Origin: *");
+      client.println(); //mandatory blank line

       // JSON response
       client.print("{\"type\":\"index\",");
@@ -129,7 +144,10 @@
     }

     if (request == "hic") {
-      remoteJSONHeaders();
+      client.println("Status: 200");
+      client.println("Content-type: application/json");
+      client.println("Access-Control-Allow-Origin: *");
+      client.println(); //mandatory blank line

       // JSON response
       client.print("{\"type\":\"index\",");
@@ -142,7 +160,10 @@
     }

     if (request == "dp") {
-      remoteJSONHeaders();
+      client.println("Status: 200");
+      client.println("Content-type: application/json");
+      client.println("Access-Control-Allow-Origin: *");
+      client.println(); //mandatory blank line

       // JSON response
       client.print("{\"type\":\"index\",");
@@ -155,7 +176,10 @@
     }

     if (request == "light") {
-      remoteJSONHeaders();
+      client.println("Status: 200");
+      client.println("Content-type: application/json");
+      client.println("Access-Control-Allow-Origin: *");
+      client.println(); //mandatory blank line

       // JSON response
       client.print("{\"type\":\"index\",");
@@ -168,7 +192,10 @@
     }

     if (request == "time") {
-      remoteJSONHeaders();
+      client.println("Status: 200");
+      client.println("Content-type: application/json");
+      client.println("Access-Control-Allow-Origin: *");
+      client.println(); //mandatory blank line

       // JSON response
       client.print("{\"type\":\"time\",");
@@ -213,8 +240,7 @@
 }

 // Common JSON response headers to allow remote API calls
-void remoteJSONHeaders() {
-  YunClient client = server.accept();
+YunClient remoteJSONHeaders(YunClient client) {
   client.println("Status: 200");
   client.println("Content-type: application/json");
   client.println("Access-Control-Allow-Origin: *");


Update sketch_aug08a.ino

Update sketch_aug08a.ino

--- plane/TRANSMITTER/sketch_aug08a/sketch_aug08a.ino
+++ plane/TRANSMITTER/sketch_aug08a/sketch_aug08a.ino
@@ -1,26 +1,42 @@
-#include <SPI.h>
-#include <nRF24L01.h>
-#include <RF24.h>
-RF24 radio(7, 8); // CNS, CE
-const byte addresses[][6] = {"00001", "00002", "00003"};
-void setup() {
-  radio.begin();
-  radio.openWritingPipe(addresses[1]); // 00001
-  radio.openWritingPipe(addresses[2]); // 00002
-  radio.openWritingPipe(addresses[3]); // 00003
-  radio.setPALevel(RF24_PA_MIN);
-}
-void loop() {
-  delay(5);
-  radio.stopListening();
-  int potValue = analogRead(A0);
-  int angleValue = map(potValue, 0, 1023, 0, 180);
-  radio.write(&angleValue, sizeof(angleValue));
-     int potValue1 = analogRead(A1);
-     int angleValue1 = map(potValue1, 0, 1023, 0, 180);
-     radio.write(&angleValue1, sizeof(angleValue1));
-         int potValue2 = analogRead(A2);
-         int angleValue2 = map(potValue2, 0, 1023, 0, 180);
-         radio.write(&angleValue2, sizeof(angleValue2));
-  delay(5);
+/*
+* Arduino Wireless Communication Tutorial
+*     Example 2 - Transmitter Code
+*
+* by Dejan Nedelkovski, www.HowToMechatronics.com
+*
+* Library: TMRh20/RF24, https://github.com/tmrh20/RF24/
+*/
+#include <SPI.h>
+#include <nRF24L01.h>
+#include <RF24.h>
+#define led 12
+RF24 radio(7, 8); // CNS, CE
+const byte addresses[][6] = {"00001", "00002"};
+boolean buttonState = 0;
+void setup() {
+  pinMode(12, OUTPUT);
+  radio.begin();
+  radio.openWritingPipe(addresses[1]); // 00001
+  radio.openReadingPipe(1, addresses[0]); // 00002
+  radio.setPALevel(RF24_PA_MIN);
 }
+void loop() {
+  delay(5);
+  radio.stopListening();
+  int potValue = analogRead(A0);
+  int angleValue = map(potValue, 0, 1023, 0, 180);
+  radio.write(&angleValue, sizeof(angleValue));
+      int potValue1 = analogRead(A1);
+      int angleValue1 = map(potValue1, 0, 1023, 0, 180);
+      radio.write(&angleValue1, sizeof(angleValue1));
+  delay(5);
+  radio.startListening();
+  while (!radio.available());
+  radio.read(&buttonState, sizeof(buttonState));
+  if (buttonState == HIGH) {
+    digitalWrite(led, HIGH);
+  }
+  else {
+    digitalWrite(led, LOW);
+  }
+}


Major improvement in decoding logic, getting logic state for the data before setting up for the next bit, rather than processing it after. Much more direct and appropriate.  It did work before but interfered with the counting of bytes accurately at the end of packets.

--- DebugManchester.ino
+++ DebugManchester.ino
@@ -4,7 +4,11 @@
  This example code is in the public domain.
  Use at your own risk, I will take no responsibility for any loss whatsoever its deployment.
  Visit https://github.com/robwlakes/ArduinoWeatherOS for the latest version and
- documentation. Filename: DebugManchester.ino
+ documentation. Filename: DebugManchester.ino ReadMe: DebugMan.md
+
+ NB: Choosing the wrong polarity will still provide "data", but will be incorrect
+ even thought the two delays are working properly!!!
+ Remember to check both Polarity settings for sensible data.

  DebugVersion_09, 28tyh July 2014

@@ -15,20 +19,21 @@
 int ledPin          = 13;  //The number of the onboard LED pin

 // Variables for Manchester Receiver Logic:
-word    sDelay     = 250;  //Small Delay about 1/4 of bit duration  try like 250 to 500
-word    lDelay     = 500;  //Long Delay about 1/2 of bit duration  try like 500 to 1000, 1/4 + 1/2 = 3/4
+word    sDelay     = 240;  //Small Delay about 1/4 of bit duration try like 220 to 480
+word    lDelay     = 480;  //Long Delay about 1/2 of bit duration  try like 440 to 880, 1/4 + 1/2 = 3/4
 byte    polarity   = 1;    //0 for lo->hi==1 or 1 for hi->lo==1 for Polarity, sets tempBit at start
-byte    tempBit    = 1;    //Reflects the required transition polarity
+byte    tempBit       ;    //Reflects the required transition polarity
+byte    bitState      ;    //State of the RxPin 3/4 way through Bit Waveform
 byte    discards   = 0;    //how many leading "bits" need to be dumped, usually just a zero if anything eg discards=1
 boolean firstZero  = false;//has it processed the first zero yet?  This a "sync" bit.
 boolean noErrors   = true; //flags if signal does not follow Manchester conventions
 //variables for Header detection
-byte    headerBits = 15;   //The number of ones expected to make a valid header
+byte    headerBits = 10;   //The number of ones expected to make a valid header
 byte    headerHits = 0;    //Counts the number of "1"s to determine a header
 //Variables for Byte storage
 byte    dataByte   = 0;    //Accumulates the bit information
 byte    nosBits    = 0;    //Counts to 8 bits within a dataByte
-byte    maxBytes   = 9;    //Set the bytes collected after each header. NB if set too high, any end noise will cause an error
+byte    maxBytes   = 6;    //Set the bytes collected after each header. NB if set too high, any end noise will cause an error
 byte    nosBytes   = 0;    //Counter stays within 0 -> maxBytes
 //Variables for multiple packets
 byte    bank       = 0;    //Points to the array of 0 to 3 banks of results from up to 4 last data downloads
@@ -56,7 +61,7 @@
   Serial.begin(115200);//make it fast so it dumps quick!
   pinMode(RxPin, INPUT);
   pinMode(ledPin, OUTPUT);
-  Serial.println();
+  Serial.println("Debug Manchester Version GIT-Hub V01");
   lDelay=2*sDelay;//just to make sure the 1:2 ratio is established. They can have some other ratio if required
   Serial.print("Using a delay of 1/4 bitWaveform ");// +-15% and they still seem to work ok, pretty tolerant!
   Serial.print(sDelay,DEC);
@@ -86,7 +91,7 @@

 // Main routines, find header, then sync in with it, get a packet, and decode data in it, plus report any errors.
 void loop(){
-  tempBit=polarity; //these begin the same for a packet
+  tempBit=polarity^1; //these begin as opposites for each packet
   noErrors=true;
   firstZero=false;
   headerHits=0;
@@ -103,16 +108,18 @@
       noErrors=false;//something has gone wrong, polarity has changed too early, ie always an error
     }//exit and retry
     else{
+      //now grab the bitState before setting up for next bit & correct for polarity
+      bitState = tempBit ^ polarity;//Polarity=1, invert OR Polarity=0, ignore
+      //Now work on what the next bit waveform is going to be
       delayMicroseconds(lDelay);
       //now 1 quarter into the next bit pattern,
-      if(digitalRead(RxPin)==tempBit){ //if RxPin has not swapped, then bitWaveform is swapping
+      if(digitalRead(RxPin)==tempBit){ //if RxPin has NOT swapped, then next data bit value IS swapping
         //If the header is done, then it means data change is occuring ie 1->0, or 0->1
-        //data transition detection must swap, so it loops for the opposite transitions
+        //data transition detection must swap, so it loops for the opposite transition in the next bit waveform
         tempBit = tempBit^1;
-      }//end of detecting no transition at end of bit waveform, ie end of previous bit waveform same as start of next bitwaveform
-
-      //Now process the tempBit state and make data definite 0 or 1's, allow possibility of Pos or Neg Polarity
-      byte bitState = tempBit ^ polarity;//if polarity=1, invert the tempBit or if polarity=0, leave it alone.
+      }//end of detecting no transition at end of bit waveform
+
+      //Now process the tempBit state and interept data as definite 0 or 1's, (Polarity corrected by now)
       if(bitState==1){ //1 data could be header or packet
         if(!firstZero){
           headerHits++;
@@ -135,6 +142,7 @@
           //we have our header, chewed up any excess and here is a zero
           if ((!firstZero)&&(headerHits>=headerBits)){ //if first zero, it has not been found previously
             firstZero=true;
+            //Serial.print("!");
           }//end of finding first zero
           add(bitState);
         }//end of dealing with a zero
@@ -204,18 +212,3 @@

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-


Both conveyors are running

Both conveyors are running

--- hardware/scanner-sorter/led_and_solenoid_control/led_and_solenoid_control.ino
+++ hardware/scanner-sorter/led_and_solenoid_control/led_and_solenoid_control.ino
@@ -100,10 +100,10 @@
     if (input==103) {
       digitalWrite(TOP_CONVEYOR_PIN, HIGH);
     }
-    if (input==102) {
+    if (input==104) {
       digitalWrite(BOTTOM_CONVEYOR_PIN, LOW);
     }
-    if (input==103) {
+    if (input==105) {
       digitalWrite(BOTTOM_CONVEYOR_PIN, HIGH);
     }
     if (Serial.read() == '\n') {};


fixed small formating

fixed small formating

--- examples/DebugMenu_Simple/DebugMenu_Simple.ino
+++ examples/DebugMenu_Simple/DebugMenu_Simple.ino
@@ -319,7 +319,7 @@

         myDebugMenu.set_user_EOC_char(';');
         myDebugMenu.set_callback(handleMenu_Main);
-        myDebugMenu.begin(true);
+        myDebugMenu.begin();

     //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     // go


Updated Beta1.37

Updated Beta1.37

Updated Beta1.37

--- examples/EasyWebSocket137/EasyWebSocket137.ino
+++ examples/EasyWebSocket137/EasyWebSocket137.ino
@@ -111,7 +111,7 @@
   String str;

   if(ret_str != "_close"){
-    if(millis()-CountTime > 10){//Data transmission from WROOM (ESP8266) every 500ms
+    if(millis()-CountTime > 500){//Data transmission from WROOM (ESP8266) every 500ms
       if(cnt > 3){
         cnt = 0;
       }


No phy mode for ESP32

No phy mode for ESP32

--- wled00/wled05_init.ino
+++ wled00/wled05_init.ino
@@ -152,7 +152,9 @@
 void initConnection()
 {
   WiFi.disconnect(); //close old connections
+  #ifdef ESP8266
   WiFi.setPhyMode(WIFI_PHY_MODE_11N);
+  #endif

   if (staticIP[0] != 0 && staticGateway[0] != 0)
   {


Motor testing with line sensors

Motor testing with line sensors

--- Kirbi/testing/gucci_motor_testing/gucci_motor_testing.ino
+++ Kirbi/testing/gucci_motor_testing/gucci_motor_testing.ino
@@ -7,8 +7,14 @@

 int counter = 0;

+bool go = true;
+
 void encoderISR() {
   counter++;
+}
+
+void stop_motors() {
+  go = false;
 }

 void setup() {
@@ -16,31 +22,103 @@
   ESC_R_SERIAL.begin(115200);
   ESC_R_SERIAL.setRX(7);
   ESC_R_SERIAL.setTX(8);
+  ESC_L_SERIAL.begin(115200);
+  ESC_L_SERIAL.setRX(27);
+  ESC_L_SERIAL.setTX(26);
   pinMode(A19, INPUT);
   attachInterrupt(A19, encoderISR, RISING);
+  pinMode(17, INPUT);
+  pinMode(A22, OUTPUT);
+  analogWrite(A22, 192);
+  pinMode(18, INPUT);
+  pinMode(19, INPUT);
+  attachInterrupt(18, stop_motors, FALLING);
+  attachInterrupt(19, stop_motors, FALLING);
 }

 void loop() {
-  uint8_t bytes[3];
-  bytes[0] = ESC_R_ADDRESS;
-  bytes[1] = 0; //0 is drive forward
-  bytes[2] = 63; //drive motor at half speed
-  uint32_t crc = 0;
-  for(int i = 0; i < 3; i++) {
-    crc = crc ^ (bytes[i] << 8);
-    for (int j = 0; j < 8; j++) {
-      if (crc & 0x8000) {
-        crc = (crc << 1) ^ 0x1021;
-      } else {
-        crc = crc << 1;
+  Serial.println(digitalRead(17));
+  if (digitalRead(17)&&go) {
+    Serial.println("go");
+    uint8_t bytes[3];
+    bytes[0] = ESC_R_ADDRESS;
+    bytes[1] = 1; //0 is drive forward
+    bytes[2] = 40; //drive motor at half speed
+    uint32_t crc = 0;
+    for(int i = 0; i < 3; i++) {
+      crc = crc ^ (bytes[i] << 8);
+      for (int j = 0; j < 8; j++) {
+        if (crc & 0x8000) {
+          crc = (crc << 1) ^ 0x1021;
+        } else {
+          crc = crc << 1;
+        }
       }
     }
+    ESC_R_SERIAL.write(bytes[0]);
+    ESC_R_SERIAL.write(bytes[1]);
+    ESC_R_SERIAL.write(bytes[2]);
+    ESC_R_SERIAL.write(((crc >> 8) & 0xFF));
+    ESC_R_SERIAL.write((crc & 0xFF));
+    bytes[0] = ESC_L_ADDRESS;
+    bytes[1] = 0; //0 is drive forward
+    bytes[2] = 40; //drive motor at half speed
+    crc = 0;
+    for(int i = 0; i < 3; i++) {
+      crc = crc ^ (bytes[i] << 8);
+      for (int j = 0; j < 8; j++) {
+        if (crc & 0x8000) {
+          crc = (crc << 1) ^ 0x1021;
+        } else {
+          crc = crc << 1;
+        }
+      }
+    }
+    ESC_L_SERIAL.write(bytes[0]);
+    ESC_L_SERIAL.write(bytes[1]);
+    ESC_L_SERIAL.write(bytes[2]);
+    ESC_L_SERIAL.write(((crc >> 8) & 0xFF));
+    ESC_L_SERIAL.write((crc & 0xFF));
+  } else {
+    Serial.println("stop");
+    uint8_t bytes[3];
+    bytes[0] = ESC_R_ADDRESS;
+    bytes[1] = 0; //0 is drive forward
+    bytes[2] = 0; //drive motor at half speed
+    uint32_t crc = 0;
+    for(int i = 0; i < 3; i++) {
+      crc = crc ^ (bytes[i] << 8);
+      for (int j = 0; j < 8; j++) {
+        if (crc & 0x8000) {
+          crc = (crc << 1) ^ 0x1021;
+        } else {
+          crc = crc << 1;
+        }
+      }
+    }
+    ESC_R_SERIAL.write(bytes[0]);
+    ESC_R_SERIAL.write(bytes[1]);
+    ESC_R_SERIAL.write(bytes[2]);
+    ESC_R_SERIAL.write(((crc >> 8) & 0xFF));
+    ESC_R_SERIAL.write((crc & 0xFF));
+    bytes[0] = ESC_L_ADDRESS;
+    bytes[1] = 0; //0 is drive forward
+    bytes[2] = 0; //drive motor at half speed
+    crc = 0;
+    for(int i = 0; i < 3; i++) {
+      crc = crc ^ (bytes[i] << 8);
+      for (int j = 0; j < 8; j++) {
+        if (crc & 0x8000) {
+          crc = (crc << 1) ^ 0x1021;
+        } else {
+          crc = crc << 1;
+        }
+      }
+    }
+    ESC_L_SERIAL.write(bytes[0]);
+    ESC_L_SERIAL.write(bytes[1]);
+    ESC_L_SERIAL.write(bytes[2]);
+    ESC_L_SERIAL.write(((crc >> 8) & 0xFF));
+    ESC_L_SERIAL.write((crc & 0xFF));
   }
-  ESC_R_SERIAL.write(bytes[0]);
-  ESC_R_SERIAL.write(bytes[1]);
-  ESC_R_SERIAL.write(bytes[2]);
-  ESC_R_SERIAL.write(((crc >> 8) & 0xFF));
-  ESC_R_SERIAL.write((crc & 0xFF));
-  Serial.println(counter);
-  delay(100);
 }


Finished available actions, still needs testing.

--- RoverMain/RoverMain.ino
+++ RoverMain/RoverMain.ino
@@ -413,22 +413,46 @@
 			break;
 		case 12: // Turn left and drive UNTESTED
 			wake();
-			// ACTION
+			leftInPlace(90);
+			allForward(100);
+			delay(1000);
 			sleep();
 			break;
 		case 13: // Turn right and drive UNTESTED
 			wake();
-			// ACTION
-			sleep();
-			break;
-		case 14: // Small spins back and forth UNTESTED
-			wake();
-			// ACTION
+			rightInPlace(90);
+			allForward(100);
+			delay(1000);
+			sleep();
+			break;
+		case 14: // Wiggle in place UNTESTED
+			wake();
+			leftInPlace(30);
+			rightInPlace(30);
+			leftInPlace(30);
+			rightInPlace(30);
+			leftInPlace(30);
+			rightInPlace(30);
+			leftInPlace(30);
+			rightInPlace(30);
+			leftInPlace(30);
+			rightInPlace(30);
+			leftInPlace(30);
+			rightInPlace(30);
 			sleep();
 			break;
 		case 15: // Traverse a spiral UNTESTED
 			wake();
-			// ACTION
+			ccwCircle(100);
+			delay(1000); // PROBABLY NEED TO CHANGE DELAY
+			ccwCircle(80);
+			delay(800); // PROBABLY NEED TO CHANGE DELAY
+			ccwCircle(60);
+			delay(600); // PROBABLY NEED TO CHANGE DELAY
+			ccwCircle(40);
+			delay(400); // PROBABLY NEED TO CHANGE DELAY
+			ccwCircle(20);
+			delay(200); // PROBABLY NEED TO CHANGE DELAY
 			sleep();
 			break;
 		default: // Do nothing


icon update

icon update


init servo at vertical position

init servo at vertical position

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

 void loop() {
   while (Serial.available() > 0) {
   int degree = Serial.parseInt();
-    if (Serial.read() == '\n') {
+    if (Serial.read() == '\n') {
+        Serial.print("Prepare turning servo ");
         mainServo.write(degree);
         Serial.print("Turn servo ");
 //        analogWrite(ledPin, 255);


Adding Disco Mode - Likely needs more work

Adding disco mode - Pi sends disco mode and Neopixels do strandtest.

--- Arduino/Mimic_LED_Controller/Mimic_LED_Controller.ino
+++ Arduino/Mimic_LED_Controller/Mimic_LED_Controller.ino
@@ -27,6 +27,7 @@
 double V4A = 0.00;
 double V4B = 0.00;
 String module = "unset module";
+boolean Disco = False;

 void setup()
 {
@@ -115,7 +116,6 @@
     module_strip.show();
   }

-
   if(V2A < 151.5)
   {
     strip.setPixelColor(0, strip.Color(255,0,0));
@@ -239,6 +239,11 @@
     strip.setPixelColor(23, strip.Color(0,0,255));
     strip.show();
   }
+  if(Disco)
+  {
+    theaterChaseRainbow_IEA(50);
+  }
+  Disco = False;
 }
 void checkSerial()
 {
@@ -263,8 +268,12 @@
   while((str = strtok_r(p," ",&p))!=NULL)
   {
     test2 = String(str);
-    delimeter = test2.indexOf('=');
-    if(test2.substring(0,delimeter)=="PSARJ")
+    delimeter = test2.indexOf('=');
+    if(test2.substring(0,delimeter)=="Disco")
+    {
+      Disco = True;
+    }
+    else if(test2.substring(0,delimeter)=="PSARJ")
     {
       PSARJ = (test2.substring(delimeter+1)).toFloat();
     }
@@ -367,3 +376,65 @@
     delay(wait);
   }
 }
+void theaterChaseRainbow_Module(uint8_t wait) {
+  for (int j=0; j < 256; j++) {     // cycle all 256 colors in the wheel
+    for (int q=0; q < 3; q++) {
+      for (uint16_t i=0; i < module_strip.numPixels(); i=i+3) {
+        module_strip.setPixelColor(i+q, Wheel_Module( (i+j) % 255));    //turn every third pixel on
+      }
+      module_strip.show();
+
+      delay(wait);
+
+      for (uint16_t i=0; i < module_strip.numPixels(); i=i+3) {
+        module_strip.setPixelColor(i+q, 0);        //turn every third pixel off
+      }
+    }
+  }
+}
+
+// Input a value 0 to 255 to get a color value.
+// The colours are a transition r - g - b - back to r.
+uint32_t Wheel_Module(byte WheelPos) {
+  WheelPos = 255 - WheelPos;
+  if(WheelPos < 85) {
+    return module_strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
+  }
+  if(WheelPos < 170) {
+    WheelPos -= 85;
+    return module_strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
+  }
+  WheelPos -= 170;
+  return module_strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
+}
+void theaterChaseRainbow_IEA(uint8_t wait) {
+  for (int j=0; j < 256; j++) {     // cycle all 256 colors in the wheel
+    for (int q=0; q < 3; q++) {
+      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
+        strip.setPixelColor(i+q, Wheel( (i+j) % 255));    //turn every third pixel on
+      }
+      strip.show();
+
+      delay(wait);
+
+      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
+        strip.setPixelColor(i+q, 0);        //turn every third pixel off
+      }
+    }
+  }
+}
+
+// Input a value 0 to 255 to get a color value.
+// The colours are a transition r - g - b - back to r.
+uint32_t Wheel_IEA(byte WheelPos) {
+  WheelPos = 255 - WheelPos;
+  if(WheelPos < 85) {
+    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
+  }
+  if(WheelPos < 170) {
+    WheelPos -= 85;
+    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
+  }
+  WheelPos -= 170;
+  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
+}


forgot to put value argument

forgot to put value argument

--- sketch_01_random_graph/sketch_01_random_graph.ino
+++ sketch_01_random_graph/sketch_01_random_graph.ino
@@ -64,10 +64,10 @@

 	// try to connect to io.adafruit.com
 	io.connect();
-	for (int i = 1; i <= 3; i++) {
+	for (int i = 1; i <= 20; i++) {
 		if (io.status() < AIO_CONNECTED) {
 			Serial.print(".");
-			delay(i * 500);
+			delay(i * 10);
 		}
 	}
 	Serial.print(' ');
@@ -90,7 +90,7 @@
 	// save a random value to the 'graph' feed on Adafruit IO
 	long value = random(0, 100);
 	Serial.println(value);
-	graph->save(random(0, 100));
+	graph->save(value);

 	// wait one second (1000 milliseconds == 1 second)
 	delay(1000);


Move the servo from pin 10 so it can be used later for SPI

--- tracker/tracker.ino
+++ tracker/tracker.ino
@@ -31,8 +31,8 @@
 #define THRESHOLD_LDR_HORZ 40
 #define MOVE_INTERVAL_MILLIS 60

-#define SERVO_PIN_HORZ 9 // PB1
-#define SERVO_PIN_VIRT 10 // PB2
+#define SERVO_PIN_HORZ 8 // PB1
+#define SERVO_PIN_VIRT 9 // PB0

 #define SERVO_HORZ_MAX 2500
 #define SERVO_HORZ_MIN 700


Led's go fade to red

Led's go fade to red

--- Buddy/Iris_buddy_workFile/Stand.ino
+++ Buddy/Iris_buddy_workFile/Stand.ino
@@ -1,26 +1,31 @@
 // komt van: _stand = Stand (_infrared, _previousStand, _backward);
-int Stand( int infrared, int &previousStand , int &backward )
+int Stand( int infrared, int &previousStand , int &backward, byte &fadeValue)
 {
   byte stand;
   if (infrared = < 40)
   {
     stand = 1;
+    fadeValue= map(infrared,0,40,0,255); //map(value, fromLow, fromHigh, toLow, toHigh)
   }
   if (infrared = < 200)
   {
     stand = 2;
+    fadeValue= map(infrared,40,200,0,255);
   }
   if (infrared = < 500)
   {
     stand = 3;
+    fadeValue= map(infrared,200,500,0,255);
   }
   if (infrared = < 700)
   {
     stand = 4;
+    fadeValue= map(infrared,500,700,0,255);
   }
   if (infrared = < 1000)
   {
     stand = 5;
+    fadeValue= map(infrared,700,1000,0,255);
   }
   else
   {
@@ -29,7 +34,7 @@
   if (stand > previousStand)
   { backward = true;
   }
-  else
+ if (
   {
     backward = false;
   }


calibration values for loadcell slow ADC down to get smoother results write CSV headder

--- software/bladeBench.ino
+++ software/bladeBench.ino
@@ -131,16 +131,16 @@
 	pinMode(BUTTON_PIN, INPUT_PULLUP);

 	adc->setReference(ADC_REF_EXT, ADC_0);
-    adc->setAveraging(1, ADC_0); // set number of averages
+    adc->setAveraging(16, ADC_0); // set number of averages
     adc->setResolution(16, ADC_0); // set bits of resolution
-    adc->setConversionSpeed(ADC_HIGH_SPEED_16BITS, ADC_0); // change the conversion speed
-    adc->setSamplingSpeed(ADC_HIGH_SPEED_16BITS, ADC_0); // change the sampling speed
+    adc->setConversionSpeed(ADC_MED_SPEED, ADC_0); // change the conversion speed
+    adc->setSamplingSpeed(ADC_MED_SPEED  , ADC_0); // change the sampling speed

 	adc->setReference(ADC_REF_EXT, ADC_1);
-    adc->setAveraging(1, ADC_1); // set number of averages
+    adc->setAveraging(16, ADC_1); // set number of averages
     adc->setResolution(16, ADC_1); // set bits of resolution
-    adc->setConversionSpeed(ADC_HIGH_SPEED_16BITS, ADC_1); // change the conversion speed
-    adc->setSamplingSpeed(ADC_HIGH_SPEED_16BITS, ADC_1); // change the sampling speed
+    adc->setConversionSpeed(ADC_MED_SPEED, ADC_1); // change the conversion speed
+    adc->setSamplingSpeed(ADC_MED_SPEED  , ADC_1); // change the sampling speed

     adc->enableCompare(1.0/2.5*adc->getMaxValue(ADC_0), 0, ADC_0); // measurement will be ready if value < 1.0V
     adc->enableCompare(1.0/2.5*adc->getMaxValue(ADC_1), 0, ADC_1); // measurement will be ready if value < 1.0V
@@ -179,10 +179,10 @@
 	commandBuffer[0].value = 1100;
 	commandBuffer[1].mode = MODE_RAMP;
 	commandBuffer[1].time = 4000;
-	commandBuffer[1].value = 1500;
+	commandBuffer[1].value = 2000;
 	commandBuffer[2].mode = MODE_HOLD;
 	commandBuffer[2].time = 2000;
-	commandBuffer[2].value = 1500;
+	commandBuffer[2].value = 2000;
 	commandBuffer[3].mode = MODE_HOLD;
 	commandBuffer[3].time = 1000;
 	commandBuffer[3].value = 1100;
@@ -200,13 +200,13 @@
 	commandBuffer[7].value = 1100;
 	commandBuffer[8].mode = MODE_HOLD;
 	commandBuffer[8].time = 1000;
-	commandBuffer[8].value = 1500;
+	commandBuffer[8].value = 1750;
 	commandBuffer[9].mode = MODE_HOLD;
 	commandBuffer[9].time = 1000;
 	commandBuffer[9].value = 1100;
 	commandBuffer[10].mode = MODE_HOLD;
 	commandBuffer[10].time = 1000;
-	commandBuffer[10].value = 1500;
+	commandBuffer[10].value = 2000;
 	commandBuffer[11].mode = MODE_HOLD;
 	commandBuffer[11].time = 1000;
 	commandBuffer[11].value = 1100;
@@ -265,7 +265,11 @@

 	//format the CSV line
 	sprintf(str, "%lu, %i, %.3f, %.3f, %.3f, %.3f, %.2f\n", time, commandValue, a1, a2, a3, a4, scaleValue);
-
+	writeToBuffer(str);
+
+}
+
+void writeToBuffer(char* str){
 	//write the CSV line to the block buffer
 	size_t thisLength;
 	size_t bufferLength;
@@ -296,6 +300,7 @@
 	}
 }

+
 unsigned int nextBuffer(unsigned int index){
 	// return the next index for the ring buffer
 	index++;
@@ -389,9 +394,12 @@
 	Serial.println("logging...");

 	buildTest();
+
+	writeToBuffer("time, motor, t1, t2, volt, amp, thrust\n");
+
 	// start the log sampling ISR
 	logSampler.priority(200); // set lowish priority.  We want to let regular fast ISRs (like servo timing) to be able to interrupt
-	logSampler.begin(log, 10000); // start logger, 1000 micros = 1khz, 10000micros = 100hz
+	logSampler.begin(log, 5000); // start logger, 1000 micros = 1khz, 10000micros = 100hz
 	runCurrentCommand();

 	bool running = true;
@@ -547,7 +555,7 @@

 void setupLoadCell() {
 	// TODO: calibration
-	scale.set_scale(2280.f);          // this value is obtained by calibrating the scale with known weights;
+	scale.set_scale(392.9f);          // this value is obtained by calibrating the scale with known weights;
 	scale.tare(8);				        // reset the scale to 0, 8 samples average
 }

@@ -560,6 +568,6 @@
 void updateScaleValue() {
 	// update the global measurement value, but only if the scale is ready to be read
 	if (scale.is_ready()){
-		scaleValue = scale.get_value();
-	}
-}
+		scaleValue = scale.get_units();
+	}
+}


Now uses constant defining the number of buzzers. This should make the system more flexible for porting to a Mega (with up to 5 buzzers). Also now reads music data for all the buzzers, if there is any sent by Python companion.

--- ArduMusic/ArduMusic.ino
+++ ArduMusic/ArduMusic.ino
@@ -1,32 +1,33 @@
 #include <Tone.h>
 #include "Notes.cpp"

-#define MAX_MUSIC_LEN 9
+#define MAX_MUSIC_LEN 400
+#define NUMBER_OF_BUZZERS 2

 // Create two tone controllers
 Tone buzzer[2];

 // Holds the time when the buzzers should play to
-unsigned long buzzer_target[2] = { 0, 0 };
+unsigned long buzzer_target[NUMBER_OF_BUZZERS];

 // The "cursor" for each of the buzzers
-unsigned int music_pos[2] = { 0, 0 };
+unsigned int music_pos[NUMBER_OF_BUZZERS];
 // Holds the length of the music
-unsigned int music_length[2] = { 0, 0 };
+unsigned int music_length[NUMBER_OF_BUZZERS];

 // Defines the music
-Note Music[2][MAX_MUSIC_LEN];
+Note Music[NUMBER_OF_BUZZERS][MAX_MUSIC_LEN];

 void setup()
 {
-  // Here we initiallize our three piezo buzzers
-  buzzer[0].begin(9);
-  buzzer[1].begin(10);
+  // Here we initiallize our piezo buzzers, on pins 8+
+  for (unsigned int i = 0; i < NUMBER_OF_BUZZERS; i++)
+    buzzer[i].begin(8+i);

   // Creates a Serial connection
   Serial.begin(9600);
@@ -43,7 +44,7 @@

   // Iterate through both buzzers
-  for (unsigned int i = 0; i < 2; i++)
+  for (unsigned int i = 0; i < NUMBER_OF_BUZZERS; i++)
   {

     // Check if it's time for the buzzer to stop
@@ -84,22 +85,28 @@
     {
       // Once the opcode is verified, send data about the arduino
       Serial.println(MAX_MUSIC_LEN);
-
-      // Immediately following the opening OPcode should be a short detailing
-      // how many notes there are for the first buzzer
-      Serial.readBytes(dat, 2);
-
-      // Get the length of the music and buffer that many x2 bytes (one byte
-      // for pitch, one for duration) into the music array
-      music_length[0] = *(unsigned short*)&dat[0];
-      Serial.readBytes((byte*)&Music[0][0], music_length[0]*2);
+      Serial.println(NUMBER_OF_BUZZERS);

-      // After loading all the music, reset the buzzers and internal cursors
-      buzzer_target[0]  = 0;
-      buzzer_target[1]  = 0;
-      music_pos[0]      = 0;
-      music_pos[1]      = 0;
+      // Receive data for both buzzers, one after the other.
+      // If only data for one buzzer is given, timeout will occur
+      for (unsigned int i = 0; i < NUMBER_OF_BUZZERS; i++)
+      {
+        // Reset the temporary datafields
+        dat[0] = 0, dat[1] = 0;
+
+        // First two bytes details how many notes will be in the music
+        // for this buzzer
+        Serial.readBytes(dat, 2);
+        music_length[i] = *(unsigned short*)&dat[0];
+
+        // Read the follow data into the music buffer for this buzzer
+        Serial.readBytes((byte*)&Music[i][0], music_length[i]*2);
+
+        // After loading all the music, reset the buzzers and internal cursors
+        buzzer_target[i]  = 0;
+        music_pos[i]      = 0;
+      }
     }

   }


working on issue #10

working on issue #10

parameter Min Position Limit and Max Position Limit configured by CAN
needs further improvement

--- arduino_control/arduino_control.ino
+++ arduino_control/arduino_control.ino
@@ -71,13 +71,25 @@
 unsigned char pdo_actual_current_4[8] = {0x22, 0x00, 0x18, 0x02, 0x01, 0, 0, 0};
 unsigned char pdo_actual_current_5[8] = {0x22, 0x00, 0x1A, 0x00, 0x01, 0, 0, 0};

-// Objects Writing
+// *****************
+// Object Writing
+// *****************
+
+// Parameters
 unsigned char set_max_following_error[8] = {0x22, 0x65, 0x60, 0, 0xD0, 7, 0, 0};
 unsigned char set_max_acceleration[8] = {0x22, 0xC5, 0x60, 0, 0x88, 0x13, 0, 0};
 unsigned char set_max_profile_velocity[8] = {0x22, 0x7F, 0x60, 0, 0xD0, 7, 0, 0};
+unsigned char set_min_position_limit[8] = {0x22, 0x7D, 0x60, 0x01, 0x20, 0x6C, 0xFB, 0xFF}; // -300000qc = 0xFFFB6C20
+unsigned char set_max_position_limit[8] = {0x22, 0x7D, 0x60, 0x02, 0xE0, 0x93, 0x04, 0}; // 300000qc = 0x0493E0
+
+// Commanding
 unsigned char setpoint_position[8] = {0x22, 0x62, 0x20, 0, 0, 0, 0, 0};

-// Objects Reading
+// *****************
+// Object Reading
+// *****************
+
+// Actual Values
 unsigned char get_actual_position[8] = {0x40, 0x64, 0x60, 0, 0, 0, 0, 0};
 unsigned char get_actual_velocity[8] = {0x40, 0x6C, 0x60, 0, 0, 0, 0, 0};
 unsigned char get_actual_current[8] = {0x40, 0x78, 0x60, 0, 0, 0, 0, 0};
@@ -148,6 +160,12 @@
   CAN.sendMsgBuf(0x601, 0, 8, set_max_profile_velocity);
   Serial.println("Max Profile Velocity set as 2000rpm");
   delay(10);
+  CAN.sendMsgBuf(0x601, 0, 8, set_min_position_limit);
+  Serial.println("Min Position Limit defined as -300000qc");
+  delay(10);
+  CAN.sendMsgBuf(0x601, 0, 8, set_max_position_limit);
+  Serial.println("Min Position Limit defined as 300000qc");
+  delay(10);
   State = Pre_Operational;
 }

@@ -318,6 +336,20 @@
       // ID 321 message has information sent by the amplification board
       // Messages coming from the amp_board has most significative bits coming first
       case 0x321:
+        // buf[1] = buf[1] - 0x98;
+        // buf[2] = buf[2] - 0x96;
+        // buf[3] = buf[3] - 0x80;
+        // Serial.println("-----------------------------");
+        // Serial.print("AMP ");
+        // Serial.println(canId, HEX);
+
+        // for(int i = 0; i<len; i++)    // print the data
+        // {
+        //     Serial.print(buf[i], HEX);
+        //     Serial.print("\t");
+        // }
+        // Serial.println();
+
         // encoderDataRead();
         encoder_data = buf[4];
         encoder_data <<= 8; // bitshift equals times 2^8
@@ -329,6 +361,8 @@
         loadcell_data = loadcell_data | buf[2];
         loadcell_data <<= 8;
         loadcell_data = loadcell_data | buf[3];
+
+        // loadcell_data = loadcell_data - 10000000;

         positionSetpoint(encoder_data);


debounce update

debounce update

--- _06-power-meter/_06-power-meter.ino
+++ _06-power-meter/_06-power-meter.ino
@@ -167,7 +167,7 @@
   Serial.println(oldrevMills);
 */

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

@@ -192,7 +192,7 @@
     payload += ( revMills + oldrevMills ) / 2 ;
     payload += "}";

-  if (( IRSTATUS != OLDIRSTATUS ) && ( revMills > 0 )) {
+  if (( IRSTATUS != OLDIRSTATUS ) && ( revMills > 600 )) {
     sendmqttMsg(payload);
     sentMills = millis();
     OLDIRSTATUS = IRSTATUS ;
@@ -201,12 +201,12 @@
   }

-  if (((millis() - sentMills) > REPORT_INTERVAL ) && ( revMills > 0 )) {
+  if (((millis() - sentMills) > REPORT_INTERVAL ) && ( revMills > 600 )) {
     sendmqttMsg(payload);
     sentMills = millis();
   }

-  if ( revMills > 0 ) {
+  if ( revMills > 1000 ) {
     delay(int(float(revMills)/10));
   }else {
     delay(100);
@@ -244,14 +244,13 @@

 void count_powermeter()
 {
-  long removebounce ;
   // 600 rev/kWh --> 1 rev 6 sec 1kW
   // max A : 40
   // 220 V * 45A = 9900,
   // 0.6sec -> 10kW
   //

-  if (( millis() - startMills ) < 500 ) {
+  if (( millis() - startMills ) < 600 ) {
     return;
   }


test : keep alive, serial out

test : keep alive, serial out

mqtt keep alive to 5 sec from 15 sec
reconnect to 1 sec from 5sec
serial begin to 115200 from none(74880)

--- _06-power_meter/_06-power_meter.ino
+++ _06-power_meter/_06-power_meter.ino
@@ -13,7 +13,7 @@
 #include "ap_setting.h"
 #endif

-#define DEBUG_PRINT 0
+#define DEBUG_PRINT 1

 //
 EnergyMonitor emon1;                   // Create an instance
@@ -128,7 +128,8 @@

 void setup() {
   if (DEBUG_PRINT) {
-    Serial.begin(74880);
+    //Serial.begin(74880);
+    Serial.begin(115200);
   }
   delay(20);
   if (DEBUG_PRINT) {
@@ -224,7 +225,7 @@
         Serial.print(client.state());
       }
       long now = millis();
-//      if (now - lastReconnectAttempt > 5000) {
+      //      if (now - lastReconnectAttempt > 5000) {
       if (now - lastReconnectAttempt > 1000) {
         lastReconnectAttempt = now;
         if (reconnect()) {
@@ -315,8 +316,8 @@
   }
   */

-  client.loop();
-
+  //client.loop();
+
   if (client.connected()) {
     if (DEBUG_PRINT) {
       Serial.print("Sending payload: ");


Update ESP8266.ino

Update ESP8266.ino

--- ESP8266/ESP8266.ino
+++ ESP8266/ESP8266.ino
@@ -1,97 +1,94 @@
-#include "WiFinder.h"
-#include <FirebaseArduino.h>
-
-#define FIREBASE_HOST "plugar-e4795.firebaseio.com"
-#define FIREBASE_AUTH "lgshhtREzTrtdGzHEV5jyAzmC16SlTg0ndgVYQuk"
-#define LED_PIN 10
-#define BTN_PIN 2
-
-char* WIFIS[][2] = {
-  {"Private", "666conexaoprivate"},
-  {"rapha", "rapha123"},
-  {"livs", "asdf1234"},
-	{"Find", "find@2016"},
-	{"Aja", "0135792468aja"}
-};
-WiFinder wifinder(WIFIS);
-
-volatile bool led_status, alterado = false;
-volatile int fb_delay = 1000, prev_delay = 1000;
-
-StaticJsonBuffer<50> tsoBuffer;
-JsonObject& timeStampObject = tsoBuffer.createObject();
-
-StaticJsonBuffer<250> nodemcuBuffer;
-JsonObject& nodemcuObject = nodemcuBuffer.createObject();
-
-void setup() {
-	Serial.begin(115200);
-  wifinder.setLed(LED_PIN);
-	wifinder.connect();
-	pinMode(BTN_PIN, INPUT_PULLUP);
-	Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
-  Firebase.setString("localIp", wifinder.getLocalIp());
-	attachInterrupt(BTN_PIN, readBtn, FALLING);
-  initJSONs();
-}
-
-void loop() {
-	wifinder.handle();
-	readLEDFirebase();
-	updateFirebase();
-	readDelayFirebase();
-
-	delay(fb_delay);
-}
-
-// Inicializa conteudo statico dos jsons
-void initJSONs(){
-  timeStampObject[".sv"] = "timestamp";
-  nodemcuObject["photoURL"] = "https://cknodemcu.files.wordpress.com/2015/10/nodemcu2.png?w=150";
-  nodemcuObject["displayName"] = "NodeMCU";
-  nodemcuObject["date"] = timeStampObject;
-}
-
-// Lê do firebase: LED
-void readLEDFirebase(){
-	bool cled_status = Firebase.getBool("LED");
-	if(led_status == cled_status) return;
-	led_status = cled_status;
-	Serial.print("LED alterado para: ");
-	Serial.println(led_status);
-	digitalWrite(LED_PIN, led_status);
-}
-
-// Lê do firebase: Delay
-void readDelayFirebase(){
-	fb_delay = Firebase.getInt("delay");
-	if(fb_delay < 1000) fb_delay = 1000;
-	if(fb_delay == prev_delay) return;
-	Serial.print("Delay alterado para: ");
-	Serial.println(fb_delay);
-	prev_delay = fb_delay;
-}
-
-// Atualiza do firebase: LED
-void updateFirebase(){
-	if(!alterado) return;
-  bool ls = !led_status;
-	Firebase.setBool("LED", ls);
-	Serial.print("Definindo LED no firebase: ");
-	Serial.println(!led_status);
-	if (Firebase.failed()) {
-		Serial.print("Erro ao setar LED:");
-		Serial.println(Firebase.error());
-		return;
-	}
-  nodemcuObject["action"] = ls;
-  Firebase.push("users", nodemcuObject);
-	alterado = false;
-	attachInterrupt(BTN_PIN, readBtn, FALLING);
-}
-
-void readBtn(){
-	Serial.println("Alterando LED via interrupt");
-	alterado = true;
-	detachInterrupt(BTN_PIN);
+#include "WiFinder.h"
+#include <FirebaseArduino.h>
+
+#define FIREBASE_HOST "YOUR_FIREBASE_HOST.firebaseio.com"
+#define FIREBASE_AUTH "YOUR_FIREBASE_AUTH"
+#define LED_PIN 10
+#define BTN_PIN 2
+
+char* WIFIS[][2] = {
+  {"Wifi1", "wifi1pass"},
+  {"Wifi2", "wifi2pass"}
+};
+WiFinder wifinder(WIFIS);
+
+volatile bool led_status, alterado = false;
+volatile int fb_delay = 1000, prev_delay = 1000;
+
+StaticJsonBuffer<50> tsoBuffer;
+JsonObject& timeStampObject = tsoBuffer.createObject();
+
+StaticJsonBuffer<250> nodemcuBuffer;
+JsonObject& nodemcuObject = nodemcuBuffer.createObject();
+
+void setup() {
+  Serial.begin(115200);
+  wifinder.setLed(LED_PIN);
+  wifinder.connect();
+  pinMode(BTN_PIN, INPUT_PULLUP);
+  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
+  Firebase.setString("localIp", wifinder.getLocalIp());
+  attachInterrupt(BTN_PIN, readBtn, FALLING);
+  initJSONs();
 }
+
+void loop() {
+  wifinder.handle();
+  readLEDFirebase();
+  updateFirebase();
+  readDelayFirebase();
+
+  delay(fb_delay);
+}
+
+// Inicializa conteudo statico dos jsons
+void initJSONs(){
+  timeStampObject[".sv"] = "timestamp";
+  nodemcuObject["photoURL"] = "https://cknodemcu.files.wordpress.com/2015/10/nodemcu2.png?w=150";
+  nodemcuObject["displayName"] = "NodeMCU";
+  nodemcuObject["date"] = timeStampObject;
+}
+
+// Lê do firebase: LED
+void readLEDFirebase(){
+  bool cled_status = Firebase.getBool("LED");
+  if(led_status == cled_status) return;
+  led_status = cled_status;
+  Serial.print("LED alterado para: ");
+  Serial.println(led_status);
+  digitalWrite(LED_PIN, led_status);
+}
+
+// Lê do firebase: Delay
+void readDelayFirebase(){
+  fb_delay = Firebase.getInt("delay");
+  if(fb_delay < 1000) fb_delay = 1000;
+  if(fb_delay == prev_delay) return;
+  Serial.print("Delay alterado para: ");
+  Serial.println(fb_delay);
+  prev_delay = fb_delay;
+}
+
+// Atualiza do firebase: LED
+void updateFirebase(){
+  if(!alterado) return;
+  bool ls = !led_status;
+  Firebase.setBool("LED", ls);
+  Serial.print("Definindo LED no firebase: ");
+  Serial.println(!led_status);
+  if (Firebase.failed()) {
+    Serial.print("Erro ao setar LED:");
+    Serial.println(Firebase.error());
+    return;
+  }
+  nodemcuObject["action"] = ls;
+  Firebase.push("users", nodemcuObject);
+  alterado = false;
+  attachInterrupt(BTN_PIN, readBtn, FALLING);
+}
+
+void readBtn(){
+  Serial.println("Alterando LED via interrupt");
+  alterado = true;
+  detachInterrupt(BTN_PIN);
+}


Add Cities Test Code

Add Cities Test Code

--- src/SpyCase/SpyCase.ino
+++ src/SpyCase/SpyCase.ino
@@ -14,6 +14,15 @@
 #define RINGPIN 12
 #define PIXELPIN 8
 #define CITIESPIN 13
+
+
+//Cities
+#define LONDON 0
+#define NEWYORK 1
+#define LIMA 2
+#define PERTH 3
+#define TOKYO 4
+#define NAIROBI 5

 /*
  * Globals
@@ -47,7 +56,17 @@
     ring.RainbowCycle(2);

     cities.begin();
-    cities.RainbowCycle(2);
+    cities.Hide(LONDON);
+    cities.Hide(NEWYORK);
+    cities.Hide(LIMA);
+    cities.Hide(PERTH);
+    cities.Hide(TOKYO);
+    cities.Hide(NAIROBI);
+
+    cities.Fade(NeoPatterns::Color(255, 0, 0),NeoPatterns::Color(0,0,0), 5, 100);
+
+    cities.Show(LONDON);
+    cities.Show(PERTH);