Memory saving static keyword

Memory saving static keyword

Added static to a bunch of the functions - saves approx 5k of program memory

--- software/firmware/LogoBotWifiScribbler/LogoBotWifiScribbler.ino
+++ software/firmware/LogoBotWifiScribbler/LogoBotWifiScribbler.ino
@@ -314,7 +314,7 @@
   pushCmd(s);
 }

-void driveTo(float x, float y) {
+static void driveTo(float x, float y) {
   // calc angle
   float ang = atan2(y-position.y, x-position.x) * 180 / PI;
   // now angle delta
@@ -370,7 +370,7 @@
   penliftServo.write(90);
 }

-void writeChar(char c) {
+static void writeChar(char c) {

     switch(c) {
       case 'A':
@@ -458,7 +458,7 @@
     }
 }

-void writeText(String s) {
+static void writeText(String s) {
   // overwrite write text
   text = s;
   text.toUpperCase();
@@ -472,13 +472,13 @@

 #define NEXTLETTER nextLetter(x + w + letterSpacing, y);

-void nextLetter(float x, float y)
+static void nextLetter(float x, float y)
 {
   pushCmd("PU");
   pushTo(x, y);
 }

-void writeA()
+static void writeA()
 {
   float x = position.x;
   float y = position.y;
@@ -494,7 +494,7 @@
   NEXTLETTER
 }

-void writeB()
+static void writeB()
 {
   float x = position.x;
   float y = position.y;
@@ -511,21 +511,21 @@
   NEXTLETTER
 }

-void writeC()
-{
-  float x = position.x;
-  float y = position.y;
-  float w = fontSize * 0.5;
-
-  pushTo(x + w, y + capHeight);
-  pushCmd("PD");
-  pushTo(x, y + capHeight);
-  pushTo(x, y);
-  pushTo(x + w, y);
-  NEXTLETTER
-}
-
-void writeD()
+static void writeC()
+{
+  float x = position.x;
+  float y = position.y;
+  float w = fontSize * 0.5;
+
+  pushTo(x + w, y + capHeight);
+  pushCmd("PD");
+  pushTo(x, y + capHeight);
+  pushTo(x, y);
+  pushTo(x + w, y);
+  NEXTLETTER
+}
+
+static void writeD()
 {
   float x = position.x;
   float y = position.y;
@@ -541,7 +541,7 @@
   NEXTLETTER
 }

-void writeE()
+static void writeE()
 {
   float x = position.x;
   float y = position.y;
@@ -559,7 +559,7 @@
   NEXTLETTER
 }

-void writeF()
+static void writeF()
 {
   float x = position.x;
   float y = position.y;
@@ -575,7 +575,7 @@
   NEXTLETTER
 }

-void writeG()
+static void writeG()
 {
   float x = position.x;
   float y = position.y;
@@ -591,7 +591,7 @@
   NEXTLETTER
 }

-void writeH()
+static void writeH()
 {
   float x = position.x;
   float y = position.y;
@@ -606,7 +606,7 @@
   NEXTLETTER
 }

-void writeI()
+static void writeI()
 {
   float x = position.x;
   float y = position.y;
@@ -618,7 +618,7 @@
   NEXTLETTER
 }

-void writeJ()
+static void writeJ()
 {
   float x = position.x;
   float y = position.y;
@@ -632,7 +632,7 @@
   NEXTLETTER
 }

-void writeK()
+static void writeK()
 {
   float x = position.x;
   float y = position.y;
@@ -648,7 +648,7 @@
   NEXTLETTER
 }

-void writeL()
+static void writeL()
 {
   float x = position.x;
   float y = position.y;
@@ -661,7 +661,7 @@
   NEXTLETTER
 }

-void writeM()
+static void writeM()
 {
   float x = position.x;
   float y = position.y;
@@ -675,20 +675,20 @@
   NEXTLETTER
 }

-void writeN()
-{
-  float x = position.x;
-  float y = position.y;
-  float w = fontSize * 0.5;
-
-  pushCmd("PD");
-  pushTo(x, y + capHeight);
-  pushTo(x + w, y);
-  pushTo(x + w, y + capHeight);
-  NEXTLETTER
-}
-
-void writeO()
+static void writeN()
+{
+  float x = position.x;
+  float y = position.y;
+  float w = fontSize * 0.5;
+
+  pushCmd("PD");
+  pushTo(x, y + capHeight);
+  pushTo(x + w, y);
+  pushTo(x + w, y + capHeight);
+  NEXTLETTER
+}
+
+static void writeO()
 {
   float x = position.x;
   float y = position.y;
@@ -702,7 +702,7 @@
   NEXTLETTER
 }

-void writeP()
+static void writeP()
 {
   float x = position.x;
   float y = position.y;
@@ -716,7 +716,7 @@
   NEXTLETTER
 }

-void writeQ()
+static void writeQ()
 {
   float x = position.x;
   float y = position.y;
@@ -735,7 +735,7 @@
   NEXTLETTER
 }

-void writeR()
+static void writeR()
 {
   float x = position.x;
   float y = position.y;
@@ -750,7 +750,7 @@
   NEXTLETTER
 }

-void writeS()
+static void writeS()
 {
   float x = position.x;
   float y = position.y;
@@ -765,7 +765,7 @@
   NEXTLETTER
 }

-void writeT()
+static void writeT()
 {
   float x = position.x;
   float y = position.y;
@@ -778,21 +778,21 @@
   NEXTLETTER
 }

-void writeU()
-{
-  float x = position.x;
-  float y = position.y;
-  float w = fontSize * 0.5;
-
-  pushTo(x, y + capHeight);
-  pushCmd("PD");
-  pushTo(x, y);
-  pushTo(x + w, y);
-  pushTo(x + w, y + capHeight);
-  NEXTLETTER
-}
-
-void writeV()
+static void writeU()
+{
+  float x = position.x;
+  float y = position.y;
+  float w = fontSize * 0.5;
+
+  pushTo(x, y + capHeight);
+  pushCmd("PD");
+  pushTo(x, y);
+  pushTo(x + w, y);
+  pushTo(x + w, y + capHeight);
+  NEXTLETTER
+}
+
+static void writeV()
 {
   float x = position.x;
   float y = position.y;
@@ -805,7 +805,7 @@
   NEXTLETTER
 }

-void writeW()
+static void writeW()
 {
   float x = position.x;
   float y = position.y;
@@ -820,7 +820,7 @@
   NEXTLETTER
 }

-void writeX()
+static void writeX()
 {
   float x = position.x;
   float y = position.y;
@@ -835,7 +835,7 @@
   NEXTLETTER
 }

-void writeY()
+static void writeY()
 {
   float x = position.x;
   float y = position.y;
@@ -850,19 +850,21 @@
   NEXTLETTER
 }

-void writeZ()
-{
-  float x = position.x;
-  float y = position.y;
-  float w = fontSize * 0.5;
-
-  pushTo(x, y + capHeight);
-  pushCmd("PD");
-  pushTo(x + w, y + capHeight);
-  pushTo(x, y);
-  pushTo(x + w, y);
-  NEXTLETTER
-}
+
+static void writeZ()
+{
+  float x = position.x;
+  float y = position.y;
+  float w = fontSize * 0.5;
+
+  pushTo(x, y + capHeight);
+  pushCmd("PD");
+  pushTo(x + w, y + capHeight);
+  pushTo(x, y);
+  pushTo(x + w, y);
+  NEXTLETTER
+}
+

 long sqr(long v) {
   return v*v;


Removed break statement added during debugging

--- firmware/firmware.ino
+++ firmware/firmware.ino
@@ -481,7 +481,6 @@
       platypus::Motor* motor = platypus::motors[motor_idx];
       motor->velocity(motor->velocity() * 0.8);
     }
-    break;
     // NOTE: WE DO NOT BREAK OUT OF THE SWITCH HERE!
   case RUNNING:
     // Rearm motors if necessary.


bug fix: HardwareSerial => SoftwareSerial

--- examples/AltPinSerial/AltPinSerial.ino
+++ examples/AltPinSerial/AltPinSerial.ino
@@ -9,7 +9,7 @@
 int txPin = 19;
 SoftwareSerial mySerial = SoftwareSerial(rxPin, txPin);
 MIDI_NAMESPACE::SerialMIDI<SoftwareSerial> serialMIDI(mySerial);
-MIDI_NAMESPACE::MidiInterface<MIDI_NAMESPACE::SerialMIDI<HardwareSerial>> MIDI((MIDI_NAMESPACE::SerialMIDI<HardwareSerial>&)serialMIDI);
+MIDI_NAMESPACE::MidiInterface<MIDI_NAMESPACE::SerialMIDI<SoftwareSerial>> MIDI((MIDI_NAMESPACE::SerialMIDI<SoftwareSerial>&)serialMIDI);

 void setup()
 {


Testing and updating TWI device drivers for ATmega2560. Adjusting TWI/RTC.

--- examples/TWI/CosaDS1307/CosaDS1307.ino
+++ examples/TWI/CosaDS1307/CosaDS1307.ino
@@ -62,6 +62,21 @@
   latest_t latest;
   rtc.read_ram(&latest, sizeof(latest), ram_pos);

+  // Set the time. Adjust below to your current time
+  DS1307::timekeeper_t now;
+#ifdef __RTC_SET_TIME__
+  now.seconds = 0;
+  now.minutes = 0x10;
+  now.hours = 0;
+  now.day = 0x02;
+  now.date = 0x21;
+  now.month = 0x01;
+  now.year = 0x13;
+  now.cntl = 0x00;
+  rtc.set_time(now);
+  latest.set = now;
+#endif
+
   // Convert bcd to binary and print latest set time
   latest.set.to_binary();
   trace.print_P(PSTR("set on "));
@@ -75,7 +90,6 @@
   trace.println();

   // Update the run time with the current time and update ram
-  DS1307::timekeeper_t now;
   rtc.get_time(now);
   latest.run = now;
   rtc.write_ram(&latest, sizeof(latest), ram_pos);


working without Alarm library, better edge detection on minute/second

--- homemonitor/homemonitor.ino
+++ homemonitor/homemonitor.ino
@@ -18,7 +18,6 @@

 // RTC Timer stuff
 #include <Time.h>
-#include <TimeAlarms.h>
 #include <Wire.h>
 #include <DS1307RTC.h>

@@ -168,10 +167,10 @@
   return true;
 }

-boolean trigger_button = false;
+boolean trigger_logging = false;
 void buttonInterrupt()
 {
-  trigger_button = true;
+  trigger_logging = true;
 }

 void updateTemperatures()
@@ -185,7 +184,7 @@
 // Read and record data to log files
 void recordData()
 {
-  Alarm.delay(250);
+  delay(250);
   Serial.println("Woo");
   if (startSD())
   {
@@ -265,53 +264,80 @@
   else
     Serial.println("RTC has set the system time");

-  updateTemperatures();
+  // Since we're using a filter call update several times to populate
+  for (int i = 0; i < 50; ++i)
+  {
+    updateTemperatures();
+    delay(20);
+  }

   // Set button to write to file
   attachInterrupt(0, buttonInterrupt, RISING);

   // Set call to update files every minute
-  Alarm.timerRepeat(60, buttonInterrupt);
+  // Alarm.timerRepeat(60, buttonInterrupt);

   // Update LCD screenevery second
-  Alarm.timerRepeat(1, triggerLCD);
+  // Alarm.timerRepeat(1, triggerLCD);

   // Done
   lcd.setCursor(0,1);
   lcd.print("Initialized.");
-  Alarm.delay(500);
+  delay(500);
   lcd.clear();
 }

+int lastMinute = -1;
+int lastSecond = -1;
 void loop()
 {
+  //////////////////////////
+  // Update Triggers
+  // Manual triggers instead of alarm on minute/second edges
+
+  // Manually trigger SD logging on new minute
+  if (minute() != lastMinute)
+  {
+    lastMinute = minute();
+    trigger_logging = true;
+  }
+
+  // Manually trigger LCD refresh on new second
+  if (second() != lastSecond)
+  {
+    lastSecond = second();
+    trigger_lcd = true;
+  }
+
+  ///////////////////////////
+  // Check Triggers
   // Called like this to avoid SPI bus collision between SD & LCD
-  if (trigger_button)
+  if (trigger_logging)
   {
     Serial.println("Trigger Button");
     recordData();
-    Alarm.delay(250);
+    delay(250);
     lcd.clear();
     if (SDCardExists)
       lcd.print("Data Logged");
     else
       lcd.print("No SD Card");
-    Alarm.delay(500);
-
-    trigger_button = false;
+    delay(500);
+
+    trigger_logging = false;
   }

   if (trigger_lcd)
   {
     // Serial.println("Trigger LCD");
-    updateTemperatures();
     updateLCD();
-    Alarm.delay(10);
+    delay(10);

     trigger_lcd = false;
   }

-  Alarm.delay(500); // Check every second
-}
-
-
+  updateTemperatures(); // Updates every loop ~ 10Hz if delay below is 100
+  delay(100);
+}
+
+


Line 108 is confusing me it yields 4,294,939,616  instead of 300,000

--- examples/RF12/RF12demo/RF12demo.ino
+++ examples/RF12/RF12demo/RF12demo.ino
@@ -86,7 +86,7 @@
 static void saveConfig () {
   // set up a nice config string to be shown on startup
   memset(config.msg, 0, sizeof config.msg);
-  strcpy(config.msg, " ");
+//  strcpy(config.msg, " ");

   byte id = config.nodeId & 0x1F;
   addCh(config.msg, '@' + id);
@@ -95,28 +95,34 @@
   if (config.nodeId & COLLECT)
     addCh(config.msg, '*');

-  strcat(config.msg, " g");
+  strcat(config.msg, " g ");
   addInt(config.msg, config.group);

-  strcat(config.msg, " @ ");
-  static byte bands[4] = { 0, 30, 60, 0 }; // 315, 433, 864, 915 Mhz
+  strcat(config.msg, " @");
+  static byte bands[4] = { 15, 30, 60, 0 }; // 315, 433, 864, 915 Mhz    // 96 - 3960 is the range of values supported by the RFM12B
   band = config.nodeId >> 6;
   addInt(config.msg, FreqFromBand(band)); // Store high order digit of frequency
   byte freq = bands[band];
-  Serial.println(freq);
-  Serial.println(config.frequency);
-  ////    Overflow of incr
-  word incr = (freq * 100) + (config.frequency*(band * 25)/100);
+                                                   Serial.println(freq);
+                                                   Serial.println(config.frequency);
+  unsigned long incr = freq * 10000;
+                                                   Serial.println(incr);
+  unsigned long wk = config.frequency*100;
+                                                   Serial.println(wk);
+  incr = wk/band*25;
+                                                   Serial.println(incr);
   ////////////////////////////////
-  Serial.println(incr);
-  word characteristic = incr/100;
-  Serial.println(characteristic);
+  unsigned long characteristic = incr/100;
+                                                   Serial.println(characteristic);
   if (characteristic < 10)
-    strcat(config.msg, "0");
+    strcat(config.msg, "x");
+  if (characteristic = 0)
+    strcat(config.msg, "z");
   addInt(config.msg, characteristic);
   strcat(config.msg, ".");
   addInt(config.msg, (incr - (characteristic * 100)));
-  strcat(config.msg, " MHz ");
+                                                   Serial.println(sizeof config.msg);
+  strcat(config.msg, " MHz .");

   config.crc = ~0;
   for (byte i = 0; i < sizeof config - 2; ++i)


code with nice curve uploaded

code with nice curve uploaded

--- Code/ProgramSerieShuntController/ProgramSerieShuntController.ino
+++ Code/ProgramSerieShuntController/ProgramSerieShuntController.ino
@@ -10,45 +10,47 @@
 #include <avr/wdt.h>
 #include <avr/pgmspace.h>

-/*******Interrupt-based Rotary Encoder Sketch*******
-by Simon Merrett, based on insight from Oleg Mazurov, Nick Gammon, rt, Steve Spence
-http://www.instructables.com/files/orig/FSD/13QB/IM3QGLHR/FSD13QBIM3QGLHR.ino */
+/*#include <Adafruit_NeoPixel.h>
+#ifdef __AVR__
+  #include <avr/power.h>
+#endif*/
+
+/* Encoder Library, for measuring quadrature encoded signals
+ * http://www.pjrc.com/teensy/td_libs_Encoder.html
+ * Copyright (c) 2011,2013 PJRC.COM, LLC - Paul Stoffregen <paul@pjrc.com>
+ *
+ * Version 1.2 - fix -2 bug in C-only code
+ * Version 1.1 - expand to support boards with up to 60 interrupts
+ * Version 1.0 - initial release
+ */

 /*******Watchdog timer by http://donalmorrissey.blogspot.co.uk/2010/04/sleeping-arduino-part-5-wake-up-via.html *********/

 /*******LCD5110_Library to control the lcd http://www.rinkydinkelectronics.com/library.php?id=48 *******/

-Encoder rotEncoder(2, 3);
-U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE|U8G_I2C_OPT_DEV_0);
-
-//static int pinA = 2;                  // Our first hardware interrupt pin is digital pin 2
-//static int pinB = 3;                  // Our second hardware interrupt pin is digital pin 3
-//volatile byte aFlag = 0;              // let's us know when we're expecting a rising edge on pinA to signal that the encoder has arrived at a detent
-//volatile byte bFlag = 0;              // let's us know when we're expecting a rising edge on pinB to signal that the encoder has arrived at a detent (opposite direction to when aFlag is set)
-//volatile byte encoderPos = 0;         // This variable stores our current value of encoder position. Change to int or uin16_t instead of byte if you want to record a larger range than 0-255
-//volatile byte oldEncPos = 0;          // Stores the last encoder position value so we can compare to the current reading and see if it has changed (so we know when to print to the serial monitor)
-volatile byte reading = 0;            // Somewhere to store the direct values we read from our interrupt pins before checking to see if we have moved a whole detent
-LCD5110 myGLCD(12,11,10,8,9);  //
-extern unsigned char SmallFont[];
-extern unsigned char TinyFont[];
-extern unsigned char MediumNumbers[];
-volatile int f_wdt=1;                 // Sleep arduino
-
-long posit = 0;
-
-// pins for the LEDs:
-
-const int analogInPinV = A0;            // Analog input pin that the potentiometer is attached to / Default = A5
-const int analogInPinA = A1;
-//const int buttonA = 2;                 // User Buttons from the rotary encoder
-//const int buttonB = 3;
-const int buttonC = 4;
-
-char selection = 0;                    // Choose true for PWM, false for no PWM
-const int  overchargeIndicatorLed = 5; // LedOutput  Default = 2
-
-
-/* Global Declaration */
+/*******U8glib.h C++ Interface Universal 8bit Graphics Library Copyright (c) 2011, olikraus@gmail.com***/
+
+/*******DECLARATIONS*******/
+/*#define LED_PIN            7
+
+Adafruit_NeoPixel LED_RGB = Adafruit_NeoPixel(1, LED_PIN, NEO_GRB + NEO_KHZ800);*/
+
+Encoder rotEncoder(2, 3);                                         // Rotary encoder object declaration
+
+U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE|U8G_I2C_OPT_DEV_0);    // OLED display declaration
+
+LCD5110 myGLCD(12,11,10,8,9);                                     // LCD display declaration
+
+volatile int f_wdt=1;                                             // Sleep arduino
+
+long posit = 0;                                                   // This value will be the previous value of the position of the rotary encoder
+
+const int analogInPinV = A0;                 // Analog input pin that the potentiometer (Voltmeter) is attached to / Default = A0
+const int analogInPinA = A1;                 // Analog input pin that the potentiometer (Ammeter) is attached to / Default = A1
+const int buttonC = 4;                       // Digital input pin that the button of the rotary encoder is attached to / Default = 4
+
+char selection = 0;                          // Choose true for PWM, false for no PWM
+const int  overchargeIndicatorLed = 5;       // LedOutput  Default = 2

 float VinMax;                                // Maximum Input Voltage Default = 4
 unsigned int R1;                             // Bottom resistance Kohm Default = 10
@@ -57,9 +59,8 @@
 float hysteresis ;                           // Value of the hysteresis
 float setpointHigh = (VinMax + hysteresis);  // Set setpointHigh Caution the battery may go beyond the overcharge
 float setpointLow = (VinMax - hysteresis) ;  // Set setpointLow
-unsigned int times;
+unsigned int times;                          // Defines the time between two points when drawing the curve
 unsigned char cpt =0;
-bool stateLCD =0;

 int limitOverchargeInAnalog;                 // Limit of the overcharge in analog value
 int limitSetpointHighInAnalog;               // Limit of the setpointhigh in analog value
@@ -72,59 +73,51 @@
 unsigned char intensity;                     // Used to set the intensity of the led with PWM control
 char pourcentageIntensity;
 int intensityInPercent;
-bool oldValue = 0;
+unsigned char curveCpt = 0;
+float curveTab[120] ;
 byte xCurve = 0;
-int arrayVin[83];

 const char serialDisplayVoltage[] PROGMEM  = {"Actual Voltage : "};
-int k;
-char myChar;
 char state = 0;
 bool testFirstSleep = HIGH;
 bool testCase5 = LOW;

-/* Value read from the pot */
+/* Value read from the potentiometers */
 int sensorValue = 0;
-int ampvalue = 0;
+//int ampvalue = 0;

 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 ///////////SETUP//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 void setup() {
+  char i = 0;
   // put your setup code here, to run once:
   // initialize serial:
   Serial.begin(9600);

-  pinMode(2, INPUT_PULLUP);             // Set pinA as an input, pulled HIGH to the logic voltage (5V or 3.3V for most cases)
-  pinMode(3, INPUT_PULLUP);             // Set pinB as an input, pulled HIGH to the logic voltage (5V or 3.3V for most cases)
-  //attachInterrupt(0,2,RISING);          // Set an interrupt on PinA, looking for a rising edge signal and executing the "PinA" Interrupt Service Routine (below)
-  //attachInterrupt(1,3,RISING);          // Set an interrupt on PinB, looking for a rising edge signal and executing the "PinB" Interrupt Service Routine (below)
-  pinMode(overchargeIndicatorLed, OUTPUT); // Set the LED indicator in OUTPUT mode
-  pinMode(13, OUTPUT);                     // Set the pin 13 as an output
-  digitalWrite(13,HIGH);                   // Set the pin 13 to HIGH (that turns on the display's blue light so we can see something)
-  //pinMode(buttonA, INPUT_PULLUP);          // Initialize the user buttons
-  //pinMode(buttonB, INPUT_PULLUP);
-  pinMode(buttonC, INPUT_PULLUP);
-
-  initEEPROMValue();                       // initialization of VinMax, maxControllerVoltage, R1, R2, hysteresis and times with the last values stored in the EEPROM
-  initLCD(500);                            // Setup the WDT
-
-  MCUSR &= ~(1<<WDRF);                     // Clear the reset flag
-
-  /* In order to change WDE or the prescaler, we need to
-  * set WDCE (This will allow updates for 4 clock cycles).
-  */
-  WDTCSR |= (1<<WDCE) | (1<<WDE);
-
-  /* set new watchdog timeout prescaler value */
-  WDTCSR = 1<<WDP0 | 1<<WDP1; /* 0.125 seconds */
-
-  /* Enable the WD interrupt (note no reset). */
-  WDTCSR |= _BV(WDIE);
-
-  //Serial.println("Initialisation complete.");
-  delay(100); //Allow for serial print to complete.
+  pinMode(2, INPUT_PULLUP);                 // Set pinA as an input, pulled HIGH to the logic voltage (5V or 3.3V for most cases)
+  pinMode(3, INPUT_PULLUP);                 // Set pinB as an input, pulled HIGH to the logic voltage (5V or 3.3V for most cases)
+  //attachInterrupt(0,2,RISING);            // Set an interrupt on PinA, looking for a rising edge signal and executing the "PinA" Interrupt Service Routine (below)
+  //attachInterrupt(1,3,RISING);            // Set an interrupt on PinB, looking for a rising edge signal and executing the "PinB" Interrupt Service Routine (below)
+  pinMode(overchargeIndicatorLed, OUTPUT);  // Set the LED indicator in OUTPUT mode
+  pinMode(13, OUTPUT);                      // Set the pin 13 as an output
+  digitalWrite(13,HIGH);                    // Set the pin 13 to HIGH (that turns on the display's blue light so we can see something)
+  pinMode(buttonC, INPUT_PULLUP);           // Initialize the encoder button
+
+  initEEPROMValue();                        // initialization of VinMax, maxControllerVoltage, R1, R2, hysteresis and times with the last values stored in the EEPROM
+  initOLED(500);                             // Setup the WDT
+
+  MCUSR &= ~(1<<WDRF);                      // Clear the reset flag
+  WDTCSR |= (1<<WDCE) | (1<<WDE);           // In order to change WDE or the prescaler, we need to set WDCE (This will allow updates for 4 clock cycles).
+  WDTCSR = 1<<WDP0 | 1<<WDP1;               // Set new watchdog timeout prescaler value (0.125 seconds)
+  WDTCSR |= _BV(WDIE);                      // Enable the WD interrupt (note no reset)
+  for (i = 0; i<120; i++)
+    {
+      curveTab[i]= 0;
+    }
+
+  delay(100);                               //Allow for serial print to complete.
 }

@@ -141,24 +134,18 @@
 //    ampvalue = analogRead(analogInPinA);
 //    Serial.println("current:");
 //    Serial.println(ampvalue);
-    configureSelection();         // Changes the value of "selection" depending on the position of the encoder
-    seriesRegulator();            // Write 0 in the parenthesis for no PWM or 1 for the PWM //default selection
-    displayLCD(selection);        // Default selection
-    displaySerialInformation();   // Read the global declaration in order to display information on the serial monitor
-    callCurveDisplay();           // Draw the curve and the battery limit
+    configureSelection();           // Changes the value of "selection" depending on the position of the encoder
+    seriesRegulator();              // Write 0 in the parenthesis for no PWM or 1 for the PWM //default selection
+    displayOLED(selection);         // Default selection
+    displaySerialInformation();     // Read the global declaration in order to display information on the serial monitor
+
+    Serial.println("curveCpt");
+    Serial.println(curveCpt);

-    Serial.println(xCurve);
-
-    enableMenu(testButtonC());    // Displays the menu if you press the rotary encoder // You can change Vlim, Vmax, R1, R2, hysteresis, times and decide if you the arduino to sleep depending on the position of the encoder
-
-    //if(oldEncPos != encoderPos)   // Updates the position of the encoder
-    //{
-    //  oldEncPos = encoderPos;
-    //}
+    enableMenu(testButtonC());      // Displays the menu if you press the rotary encoder // You can change Vlim, Vmax, R1, R2, hysteresis, times and decide if you the arduino to sleep depending on the position of the encoder
     f_wdt = 0;
-
-    /* Re-enter sleep mode. */
-    enterSleepArduino();
+
+    enterSleepArduino();            // Re-enter sleep mode
   }
   else
   {
@@ -172,22 +159,10 @@
 ///////FUNCTION/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

-
-//bool CheckButtonA(void)
-//{
-//
-//  if(digitalRead(buttonA) == LOW)
-//  {
-//    //something
-//  }
-//  else
-//  {
-//    //an other thing
-//  }
-//}
-
-void displaySerialInformation()                      // Read the global declaration in order to display information on the serial monitor // 0 for all value
-{
+void displaySerialInformation()                                                              // Read the global declaration in order to display information on the serial monitor // 0 for all value
+{
+  int k;
+  char myChar;
   int len = strlen_P(serialDisplayVoltage);
   for (k = 0; k < len; k++)
   {
@@ -375,7 +350,7 @@
 }

-void initLCD( int tempo )                         // Initialize the LCD
+void initOLED( int tempo )                         // Initialize the OLED
 {
   u8g.begin();
   if ( u8g.getMode() == U8G_MODE_R3G3B2 ) {
@@ -402,11 +377,10 @@

 }

-void displayLCD(char selection)                   // Diplays the informations on the LCD
+void displayOLED(char selection)                   // Diplays the informations on the OLED
 {
   char percent;
-  char i;
-  float mappedVinMax;
+
   float mappedval;

   u8g.firstPage();
@@ -468,15 +442,18 @@

   u8g.drawHLine(5, 60, 120);
   u8g.drawLine(5, 60, 5, 35);
-  mappedVinMax=map(VinMax,0,maxControllerVoltage, 0, 25);
-  u8g.drawHLine(5, 60 - mappedVinMax, 120);
-  u8g.setColorIndex(0);
-  for (i = 5 ; i < 124; i = i +2)
-  {
-    u8g.drawPixel(i , 60 - mappedVinMax );
-  }
-  u8g.setColorIndex(255);
+
+  drawBatteryLimit();
+  curveDisplay();
   }while(u8g.nextPage());
+  if (curveCpt < 120)
+  {
+    curveCpt++;
+  }
+  else
+  {
+    curveCpt = 0;
+  }
   delay(500);
 }

@@ -1127,28 +1104,15 @@

 }

-/***************************************************
-*  Name:        enterSleep
-*
-*  Returns:     Nothing.
-*
-*  Parameters:  None.
-*
-*  Description: Enters the arduino into sleep mode.
-*
-***************************************************/
-void enterSleepArduino(void)
-{
-  set_sleep_mode(SLEEP_MODE_IDLE);   /* EDIT: could also use SLEEP_MODE_PWR_DOWN for lowest power consumption. */
+void enterSleepArduino(void)           //Enters the arduino into sleep mode
+{
+  set_sleep_mode(SLEEP_MODE_IDLE);
   sleep_enable();

-  /* Now enter sleep mode. */
   sleep_mode();
-
-  /* The program will continue from here after the WDT timeout*/
-  sleep_disable(); /* First thing to do is disable sleep. */
-
-  /* Re-enable the peripherals. */
+
+  sleep_disable();
+
   power_all_enable();
 }

@@ -1188,22 +1152,22 @@

 void drawCurve(byte numberArray)
 {
-  float mappedValueVin;
-  byte testNumberArray;
-
-  mappedValueVin=map(Vin,0,maxControllerVoltage, 0, 35);
-  u8g.drawPixel(60 - mappedValueVin, numberArray);
+  u8g.setColorIndex(1);
+  u8g.drawPixel(5 + numberArray, 60 - curveTab[numberArray]);
+  u8g.setColorIndex(255);
 }

 void drawBatteryLimit(void)
 {
-
-  //char positionX;
- // bool test =0;
+  char i;
   float mappedVinMax;
-  mappedVinMax=map(VinMax,0,maxControllerVoltage, 0, 22);
-  u8g.setColorIndex(128);
-  u8g.drawHLine(5, 60 - mappedVinMax , 120);
+  mappedVinMax=map(VinMax,0,maxControllerVoltage, 0, 25);
+  u8g.drawHLine(5, 60 - mappedVinMax, 120);
+  u8g.setColorIndex(0);
+  for (i = 5 ; i < 124; i = i +2)
+  {
+    u8g.drawPixel(i , 60 - mappedVinMax );
+  }
   u8g.setColorIndex(255);
 }

@@ -1214,63 +1178,17 @@
   analogWrite(outputPin, mappedIntensity);
 }

-
-/***************************************************
-*  Name:        ISR(WDT_vect)
-*
-*  Returns:     Nothing.
-*
-*  Parameters:  None.
-*
-*  Description: Watchdog Interrupt Service. This
-*               is executed when watchdog timed out.
-*
-***************************************************/
-ISR(WDT_vect)
+ISR(WDT_vect)                             //Watchdog Interrupt Service. This is executed when watchdog timed out
 {
   if(f_wdt == 0)
   {
-    f_wdt=1; // default 1
+    f_wdt=1;
   }
   else
   {
              //Serial.println("WDT Overrun!!!");
   }
 }
-
-
-//void PinA()
-//{
-//  cli();                                  // Stop interrupts happening before we read pin values
-//  reading = PIND & 0xC;                   // Read all eight pin values then strip away all but pinA and pinB's values
-//  if(reading == B00001100 && aFlag)       // Check that we have both pins at detent (HIGH) and that we are expecting detent on this pin's rising edge
-//  {
-//  encoderPos --;                          // Decrement the encoder's position count
-//  bFlag = 0;                              // Reset flags for the next turn
-//  aFlag = 0;                              // Reset flags for the next turn
-//  }
-//  else if (reading == B00000100)
-//  {
-//    bFlag = 1;                            // Signal that we're expecting pinB to signal the transition to detent from free rotation
-//  }
-//  sei();                                  // Restart interrupts
-//}
-//
-//void PinB(){
-//  cli();                                  // Sstop interrupts happening before we read pin values
-//  reading = PIND & 0xC;                   // Read all eight pin values then strip away all but pinA and pinB's values
-//  if (reading == B00001100 && bFlag)      // Ccheck that we have both pins at detent (HIGH) and that we are expecting detent on this pin's rising edge
-//  {
-//    encoderPos ++;                        // Increment the encoder's position count
-//    bFlag = 0;                            // Reset flags for the next turn
-//    aFlag = 0;                            // Reset flags for the next turn
-//  }
-//  else if (reading == B00001000)
-//  {
-//    aFlag = 1;                            // Signal that we're expecting pinA to signal the transition to detent from free rotation
-//  }
-//  sei();                                  // Restart interrupts
-//}

 void updateValue(void)                    // Update setpointHigh and setpointLow depending on VinMax and hysteresis
 {
@@ -1290,25 +1208,33 @@

 void curveDisplay(void)                   // Draw the curve
 {
-
-
-}
-
-bool callCurveDisplay()                   // Calls curveDisplay and drawBatteryLimit
-{
-  int pix = 5;
-
+  char i;
+  float mappedValueVin;
   if (cpt >= times)
   {
-    //curveDisplay();
-    drawCurve(pix);
-    pix++;
-    cpt=0;
-  }
-  else
-  {
-    cpt++;
-  }
-
-}
-
+    cpt = 0;
+    mappedValueVin=map(Vin,0,maxControllerVoltage, 0, 25);
+    curveTab[curveCpt] = mappedValueVin;
+  }
+  else
+  {
+    cpt++;
+  }
+  if (curveCpt < 120)
+  {
+    for (i = 0; i<curveCpt; i++)
+    {
+      drawCurve(i);
+    }
+  }
+  else
+  {
+    for (i = 0; i<120; i++)
+    {
+      curveTab[i]= 0;
+    }
+  }
+
+}
+
+


testing

testing

--- module/module_wifi.ino
+++ module/module_wifi.ino
@@ -35,6 +35,10 @@

     Serial.print(getStr);
     Serial.print(" ");
+    Serial.print(String(ID));
+    Serial.print(" ")
+    Serial.print(String(time));
+    Serial.print(" ")
     Serial.print(getStr.length());
     Serial.print(" ");
     Serial.println(cmd);


delete debug print and move font position

--- examples/kanjiDisp/kanjiDisp.ino
+++ examples/kanjiDisp/kanjiDisp.ino
@@ -1,36 +1,35 @@
 #include "Adafruit_GFX.h"
 #include "Adafruit_ILI9341.h"
-#include "../../Humblesoft_ILI9341.h"
+#include "Humblesoft_ILI9341.h"

-IMPORT_BIN("ILGH16XB.FNT", font_h);
-IMPORT_BIN("ILGZ16XB.FNT", font_z);
+IMPORT_BIN("fontx/ILGH16XB.FNT", font_h);
+IMPORT_BIN("fontx/ILGZ16XB.FNT", font_z);

 extern uint8_t font_h[], font_z[];

 Humblesoft_ILI9341 tft = Humblesoft_ILI9341();

 void setup() {
-  Serial.begin(19200);
   delay(100);
-  Serial.println("\n\nReset:");
   tft.begin();
   tft.setFontx(font_h,font_z);
   tft.setRotation(3);
+  tft.fillScreen(ILI9341_BLACK);

-  tft.fillScreen(ILI9341_BLACK);
-
   tft.setTextSize(1);
-  tft.print("HSES-LCD24漢字表示デモ\nABCDEFGHIJKLMNOPQRSTUVWXYZ\n");
-  tft.print("熊本県熊本市中央区萩原町3番9号\n");
+  tft.print("Humblesoft_ILI9341 漢字表示デモ\nABCDEFGHIJKLMNOPQRSTUVWXYZ\n");
+  tft.print("\n");
+  tft.print("このプログラムはILフォントを使用しています。");
+  tft.print("ILフォントはIPAフォントを元に作成されたfontx形式のフォントです。\n");

   tft.setTextSize(4);
   tft.setTextColor(ILI9341_GREEN);
-  tft.setCursor(0, 60);
-  tft.print("Hello世界");
-  tft.setCursor(80, 140);
+  tft.setCursor(0, tft.getCursorY() + 10);
+  tft.print("Hello世界\n");
+  tft.setCursor(80, tft.getCursorY() + 10);
   tft.setTextSize(3);
   tft.setTextColor(ILI9341_YELLOW);
-  tft.print("ILI9341");
+  tft.print("ILI9341\n");
 }

 void loop() {


Cleaned up output text, and added cal data by default

--- examples/sensorapi/sensorapi.ino
+++ examples/sensorapi/sensorapi.ino
@@ -68,6 +68,7 @@
   bno.getSystemStatus(&system_status, &self_test_results, &system_error);

   /* Display the results in the Serial Monitor */
+  Serial.println("");
   Serial.print("System Status: 0x");
   Serial.println(system_status, HEX);
   Serial.print("Self Test:     0x");
@@ -107,7 +108,7 @@
   Serial.print(" A:");
   Serial.print(accel, DEC);
   Serial.print(" M:");
-  Serial.println(mag, DEC);
+  Serial.print(mag, DEC);
 }

 /**************************************************************************/
@@ -134,7 +135,7 @@
   displaySensorDetails();

   /* Optional: Display current status */
-  // displaySensorStatus();
+  displaySensorStatus();

   bno.setExtCrystalUse(true);
 }
@@ -160,7 +161,10 @@
   Serial.print(event.orientation.z, 4);

   /* Optional: Display calibration status */
-  // displayCalStatus();
+  displayCalStatus();
+
+  /* Optional: Display sensor status (debug only) */
+  //displaySensorStatus();

   /* New line for the next sample */
   Serial.println("");


Tweaks to the button code.

Tweaks to the button code.

--- rfduino/buttons/buttons.ino
+++ rfduino/buttons/buttons.ino
@@ -31,30 +31,39 @@
   RFduinoBLE.begin();
 }

+int previousA;
+
 void loop()
 {
   digitalWrite(led_g, LOW);

-  // Sleep until RFduino_pinWake pins are HIGH
   Serial.println("sleeping");
+//
+//  Serial.println(digitalRead(button_a));
+//  Serial.println(digitalRead(button_b));
+//  Serial.println("--");
+//  return;

   RFduino_ULPDelay(INFINITE);

   digitalWrite(led_g, HIGH);

-  if (RFduino_pinWoke(button_a))
-  {
+  Serial.println(digitalRead(button_a));
+  Serial.println(digitalRead(button_b));
+
+  if (RFduino_pinWoke(button_a)) {
     Serial.println("awoke from pin 5");
     RFduinoBLE.sendInt(0);
-    RFduino_resetPinWake(button_a);
+    delay(500);
   }

-  if (RFduino_pinWoke(button_b))
-  {
+  if (RFduino_pinWoke(button_b)) {
     Serial.println("awoke from pin 6");
     RFduinoBLE.sendInt(1);
-    RFduino_resetPinWake(button_b);
+    delay(500);
   }
+  RFduino_resetPinWake(button_a);
+  RFduino_resetPinWake(button_b);
 }

 void RFduinoBLE_onAdvertisement(bool start)


Update with time

Update with time

--- inverted-pendulum.ino
+++ inverted-pendulum.ino
@@ -145,7 +145,7 @@
   Serial.println(pendulum.xEncMax);

   resetTimer = 0;
-  pendulum.update(trackEncoder.read(), thetaEncoder.read());
+  pendulum.update(trackEncoder.read(), thetaEncoder.read(), millis());
   while (abs(pendulum.xEnc) > 2)
   {
     if (resetTimer > maxTime)
@@ -156,7 +156,7 @@
     digitalWrite(DIR_PIN, pendulum.x > 0 ? LEFT : RIGHT);
     analogWrite(PWM_PIN, (pendulum.x + 0.15)*maxPwm);
     delay(10);
-    pendulum.update(trackEncoder.read(), thetaEncoder.read());
+    pendulum.update(trackEncoder.read(), thetaEncoder.read(), millis());
   }

   analogWrite(PWM_PIN, 0);
@@ -260,7 +260,7 @@
   handleCommands();

   // Update pendulum state
-  pendulum.update(trackEncoder.read(), thetaEncoder.read());
+  pendulum.update(trackEncoder.read(), thetaEncoder.read(), millis());

   // If pendulum is not inverted, generate setpoint for swinging action
   // cartPid.setpoint = pendulum.swingX(0.5);


Made sure all string literals are stored in program memory

--- frontdesk/frontdesk.ino
+++ frontdesk/frontdesk.ino
@@ -52,7 +52,7 @@
 			// Reset timer on card and disable authorization
 			sendCommand(CMD_WRITE, blockID, machineID, keyA, 0, 0);
 			delay(waitforWriteResponse);
-			Serial.println("Card reset");
+			Serial.println(F("Card reset"));
 		}
 		digitalWrite(ledPin, HIGH);
 	}


add json char arr and parseObject fn

add json char arr and parseObject fn

--- weather-clock.ino
+++ weather-clock.ino
@@ -7,7 +7,7 @@

 // using json = nlohmann::json;

-char ssid[] = "Human Condition Global 2.4GHz"; //  your network SSID (name)
+char ssid[] = WIFI_NAME; //  your network SSID (name)
 char pass[] = WIFI_PASS;    // your network password (use for WPA, or use as key for WEP)
 int keyIndex = 0;            // your network key Index number (needed only for WEP)

@@ -17,7 +17,12 @@
 //IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
 char server[] = "weatherclockserver.herokuapp.com";

+
+StaticJsonBuffer<600> jsonBuffer;
 char c;
+int i = 0;
+char charArr[600];
+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):
@@ -78,13 +83,19 @@
     // Serial.println(client.available());

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

+  // for(byte x = 0; x < sizeof(c); x++){
+  //   json[x] = c[x];
+  // }

+  JsonObject& root = jsonBuffer.parseObject(charArr);
+
+  Serial.write(root);
   // if the server's disconnected, stop the client:
   if (!client.connected()) {
     Serial.println();


SetIo: insertBits instead of insertByte: can insert less than 8 bits

--- SetTime/SetTime.ino
+++ SetTime/SetTime.ino
@@ -248,9 +248,9 @@
   Serial.println();
 }

-void insertByte(uint8_t* dst, int dstBit, uint8_t data)
-{
-  for (int bitN = 7; bitN >= 0; --bitN) {
+void insertBits(int n, uint8_t* dst, int dstBit, uint8_t data)
+{
+  for (int bitN = n - 1; bitN >= 0; --bitN) {
     *dst = *dst & ~(1 << dstBit) | ((!!(data & (1 << bitN))) << dstBit);
     if (++dstBit == 8) {
       ++dst;


Api documentation

Api documentation


Response to ping, deviceid in mqtt string

--- Arilux_AL-LC0X.ino
+++ Arilux_AL-LC0X.ino
@@ -18,15 +18,17 @@

   MQTT topics and payloads:
     State:
-      - State:    arilux/state/state        ON/OFF
-      - Command:  arilux/state/set          ON/OFF
+      - State:    arilux/<deviceid>/state/state        ON/OFF
+      - Command:  arilux/<deviceid>/state/set          ON/OFF
     Brightness:
-      - State:    arilux/brightness/state   0-255
-      - Command:  arilux/brightness/set     0-255
+      - State:    arilux/<deviceid>/brightness/state   0-255
+      - Command:  arilux/<deviceid>/brightness/set     0-255
     Color:
-      - State:    arilux/color/state        0-255,0-255,0-255
-      - Command:  arilux/color/set          0-255,0-255,0-255
-
+      - State:    arilux/<deviceid>/color/state        0-255,0-255,0-255
+      - Command:  arilux/<deviceid>/color/set          0-255,0-255,0-255
+    White:
+      - State:    arilux/<deviceid>/white/state        0-255,0-255
+      - Command:  arilux/<deviceid>/white/set          0-255,0-255
   Configuration (Home Assistant) :
     light:
       - platform: mqtt
@@ -54,16 +56,16 @@
 */

-#define IR_REMOTE
+//#define IR_REMOTE
 // TLS support, make sure to edit the fingerprint and the MQTT broker IP address if
 // you are not using CloudMQTT
-#define TLS
-//#define DEBUG_TELNET
+//#define TLS
+#define DEBUG_TELNET

 #include <ESP8266WiFi.h>        // https://github.com/esp8266/Arduino
 #include <PubSubClient.h>       // https://github.com/knolleary/pubsubclient/releases/tag/v2.6
 #ifdef IR_REMOTE
-  #include <IRremoteESP8266.h>  // https://github.com/markszabo/IRremoteESP8266
+#include <IRremoteESP8266.h>  // https://github.com/markszabo/IRremoteESP8266
 #endif
 #include <ArduinoOTA.h>
 #include "Arilux.h"
@@ -85,35 +87,52 @@
   #define     DEBUG_PRINT(x)    telnetClient.print(x)
   #define     DEBUG_PRINTLN(x)  telnetClient.println(x)
 #else
-  #define     DEBUG_PRINT(x)
-  #define     DEBUG_PRINTLN(x)
+  #define     DEBUG_PRINT(x)    Serial.print(x)
+  #define     DEBUG_PRINTLN(x)  Serial.println(x)
 #endif

 // Wi-Fi
-const char*   WIFI_SSID     = "[REDACTED]";
-const char*   WIFI_PASSWORD = "[REDACTED]";
+const char*   WIFI_SSID     = "<ssid>";
+const char*   WIFI_PASSWORD = "<password>";
+#define HOST "ARILUX%s"
+char chipid[12];

 // MQTT topics
-const char*   ARILUX_MQTT_STATE_STATE_TOPIC         = "arilux/state/state";
-const char*   ARILUX_MQTT_STATE_COMMAND_TOPIC       = "arilux/state/set";
-const char*   ARILUX_MQTT_BRIGHTNESS_STATE_TOPIC    = "arilux/brightness/state";
-const char*   ARILUX_MQTT_BRIGHTNESS_COMMAND_TOPIC  = "arilux/brightness/set";
-const char*   ARILUX_MQTT_COLOR_STATE_TOPIC         = "arilux/color/state";
-const char*   ARILUX_MQTT_COLOR_COMMAND_TOPIC       = "arilux/color/set";
+char   ARILUX_MQTT_STATE_STATE_TOPIC[44];
+char   ARILUX_MQTT_STATE_COMMAND_TOPIC[44];
+char   ARILUX_MQTT_BRIGHTNESS_STATE_TOPIC[44];
+char   ARILUX_MQTT_BRIGHTNESS_COMMAND_TOPIC[44];
+char   ARILUX_MQTT_COLOR_STATE_TOPIC[44];
+char   ARILUX_MQTT_COLOR_COMMAND_TOPIC[44];
+char   ARILUX_MQTT_WHITE_STATE_TOPIC[44];
+char   ARILUX_MQTT_WHITE_COMMAND_TOPIC[44];
+
+#define DEFARILUX_MQTT_STATE_STATE_TOPIC "arilux/%s/state/state"
+#define DEFARILUX_MQTT_STATE_COMMAND_TOPIC  "arilux/%s/state/set"
+#define DEFARILUX_MQTT_BRIGHTNESS_STATE_TOPIC "arilux/%s/brightness/state"
+#define DEFARILUX_MQTT_BRIGHTNESS_COMMAND_TOPIC "arilux/%s/brightness/set"
+#define DEFARILUX_MQTT_COLOR_STATE_TOPIC  "arilux/%s/color/state"
+#define DEFARILUX_MQTT_COLOR_COMMAND_TOPIC  "arilux/%s/color/set"
+#define DEFARILUX_MQTT_WHITE_STATE_TOPIC  "arilux/%s/white/state"
+#define DEFARILUX_MQTT_WHITE_COMMAND_TOPIC  "arilux/%s/white/set"
+const char*   TOPICPING =  "ping";
+const char*   TOPICPONG = "pong";
+

 // MQTT payloads
-const char*   ARILUX_MQTT_STATE_ON_PAYLOAD          = "ON";
-const char*   ARILUX_MQTT_STATE_OFF_PAYLOAD         = "OFF";
+const char*   ARILUX_MQTT_STATE_WHITEFULLON_PAYLOAD         = "2";
+const char*   ARILUX_MQTT_STATE_ON_PAYLOAD          = "1";
+const char*   ARILUX_MQTT_STATE_OFF_PAYLOAD         = "0";

 // MQTT buffer
-char msgBuffer[12];
+char msgBuffer[32];

 // MQTT
 const char*   MQTT_CLIENT_ID                        = "arilux";
-const char*   MQTT_SERVER_IP                        = "m21.cloudmqtt.com";
-const int     MQTT_SERVER_PORT                      = [REDACTED];
-const char*   MQTT_USER                             = "[REDACTED]";
-const char*   MQTT_PASSWORD                         = "[REDACTED]";
+const char*   MQTT_SERVER_IP                        = "192.168.1.200";
+const int     MQTT_SERVER_PORT                      = 1883;
+const char*   MQTT_USER                             = "";
+const char*   MQTT_PASSWORD                         = "";

 volatile uint8_t cmd = ARILUX_CMD_NOT_DEFINED;

@@ -179,6 +198,11 @@
     } else if (payload.equals(String(ARILUX_MQTT_STATE_OFF_PAYLOAD))) {
       if (arilux.turnOff())
         cmd = ARILUX_CMD_STATE_CHANGED;
+    } else if (payload.equals(String(ARILUX_MQTT_STATE_WHITEFULLON_PAYLOAD))) {
+      if (arilux.turnOn())
+        cmd = ARILUX_CMD_STATE_CHANGED;
+      arilux.setWhite(255,255);
+      arilux.setBrightness(255);
     }
   } else if (String(ARILUX_MQTT_BRIGHTNESS_COMMAND_TOPIC).equals(p_topic)) {
     if (arilux.setBrightness(payload.toInt()))
@@ -190,7 +214,13 @@

     if (arilux.setColor(payload.substring(0, firstIndex).toInt(), payload.substring(firstIndex + 1, lastIndex).toInt(), payload.substring(lastIndex + 1).toInt()))
       cmd = ARILUX_CMD_COLOR_CHANGED;
-  }
+    } else if (String(ARILUX_MQTT_WHITE_COMMAND_TOPIC).equals(p_topic)) {
+      uint8_t firstIndex = payload.indexOf(',');
+      if (arilux.setWhite(payload.substring(0, firstIndex).toInt(), payload.substring(firstIndex + 1).toInt()))
+        cmd = ARILUX_CMD_WHITE_CHANGED;
+    } else if (String(TOPICPING).equals(p_topic)) {
+        cmd = ARILUX_CMD_PING;
+    }
 }

 /*
@@ -208,7 +238,6 @@
       DEBUG_PRINTLN(MQTT_PASSWORD);
       DEBUG_PRINT(F("Broker: "));
       DEBUG_PRINTLN(MQTT_SERVER_IP);
-
       delay(1000);
       ESP.reset();
     }
@@ -234,6 +263,20 @@
   } else {
     DEBUG_PRINT(F("ERROR: Sending the MQTT subscribe failed. Topic: "));
     DEBUG_PRINTLN(ARILUX_MQTT_COLOR_COMMAND_TOPIC);
+  }
+  if (mqttClient.subscribe(ARILUX_MQTT_WHITE_COMMAND_TOPIC)) {
+    DEBUG_PRINT(F("INFO: Sending the MQTT subscribe succeeded. Topic: "));
+    DEBUG_PRINTLN(ARILUX_MQTT_WHITE_COMMAND_TOPIC);
+  } else {
+    DEBUG_PRINT(F("ERROR: Sending the MQTT subscribe failed. Topic: "));
+    DEBUG_PRINTLN(ARILUX_MQTT_WHITE_COMMAND_TOPIC);
+  }
+  if (mqttClient.subscribe(TOPICPING)) {
+    DEBUG_PRINT(F("INFO: Sending the MQTT subscribe succeeded. Topic: "));
+    DEBUG_PRINTLN(TOPICPING);
+  } else {
+    DEBUG_PRINT(F("ERROR: Sending the MQTT subscribe failed. Topic: "));
+    DEBUG_PRINTLN(TOPICPING);
   }
 }

@@ -432,6 +475,30 @@
       }
       cmd = ARILUX_CMD_NOT_DEFINED;
       break;
+      case ARILUX_CMD_WHITE_CHANGED:
+      snprintf(msgBuffer, sizeof(msgBuffer), "%d,%d", arilux.getWhite1Value(), arilux.getWhite2Value());
+      if (mqttClient.publish(ARILUX_MQTT_WHITE_STATE_TOPIC, msgBuffer, true)) {
+        DEBUG_PRINT(F("INFO: MQTT message publish succeeded. Topic: "));
+        DEBUG_PRINT(ARILUX_MQTT_WHITE_STATE_TOPIC);
+        DEBUG_PRINT(F(". Payload: "));
+        DEBUG_PRINTLN(msgBuffer);
+      } else {
+        DEBUG_PRINTLN(F("ERROR: MQTT message publish failed, either connection lost, or message too large"));
+      }
+      cmd = ARILUX_CMD_NOT_DEFINED;
+      break;
+      case ARILUX_CMD_PING:
+      snprintf(msgBuffer, sizeof(msgBuffer), "arilux/%s", chipid);
+      if (mqttClient.publish(TOPICPONG, msgBuffer, true)) {
+        DEBUG_PRINT(F("INFO: MQTT message publish succeeded. Topic: "));
+        DEBUG_PRINT(TOPICPONG);
+        DEBUG_PRINT(F(". Payload: "));
+        DEBUG_PRINTLN(msgBuffer);
+      } else {
+        DEBUG_PRINTLN(F("ERROR: MQTT message publish failed, either connection lost, or message too large"));
+      }
+      cmd = ARILUX_CMD_NOT_DEFINED;
+      break;
     default:
       break;
   }
@@ -468,13 +535,19 @@
 //  SETUP() AND LOOP()
 ///////////////////////////////////////////////////////////////////////////
 void setup() {
+  char host[64];
   Serial.begin(115200);
-
+  delay(500);
 #ifdef DEBUG_TELNET
   // start the Telnet server
   telnetServer.begin();
   telnetServer.setNoDelay(true);
 #endif
+  sprintf(chipid, "%08X", ESP.getChipId());
+  sprintf(host, HOST, chipid);
+  Serial.print("hostname:");
+  Serial.println(host);
+  WiFi.hostname(host);

   // setup the Wi-Fi
   setupWiFi();
@@ -492,14 +565,32 @@
   // check the fingerprint of io.adafruit.com's SSL cert
   verifyFingerprint();
 #endif
-
-  // init MQTT
+  sprintf(ARILUX_MQTT_STATE_STATE_TOPIC, DEFARILUX_MQTT_STATE_STATE_TOPIC,chipid);
+  sprintf(ARILUX_MQTT_STATE_COMMAND_TOPIC,DEFARILUX_MQTT_STATE_COMMAND_TOPIC,chipid);
+  sprintf(ARILUX_MQTT_BRIGHTNESS_STATE_TOPIC,DEFARILUX_MQTT_BRIGHTNESS_STATE_TOPIC,chipid);
+  sprintf(ARILUX_MQTT_BRIGHTNESS_COMMAND_TOPIC,DEFARILUX_MQTT_BRIGHTNESS_COMMAND_TOPIC,chipid);
+  sprintf(ARILUX_MQTT_COLOR_STATE_TOPIC,DEFARILUX_MQTT_COLOR_STATE_TOPIC,chipid);
+  sprintf(ARILUX_MQTT_COLOR_COMMAND_TOPIC,DEFARILUX_MQTT_COLOR_COMMAND_TOPIC,chipid);
+  sprintf(ARILUX_MQTT_WHITE_STATE_TOPIC,DEFARILUX_MQTT_WHITE_STATE_TOPIC,chipid);
+  sprintf(ARILUX_MQTT_WHITE_COMMAND_TOPIC,DEFARILUX_MQTT_WHITE_COMMAND_TOPIC,chipid);
   mqttClient.setServer(MQTT_SERVER_IP, MQTT_SERVER_PORT);
   mqttClient.setCallback(callback);
   connectMQTT();

   // set hostname and start OTA
-  ArduinoOTA.setHostname("arilux");
+  ArduinoOTA.setHostname(host);
+   ArduinoOTA.onStart([]() {
+      arilux.setAll(0,0,0,0,0);
+
+  });
+  ArduinoOTA.onError([](ota_error_t error) {
+    Serial.printf("Error[%u]: ", error);
+    if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
+    else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
+    else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
+    else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
+    else if (error == OTA_END_ERROR) Serial.println("End Failed");
+  });
   ArduinoOTA.begin();
 }

@@ -508,29 +599,16 @@
   // handle Telnet connection for debugging
   handleTelnet();
 #endif
-
-  yield();
-
 #ifdef IR_REMOTE
   // handle received IR codes from the remote
   handleIRRemote();
 #endif
-
-  yield();
-
   // handle commands
   handleCMD();
-
   yield();
-
   if (!mqttClient.connected()) {
     connectMQTT();
   }
   mqttClient.loop();
-
-  yield();
-
   ArduinoOTA.handle();
-
-  yield();
-}
+}


arrumando codigo, agora está funcionando, passando se qual a posição de qual botao é possivel carregar a struct com os dados do botao em questão

--- codigo.ino
+++ codigo.ino
@@ -175,17 +175,17 @@
     }
     else
     {
-        irsend.sendNEC(buttons_list[pressed_button].codeType, buttons_list[pressed_button].codeLen);
+        irsend.sendNEC(buttons_list[pressed_button].codeValue, buttons_list[pressed_button].codeLen);
         Serial.print("Sent NEC ");
-        Serial.println(buttons_list[pressed_button].codeType, HEX);
+        Serial.println(buttons_list[pressed_button].codeValue, HEX);
     }

 }
 void sendCodeSony(int pressed_button)
 {
-    irsend.sendSony(buttons_list[pressed_button].codeType, buttons_list[pressed_button].codeLen);
+    irsend.sendSony(buttons_list[pressed_button].codeValue, buttons_list[pressed_button].codeLen);
     Serial.print("Sent Sony ");
-    Serial.println(buttons_list[pressed_button].codeType, HEX);
+    Serial.println(buttons_list[pressed_button].codeValue, HEX);
 }
 void sendCodeRC5orRC6(int repeat, int pressed_button)
 {


removed test comment

removed test comment


Tweak max amplitude

Tweak max amplitude

--- Cymatic-Triangles/Cymatic-Triangles.ino
+++ Cymatic-Triangles/Cymatic-Triangles.ino
@@ -37,7 +37,7 @@
 int next_audio_tick = 0; // Refresh rate of the animation
 int next_animate_tick = 0; // Refresh rate of the animation
 float min_amplitude = 500;
-float max_amplitude = 3000;
+float max_amplitude = 2000;
 int start_hue = 0;
 int amp_sum_L = 0;
 int amp_sum_R = 0;


Switch BOOT pin before power down delay.

--- scripts/mt_loader_usb/mt_loader_usb.ino
+++ scripts/mt_loader_usb/mt_loader_usb.ino
@@ -51,8 +51,8 @@
 void board_power(boolean boot)
 {
   digitalWrite(BOARD_PWR, LOW);
-  delay(250);
   digitalWrite(BOARD_BOOT, boot ? HIGH : LOW);
+  delay(1000);
   digitalWrite(BOARD_PWR, HIGH);

   if (!board_detect(true))


minor comment change

minor comment change

--- IMUtest.ino
+++ IMUtest.ino
@@ -13,7 +13,7 @@

 // speed settings
 int  msecPerCycle = 50;
-long baud = 115200; // 115200; // 9600, 57600, 115200
+long baud = 115200; // typically 9600, 57600, 115200

 // generally have only one of the following set to TRUE, depending upon task
 bool PRINTSCREEN  = true;   // compare gyro fusion 'on' to gyro fusion 'off',


enable car detect only after start pressed; add messages for how to start and when to go

--- SlotCar.ino
+++ SlotCar.ino
@@ -15,18 +15,19 @@
   delay(3000);
   displayInit();
   timerInit();
-  detectInit();
   startInit();
+  detectDisable();
 }

 void loop() {

-  displayUpdate();
-
+  displayStart();
   waitForStartButton();
   delay(3000);
-
+
+  displayGo();
   startSequence();
+  detectEnable();

   while (1) {
     if (startPressed()) break;


check new checksum before flashing file

check new checksum before flashing file

--- FirmwareManager/src/FirmwareManager.ino
+++ FirmwareManager/src/FirmwareManager.ino
@@ -456,6 +456,10 @@
         SPIFFS.remove(LOCAL_ESP_MD5);
         SPIFFS.remove(LOCAL_ESP_INDEX_MD5);

+        SPIFFS.remove(SERVER_FPGA_MD5);
+        SPIFFS.remove(SERVER_ESP_MD5);
+        SPIFFS.remove(SERVER_ESP_INDEX_MD5);
+
         // remove legacy config data
         SPIFFS.remove("/etc/firmware_fpga");
         SPIFFS.remove("/etc/firmware_format");


potentiometer library

potentiometer library

--- NeoPixelSwitchBox/NeoPixelSwitchBox.ino
+++ NeoPixelSwitchBox/NeoPixelSwitchBox.ino
@@ -24,25 +24,11 @@

 /*
-  initialize the ring
-    What pin is it on?
-    Function to turn on/off a group of indices together - could be handled by NeoPixelLightCluster
-    randomAll()
-    rainbow()
-    spin() - set spin speed - (-100, +100), % of max - needs to operate on the individual light level
-    update() - poll and update all lights

-  Make my "lights" (NeoPixelLight)
-    What indices does it control?
-    Specify indices
-    brightness()
-    blink()
-    toggleOnOff()
-    setColor()
-
   initialize the switches/buttons
   initialize pots
   - guess I should just set everything based on the hardware to start
+  or - start with defaults and then update state once there's a change - might be trickier than it's worth

   SPIN
   Set up knob to have guarantee it's possible to stop the spin in the center of the knob - maybe with a detent?


Tweak.

Tweak.

--- temp_ctrl/temp_ctrl.ino
+++ temp_ctrl/temp_ctrl.ino
@@ -117,7 +117,7 @@
 float pidDrive;
 bool heaterIsOn;

-float iStateLim[] = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 10, 10, 25, 25, 50, 50, 100, 100, 200, 200, 400, 400 };
+float iStateLim[] = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 10, 10, 25, 25, 50, 50, 100, 100, 200, 200, 400, 400};
 int iStateLimIterator = -1; // increment before use!
 const uint8_t iStateLimSize = 27;

@@ -323,7 +323,9 @@
       turnOnTimeLeft = turnOnTime - millis();
       delay(1000);
     } while (turnOnTimeLeft > 0);
-
+
+    for (uint8_t i = 0; i < tempAvg.getSize(); i++)
+      tempAvg.push(getTemperature());
     tempZero = tempAvg.getAverage();

     if (++iStateLimIterator >= iStateLimSize) { while(1) {/*take a nop*/} }


Start join after setting join keys

Start join after setting join keys

--- MapTheThings-Arduino/MapTheThings-Arduino.ino
+++ MapTheThings-Arduino/MapTheThings-Arduino.ino
@@ -163,6 +163,8 @@
 AssignSessionCallback(NwkSKey, FLAG_NWK_SKEY_SET)
 AssignSessionCallback(AppSKey, FLAG_APP_SKEY_SET)

+void onJoin(u1_t *appskey, u1_t *nwkskey, u1_t *devaddr);
+
 #define AssignAppCallback(key, flag) \
 void assign##key##Callback(uint8_t data[], uint16_t len) { \
   debugLogData("assign" #key, data, len); \
@@ -171,6 +173,9 @@
     saveSettingBytes(offset(settings, key), settings.key, sizeof(settings.key)); \
     settings.flags |= flag; \
     saveSettingValue(offset(settings, flags), settings.flags); \
+    if ((settings.flags & FLAG_JOIN_VARS_SET)==FLAG_JOIN_VARS_SET) { \
+      loraJoin(settings.seq_no, settings.AppKey, settings.AppEUI, settings.DevEUI, onJoin); \
+    } \
   } \
 }


- use encoder lib, change pins for Bluefruit LE, work around for Android central

--- examples/HID/HID_volume/HID_volume.ino
+++ examples/HID/HID_volume/HID_volume.ino
@@ -3,32 +3,33 @@
 #include <BLEHIDPeripheral.h>
 #include <BLEMultimedia.h>

+// http://www.pjrc.com/teensy/td_libs_Encoder.html
+#include <Encoder.h>
+
 // define pins (varies per shield/board)
-#define BLE_REQ   9
-#define BLE_RDY   8
-#define BLE_RST   4
+#define BLE_REQ   10
+#define BLE_RDY   2
+#define BLE_RST   9

 #define BUTTON_PIN 5

-#define ENC_A_PIN 6
-#define ENC_B_PIN 7
+#define ENC_RIGHT_PIN 3
+#define ENC_LEFT_PIN  4
+
+//#define ANDROID_CENTRAL

 BLEHIDPeripheral bleHIDPeripheral = BLEHIDPeripheral(BLE_REQ, BLE_RDY, BLE_RST);
 BLEMultimedia bleMultimedia;

+Encoder encoder(ENC_RIGHT_PIN, ENC_LEFT_PIN);
+
 int buttonState;

 void setup() {
-  Serial.begin(9600);
-#if defined (__AVR_ATmega32U4__)
-  while(!Serial);
-#endif
+  Serial.begin(115200);

   pinMode(BUTTON_PIN, INPUT_PULLUP);
   buttonState = digitalRead(BUTTON_PIN);
-
-  pinMode(ENC_A_PIN, INPUT_PULLUP);
-  pinMode(ENC_B_PIN, INPUT_PULLUP);

   if (buttonState == LOW) {
     Serial.println(F("BLE HID Peripheral - clearing bond data"));
@@ -36,6 +37,12 @@
     // clear bond store data
     bleHIDPeripheral.clearBondStoreData();
   }
+
+  encoder.write(0);
+
+#ifdef ANDROID_CENTRAL
+  bleHIDPeripheral.setReportIdOffset(1);
+#endif

   bleHIDPeripheral.setLocalName("HID Volume");
   bleHIDPeripheral.addHID(bleMultimedia);
@@ -54,28 +61,9 @@
     Serial.println(central.address());

     while (bleHIDPeripheral.connected()) {
+      pollButton();

-      // check the button
-      int tempButtonState = digitalRead(BUTTON_PIN);
-      if (tempButtonState != buttonState) {
-        buttonState = tempButtonState;
-
-        if (buttonState == LOW) {
-          Serial.println(F("Mute"));
-          bleMultimedia.write(MMKEY_MUTE);
-        }
-      }
-
-      // check the encoder
-      int encoderState = readEncoder();
-
-      if (encoderState == -1) {
-        Serial.println(F("Volume down"));
-        bleMultimedia.write(MMKEY_VOL_DOWN);
-      } else if (encoderState == 1) {
-        Serial.println(F("Volume up"));
-        bleMultimedia.write(MMKEY_VOL_UP);
-      }
+      pollEncoder();
     }

     // central disconnected
@@ -84,21 +72,35 @@
   }
 }

-//
-// Based off of: http://www.circuitsathome.com/mcu/programming/reading-rotary-encoder-on-arduino
-//
-
-int8_t encStates[] = { 0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0 };
-uint8_t oldAB = 0;
-
-int8_t readEncoder()
-{
-  oldAB <<= 1;
-  oldAB |= digitalRead(ENC_A_PIN);
+void pollButton() {
+  // check the button
+  int tempButtonState = digitalRead(BUTTON_PIN);

-  oldAB <<= 1;
-  oldAB |= digitalRead(ENC_B_PIN);
-
-  return ( encStates[( oldAB & 0x0f )]);
+  if (tempButtonState != buttonState) {
+    buttonState = tempButtonState;
+
+    if (buttonState == LOW) {
+      Serial.println(F("Mute"));
+      bleMultimedia.write(MMKEY_MUTE);
+    }
+  }
 }

+void pollEncoder() {
+  // check the encoder
+  int encoderState = encoder.read();
+
+  if (encoderState != 0) {
+      if (encoderState > 0) {
+        Serial.println(F("Volume up"));
+        bleMultimedia.write(MMKEY_VOL_UP);
+      } else {
+        Serial.println(F("Volume down"));
+        bleMultimedia.write(MMKEY_VOL_DOWN);
+      }
+
+    encoder.write(0);
+  }
+}
+
+


fixed the bug introduced in initializeBoard in the previous commit

--- tictactoe/tictactoe.ino
+++ tictactoe/tictactoe.ino
@@ -128,14 +128,27 @@

   // 1 - Initialize the tictactoe board
   Serial.println("Initializing tictactoe squares...");
+
   for (int i = 0; i < 9; i++){
     squares[i] = new Square(8 - i, i + 1, &_sd);
   }
+  Serial.println("-Calibrating sensors.");
   calibrateSensors();
+
+  Serial.println("-Testing squares.");
+  delay(100);
   clearSquares();
+  Serial.println("--Green.");
   allGreen();
-  delay(1000);
+  delay(500);
   clearSquares();
+  Serial.println("--Red.");
+  allRed();
+  delay(500);
+  clearSquares();
+  delay(100);
+
+  Serial.println("-Squares initialized.");
   Serial.println("");
   // 2 - Initialize the baseboard peripherals
   initializeHardwarePeripherals();
@@ -262,6 +275,7 @@
   display.printText("Initializing...", 6, 1, GREEN);
   initializeRFID();
   initializeSoundPlayer();
+  Serial.println("Hardware initialized");
 }

 void initializeBoard(){
@@ -678,6 +692,7 @@
   }
 }

+
 void restartGame(){

   clearSquares();


Added filtering code

Added filtering code

--- sensor_firmware/sensor_firmware.ino
+++ sensor_firmware/sensor_firmware.ino
@@ -8,34 +8,46 @@

 int counter = 0;
 int average = 0;
+float output = 0;
+float previous_output = 0;
+int freq = 4000;

 void setup() {
     int baud_rate = 9600;
     Serial.begin(baud_rate);
+    Serial.println("Begin program");
+    // analogReference(EXTERNAL);

-    // Set sample period in microseconds for 8kHz
-    long timer_delay_us = 125;
+    // Set frequency
+    long period = ((float)1.0/(float)freq)*(1E6);
+    Serial.print("Period: ");
+    Serial.println(period);
+    long timer_delay_us = period;
+
+    // Attach timer
     Timer1.initialize(timer_delay_us);
     Timer1.attachInterrupt(interrupt_loop);
 }

 void loop() {
-    // We don't actually need anything in here since all of our
-    // logic is in the Interrupt Service Routine (ISR)
 }

 /* Here is the routine that is run when the timer interrupt goes off */
 void interrupt_loop(){
     int sensorValue = analogRead(A0);

-    // prints out an average value after 5000 samples
-    // TODO: Implement our actual filter here
-    if(counter == 5000){
-        Serial.println(sensorValue);
+    // Print out every second
+    if(counter >= freq){
+        previous_output = output;
+        output = output*0.190 + 2.753;
+        // output = 2.753;
+        Serial.println(output);
         counter = 0;
     }
+    // Sample continiously
     else{
-        average = (average + sensorValue)/2;
+        output = 0.0002*abs(sensorValue - 508) + 0.9998*(previous_output);
+        previous_output = output;
         counter++;
     }
 }


Removed commented-out code.

Removed commented-out code.

--- src/LearningRemote.ino
+++ src/LearningRemote.ino
@@ -33,16 +33,6 @@
   keyPivotCCW,
   keyHalt
 };
-
-//char * remoteKeyNames[KEYCOUNT] = {
-  //"Forward",
-  //"Back",
-  //"Left",
-  //"Right",
-  //"PivotCW",
-  //"PivotCCW",
-  //"Halt"
-//};

 IRrecv irrecv(irPin);     // create the IR receive object
 decode_results results;   // ir data goes here