General cleanup and simplification

General cleanup and simplification

--- DigitalVFO.ino
+++ DigitalVFO.ino
@@ -21,14 +21,13 @@
 const char *Callsign = "vk4fawr";

 // display constants - below is for ubiquitous small HD44780 16x2 display
-#define NUM_ROWS        2
-#define NUM_COLS        16
+const int NumRows = 2;
+const int NumCols = 16;

 // macro to get number of elements in an array
 #define ALEN(a)    (sizeof(a)/sizeof(a[0]))

-// define one row of blanks
-// FIXME: should be dynamic
+// string holding one entire blank row (allocated in setup())
 char *BlankRow = NULL;

 // define data pins we connect to the LCD
@@ -55,16 +54,16 @@

 // max and min frequency showable
-#define MAX_FREQ        30000000L
-#define MIN_FREQ        1000000L
+const unsigned long MaxFreq = 30000000L;
+const unsigned long MinFreq = 1000000L;

 // size of frequency display in chars (30MHz is maximum frequency)
-#define MAX_FREQ_CHARS  8
+const int NumFreqChars = 8;

 // address in display CGRAM for definable and other characters
-#define SELECT_CHAR     0     // shows 'underlined' decimal digits (dynamic, 0 to 9)
-#define SPACE_CHAR      1     // shows an 'underlined' space character
-#define ALLSET_CHAR     0xff  // the 'all bits set' char in display RAM, used for 'bar' display
+const int SelectChar = 0;     // shows 'underlined' decimal digits (dynamic, 0 to 9)
+const int SpaceChar = 1;      // shows an 'underlined' space character
+const int AllsetChar = 0xff;  // the 'all bits set' char in display RAM, used for 'bar' display

 // define the numeric digits and space with selection underline
 byte sel0[8] = {0xe,0x11,0x13,0x15,0x19,0x11,0xe,0x1f};
@@ -81,7 +80,7 @@

 // array of references to the 11 'selected' characters (0 to 9 plus space)
 byte *sel_digits[] = {sel0, sel1, sel2, sel3, sel4, sel5, sel6, sel7, sel8, sel9, selspace};
-#define SPACE_INDEX   10
+const int SpaceIndex = 10;

 // map select_offset to bump values
 unsigned long offset2bump[] = {1,           // offset = 0
@@ -98,38 +97,47 @@
 LiquidCrystal lcd(lcd_RS, lcd_ENABLE, lcd_D4, lcd_D5, lcd_D6, lcd_D7);

 // define the VFOevents
-#define vfo_None      0
-#define vfo_RLeft     1
-#define vfo_RRight    2
-#define vfo_DnRLeft   3
-#define vfo_DnRRight  4
-#define vfo_Click     5
-#define vfo_HoldClick 6
-#define vfo_DClick    7
+enum Event
+{
+  vfo_None,
+  vfo_RLeft,
+  vfo_RRight,
+  vfo_DnRLeft,
+  vfo_DnRRight,
+  vfo_Click,
+  vfo_HoldClick,
+  vfo_DClick,
+};

 // the "in use" display character, "→"
-#define IN_USE_CHAR   0x7e
+const int InUseChar = 0x7e;

 // default LCD contrast & brightness
 const unsigned int DefaultLcdContrast = 70;
 const unsigned int DefaultLcdBrightness = 150;

 // VFO modes - online or standby
-#define vfo_Standby   0
-#define vfo_Online    1
+enum Mode
+{
+  vfo_Standby,
+  vfo_Online
+};

 // stuff for the calibrate action
 const int MinClockOffset = -32000;
 const int MaxClockOffset = +32000;
 const int MaxOffsetDigits = 5;

+// define the length of the event queue
+const int EventQueueLength = 10;
+

 //##############################################################################
 // The VFO state variables and typedefs
 //##############################################################################

-typedef unsigned int Mode;
-Mode VfoMode;               // VFO mode
+//typedef unsigned int Mode;
+enum Mode VfoMode;          // VFO mode

 typedef unsigned long Frequency;
 Frequency VfoFrequency;     // VFO frequency (Hz)
@@ -154,35 +162,35 @@
 // Abort the program.
 // Tries to tell the world what went wrong, then just loops.
 //     msg  address of error string
-// Only first NUM_ROWS*NUM_COLS chars of message is displayed on LCD.
+// Only first NumRows*NumCols chars of message is displayed on LCD.
 //----------------------------------------

 void abort(const char *msg)
 {
-  char buf[NUM_COLS*NUM_ROWS+1];
+  char buf[NumCols*NumRows+1];
   char *ptr = buf;

   // print error on console (maybe)
   Serial.printf(F("message=%s\nTeensy is paused!\n"), msg);

-  // truncate/pad message to NUM_ROWS * NUM_COLS chars
-  for (int i = 0; i < NUM_COLS*NUM_ROWS; ++i)
+  // truncate/pad message to NumRows * NumCols chars
+  for (int i = 0; i < NumCols*NumRows; ++i)
     *ptr++ = ' ';
   *ptr = '\0';

-  strncpy(buf, msg, NUM_COLS*NUM_ROWS);
-  if (strlen(msg) < NUM_COLS*NUM_ROWS)
+  strncpy(buf, msg, NumCols*NumRows);
+  if (strlen(msg) < NumCols*NumRows)
     strncpy(buf + strlen(msg), "                                ",
-            NUM_COLS*NUM_ROWS - strlen(msg));
+            NumCols*NumRows - strlen(msg));

   // show what we can on the display, forever
   while (1)
   {
     lcd.clear();
-    for (int i = 0; i < NUM_ROWS; ++i)
+    for (int i = 0; i < NumRows; ++i)
     {
       lcd.setCursor(0, i);
-      lcd.print(buf + i*NUM_COLS);
+      lcd.print(buf + i*NumCols);
     }
     delay(2000);

@@ -230,7 +238,7 @@
   lcd.print(ProgramName);
   lcd.print(" ");
   lcd.print(Version);
-  lcd.setCursor(NUM_COLS-strlen(Callsign), 1);
+  lcd.setCursor(NumCols-strlen(Callsign), 1);
   lcd.print(Callsign);
 }

@@ -387,7 +395,7 @@
   // write indexed item on lower row, right-justified
   lcd.setCursor(0, 1);
   lcd.print(BlankRow);
-  lcd.setCursor(NUM_COLS - max_len, 1);
+  lcd.setCursor(NumCols - max_len, 1);
   lcd.print(menu->items[item_num]->title);
 }

@@ -491,9 +499,7 @@
 // Implemented as a circular buffer.
 //##############################################################################

-#define QueueLength 10
-
-VFOEvent event_queue[QueueLength];
+VFOEvent event_queue[EventQueueLength];
 int queue_fore = 0;   // fore pointer into circular buffer
 int queue_aft = 0;    // aft pointer into circular buffer

@@ -507,7 +513,7 @@

   // move fore ptr one slot up, wraparound if necessary
   ++queue_fore;
-  if (queue_fore >= QueueLength)
+  if (queue_fore >= EventQueueLength)
     queue_fore = 0;

   // if queue full, abort
@@ -534,7 +540,7 @@

   // move aft pointer up one slot, wrap if necessary
   ++queue_aft;
-  if (queue_aft  >= QueueLength)
+  if (queue_aft  >= EventQueueLength)
     queue_aft = 0;

   interrupts();
@@ -552,7 +558,7 @@

   // handle case when events wrap around
   if (result < 0)
-    result += QueueLength;
+    result += EventQueueLength;

   interrupts();

@@ -577,7 +583,7 @@

   Serial.printf(F("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"));
   Serial.printf(F("Queue: %s\n"), msg);
-  for (int i = 0; i < QueueLength; ++i)
+  for (int i = 0; i < EventQueueLength; ++i)
   {
     VFOEvent event = event_queue[i];

@@ -616,7 +622,7 @@
   ulong2buff(buf, num_digits, value);

   // create special underlined selection character including selected digit
-  lcd.createChar(SELECT_CHAR, sel_digits[int(buf[index])]);
+  lcd.createChar(SelectChar, sel_digits[int(buf[index])]);

   // we set cursor here because we lose cursor position after lcd.createChar()!?
   // would prefer to set cursor position outside this function, but ไม่เป็นไร.
@@ -634,7 +640,7 @@
     {
       if (index == i)
       {
-        lcd.write(byte(SPACE_CHAR));
+        lcd.write(byte(SpaceChar));
       }
       else
       {
@@ -645,7 +651,7 @@
     {
       if (index == i)
       {
-        lcd.write(byte(SELECT_CHAR));
+        lcd.write(byte(SelectChar));
       }
       else
       {
@@ -685,7 +691,7 @@
   ulong2buff(buf, num_digits, value);

   // create special underlined selection character including selected digit
-  lcd.createChar(SELECT_CHAR, sel_digits[int(buf[index])]);
+  lcd.createChar(SelectChar, sel_digits[int(buf[index])]);

   // we set cursor here because we lose cursor position after lcd.createChar()!?
   // would prefer to set cursor position outside this function, but ไม่เป็นไร.
@@ -706,7 +712,7 @@
     {
       if (index == i)
       {
-        lcd.write(byte(SPACE_CHAR));
+        lcd.write(byte(SpaceChar));
       }
       else
       {
@@ -717,7 +723,7 @@
     {
       if (index == i)
       {
-        lcd.write(byte(SELECT_CHAR));
+        lcd.write(byte(SelectChar));
       }
       else
       {
@@ -735,20 +741,20 @@

 // time when click becomes a "hold click" (milliseconds)
 // the delay is configurable in the UI
-#define MinHoldClickTime        100
-#define MaxHoldClickTime        1000
-#define DefaultHoldClickTime    500
+const int MinHoldClickTime = 100;     // min configurable time
+const int MaxHoldClickTime = 1000;    // max configurable time
+const int DefaultHoldClickTime = 500; // default time

 // time when click becomes a "double click" (milliseconds)
 // the delay is configurable in the UI
-#define MinDClickTime           100
-#define MaxDClickTime           1000
-#define DefaultDClickTime       300
-
+const int MinDClickTime = 100;        // min configurable time
+const int MaxDClickTime = 1000;       // max configurable time
+const int DefaultDClickTime = 300;    // default time
+
+// internal variables
 unsigned int ReHoldClickTime = DefaultHoldClickTime;
 unsigned int ReDClickTime = DefaultDClickTime;

-// internal variables
 bool re_rotation = false;       // true if rotation occurred while knob down
 bool re_down = false;           // true while knob is down
 unsigned long re_down_time = 0; // milliseconds when knob is pressed down
@@ -778,6 +784,7 @@
   attachInterrupt(digitalPinToInterrupt(re_pinPush), pinPush_isr, CHANGE);

   // look at RE button, if DOWN this function returns 'true'
+  // FIXME - Worry about bounce?
   return ! (PIND & 0x10);
 }

@@ -787,7 +794,7 @@

 void pinPush_isr(void)
 {
-  cli();
+  noInterrupts();

   re_down = ! (PIND & 0x10);

@@ -837,7 +844,7 @@
     }
   }

-  sei();
+  interrupts();
 }

 //----------------------------------------
@@ -848,7 +855,7 @@
 {
   byte reading;

-  cli();
+  noInterrupts();

   reading = PIND & 0xC;

@@ -873,7 +880,7 @@
     bFlag = 1;
   }

-  sei();
+  interrupts();
 }

 //----------------------------------------
@@ -884,7 +891,7 @@
 {
   byte reading;

-  cli();
+  noInterrupts();

   reading = PIND & 0xC;

@@ -909,13 +916,18 @@
     aFlag = 1;
   }

-  sei();
+  interrupts();
 }

 //##############################################################################
 // Code to save/restore in EEPROM.
 //##############################################################################
+
+// Define the address in EEPROM of various things.
+// The "NEXT_FREE" value is the address of the next free slot address.
+// Ignore "redefine errors" - silly compiler!
+// The idea is that we are free to rearrange objects below with minimum fuss

 // start storing at address 0
 #define NEXT_FREE   (0)
@@ -1102,17 +1114,17 @@

 void dds_update(Frequency frequency)
 {
-//  int32_t data = frequency * 4294967296.0 / 180.0e6;
-  unsigned long data = frequency * 4294967296 / (6 * (30000000 - VfoClockOffset));
+  // as in datasheet page 12 - modified to include calibration offset
+  unsigned long data = (frequency * 4294967296) / (180000000 - VfoClockOffset);

   Serial.printf(F("dds_update: frequency=%ld, VfoClockOffset=%d, data=%ld\n"),
                 frequency, VfoClockOffset, data);
-
+
+  // start programming the DDS-60
   for (int b = 0; b < 4; ++b, data >>= 8)
   {
     dds_tfr_byte(data & 0xFF);
   }
-
   dds_tfr_byte(0x001);
   dds_pulse_high(DDS_FQ_UD);
 }
@@ -1150,15 +1162,11 @@
   pinMode(DDS_W_CLK, OUTPUT);
   pinMode(DDS_DATA, OUTPUT);

-  // if your board needs it, connect RESET pin and pulse it to reset AD9851
-  // dds_pulse_high(RESET)
-
   // set serial load enable (Datasheet page 15 Fig. 17)
   dds_pulse_high(DDS_W_CLK);
   dds_pulse_high(DDS_FQ_UD);

-  // wait a bit, then go into standby
-  delay(100);
+  // go into standby
   dds_standby();
 }

@@ -1175,10 +1183,10 @@
 void setup(void)
 {
   // initialize the BlankRow global to a blank string length of a display row
-  BlankRow = (char *) malloc(NUM_COLS + 1);     // size of one display row
-  for (int i = 0; i < NUM_COLS; ++i)
+  BlankRow = (char *) malloc(NumCols + 1);     // size of one display row
+  for (int i = 0; i < NumCols; ++i)
     BlankRow[i] = ' ';
-  BlankRow[NUM_COLS] = '\0';
+  BlankRow[NumCols] = '\0';

   // initialize the serial console
   Serial.begin(115200);
@@ -1196,12 +1204,12 @@
   analogWrite(mc_Contrast, LcdContrast);

   // initialize the display
-  lcd.begin(NUM_COLS, NUM_ROWS);      // define display size
+  lcd.begin(NumCols, NumRows);      // define display size
   lcd.clear();
   lcd.noCursor();

   // create underlined space for frequency display
-  lcd.createChar(SPACE_CHAR, sel_digits[SPACE_INDEX]);
+  lcd.createChar(SpaceChar, sel_digits[SpaceIndex]);

   // set up the DDS device
   dds_setup();
@@ -1254,7 +1262,7 @@
   lcd.clear();
   lcd.setCursor(0, 0);
   lcd.print("Vfo:");
-  display_sel_value(VfoFrequency, VfoSelectDigit, MAX_FREQ_CHARS, NUM_COLS - MAX_FREQ_CHARS - 2, 0);
+  display_sel_value(VfoFrequency, VfoSelectDigit, NumFreqChars, NumCols - NumFreqChars - 2, 0);
   lcd.print("Hz");

   lcd.setCursor(0, 1);
@@ -1278,12 +1286,12 @@
   if (VfoFrequency == freq)
   {
     lcd.setCursor(0, 1);
-    lcd.write(IN_USE_CHAR);
+    lcd.write(InUseChar);
   }
   lcd.setCursor(4, 1);
   lcd.write(slot_num + '0');
   lcd.print(":");
-  display_sel_value(freq, -1, MAX_FREQ_CHARS, NUM_COLS - MAX_FREQ_CHARS - 2, 1);
+  display_sel_value(freq, -1, NumFreqChars, NumCols - NumFreqChars - 2, 1);
   lcd.print("Hz");
 }

@@ -1470,7 +1478,7 @@
   SelOffset zero_offset = 0;

   // zero the frequency+selected values
-  VfoFrequency = MIN_FREQ;
+  VfoFrequency = MinFreq;
   VfoSelectDigit = 0;
   VfoClockOffset = 0;
   LcdBrightness = DefaultLcdBrightness;
@@ -1545,7 +1553,7 @@
   lcd.print(BlankRow);
   lcd.setCursor(0, 1);
   for (int i = 0; i < length; ++i)
-    lcd.write(ALLSET_CHAR);
+    lcd.write(AllsetChar);
 }

 //----------------------------------------
@@ -1684,7 +1692,7 @@
   if (msec == def_time)
   {
     lcd.setCursor(0, 1);
-    lcd.write(IN_USE_CHAR);
+    lcd.write(InUseChar);
   }

   lcd.setCursor(8, 1);
@@ -1946,7 +1954,7 @@
     VfoMode = vfo_Online;
   }

-  // update display
+  // clear row 1 and write new mode string
   lcd.setCursor(0, 1);
   lcd.write(BlankRow);
   lcd.setCursor(0, 1);
@@ -1976,7 +1984,7 @@
 struct Menu settings_menu = {"Settings", ALEN(mia_settings), mia_settings};

 //----------------------------------------
-// main menu
+// Main menu
 //----------------------------------------

 struct MenuItem mi_save = {"Save slot", NULL, &saveslot_action};
@@ -1995,9 +2003,11 @@

 void loop(void)
 {
+#ifdef JUNK
   // remember old values, update screen if changed
   Frequency old_freq = VfoFrequency;
   int old_position = VfoSelectDigit;
+#endif

   // handle all events in the queue
   while (event_pending() > 0)
@@ -2010,24 +2020,24 @@
       case vfo_RLeft:
         Serial.printf(F("loop: vfo_RLeft\n"));
         VfoFrequency -= offset2bump[VfoSelectDigit];
-        if (VfoFrequency < MIN_FREQ)
-          VfoFrequency = MIN_FREQ;
-        if (VfoFrequency > MAX_FREQ)
-          VfoFrequency = MAX_FREQ;
+        if (VfoFrequency < MinFreq)
+          VfoFrequency = MinFreq;
+        if (VfoFrequency > MaxFreq)
+          VfoFrequency = MaxFreq;
        break;
       case vfo_RRight:
         Serial.printf(F("loop: vfo_RRight\n"));
         VfoFrequency += offset2bump[VfoSelectDigit];
-        if (VfoFrequency < MIN_FREQ)
-          VfoFrequency = MIN_FREQ;
-        if (VfoFrequency > MAX_FREQ)
-          VfoFrequency = MAX_FREQ;
+        if (VfoFrequency < MinFreq)
+          VfoFrequency = MinFreq;
+        if (VfoFrequency > MaxFreq)
+          VfoFrequency = MaxFreq;
         break;
       case vfo_DnRLeft:
         Serial.printf(F("loop: vfo_DnRLeft\n"));
         VfoSelectDigit += 1;
-        if (VfoSelectDigit >= MAX_FREQ_CHARS)
-          VfoSelectDigit = MAX_FREQ_CHARS - 1;
+        if (VfoSelectDigit >= NumFreqChars)
+          VfoSelectDigit = NumFreqChars - 1;
         break;
       case vfo_DnRRight:
         Serial.printf(F("loop: vfo_DnRRight\n"));
@@ -2053,17 +2063,12 @@
         break;
     }

-    // display frequency if changed, update DDS-60 if online
-    if (old_freq != VfoFrequency || old_position != VfoSelectDigit)
-    {
-      display_sel_value(VfoFrequency, VfoSelectDigit, MAX_FREQ_CHARS, NUM_COLS - MAX_FREQ_CHARS - 2, 0);
-      old_freq = VfoFrequency;
-      old_position = VfoSelectDigit;
-
-      save_to_eeprom();         // worry about frequent writes?
-
-      if (VfoMode == vfo_Online)
-        dds_update(VfoFrequency);
-    }
-  }
-}
+    // update the display, write changes to EEPROM
+    display_sel_value(VfoFrequency, VfoSelectDigit, NumFreqChars, NumCols - NumFreqChars - 2, 0);
+    save_to_eeprom();         // FIXME: worry about frequent writes?
+
+    // if online, update DDS-60
+    if (VfoMode == vfo_Online)
+      dds_update(VfoFrequency);
+  }
+}


Fix include path

Fix include path

--- Programmer.ino
+++ Programmer.ino
@@ -34,7 +34,7 @@
 #include <SPI.h>
 #include <SoftwareSerial.h>

-#include "../common/common.c"
+#include "common.inc"

 // nRF24LE1 Serial port connections.  These will differ with the different chip
 // packages


fix add comment

fix
add comment

--- RGB_matrix.ino
+++ RGB_matrix.ino
@@ -5,6 +5,7 @@
 #define BUZZER_PIN 8
 #define SWITCH_PIN 9
 #define isPress() (!digitalRead(SWITCH_PIN))
+#define until(x) while(!(x))

 PlayMelody melodyA(BUZZER_PIN);
 PlayMelody melodyB(BUZZER_PIN);
@@ -40,15 +41,16 @@
 void loop(){

     //音が変わるたびに発光箇所が変わる
-    while( !isPress() ){
+    until(isPress()) {  //スイッチが押されるまで繰り返す
         delay(500);
         melodyA.play();
-        while( melodyA.isPlaying() && !isPress() ){
+        while( melodyA.isPlaying() ){   //曲が終わるまで再生を継続
             static unsigned long cnt=0;
             cnt += melodyA.play();
             Led::setAll(OFF);
             Led::set(cnt%9,WHITE);
             Led::lighting();
+            if( isPress() ) break;  //スイッチが押されたら再生停止
         }
         melodyA.stop();
         Led::setAll(OFF);
@@ -59,14 +61,16 @@

     //音の高さによって色が変わる
-    while( !isPress() ){
+    until(isPress()) {  //スイッチが押されるまで繰り返す
         delay(500);
         melodyB.play();
-        while( melodyB.isPlaying() && !isPress()){
+        while( melodyB.isPlaying() ){   //曲が終わるまで再生を継続
             melodyB.play();
+            //現在再生中の音程から色を決定
             LedColor color = int2color( melodyB.getPitch()%7+1 );
             Led::setAll(color);
             Led::lighting();
+            if( isPress() ) break;  //スイッチが押されたら再生停止
         }
         melodyB.stop();
         Led::setAll(OFF);
@@ -77,14 +81,15 @@

     //とにかくカラフル
-    while( !isPress() ){
+    until(isPress()) {  //スイッチが押されるまで繰り返す
         delay(500);
         melodyC.play();
-        while( melodyC.isPlaying() && !isPress() ){
-            if( melodyC.play() )
-                for(int i=0;i<3;i++)
+        while( melodyC.isPlaying() ){   //曲が終わるまで再生を継続
+            if( melodyC.play() )    //新しい音の再生が始まったら
+                for(int i=0;i<3;i++)    //３回「ランダムに選んだLEDをランダムな色に設定」する
                     Led::set(random(0,8),int2color(random(0,7)));
             Led::lighting();
+            if( isPress() ) break;  //スイッチが押されたら再生停止
         }
         melodyC.stop();
         Led::setAll(OFF);


BETA 0.4 fix #2

BETA 0.4 fix #2

- Minor bugfixes

--- Core.ino
+++ Core.ino
@@ -58,11 +58,11 @@
       if(analogRead(SENSOR_LEFT) > 150){
           stop();
           rotate(RIGHT);
-          wlak();
+          walk();
       } else {
           stop();
           rotate(LEFT);
-          wlak();
+          walk();
       }
     } else {
       walk();


fix servo range

fix servo range

--- testing/arduino/self-driving-v6.ino
+++ testing/arduino/self-driving-v6.ino
@@ -8,10 +8,10 @@

 // Ranges and Data
 const uint8_t rangeLimit_Warning1 = 60;
-const uint8_t rangeLimit_Warning2 = 50;
-const uint8_t rangeLimit_Warning3 = 40;
-const uint8_t rangeLimit_Stop = 25;
-const uint8_t motorSpeed = 70;
+const uint8_t rangeLimit_Warning2 = 55;
+const uint8_t rangeLimit_Warning3 = 45;
+const uint8_t rangeLimit_Stop = 35;
+const uint8_t motorSpeed = 70; // max: 255

 const uint16_t rangeLimit_RotateFor = 250;
 unsigned long rangeLimit_Timestamp = 0;
@@ -98,7 +98,7 @@
     LEDStrip.show(); // Initialize all pixels to 'off'

     // attach servo pin and set to initial direction
-    ServoMotor.attach(servoPin);
+    ServoMotor.attach(servoPin, 400, 2600);
     ServoMotor.write(servoCenter);
 }


git-svn-id: svn://192.168.1.10/public/Zimodem@15152 0d6f1817-ed0e-0410-87c9-987e46238f29

--- zimodem/zcommand.ino
+++ zimodem/zcommand.ino
@@ -1032,6 +1032,7 @@
       freeCharArray(&tempDelimiters);
       freeCharArray(&tempMaskOuts);
       streamMode.switchTo(c);
+      return ZCONNECT;
     }
     else
       return ZERROR;
@@ -1060,6 +1061,7 @@
       freeCharArray(&tempDelimiters);
       freeCharArray(&tempMaskOuts);
       streamMode.switchTo(c);
+      return ZCONNECT;
     }
   }
   return ZOK;
@@ -1428,7 +1430,8 @@
     String dmodifiers="";
     while(index<len)
     {
-      while((index<len)&&(sbuf[index]==' ')||(sbuf[index]=='\t'))
+      while((index<len)
+      &&((sbuf[index]==' ')||(sbuf[index]=='\t')))
         index++;
       lastCmd=lc(sbuf[index++]);
       vstart=index;
@@ -1440,7 +1443,8 @@
         secCmd = sbuf[vstart];
         vstart++;
       }
-      while((index<len)&&(sbuf[index]==' ')||(sbuf[index]=='\t'))
+      while((index<len)
+      &&((sbuf[index]==' ')||(sbuf[index]=='\t')))
       {
         vstart++;
         index++;
@@ -1466,6 +1470,9 @@
           const char *DMODIFIERS=",lbexprtw+";
           while((index<len)&&(strchr(DMODIFIERS,lc(sbuf[index]))!=null))
             dmodifiers += lc((char)sbuf[index++]);
+          while((index<len)
+          &&((sbuf[index]==' ')||(sbuf[index]=='\t')))
+            index++;
           vstart=index;
           if(sbuf[index]=='\"')
           {


Fix for spacing in numeric arguments.

Fix for spacing in numeric arguments.

git-svn-id: d8bfcd070c2c81762cca1b3912331324182919ba@20615 0d6f1817-ed0e-0410-87c9-987e46238f29


upd: moved initMDNS()

upd: moved initMDNS()

--- ArduinoFirmwareEsp/ArduinoFirmwareEsp.ino
+++ ArduinoFirmwareEsp/ArduinoFirmwareEsp.ino
@@ -23,12 +23,12 @@
   pinMode(WIFI_LED, OUTPUT);      //initialize wifi LED
   digitalWrite(WIFI_LED, LOW);
   ArduinoOTA.begin();             //OTA ESP
+  initMDNS();
   CommunicationLogic.begin();
   SPIFFS.begin();
   initHostname();
   initWebServer();                 //UI begin
   setWiFiConfig();
-  initMDNS();

 }


Present as many lights as there are defined on the strip

--- ESP8266HueEmulator/ESP8266HueEmulator.ino
+++ ESP8266HueEmulator/ESP8266HueEmulator.ino
@@ -96,7 +96,7 @@
     addConfigJson(config);
     aJsonObject *lights;
     aJson.addItemToObject(root, "lights", lights = aJson.createObject());
-    for (int i = 1; i <= 8; i++) // FIXME: Why does this not work for more than 8?
+    for (int i = 1; i <= pixelCount; i++)
       addLightJson(lights, i, StripRgbColors[i-1]);
     aJsonObject *schedules;
     aJson.addItemToObject(root, "schedules", schedules = aJson.createObject());


Add motors to main app

Add motors to main app

--- src/main.ino
+++ src/main.ino
@@ -1,7 +1,14 @@
 #include "MPU6050.h"
+#include "Motor.h"

 // Sensor inputs
 MPU6050 *sensors = new MPU6050();
+
+// Motors
+Motor *motorFrontLeft = new Motor(A5);
+Motor *motorFrontRight = new Motor(A4);
+Motor *motorBackLeft = new Motor(A0);
+Motor *motorBackRight = new Motor(A1);

 void setup() {
     // Setup USB serial output


Implement channel hoping.

Implement channel hoping.

--- src/main.ino
+++ src/main.ino
@@ -62,6 +62,9 @@
   Serial.print("RSSI: ");
   Serial.print(snifferPacket->rx_ctrl.rssi, DEC);

+  Serial.print(" Ch: ");
+  Serial.print(wifi_get_channel());
+
   char addr[] = "00:00:00:00:00:00";
   getMAC(addr, snifferPacket->data, 10);
   Serial.print(" Peer MAC: ");
@@ -92,6 +95,21 @@
   sprintf(addr, "%02x:%02x:%02x:%02x:%02x:%02x", data[offset+0], data[offset+1], data[offset+2], data[offset+3], data[offset+4], data[offset+5]);
 }

+#define CHANNEL_HOP_INTERVAL_MS   1000
+static os_timer_t channelHop_timer;
+
+/**
+ * Callback for channel hoping
+ */
+void channelHop()
+{
+  // hoping channels 1-14
+  uint8 new_channel = wifi_get_channel() + 1;
+  if (new_channel > 14)
+    new_channel = 1;
+  wifi_set_channel(new_channel);
+}
+
 #define DISABLE 0
 #define ENABLE  1

@@ -107,6 +125,12 @@
   delay(10);
   wifi_promiscuous_enable(ENABLE);

+  // setup the channel hoping callback timer
+  os_timer_disarm(&channelHop_timer);
+  os_timer_setfn(&channelHop_timer, (os_timer_func_t *) channelHop, NULL);
+  os_timer_arm(&channelHop_timer, CHANNEL_HOP_INTERVAL_MS, 1);
 }

-void loop() {}
+void loop() {
+  delay(10);
+}


decrease cold temperature from 25 to 10

decrease cold temperature from 25 to 10

--- arduino/sadr_meteo_no_firmata/sadr_meteo_no_firmata.ino
+++ arduino/sadr_meteo_no_firmata/sadr_meteo_no_firmata.ino
@@ -85,7 +85,7 @@
 // On contrôle avec la broche 11
 #define OUTP 11
 // Target temperature
-#define COLD_TEMPERATURE_TARGET 25
+#define COLD_TEMPERATURE_TARGET 10
 #define HOT_TEMPERATURE_TARGET 55
 #define COLD_TEMPERATURE_SECURITY -20 // must be less than COLD_TEMPERATURE_TARGET
 #define HOT_TEMPERATURE_SECURITY 60 // must be greater than HOT_TEMPERATURE_TARGET
@@ -572,7 +572,7 @@
      Consigne = HOT_TEMPERATURE_TARGET;
   } else {
      if (!isnan(T22int)) {
-        int newConsigne = ((T22int / 5) + 2 );
+        int newConsigne = ((T22int / 5) + 1 );
         newConsigne *= 5;
         if (newConsigne > COLD_TEMPERATURE_TARGET && newConsigne < HOT_TEMPERATURE_TARGET) {
             Consigne = max(COLD_TEMPERATURE_TARGET , newConsigne);


Adjusting resolution and alarm triggers.

--- examples/OWI/CosaDS18B20/CosaDS18B20.ino
+++ examples/OWI/CosaDS18B20/CosaDS18B20.ino
@@ -80,13 +80,14 @@
     uint8_t resolution;
     DS18B20* t = temp[i];
     t->connect(i);
+    t->set_resolution(10);
+    t->set_trigger(30, 20);
+    t->write_scratchpad();
     t->get_trigger(high, low);
     resolution = t->get_resolution();
     trace << (OWI::Driver&) *t << endl;
     trace << PSTR("resolution = ") << resolution << endl;
     trace << PSTR("trigger = ") << high << ':' << low << endl;
-    t->set_trigger(30, 20);
-    t->write_scratchpad();
     trace << endl;
   }
   ledPin.toggle();


Improving log

Improving log

--- examples/SimpleLibDemo/SimpleLibDemo.ino
+++ examples/SimpleLibDemo/SimpleLibDemo.ino
@@ -15,21 +15,33 @@
   radio.selectFrequency(89.1);
   delay(5000);

+  //Mutes the radio
   radio.mute();
   delay(2000);
+  //Unmutes the radio
   radio.turnTheSoundBackOn();
   delay(2000);

-  //Observation: At this point your Serial Monitor window should be open.
-
+  //Observation: At this point your Serial Monitor window
+  //should be already open if you want to see the results.
+  Serial.print("Stereo or Mono? ");
+  Serial.println(radio.isStereo() ? "Stereo" : "Mono");
+  //Mutes right channel
   radio.muteRight();
   delay(2000);
+  //Should go mono
+  Serial.print("Stereo or Mono? ");
   Serial.println(radio.isStereo() ? "Stereo" : "Mono");
+  //Unmutes right channel
   radio.turnTheRightSoundBackOn();
   delay(2000);
+  //Mutes left channel
   radio.muteLeft();
+  //Should also be mono
+  Serial.print("Stereo or Mono? ");
   Serial.println(radio.isStereo() ? "Stereo" : "Mono");
   delay(2000);
+  //Unmutes left channel
   radio.turnTheLeftSoundBackOn();
   delay(2000);

@@ -40,12 +52,19 @@
   radio.setStandByOff();
   delay(2000);

+  //Search Up is the default
   Serial.println("Search Up in progress...");
   radio.setSearchMidStopLevel();
   isBandLimitReached = radio.startsSearchMutingFromBeginning();

+  Serial.print("Band limit reached? ");
+  Serial.println(isBandLimitReached ? "Yes" : "No");
+  delay(2000);
+
   float freq = radio.readFrequencyInMHz();
-  Serial.println(freq, 1);
+  Serial.print("Station found: ");
+  Serial.print(freq, 1);
+  Serial.println(" MHz");
   delay(2000);

   while (!isBandLimitReached) {
@@ -54,8 +73,14 @@
     //If you want listen to station search, use radio.searchNext() instead
     isBandLimitReached = radio.searchNextMuting();

+    Serial.print("Band limit reached? ");
+    Serial.println(isBandLimitReached ? "Yes" : "No");
+    delay(2000);
+
     freq = radio.readFrequencyInMHz();
-    Serial.println(freq, 1);
+    Serial.print("Station found: ");
+    Serial.print(freq, 1);
+    Serial.println(" MHz");
     delay(2000);
   }

@@ -67,28 +92,47 @@
   Serial.println("Search Down in progress...");
   isBandLimitReached = radio.searchNextMuting();

+  Serial.print("Band limit reached? ");
+  Serial.println(isBandLimitReached ? "Yes" : "No");
+  delay(2000);
+
   freq = radio.readFrequencyInMHz();
-  Serial.println(freq, 1);
+  Serial.print("Station found: ");
+  Serial.print(freq, 1);
+  Serial.println(" MHz");
   delay(2000);

   while (!isBandLimitReached) {

     Serial.println("Search Down in progress...");
     isBandLimitReached = radio.searchNextMuting();
+
+    Serial.print("Band limit reached? ");
+    Serial.println(isBandLimitReached ? "Yes" : "No");
+    delay(2000);

     freq = radio.readFrequencyInMHz();
-    Serial.println(freq, 1);
+    Serial.print("Station found: ");
+    Serial.print(freq, 1);
+    Serial.println(" MHz");
     delay(2000);
   }

   radio.selectFrequency(89.1);

   //Read frequenci in MHz
-  Serial.println(radio.readFrequencyInMHz(), 1);
+  Serial.print("Station selected: ");
+  Serial.print(radio.readFrequencyInMHz(), 1);
+  Serial.println(" MHz");
+
   //Shows reception signal level
+  Serial.print("Signal level: ");
   Serial.println(radio.getSignalLevel());
+
   //Reception stereo or mono?
+  Serial.print("Stereo or Mono? ");
   Serial.println(radio.isStereo() ? "Stereo" : "Mono");
+
 }

 void loop() {


Using unique name for C3 LED

Using unique name for C3 LED

--- Elcano_C3_Pilot/Elcano_C3_Pilot.ino
+++ Elcano_C3_Pilot/Elcano_C3_Pilot.ino
@@ -1,5 +1,7 @@
+
 #include <Common.h>
-#include <IO.h>
+#include <IO_C3.h>
+#include <IO_Mega.h>
 #include <Matrix.h>

 /*
@@ -105,7 +107,7 @@
 {
         pinMode(Rx0, INPUT);
         pinMode(Tx0, OUTPUT);
-        pinMode(LED, OUTPUT);
+        pinMode(C3_LED, OUTPUT);
      	Serial.begin(9600);
         pinMode(DATA_READY, INPUT);
         DataAvailable = false;


- change total_pixel - modify start up animation

--- ptw-wheel.ino
+++ ptw-wheel.ino
@@ -2,12 +2,12 @@

 // Arduino Nano v2.x, v3.x

-#define TOTAL_PIXELS 99
+#define TOTAL_PIXELS 72

 // common settings :::::::::

 #define MAX_VAL 64 // 0 to 255 for brightness 多くのLEDを制御した場合に、色が安定しない問題を解決するために設けた制限
-#define DELAY_TIME 5
+
 // Parameter 1 = number of pixels in strip
 // Parameter 2 = pin number (most are valid)
 // Parameter 3 = pixel type flags, add together as needed:
@@ -50,7 +50,7 @@

   // startup animation
   rainbow(2);
-  colorWipe(0, DELAY_TIME);
+  colorWipe(0, 2);
 }

 void loop() {


Fixed fakeupdate url for Win10

Fixed fakeupdate url for Win10

--- RickRoll_Update/RickRoll_Update.ino
+++ RickRoll_Update/RickRoll_Update.ino
@@ -13,7 +13,7 @@
   DigiKeyboard.delay(5000);
   DigiKeyboard.sendKeyStroke(KEY_R, MOD_GUI_LEFT);
   DigiKeyboard.delay(3000);
-  DigiKeyboard.print("http://fakeupdate.net/win10u/index.html");
+  DigiKeyboard.print("http://fakeupdate.net/win10ue");
   DigiKeyboard.sendKeyStroke(KEY_ENTER);
   DigiKeyboard.delay(2000);
   DigiKeyboard.sendKeyStroke(KEY_F11);


Fixed typos in example

Fixed typos in example

--- examples/MifareClassicValueBlock/MifareClassicValueBlock.ino
+++ examples/MifareClassicValueBlock/MifareClassicValueBlock.ino
@@ -213,7 +213,7 @@
         Serial.println(mfrc522.GetStatusCodeName(status));
         return;
     }
-    Serial.print("New value of value of block "); Serial.print(valueBlockA);
+    Serial.print("New value of value block "); Serial.print(valueBlockA);
     Serial.print(" = "); Serial.println(value);

     // Decrement 10 from the value of valueBlockB and store the result in valueBlockB.
@@ -237,7 +237,7 @@
         Serial.println(mfrc522.GetStatusCodeName(status));
         return;
     }
-    Serial.print("New value of value of block "); Serial.print(valueBlockB);
+    Serial.print("New value of value block "); Serial.print(valueBlockB);
     Serial.print(" = "); Serial.println(value);
     // Check some boundary...
     if (value <= -100) {


Adjusted max speed

Adjusted max speed

--- Pan_Tilt_laser/Pan_Tilt_laser.ino
+++ Pan_Tilt_laser/Pan_Tilt_laser.ino
@@ -145,7 +145,7 @@
   int probability = random(101);
   int lowVal = 2;
   int midVal = 7;
-  int hiVal = 12;
+  int hiVal = 10;

   if(oldSpeed == lowVal){
     if(probability < 20){


Demo: fixed the brown-out beep.

Demo: fixed the brown-out beep.

--- examples/Demo/Demo.ino
+++ examples/Demo/Demo.ino
@@ -32,7 +32,7 @@
 char buttonMonitor();

 // A couple of simple tunes, stored in program space.
-const char beepBrownout[] PROGMEM = "<c32<e32#<g32";
+const char beepBrownout[] PROGMEM = "<c8";
 const char beepWelcome[] PROGMEM = ">g32>>c32";
 const char beepThankYou[] PROGMEM = ">>c32>g32";
 const char beepButtonA[] PROGMEM = "!c32";


add sketch of future code

add sketch of future code

--- engine-room/engine_arduino/engine_arduino.ino
+++ engine-room/engine_arduino/engine_arduino.ino
@@ -25,6 +25,13 @@
   leds.write(colors, 4);

   Serial.println('red'); // m is char*
+
+
+  // Sketch of eventual code
+  // Read switch values
+  // On switch change, set logic to change led colors
+  // write new colors
+  // On certain conditions (two reds in a row, etc) send serial command
 }

 rgb_color getRed()


added receiving CAN signals

added receiving CAN signals

--- Firmware/Firmware.ino
+++ Firmware/Firmware.ino
@@ -9,7 +9,7 @@
 #include <CAN.h>
 #include <SPI.h>

-#define BUS_SPEED 1000  // 1Mbps
+#define BUS_SPEED 1000  // 1Mbaud

 void setup()
 {
@@ -22,17 +22,33 @@
     CAN.setMode(NORMAL);
     // CAN.setMode(LOOPBACK);  // set to "NORMAL" for standard com

-    // Wait 10 seconds so that I can still upload even
+    // Wait a second so that I can still upload even
     // if the previous iteration spams the serial port
-    delay(100);
+    delay(1000);
+
+    startNode(0x01); // @todo: variable auch nutzen!
 }

 void loop()
 {
+    receive();
+    delay(100);
+}
+
+void startNode(byte nodeNr)
+{
+    // Nanocan Referenzhandbuch S.14
+    byte startnodeCommand[2] = {0x01, 0x01};
+    CAN.load_ff_0(2, 0x00, startnodeCommand);
+    CAN.send_0();
+}
+
+void sendTest()
+{
     static byte val = 0;
     val++;

-    byte length, rx_status,i;
+    byte length;
     unsigned short frame_id;
     byte frame_data[8];

@@ -52,6 +68,47 @@
     CAN.load_ff_1(1, 0x1d5, frame_data);
     CAN.send_0();
     CAN.send_1();
+}

-    delay(100);
+void receive()
+{
+    byte length = 0;
+    byte rx_status = 0;
+    unsigned short frame_id = 0;
+    byte frame_data[8];
+
+    // clear frame data
+    for (int i = 0; i < 8; i++)
+    {
+        frame_data[i] = 0;
+    }
+
+    rx_status = CAN.readStatus();
+    if ((rx_status & 0x01) == 0x01)
+    {
+        CAN.readDATA_ff_0(&length, frame_data, &frame_id);
+    }
+    else if ((rx_status & 0x02) == 0x02)
+    {
+        CAN.readDATA_ff_1(&length, frame_data, &frame_id);
+    }
+
+    if (((rx_status & 0x01) == 0x01) || ((rx_status & 0x02) == 0x02))
+    {
+        Serial.print("Rx:");
+        Serial.print(rx_status, HEX);
+        Serial.print(" ");
+        Serial.print(length, HEX);
+
+        Serial.print(" - ");
+        Serial.print(frame_id, HEX);
+        Serial.print(": ");
+
+        for (int i = 0; i < 8; i++)
+        {
+            Serial.print(" ");
+            Serial.print(frame_data[i], HEX);
+        }
+        Serial.println();
+    }
 }


Deep sleep kicks in too early: ESP8266 is unable to publish the message.

--- ha_mqtt_sensor_dht22/ha_mqtt_sensor_dht22.ino
+++ ha_mqtt_sensor_dht22/ha_mqtt_sensor_dht22.ino
@@ -95,6 +95,7 @@
   char data[200];
   root.printTo(data, root.measureLength() + 1);
   client.publish(MQTT_SENSOR_TOPIC, data, true);
+  yield();
 }

 // function called when a MQTT message arrived


Enable all the leds

Enable all the leds

--- blink_strip/blink_strip.ino
+++ blink_strip/blink_strip.ino
@@ -29,7 +29,7 @@
 void loop()
 {
   for(uint8_t i = 0; i < 10; i++) {
-    send_pixel(0,0,0);
+//    send_pixel(0,0,0);
   }

   float brightness = random(100,100)/100.0;
@@ -52,3 +52,4 @@
 }

+


Version with PID included. Bug after a few seconds...

--- HBridgePWM/Sabertooth/Sabertooth.ino
+++ HBridgePWM/Sabertooth/Sabertooth.ino
@@ -10,6 +10,7 @@
 #include <SoftwareSerial.h>
 #include <SabertoothSimplified.h>
 #include <TinyGPS++.h>
+#include <PID_v1.h>

 SoftwareSerial SWSerial(NOT_A_PIN, 8); // RX on no pin (unused), TX on pin 11 (to S1).
 SabertoothSimplified ST(SWSerial); // Use SWSerial as the serial port.
@@ -33,8 +34,16 @@
 long lastWriteTime = 0;

 TinyGPSPlus nmea;
-TinyGPSCustom pwm(nmea, "ORPWM", 1); // $GPGSA sentence, 15th element
-
+TinyGPSCustom pwm(nmea, "ORPWM", 1);
+TinyGPSCustom roll(nmea, "ORPOS", 1);
+TinyGPSCustom elevation(nmea, "ORPOS", 2);
+TinyGPSCustom bearing(nmea, "ORPOS", 3);
+
+//Define Variables we'll be connecting to
+double Setpoint, Input, Output;
+
+//Specify the links and initial tuning parameters
+PID myPID(&Input, &Output, &Setpoint,10,0,50, DIRECT);

 void setup()
 {
@@ -42,6 +51,11 @@
   SWSerial.begin(9600);
   // Initialize serial communications at 9600 bps:
   Serial.begin(19200);
+  Input = 0;
+  Setpoint = 0;
+  //turn the PID on
+  myPID.SetMode(AUTOMATIC);
+  myPID.SetOutputLimits(-128, 128);
 }

 void SerialEvent() {
@@ -87,7 +101,8 @@
       while (*gpsStream)
         if (nmea.encode(*gpsStream++))
       {
-        alphaSigned = StrToFloat(pwm.value());
+        alphaSigned = StrToFloat(pwm.value());
+        Input = StrToFloat(pwm.value());
         lastSerialInputTime = millis();
       }
     }
@@ -98,9 +113,11 @@
 void loop()
 {
   SerialEvent();
+  myPID.Compute();
   int power;
   sensorValue = analogRead(analogInPin);
   setMode();
+  //alphaSigned=Output/127.0;
   computeAlphaSigned();
   power = alphaSigned*127;
   ST.motor(1, power);
@@ -108,7 +125,8 @@
   if (millis()-lastWriteTime>100)
   {
     lastWriteTime = millis();
-    Serial.println(alphaSigned);
+    //Serial.println(alphaSigned);
+    Serial.println(Output);
     if (isSerialControl)
     {
       //Serial.println("S");


Cleanup.

Cleanup.

--- examples/Blink/CosaBlinkRandom/CosaBlinkRandom.ino
+++ examples/Blink/CosaBlinkRandom/CosaBlinkRandom.ino
@@ -34,8 +34,8 @@

 void loop()
 {
-  ledPin.high();
-  delay(random(100, 500));
-  ledPin.low();
-  delay(random(100, 500));
+  ledPin.on();
+  delay(rand(100, 500));
+  ledPin.off();
+  delay(rand(100, 500));
 }


Send all data in once

Send all data in once

--- arduino_slave_sensor/Temp_probe.ino
+++ arduino_slave_sensor/Temp_probe.ino
@@ -10,7 +10,6 @@
 DHT dht(DHTPIN, DHTTYPE);

 int sleep_index=0;
-int ack=0;

 void setup() {
   Serial.begin(9600);
@@ -21,28 +20,21 @@

 int sendData(int temp, int hum)
 {
-  ack = 0;
-  //dummy bytes
-  Serial.write(169);
-  Serial.write(244);
-  Serial.write(190);
-  //humidity
-  Serial.write(hum);
-  //255 - humidity
-  Serial.write(255-hum);
-  //temperature + 25
-  //(temperature can be negative)
-  Serial.write(temp+25);
-  //230 - temperature
-  Serial.write(255-temp);
-  //for redunduncy, temperature + humidity
-  Serial.write(hum+temp);
-  //temperature + humidity - 255
-  Serial.write(hum+temp);
-  //dummy bytes
-  Serial.write(190);
-  Serial.write(244);
-  Serial.write(169);
+	int send_temp, cs_temp, cs_hum, redund, cs_redund;
+  int ack = 0;
+	int dummy_byte1=169;
+	int dummy_byte2=244;
+	int dummy_byte3=190;
+
+	send_temp = temp + 25;
+	cs_temp = 255 - (temp + 25);
+	cs_hum = 255 - hum;
+	redund = hum + temp + 25;
+	cs_redund = 255 - (hum + temp + 25);
+
+	byte packet[] = {dummy_byte1, dummy_byte2, dummy_byte3, hum, cs_hum, send_temp, cs_temp, redund, cs_redund, dummy_byte3, dummy_byte2, dummy_byte1};
+  Serial.write(packet, 12);
+
   delay(200);
   if (Serial.available() > 0) {
     ack=Serial.read();


fix cc3000 button feed name

fix cc3000 button feed name

--- arduino-cc3000/button/button.ino
+++ arduino-cc3000/button/button.ino
@@ -86,9 +86,9 @@

   // send the proper value to AIO depending on button state
   if(current == LOW)
-    sendData("button", "1");
+    sendData("Button", "1");
   else
-    sendData("button", "0");
+    sendData("Button", "0");

   // save the button state
   last = current;


Rotation and update code for arduino nano

--- pug.ino
+++ pug.ino
@@ -6,7 +6,9 @@
 #define leftMotorPin1 9
 #define leftMotorPin2 10

-#define starterServoPin 7
+#define starterServoPin 15
+
+#define rotateTime 750

 // Globals vars
 Servo starterServo;
@@ -68,7 +70,7 @@
 void rotateRight() {
   setLeftSpeed( 60 );
   setRightSpeed( -60 );
-  delay(1500);
+  delay(rotateTime);
   stopMotors();
 }

@@ -78,7 +80,7 @@
 void rotateLeft() {
   setLeftSpeed( -60 );
   setRightSpeed( 60 );
-  delay(1500);
+  delay(rotateTime);
   stopMotors();
 }

@@ -180,20 +182,26 @@
   {
     case 'I': // Initialize
       setLeftSpeed(20);
-    break;
+      break;
     case 'R': // Rotation
       if (serialInput[1] == 'L') rotateLeft();
       else rotateRight();
       break;

-    case 'F': // Booth motor
+    case 'F': // Front direction
       setLeftSpeed( serialInput[1] * 100 + serialInput[2] * 10 + serialInput[3]);
       setRightSpeed( serialInput[1] * 100 + serialInput[2] * 10 + serialInput[3]);
-      break;
-
-    case 'B': // Booth motor
+      delay(1500);
+      setLeftSpeed( -2 );
+      setRightSpeed( -2);
+      delay(400);
+      stopMotors();
+      break;
+
+    case 'B': // Back direction
       setLeftSpeed( (serialInput[1] * 100 + serialInput[2] * 10 + serialInput[3]) * -1);
       setRightSpeed( (serialInput[1] * 100 + serialInput[2] * 10 + serialInput[3]) * -1);
+
       break;

     case 'S': // Starting block


Fixed LED blinking

Fixed LED blinking

--- Arduino/Arduino.ino
+++ Arduino/Arduino.ino
@@ -2,9 +2,9 @@

 #include <stdio.h>
 #include <adk.h>
-#define LED_GREEN 53
-#define LED_YELLOW 52
-#define LED_RED 7
+#define LED_GREEN 22
+#define LED_YELLOW 24
+#define LED_RED 26
 #define BUFFSIZE   255
 #define MAX_POWER  400
 #define DELAY 50 // Smaller delay breaks everything about communication
@@ -114,8 +114,8 @@
 char inStringBuffer[BUFFSIZE];
 char outStringBuffer[BUFFSIZE];
 uint32_t bytesRead = 0;
-int blinkGreenTimer, blinkRedTimer;
-bool stateRed,stateGreen;
+int blinkGreenTimer, blinkYellowTimer;
+bool stateYellow,stateGreen;
 bool emergency_mode,warning,FL_edge,FR_edge;
 int emergency_sensor_threshold =880,currentState=IDLE;

@@ -141,8 +141,8 @@
   delay(1000);
   Serial.println("All power to the engines!");
   stop(SOFT);
-  blinkGreenTimer=blinkRedTimer= millis();
-  stateGreen=stateRed=true;
+  blinkGreenTimer=blinkYellowTimer= millis();
+  stateGreen=stateYellow=true;
   emergency_mode=warning=false;
   digitalWrite(LED_GREEN, LOW);
   digitalWrite(LED_YELLOW, LOW);
@@ -215,6 +215,8 @@
           Serial.print("ERROR: Command "); Serial.print(command); Serial.print(", param1 "); Serial.print(param1); Serial.print(", param2 "); Serial.print(param2); Serial.println(", is not valid!");
         }
       }
+      stateYellow=false;
+      digitalWrite(LED_YELLOW, stateYellow);
       if (millis()-blinkGreenTimer>300){
         stateGreen=!stateGreen;
         blinkGreenTimer=millis();
@@ -222,10 +224,12 @@
       }
     }
     else {
-      if (millis()-blinkRedTimer>300){
-        stateRed=!stateRed;
-        blinkRedTimer=millis();
-        digitalWrite(LED_YELLOW, stateRed);
+      stateGreen=false;
+      digitalWrite(LED_GREEN, stateGreen);
+      if (millis()-blinkYellowTimer>300){
+        stateYellow=!stateYellow;
+        blinkYellowTimer=millis();
+        digitalWrite(LED_YELLOW, stateYellow);
       }
       Serial.print("*");
     }


WIP

WIP

Added comments and status bools

--- Arduino/Arduino.ino
+++ Arduino/Arduino.ino
@@ -4,11 +4,11 @@
 #include <Servo.h>

 // SERVOS
-Servo throttle;
-Servo rotatingFront;
-Servo rotatingBack;
-Servo leftRight;
-Servo upDown;
+Servo throttle;       // Speed
+Servo rotatingFront;  // cylinder at the front
+Servo rotatingBack;   // cylinder at the back
+Servo leftRight;      // left-right
+Servo upDown;         // up-down

 // SENSORS
 // Nothing here yet
@@ -24,6 +24,19 @@
 int ByteReceived;   // store byte recieved via serial

 char statusReport = 'A'; // one-byte status report to controller
+
+bool batteryLow = false;
+bool batteryOk = true;
+bool motorOk = true;
+bool servosOk = true;
+bool sensorsOk = true;
+bool arduinoOk = true;
+
+// CONSTANTS
+
+const int LOOP_DELAY = 100;
+
+

 // INITIALIZE
 void setup() {
@@ -98,6 +111,12 @@
 //  }

   // Get information from Serial
+
+  // Check if the information is even complete/correct
+
+  // Check if there are any commands to execute
+
+  // Read servo inputs
   int Read = 0;
   Read = Serial.read();
   pos1 = Read;
@@ -126,5 +145,5 @@
   Serial.write(pos5);

   // Delay
-  delay(100);
+  delay(LOOP_DELAY);
 }


Arduino refactoring

Arduino refactoring

--- Arduino/Arduino.ino
+++ Arduino/Arduino.ino
@@ -1,7 +1,6 @@
-// arduino.ino
-
 #include <stdio.h>
 #include <adk.h>
+
 #define LED_GREEN 22
 #define LED_YELLOW 24
 #define LED_RED 26
@@ -48,13 +47,6 @@
 #define FL A5
 #define FR A4

-
-const int
-LEFT = 0,
-RIGHT = 1,
-BOTH = 2,
-DEFAULT_VELOCITY=135;
-
 const bool
 FORWARD = HIGH,
 BACKWARD = LOW,
@@ -62,35 +54,42 @@
 SOFT = false;

 // Motors definition
-//Ch A = LEFT, Ch B = RIGHT
+//Ch. A = LEFT, Ch. B = RIGHT
 const int
-PWM_LEFT   = 3,
-DIR_LEFT   = 12,
+PWM_LEFT = 3,
+PWM_RIGHT = 11,
+DIR_LEFT = 12,
+DIR_RIGHT = 13,
 BRAKE_LEFT = 9,
-SNS_LEFT  = A0;
-const int
-PWM_RIGHT   = 11,
-DIR_RIGHT   = 13,
 BRAKE_RIGHT = 8,
-SNS_RIGHT  = A1;
+SNS_LEFT = A0,
+SNS_RIGHT = A1,
+LEFT = 0,
+RIGHT = 1,
+BOTH = 2,
+DEFAULT_VELOCITY = 135;

 int
 command,
 param1,
 param2,
 lastCommand=CMD_STOP,
+emergency_sensor_threshold = 800,
 targetLeftVelocity = 0,
 targetRightVelocity = 0,
 currentLeftVelocity = 0,
 currentRightVelocity= 0,
 baseVelocity = 131,
-velocityStep= 5;
+velocityStep= 5,
+blinkGreenTimer,
+blinkYellowTimer,
+currentState = IDLE;
+
+// Test Variabiles
+int randomint;
+int last_send = 0;

 long coldTimerStart;
-
-
-
-

 // Start Accessory Descriptor. It's how Arduino identifies itself in Android.
 char accessoryName[] = "UDOO Mobile Tank";
@@ -105,29 +104,28 @@
 USBHost Usb;
 ADK adk(&Usb, manufacturer, model, accessoryName, versionNumber, url, serialNumber);
 // End ADK configuration
+
 // Debug mode for communication
 bool COM_DEBUG_MODE = false;
+
 // Debug mode for movment
 bool MOV_DEBUG_MODE = false;
+
 uint8_t inBuffer[BUFFSIZE];
 uint8_t outBuffer[BUFFSIZE];
 char inStringBuffer[BUFFSIZE];
 char outStringBuffer[BUFFSIZE];
 uint32_t bytesRead = 0;
-int blinkGreenTimer, blinkYellowTimer;
-bool stateYellow,stateGreen;
-bool emergency_mode,warning,FL_edge,FR_edge;
-int emergency_sensor_threshold =800,currentState=IDLE;
-
-
-
-// Test Variabiles
-int randomint;
-int last_send = 0;
-
+
+bool
+stateYellow,
+stateGreen,
+emergency_mode,
+warning,
+FL_edge,
+FR_edge;

 void setup() {
-  // Configure the A output
   pinMode(BRAKE_LEFT, OUTPUT);  // Brake pin on channel A
   pinMode(DIR_LEFT, OUTPUT);    // Direction pin on channel A
   pinMode(BRAKE_RIGHT, OUTPUT);  // Brake pin on channel B
@@ -150,85 +148,83 @@
 }

 void loop() {
- Serial.print(analogRead(FL));Serial.print(" Left - Right ");Serial.println(analogRead(FR));
+  Serial.print(analogRead(FL));Serial.print(" Left - Right ");Serial.println(analogRead(FR));
   //Go in emergency mode after two bad readings from sensor
   if (MOV_DEBUG_MODE){
     Serial.print("FL reading: ");
     Serial.println(analogRead(FL));
   }
   if (!sensorsOk() && warning){
-    emergency_mode=true;
+    emergency_mode = true;
     emergency();
-    }else if (!sensorsOk() && !warning){
-      warning=true;
-      Serial.println("Emergency warning");
-    }
-    else {
-      warning=false;
-    }
-    if (COM_DEBUG_MODE) {
-      Serial.print(".");
-    }
-
-
-    Usb.Task();
+  }else if (!sensorsOk() && !warning){
+    warning = true;
+    Serial.println("Emergency warning");
+  }
+  else {
+    warning = false;
+  }
+  if (COM_DEBUG_MODE) {
+    Serial.print(".");
+  }
+  Usb.Task();
   // Check that ADK is available
   if (adk.isReady()) {
     char*a;
     if (strlen(a = readFromADK()) > 0) {
       if (decodeCommand(a, &command, &param1, &param2)) {
-        if (MOV_DEBUG_MODE && (command == CMD_LEFT || command== CMD_RIGHT)){
+        if (MOV_DEBUG_MODE && (command == CMD_LEFT || command == CMD_RIGHT)){
           Serial.print("COMMAND: Command "); Serial.print(command); Serial.print(", param1 "); Serial.print(param1); Serial.print(", param2 "); Serial.print(param2); Serial.println(", received and is beign processed!");
         }
         switch (command) {
           case CMD_LEFT:
-          currentState=HUNTING;
-          turnLeft(param1, param2);
-          break;
+            currentState = HUNTING;
+            turnLeft(param1, param2);
+            break;
           case CMD_RIGHT:
-          currentState=HUNTING;
-          turnRight(param1, param2);
-          break;
+            currentState = HUNTING;
+            turnRight(param1, param2);
+            break;
           case CMD_STOP:
-          currentState=IDLE;
-          stop(HARD);
-          break;
+            currentState = IDLE;
+            stop(HARD);
+            break;
           case CMD_MOVE_FORWARD:
-          currentState=HUNTING;
-          moveForward(param1,param2);
-          break;
+            currentState = HUNTING;
+            moveForward(param1,param2);
+            break;
           case CMD_SEARCH:
-          currentState=SEARCHING;
-          moveForward(DEFAULT_VELOCITY,DEFAULT_VELOCITY);
-          break;
+            currentState = SEARCHING;
+            moveForward(DEFAULT_VELOCITY,DEFAULT_VELOCITY);
+            break;
           default:
-          stop(HARD);
-          if (COM_DEBUG_MODE) {
-            Serial.println("Default Block");
-          }
-          break;
+            stop(HARD);
+            if (COM_DEBUG_MODE) {
+              Serial.println("Default Block");
+            }
+            break;
         }
-        lastCommand=command;
+        lastCommand = command;
       }
       else {
         if (MOV_DEBUG_MODE){
           Serial.print("ERROR: Command "); Serial.print(command); Serial.print(", param1 "); Serial.print(param1); Serial.print(", param2 "); Serial.print(param2); Serial.println(", is not valid!");
         }
       }
-      stateYellow=false;
+      stateYellow = false;
       digitalWrite(LED_YELLOW, stateYellow);
-      if (millis()-blinkGreenTimer>300){
-        stateGreen=!stateGreen;
-        blinkGreenTimer=millis();
+      if (millis() - blinkGreenTimer > 300){
+        stateGreen = !stateGreen;
+        blinkGreenTimer = millis();
         digitalWrite(LED_GREEN, stateGreen);
       }
     }
     else {
-      stateGreen=false;
+      stateGreen = false;
       digitalWrite(LED_GREEN, stateGreen);
-      if (millis()-blinkYellowTimer>300){
-        stateYellow=!stateYellow;
-        blinkYellowTimer=millis();
+      if (millis() - blinkYellowTimer > 300){
+        stateYellow = !stateYellow;
+        blinkYellowTimer = millis();
         digitalWrite(LED_YELLOW, stateYellow);
       }
       Serial.print("*");
@@ -272,27 +268,6 @@
   delay(DELAY / 10);
 }

-//TODO remove
-void sendToADKDelayed(int command, int param1, int param2) {
-  int time = millis();
-  if (time - last_send > 2000) {
-    last_send = time;
-    randomint = random(-1500, 1500);
-    memset(outStringBuffer, 0, BUFFSIZE);
-    sprintf(outStringBuffer, "%d,%d,%d", command, param1, param2);
-    memcpy(outBuffer, outStringBuffer, BUFFSIZE);
-    adk.write(strlen(outStringBuffer), outBuffer);
-    if (COM_DEBUG_MODE) {
-      Serial.print("\nSending | ");
-      Serial.print(outStringBuffer);
-      Serial.print(" | ");
-      Serial.print(strlen(outStringBuffer));
-      Serial.println(" bytes outgoing");
-    }
-  }
-  delay(DELAY / 10);
-}
-
 bool decodeCommand(char* incoming, int* command, int* param1, int* param2) {
   // Incoming message pattern command,param1,param2
   char delimiter = ',';
@@ -321,8 +296,8 @@
     Serial.println(*param2);
   }
   return true;
-
-}
+}
+
 void getDistance(){
   long duration, distance;
   digitalWrite(TRIG_PIN, LOW);
@@ -333,11 +308,11 @@
   //The module return an high signal with duration equal to the sound travel time
   duration = pulseIn(ECHO_PIN, HIGH, 2000);//ignores target far more than 71cm
   // Divide half
-  distance = (duration/2) / 29.1;
+  distance = (duration / 2) / 29.1;
   if (COM_DEBUG_MODE) {
     Serial.print(distance);Serial.println("cm");
   }
-  sendToADK(INFO,DISTANCE,(int)distance);
+  sendToADK(INFO, DISTANCE, (int)distance);
 }

 void setDirection(int side, bool direction) {
@@ -356,58 +331,59 @@
 void brake(int side) {
   switch(side){
     case LEFT:
-    digitalWrite(BRAKE_LEFT, HIGH);
-    break;
+      digitalWrite(BRAKE_LEFT, HIGH);
+      break;
     case RIGHT:
-    digitalWrite(BRAKE_RIGHT, HIGH);
-    break;
+      digitalWrite(BRAKE_RIGHT, HIGH);
+      break;
     case BOTH:
-    digitalWrite(BRAKE_LEFT, HIGH);
-    digitalWrite(BRAKE_RIGHT, HIGH);
-    break;
+      digitalWrite(BRAKE_LEFT, HIGH);
+      digitalWrite(BRAKE_RIGHT, HIGH);
+      break;
     default:
-    break;
+      break;
   }
 }

 void releaseBrake(int side) {
   switch(side){
     case LEFT:
-    digitalWrite(BRAKE_LEFT, LOW);
-    break;
+      digitalWrite(BRAKE_LEFT, LOW);
+      break;
     case RIGHT:
-    digitalWrite(BRAKE_RIGHT, LOW);
-    break;
+      digitalWrite(BRAKE_RIGHT, LOW);
+      break;
     case BOTH:
-    digitalWrite(BRAKE_LEFT, LOW);
-    digitalWrite(BRAKE_RIGHT, LOW);
-    break;
+      digitalWrite(BRAKE_LEFT, LOW);
+      digitalWrite(BRAKE_RIGHT, LOW);
+      break;
     default:
-    break;
-  }
-}
-void moveForward(int velocityLeft,int velocityRight){
-  setDirection(BOTH,FORWARD);
+      break;
+  }
+}
+
+void moveForward(int velocityLeft, int velocityRight){
+  setDirection(BOTH, FORWARD);
   releaseBrake(BOTH);
   analogWrite(PWM_LEFT, velocityLeft);
   analogWrite(PWM_RIGHT, velocityRight);
 }

-void moveBackward(int velocityLeft,int velocityRight){
-  setDirection(BOTH,BACKWARD);
+void moveBackward(int velocityLeft, int velocityRight){
+  setDirection(BOTH, BACKWARD);
   releaseBrake(BOTH);
   analogWrite(PWM_LEFT, velocityLeft);
   analogWrite(PWM_RIGHT, velocityRight);
 }

 void turnLeft(int velocity, int mode){
-  if (lastCommand!=CMD_LEFT){
+  if (lastCommand != CMD_LEFT){
     stop(HARD);
   }
   setDirection(RIGHT, FORWARD);
   releaseBrake(RIGHT);
   analogWrite(PWM_RIGHT, velocity);
-  if (mode==TURN_ON_SPOT){
+  if (mode == TURN_ON_SPOT){
     setDirection(LEFT, BACKWARD);
     releaseBrake(LEFT);
     analogWrite(PWM_LEFT, velocity);
@@ -416,16 +392,16 @@

 void turnRight(int velocity, int mode){
   if (lastCommand!=CMD_RIGHT){
-   stop(HARD);
- }
- setDirection(LEFT, FORWARD);
- releaseBrake(LEFT);
- analogWrite(PWM_LEFT, velocity);
- if (mode==TURN_ON_SPOT){
-  setDirection(RIGHT, BACKWARD);
-  releaseBrake(RIGHT);
-  analogWrite(PWM_RIGHT, velocity);
-}
+    stop(HARD);
+  }
+  setDirection(LEFT, FORWARD);
+  releaseBrake(LEFT);
+  analogWrite(PWM_LEFT, velocity);
+  if (mode == TURN_ON_SPOT){
+    setDirection(RIGHT, BACKWARD);
+    releaseBrake(RIGHT);
+    analogWrite(PWM_RIGHT, velocity);
+  }
 }

 // with method = HARD = true it uses brakes, otherwise stop by inertia
@@ -451,27 +427,27 @@
   stop(HARD);
   if (FLIsOut() && FRIsOut()){
     delay(200);
-    moveBackward(DEFAULT_VELOCITY+15,DEFAULT_VELOCITY+15);
+    moveBackward(DEFAULT_VELOCITY+15, DEFAULT_VELOCITY+15);
     delay(500);
-    turnRight(DEFAULT_VELOCITY+15,TURN_ON_SPOT);
+    turnRight(DEFAULT_VELOCITY+15, TURN_ON_SPOT);
     delay(1000);
   }
   else if (FLIsOut()){
-    moveBackward(DEFAULT_VELOCITY+15,DEFAULT_VELOCITY+15);
+    moveBackward(DEFAULT_VELOCITY+15, DEFAULT_VELOCITY+15);
     delay(200);
     turnRight(DEFAULT_VELOCITY+15, TURN_ON_SPOT);
     delay(500);
   }
   else if (FRIsOut()){
-    moveBackward(DEFAULT_VELOCITY+15,DEFAULT_VELOCITY+15);
+    moveBackward(DEFAULT_VELOCITY+15, DEFAULT_VELOCITY+15);
     delay(200);
     turnLeft(DEFAULT_VELOCITY+25, TURN_ON_SPOT);
     delay(500);
   }
   stop(SOFT);
   //TODO if is not all ok, call it recursively
-  emergency_mode=warning=false;
-  FL_edge=FR_edge=false;
+  emergency_mode = warning = false;
+  FL_edge = FR_edge = false;
   Serial.println("EMERGENCY ENDED");
   digitalWrite(LED_RED, LOW);
 }
@@ -479,13 +455,15 @@
 bool sensorsOk(){
   return !FLIsOut() && !FRIsOut();
 }
+
 bool FRIsOut(){
-  return analogRead(FR)>emergency_sensor_threshold;
-}
+  return analogRead(FR) > emergency_sensor_threshold;
+}
+
 bool FLIsOut(){
-  return analogRead(FL)>emergency_sensor_threshold;
+  return analogRead(FL) > emergency_sensor_threshold;
 }

 void terminateAndroidApp(){
-  sendToADK(INFO,TERMINATE,CMD_NULL_VALUE);
+  sendToADK(INFO, TERMINATE, CMD_NULL_VALUE);
 }


Ajout commentaire entête fichier

Ajout commentaire entête fichier

--- Pince/pince/pince.ino
+++ Pince/pince/pince.ino
@@ -1,3 +1,14 @@
+/* |=====================|
+ * | Gestion de la pince |
+ * |=====================|
+ */
+/**
+ *    \file pince.cpp
+ *    \brief Gestion de la pince
+ *    \author Olivier JOMBART
+ *    \date Novemmbre 2016
+*/
+
 #include <Servo.h>

 Servo myservo;        // create servo object to control a servo


Added small delay to arduino code

Added small delay to arduino code

--- Arduino_LEDs/Arduino_LEDs.ino
+++ Arduino_LEDs/Arduino_LEDs.ino
@@ -42,6 +42,7 @@
 //for(distance=1000; distance > 50; distance=distance-100){
 //  for(angle=0;angle<360;angle=angle+10){
 while (Serial.available()){
+  delay(30);
   inputstring = Serial.readStringUntil('A');
   refresh = 1;
 }


added temperature measurement

added temperature measurement

--- control/control.ino
+++ control/control.ino
@@ -14,6 +14,10 @@
 #include "tx433_Nexa.h" // Nexa headers
 #include <buttons.h>  // Button sensing

+// Temperature Pin
+const int TEMP_PIN = A1;
+float tempC = 0;
+
 // Setup software serial
 SoftwareSerial com(10, 11); // RX, TX

@@ -49,9 +53,16 @@

 void setup()
 {
+  // Set aRef to INTERNAL 1.1v
+  analogReference(INTERNAL);
+
+  pinMode(TEMP_PIN, OUTPUT);
+
   pinMode(PUMP_PIN, OUTPUT);
   digitalWrite(PUMP_PIN, HIGH);
+
   pinMode(OVERFLOW_PIN, INPUT);
+
   pinMode(FORCE_CYCLE_PIN, INPUT);
   digitalWrite(FORCE_CYCLE_PIN, LOW);

@@ -95,6 +106,7 @@
 void  loop(){
   CheckWaterOn();
   CheckButtons();
+  sendTemp();
   digitalClockDisplay();
   Alarm.delay(0); // o == check all the time
 }
@@ -226,6 +238,30 @@
     }
 }

+void sendTemp()
+{
+  static long last_temp_transmit = millis();
+  if ((millis() - last_temp_transmit) >= 100)
+   {
+    readTemp();
+    String data = "id=temp value=";
+    data += tempC;
+    sendData(data);
+    //Serial.print("Temp in room: ");
+    //Serial.println(data);
+    last_temp_transmit = millis();
+   }
+  }
+
+void readTemp()
+{
+  float tmp = 0;
+  for (int i=0; i < 10; i++)
+    tmp += analogRead(TEMP_PIN) / 9.31;
+
+  tempC = tmp / 10;
+  }
+
 void digitalClockDisplay()
 {
   // digital clock display of the time


Adding composite command SMQB.

Adding composite command SMQB.

Eggbot extension usually interleaves SM commands with QB to test PRG button.
It makes it hard to buffer and introduces delays in motion.
SMQB does both at once: moves motors and then returns PRG button state.
To make buffering simpler with synchronous eggbot extension, motion acknowledge is send before actual move.

--- Functions.ino
+++ Functions.ino
@@ -5,6 +5,7 @@
   SCmd.addCommand("SC",stepperModeConfigure);
   SCmd.addCommand("SP",setPen);
   SCmd.addCommand("SM",stepperMove);
+  SCmd.addCommand("SMQB",stepperMoveQueryButton); // composite function enabling smooth movement
   SCmd.addCommand("SE",ignore);
   SCmd.addCommand("TP",togglePen);
   SCmd.addCommand("PO",ignore);    //Engraver command, not implemented, gives fake answer
@@ -15,7 +16,7 @@
   SCmd.addCommand("SL",setLayer);
   SCmd.addCommand("QL",queryLayer);
   SCmd.addCommand("QP",queryPen);
-  SCmd.addCommand("QB",queryButton); //preparation for "PRG" Button, actually gives fake answer,
+  SCmd.addCommand("QB",queryButton);
   SCmd.setDefaultHandler(unrecognized); // Handler for command that isn't matched (says "What?")
   }

@@ -82,69 +83,107 @@
 	sendAck();
 }

-void stepperMove(){
+void stepperMove() {
   uint16_t duration=0; //in ms
   int penStepsEBB=0; //Pen
   int rotStepsEBB=0; //Rot
+
+  if (!parseSMArgs(&duration, &penStepsEBB, &rotStepsEBB)) {
+    sendError();
+    return;
+  }
+
+  if ( (penStepsEBB==0) && (rotStepsEBB==0) ) {
+    delay(duration);
+    sendAck();
+    return;
+  }
+
+  doMove(duration, penStepsEBB, rotStepsEBB);
+  sendAck();
+}
+
+void stepperMoveQueryButton() {
+  uint16_t duration=0; //in ms
+  int penStepsEBB=0; //Pen
+  int rotStepsEBB=0; //Rot
+
+  if (!parseSMArgs(&duration, &penStepsEBB, &rotStepsEBB)) {
+    sendError();
+    return;
+  }
+
+  if ( (penStepsEBB==0) && (rotStepsEBB==0) ) {
+    delay(duration);
+    queryButton();
+    return;
+  }
+
+  // sending ACK before actual move to allow buffering
+  queryButton();
+  doMove(duration, penStepsEBB, rotStepsEBB);
+}
+
+bool parseSMArgs(uint16_t *duration, int *penStepsEBB, int *rotStepsEBB) {
   char *arg1;
   char *arg2;
   char *arg3;
   arg1 = SCmd.next();
   if (arg1 != NULL) {
-      duration = atoi(arg1);
-      arg2 = SCmd.next();
-      }
-   if (arg2 != NULL) {
-      penStepsEBB = atoi(arg2);
-      arg3 = SCmd.next();
-      }
-   if (arg3 != NULL) {
-      rotStepsEBB = atoi(arg3);
-	  //sendAck();
+     *duration = atoi(arg1);
+     arg2 = SCmd.next();
+  }
+  if (arg2 != NULL) {
+     *penStepsEBB = atoi(arg2);
+     arg3 = SCmd.next();
+  }
+  if (arg3 != NULL) {
+     *rotStepsEBB = atoi(arg3);

-       if ( (penStepsEBB==0) && (rotStepsEBB==0) ) {
-          delay(duration);
-		  sendAck();
-	   }
-       if ( (penStepsEBB!=0) || (rotStepsEBB!=0) )  {
-	sendAck();
-//################### Move-Code Start ############################################################
-           //Turn on Motors, if they are off....
-                   motorsOn();
-		   //incoming EBB-Steps will be multiplied by 16, then Integer-maths is done, result will be divided by 16
-		   // This make thinks here really complicated, but floating point-math kills performance and memory, believe me... I tried...
-		   long rotSteps =   (  (long)rotStepsEBB * 16 / rotStepCorrection) + (long)rotStepError;	//correct incoming EBB-Steps to our microstep-Setting and multiply  by 16 to avoid floatingpoint...
-		   long penSteps =   (  (long)penStepsEBB * 16 / penStepCorrection) + (long)penStepError;
-		   int rotStepsToGo = (int) (rotSteps/16);		//Calc Steps to go, which are possible on our machine
-		   int penStepsToGo = (int) (penSteps/16);
-		   rotStepError = (long)rotSteps - ((long) rotStepsToGo * (long)16);	// calc Position-Error, if there is one
-		   penStepError = (long)penSteps - ((long) penStepsToGo * (long)16);
-		   long temp_rotSpeed =  ((long)rotStepsToGo * (long)1000 / (long)duration );	// calc Speed in Integer Math
-		   long temp_penSpeed =  ((long)penStepsToGo * (long)1000 / (long)duration ) ;
-		   if (temp_rotSpeed <0 ) //remove sign, there is no negative Speed....
-			   temp_rotSpeed= -temp_rotSpeed;
-		   if (temp_penSpeed <0 ) //remove sign, there is no negative Speed....
-			   temp_penSpeed= -temp_penSpeed;
-		   float rotSpeed= (float) temp_rotSpeed;	// type cast
-		   float penSpeed= (float) temp_penSpeed;
-           rotMotor.move(rotStepsToGo);		// finally, let us set the target position...
-           rotMotor.setSpeed(rotSpeed);		// and the Speed!
-           penMotor.move(penStepsToGo);
-           penMotor.setSpeed( penSpeed );
-           while ( penMotor.distanceToGo() || rotMotor.distanceToGo() ) {
-				   penMotor.runSpeedToPosition(); // Moving.... moving... moving....
-				   rotMotor.runSpeedToPosition();
-			     }
-//################### Move-Code End ############################################################
-	//	   sendAck();     //Mission completed
-            }
-	  }
-   else
-      sendError();
-
-}
-
-
+     return true;
+  }
+
+  return false;
+}
+
+void doMove(uint16_t duration, int penStepsEBB, int rotStepsEBB) {
+  motorsOn();
+
+  //incoming EBB-Steps will be multiplied by 16, then Integer-maths is done, result will be divided by 16
+  // This make thinks here really complicated, but floating point-math kills performance and memory, believe me... I tried...
+  long rotSteps =   (  (long)rotStepsEBB * 16 / rotStepCorrection) + (long)rotStepError;	//correct incoming EBB-Steps to our microstep-Setting and multiply  by 16 to avoid floatingpoint...
+  long penSteps =   (  (long)penStepsEBB * 16 / penStepCorrection) + (long)penStepError;
+
+  int rotStepsToGo = (int) (rotSteps/16);		//Calc Steps to go, which are possible on our machine
+  int penStepsToGo = (int) (penSteps/16);
+
+  rotStepError = (long)rotSteps - ((long) rotStepsToGo * (long)16);	// calc Position-Error, if there is one
+  penStepError = (long)penSteps - ((long) penStepsToGo * (long)16);
+
+  long temp_rotSpeed =  ((long)rotStepsToGo * (long)1000 / (long)duration );	// calc Speed in Integer Math
+  long temp_penSpeed =  ((long)penStepsToGo * (long)1000 / (long)duration ) ;
+
+  if (temp_rotSpeed <0 ) //remove sign, there is no negative Speed....
+    temp_rotSpeed= -temp_rotSpeed;
+
+  if (temp_penSpeed <0 ) //remove sign, there is no negative Speed....
+    temp_penSpeed= -temp_penSpeed;
+
+  float rotSpeed= (float) temp_rotSpeed;	// type cast
+  float penSpeed= (float) temp_penSpeed;
+
+  rotMotor.move(rotStepsToGo);		// finally, let us set the target position...
+  rotMotor.setSpeed(rotSpeed);		// and the Speed!
+
+  penMotor.move(penStepsToGo);
+  penMotor.setSpeed( penSpeed );
+
+  while ( penMotor.distanceToGo() || rotMotor.distanceToGo() ) {
+    penMotor.runSpeedToPosition(); // Moving.... moving... moving....
+    rotMotor.runSpeedToPosition();
+  }
+}
+
 void setPen(){
   int cmd;
   int value;


feat: Add external antenna support

feat: Add external antenna support

--- src/DryAgeMeat.ino
+++ src/DryAgeMeat.ino
@@ -10,6 +10,7 @@
 DryAgeMeat dryAgeMeat;

 SYSTEM_THREAD(ENABLED);
+STARTUP(WiFi.selectAntenna(ANT_AUTO));

 void setup(void) {
   dryAgeMeat.setup();


add sensor reading - ping

add sensor reading - ping

--- Foam.ino
+++ Foam.ino
@@ -2,21 +2,24 @@
 #include <Ethernet.h>
 #include <ArduinoJson.h>

+const int pingPin = 7;
+const int bufferSize = 160;
+
 // Enter a MAC address and IP address for your controller below.
-// The IP address will be dependent on your local network:
 byte mac[] = {
   0x90, 0xA2, 0XDA, 0x00, 0x45, 0xBA
 };
+
+// The IP address will be dependent on your local network:
 IPAddress ip(192, 168, 1, 170);

 // Enter the IP address of the server you're connecting to:
-IPAddress server(192, 168, 1, 6);
-//char server[] = "192.168.1.2";
+IPAddress server(192, 168, 1, 254);

 // Initialize the Ethernet client library
 EthernetClient client;

-JsonObject& createJsonObject(){
+JsonObject& createJsonObject(float value){
   StaticJsonBuffer<500> jsonBuffer;

   JsonObject&  contextElement = jsonBuffer.createObject();
@@ -25,11 +28,11 @@
   contextElement["id"] = "Room1";
   JsonArray& attributes = contextElement.createNestedArray("attributes");

-
   JsonObject& attribute = jsonBuffer.createObject();
   attribute["name"] = "distance";
   attribute["type"] = "float";
-  attribute["value"] = "10";
+  attribute["value"].set(value,4);
+  //
   attributes.add(attribute);

   JsonObject& root = jsonBuffer.createObject();
@@ -40,72 +43,89 @@
   return root;
 }

+float readSensor(){
+  float cm;
+  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
+  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
+  pinMode(pingPin, OUTPUT);
+  digitalWrite(pingPin, LOW);
+  delayMicroseconds(2);
+  digitalWrite(pingPin, HIGH);
+  delayMicroseconds(5);
+  digitalWrite(pingPin, LOW);
+
+  // The same pin is used to read the signal from the PING))): a HIGH
+  // pulse whose duration is the time (in microseconds) from the sending
+  // of the ping to the reception of its echo off of an object.
+  pinMode(pingPin, INPUT);
+
+  float distance = pulseIn(pingPin, HIGH);
+
+  return microsecondsToCentimeters(distance);
+}
+
+float microsecondsToCentimeters(float microseconds)
+{
+  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
+  // The ping travels out and back, so to find the distance of the
+  // object we take half of the distance travelled.
+  return (microseconds / 29 / 2) / 100;
+}

 void setup() {

-  // start the Ethernet connection:
-  //Ethernet.begin(mac, ip);
   // Open serial communications and wait for port to open:
   Serial.begin(9600);
+
+  // start the Ethernet connection:
   if (Ethernet.begin(mac) == 0) {
     Serial.println("Failed to configure Ethernet using DHCP");
     // no point in carrying on, so do nothing forevermore:
     // try to congifure using IP address instead of DHCP:
     Ethernet.begin(mac, ip);
   }
+
   // give the Ethernet shield a second to initialize:
   delay(1000);
-
-  Serial.println("connecting...");
-
-  // if you get a connection, report back via serial:
-  if (client.connect(server, 1026)) {
-    JsonObject& x = createJsonObject();
-    Serial.println("connected");
-    client.println("POST /v1/updateContext HTTP/1.1");
-    client.println("Host: 192.168.1.6:1026");
-    client.println("User-Agent: Arduino/1.1");
-    client.println("Connection: close");
-    client.println("Content-Type: application/json");
-    client.print("Content-Length: ");
-    client.println(159);
-    client.println();
-    x.printTo(client);
-    client.println();
-    Serial.println("JSON Sent");
-  }
-  else {
-    // if you didn't get a connection to the server:
-    Serial.println("connection failed");
-  }
 }

 void loop()
 {
   // if there are incoming bytes available
   // from the server, read them and print them:
-  if (client.available()) {
-    char c = client.read();
-    Serial.print(c);
+  Serial.println("connecting...");
+  if (client.connect(server, 1026)) {
+    //
+      float value = readSensor();
+      Serial.println(value);
+      delay(1000);
+      JsonObject& data = createJsonObject(value);
+      client.println("POST /v1/updateContext HTTP/1.1");
+      client.println("Host: 192.168.1.254:1026");
+      client.println("User-Agent: Arduino/1.1");
+      client.println("Connection: close");
+      client.println("Accept: application/json;");
+      client.println("Content-Type: application/json;");
+      client.print("Content-Length: ");
+      client.println(bufferSize);
+      client.println();
+      data.printTo(client);
+      client.println();
+      Serial.println("JSON Sent");
+      //
+      if (client.available()) {
+        char c = client.read();
+        Serial.print(c);
+      }
+      client.stop();
   }
-
-  // as long as there are bytes in the serial queue,
-  // read them and send them out the socket if it's open:
-  /*while (Serial.available() > 0) {
-    char inChar = Serial.read();
-    if (client.connected()) {
-      client.print(inChar);
-    }
-  }*/

   // if the server's disconnected, stop the client:
   if (!client.connected()) {
     Serial.println();
     Serial.println("disconnecting.");
-    client.stop();
+    //client.stop();
     // do nothing:
-    while (true);
-  }else{
-    //client.println("from ard");
+    //while (true);
   }
 }


fix blynk

fix blynk

--- wled00/wled16_blynk.ino
+++ wled00/wled16_blynk.ino
@@ -58,18 +58,21 @@
 BLYNK_WRITE(V4)
 {
  effectCurrent = param.asInt()-1;//fx
- colorUpdated(9);
+ strip.setMode(effectCurrent);
+ colorUpdated(6);
 }

 BLYNK_WRITE(V5)
 {
  effectSpeed = param.asInt();//sx
+ strip.setSpeed(effectSpeed);
  colorUpdated(6);
 }

 BLYNK_WRITE(V6)
 {
  effectIntensity = param.asInt();//ix
+ strip.setIntensity(effectIntensity);
  colorUpdated(6);
 }


to fit on display

to fit on display

--- init.ino
+++ init.ino
@@ -55,7 +55,7 @@

 void init_lcd() {
 	lcd.begin(16, 2);
-	lcd.print(F("LED Control System"));
+	lcd.print(F("LED Control"));
 }

 void init_timing() {


Only report CSV files.

Only report CSV files.

--- SimpleCSV.ino
+++ SimpleCSV.ino
@@ -124,6 +124,13 @@
       continue;
     }

+    // skip anything that is not a csv
+    if (dir.name[8]  != 'C' ||
+        dir.name[9]  != 'S' ||
+        dir.name[10] != 'V' ) {
+      continue;
+    }
+
     Serial.print("read ");
     cbPrintFilename(filename, dir);
     Serial.print(filename);


add temp fn

add temp fn

--- weather-clock.ino
+++ weather-clock.ino
@@ -1,5 +1,3 @@
-
-
 #include <SPI.h>
 #include "WiFi101.h"
 #include "keys.h"
@@ -28,12 +26,17 @@
 StaticJsonBuffer<600> jsonBuffer;
 char c;
 int i = 0;
-char charArr[600];
+String response = "";
 char json[600];
 // Initialize the Ethernet client library
 // with the IP address and port of the server
 // that you want to connect to (port 80 is default for HTTP):
 WiFiClient client;
+
+void setLEDColor(temp) {
+  // if temp is under 60 degrees, find the difference from 60 and multiply that by 4.25 to find the G value (B stays at 255)
+  // if the temperature is above 60 degrees, increase the G value by 5 (R stays at 255)
+}

 void setup() {
   pixels.begin(); // This initializes the NeoPixel library.
@@ -78,19 +81,20 @@

 void loop() {
   pixels.setPixelColor(0, 245,51,255);
+  pixels.setPixelColor(1, 255,0,0);
   pixels.show();

   while(client.available()) {
     c = client.read();
-    Serial.write(c);
-    charArr[i] = c;
+    // Serial.write(c);
+    response += c;
+    Serial.println(response);
     i++;
   }

-
-  JsonObject& root = jsonBuffer.parseObject(charArr);
+  // JsonObject& root = jsonBuffer.parseObject(charArr);
   // char target[600];
   // root.printTo(target, root.measureLength() + 1);
   // Serial.println(target);


Bump version ID

Bump version ID

--- wled00/wled00.ino
+++ wled00/wled00.ino
@@ -90,7 +90,7 @@
  #endif

 //version code in format yymmddb (b = daily build)
-#define VERSION 2001191
+#define VERSION 2001262

 char versionString[] = "0.9.0-b2";


Fixed the threshold bug.

Fixed the threshold bug.

--- BackEnd/BackEnd.ino
+++ BackEnd/BackEnd.ino
@@ -478,32 +478,48 @@
   // Open File
   FILE *fp;
   char sJsonFile[CONFIG_FILE_MAX_SIZE];
+  memset(sJsonFile,'\0',CONFIG_FILE_MAX_SIZE);

   // Read file
   fp = fopen(_sFullFilePath, "r");
 //  Serial.println("File Open");
+
+  #ifdef DEBUG_CAT
+    trace_info("%s(): File: %s\n", __func__, _sFullFilePath);
+  #endif
+
   if( fp )
   {
     if( !fgets(sJsonFile, CONFIG_FILE_MAX_SIZE, fp) )
     {
- //     Serial.print("ERROR empty file: ");
- //     Serial.println(_sFullFilePath);
+      /*
+      #ifdef DEBUG_CAT
+        trace_info("%s(): ERROR reading file. Content: %s\n", __func__, sJsonFile);
+      #endif
+      */
+
+      Serial.print("ERROR reading file. Content: ");
+//      Serial.println(sJsonFile);

       // The file is empty for some reason. Let's use the standard init function
       //initBoardState();
       return;
     }
-    /*
-    else
-    {
-      Serial.println(sJsonFile);
-    }
-    */
+    else
+    {
+      /*
+      #ifdef DEBUG_CAT
+        trace_info("%s(): SUCCESS reading file. Content: %s\n", __func__, sJsonFile);
+      #endif
+      */
+      Serial.print("SUCCESS reading file. Content: ");
+//      Serial.println(sJsonFile);
+    }
   }
   else
   {
- //    Serial.print("ERROR opening file: ");
-//     Serial.println(_sFullFilePath);
+     Serial.print("ERROR opening file: ");
+     Serial.println(_sFullFilePath);
      return;
   }
   /*
@@ -521,7 +537,8 @@

   // Parse file
   aJsonObject *poMsg = aJson.parse(sJsonFile);
-//  Serial.println("Parse File");
+  Serial.println("Parse File");
+  Serial.println(sJsonFile);

   if( poMsg )
   {
@@ -970,8 +987,28 @@

 float getScaledPinValue(int _iInPinNum)
 {
-  //return (g_aPins[_iInPinNum].value - g_aPins[_iInPinNum].input_min)/(g_aPins[_iInPinNum].input_max - g_aPins[_iInPinNum].input_min);
-  return (getFilteredPinValue(_iInPinNum) - g_aPins[_iInPinNum].input_min)/(g_aPins[_iInPinNum].input_max - g_aPins[_iInPinNum].input_min);
+
+  // No damping
+  if( g_aPins[_iInPinNum].input_max != g_aPins[_iInPinNum].input_min )
+  {
+    if( g_aPins[_iInPinNum].value >=  g_aPins[_iInPinNum].input_max)
+    {
+      return 1.0;
+    }
+    else if( g_aPins[_iInPinNum].value <= g_aPins[_iInPinNum].input_min )
+    {
+      return 0.0;
+    }
+    else
+    {
+      // No Damping
+      return (g_aPins[_iInPinNum].value - g_aPins[_iInPinNum].input_min)/(g_aPins[_iInPinNum].input_max - g_aPins[_iInPinNum].input_min);
+      // Damping Enabled
+      //  return (getFilteredPinValue(_iInPinNum) - g_aPins[_iInPinNum].input_min)/(g_aPins[_iInPinNum].input_max - g_aPins[_iInPinNum].input_min);
+    }
+  }
+
+  return 0.0;
 }

 float getFilteredPinValue(int _iInPinNum)
@@ -1742,15 +1779,16 @@
   // Initi some global variables
   g_last_print = millis();

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

   //Serial.println("Starting WebSocket");
   initWebsocket();
@@ -1770,7 +1808,7 @@
     updateBoardState();

 // TESTING
-//  getSerialCommand();
+  getSerialCommand();

   if (millis() - g_last_print > 1000)
   {
@@ -1818,7 +1856,8 @@
     {
     case UP:
 //      g_iNewCode = 0;
-//      initBoardStateFromFile(BOARD_CONFIG_FILE_FULL_PATH);
+      Serial.println("Init from File.");
+      initBoardStateFromFile(BOARD_CONFIG_FILE_FULL_PATH);
        //      g_iWriteToFile=0;
   //     digitalWrite(13, HIGH );
       break;
@@ -1827,7 +1866,7 @@

   //         digitalWrite(13, LOW );
      // Serial.println("Writing board state to file");
-//        writeBoardStateToFile(BOARD_CONFIG_FILE_FULL_PATH);
+        writeBoardStateToFile(BOARD_CONFIG_FILE_FULL_PATH);
       // g_iWriteToFile=1;

 //        system("shutdown -r now");


Update HC-SR04.ino

Update HC-SR04.ino

--- Device/HC-SR04.ino
+++ Device/HC-SR04.ino
@@ -1,6 +1,6 @@
 //Reference Value to Get The Status of Parking
-#define parked 200
-#define fault 4000
+#define parked 100
+#define fault 4500

 //Pin Setting for the 3 Ultrasonic Sensors
 #define trigPin 13
@@ -9,11 +9,6 @@
 #define echoPin2 5
 #define trigPin3 8
 #define echoPin3 9
-
-//Flags
-boolean d1 = 0;
-boolean d2 = 0;
-boolean d3 = 0;
 /*
 //Deducting the Low Pulse fromm the Echo Pin
 unsigned long echoDeduct(uint8_t pin, uint8_t state, unsigned long timeout)
@@ -50,18 +45,18 @@
   pinMode(echoPin3, INPUT);
 }

+//
 void loop() {
   long duration, distance,duration2, distance2,duration3, distance3;
-  //Trigger Pin is made High for 10us and Wait for the Echo Pulse
   digitalWrite(trigPin, LOW);
   delayMicroseconds(2);
   digitalWrite(trigPin, HIGH);
   delayMicroseconds(10);
   digitalWrite(trigPin, LOW);
-  //Obtain the Duration from the HIGH Pulse from Echo Pin
   duration = pulseIn(echoPin, HIGH);
   distance = (duration/2) / 29.1;
   delay(300);
+
   digitalWrite(trigPin2, LOW);
   delayMicroseconds(2);
   digitalWrite(trigPin2, HIGH);
@@ -77,122 +72,119 @@
   digitalWrite(trigPin3, LOW);
   duration3 = pulseIn(echoPin3, HIGH);
   distance3 = (duration3/2) / 29.1;
-  delay(200);
-  //Parking Lot 1
-  //Send the Sensor Status for the RPi using the Serial Communication
-  if(distance < fault && distance2 < fault && distance3 < fault)
+  delay(300);
+
+  if(distance < fault && distance2 < fault && distance3 < fault) {
+  if(distance <= parked && distance2 <= parked && distance3 <= parked)
   {
-          if(distance <= parked && distance2 <= parked && distance3 <= parked)
-          {
-            Serial.write("01");
-          }
-          else if(distance <= parked && distance2 <= parked && distance3 > parked)
-          {
-            Serial.write("02");
-          }
-          else if(distance <= parked && distance2 > parked && distance3 <= parked)
-          {
-            Serial.write("03");
-          }
-          else if(distance <= parked && distance2 > parked && distance3 > parked)
-          {
-            Serial.write("04");
-          }
-          else if(distance > parked && distance2 <= parked && distance3 <= parked)
-          {
-            Serial.write("05");
-          }
-          else if(distance > parked && distance2 <= parked && distance3 > parked)
-          {
-            Serial.write("06");
-          }
-          else if(distance > parked && distance2 > parked && distance3 <= parked)
-          {
-            Serial.write("07");
-          }
-          else if(distance > parked && distance2 > parked && distance3 > parked)
-          {
-            Serial.write("08");
-          }
+    Serial.write("222");
   }
-  else
+  else if(distance <= parked && distance2 <= parked && distance3 > parked)
   {
-          if(distance > fault && distance2 <= parked && distance3 <= parked)
-          {
-            Serial.write("09");
-          }
-          else if(distance > fault && distance2 <= parked && distance3 > parked)
-          {
-            Serial.write("10");
-          }
-          else if(distance > fault && distance2 > parked && distance3 <= parked)
-          {
-            Serial.write("11");
-          }
-          else if(distance > fault && distance2 > parked && distance3 > parked)
-          {
-            Serial.write("12");
-          }
-          else if(distance <= parked && distance2 > fault && distance3 <= parked)
-          {
-            Serial.write("13");
-          }
-          else if(distance <= parked && distance2 > fault && distance3 > parked)
-          {
-            Serial.write("14");
-          }
-          else if(distance > parked && distance2 > fault && distance3 <= parked)
-          {
-            Serial.write("15");
-          }
-          else if(distance > parked && distance2 > fault && distance3 > parked)
-          {
-            Serial.write("16");
-          }
-          else if(distance <= parked && distance2 <= parked && distance3 > fault)
-          {
-            Serial.write("17");
-          }
-          else if(distance <= parked && distance2 > parked && distance3 > fault)
-          {
-            Serial.write("18");
-          }
-          else if(distance > parked && distance2 <= parked && distance3 > fault)
-          {
-            Serial.write("19");
-          }
-          else if(distance > parked && distance2 > parked && distance3 > fault)
-          {
-            Serial.write("20");
-          }
-            else if(distance > fault && distance2 > fault && distance3 <= parked)
-          {
-            Serial.write("21");
-          }
-          else if(distance > fault && distance2 > fault && distance3 > parked)
-          {
-            Serial.write("22");
-          }
-          else if(distance <= parked && distance2 > fault && distance3 > fault)
-          {
-            Serial.write("23");
-          }
-          else if(distance > parked && distance2 > fault && distance3 > fault)
-          {
-            Serial.write("24");
-          }
-          else if(distance > fault && distance2 <= parked && distance3 >fault)
-          {
-            Serial.write("25");
-          }
-          else if(distance > fault && distance2 > parked && distance3 >fault)
-          {
-            Serial.write("26");
-          }
-          else if(distance > fault && distance2 > fault && distance3 > fault)
-          {
-            Serial.write("27");
-          }
+    Serial.write("221");
+  }
+  else if(distance <= parked && distance2 > parked && distance3 <= parked)
+  {
+    Serial.write("212");
+  }
+  else if(distance <= parked && distance2 > parked && distance3 > parked)
+  {
+    Serial.write("211");
+  }
+  else if(distance > parked && distance2 <= parked && distance3 <= parked)
+  {
+    Serial.write("122");
+  }
+  else if(distance > parked && distance2 <= parked && distance3 > parked)
+  {
+    Serial.write("121");
+  }
+  else if(distance > parked && distance2 > parked && distance3 <= parked)
+  {
+    Serial.write("112");
+  }
+  else if(distance > parked && distance2 > parked && distance3 > parked)
+  {
+    Serial.write("111");
+  }
+  }
+  else{
+  if(distance > fault && distance2 <= parked && distance3 <= parked)
+  {
+    Serial.write("322");
+  }
+  else if(distance > fault && distance2 <= parked && distance3 > parked)
+  {
+    Serial.write("321");
+  }
+  else if(distance > fault && distance2 > parked && distance3 <= parked)
+  {
+    Serial.write("312");
+  }
+  else if(distance > fault && distance2 > parked && distance3 > parked)
+  {
+    Serial.write("311");
+  }
+  else if(distance <= parked && distance2 > fault && distance3 <= parked)
+  {
+    Serial.write("232");
+  }
+  else if(distance <= parked && distance2 > fault && distance3 > parked)
+  {
+    Serial.write("231");
+  }
+  else if(distance > parked && distance2 > fault && distance3 <= parked)
+  {
+    Serial.write("132");
+  }
+  else if(distance > parked && distance2 > fault && distance3 > parked)
+  {
+    Serial.write("131");
+  }
+  else if(distance <= parked && distance2 <= parked && distance3 > fault)
+  {
+    Serial.write("223");
+  }
+  else if(distance <= parked && distance2 > parked && distance3 > fault)
+  {
+    Serial.write("213");
+  }
+  else if(distance > parked && distance2 <= parked && distance3 > fault)
+  {
+    Serial.write("123");
+  }
+  else if(distance > parked && distance2 > parked && distance3 > fault)
+  {
+    Serial.write("113");
+  }
+  else if(distance > fault && distance2 > fault && distance3 <= parked)
+  {
+    Serial.write("332");
+  }
+  else if(distance > fault && distance2 > fault && distance3 > parked)
+  {
+    Serial.write("331");
+  }
+  else if(distance <= parked && distance2 > fault && distance3 > fault)
+  {
+    Serial.write("233");
+  }
+  else if(distance > parked && distance2 > fault && distance3 > fault)
+  {
+    Serial.write("133");
+  }
+  else if(distance > fault && distance2 <= parked && distance3 >fault)
+  {
+    Serial.write("323");
+  }
+  else if(distance > fault && distance2 > parked && distance3 >fault)
+  {
+    Serial.write("313");
+  }
+  else if(distance > fault && distance2 > fault && distance3 > fault)
+  {
+    Serial.write("333");
+  }
   }
   delay(5000);
 }


adicionando usuario nodeMCU

adicionando usuario nodeMCU

--- ESP8266/ESP8266.ino
+++ ESP8266/ESP8266.ino
@@ -18,6 +18,12 @@
 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);
@@ -26,6 +32,7 @@
 	Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
   Firebase.setString("localIp", wifinder.getLocalIp());
 	attachInterrupt(BTN_PIN, readBtn, FALLING);
+  initJSONs();
 }

 void loop() {
@@ -35,6 +42,14 @@
 	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
@@ -60,7 +75,8 @@
 // Atualiza do firebase: LED
 void updateFirebase(){
 	if(!alterado) return;
-	Firebase.setBool("LED", !led_status);
+  bool ls = !led_status;
+	Firebase.setBool("LED", ls);
 	Serial.print("Definindo LED no firebase: ");
 	Serial.println(!led_status);
 	if (Firebase.failed()) {
@@ -68,6 +84,8 @@
 		Serial.println(Firebase.error());
 		return;
 	}
+  nodemcuObject["action"] = ls;
+  Firebase.push("users", nodemcuObject);
 	alterado = false;
 	attachInterrupt(BTN_PIN, readBtn, FALLING);
 }


changed includes

changed includes

--- Esp8266/Esp8266.ino
+++ Esp8266/Esp8266.ino
@@ -10,7 +10,8 @@
 MotorDriver _motorA;
 MotorDriver _motorB;

-WebSocketListener _wsl;
+ESPAsyncWebService webService(80);
+ESPAsyncWebSocketListener _wsl;

 unsigned long nextLoopInterval = 0;

@@ -44,7 +45,6 @@
   fs.begin();

   // general web server setup
-  WebService webService(80);
   webService.begin();
   // rewrite root context
   webService.getWebServer().rewrite("/", "/index.html");


fixed namespace esp8266utils

fixed namespace esp8266utils

--- Esp8266/Esp8266.ino
+++ Esp8266/Esp8266.ino
@@ -6,10 +6,10 @@
 // web server settings
 const static int PORT = 80;

-esp8266util::MotorDriver _motorA;
-esp8266util::MotorDriver _motorB;
+esp8266utils::MotorDriver _motorA;
+esp8266utils::MotorDriver _motorB;

-esp8266util::WebSocketListener _wsl;
+esp8266utils::WebSocketListener _wsl;

 void setup() {
   // logger setup
@@ -44,7 +44,7 @@
   // setup hardware components
   _motorA.begin(MOTOR_A_PWM, MOTOR_A_DIR),
       _motorB.begin(MOTOR_B_PWM, MOTOR_B_DIR),
-      esp8266util::MotorDriver::setPWMRange(PWM_RANGE);
+      esp8266utils::MotorDriver::setPWMRange(PWM_RANGE);

   // WiFi setup
   WIFI_STA_CFG.addAP(WIFI_SSID_1, WIFI_PSK_1);
@@ -72,25 +72,25 @@
   // cache-control 15 seconds
   // add dynamic http resources
   SERVER.on("/fs", HTTP_GET, [](AsyncWebServerRequest *request) {
-    SERVER.send(request, "text/json", FILESYSTEM.getStorageDetails());
+    SERVER.send(request, esp8266utils::TEXT_JSON, FILESYSTEM.getStorageDetails());
   });
   SERVER.on("/files", HTTP_GET, [](AsyncWebServerRequest *request) {
-    SERVER.send(request, "text/json", FILESYSTEM.getFileListing());
+    SERVER.send(request, esp8266utils::TEXT_JSON, FILESYSTEM.getFileListing());
   });
   SERVER.on("/sta", HTTP_GET, [](AsyncWebServerRequest *request) {
-    SERVER.send(request, "text/json", WIFI_STA_CFG.getDetails());
+    SERVER.send(request, esp8266utils::TEXT_JSON, WIFI_STA_CFG.getDetails());
   });
   SERVER.on("/ap", HTTP_GET, [](AsyncWebServerRequest *request) {
-    SERVER.send(request, "text/json", WIFI_AP_CFG.getDetails());
+    SERVER.send(request, esp8266utils::TEXT_JSON, WIFI_AP_CFG.getDetails());
   });
   SERVER.on("/esp", HTTP_GET, [](AsyncWebServerRequest *request) {
-    SERVER.send(request, "text/json", SYS_CFG.getDetails());
+    SERVER.send(request, esp8266utils::TEXT_JSON, SYS_CFG.getDetails());
   });
   SERVER.on("/motor_a", HTTP_GET, [](AsyncWebServerRequest *request) {
-    SERVER.send(request, "text/json", _motorA.getDetails());
+    SERVER.send(request, esp8266utils::TEXT_JSON, _motorA.getDetails());
   });
   SERVER.on("/motor_b", HTTP_GET, [](AsyncWebServerRequest *request) {
-    SERVER.send(request, "text/json", _motorB.getDetails());
+    SERVER.send(request, esp8266utils::TEXT_JSON, _motorB.getDetails());
   });
   // add web socket support
   _wsl.onTextMessage([](AsyncWebSocket *ws, AsyncWebSocketClient *client, AwsEventType type, AwsFrameInfo *info, uint8_t *data, size_t len) {