fixed 5min reporting rain

fixed 5min reporting rain

--- mwsLRWHFv2/mwsLRWHFv2.ino
+++ mwsLRWHFv2/mwsLRWHFv2.ino
@@ -189,7 +189,7 @@
   {
     dailyrainin += rain_bucket_mm;
     rainHour[minutes] += rain_bucket_mm; //Increase this minute's amount of rain
-    rain5m[minutes_5m] += rain_bucket_mm; // increase this 5 mnts amout of rain
+    rain5min[minutes_5m] += rain_bucket_mm; // increase this 5 mnts amout of rain
     rainlast = raintime; // set up for next event
   }


bros, date math is hard

bros, date math is hard

--- garage_status.ino
+++ garage_status.ino
@@ -4,33 +4,42 @@
 // This #include statement was automatically added by the Particle IDE.
 #include "neopixel/neopixel.h"

-// ---- CHANGE THIS ----
+
+// ---- CUSTOMIZE ME ----
 #define PIXEL_PIN D1
 #define PIXEL_COUNT 2
 #define PIXEL_TYPE WS2812B

+// blackout means don't run during "the day", define what times that means here
+int lightupStart = 18;  // time in 24h to display - 6pm
+int lightupHours = 9;   // hours to light         - 3am
+// I'd love to use the do time ranges here but it's too hard to
+// implement without a real time/date library.  You can't easily
+// represent like 3am -- meaning the next day with a number.
+
+// ---- END CUSTOMIZE ME ----
+
+
 Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL_COUNT, PIXEL_PIN, PIXEL_TYPE);

 int doorState = -1;
-
-// don't run during "the day", define what that means here
-int blackoutStart = 3;  // 3am
-int blackoutEnd  = 18;  // 6pm
-// I'd love to use the positive inflection here but it's too hard to
-// implement without a real time/date library.  You can't easily
-// represent like 3am -- meaning the next day with a number.
-
+bool lightupEndNextDay;
+int currentHour;
+int lightupEnd;

 void setup() {
   // Serial.begin(9600);

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

   strip.begin();
-  strip.show(); // Initialize all pixels to 'off'
+  strip.show();   // Initialize all pixels to 'off'
+
   Particle.subscribe("squarism/garage/open", eventHandler);

-  // Serial.println("I'm booted!");
+  // figure out if operating time is actually next day
+  lightupEndNextDay = endTimeIsNextDay();
+  //   Serial.println("I'm booted!");
 }

 void loop() {
@@ -38,6 +47,12 @@
     Particle.connect();
   }
   Particle.process();
+
+  // Do you guys like TDD?  Do you guys like testing?  Well listen to this!
+  // ** Johnny B. Goode plays while testers cry blood **
+  // Time.setTime(1446023974);  // 2am
+  // Time.setTime(1446029100);  // 3:45am
+  // Time.setTime(1446031100);  // 4:18am

   if (isOperatingTime()) {
     switch(doorState)
@@ -54,6 +69,8 @@
     blankStrip();
     delay(60000);
   }
+
+  delay(5000);
 }

 void eventHandler(const char *event, const char *data) {
@@ -76,14 +93,35 @@
   }
 }

-bool isOperatingTime() {
-  if (!((Time.hour() >= blackoutStart) && (Time.hour() <= blackoutEnd))) {
+bool endTimeIsNextDay() {
+  if (lightupStart + lightupHours >= 24) {
     return true;
   } else {
     return false;
   }
 }

+bool isOperatingTime() {
+  currentHour = Time.hour();
+  lightupEnd = lightupStart + lightupHours;
+
+  // same day calculation
+  if ( (lightupEndNextDay == false) && ((currentHour >= lightupStart) && (currentHour < lightupEnd))) {
+    return true;
+  }
+
+  // End time is tomorrow.
+  // Let's say that operating time is 6pm to 3am.  That's 18 --> 27, 27 representing the next day.
+  // We will count time from 18 on up and then from 3 to 0.  So we measure the bleed over with the or statement below
+  // here to cover the "next day" case.
+  if ( (lightupEndNextDay == true) && (currentHour >= lightupStart) || (currentHour <= (lightupEnd - 24))) {
+    return true;
+  }
+
+  return false;
+}
+
+// Turn all the neopixels off
 void blankStrip() {
   uint32_t black = strip.Color(0, 0, 0);
   for(uint16_t i=0; i<strip.numPixels(); i++) {
@@ -100,6 +138,7 @@
   }
 }

+// Sort of a red to orange fade effect.  Pretty sweet.
 void fireRing(uint16_t wait) {
   uint16_t i, j;
   int colorStart = 95;  // a pure red
@@ -119,9 +158,9 @@
     strip.show();
     delay(wait);
   }
-
 }

+// Sort of a blue to light blue fade effect.  Soothing.
 void iceRing(uint16_t wait) {
   uint16_t i, j;
   int colorStart = 166;  // blue
@@ -141,7 +180,6 @@
     strip.show();
     delay(wait);
   }
-
 }


update fsr thread enable part

update fsr thread enable part

--- Arduino/AlphaChairArduino/AlphaChairArduino.ino
+++ Arduino/AlphaChairArduino/AlphaChairArduino.ino
@@ -20,7 +20,6 @@
 int PRESSURE = A0;
 int TEMPERATURE = A1;

-bool isFSROn = false;
 bool isTMPOn = false;

 int MAX_TMP;
@@ -64,10 +63,10 @@
     digitalWrite(INB,LOW);
   }else if(response.equals(FSR_ON)){
     Serial.println(response);
-    isFSROn= true;
+    fsrThread.enabled = true;
   }else if(response.equals(FSR_OFF)){
     Serial.println(response);
-    isFSROn= false;
+    fsrThread.enabled = false;
   }else if(response.equals(TMP_ON)){
     Serial.println(response);
     isTMPOn = true;
@@ -81,13 +80,8 @@
     readTmp();
   }

-  if(isFSROn){
-    fsrThread.enabled = true;
-    if(fsrThread.shouldRun())
+  if(fsrThread.shouldRun())
     fsrThread.run();
-  }else{
-    fsrThread.enabled = false;
-  }
 }

 // Runnable for fsrThread


Fix for loop

Fix for loop

--- ArduinoMotionStairLights.ino
+++ ArduinoMotionStairLights.ino
@@ -1,7 +1,7 @@
 /*
  * Description: Motion activated stair lights.
  * Author: Dean Montgomery
- * Version: 1.0
+ * Version: 1.1
  * Date: Aug 8, 2015
  *
  * 2 PIR sesors at the top and bottom of the stairs.
@@ -231,7 +231,7 @@
         z[2] = CRGB(random8(2,100),random8(2,100),random8(2,100));
         z[3] = c1;
         for (i=0; i<4; i++){
-          for (x = 0; x<=255; x=qadd8(x,1)){
+          for (x = 0; x<255; x=qadd8(x,1)){
             trans2 = blend(z[i],z[i+1],x);
             fill_solid(leds, NUM_LEDS, trans2);
             FastLED.show();


declare TOTAL_PIXELS

declare TOTAL_PIXELS

--- arduino-neopixel.ino
+++ arduino-neopixel.ino
@@ -1,7 +1,10 @@
 #include <Adafruit_NeoPixel.h>
+#define TOTAL_PIXELS 99
+
+// common settings :::::::::
+
 #define MAX_VAL 64 // 0 to 255 for brightness 多くのLEDを制御した場合に、色が安定しない問題を解決するために設けた制限
 #define DELAY_TIME 10
-
 // Parameter 1 = number of pixels in strip
 // Parameter 2 = pin number (most are valid)
 // Parameter 3 = pixel type flags, add together as needed:
@@ -9,7 +12,7 @@
 //   NEO_GRB     Pixels are wired for GRB bitstream
 //   NEO_KHZ400  400 KHz bitstream (e.g. FLORA pixels)
 //   NEO_KHZ800  800 KHz bitstream (e.g. High Density LED strip)
-Adafruit_NeoPixel strip = Adafruit_NeoPixel(99, 6, NEO_GRB + NEO_KHZ800);
+Adafruit_NeoPixel strip = Adafruit_NeoPixel(TOTAL_PIXELS, 6, NEO_GRB + NEO_KHZ800);

 char input[11];   // 文字列格納用
 String input_str;   // 文字列格納用


-Use ESP_LOGx log levels for serial output.

--- aquacontrol32.ino
+++ aquacontrol32.ino
@@ -286,11 +286,8 @@
   btStop();

   Serial.begin( 115200 );
-  Serial.println();
-  Serial.printf( "aquacontrol32 %s\n", SKETCH_VERSION );
-  Serial.print( "ESP32 SDK: " );
-  Serial.println( ESP.getSdkVersion() );
-  Serial.println();
+  ESP_LOGI( TAG, "aquacontrol32 %s", SKETCH_VERSION );
+  ESP_LOGI( TAG, "ESP32 SDK: %s", ESP.getSdkVersion() );

   SPI.begin( SPI_SCK_PIN, SPI_MISO_PIN, SPI_MOSI_PIN );
   SPI.setFrequency( 80000000 );
@@ -300,7 +297,8 @@
   if ( TFT_HAS_NO_MISO || tft.readcommand8( ILI9341_RDSELFDIAG ) == 0xE0 )
   {
     touch.begin();
-    Serial.println( TFT_HAS_NO_MISO ? "Forced ILI9341 start." : "ILI9341 display found." );
+    if ( TFT_HAS_NO_MISO ) ESP_LOGI( TAG, "Forced ILI9341 start." );
+    else                   ESP_LOGI( TAG, "ILI9341 display found." );
     xTaskCreatePinnedToCore(
       tftTask,                        /* Function to implement the task */
       "tftTask",                      /* Name of the task */
@@ -312,16 +310,16 @@
   }
   else
   {
-    Serial.println( "No ILI9341 found" );
-  }
-
-  Wire.begin( I2C_SDA_PIN, I2C_SCL_PIN );
+    ESP_LOGI( TAG, "No ILI9341 found" );
+  }
+
+  Wire.begin( I2C_SDA_PIN, I2C_SCL_PIN, 1000000 );

   Wire.beginTransmission( OLED_ADDRESS );
   uint8_t err = Wire.endTransmission();
   if ( err == 0 )
   {
-    Serial.printf( "Found I2C device at address 0x%x.\n", OLED_ADDRESS );
+    ESP_LOGI( TAG, "Found I2C device at address 0x%x.\n", OLED_ADDRESS );
     xTaskCreatePinnedToCore(
       oledTask,                       /* Function to implement the task */
       "oledTask",                     /* Name of the task */
@@ -333,7 +331,7 @@
   }
   else
   {
-    Serial.println( "No I2C device found." );
+    ESP_LOGI( TAG, "No I2C device found." );
   }

   xTaskCreatePinnedToCore(


Begin SPI communication dev

Begin SPI communication dev

--- ARDUINO/i2c_rx_and_servo/i2c_rx_and_servo.ino
+++ ARDUINO/i2c_rx_and_servo/i2c_rx_and_servo.ino
@@ -74,10 +74,10 @@
 #define SERVO_NUM 4

 // Assign your channel out pins
-#define FL_MOTOR_OUT_PIN 4
-#define FR_MOTOR_OUT_PIN 5
-#define BL_MOTOR_OUT_PIN 6
-#define BR_MOTOR_OUT_PIN 7
+#define FL_MOTOR_OUT_PIN A0
+#define FR_MOTOR_OUT_PIN A1
+#define BL_MOTOR_OUT_PIN A2
+#define BR_MOTOR_OUT_PIN A3

 //define Servo variables
 Servo MOTOR[SERVO_NUM];
@@ -89,11 +89,11 @@
 } *rcv_data = new int_byt[SERVO_NUM];

-
+//setup function
 void setup()
 {
   Serial.begin(9600);
-  Serial.println("multiChannels");
+  // Serial.println("multiChannels");

   pinMode(LED_PIN, OUTPUT);

@@ -115,9 +115,9 @@
   //Set servo values to min
   for (int i=0;i<SERVO_NUM;i++)
     {
-      MOTOR[i].writeMicroseconds(RC_MIN);
-    }
-
+      rcv_data[i].i =RC_MIN;
+      MOTOR[i].writeMicroseconds(rcv_data[i].i);
+    }

   // initialize i2c as slave
   // define call backs ofr I2C
@@ -129,15 +129,41 @@

 void loop()
 {
-  // noInterrupts();
-
-  //Update servo values
-  for (int i=0;i<SERVO_NUM;i++)
-    {
-      MOTOR[i].writeMicroseconds(rcv_data[i].i);
-    }
-
-  //  interrupts();
+  //nothing to do here
+}
+
+//on Receive
+void SetServos(int byteCount)
+{
+
+// the RPI shoud send 4 x 1 uint16_t (2 bytes) values
+// one for each PID updated Motor speed
+
+  digitalWrite(LED_PIN,HIGH);
+  if (byteCount == 8)
+    {
+
+      //Serial.println(Wire.available());
+
+      while(Wire.available()) {
+
+	for (int i=0;i<SERVO_NUM;i++)
+	  {
+	    rcv_data[i].b[0] = Wire.read(); //upper bits?
+	    rcv_data[i].b[1] = Wire.read(); //lower bits?
+	  }
+      }
+      //update servos
+      for (int i=0;i<SERVO_NUM;i++)
+	{
+	  MOTOR[i].writeMicroseconds(rcv_data[i].i);
+	}
+
+    }
+
+  digitalWrite(LED_PIN,LOW);
+
+  return;
 }

@@ -148,38 +174,28 @@

   union Sharedblock
   {
-    byte b[4]; // utiliser char parts[4] pour port série
-    float d;
+    byte b[2]; // utiliser char parts[4] pour port série
+    uint16_t ui;
   } RCsignal[4];

   //Note we don't use shared volatile vars
   //sot that ISRs keep priority on them
-  RCsignal[0].d=
-    (float) (unThrottleInShared-THR_MIN)/
-    (THR_MAX-THR_MIN) * 100.0;
-  RCsignal[1].d=
-     ((float) unYawInShared-(RC_MAX+RC_MIN)/2)/
-    (RC_MAX-RC_MIN) * K_YAW;
-  RCsignal[2].d=
-     ((float) unPitchInShared-(RC_MAX+RC_MIN)/2)/
-    (RC_MAX-RC_MIN) * K_PITCH;
-  RCsignal[3].d=
-     ((float) unRollInShared-(RC_MAX+RC_MIN)/2)/
-    (RC_MAX-RC_MIN) * K_ROLL;
-
-
-
-  byte data[16];
+  RCsignal[0].ui= unThrottleInShared;
+  RCsignal[1].ui= unYawInShared;
+  RCsignal[2].ui= unPitchInShared;
+  RCsignal[3].ui= unRollInShared;
+
+  byte buffer[8];
   for (int i=0;i<4;i++)
     {
-    for (int ii=0;ii<4;ii++)
+    for (int ii=0;ii<2;ii++)
       {
-	data[ii+4*i] = RCsignal[i].b[ii];
+	buffer[ii+2*i] = RCsignal[i].b[ii];
       }
     }

-  Wire.write(data,16);
+  Wire.write(buffer,8);

 }

@@ -239,25 +255,3 @@
       bUpdateFlagsShared |= ROLL_FLAG;
     }
 }
-
-
-void SetServos(int byteCount)
-{
-
-// the RPI shoud send 4 x 1 uint16_t (2 bytes) values
-// one for each PID updated Motor speed
-  if (byteCount == 8)
-    {
-      while(Wire.available()) {
-
-	for (int i=0;i<SERVO_NUM;i++)
-	  {
-	    rcv_data[i].b[0] = Wire.read(); //upper bits?
-	    rcv_data[i].b[1] = Wire.read(); //upper bits?
-
-	  }
-      }
-    }
-
-  return;
-}


Revert "Add code from JumpToAppWithOffset"

This reverts commit c8276a81cc2d5715a661cd1a3f32a5242bf05a28.

--- AnimatedGIFs.ino
+++ AnimatedGIFs.ino
@@ -62,67 +62,6 @@
 #include "GIFDecoder.h"

 #define DISPLAY_TIME_SECONDS 10
-// the assembly code must be run inside a C, not C++ function
-#ifdef __cplusplus
-extern "C" {
-#endif
-void jumpToApplicationAt0x38080() {
-  /* Load stack pointer and program counter from start of new program */
-  asm("movw r0, #0x8080");
-  asm("movt r0, #0x0003");
-  asm("ldr sp, [r0]");
-  asm("ldr pc, [r0, #4]");
-}
-#ifdef __cplusplus
-}
-#endif
-
-
-/*
- * These are the minimum peripherals that needed to be disabled to allow the
- * uTasker USB-MSD application to work.  You may need to reset more peripherals
- * depending on the application you are running, and what other peripherals
- * your sketch uses if you add more to this example than just blinking an LED
-*/
-void resetPeripherals() {
-  // set SPI back to normal
-  SPCR.disable_pins();
-  SPI0_MCR = SPI_MCR_HALT | SPI_MCR_MDIS;
-  SPI0_CTAR1 = 0;
-  SPI0_CTAR0 = 0;
-  SIM_SCGC6 &= ~(SIM_SCGC6_SPI0);
-
-
-  /* set (some of) USB back to normal */
-  NVIC_DISABLE_IRQ(IRQ_USBOTG);
-  NVIC_CLEAR_PENDING(IRQ_USBOTG);
-  SIM_SCGC4 &= ~(SIM_SCGC4_USBOTG);
-
-  /* disable all GPIO interrupts */
-  NVIC_DISABLE_IRQ(IRQ_PORTA);
-  NVIC_DISABLE_IRQ(IRQ_PORTB);
-  NVIC_DISABLE_IRQ(IRQ_PORTC);
-  NVIC_DISABLE_IRQ(IRQ_PORTD);
-  NVIC_DISABLE_IRQ(IRQ_PORTE);
-
-  /* set (some of) ADC1 back to normal */
-  // wait until calibration is complete
-  while(ADC1_SC3 & ADC_SC3_CAL);
-
-  // clear flag if calibration failed
-  if(ADC1_SC3 & 1<<6)
-    ADC1_SC3 |= 1<<6;
-
-  // clear conversion complete flag (which could trigger ISR otherwise)
-  if(ADC1_SC1A & 1<<7)
-    ADC1_SC1A |= 1<<7;
-
-  /* set some clocks back to default/reset settings */
-  MCG_C1 = MCG_C1_CLKS(2) | MCG_C1_FRDIV(4);
-  SIM_CLKDIV1 = 0;
-  SIM_CLKDIV2 = 0;
-}
-

 // range 0-255
 const int defaultBrightness = 255;


sdlib added /BB

sdlib added /BB

--- datasafe.ino
+++ datasafe.ino
@@ -22,7 +22,7 @@

 /**** ntc settings ****/

-// NFCLib nfclib;
+NFCLib nfclib;

 char nfc_key[6] = {
 	0, 0, 0, 0, 0, 0 }; // the key buffer
@@ -33,7 +33,7 @@

 /**** sd settings ****/

-// SDLib sd;
+SDLib sd;

@@ -68,10 +68,10 @@
 	ds_screen.reset();

 	// reset the sd card controller
-	// sd.setup();
+	sd.setup();

         // setup the nfc controller
-        //nfclib.setupHost();
+        nfclib.setupHost();
 }

@@ -138,12 +138,10 @@
 void doStateNfcCardLogin() {

 	// read the nfc card
-    /*
 	uint8_t uid[] = {
 		0, 0, 0, 0, 0, 0, 0   	};                    // Buffer to store the returned UID
 	uint8_t uidLength = nfclib.initTarget(&*uid);               // Length of the UID (4 or 7 bytes depending on ISO14443A card type)
 	uidLength = nfclib.printTarget();
-    */

 	// next state
 	nextState();
@@ -153,7 +151,7 @@
 	// show the data
 	ds_screen.showDataScreen();

-	// sd.showFile("test.txt");
+	//sd.showFile("test.txt");

 	delay(3000);

@@ -164,19 +162,27 @@

+/**** debug functions ****/
+
+/*
+int availableMemory() {
+    // Use 1024 with ATmega168
+    int size = 2048;
+    byte *buf;
+    while ((buf = (byte *) malloc(--size)) == NULL);
+        free(buf);
+    return size;
+}
+*/
+
+
+
 /**** arduino default functions ****/

 void setup(void) {
-        Serial.begin(115200);
-
-         while (!Serial) {
-                 ; // wait for serial port to connect. Needed for Leonardo only
-        }
-
-        Serial.println("test!!!");

 	// setup the screen
-	ds_screen.begin();
+	ds_screen.begin();

 #ifdef PROG_VERBOSE
         Serial.println(DATASAFE_MESSAGE_000);
@@ -185,6 +191,8 @@

 void loop()
 {
+//        Serial.println(availableMemory());
+
 	// working with the state pattern because we have different screens (states)
 	switch (current_state) {
 	case STATE_RESET:


Show 4 digits; colour the digits differently for clarity

--- countdown/digits.ino
+++ countdown/digits.ino
@@ -93,15 +93,15 @@
 const boolean* digits[] = {zero, one, two, three, four, five, six, seven, eight, nine};

-void showDigit(uint8_t c, uint8_t dx, uint8_t dy){
+void writeDigit(uint8_t c, uint8_t dx, uint8_t dy, CRGB* colour){
   // Digits are 3 by 5 (x by y)
   for(uint8_t y=0; y != 5; ++y){
     Serial.println();
     for(uint8_t x=0; x!=3; ++x){
       if(digits[c][x+3*y]){
-        leds[xy2i(dx+x,dy+y)] = CRGB::Red;
+        leds[xy2i(dx+x,dy+y)] = colour;
       } else {
-        leds[xy2i(dx+x,dy+y)] = CRGB::Black;
+        leds[xy2i(dx+x,dy+y)] = colour;
       }
     }
   }
@@ -113,7 +113,7 @@
   // Let the controller know we're using WS2801 leds, and give a pointer to the current colour array
   LEDS.addLeds<WS2801, RGB>(leds, NUM_LEDS);
   // Limit the brightness somewhat (scale is 0-255)
-  LEDS.setBrightness(24);
+  LEDS.setBrightness(48);

   for(uint8_t i=0; i<NUM_LEDS; ++i){
     leds[i] = CRGB::Black;
@@ -124,14 +124,15 @@
   Serial.begin(57600);
 }

-uint8_t d = 0;
+uint8_t ds[] = {0,1,2,3};
+CRGB digit_colours[] = {CRGB::Red, CRGB::OrangeRed, CRGB::Cyan, CRGB::Blue};
 void loop(){
-
-  showDigit(d,3,2);
+  for(uint8_t i=0; i!=4; ++i){
+    writeDigit(ds[i]++, (i>1?2:0) + (i%2)*5, (i>1?5:0), digit_colours[i]);
+    if(ds[i]>9) ds[i] = 0;
+  }
   LEDS.show();
   delay(5000);
-  ++d;
-  if(d>9) d = 0;
 }


todos

todos

--- crossbow.ino
+++ crossbow.ino
@@ -1,3 +1,15 @@
+/*
+
+TODO
+
+* Watchdog to go back to IDLE if frame did not completed in reasonable timer
+* Watchdog to force PPM output to LOW if RC_DATA was not received in 500ms aka filsafe
+* Telemetry feedback from RX to TX
+* Some kind of alarm when RSSI goes LOW
+* ability for RX and TX to change frequency
+* serial passtrough (?)
+
+*/
 #include <LoRa.h>
 #include "variables.h"
 #include "qsp.h"


Fixes crashes upon boot.

Fixes crashes upon boot.


Added code to disable the fona board between measurements

--- rede-firmware.ino
+++ rede-firmware.ino
@@ -134,41 +134,9 @@
   digitalWrite(MULT_B, HIGH);
   pinMode(MULT_C, OUTPUT);
   digitalWrite(MULT_C, LOW);
-
-  // Set key pin to low
-  pinMode(FONA_KEY, OUTPUT);
-  digitalWrite(FONA_KEY, LOW);
-
-  // Enables fona battery
-  pinMode(FONA_EN_BAT, OUTPUT);
-  digitalWrite(FONA_EN_BAT, HIGH);

   // Connection to the SIM800
   Serial2.begin(4800);
-
-  // See if the FONA is responding
-  if (!fona.begin(Serial2)) {
-    Serial.println(F("FONA not found"));
-    while (1);
-  }
-  Serial.println(F("FONA is OK"));
-
-  // Configure a GPRS APN, username, and password.
-  fona.setGPRSNetworkSettings(F("zap.vivo.com.br"), F(""), F(""));
-
-  // It takes around 10 seconds for the FONA to initialize
-  // We need to wait the initialization in order to enable GPRS
-  // So...
-  delay(10000);
-  for (int i = 0; i < 3 && !fona.enableGPRS(true); i++)
-  {
-    Serial.println("FONA GPRS not enabled!");
-    delay(10000);
-  }
-
-  if (!fona.enableNetworkTimeSync(true)) {
-    Serial.println(F("Failed to enable time sync"));
-  }

   calc_sensors();
 }
@@ -176,10 +144,13 @@
 void loop() {
   if (time_elapsed >= SEND_INTERVAL) {
     time_elapsed = 0;
+    // Get readings from weather shield.
+    calc_sensors();
+
+    // Enable fona
+    enable_fona();
     // Get time.
     fona.getTime(buffer+1, 25);
-    // Get readings from weather shield.
-    calc_sensors();

     // Format of the buffer:
     // <YYYY-MM-DDTHH:MM:SS-03:00>;<type1>:<value1>:{unit1};...;<typeN>:<valueN>:{unitN}
@@ -201,8 +172,6 @@
       }
     }

-    // Use dtostrf now to print data to the buffer.
-
 #if HUMIDITY_SENSOR
     // Add humidity
     len = strlen(buffer);
@@ -311,11 +280,63 @@
     } else {
       Serial.println(F("HTTP POST Sent!"));
     }
+
+    disable_fona();
   }

   // Increase counter, sleep for 1 second.
   time_elapsed++;
   delay(1000);
+}
+
+boolean enable_fona() {
+  // Set key pin to low
+  pinMode(FONA_KEY, OUTPUT);
+  digitalWrite(FONA_KEY, LOW);
+
+  // Enable fona battery
+  pinMode(FONA_EN_BAT, OUTPUT);
+  digitalWrite(FONA_EN_BAT, HIGH);
+
+  // See if the FONA is responding
+  if (!fona.begin(Serial2)) {
+    Serial.println(F("FONA not found"));
+    return false;
+  }
+  Serial.println(F("FONA is OK"));
+
+  // Configure a GPRS APN, username, and password.
+  fona.setGPRSNetworkSettings(F("zap.vivo.com.br"), F(""), F(""));
+
+  // It takes around 10 seconds for the FONA to initialize
+  // We need to wait the initialization in order to enable GPRS
+  // So...
+  delay(10000);
+  for (int i = 0; i < 4 && !fona.enableGPRS(true); i++)
+  {
+    Serial.println("FONA GPRS not enabled!");
+    delay(10000);
+  }
+
+  if (!fona.enableNetworkTimeSync(true)) {
+    Serial.println(F("Failed to enable time sync"));
+  }
+
+  Serial.println(F("Enabled fona"));
+
+  return true;
+}
+
+void disable_fona() {
+  // Set key pin to high
+  pinMode(FONA_KEY, OUTPUT);
+  digitalWrite(FONA_KEY, HIGH);
+
+  // Disable fona battery
+  pinMode(FONA_EN_BAT, OUTPUT);
+  digitalWrite(FONA_EN_BAT, LOW);
+
+  Serial.println(F("Disabled fona"));
 }

 boolean send_http_post(char *url, char *id, char *data) {
@@ -334,7 +355,8 @@
   Serial.print("POST message: ");
   Serial.println(buffer2);

-  fona.HTTP_POST_start(url, F("application/json"), (uint8_t *)buffer2, strlen(buffer2), &statuscode, &response_length);
+  fona.HTTP_POST_start(url, F("application/json"), (uint8_t *)buffer2,
+                       strlen(buffer2), &statuscode, &response_length);

   Serial.print("Status: ");
   Serial.println(statuscode);
@@ -464,8 +486,9 @@
   return (float)raw / 16.0;
 }

-//Returns the voltage of the light sensor based on the 3.3V rail
-//This allows us to ignore what VCC might be (an Arduino plugged into USB has VCC of 4.5 to 5.2V)
+// Returns the voltage of the light sensor based on the 3.3V rail
+// This allows us to ignore what VCC might be (an Arduino plugged into USB has
+// VCC of 4.5 to 5.2V)
 float get_light_level() {
   float operatingVoltage = analogRead(REFERENCE_3V3);


Fix more includes, because Arduino

Fix more includes, because Arduino

--- library/examples/MCP23017-Test/MCP23017-Test.ino
+++ library/examples/MCP23017-Test/MCP23017-Test.ino
@@ -11,7 +11,14 @@
  * 18 pullup to 5V (RST)
  */

+#include <SPI.h>
 #include <Wire.h>
+#include <Adafruit_GFX.h>
+#include <Adafruit_NeoPixel.h>
+#include <Adafruit_ILI9341.h>
+#include <UniversalInputManager.h>
+#include <IButton.h>
+
 #include <Adafruit_MCP23017.h>

 #define INTERRUPT_PIN 2


Description for "closeToWall" variable

Description for "closeToWall" variable

--- 2018-Firefighter/2018-Firefighter.ino
+++ 2018-Firefighter/2018-Firefighter.ino
@@ -44,7 +44,7 @@
 bool hearingStartSound = false;
 bool robotOn = false;
 unsigned long freqCount;
-double closeToWall = 2;
+double closeToWall = 2;   //defines how close the robot should be (inches) to the wall to register as being "too close"

 void moveForward() {
   leftServo.write(180);


Bugfix Wrong function parameters for ESP8266

--- ANI_CameraRemote/ANI_CameraRemote.ino
+++ ANI_CameraRemote/ANI_CameraRemote.ino
@@ -650,7 +650,7 @@
 #else
 // Methods for ESP8266
 void displaySetup() { }
-void onDisplay() { }
+void onDisplay(lcdScreens screen) { }
 void checkInactivity() { }
 void processKeyboard() { }
 #endif


speedo/speedo.ino : removed any trace that was not outputint the mph reading

--- speedo/speedo.ino
+++ speedo/speedo.ino
@@ -113,10 +113,10 @@
   delay(50);
   digitalWrite(13, LOW);

-  Serial.print("NEW RECORD");
-  Serial.print("\t");
-  Serial.print(best);
-  Serial.print("\n");
+  //Serial.print("NEW RECORD");
+  //Serial.print("\t");
+  //Serial.print(best);
+  //Serial.print("\n");
 }

 void loop(){
@@ -125,12 +125,12 @@
   if (mph > best)
   {
     best = mph;
-    displayBest();
+    //displayBest();
   }
   else if(mph > 8.80)
   {
     best = 0;
-    Serial.print("Best reset\n");
+    //Serial.print("Best reset\n");
   }
   delay(1000);
 }


Remove debug code

Remove debug code

--- dds_playground/src/sketch.ino
+++ dds_playground/src/sketch.ino
@@ -47,10 +47,6 @@
         wt_init(&wavetables[i], wt_sine_data, WT_SINE_LENGTH);
         wavetables[i].increment = 0; // all oscillators silent
     }
-
-    wavetables[0].increment = ACCUMULATOR_STEPS;
-    wavetables[0].currentnote = 0;
-    used_wavetables++;

     setup_sample_timer();
     setup_pwm_audio_timer();


Previous digit half tone was fixed

Previous digit half tone was fixed

--- digit4/digit4.ino
+++ digit4/digit4.ino
@@ -1,3 +1,5 @@
+const int DIGIT_DELAY = 500;
+
 const int DIGIT_1_PIN = 3;
 const int DIGIT_2_PIN = 5;
 const int DIGIT_3_PIN = 6;
@@ -12,13 +14,17 @@
 const int SEGMENT_G_PIN = 13;

 const byte DIGIT_OFF = 255;
-const byte DIGIT_ON = 10; // increase the value to reduce current
+const byte DIGIT_ON = 100; // increase the value to reduce current

 const short MINUS = -1;
 const short DEGREE = -2;

 int currentDigitIndex = 0;
+const int INACTIVE = -1;
 short digits[4];
+
+int temperature = -23;
+int humidity = 46;

 void activateDigit(int digit) {
   switch (digit) {
@@ -208,11 +214,12 @@
 }

 void loop() {
+  activateDigit(INACTIVE);
+  drawDigit(digits[currentDigitIndex]);
   activateDigit(currentDigitIndex);
-  drawDigit(digits[currentDigitIndex]);

   currentDigitIndex++;
   if (currentDigitIndex >= 4) currentDigitIndex = 0;

-  delayMicroseconds(500);
-}
+  delayMicroseconds(DIGIT_DELAY);
+}


cleanup

cleanup

--- firmware/firmware.ino
+++ firmware/firmware.ino
@@ -189,13 +189,6 @@
 			if (changed[i] < 24) {
 				// pad
 				pads[pinToPadMap[changed[i]]].trigger(pinStates[changed[i]]);
-				/*int note = 12 + selectedOctave * 24 + pinToPadMap[changed[i]];
-				if (pinStates[changed[i]]) {
-					MIDI.sendNoteOn(note, 120, 1);
-					// display.displayNote(note);
-				} else {
-					MIDI.sendNoteOff(note, 0, 1);
-				}*/
 			// TODO: refactor the following
 			} else if (changed[i] == SHIFT_A_BIT) {
 				// shift A


changed sharp IR sensor access

changed sharp IR sensor access

--- firmware/firmware.ino
+++ firmware/firmware.ino
@@ -1,6 +1,6 @@
 #include <Servo.h>

-#include "SharpIR.h"
+#include "irsharp.h"
 #include "Communication.h"
 #include "Hdlc.h"


Added Magnitude calcs. (First cut)

Added Magnitude calcs. (First cut)

--- Sketches/MIDI1/MIDI1.ino
+++ Sketches/MIDI1/MIDI1.ino
@@ -1,11 +1,6 @@
-// ADXL335 Test Program
+// MotionMIDI Arduino Code for the ADXL335

-// Old Values
-// Coincidentally, the difference between these is 127, perfect for MIDI
-//#define MIN 270
-//#define MAX 397
-
-#define CENTER 371  // Same for x, y, and z
+#define CENTER 341        // Assume same for x, y, and z
 #define RANGE  100
 #define MAX    (CENTER+RANGE)
 #define MIN    (CENTER-RANGE)
@@ -15,36 +10,33 @@
 void setup()
 {
 //Serial.begin(31250);     // Raw MIDI
-  Serial.begin(38400);     // Direct connect
+  Serial.begin(38400);     // Direct connect or XBee
   pinMode(LED, OUTPUT);
 }

 void loop()
-{
-  int x, y, z;
-  byte x1, y1, z1;
+{
+  digitalWrite(LED, HIGH);      // set the LED on
+
+  int x = analogRead(0);        // read analog input pin 0
+  int y = analogRead(1);        // read analog input pin 1
+  int z = analogRead(2);        // read analog input pin 2
+  float m = Magnitude(x,y,z);   // get the overall magnitude

-  digitalWrite(LED, HIGH);   // set the LED on
-
-  x = analogRead(0);       // read analog input pin 0
-  y = analogRead(1);       // read analog input pin 1
-  z = analogRead(2);       // read analog input pin 2
-
-// Serial.println(z, DEC);  // print the acceleration in the X axis for debugging
-
-  x1 = AccelToCC(x);
-  y1 = AccelToCC(y);
-  z1 = AccelToCC(z);
-
-  sendMIDI(0xB0,20,x1);   // Channel 1, CC#20
-  sendMIDI(0xB0,21,y1);   // Channel 1, CC#21
-  sendMIDI(0xB0,22,z1);   // Channel 1, CC#22
-
+  byte xcc = AccelToCC(x);
+  byte ycc = AccelToCC(y);
+  byte zcc = AccelToCC(z);
+  byte mcc = m*127;
+
+  sendMIDI(0xB0,20,xcc);   // X = Channel 1, CC#20
+  sendMIDI(0xB0,21,ycc);   // Y = Channel 1, CC#21
+  sendMIDI(0xB0,22,zcc);   // Z = Channel 1, CC#22
+  sendMIDI(0xB0,23,mcc);   // M = Channel 1, CC#23
+
   digitalWrite(LED, LOW);  // set the LED off
-
+
   delay(100);              // wait 100ms for next reading
 }
-

 void sendMIDI(byte cmd, byte data1, byte data2)
 {
@@ -55,20 +47,42 @@

 // Map an input between MIN and MAX to 0 to 127
 byte AccelToCC(int in)
-{
-    // Bound
-    if (in > MAX) in=MAX;
-    if (in < MIN) in=MIN;
-
-    // Change zero-offset
-    in = in-MIN;
-
-    // Scale between 0.0 and 1.0
-    float temp = (float)in/((float)MAX-(float)MIN);
-
-    //Serial.println(temp, DEC);
-
-    return temp*127;
+{
+  float temp = Scale(in);
+  return temp*127;
 }

+// Scale one of the inputs to between 0.0 and 1.0
+float Scale(int in)
+{
+  // Bound
+  if (in > MAX) in=MAX;
+  if (in < MIN) in=MIN;

+  // Change zero-offset
+  in = in-MIN;
+
+  // Scale between 0.0 and 1.0
+  float temp = (float)in/((float)MAX-(float)MIN);
+  return temp;
+}
+
+// Get the magnitude of the overall acceleration, with gravity removed.
+float Magnitude(int x, int y, int z)
+{
+  // We want them signed and rescaled betweeen +/- 1.0
+  float xf=2.0*(Scale(x) - 0.5);
+  float yf=2.0*(Scale(y) - 0.5);
+  float zf=2.0*(Scale(z) - 0.5);
+
+  float mf =sqrt(sq(xf) + sq(yf) + sq(zf));
+
+  // Subtract out gravity.  Our scaling isn't perfect so this is an empirical value.
+  mf = abs(mf - 0.7);
+
+  // Bound
+  if (mf > 1.0) mf = 1.0;
+
+  //Serial.println(mf, DEC);
+  return mf;
+}


Fixed example

Fixed example

Signed-off-by: Roman3349 <6b7cbc66756660b4790b3af1ec1507653acaa035@centrum.cz>

--- examples/Init/Init.ino
+++ examples/Init/Init.ino
@@ -15,7 +15,8 @@
  */

 // For IQRF
-#include "iqrf_library.h"
+#include <iqrf_library.h>
+#include <MsTimer2.h>

 // 5000@1ms = 5s
 #define USER_TIMER_PERIOD 5000
@@ -41,10 +42,14 @@
 const uint8_t testBuffer[64] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64};
 const uint8_t ledPin = 13;

+// INSTANCES
+// IQRFTR instance
+IQRFTR* iqrfTr = new IQRFTR;
+
 /**
  * Init peripherals
  */
-void setup(void) {
+void setup() {
   // User LED
   pinMode(ledPin, OUTPUT);
   // Up - PC
@@ -53,10 +58,10 @@
   IQRF_Init(MyIqrfRxHandler, MyIqrfTxHandler);
   // Info - TR
   switch (IQRF_GetModuleType()) {
-    case trTypes::TR_52D:
+    case iqrfTr->types::TR_52D:
       Serial.println("Module type: TR-52D");
       break;
-    case trTypes::TR_72D:
+    case iqrfTr->types::TR_72D:
       Serial.println("Module type: TR-72D");
       break;
     default:
@@ -75,7 +80,7 @@
 /**
  * Main loop
  */
-void loop(void) {
+void loop() {
   // TR module SPI comunication driver
   IQRF_Driver();
   // Test send data every 5s
@@ -95,7 +100,7 @@
 /**
  * 1ms timer callback
  */
-void cb_timer1ms(void) {
+void cb_timer1ms() {
   // app timer, call handler
   if (app_vars.appTimer) {
     if ((--app_vars.appTimer) == 0) {
@@ -108,14 +113,14 @@
 /**
  * User timer handler
  */
-void AppTimerHandler(void) {
+void AppTimerHandler() {
   app_vars.appTimerAck = true;
 }

 /**
  * IQRF RX callback
  */
-void MyIqrfRxHandler(void) {
+void MyIqrfRxHandler() {
   // Read and print received data
   IQRF_GetRxData(app_vars.myIqrfRxBuf, IQRF_GetRxDataSize());
   Serial.print("IQRF receive done: ");


Made string seperate

Made string seperate

--- arduino/arduino.ino
+++ arduino/arduino.ino
@@ -16,12 +16,12 @@
   char command = char(0);
   char end_stop = char(255);
   String send_message = String(message + end_stop);
-  send_message = String(command + send_message);
+  String send_message_with_command = String(command + send_message);

-  int send_length = send_message.length()+1;
+  int send_length = send_message_with_command.length()+1;

   char charBuf[send_length];
-  send_message.toCharArray(charBuf, send_length);
+  send_message_with_command.toCharArray(charBuf, send_length);
   Serial.write(charBuf);
 }


updated

updated

--- src/arduino/bear.ino
+++ src/arduino/bear.ino
@@ -40,6 +40,7 @@
     // stop working if the first byte is zero
     if (x == 0) {
       interval_millis = 0;
+      stop_beat();
       return;
     }

@@ -50,22 +51,17 @@
     current_beat = 0;

     flash_beat(true);
-  } else if (interval_millis == 0) {
-    stop_beat();
-    return;
-  } else {
-    if (current_millis - previous_millis >= interval_millis) {
-      previous_millis += interval_millis;
-      current_beat = (current_beat + 1) % num_beats;
-      flash_beat(current_beat == 0);
-    }
+  } else if (interval_millis != 0 && current_millis - previous_millis >= interval_millis) {
+    previous_millis += interval_millis;
+    current_beat = (current_beat + 1) % num_beats;
+    flash_beat(current_beat == 0);
   }
 }

 void flash_beat(bool is_downbeat) {
   digitalWrite(LED_BUILTIN, HIGH);
   digitalWrite(is_downbeat ? RED : BLUE, HIGH);
-  delay(is_downbeat ? 300 : 150);
+  delay(is_downbeat ? 200 : 150);
   digitalWrite(LED_BUILTIN, LOW);
   digitalWrite(is_downbeat ? RED : BLUE, LOW);
 }


Reformat the sending of a response

Reformat the sending of a response

--- barf_esp8266.ino
+++ barf_esp8266.ino
@@ -302,11 +302,15 @@
 		status_reason = "";
 	}

-	// Prepare the response
-	String s = String("HTTP/1.1 " + String(status_code) + " " + status_reason + "\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n") + response_data + String("\n");
-
 	// Send the response to the client
-	client.print(s);
+	client.print("HTTP/1.1 ");
+	client.print(status_code);
+	client.print(" ");
+	client.print(status_reason);
+	client.print("\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n");
+	client.print(response_data);
+	client.print("\n");
+
 	client.stop();

 	// Update activity timestamp


Changed QoS to 1 due to bug in MQTTClient not transmitting on QoS 2. Renamed "publish" to "publishToBroker" to differentiate it from mqttClient.publish Added while loop in setup() to ensure a connection is established so that the system always initiates as inactive

--- sensor/ZoneControlSensor.ino
+++ sensor/ZoneControlSensor.ino
@@ -24,7 +24,7 @@
 //MQTT constants
 #define MQTTCLIENT_QOS2 1
 const char* mainTopic = "londonbridge";
-MQTT::QoS qos = MQTT::QOS2;
+MQTT::QoS qos = MQTT::QOS1;
 bool retained = true;

 //Room State
@@ -96,7 +96,7 @@
 /**
 Publishes a message to the MQTT Broker
 */
-int publish(char topic[11], char message[11]) {
+int publishToBroker(char topic[11], char message[11]) {
 	//initialise variables
 	char topicBuffer[100];
 	char messageBuffer[100];
@@ -116,6 +116,10 @@
 	payloadlen = strlen(messageBuffer) + 1;

 	//publish message
+	Serial.print("Topic: ");
+	Serial.println(topicBuffer);
+	Serial.print("Message: ");
+	Serial.println((char*)payload);
 	int returnCode = mqttClient.publish(topicBuffer, payload, payloadlen, qos, retained);
 	return returnCode;
 }
@@ -137,7 +141,7 @@
 		}
 		//set current state to inactive
 		currentRoomState = INACTIVE;
-		returnCode = publish("state", "inactive");
+		returnCode = publishToBroker("state", "inactive");
 	}
 	//else if emergency button pressed
 	else if (newRoomState == EMERGENCY) {
@@ -148,7 +152,7 @@
 		digitalWrite(leds[2], HIGH);
 		//set current state to emergency
 		currentRoomState = EMERGENCY;
-		returnCode = publish("state", "emergency");
+		returnCode = publishToBroker("state", "emergency");
 	}
 	//else if caution button pressed
 	else if (newRoomState == CAUTION) {
@@ -159,7 +163,7 @@
 		digitalWrite(leds[1], HIGH);
 		//set current state to caution
 		currentRoomState = CAUTION;
-		returnCode = publish("state", "caution");
+		returnCode = publishToBroker("state", "caution");
 	}
 	//else if active button pressed
 	else if (newRoomState == ACTIVE) {
@@ -170,7 +174,7 @@
 		digitalWrite(leds[0], HIGH);
 		//set current state to active
 		currentRoomState = ACTIVE;
-		returnCode = publish("state", "active");
+		returnCode = publishToBroker("state", "active");
 	}
 	//if message publish not successful, error has occured
 	//report an error until board restarted and problem fixed
@@ -251,15 +255,18 @@
 	//establish Ethernet connection
 	Ethernet.begin(mac);
 	//connect to MQTT broker
-	connect();
+	while (!mqttClient.isConnected()){
+		connect();
+	}
 	//set current room state to inactive
 	currentRoomState = INACTIVE;
-	publish("state", "inactive");
+	publishToBroker("state", "inactive");
 }

 void loop() {
 	if (!mqttClient.isConnected()) {
 		connect();
-	}
-	checkSwitches();
+	} else {
+		checkSwitches();
+	}
 }


AC_FLOW update

AC_FLOW update

--- _04-mqtt-lcd-dust-sensor/_04-mqtt-lcd-dust-sensor-nano/_04-mqtt-lcd-dust-sensor-nano.ino
+++ _04-mqtt-lcd-dust-sensor/_04-mqtt-lcd-dust-sensor-nano/_04-mqtt-lcd-dust-sensor-nano.ino
@@ -3,8 +3,6 @@

 IRsend irsend;

-// IR
-// D3 is out
 const int AC_TYPE  = 0;
 // 0 : TOWER
 // 1 : WALL
@@ -21,6 +19,10 @@
 // 1 : mid
 // 2 : high
 // 3 : rotate
+
+const int AC_FLOW_TOWER[4] = {0, 4, 6, 12};
+const int AC_FLOW_WALL[4]  = {0, 2, 4, 5};
+

 int AC_AIR_ACLEAN  = 0;
 // 0 : off
@@ -111,9 +113,14 @@
   int AC_MSBITS4 = 0;
   int AC_MSBITS5 = temperature - 15;
   int AC_MSBITS6 ;
-
-
-
+
+  if ( AC_TYPE == 0) {
+    AC_MSBITS6 = AC_FLOW_TOWER[air_flow];
+  } else {
+    AC_MSBITS6 = AC_FLOW_WALL[air_flow];
+  }
+
+/*
   if ( AC_TYPE == 0) {
     if ( air_flow == 0 ) {
       AC_MSBITS6 = 0;
@@ -142,6 +149,7 @@
     }

   }
+*/

   int AC_MSBITS7 = (AC_MSBITS3 + AC_MSBITS4 + AC_MSBITS5 + AC_MSBITS6) & B00001111;

@@ -246,8 +254,6 @@

 }

-// function that executes whenever data is requested by master
-// this function is registered as an event, see setup()
 void requestEvent()
 {
   byte myArray[2];


better score display

better score display

--- oledPong/oledPong.ino
+++ oledPong/oledPong.ino
@@ -147,21 +147,19 @@
   u8g.drawBox(64, 0, 1, 64);
   u8g.drawBox(PADDLE_XL, paddleL, 2, 5);
   u8g.drawBox(PADDLE_XR, paddleR, 2, 5);
-  /*u8g.setPrintPos(27, 35);
-  u8g.print(ballY);*/

   if (scoreL <= 9) {u8g.setPrintPos(27, 15);}
-  else if (scoreL >= 10 && scoreL <= 99){u8g.setPrintPos(24, 15);}
+  else if (scoreL >= 10 && scoreL <= 99) {u8g.setPrintPos(24, 15);}
   else if (scoreL >= 100 && scoreL <= 999) {u8g.setPrintPos(21, 15);}
-  else if (scoreL >= 1000 && scoreL <= 9999){u8g.setPrintPos(18, 15);}
-  else if (scoreL >= 10000 && scoreL <= 99999){u8g.setPrintPos(15, 15);}
+  else if (scoreL >= 1000 && scoreL <= 9999) {u8g.setPrintPos(18, 15);}
+  else if (scoreL >= 10000) {u8g.setPrintPos(15, 15);}
   u8g.print(scoreL);

   if (scoreR <= 9) {u8g.setPrintPos(98, 15);}
-  else if (scoreR >= 10 && scoreR <= 99){u8g.setPrintPos(95, 15);}
+  else if (scoreR >= 10 && scoreR <= 99) {u8g.setPrintPos(95, 15);}
   else if (scoreR >= 100 && scoreR <= 999) {u8g.setPrintPos(92, 15);}
-  else if (scoreR >= 1000 && scoreR <= 9999){u8g.setPrintPos(89, 15);}
-  else if (scoreR >= 10000 && scoreR <= 99999){u8g.setPrintPos(86, 15);}
+  else if (scoreR >= 1000 && scoreR <= 9999) {u8g.setPrintPos(89, 15);}
+  else if (scoreR >= 10000) {u8g.setPrintPos(86, 15);}
   u8g.print(scoreR);
 }


first data transfers in place

first data transfers in place

--- control/control.ino
+++ control/control.ino
@@ -7,12 +7,15 @@

 #include <Wire.h>
 #include <LiquidCrystal_I2C.h>
-
+#include <SoftwareSerial.h>
 #include <Time.h>
 #include <TimeAlarms.h>
 #include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t
 #include "tx433_Nexa.h" // Nexa headers
 #include <buttons.h>  // Button sensing
+
+// Setup software serial
+SoftwareSerial com(10, 11); // RX, TX

 // Set the LCD address to 0x27 for a 16 chars and 2 line display
 LiquidCrystal_I2C lcd(0x27, 16, 2);
@@ -60,6 +63,9 @@
   lcd.begin();
   lcd.backlight();

+  // Set data rate for communication with espXXX
+  com.begin(9600);
+
   while (!Serial) ; // wait until Arduino Serial Monitor opens
   setSyncProvider(RTC.get);   // the function to get the time from the RTC

@@ -68,12 +74,6 @@

   Serial.begin(9600);
   Serial.println(FILLTIME_MILLIS);
-
-  //setTime(8,29,50,1,1,11); // set time to Saturday 8:29:00am Jan 1 2011
-
-  // create the alarms
-  //Alarm.alarmRepeat(8,00,0, MorningAlarm);  // 8:00am every day
-  //Alarm.alarmRepeat(8,35,0,EveningAlarm);  // 8:45pm every day

   Alarm.timerRepeat(0, CHECK_INTERVAL_MINUTES, 0, CheckWaterOn);            // timer for every fill time
   //Alarm.timerRepeat(FILL_INTERVAL, FillTimer);  //For testing with higher frequencey
@@ -87,9 +87,13 @@
   // Light alarms
   Alarm.alarmRepeat(light_time_on[0], light_time_on[1], light_time_on[2], LightOn);
   Alarm.alarmRepeat(light_time_off[0], light_time_off[1], light_time_off[2], LightOff);
+
+  // Com startup
+  com.print("\r\n\r\n\r\nrequire('main').main();\r\n\r\n\r\n");

   // Make sure light is on/off as planned by the hour
   checkLight();
+
 }

 void  loop(){
@@ -109,12 +113,14 @@
 void LightOn(){
   Serial.println("Light on, Good morning!");
   Nexa.Device_On(0);
+  sendData("id=light value=on");
 }

 // Light timer
 void LightOff(){
   Serial.println("Light Off, Good nights!");
   Nexa.Device_Off(0);
+  sendData("id=light value=off");
 }

 void ForcedTimer(){
@@ -130,12 +136,15 @@
     Alarm.timerOnce(0, FILLTIME_HALF_MINUTES, 0, WaterOff);
     WATERON = true;
     lcd.print("Water ON        ");
+    sendData("id=water value=on");
   }
 }

 void WaterOff(){
   //Serial.println("Water OFF");
   digitalWrite(PUMP_PIN, HIGH);
+  if (WATERON)
+    sendData("id=water value=off");
   WATERON = false;
 }

@@ -196,6 +205,16 @@
     lcd.print("Water off, OK   ");
     //Serial.println("Water off, all OK");
   }
+}
+
+void sendData(String value)
+{
+  static long last_transmit = millis();
+  if ((millis() - last_transmit) >= 1000)
+   {
+    com.print("set-property " + value + "\r\n");
+    last_transmit = millis();
+   }
 }

 void checkLight()
@@ -228,12 +247,6 @@
   lcd.print(hour());
   printDigits(minute());
   printDigits(second());
-  //Serial.print(" Millis: ");
-  //Serial.print(millis());
-  //Serial.print(" Last: ");
-  //Serial.print(last_fill_start);
-
-  //Serial.println();
 }

 void printDigits(int digits)


Normalize line endings

Normalize line endings

--- AltimeterFuncs.ino
+++ AltimeterFuncs.ino
@@ -1,54 +1,54 @@
-#if ROLE == ROLE_SKY
-// returns smoothed uncalibrated altitude
-float getAltitude() {
-  if (!bmpConnected) {
-    return -1;
-  }
-
-  sensors_event_t event;
-  bmp.getEvent(&event);
-
-  float temperature;
-  bmp.getTemperature(&temperature);
-
-  float seaLevelPressure = SENSORS_PRESSURE_SEALEVELHPA;
-
-  float currentAlt = bmp.pressureToAltitude(seaLevelPressure, event.pressure, temperature) * METERS_TO_FEET_RATIO;
-  return smoothAltitude(currentAlt);
-}
-
-// outputs a running average of the last n (ALTITUDE_SMOOTHING) altitudes
-float smoothAltitude(float newAlt) {
-  // cycle every time this is called
-  lastAltitudes[lastAltitudeIndex] = newAlt;
-  lastAltitudeIndex++;
-  if (lastAltitudeIndex >= ALTITUDE_SMOOTHING) {
-    lastAltitudeIndex = 0;
-  }
-
-  // get average
-  float sum = 0;
-  for (int i = 0; i < ALTITUDE_SMOOTHING; i++) {
-    sum += lastAltitudes[i];
-  }
-  return sum / ALTITUDE_SMOOTHING;
-}
-// this is to check and see if our altimeter is just returning 0s and reset the arduino
-void checkAltimeterDataIntegrity() {
-  // only check when our altitude is at the end in order to avoid the initial {0,0,0...}
-  if (lastAltitudeIndex != ALTITUDE_SMOOTHING) {
-    return;
-  }
-  bool allZeros = true;
-  for (int i = 0; i < ALTITUDE_SMOOTHING; i++) {
-    if (lastAltitudes[i] != 0.0f) {
-      allZeros = false;
-    }
-  }
-  if (allZeros) {
-    Serial.println("RESETTING ARDUINO");
-    digitalWrite(resetPin, LOW);
-  }
-
-}
+#if ROLE == ROLE_SKY
+// returns smoothed uncalibrated altitude
+float getAltitude() {
+  if (!bmpConnected) {
+    return -1;
+  }
+
+  sensors_event_t event;
+  bmp.getEvent(&event);
+
+  float temperature;
+  bmp.getTemperature(&temperature);
+
+  float seaLevelPressure = SENSORS_PRESSURE_SEALEVELHPA;
+
+  float currentAlt = bmp.pressureToAltitude(seaLevelPressure, event.pressure, temperature) * METERS_TO_FEET_RATIO;
+  return smoothAltitude(currentAlt);
+}
+
+// outputs a running average of the last n (ALTITUDE_SMOOTHING) altitudes
+float smoothAltitude(float newAlt) {
+  // cycle every time this is called
+  lastAltitudes[lastAltitudeIndex] = newAlt;
+  lastAltitudeIndex++;
+  if (lastAltitudeIndex >= ALTITUDE_SMOOTHING) {
+    lastAltitudeIndex = 0;
+  }
+
+  // get average
+  float sum = 0;
+  for (int i = 0; i < ALTITUDE_SMOOTHING; i++) {
+    sum += lastAltitudes[i];
+  }
+  return sum / ALTITUDE_SMOOTHING;
+}
+// this is to check and see if our altimeter is just returning 0s and reset the arduino
+void checkAltimeterDataIntegrity() {
+  // only check when our altitude is at the end in order to avoid the initial {0,0,0...}
+  if (lastAltitudeIndex != ALTITUDE_SMOOTHING) {
+    return;
+  }
+  bool allZeros = true;
+  for (int i = 0; i < ALTITUDE_SMOOTHING; i++) {
+    if (lastAltitudes[i] != 0.0f) {
+      allZeros = false;
+    }
+  }
+  if (allZeros) {
+    Serial.println("RESETTING ARDUINO");
+    digitalWrite(resetPin, LOW);
+  }
+
+}
 #endif


Clean up

Clean up

--- module/module.ino
+++ module/module.ino
@@ -217,10 +217,11 @@
 		// if periodX and periodY IS NOT a valid pair
 		if ( !inRange(periodX, periodY) ) {
 			// check if enough negative signals have been detected
+			// calculate elapsed time
 			if (checkHistory(signals) == flag.detectedJobEnd) {
 				elapsedTime = calculateTime(startTime);

-				// check if a job was detected and return the time
+				// if a job was detected, return
 				if (startTime > 0 && elapsedTime > freeTime) {
 					return elapsedTime;
 				}
@@ -263,12 +264,9 @@
 	}

 	if (debug) {
-		Serial.print(numValid); Serial.print(numInvalid);
-		Serial.print(" ");
-	}
-	else {
-		delay(debounce);
-	}
+		Serial.print(numValid); Serial.print(numInvalid); Serial.print(" ");
+	}
+	//delay(debounce);

 	if (numValid == sampleSize) {
 		return flag.detectedJobStart;
@@ -286,7 +284,6 @@
 	There are slight deviations at times, so summing the values together
 	and using the maximum possible sum as a check is a reliable way to
 	determine if a signal is valid.
-
 */
 bool inRange(unsigned long periodX, unsigned long periodY) {
 	const int upperBound = 6;
@@ -300,14 +297,15 @@
 		return false;
 	}
 }
-
 /*
 	Calculate time elapsed in seconds.
 */
 unsigned long calculateTime(unsigned long startTime) {
 	return (millis() - startTime)/1000;
 }
-
+/*
+	This will play 3 rapid notes or 1 long note.
+*/
 void soundFeedback(bool isReject) {
 	if (isReject) {
 		tone(speakerPin, rejectNote, rejectDuration);


Added untested code for controlling current

--- arduino/rfglow_tcl591xx/rfglow_tcl591xx.ino
+++ arduino/rfglow_tcl591xx/rfglow_tcl591xx.ino
@@ -119,6 +119,8 @@
 unsigned int mH = 0;
 unsigned int mS = 255;
 unsigned int mB = 60;
+
+unsigned int ma = 120;

 int clickState = 0;

@@ -203,7 +205,34 @@
   DEBUG_PRINTLN("setHSVRaw() called: "+h+" "+s+" "+v);

   unsigned char r, g, b;
-  unsigned char region, remainder, p, q, t;
+  unsigned char region, remainder, p, q, t, maLevel, newMa;
+
+  maLevel = h / 360;
+  h = h % 360;
+
+
+  switch (maLevel) {
+    case 1:
+      newMa = 90;
+      break;
+    case 2:
+      newMa = 60;
+      break;
+    case 3:
+      newMa = 30;
+      break;
+    default:
+      newMa = 120;
+  }
+
+  if (v == 0) {
+    newMa = 0;
+  }
+
+  if (newMa != ma) {
+    driver->set_milliamps(newMa);
+    ma = newMa;
+  }

   if (s == 0) {
     r = v;


Fix bug

Fix bug

--- robot/robot.ino
+++ robot/robot.ino
@@ -57,9 +57,7 @@
       }

       // Determine the speed
-      //TODO: Should be command & SPEED_MASK?
       uint8_t spd = command & SPEED_MASK;
-      //TODO: This line creates a quadratic releationship between what should be linear speed values. It would be better to multiply by a constant.
       if (spd == 16) {
         spd = 256;
       } else {
@@ -74,7 +72,7 @@
             case 0:
               // Negative direction
               analogWrite(motor_x[1], spd);
-              digitalWrite(motor_x[1], HIGH);
+              digitalWrite(motor_x[0], LOW);
               break;
             case 1:
               // Positive direction
@@ -89,7 +87,7 @@
             case 0:
               // Negative direction
               analogWrite(motor_y[1], spd);
-              digitalWrite(motor_y[1], HIGH);
+              digitalWrite(motor_y[0], LOW);
               break;
             case 1:
               // Positive direction


Update SparkCore.ino

Update SparkCore.ino

--- firmware/examples/Transports/SparkCore/SparkCore.ino
+++ firmware/examples/Transports/SparkCore/SparkCore.ino
@@ -31,7 +31,16 @@
 // Attach a Button widget to the Virtual pin 1 - and send sweet tweets!
 BLYNK_WRITE(1) {
     if (param.asInt()) { // On button down...
+        // Twitting!
+        // Note:
+        //   We allow 1 tweet per minute for now.
+        //   Twitter doesn't allow identical subsequent messages.
         Blynk.tweet("My Particle project is tweeting using @blynk_app and this is awesome!\n @Particle #IoT #blynk");
+
+        // Pushing notification to the app!
+        // Note:
+        //   We allow 1 notification per minute for now.
+        Blynk.notify("You pressed the button and I know it ;)");
     }
 }


Stage1

--- compet/stage1/stage1.ino
+++ compet/stage1/stage1.ino
@@ -116,23 +116,25 @@
 void loop() {

     //playCarSound
+    mySound.doAction(1);
+    // forward to wall
+    myRobot->goToWall("Front", 5, 100);
+    // touch wall (forwardAt)
+    myRobot->forwardAtDistance(100, 5);
+    // backAt
+    myRobot->backwardAtDistance(100, 5);
+    // turn
+    myRobot->turnLeftAtDegre(150, 90);
+    // touch wall (forwardAt)
+    myRobot->forwardAtDistance(get
+    // wait 3 seconds
+    delay(3000);
+    // danse
+    myRobot->turnLeftAtDegre(150, 360);

-    // forward to wall
-
-    // touch wall (forwardAt)
-
+    myRobot->turnRightAtDegre(150, 360);
     // backAt
-
-    // turn
-
-    // touch wall (forwardAt)
-
-    // wait 3 seconds
-
-    // danse
-
-    // backAt
-
+
     //turn

     // forwardAt or forwardDistance


cleanup

cleanup

--- sensornode/sensornode_rf24.ino
+++ sensornode/sensornode_rf24.ino
@@ -55,11 +55,7 @@

   // open pipe for writing
   radio.openWritingPipe(0xF0F0F0F0E1LL);
-
-  //radio.enableDynamicPayloads();
-
-  radio.powerUp();
-
+  radio.powerUp();
   radio.printDetails();

   Serial << "\n" << "Startup took " << millis() << "ms" << endl;
@@ -82,7 +78,7 @@
   Serial << temp << "C" << endl;
   Serial << "measuring humidity: ";
   digitalWrite(3, HIGH);
-  unsigned long hum = round(dht.readHumidity()*100.0);
+  int hum = round(dht.readHumidity()*100.0);
   Serial << hum << "%" << endl;

   digitalWrite(3, HIGH);


Linde speen tesc succeeded

Linde speen tesc succeeded

--- linde-steering/linde_test.ino
+++ linde-steering/linde_test.ino
@@ -3,6 +3,48 @@
 #define PILKAS 6
 #define GELTONAS 5

+#define SPI_LATCH           10
+#define SPI_DATA          11
+#define SPI_CLK           13
+
+#define CTRL_AUX      B00100000
+
+
+#define THROTTLE_PIN1  A3
+#define THROTTLE_PIN2 A4
+#define THROTTLE_PIN3 A5
+
+#define STEERING_ENABLE       7
+
+// command inteface
+#include <SerialCommand.h>
+SerialCommand sCmd;     // The SerialCommand object
+
+#include <Servo.h>
+
+Servo myservo;  // create servo object to control a servo
+// twelve servo objects can be created on most boards
+
+
+volatile int pos = 0;    // variable to store the servo position
+
+void CMD_any() {
+  Serial.println("WUT?");
+}
+
+void CMD_incr() {
+  pos=pos+1;
+}
+
+void CMD_decr() {
+  pos=pos-1;
+}
+
+uint8_t control = 0;
+
+
+void sendControl(void);
+void Aux(bool);

 //pilkas geltonas
 uint8_t center[] = {113, 138};
@@ -12,9 +54,27 @@
   pinMode(PILKAS, OUTPUT);
   pinMode(GELTONAS, OUTPUT);

+  pinMode(THROTTLE_PIN1, OUTPUT);
+  pinMode(THROTTLE_PIN2, OUTPUT);
+
+  pinMode(STEERING_ENABLE, OUTPUT);
+
+  pinMode(SPI_LATCH, OUTPUT);
+  pinMode(SPI_DATA, OUTPUT);
+Serial.begin(9600);
+Serial.println("Start servo debug");
+
+
+sendControl();
+
   analogWrite(PILKAS, center[0]);
   analogWrite(GELTONAS, center[1]);

+myservo.attach(9);  // attaches the servo on pin 9 to the servo object
+
+ //center
+
+myservo.write(110);
   delay(1000);

   digitalWrite(TAKEOVER, HIGH);
@@ -29,15 +89,91 @@

 //  delay(500);

+
+
+
+
 }

+
+
+
+
 void loop() {
-  center[0]++;
-  center[1]++;
+//  center[0]++;
+//  center[1]++;

-  analogWrite(PILKAS, center[0]);
-  analogWrite(GELTONAS, center[1]);
+//  analogWrite(PILKAS, center[0]);
+//  analogWrite(GELTONAS, center[1]);

-  delay(10);
+//  delay(10);
+
+//myservo.write(pos);              // tell servo to go to position in variable 'pos'
+//Serial.print("Servo at ");
+//Serial.println(pos);
+
+//for (short i=30;i<110;i++) {
+//myservo.write(i);              // tell servo to go to position in variable 'pos'
+//Serial.print("Servo at ");
+//Serial.println(i);
+// delay(1500);
+
+//myservo.write(129);
+
+
+delay(1000);
+ myservo.write(85);
+ delay(100);
+ Aux(1);
+ delay(100);
+ myservo.write(40);
+ delay(1000);
+ myservo.write(30);
+ delay(1000);
+ myservo.write(40);
+ delay(1000);
+ myservo.write(85);
+
+
+//delay(2000);
+//Aux(1);
+//delay(200);
+
+//digitalWrite(THROTTLE_PIN2, LOW);
+//digitalWrite(THROTTLE_PIN1, HIGH); // forward
+
+//delay(100);
+//digitalWrite(STEERING_ENABLE, HIGH);
+
+//delay(5000);
+
+//digitalWrite(STEERING_ENABLE, LOW);
+//delay(100);
+//digitalWrite(STEERING_ENABLE, HIGH);
+//delay(10);
+//digitalWrite(THROTTLE_PIN1, LOW);
+//digitalWrite(THROTTLE_PIN2, HIGH); // back
+//delay(500);
+//
+//digitalWrite(STEERING_ENABLE, LOW);
+//delay(100);
+//digitalWrite(THROTTLE_PIN1, LOW);
+//digitalWrite(THROTTLE_PIN2, LOW); // back
+
 }
+
+void Aux(bool state) {
+  if (state) {
+    control = control | CTRL_AUX;
+  } else {
+    control = control & ~CTRL_AUX;
+  }
+ sendControl();
+}
+
+void sendControl(void) {
+   digitalWrite(SPI_LATCH, LOW);
+   shiftOut(SPI_DATA, SPI_CLK, MSBFIRST, control);
+   digitalWrite(SPI_LATCH, HIGH);
+}


example: do not use printhex

example: do not use printhex

--- examples/MAX1464_example.ino
+++ examples/MAX1464_example.ino
@@ -19,8 +19,6 @@
 /**
  * \file
  */
-
-#include "printhex.h"

 #include "MAX1464.h"

@@ -122,7 +120,7 @@
                 Serial.print(port_cp);
                 Serial.print(" == ");
                 uint16_t value = max1464.readCpuPort((CPU_PORT)port);
-                printHex16(value);
+                Serial.print(value, HEX);
                 Serial.println();
             }
         }


Added comments

Added comments

--- software/Arduino/ServoController/ServoController.ino
+++ software/Arduino/ServoController/ServoController.ino
@@ -1,7 +1,7 @@
 /**********************************************************************
  * Arduino Uno Program - Controls Servos and Reads IMU                *
  * Project: Eclipse Tracking (2017)                                   *
- * Version: 2.0 (4/15/2017)                                           *
+ * Version: 3.0 (5/07/2017)                                           *
  * Max Bowman / Jeremy Seeman / George Moe                            *
  **********************************************************************/
 #include <Servo.h>
@@ -28,7 +28,6 @@
 const float COUNTER_CLOCK_WISE_SPEED = 100;
 const float ZERO_SPEED = 75;
 const byte GEAR_RATIO = 2; // servo gear : slip gear
-// =======================================================

 // ============ Initialize electronic interfaces =========
 Servo azimuth;
@@ -42,7 +41,9 @@
 int timer = millis();
 bool update_flag = false; // interrupt flag for executing motor update

-// Initialize everything
+/**
+    Sets up everything
+*/
 void setup() {
   // Initialize I/O
   Serial.begin(115200);
@@ -94,10 +95,17 @@
   }
 }

+/**
+    Triggered every motorUpdateRate milliseconds
+    Starts the motor update
+*/
 void updateMotor() {
   update_flag = true;
 }

+/**
+    Sets up the IMU
+*/
 void setupIMU() {
   imu.settings.device.commInterface = IMU_MODE_I2C;
   imu.settings.device.mAddress = LSM9DS1_M;
@@ -107,7 +115,11 @@
   }
 }

-// For stepper motors
+/**
+    Rotates a continuous rotation servo a specified number
+    of degrees.
+    @param degrees to rotate the servo
+*/
 void rotateServoBy(float deg) {
   float wait = abs((deg / 360) / RPM);
   if (deg < 0) azimuth.write(COUNTER_CLOCK_WISE_SPEED);
@@ -116,6 +128,10 @@
   azimuth.write(ZERO_SPEED);
 }

+/**
+    Reads the IMU's gyro
+    @return rate in degrees / ms
+*/
 float readGyro() {
   if (imu.gyroAvailable()) {
     imu.readGyro();
@@ -123,6 +139,11 @@
   return imu.calcGyro(imu.gz) - calibratedOffset;
 }

+/**
+    Blinks an LED on pin 13
+    @param delay in milliseconds
+    @param number of blinks
+*/
 void blinkLED(int del, int n) {
   for (int i = 0; i < n; i++) {
     digitalWrite(LED, HIGH);
@@ -132,6 +153,11 @@
   }
 }

+/**
+    Finds the calibration constant of the
+    gyro.
+    @param number of calibration samples
+*/
 int zeroGyro(int calibrationSamples) {
   float zSum = 0;
   for(int i = 0; i < calibrationSamples; i++) {
@@ -145,4 +171,3 @@
   }
   return zSum / calibrationSamples;
 }
-


digital counter

digital counter

--- outdoor-firm/outdoor-firm.ino
+++ outdoor-firm/outdoor-firm.ino
@@ -14,6 +14,7 @@

 #define DHT_PIN 7
 #define ONE_WIRE_BUS 9
+#define COUNTER_PIN 2

 #define LOOP_TIME                 1000 // msec

@@ -28,12 +29,21 @@
 DallasTemperature sensors(&oneWire);
 SFE_BMP180 pressure;

+volatile long int counter = 0;
+
+void pin2int() {
+  counter++;
+}
+
 void setup()
 {

   pinMode(HC_05_SETUPKEY, OUTPUT);
   pinMode(HC_05_PWR1, OUTPUT);      // Connect in parallel to HC-05 VCC
   pinMode(HC_05_PWR2, OUTPUT);      // Connect in parallel to HC-05 VCC
+
+
+attachInterrupt(digitalPinToInterrupt(COUNTER_PIN), pin2int, FALLING);

   pinMode(10, INPUT);
   pinMode(8, INPUT);
@@ -127,6 +137,7 @@
   fbt_echo_send(Tp);
   fbt_echo_send(T0);
   fbt_echo_send(T1);
+  fbt_echo_send(counter);

   bt_echo_send(")");


test code for data reading and writing

test code for data reading and writing

--- spi_flash.ino
+++ spi_flash.ino
@@ -3,55 +3,37 @@

 S25FL208K *spiFlash;

+uint32_t testAddr = 0x000008;
+
 void setup(){
   Serial.begin(115200);
   // if this is run before setup, then doesn't work.
   // other option is to have an init function.
-  //spiFlash = new S25FL208K(4);
+  spiFlash = new S25FL208K(4);
   Serial.println("Setup complete.");

-  //Serial.println(spiFlash->readStatus(),BIN);
-  //spiFlash->writeEnable();
-  //Serial.println(spiFlash->readStatus(),BIN);
+  String test = "Hello world";

-  SPI.begin();
-  int csPin = 4;
-  pinMode(csPin, OUTPUT);
-  digitalWrite(csPin, 1);
+  uint8_t* dataToStore = new uint8_t[test.length()];
+  for(int i = 0; i<test.length(); i++){
+    dataToStore[i] = uint8_t(test[i]);
+  }

-  uint8_t res = 0;
-  digitalWrite(csPin, 0);
-  SPI.transfer(0x05);
-  res = SPI.transfer(0);
-  digitalWrite(csPin, 1);
+  unsigned long timeWrite = millis();
+  spiFlash->storeData(testAddr, test.length(), dataToStore);

-  Serial.println(res,BIN);
+  while(spiFlash->getWIP()){
+    Serial.print(".");
+  }

-  digitalWrite(csPin, 0);
-  SPI.transfer(0x06);
-  digitalWrite(csPin, 1);
+  Serial.print("\nTime taken to write:");
+  Serial.println(millis() - timeWrite);

-  digitalWrite(csPin, 0);
-  SPI.transfer(0x05);
-  res = SPI.transfer(0);
-  digitalWrite(csPin, 1);
-
-  Serial.println(res,BIN);
-
-  digitalWrite(csPin, 0);
-  SPI.transfer(0x04);
-  digitalWrite(csPin, 1);
-
-  digitalWrite(csPin, 0);
-  SPI.transfer(0x05);
-  res = SPI.transfer(0);
-  digitalWrite(csPin, 1);
-
-  Serial.println(res,BIN);
-
-
-
-
+  uint8_t* dataToRead = new uint8_t[20];
+  spiFlash->readData(0, 20, dataToRead);
+  for(int i = 0; i<20; i++){
+    Serial.print((char)dataToRead[i]);
+  }
 }

 void loop(){


update

update

--- MCU/MCU-Sketch/MCU-Sketch.ino
+++ MCU/MCU-Sketch/MCU-Sketch.ino
@@ -1,11 +1,11 @@
 // Pin Mapping [Check Document]

-#define RIGHT_ENABLE P2_0
-#define LEFT_ENABLE P2_5
-#define LEFT_AHEAD P2_1
-#define LEFT_BACK P2_2
-#define RIGHT_AHEAD P2_3
-#define RIGHT_BACK P2_4
+#define LEFT_ENABLE P2_0
+#define RIGHT_ENABLE P2_5
+#define RIGHT_AHEAD P2_1
+#define RIGHT_BACK P2_2
+#define LEFT_AHEAD P2_3
+#define LEFT_BACK P2_4

 // AHEAD: HIGH  BACK: LOW -> MOVE FORWARD
 // AHEAD: LOW  BACK: HIGH -> MOVE BACKWARD
@@ -14,6 +14,9 @@
 // Default Value
 #define VALUE_A 170
 #define VALUE_B 128
+
+int SPEED = 255;
+float COEFFICIENT = 0.4;

 // Interface
 // Precise direction control -> analogWrite()
@@ -42,6 +45,8 @@
 }

 void park(){
+  digitalWrite(LEFT_ENABLE,LOW);
+  digitalWrite(RIGHT_ENABLE,LOW);
   digitalWrite(LEFT_AHEAD,LOW);
   digitalWrite(LEFT_BACK,LOW);
   digitalWrite(RIGHT_AHEAD,LOW);
@@ -49,6 +54,8 @@
 }

 void turnLeft(){
+  analogWrite(LEFT_ENABLE, COEFFICIENT*SPEED);
+  analogWrite(RIGHT_ENABLE, SPEED);
   digitalWrite(LEFT_AHEAD,LOW);
   digitalWrite(LEFT_BACK,LOW);
   digitalWrite(RIGHT_AHEAD,HIGH);
@@ -56,6 +63,8 @@
 }

 void turnRight(){
+  analogWrite(RIGHT_ENABLE, COEFFICIENT*SPEED);
+  analogWrite(LEFT_ENABLE, SPEED);
   digitalWrite(LEFT_AHEAD,HIGH);
   digitalWrite(LEFT_BACK,LOW);
   digitalWrite(RIGHT_AHEAD,LOW);


Updated claw motion settings for new servo

--- dfrdb/dfrdb.ino
+++ dfrdb/dfrdb.ino
@@ -76,8 +76,8 @@
 const int minClawAngle = 30;  // open claw; limit angles to protect servo
 const int maxClawAngle = 147; // closed claw
 int wristAngle = 85;
-const int minWristAngle = 10;
-const int maxWristAngle = 135;
+const int minWristAngle = 25;
+const int maxWristAngle = 125;

 /********************
 ====== BODY =========


adjust claw and wrist angles

adjust claw and wrist angles

--- dfrdb/dfrdb.ino
+++ dfrdb/dfrdb.ino
@@ -73,11 +73,11 @@
 int clawAngle = 85;       // init position
 const int ClawRDZ = 1450; // threshold for closing claw - right limit of dead zone
 const int ClawLDZ = 1550; // threshold for opening claw
-const int minClawAngle = 5;      // limit travel to protect servo
-const int maxClawAngle = 135;
+const int minClawAngle = 30;  // open claw; limit angles to protect servo
+const int maxClawAngle = 147; // closed claw
 int wristAngle = 85;
-const int minWristAngle = 0;
-const int maxWristAngle = 150;
+const int minWristAngle = 10;
+const int maxWristAngle = 135;

 /********************
 ====== BODY =========


Add #define blocks to make it clear where there are SmartMatrix sections that can be removed

--- AnimatedGIFs.ino
+++ AnimatedGIFs.ino
@@ -30,7 +30,7 @@
  * This SmartMatrix Library example displays GIF animations loaded from a SD Card connected to the Teensy 3
  *
  * The example can be modified to drive displays other than SmartMatrix by replacing SmartMatrix Library calls in setup() and
- * the *Callback() functions with calls to a different library
+ * the *Callback() functions with calls to a different library (look for the USE_SMARTMATRIX and ENABLE_SCROLLING blocks and replace)
  *
  * This code has been tested with many size GIFs including 128x32, 64x64, 32x32, and 16x16 pixel GIFs, but is optimized for 32x32 pixel GIFs.
  *
@@ -86,7 +86,8 @@

 #define DISPLAY_TIME_SECONDS 10

-#define ENABLE_SCROLLING  1
+#define USE_SMARTMATRIX         1
+#define ENABLE_SCROLLING        1

 // range 0-255
 const int defaultBrightness = 255;
@@ -94,6 +95,7 @@
 const rgb24 COLOR_BLACK = {
     0, 0, 0 };

+#if (USE_SMARTMATRIX == 1)
 /* SmartMatrix configuration and memory allocation */
 #define COLOR_DEPTH 24                  // known working: 24, 48 - If the sketch uses type `rgb24` directly, COLOR_DEPTH must be 24
 const uint8_t kMatrixWidth = 32;        // known working: 32, 64, 96, 128
@@ -107,8 +109,9 @@

 SMARTMATRIX_ALLOCATE_BUFFERS(matrix, kMatrixWidth, kMatrixHeight, kRefreshDepth, kDmaBufferRows, kPanelType, kMatrixOptions);
 SMARTMATRIX_ALLOCATE_BACKGROUND_LAYER(backgroundLayer, kMatrixWidth, kMatrixHeight, COLOR_DEPTH, kBackgroundLayerOptions);
-#if ENABLE_SCROLLING == 1
+#if (ENABLE_SCROLLING == 1)
 SMARTMATRIX_ALLOCATE_SCROLLING_LAYER(scrollingLayer, kMatrixWidth, kMatrixHeight, COLOR_DEPTH, kScrollingLayerOptions);
+#endif
 #endif

 /* template parameters are maxGifWidth, maxGifHeight, lzwMaxBits
@@ -140,15 +143,21 @@
 int num_files;

 void screenClearCallback(void) {
+#if (USE_SMARTMATRIX == 1)
   backgroundLayer.fillScreen({0,0,0});
+#endif
 }

 void updateScreenCallback(void) {
+#if (USE_SMARTMATRIX == 1)
   backgroundLayer.swapBuffers();
+#endif
 }

 void drawPixelCallback(int16_t x, int16_t y, uint8_t red, uint8_t green, uint8_t blue) {
-  backgroundLayer.drawPixel(x, y, {red, green, blue});
+#if (USE_SMARTMATRIX == 1)
+    backgroundLayer.drawPixel(x, y, {red, green, blue});
+#endif
 }

 // Setup method runs once, when the sketch starts
@@ -169,9 +178,10 @@
     Serial.println("Starting AnimatedGIFs Sketch");

+#if (USE_SMARTMATRIX == 1)
     // Initialize matrix
     matrix.addLayer(&backgroundLayer);
-#if ENABLE_SCROLLING == 1
+#if (ENABLE_SCROLLING == 1)
     matrix.addLayer(&scrollingLayer);
 #endif

@@ -199,9 +209,10 @@
     // Clear screen
     backgroundLayer.fillScreen(COLOR_BLACK);
     backgroundLayer.swapBuffers(false);
+#endif

     if(initSdCard(SD_CS) < 0) {
-#if ENABLE_SCROLLING == 1
+#if (ENABLE_SCROLLING == 1)
         scrollingLayer.start("No SD card", -1);
 #endif
         Serial.println("No SD card");
@@ -209,12 +220,15 @@
     }

     // for ESP32 we need to allocate SmartMatrix DMA buffers after initializing the SD card to avoid using up too much memory
+#if (ENABLE_SCROLLING == 1)
+    scrollingLayer.start("TESTING TESTING TESTING", -1);
+#endif

     // Determine how many animated GIF files exist
     num_files = enumerateGIFFiles(GIF_DIRECTORY, false);

     if(num_files < 0) {
-#if ENABLE_SCROLLING == 1
+#if (ENABLE_SCROLLING == 1)
         scrollingLayer.start("No gifs directory", -1);
 #endif
         Serial.println("No gifs directory");
@@ -222,7 +236,7 @@
     }

     if(!num_files) {
-#if ENABLE_SCROLLING == 1
+#if (ENABLE_SCROLLING == 1)
         scrollingLayer.start("Empty gifs directory", -1);
 #endif
         Serial.println("Empty gifs directory");


Fix the 16 bit overflow on BLOCK_SIZE

Fix the 16 bit overflow on BLOCK_SIZE

--- arduino_serial.ino
+++ arduino_serial.ino
@@ -1,17 +1,9 @@
 #define DEBUG 0

 const uint16_t MAX_BUFFER_SIZE = SERIAL_RX_BUFFER_SIZE - 1;
-//const uint32_t BLOCK_SIZE = 32 * 1024;
-const uint32_t BLOCK_SIZE = 2000 * 1024;
-//uint16_t buffer_size = 0
-uint16_t buffer_size = 240;
+const uint32_t BLOCK_SIZE = 32 * 1024L;
+uint16_t buffer_size = 0;
 uint32_t threshold = 0;
-
-void message(const __FlashStringHelper *msg)
-{
-	Serial.print(F("M"));
-	Serial.println(msg);
-}

 void setup()
 {
@@ -25,7 +17,7 @@

 void loop()
 {
-	// Flush
+	// Flush the serial input buffer
 	Serial.flush();
 	while (Serial.available() > 0) {
 #if DEBUG
@@ -44,8 +36,8 @@
 	}
 	snprintf(send_buffer_first, sizeof send_buffer_first, fmt, buffer_size);
 	// Choice of threshold
-	threshold = buffer_size * 3 / 4 + 1;
-	//threshold = buffer_size;
+	//threshold = buffer_size * 3 / 4 + 1;
+	threshold = buffer_size;
 	snprintf(send_buffer, sizeof send_buffer, fmt, threshold);
 	//
 	int c = -1;
@@ -68,7 +60,13 @@
 	while (n) {
 		int a;
 		while (n && (a = Serial.available()) > 0) {
+#if DEBUG
+			Serial.print(F("Dn="));
+			Serial.println(n);
+#endif
 			c = Serial.read();
+			// Process the data
+			delayMicroseconds(50);
 #if DEBUG
 			Serial.print(F("Dc = "));
 			Serial.print(c);


Allow mid-game reset. Closes #11

Allow mid-game reset. Closes #11

--- Pingduino/Pingduino.ino
+++ Pingduino/Pingduino.ino
@@ -129,13 +129,11 @@
   // Show the score
   display.refresh(game);

-  // Handle game over actions
-  if (game.over()) {
-    if (requestReset > 0) {
-      game.restart(requestReset);
-      p1Score = p2Score = 0;
-      requestReset = 0;
-    }
+  // Handle game reset
+  if (requestReset > 0) {
+    game.restart(requestReset);
+    p1Score = p2Score = 0;
+    requestReset = 0;
   }

   delay(20);


Remove temporary buffer in ConfigFile.ino (#8298)

When reading from a `Stream`, like `File`, using a temporary buffer is counterproductive because it complexifies the code and increases memory usage.
It's also a source of confusion because it can create dangling pointers in the `JsonDocument`.
The only benefit of using a buffer is the reading speed, but I don't think speed is the focus in this example; if it were, it would use a buffer in `saveConfig()` too.

--- libraries/esp8266/examples/ConfigFile/ConfigFile.ino
+++ libraries/esp8266/examples/ConfigFile/ConfigFile.ino
@@ -11,6 +11,9 @@
 #include "FS.h"
 #include <LittleFS.h>

+// more and possibly updated information can be found at:
+// https://arduinojson.org/v6/example/config/
+
 bool loadConfig() {
   File configFile = LittleFS.open("/config.json", "r");
   if (!configFile) {
@@ -18,22 +21,8 @@
     return false;
   }

-  size_t size = configFile.size();
-  if (size > 1024) {
-    Serial.println("Config file size is too large");
-    return false;
-  }
-
-  // Allocate a buffer to store contents of the file.
-  std::unique_ptr<char[]> buf(new char[size]);
-
-  // We don't use String here because ArduinoJson library requires the input
-  // buffer to be mutable. If you don't use ArduinoJson, you may as well
-  // use configFile.readString instead.
-  configFile.readBytes(buf.get(), size);
-
   StaticJsonDocument<200> doc;
-  auto error = deserializeJson(doc, buf.get());
+  auto error = deserializeJson(doc, configFile);
   if (error) {
     Serial.println("Failed to parse config file");
     return false;


proper conversion from hex string retrieved from rfid reader to bytes, added some delays to give it time to process the rfid

--- autonomo_lorabee/autonomo_lorabee.ino
+++ autonomo_lorabee/autonomo_lorabee.ino
@@ -1,20 +1,16 @@
 #include <Sodaq_RN2483.h>
-
-#define DEBUG
+#include <stdio.h>
+#include <string.h>

 #define debugSerial SerialUSB

+#define rfidSerial Serial
 #define loraSerial Serial1

-const uint8_t devAddr[4]  = { 0x02, 0x01, 0x59, 0x00 };
+byte devAddr[4]  = { 0x02, 0x01, 0x59, 0x00 };
 const uint8_t appSKey[16] = { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6,  0xAB, 0xF7, 0x15, 0x88,  0x09, 0xCF, 0x4F, 0x3C };
 const uint8_t nwkSKey[16] = { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6,  0xAB, 0xF7, 0x15, 0x88,  0x09, 0xCF, 0x4F, 0x3C };

-// GPIO Ports
-const int led = 12;
-const int startButton = 11;
-const int stopButton = 10;
-
 long t = millis();

 boolean charging = false;
@@ -22,81 +18,158 @@
 const byte START = 0x00;
 const byte STOP  = 0x01;

-// get from rifd reader
-const uint8_t RFID[4] = {0xAE, 0x9C, 0x39, 0x12};
-
-void setup()
-{
+char buffer[64]; // buffer array for data receive over serial port
+int count=0;
+
+byte dur[2];
+byte vol[2];
+byte msg[15];
+
+unsigned char charToHexDigit(char c) {
+  if (c >= 'A')
+    return (c - 'A' + 10);
+  else
+    return (c - '0');
+}
+
+unsigned char ascii2HexToByte(char *ptr) {
+  return charToHexDigit( *ptr )*16 + charToHexDigit( *(ptr+1) );
+}
+
+int stringToBytes(char *string, char *result) {
+  int k=0;
+  int strLen = strlen(string);
+
+  for(int i = 0; i < strLen; i = i + 2)
+  {
+      result[k] = ascii2HexToByte( &string[i] );
+      k++;
+  }
+  return k; // number of bytes in the result array
+}
+
+void setup() {
+  digitalWrite(BEE_VCC, HIGH); // turn on lora module
+  pinMode(13, OUTPUT);
+
   debugSerial.begin(57600);
-
-  digitalWrite(BEE_VCC, HIGH);
-
-  pinMode(led, OUTPUT);
-  pinMode(startButton, INPUT);
-  pinMode(stopButton, INPUT);
-
-
+  rfidSerial.begin(9600);
   loraSerial.begin(LoRaBee.getDefaultBaudRate());

   LoRaBee.setDiag(debugSerial); // optional
-  if (LoRaBee.initABP(loraSerial, devAddr, appSKey, nwkSKey, true))
-  {
+  if (LoRaBee.initABP(loraSerial, devAddr, appSKey, nwkSKey, true)) {
     debugSerial.println("Connection to the network was successful.");
   }
-  else
-  {
+  else {
     debugSerial.println("Connection to the network failed!");
   }
 }

-void loop()
-{
-  debugSerial.println("Sleeping for 5 seconds before starting sending out test packets.");
-  for (uint8_t i = 5; i > 0; i--)
-  {
+void loop() {
+  while ((!SerialUSB) && (millis() < 5000)); // wait for usb serial monitor for 5 seconds
+
+  debugSerial.println("Sleeping for 5 seconds");
+  for (uint8_t i = 5; i > 0; i--) {
     debugSerial.println(i);
     delay(1000);
   }

-  while (true)
-  {
-    int startPressed = ! digitalRead(startButton);
-    int stopPressed = ! digitalRead(stopButton);
-
-    if (startPressed && !charging) {
-      charging=true;
-      t = millis();
-      uint8_t startMsg[] = { START, RFID[3], RFID[2], RFID[1], RFID[0] };
-      sendMessage(startMsg, 5);
-      debugSerial.println("Starting Charging");
+  while (true) {
+    if (rfidSerial.available()) {
+
+      delay(200);
+      // read rfid key
+      while(rfidSerial.available()) {
+        buffer[count++]=rfidSerial.read();
+        if(count == 64)break;
+      }
+
+      char buf[6];
+
+      int len = stringToBytes(buffer, buf);
+
+      for(int i= 0; i < len; i++) {
+        debugSerial.print((unsigned char)*(buf+i),HEX);
+      }
+      debugSerial.print( "\n");
+
+      if (!charging) {
+        // start charging
+        charging = true;
+
+        debugSerial.println("Starting charging");
+
+        msg[0] = {START};
+        memcpy(msg+1, buf, 6);
+        memcpy(msg+7, devAddr, 4);
+
+        t = millis();
+
+        sendMessage(msg,11);
+
+        clearMsg();
+
+      } else {
+        // stop charging
+        charging = false;
+
+        debugSerial.println("Stopping charging");
+
+        int duration = (millis()-t)/1000;
+        int volume = random(100);
+
+        debugSerial.println(duration, DEC);
+        debugSerial.println(volume, DEC);
+
+        dur[0] = highByte(duration);
+        dur[1] = lowByte(duration);
+        vol[0] = highByte(volume);
+        vol[1] = lowByte(volume);
+
+        msg[0] = {STOP};
+        memcpy(msg+1, buf, 6);
+        memcpy(msg+7, devAddr, 4);
+        memcpy(msg+11, dur, 2);
+        memcpy(msg+13, vol, 2);
+
+        sendMessage(msg,15);
+
+        clearVolumeAndDuration();
+        clearMsg();
+      }
+      //debugSerial.write(buffer,count);
+
+      clearBufferArray();
+      count = 0;
+      delay(1000);
     }

-    if (stopPressed) {
-      charging=false;
-      int duration = (millis()-t)/1000;
-      int volume = random(100);
-      debugSerial.println("Charged " + String(volume) + " kWh in: " + String(duration) + " seconds");
-      uint8_t stopMsg[] = { STOP, RFID[3], RFID[2], RFID[1], RFID[0], lowByte(duration), highByte(duration), lowByte(volume), highByte(volume) }; //last 2 bytes is volume
-      sendMessage(stopMsg, 9);
-      debugSerial.println("Stopped Charging");
+    //turn led on/off whether or not we're charging
+    if (charging) {
+      digitalWrite(13,HIGH);
+    } else {
+      digitalWrite(13,LOW);
     }
-
-    if (charging) {
-      digitalWrite(12,HIGH);
-    } else {
-      digitalWrite(12,LOW);
-    }
-    delay(100);
-  }
-}
-
-void blinkLed(int times, int len) {
-  for (uint8_t i = times; i > 0; i--) {
-    digitalWrite(13, HIGH);
-    delay(len/2);
-    digitalWrite(13, LOW);
-    delay(len/2);
-  }
+  }
+}
+
+void clearMsg() {
+  for (int i=0; i<15;i++) {
+    msg[i]=NULL;
+  }
+}
+
+void clearBufferArray() {
+  for (int i=0; i<count;i++) {
+    buffer[i]=NULL;
+  }
+}
+
+void clearVolumeAndDuration() {
+  vol[0]=NULL;
+  vol[1]=NULL;
+  dur[0]=NULL;
+  dur[1]=NULL;
 }

 void sendMessage(uint8_t* data, int size) {
@@ -146,3 +219,4 @@
 }

+


Update AD9850.ino

Update AD9850.ino

--- examples/AD9850.ino
+++ examples/AD9850.ino
@@ -1,4 +1,4 @@
-#include <AD9850SPI.h>
+#include <AD9850.h>

 const int W_CLK_PIN = 7;
 const int FQ_UD_PIN = 8;


added dead zones

added dead zones

--- MotorsRX/MotorsRX.ino
+++ MotorsRX/MotorsRX.ino
@@ -38,16 +38,22 @@

 int Joystick1A; //vertical
 int Map1A;
+int Map1ACR;
 int Joystick1B;
 int Map1B;
+int Map1BCR;
 int Joystick1C;
 int Map1C;
+int Map1CCR;
 int Joystick2A; //horizontal
 int Map2A;
+int Map2ACR;
 int Joystick2B;
 int Map2B;
+int Map2BCR;
 int Joystick2C;
 int Map2C;
+int Map2CCR;

 unsigned char checksum0;
 unsigned char checksum1;
@@ -164,14 +170,15 @@
   }
 }
 void MotorWriteBasic() {
+
   H2.writeMicroseconds(Map2B);
   H3.writeMicroseconds(Map2B);
-  H1.writeMicroseconds(Map2A);
-  H4.writeMicroseconds(Map2A);
-
-  V1.writeMicroseconds(Map1A);
+  H1.writeMicroseconds(Map2ACR);
+  H4.writeMicroseconds(Map2ACR);
+
+  V1.writeMicroseconds(Map1ACR);
   V2.writeMicroseconds(Map1A);
-  V3.writeMicroseconds(Map1B);
+  V3.writeMicroseconds(Map1BCR);
   V4.writeMicroseconds(Map1B);
 }

@@ -329,8 +336,8 @@
 //  Serial.print(" ");
 //  Serial.print(Map1C);
 //  Serial.print(" ");
-//  Serial.print(Map2A);
-//  Serial.print(" ");
+  Serial.print(Map2A);
+  Serial.print(" ");
   Serial.print(Map2B);
   Serial.print(" ");
 //  Serial.println(Map2C);
@@ -339,13 +346,83 @@

 void MapJoysticks() { // Maps joysticks for use with ESC
-  Map1A = map(Joystick1A, 0, 1023, 1100, 1900);
-  Map1B = map(Joystick1B, 0, 1023, 1100, 1900);
-  Map1C = map(Joystick1C, 0, 1023, 1100, 1900);
-  Map2A = map(Joystick2A, 0, 1023, 1100, 1900);
-  Map2B = map(Joystick2B, 0, 1023, 1100, 1900);
-  Map2C = map(Joystick2C, 0, 1023, 1100, 1900);
-
+  if (Joystick1A > 600) {
+    Map1A = map(Joystick1A, 600, 1023, 1500, 1900);
+    Map1ACR = map(Joystick1A, 600, 1023, 1500, 1100);
+  }
+  if (Joystick1A < 424) {
+    Map1A = map(Joystick1A, 0, 424, 1100, 1500);
+    Map1ACR = map(Joystick1A, 0, 424, 1900, 1500);
+  }
+  if ((Joystick1A > 424) && (Joystick1A < 600)) {
+    Map1A = 1500;
+    Map1ACR = 1500;
+  }
+
+  if (Joystick1B > 600) {
+    Map1B = map(Joystick1B, 600, 1023, 1500, 1900);
+    Map1BCR = map(Joystick1B, 600, 1023, 1500, 1100);
+  }
+  if (Joystick1B < 424) {
+    Map1B = map(Joystick1B, 0, 424, 1100, 1500);
+    Map1BCR = map(Joystick1B, 0, 424, 1900, 1500);
+  }
+  if ((Joystick1B > 424) && (Joystick1B < 600)) {
+    Map1B = 1500;
+    Map1BCR = 1500;
+  }
+
+  if (Joystick1C > 600) {
+    Map1C = map(Joystick1C, 600, 1023, 1500, 1900);
+    Map1CCR = map(Joystick1C, 600, 1023, 1500, 1100);
+  }
+  if (Joystick1C < 424) {
+    Map1C = map(Joystick1C, 0, 424, 1100, 1500);
+    Map1CCR = map(Joystick1C, 0, 424, 1900, 1500);
+  }
+  if ((Joystick1C > 424) && (Joystick1C < 600)) {
+    Map1C = 1500;
+    Map1CCR = 1500;
+  }
+
+  if (Joystick2A > 600) {
+    Map2A = map(Joystick2A, 600, 1023, 1500, 1900);
+    Map2ACR = map(Joystick2A, 600, 1023, 1500, 1100);
+  }
+  if (Joystick2A < 424) {
+    Map2A = map(Joystick2A, 0, 424, 1100, 1500);
+    Map2ACR = map(Joystick2A, 0, 424, 1900, 1500);
+  }
+  if ((Joystick2A > 424) && (Joystick2A < 600)) {
+    Map2A = 1500;
+    Map2ACR = 1500;
+  }
+
+  if (Joystick2B > 600) {
+    Map2B = map(Joystick2B, 600, 1023, 1500, 1900);
+    Map2BCR = map(Joystick2B, 600, 1023, 1500, 1100);
+  }
+  if (Joystick2B < 424) {
+    Map2B = map(Joystick2B, 0, 424, 1100, 1500);
+    Map2BCR = map(Joystick2B, 0, 424, 1900, 1500);
+  }
+  if ((Joystick2B > 424) && (Joystick2B < 600)) {
+    Map2B = 1500;
+    Map2BCR = 1500;
+  }
+
+  if (Joystick2C > 600) {
+    Map2C = map(Joystick2C, 600, 1023, 1500, 1900);
+    Map2CCR = map(Joystick2C, 600, 1023, 1500, 1100);
+  }
+  if (Joystick2C < 424) {
+    Map2C = map(Joystick2C, 0, 424, 1100, 1500);
+    Map2CCR = map(Joystick2C, 0, 424, 1900, 1500);
+  }
+  if ((Joystick2C > 424) && (Joystick2C < 600)) {
+    Map2C = 1500;
+    Map2CCR = 1500;
+  }
 }

 void DrivingLight() {


Adjust minimum amplitude as well for spacious songs

--- Cymatic-Triangles/getAudio.ino
+++ Cymatic-Triangles/getAudio.ino
@@ -38,8 +38,8 @@

     // strobe to the next frequency
     digitalWrite(STROBE_PIN, HIGH);
+  }

-  }//for i
   return spectrum_total;
 }

@@ -47,14 +47,25 @@
   int current = sound_buffer[0];

   if (current > max_amplitude) {
-      max_amplitude *= 1.01;
+      max_amplitude *= 1.1;
   } else {
-      max_amplitude *= 0.9999;
+      max_amplitude *= 0.9995;
   }

-  if (max_amplitude < min_amplitude) {
-    max_amplitude = min_amplitude;
+  if (current > min_amplitude) {
+      min_amplitude *= 1.0005;
+  } else {
+      min_amplitude *= 0.9;
   }
+
+  if (min_amplitude < 400) {
+    min_amplitude = 400;
+  }
+
+  if (max_amplitude < min_amplitude + 100) {
+    max_amplitude = min_amplitude + 100;
+  }
+
 }

 void updateSoundWave() {


Finally implementeer the sleep function.

Using Ext interrupt to wake.

--- LikeJar_5.ino
+++ LikeJar_5.ino
@@ -6,6 +6,7 @@
 // Soldered on a perfboard with a Kingbright 3 digit 7 segment common cathode LED module.

 // Version history:
+// 0.95: Added check to ignore the button press that wakes the Atmega.
 // 0.94: Added basic avr Sleep untill interrupt. Removed Narcoleptic_m8, didn't work.
 // 0.93: Added Narcoleptic_m8 library and sleep function.
 // 0.92: Beta for 5th version (button pin changed to hardware interrupt pin).
@@ -56,16 +57,19 @@
 const int buttonpin = 2;

 long ticks = 0;
-const byte reset = 6 ;
+byte reset = 6;
 const byte divide = 1;
-int likes;                    // The number of button presses.
+long likes;                     // The number of button presses.
 int num;
 int value;                    // The number displayed on the LEDs.
 int n = 0;
 int buttonState = 0;          // Current state of the button.
 int lastButtonState = 0;      // Previous state of the button.
 long coolDownTicks = 0;       // Hold delay before a new button press is registered.
-unsigned long timer = 0;
+long timer = 0;               // Tick counter, helps count.
+int ignorePress = 0;          // Ignore the button press when coming out of sleep.
+long glowstart = 0;           // To fade in, and out the display.
+long currentglow = 0;         // To fade in, and out the display.

 void setup()
 {
@@ -80,7 +84,6 @@
   pinMode(digit2pin, OUTPUT);
   pinMode(digit3pin, OUTPUT);

-  // Setup specific for prototype 2.
   // Pullup resistor on button pin
   pinMode(buttonpin, INPUT);
   digitalWrite(buttonpin, HIGH);       // turn on pullup resistor
@@ -109,22 +112,6 @@
   // Read the number of Likes from last run.
   eeprom_read_block((void*)&likes, (void*)0, sizeof(likes));

-  /* Now it is time to enable an interrupt. In the function call
-   * attachInterrupt(A, B, C)
-   * A   can be either 0 or 1 for interrupts on pin 2 or 3.
-   *
-   * B   Name of a function you want to execute while in interrupt A.
-   *
-   * C   Trigger mode of the interrupt pin. can be:
-   *             LOW        a low level trigger
-   *             CHANGE     a change in level trigger
-   *             RISING     a rising edge of a level trigger
-   *             FALLING    a falling edge of a level trigger
-   *
-   * In all but the IDLE sleep modes only LOW can be used.
-   */
-  attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
-
   // Serial is only used for debugging.
   // Serial.begin(115200);
 }
@@ -184,6 +171,7 @@
    */

   attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
+  attachInterrupt(1,wakeUpNow, LOW); // use interrupt 1 (pin 3) and run function
   // wakeUpNow when pin 2 gets LOW

   sleep_mode();            // here the device is actually put to sleep!!
@@ -234,7 +222,11 @@
   if (buttonState != lastButtonState) {
     if (buttonState == LOW) {
       // if the current state is LOW then the button was pushed.
-      if (coolDownTicks == 0)
+      if (ignorePress == 1)
+      {
+        ignorePress = 0;
+      }
+      else if (coolDownTicks == 0)
       {
         likes++;
         coolDownTicks = 2000;
@@ -247,20 +239,33 @@
       }
       // There was an interaction, reset the sleep timer.
       timer = 0;
+      // Reset the dim value.
+      reset = 6;
     }
   }
   // save the current state as the last state,
   // for next time through the loop
   lastButtonState = buttonState;

-  if (timer > 30000)
+  // The timer that sleeps the device.
+  // 30000 ticks is about 26 seconds.
+  // 2076921 is about 30 minutes.
+  if (timer > 2076921)
+  //if (timer > 10000)
+  {
+    reset = 20;
+  }
+
+  // 8307692 is about 2 hours.
+  if (timer > 8307692)
+  //if (timer > 30000)
   {
     digitalWrite(digit1pin,0);
     digitalWrite(digit3pin,0);
     digitalWrite(digit2pin,0);
     sleepNow();     // sleep function called here
-//    coolDownTicks = 100;
-    lastButtonState = buttonState;
+    ignorePress = 1;
+    timer = 0;
   }

   //////////////
@@ -280,7 +285,7 @@
   }

   // Middle significant digit
-  if(n == 2)
+  else if(n == 3)
   {
     digitalWrite(digit1pin,0);
     digitalWrite(digit3pin,0);
@@ -290,7 +295,7 @@
   }

   // Least significant digit
-  if(n == 3)
+  else if(n == 5)
   {
     digitalWrite(digit1pin,0);
     digitalWrite(digit2pin,0);
@@ -306,7 +311,7 @@
   }

   // The rest of the time the leds are off, saves 10 mA power.
-  if(n > 3)
+  else
   {
      digitalWrite(digit1pin,0);
      digitalWrite(digit2pin,0);


Corrections to the setpoint

Corrections to the setpoint

bich

--- Firmware/R2-Quadcopter/PID.ino
+++ Firmware/R2-Quadcopter/PID.ino
@@ -33,20 +33,17 @@
 void pid_setpoint_update() {
   /* Ici on regarde si le stick est au milieu et on laisse une marg
    * d'erreur pour que quand on le lache, il donne une erraur nulle. */
-  if (input[0] > THROTTLE_RMID - 20 && input[0] < THROTTLE_RMID + 20)
-    pid_roll_setpoint = 0;
-  else
-    pid_roll_setpoint = map(input[0], ROLL_RMIN, ROLL_RMAX, ROLL_WMIN, ROLL_WMAX);
+  pid_roll_setpoint = 0;
+  if(input[0] > THROTTLE_RMID+10)pid_roll_setpoint = (input[0]-THROTTLE_RMID+10)/2;
+  else if(input[0] < THROTTLE_RMID-10)pid_roll_setpoint = (input[0]-THROTTLE_RMID-10)/2;
   // PITCH rx at mid level? +-20ms
-  if (input[1] > THROTTLE_RMID - 20 && input[1] < THROTTLE_RMID + 20)
-    pid_pitch_setpoint = 0;
-  else
-    pid_pitch_setpoint = map(input[1], PITCH_RMIN, PITCH_RMAX, PITCH_WMIN, PITCH_WMAX);
+  pid_pitch_setpoint = 0;
+  if(input[1] > THROTTLE_RMID+10)pid_pitch_setpoint = (input[1]-THROTTLE_RMID+10)/2;
+  else if(input[1] < THROTTLE_RMID-10)pid_pitch_setpoint = (input[1]-THROTTLE_RMID-10)/2;
   //YAW rx mid +-20ms
-  if (input[3] > THROTTLE_RMID - 20 && input[3] < THROTTLE_RMID + 20)
-    pid_yaw_setpoint = 0;
-  else
-    pid_yaw_setpoint = map(input[3], YAW_RMIN, YAW_RMAX, YAW_WMIN, YAW_WMAX);
+  pid_yaw_setpoint = 0;
+  if(input[3] > THROTTLE_RMID+10)pid_yaw_setpoint = (input[3]-THROTTLE_RMID+10)/2;
+  else if(input[3] < THROTTLE_RMID-10)pid_yaw_setpoint = (input[3]-THROTTLE_RMID-10)/2;
 }

 // Calculer les termes der et int pour l'intervalle delta-temps


Toggle

Toggle

--- fingerprint.ino
+++ fingerprint.ino
@@ -2,7 +2,7 @@

 //Error pin to flash on error
 int ERROR_PIN = 13;
-int LIGHT_PIN = 7;
+int PWM_PIN = 3;
 /**
  * Enumeration of commands
  * Value set to control code of command
@@ -26,7 +26,6 @@
   NAK = 0x31,
   DELETE_ALL = 0x41
 } Command;
-
 /**
  * Command structure
  */
@@ -50,6 +49,7 @@
 void start();
 void enroll(Command cmd, uint32_t param);
 //Utility functions
+void toggle();
 void flash(uint32_t num,int time);
 //Error leaf function
 void error(uint32_t error);
@@ -71,8 +71,7 @@
 void setup()
 {
   pinMode(ERROR_PIN, OUTPUT);
-  pinMode(LIGHT_PIN, OUTPUT);
-  digitalWrite(LIGHT_PIN,HIGH);
+  pinMode(PWM_PIN, OUTPUT);
   Serial.begin(9600);
   //Wait for the serial pins to connect (May only be needed for Leonardo board)
   while (!Serial) {}
@@ -80,7 +79,7 @@
   CommandPacket* led = getCommand(CMOS_LED);
   setParameter(led,1);
   sendCommand(led);
-  delay(1000);
+  delay(500);
   setParameter(led,0);
   sendCommand(led);
   free(led);
@@ -116,14 +115,19 @@
   free(cmd);
   //Get number enrolled...if zero, enroll
   cmd = getCommand(GET_ENROLL_COUNT);
-  uint32_t param = sendCommand(cmd);
+  uint32_t cnt = sendCommand(cmd);
   free(cmd);
-  flash(param,100);
-  if (param == 0)
+  //Is there a finger
+  cmd = getCommand(IS_PRESS_FINGER);
+  uint32_t fin = sendCommand(cmd);
+  free(cmd);
+  //If no figers, or a finger is actively on scanner
+  //Learn a new one
+  if (cnt == 0 || fin  == 0)
   {
     //Signal enroll
     flash(3,300);
-    enroll(ENROLL_START,param);
+    enroll(ENROLL_START,cnt);
   }
 }
 /**
@@ -152,7 +156,7 @@
       param = sendCommand(packet);
       setParameter(led,0);
       sendCommand(led);
-      delay(1000);
+      delay(500);
       enroll((Command)(cmd+1),0);
     case ENROLL3+1:
       break;
@@ -161,23 +165,31 @@
   free(led);
 }
 /**
- * Flashes LED
+ * Toggle the light.
+ */
+void toggle() {
+  static uint8_t out = 0;
+  out = (out == 0) ? 99 : out - 33;
+  analogWrite(PWM_PIN,(((uint16_t)out)*256)/100);
+}
+
+/**
+ * Loops waiting for finger print.
  */
 void loop()
 {
   CommandPacket* led = getCommand(CMOS_LED);
   setParameter(led,1);
   sendCommand(led);
-
   CommandPacket* finger = getCommand(IS_PRESS_FINGER);
   while (sendCommand(finger) != 0) {}
   free(finger);
   CommandPacket* id = getCommand(IDENTIFY);
   if(sendCommand(id) < 199) {
-    digitalWrite(LIGHT_PIN,!digitalRead(LIGHT_PIN));
+    toggle();
     setParameter(led,0);
     sendCommand(led);
-    delay(1000);
+    delay(500);
   }
   free(id);
   free(led);
@@ -255,8 +267,6 @@
   uint32_t param = packet->param;
   uint16_t cmd = packet->cmd;
   free(packet);
-  //if (cmd == NAK)
-  //  error(param);
   return param;
 }
 /**
@@ -268,12 +278,6 @@
 {
   fillChecksum(bytes,len);
   int i = 0;
-  /*Serial.print("< ");
-  for (i = 0; i < len; i++) {
-    Serial.print(bytes[i],HEX);
-    Serial.print(" ");
-  }
-  Serial.println();*/
   if (Serial.write(bytes,len) != len)
     error(10);
 }


added debug variable

added debug variable

--- Arduino/Turnstyle/Turnstyle.ino
+++ Arduino/Turnstyle/Turnstyle.ino
@@ -39,6 +39,9 @@
 int population = 0;          // current population of the room
 unsigned long closeLastTime = 0, farLastTime = 0; // The last times a person was detected at the close and far sensors, respectively.  Note that 0 means the last detection never happened or happened too long ago.

+// FOR DEBUGGING -- SET TO FALSE TO USE WITH NODE SERVER
+boolean debug = true;
+
 // SETUP
 void setup() {
   Serial.begin(9600);
@@ -87,9 +90,9 @@

     if (doorAngle < OPEN_ANGLE) { // Door is closed
       closeDoor();
-      Serial.println("Door not open");
+      printIfDebug("Door not open");
     } else if (microsNow - microsLastRead < microsBetweenReads) { // Door is open, a movement was recently detected, and we are waiting between movements; do not double count or re-record the last passing time because the person may still be passing through.
-      Serial.println("Movement Detected");
+      printIfDebug("Movement Detected");
     } else { // Door is open, but a complete movement has not been discovered recently.
       openDoor();
       ping_1 = sonar_1.ping_cm();
@@ -180,6 +183,16 @@
   lcd.setCursor(12, 0);
   lcd.print(population);
   lcd.setCursor(0, 1);
+
+  if (debug) {
+    Serial.print("Population: ");
+  }
+  Serial.print(population);
+  if (!debug) {
+    Serial.println("*");
+  } else {
+    Serial.println();
+  }
   farLastTime = 0;
   closeLastTime = 0;
   microsLastRead = micros();
@@ -211,11 +224,19 @@
 }

 void printinfo(float doorAngle, int ping_1, int ping_2) {
-  Serial.print("Door Angle: ");
-  Serial.print(doorAngle);
-  Serial.print(" | Ping 1: ");
-  Serial.print(ping_1); // Send ping, get distance in cm and print result (0 = outside set distance range)
-  Serial.print(" cm | Ping 2: ");
-  Serial.print(ping_2); // Send ping, get distance in cm and print result (0 = outside set distance range)
-  Serial.println(" cm");
-}
+  if (debug) {
+    Serial.print("Door Angle: ");
+    Serial.print(doorAngle);
+    Serial.print(" | Ping 1: ");
+    Serial.print(ping_1); // Send ping, get distance in cm and print result (0 = outside set distance range)
+    Serial.print(" cm | Ping 2: ");
+    Serial.print(ping_2); // Send ping, get distance in cm and print result (0 = outside set distance range)
+    Serial.println(" cm");
+  }
+}
+
+void printIfDebug(String message) {
+  if (debug) {
+    Serial.println(message);
+  }
+}


added dimming for connect/disconnect

added dimming for connect/disconnect

mostly implements #28
there is a need for a trailing preamble still to do but it needs a coordinated effort between the windows code and the arduino code. if the trailing preamble (=postamble?) is not used, it is impossible to decide whether the serial connection was lost or the screen is just black!

--- Arduino/adrilight/adrilight.ino
+++ Arduino/adrilight/adrilight.ino
@@ -2,7 +2,6 @@

 #define NUM_LEDS (2*73+2*41)
 #define LED_DATA_PIN 3
-#define NUM_BYTES (NUM_LEDS*3) // 3 colors

 #define BRIGHTNESS 255
 #define UPDATES_PER_SECOND 60
@@ -14,17 +13,16 @@
 #define MODE_BLACK 2
 uint8_t mode = MODE_ANIMATION;

+uint8_t currentBrightness = BRIGHTNESS;
 byte MESSAGE_PREAMBLE[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 };
 uint8_t PREAMBLE_LENGTH = 10;
 uint8_t current_preamble_position = 0;

 unsigned long last_serial_available = -1L;

-int led_counter = 0;
-int byte_counter = 0;
-
 CRGB leds[NUM_LEDS];
-byte buffer[NUM_BYTES];
+CRGB leds2[NUM_LEDS];
+byte buffer[3];

 // Filler animation attributes
 CRGBPalette16 currentPalette = RainbowColors_p;
@@ -33,118 +31,134 @@

 void setup()
 {
-    Serial.begin(1000000); // 115200
-    FastLED.clear(true);
-    FastLED.addLeds<WS2812B, LED_DATA_PIN, GRB>(leds, NUM_LEDS);
-    FastLED.setBrightness(BRIGHTNESS);
+  Serial.begin(1000000);
+  FastLED.clear(true);
+  FastLED.addLeds<WS2812B, LED_DATA_PIN, GRB>(leds, NUM_LEDS);
+  FastLED.setBrightness(currentBrightness);
+  FastLED.setDither(0);
 }

 void loop()
 {
-    switch (mode) {
-        case MODE_ANIMATION:
-            fillLEDsFromPaletteColors();
-            break;
-
-        case MODE_AMBILIGHT:
-            processIncomingData();
-            break;
+  switch (mode) {
+    case MODE_ANIMATION:
+      fillLEDsFromPaletteColors();
+      break;

-            case MODE_BLACK:
-            showBlack();
-            break;
-    }
-
+    case MODE_AMBILIGHT:
+      processIncomingData();
+      break;
+
+    case MODE_BLACK:
+      showBlack();
+      break;
+  }
 }
-
 void processIncomingData()
 {
-    if (waitForPreamble(TIMEOUT))
+  if (waitForPreamble(TIMEOUT))
+  {
+    for (int ledNum = 0; ledNum < NUM_LEDS; ledNum++)
     {
-        Serial.readBytes((char*)buffer, NUM_BYTES);
+      //we always have to read 3 bytes (RGB!)
+      //if it is less, we ignore this frame and wait for the next preamble
+      if (Serial.readBytes((char*)buffer, 3) < 3) return;

-        while (byte_counter < NUM_BYTES)
-        {
-            byte blue = buffer[byte_counter++];
-            byte green = buffer[byte_counter++];
-            byte red = buffer[byte_counter++];
-
-            leds[led_counter++] = CRGB(red, green, blue);
-        }
+      byte blue = buffer[0];
+      byte green = buffer[1];
+      byte red = buffer[2];

-        FastLED.show();
-
-        // flush the serial buffer to avoid flickering
-        while(Serial.available()) { Serial.read(); }
-
-        byte_counter = 0;
-        led_counter = 0;
+      //there should be a last "invisible color" because black is actually possible!
+      if (ledNum == NUM_LEDS-1 && red == 0 && blue == 0 && green == 0) return;
+
+      //debug: show black as red!
+      //if (red == 0 && blue == 0 && green == 0) red = 255;
+
+      leds2[ledNum] = CRGB(red, green, blue);
     }
-    else
+    for (int ledNum = 0; ledNum < NUM_LEDS; ledNum++)
     {
-        //if we get here, there must have been data before(so the user already knows, it works!)
-        //simply go to black!
-        mode = MODE_BLACK;
+      leds[ledNum]=leds2[ledNum];
     }
+    if (currentBrightness < BRIGHTNESS)
+    {
+      currentBrightness++;
+      FastLED.setBrightness(currentBrightness);
+    }
+
+      //this should only be done, if a trailing preamble (=postamble?) is received.
+      //If it is not received, it is possible, the connection was lost and the LED
+      //buffer should not be used
+
+      //send LED data to actual LEDs
+      FastLED.show();
+  }
+  else
+  {
+    //if we get here, there must have been data before(so the user already knows, it works!)
+    //simply go to black!
+    mode = MODE_BLACK;
+  }
 }

 bool waitForPreamble(int timeout)
 {
-    last_serial_available = millis();
-    current_preamble_position = 0;
-    while (current_preamble_position < PREAMBLE_LENGTH)
+  last_serial_available = millis();
+  current_preamble_position = 0;
+  while (current_preamble_position < PREAMBLE_LENGTH)
+  {
+    if (Serial.available() > 0)
     {
-        if (Serial.available() > 0)
-        {
-            last_serial_available = millis();
+      last_serial_available = millis();

-            if (Serial.read() == MESSAGE_PREAMBLE[current_preamble_position])
-            {
-                current_preamble_position++;
-            }
-            else
-            {
-                current_preamble_position = 0;
-            }
-        }
+      if (Serial.read() == MESSAGE_PREAMBLE[current_preamble_position])
+      {
+        current_preamble_position++;
+      }
+      else
+      {
+        current_preamble_position = 0;
+      }
+    }

-        if (millis() - last_serial_available > timeout)
-        {
-            return false;
-        }
+    if (millis() - last_serial_available > timeout)
+    {
+      return false;
     }
-    return true;
+  }
+  return true;
 }

 void fillLEDsFromPaletteColors()
 {
-    startIndex++;
+  startIndex++;

-    uint8_t colorIndex = startIndex;
-    for( int i = 0; i < NUM_LEDS; i++) {
-            leds[i] = ColorFromPalette(currentPalette, colorIndex, BRIGHTNESS, currentBlending);
-            colorIndex += 3;
-        }
+  uint8_t colorIndex = startIndex;
+  for ( int i = 0; i < NUM_LEDS; i++) {
+    leds[i] = ColorFromPalette(currentPalette, colorIndex, BRIGHTNESS, currentBlending);
+    colorIndex += 3;
+  }

-    FastLED.delay(1000 / UPDATES_PER_SECOND);
+  FastLED.delay(1000 / UPDATES_PER_SECOND);

-    if (Serial.available() > 0)
-    {
-        mode = MODE_AMBILIGHT;
-    }
+  if (Serial.available() > 0)
+  {
+    mode = MODE_AMBILIGHT;
+  }
 }

 void showBlack()
-{
-    for( int i = 0; i < NUM_LEDS; i++)
-    {
-        leds[i] = CRGB(0,0,0);
-    }
-    FastLED.delay(1000 / UPDATES_PER_SECOND);
+{
+  if (currentBrightness > 0)
+  {
+    currentBrightness--;
+    FastLED.setBrightness(currentBrightness);
+  }

-    if (Serial.available() > 0)
-    {
-        mode = MODE_AMBILIGHT;
-    }
+  FastLED.delay(1000 / UPDATES_PER_SECOND);
+
+  if (Serial.available() > 0)
+  {
+    mode = MODE_AMBILIGHT;
+  }
 }
-