Delete comunicacaoNano.ino

Delete comunicacaoNano.ino

--- MarceloForesto/RobotArchitecture/comunicacaoNano.ino
+++ MarceloForesto/RobotArchitecture/comunicacaoNano.ino
@@ -1,115 +0,0 @@
-/*
-  Software serial multple serial test
- Receives from the hardware serial, sends to software serial.
- Receives from software serial, sends to hardware serial.
- The circuit:
- * RX is digital pin 10 (connect to TX of other device)
- * TX is digital pin 11 (connect to RX of other device)
- Note:
- Not all pins on the Mega and Mega 2560 support change interrupts,
- so only the following can be used for RX:
- 10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69
- Not all pins on the Leonardo and Micro support change interrupts,
- so only the following can be used for RX:
- 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).
- created back in the mists of time
- modified 25 May 2012
- by Tom Igoe
- based on Mikal Hart's example
- This example code is in the public domain.
- ls --color=never
- */
-#include <SoftwareSerial.h>
-#include <SPI.h>
-#include <MFRC522.h>
-
-#define SS_PIN 10
-#define RST_PIN 9
-
-MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class
-
-MFRC522::MIFARE_Key key;
-
-SoftwareSerial mySerial(7, 8); // RX, TX
-
-byte  serIn;
-int code[] = {32,154,149,117}; //This is the stored UID (Unlock Card)
-int codeRead = 0;
-String uidString;
-String rfidCode;
-char charBuf[50];
-
-void setup() {
-  pinMode(13,OUTPUT);
-  // Open serial communications and wait for port to open:
-  Serial.begin(115200);
-  SPI.begin(); // Init SPI bus
-  rfid.PCD_Init(); // Init MFRC522
-  while (!Serial) {
-    ; // wait for serial port to connect. Needed for native USB port only
-  }
-
-  // set the data rate for the SoftwareSerial port
-  mySerial.begin(115200);
-
-}
-
-void loop() { // run over and over
-  if(mySerial.available()>0){
-          serIn = mySerial.read();
-          Serial.println(char(serIn));
-          if (char(serIn) == '1'){
-            digitalWrite(13,HIGH);
-            mySerial.write("Ligou");
-          }
-          if (char(serIn) == '0'){
-            digitalWrite(13,LOW);
-            mySerial.write("Desligou");
-          }
-          if (char(serIn) == '2'){
-            while (!rfid.PICC_IsNewCardPresent());
-            readRFID();
-
-            delay(100);
-          }
-  }
-}
-
-
-void readRFID()
-{
-
-  rfid.PICC_ReadCardSerial();
-  MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
-
-  // Check is the PICC of Classic MIFARE type
-  if (piccType != MFRC522::PICC_TYPE_MIFARE_MINI &&
-    piccType != MFRC522::PICC_TYPE_MIFARE_1K &&
-    piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
-    return;
-  }
-
-
-
-    printDec(rfid.uid.uidByte, rfid.uid.size);  //imprime o RFID
-
-    uidString = String(rfid.uid.uidByte[0])+" "+String(rfid.uid.uidByte[1])+" "+String(rfid.uid.uidByte[2])+ " "+String(rfid.uid.uidByte[3]);
-
-
-    // Halt PICC
-  rfid.PICC_HaltA();
-
-  // Stop encryption on PCD
-  rfid.PCD_StopCrypto1();
-}
-
-void printDec(byte *buffer, byte bufferSize) {
-  for (byte i = 0; i < bufferSize; i++) {
-    rfidCode = rfidCode + buffer[i];
-  }
-  rfidCode.toCharArray(charBuf, 50);
-  mySerial.write(charBuf);
-
-  rfidCode = "";
-  memset(charBuf, 0, sizeof(charBuf));
-}


push pull

push pull

--- discont/Motor_Shield/MotorShield/MotorShield.ino
+++ discont/Motor_Shield/MotorShield/MotorShield.ino
@@ -11,7 +11,7 @@
 volatile int tickDataRight = 0;
 volatile int tickDataLeft = 0;

-const float ticksPerRev = 200.0;
+const float ticksPerRev = 48.0;
 const float gearRatio = 32.0;
 const float wheelCir = 1.092; // Meters
 const float metersPerTick = wheelCir / (ticksPerRev * gearRatio);
@@ -78,8 +78,8 @@
   pinMode(rightDisable, OUTPUT);
   pinMode(leftForwardSpeed, OUTPUT);
   pinMode(leftBackwardSpeed, OUTPUT);
-  attachInterrupt(1, tickRight, CHANGE);
-  attachInterrupt(0, tickLeft, CHANGE);
+  attachInterrupt(digitalPinToInterrupt(3), tickRight, CHANGE);
+  attachInterrupt(digitalPinToInterrupt(2), tickLeft, CHANGE);

   delay(1000);

@@ -93,9 +93,6 @@
   Serial.println();
   Serial.flush();
   Serial.println("Ready");
-
-  setPwmFrequency(6, 1);
-  setPwmFrequency(9, 1);
 }

 boolean gotCommand = false;
@@ -132,6 +129,13 @@
 	PWM_L = 0;
 	PWM_R = 0;
   }*/
+    Serial.print('$');
+  Serial.print(actualSpeedL);
+  Serial.print(',');
+  Serial.print(actualSpeedR);
+  Serial.print(',');
+  Serial.print(dT_sec);
+  Serial.print('\n');
   desiredSpeedL = 1.0;
   desiredSpeedR = 1.0;


fix code

fix code

--- little-switches/arduino/galoppo/galoppo.ino
+++ little-switches/arduino/galoppo/galoppo.ino
@@ -23,6 +23,7 @@
 long t6 = 0;

 int tempo = 0;
+float w = 0;

 void setup() {
   delay(1000);
@@ -49,9 +50,10 @@
 }

 void loop() {
-  tempo = map(analogRead(pot),0,1023,50,200);
+  w = map(analogRead(pot),0,1023,0.25,3);
+
   Serial.print("tempo: ");
-  Serial.print(tempo);
+  Serial.print(w);
   Serial.println(" ms");

   if (keyboard.available()) {
@@ -59,40 +61,22 @@
     char c = keyboard.read();

     if (c == '1') {
-      digitalWrite(zampaAS,HIGH);
-      t1 = millis();
-    } else if (c == '2') {
-      digitalWrite(zampaAD,HIGH);
-      t2 = millis();
-    } else if (c == '3') {
-      digitalWrite(zampaPS,HIGH);
-      t3 = millis();
-    } else if (c == '4') {
-      digitalWrite(zampaPD,HIGH);
-      t4 = millis();
-    } else if (c == 'p') {
+      galoppo(w);
+    }
+    else if (c == 'p') {
       digitalWrite(piede,HIGH);
       t5 = millis();
-    } else if (c == 't') {
+    }
+    else if (c == 't') {
       digitalWrite(tamburo,HIGH);
       t6 = millis();
     }
-
-
+
   }

   else {
-    if ((millis() - t1) > tempo) {
-      digitalWrite(zampaAS,LOW);
-    }
-    if ((millis() - t2) > tempo) {
-      digitalWrite(zampaAD,LOW);
-    }
-    if ((millis() - t3) > tempo) {
-      digitalWrite(zampaPS,LOW);
-    }
-    if ((millis() - t4) > tempo) {
-      digitalWrite(zampaPD,LOW);
+    if ((millis() - t5) > tempo) {
+      digitalWrite(piede,LOW);
     }
     if ((millis() - t5) > tempo) {
       digitalWrite(piede,LOW);
@@ -102,3 +86,39 @@
     }
   }
 }
+
+void galoppo(float v) {
+  bool fine=false;
+  long ii = millis();
+  while (!fine) {
+    digitalWrite(zampaPS,HIGH);
+    if ((millis() - ii) > (300*v) {
+      digitalWrite(zampaPS,LOW);
+    }
+
+    if ((millis() - ii) > (75*v)) {
+      digitalWrite(zampaPD,HIGH);
+    }
+    if ((millis() - ii) > (375*v)) {
+      digitalWrite(zampaPD,LOW);
+    }
+
+    if ((millis() - ii) > (150*v)) {
+      digitalWrite(zampaAS,HIGH);
+    }
+    if ((millis() - ii) > (450*v)) {
+      digitalWrite(zampaAS,HIGH);
+    }
+
+    if ((millis() - ii) > (225*v)) {
+      digitalWrite(zampaAD,HIGH);
+    }
+    if ((millis() - ii) > (525*v)) {
+      digitalWrite(zampaAD,HIGH);
+    }
+
+
+
+    digitalWrite(zampaAD,HIGH);
+  }
+}


fix merger

fix merger

--- _arduino/ardu/estado.ino
+++ _arduino/ardu/estado.ino
@@ -18,7 +18,6 @@
   _saveAddY=0;
   start=false;
 }
-
 void sendData(){
   Serial.print(xyzp[0]);
   Serial.print(',');
@@ -26,7 +25,6 @@
   Serial.print(',');
   Serial.println(xyzp[2]);
 }
-
 void TakeOrigin(){
   if(x==true||y==true||z==true){
     bx = digitalRead(btnX);
@@ -51,7 +49,6 @@
   addX = 0;
   addY = 0;
   double auxX=xyzp[0],auxY=xyzp[1];
-
   // si son distintos realizo calculos para corregir errores
   if(auxX!=auxY){
     if(auxX<0){auxX = auxX*-1;}


Examples: update FreqShifter_FD for revised class name

--- examples/04-FrequencyDomain/FrequencyShifter_FD/FrequencyShifter_FD.ino
+++ examples/04-FrequencyDomain/FrequencyShifter_FD/FrequencyShifter_FD.ino
@@ -42,7 +42,7 @@
 //create audio library objects for handling the audio
 Tympan                        audioHardware(TympanRev::D);     //do TympanRev::C or TympanRev::D
 AudioInputI2S_F32             i2s_in(audio_settings);          //Digital audio *from* the Tympan AIC.
-AudioEffectFreqShiftFD_F32    freqShift(audio_settings);       //create the frequency-domain processing block
+AudioEffectFreqShift_FD_F32    freqShift(audio_settings);      //Freq domain processing!  https://github.com/Tympan/Tympan_Library/blob/master/src/AudioEffectFreqShiftFD_F32.h
 AudioEffectGain_F32           gain1;                           //Applies digital gain to audio data.
 AudioOutputI2S_F32            i2s_out(audio_settings);         //Digital audio out *to* the Tympan AIC.


Further work on the example

Further work on the example

--- examples/AnalogKeysExample/AnalogKeysExample.ino
+++ examples/AnalogKeysExample/AnalogKeysExample.ino
@@ -4,7 +4,47 @@
 	Released into the public domain.
 */

+#include <LiquidCrystal.h>
 #include <AnalogKeys.h>

-AnalogKeys AnalogKeys();
+// LCD variables
+#define rs 8
+#define enable 9
+#define d4 4
+#define d5 5
+#define d6 6
+#define d7 7

+LiquidCrystal lcd(rs, enable, d4, d5, d6, d7);
+
+//AnalogKey Variables
+#define KEYSLENGTH (sizeof(keys) / sizeof(char *))
+#define TRIES 40 // Number of times analog data is read while calibrating
+#define CALIBRATIONTIME 800 // Nmber of ms each key takes to calibrate
+#define TIMEPERKEY (CALIBRATIONTIME / TRIES)
+#define INPUTPIN 0
+
+char* keys [] = {"NONE", "LEFT", "RIGHT", "UP", "DOWN", "SELECT"};
+int analogValues [KEYSLENGTH] = {};
+
+AnalogKeys analogKeys(&lcd, INPUTPIN, keys, KEYSLENGTH, analogValues);
+
+boolean needsCalibration = true;
+
+void setup () {
+  needsCalibration = true;
+}
+
+void loop () {
+   if (needsCalibration) {
+       analogKeys.calibrateKeys(TRIES, TIMEPERKEY);
+       needsCalibration = false;
+   }
+   lcd.clear();
+   lcd.setCursor(0, 0);
+   lcd.print("Press a key");
+   lcd.setCursor(0, 1);
+   lcd.print("Pressed: ");
+   lcd.print(analogKeys.getPressedKey());
+   delay(200);
+}


Cleaning up setup variables and adding comments.

--- src/rx5808-pro-diversity/rx5808-pro-diversity.ino
+++ src/rx5808-pro-diversity/rx5808-pro-diversity.ino
@@ -96,8 +96,8 @@
 uint8_t rssi_scaled = 0;
 uint8_t active_receiver = useReceiverA;
 #ifdef USE_DIVERSITY
-uint8_t diversity_mode = useReceiverAuto;
-char diversity_check_count = 0;
+    uint8_t diversity_mode = useReceiverAuto;
+    char diversity_check_count = 0; // used to decide when to change antennas.
 #endif
 uint8_t rssi_seek_threshold = RSSI_SEEK_TRESHOLD;
 uint8_t hight = 0;
@@ -119,20 +119,19 @@
 uint8_t last_dip_band=255;
 uint8_t scan_start=0;
 uint8_t first_tune=1;
-uint8_t force_menu_redraw=0;
+boolean force_menu_redraw=0;
 uint16_t rssi_best=0; // used for band scaner
 uint16_t rssi_min_a=0;
 uint16_t rssi_max_a=0;
 uint16_t rssi_setup_min_a=0;
 uint16_t rssi_setup_max_a=0;
 #ifdef USE_DIVERSITY
-uint16_t rssi_min_b=0;
-uint16_t rssi_max_b=0;
-uint16_t rssi_setup_min_b=0;
-uint16_t rssi_setup_max_b=0;
-#endif
-uint16_t rssi_seek_found=0;
-uint16_t rssi_setup_run=0;
+    uint16_t rssi_min_b=0;
+    uint16_t rssi_max_b=0;
+    uint16_t rssi_setup_min_b=0;
+    uint16_t rssi_setup_max_b=0;
+#endif
+uint8_t rssi_setup_run=0;

 char call_sign[10];
 bool settings_beeps = true;
@@ -230,11 +229,6 @@
 #endif
     force_menu_redraw=1;

-    // tune to first channel
-
-    // Setup Done - LED ON
-    digitalWrite(led, HIGH);
-
     // Init Display
     if (drawScreen.begin(call_sign) > 0) {
         // on Error flicker LED
@@ -250,11 +244,13 @@
 #endif

 #ifdef USE_DIVERSITY
-    // make sure we use receiver A when diveristy is unplugged.
+    // make sure we use receiver Auto when diveristy is unplugged.
     if(!isDiversity()) {
-        diversity_mode = useReceiverA;
-    }
-#endif
+        diversity_mode = useReceiverAuto;
+    }
+#endif
+    // Setup Done - Turn Status LED off.
+    digitalWrite(led, LOW);

 }


Get GPS running

Get GPS running

--- src/communication.ino
+++ src/communication.ino
@@ -138,7 +138,7 @@
                 break;
         case 3: // base62 short form
                 // build a dateTime string, convert it to long, then to base62
-                tempDateTimeString += convertToBase62(year - 2000);
+                tempDateTimeString += convertToBase62(year % 100);
                 tempDateTimeString += convertToBase62(month);
                 tempDateTimeString += convertToBase62(day);
                 tempDateTimeString += convertToBase62(hour);


remove warning. new iOS released with fix.

--- examples/Widgets/LED/LED.ino
+++ examples/Widgets/LED/LED.ino
@@ -67,7 +67,6 @@
   }
 }

-//WARNING Led fading is not yes supported on iOS app.
 void fadeLedWidget()
 {
   static int value = 0;


General tweaks

General tweaks

--- apollo/apolloClient/apolloClient.ino
+++ apollo/apolloClient/apolloClient.ino
@@ -153,20 +153,19 @@
         }
       }
 end:
-
       Serial.println(F("done waiting for data"));
       Serial.println();
-      Serial.print(F("Prepended Value = "));
-
-      int prependedSize = twoBytes();
+      Serial.print(F("File size = "));
+
+      unsigned int prependedSize = twoBytes();
       unsigned int checksum = twoBytes();

       Serial.print(prependedSize);
       Serial.println(F(" bytes"));
-      Serial.print(F("Prepended checksum = "));
+      Serial.print(F("File checksum = "));
       Serial.println(checksum);
-      Serial.print(F("Data: "));
-      int i = 0;
+      Serial.print(F("Receiving Data: "));
+      int bytesReceived = 0;
       byte sum1 = 0;
       byte sum2 = 0;

@@ -174,53 +173,54 @@
         while (client.available()) {
           byte e = client.read();

-          if (i == 0) {
+          if (bytesReceived == 0) {
             Serial.print(F("0% "));
           }
-          if (i % (prependedSize / 64) == 0) {
+          else if (bytesReceived % (prependedSize / 64) == 0) {
             Serial.print(F("."));
           }
-          if (i == prependedSize - 1) {
+          else if (bytesReceived == prependedSize - 1) {
             Serial.print(F(" 100%"));
           }

           file.write(e);
           sum1 = (sum1 + e) % 255;
           sum2 = (sum2 + sum1) % 255;
-          i++;
+          bytesReceived++;
         }
       }
+
       unsigned int computedChecksum = sum1 << 8;
       computedChecksum |= sum2;
-
+
       Serial.println();
-      Serial.print("Computed Checksum = ");
-      Serial.print(computedChecksum);
-
-      file.close();
-      Serial.println();
-      Serial.print(i);
-      Serial.println(F(" Bytes Received."));
-      if (prependedSize <= 0 || prependedSize != i || checksum != computedChecksum) {
-        Serial.println(F("ERROR RECEIVING FIRMWARE!"));
-      }
-      else {
-        Serial.println(F("SUCCESS!"));
-      }
+      Serial.print(F("Computed Checksum = "));
+      Serial.println(computedChecksum);
+
+      if (prependedSize == bytesReceived && checksum == computedChecksum) {
+        Serial.println(F("File check: OK"));
+      }
+      else if (checksum != computedChecksum) {
+        Serial.println(F("File check: CHECKSUM ERROR!"));
+      }
+      else if (prependedSize != bytesReceived) {
+        Serial.println(F("File check: FILE SIZE ERROR!"));
+      }
+
       if (!client.connected()) {
         Serial.println(F("Disconecting from update server"));
         client.stop();
       }

+
+      file.close();
       //Disable the SD card:
       pinMode(CHIP_SELECT, OUTPUT);
       digitalWrite(CHIP_SELECT, HIGH);
-
-      if (i > 4096) {
-        Serial.println(F("Resetting..."));
-        delay(200);
-        resetFunc();
-      }
+      Serial.println(F("Resetting..."));
+      delay(200);
+      resetFunc();
+
     }
     else {
       Serial.println(F("connection failed")); //error message if no client connect


changing the color value

changing the color value

--- musicglove2/musicglove2.ino
+++ musicglove2/musicglove2.ino
@@ -111,7 +111,7 @@

   const int sizeRow = 9; // RGB
   const int sizeCol = 3; // nine colors
-  int constanterror = 5000;
+  int constanterror = 6000;
   bool redMatch = false;
   bool greenMatch = false;
   bool blueMatch = false;
@@ -142,7 +142,7 @@
       200, 120, 55            }
     , // black
     {
-      44000, 53100, 34200            } // white
+      20000, 20000, 20000            } // white
   };
   String colorary [9] = {
     "red", "orange", "yellow", "green", "blue", "indigo", "violet", "black", "white"      };


Delete _06_kidSerie_sketch_02.Adafruit_fake_feeds.ino

--- _06_kidSerie_sketch_02.Adafruit_fake_feeds.ino
+++ _06_kidSerie_sketch_02.Adafruit_fake_feeds.ino
@@ -1,245 +0,0 @@
-/*
-  Project name:
-     06 #kidSerie - Go code? Explainning My Approach As Hobbyist!!!
-     (Awesome Smart Phone App!)
-     Flavour III -
-     Hex File: _06_kidSerie_sketch_02.Adafruit_fake_feeds.ino
-   Revision History:
-     20161029:
-       - from github adafruit/Adafruit_MQTT_Library
-  https://github.com/adafruit/Adafruit_MQTT_Library/blob/master/examples/mqtt_esp8266/mqtt_esp8266.ino
-  https://learn.adafruit.com/mqtt-adafruit-io-and-you/intro-to-adafruit-mqtt
-   Description:
-     How to teach young people how to take advantage of already tested codes and create a new one from them.
-     I decided to face a new challenge. This code is the second one and joining the first one we will communicate with
-     the Adafruit-io Broker to send temperature and humidity data via MQTT Protocol.
-   MCU:                  Arduino 1.6.12 - @16MHz       http://www.arduino.cc/
-   ESP8266:              ESP-01                        https://goo.gl/E0Eq4l
-   DHT11:                PRODUCT ID: 386               https://www.adafruit.com/product/386
-   Connections:
-      See Official youtube channel vids: https://youtu.be/cwYix_Oyui4
-   Based on:   Tony DiCola for Adafruit Industries - see below!
-   This program is free software: you can redistribute it and/or modify
-   it under the terms of the GNU General Public License v3 as published by
-   the Free Software Foundation
-*/
-/***************************************************
-  Adafruit MQTT Library ESP8266 Example
-  Must use ESP8266 Arduino from:
-    https://github.com/esp8266/Arduino
-  Works great with Adafruit's Huzzah ESP board & Feather
-  ----> https://www.adafruit.com/product/2471
-  ----> https://www.adafruit.com/products/2821
-  Adafruit invests time and resources providing this open source code,
-  please support Adafruit and open-source hardware by purchasing
-  products from Adafruit!
-  Written by Tony DiCola for Adafruit Industries.
-  MIT license, all text above must be included in any redistribution
- ****************************************************/
- /******************************* Adafruit MQTT *******************************/
-
-#include "Adafruit_MQTT.h"
-#include "Adafruit_MQTT_Client.h"
-
-/******************************* Esp8266**************************************/
-
-#include <ESP8266WiFi.h>
-#include <WiFiClient.h>
-#include <ESP8266WebServer.h>
-
-/******************************* DHT Config **********************************/
-#include <DHT.h>
-#define DHTTYPE DHT11
-#define DHTPIN  2
-
-/************************* WiFi Access Point *********************************/
-
-#define WLAN_SSID       "...your SSID..."
-#define WLAN_PASS       "...your password..."
-
-/************************* Adafruit.io Setup *********************************/
-
-#define AIO_SERVER      "io.adafruit.com"
-#define AIO_SERVERPORT  1883                   // use 8883 for SSL
-#define AIO_USERNAME    "...your AIO username (see https://accounts.adafruit.com)..."
-#define AIO_KEY         "...your AIO key..."
-
-/************ Global State (you don't need to change this!) ******************/
-
-// Create an ESP8266 WiFiClient class to connect to the MQTT server.
-WiFiClient client;
-// or... use WiFiFlientSecure for SSL
-//WiFiClientSecure client;
-
-// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
-Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
-
-/****************************** Feeds ***************************************/
-/****************************** Topics ***************************************/
-// Setup a feed called 'photocell' for publishing.
-// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
-Adafruit_MQTT_Publish temp_topic = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/temp");
-Adafruit_MQTT_Publish humid_topic = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/humid");
-/****************************** Subscriptions*********************************/
-// Setup a feed called 'photocell' for subscribing to changes.
-Adafruit_MQTT_Subscribe temp_subscription = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/temp");
-Adafruit_MQTT_Subscribe humid_subscription = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/humid");
-
-/***************************  MQTT Conn   ************************************/
-
-// Bug workaround for Arduino 1.6.6, it seems to need a function declaration
-// for some reason (only affects ESP8266, likely an arduino-builder bug).
-void MQTT_connect();
-
-/*************************** DHT Init   **************************************/
-// Initialize DHT sensor
-// NOTE: For working with a faster than ATmega328p 16 MHz Arduino chip, like an ESP8266,
-// you need to increase the threshold for cycle counts considered a 1 or 0.
-// You can do this by passing a 3rd parameter for this threshold.  It's a bit
-// of fiddling to find the right value, but in general the faster the CPU the
-// higher the value.  The default for a 16mhz AVR is a value of 6.  For an
-// Arduino Due that runs at 84mhz a value of 30 works.
-// This is for the ESP8266 processor on ESP-01
-DHT dht(DHTPIN, DHTTYPE, 15); // 11 works fine for ESP8266
-/*************************** DHT Data   **************************************/
-//float humidity, temp_f;  // Values read from sensor Fahrenheit
-float humidity, temp_c;  // Values read from sensor as Celsius
-String tempString = "";   // String to display
-/*************************** DHT Timing   ************************************/
-// Generally, you should use "unsigned long" for variables that hold time
-unsigned long previousMillis = 0;        // will store last temp was read
-const long interval = 2000;              // interval at which to read sensor
-
-/****************************** Setup  ***************************************/
-void setup() {
-  Serial.begin(115200);
-  delay(10);
-
-  Serial.println(F("Adafruit MQTT demo"));
-
-  // Connect to WiFi access point.
-  Serial.println(); Serial.println();
-  Serial.print("Connecting to ");
-  Serial.println(WLAN_SSID);
-
-  WiFi.begin(WLAN_SSID, WLAN_PASS);
-  while (WiFi.status() != WL_CONNECTED) {
-    delay(500);
-    Serial.print(".");
-  }
-  Serial.println();
-
-  Serial.println("WiFi connected");
-  Serial.println("IP address: "); Serial.println(WiFi.localIP());
-
-  // Setup MQTT subscription for onoff feed.
-  mqtt.subscribe(&temp_subscription);
-  delay(1000);
-  mqtt.subscribe(&humid_subscription);
-}
-
-//uint32_t x=0;    // Mock data
-
-/****************************** Loop  ***************************************/
-void loop() {
-  gettemperature() ;
-  // Ensure the connection to the MQTT server is alive (this will make the first
-  // connection and automatically reconnect when disconnected).  See the MQTT_connect
-  // function definition further below.
-  MQTT_connect();
-
-  // this is our 'wait for incoming subscription packets' busy subloop
-  // try to spend your time here
-
- /****************************** Subscript  ***********************************/
- Adafruit_MQTT_Subscribe *subscription;
-  while ((subscription = mqtt.readSubscription(5000))) {
-    if (subscription == &temp_subscription) {
-      Serial.print(F("Got: "));
-      Serial.println((char *)temp_subscription.lastread);
-    }
-    else {
-      Serial.print(F("Got humid: "));
-      Serial.println((char *)humid_subscription.lastread);
-    }
-  }
- /****************************** Publish  **********************************/
-   // Now we can publish stuff!
-  Serial.print(F("\nSending temp val "));
-  Serial.print(temp_c);
-  Serial.print("...");
-  if (! temp_topic.publish(temp_c)) {
-    Serial.println(F("Failed"));
-  } else {
-    Serial.println(F("OK!"));
-  }
-
-  Serial.print(F("\nSending humid val "));
-  Serial.print(humidity);
-  Serial.print("...");
-  if (! humid_topic.publish(humidity)) {
-    Serial.println(F("Failed"));
-  } else {
-    Serial.println(F("OK!"));
-  }
-/****************************** Ping  ***************************************/
-
-  // ping the server to keep the mqtt connection alive
-  // NOT required if you are publishing once every KEEPALIVE seconds
-  /*
-  if(! mqtt.ping()) {
-    mqtt.disconnect();
-  }
-  */
-}
-/********************************* MQTT Conn  ********************************/
-// Function to connect and reconnect as necessary to the MQTT server.
-// Should be called in the loop function and it will take care if connecting.
-void MQTT_connect() {
-  int8_t ret;
-
-  // Stop if already connected.
-  if (mqtt.connected()) {
-    return;
-  }
-
-  Serial.print("Connecting to MQTT... ");
-
-  uint8_t retries = 3;
-  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
-       Serial.println(mqtt.connectErrorString(ret));
-       Serial.println("Retrying MQTT connection in 5 seconds...");
-       mqtt.disconnect();
-       delay(5000);  // wait 5 seconds
-       retries--;
-       if (retries == 0) {
-         // basically die and wait for WDT to reset me
-         while (1);
-       }
-  }
-  Serial.println("MQTT Connected!");
-}
-void gettemperature() {
-  // Wait at least 2 seconds seconds between measurements.
-  // if the difference between the current time and last time you read
-  // the sensor is bigger than the interval you set, read the sensor
-  // Works better than delay for things happening elsewhere also
-  unsigned long currentMillis = millis();
-
-  if (currentMillis - previousMillis >= interval) {
-    // save the last time you read the sensor
-    previousMillis = currentMillis;
-
-    // Reading temperature for humidity takes about 250 milliseconds!
-    // Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor)
-    humidity = dht.readHumidity();          // Read humidity (percent)
-    //temp_f = dht.readTemperature(true);     // Read temperature as Fahrenheit
-    temp_c = dht.readTemperature();    // Read temperature as Celsius
-    // Check if any reads failed and exit early (to try again).
-    if (isnan(temp_c) || temp_c != 0 )
-      if (isnan(temp_c) || isnan(humidity) || temp_c != 0 || humidity != 0 ) {
-        Serial.println("Failed to read from DHT sensor!");
-        return;
-        }
-     }
-  }


stairs: merge rainbow and rainbowcycle modes

--- stairs/main.ino
+++ stairs/main.ino
@@ -39,7 +39,6 @@
 void modeGradient();
 void modeOff();
 void modeRainbow();
-void modeRainbowCycle();
 void modeRainbowTrain();
 void modeSine();
 void modeSolid();
@@ -51,10 +50,10 @@
     &modeGradient,
     &modeEase,
     &modeRainbow,
-    &modeRainbowCycle,
     &modeRainbowTrain,
+    &modeBreathe,
     &modeSine,
-    &modeBreathe,
+    &modeOff,
     &modeOff
 };

@@ -183,23 +182,12 @@
                   NUM_LEDS-1, CHSV(pots.var, pots.sat, pots.val));
 }

-// Draw the rainbow. The additional parameter moves the rainbow back and forth.
+// Animate the rainbow. The hue parameter moves the rainbow back and forth,
+// while the additional parameter regulates the animation speed.
 void modeRainbow() {
     uint8_t hue;
     for (uint8_t led = 0; led < NUM_LEDS; led++) {
-        hue = ledAngle(led);
-        hue += pots.var;
-        leds[led] = CHSV(hue, pots.sat, pots.val);
-    }
-}
-
-// Draw the rainbow, and gradually move it according to the addition parameter,
-// which regulates the speed.
-void modeRainbowCycle() {
-    uint8_t hue;
-    for (uint8_t led = 0; led < NUM_LEDS; led++) {
-        hue = ledAngle(led);
-        hue += animation();
+        hue = ledAngle(led) + animation() + pots.hue;
         leds[led] = CHSV(hue, pots.sat, pots.val);
     }
 }


Added watchdog

Added watchdog

--- examples/EchoBot/EchoBot.ino
+++ examples/EchoBot/EchoBot.ino
@@ -7,16 +7,19 @@
   For a step-by-step tutorial visit:
   https://create.arduino.cc/projecthub/Arduino_Genuino/telegram-bot-library-ced4d4

-  Updated 19 May 2016
+  Updated 29 Nov 2016
   by Tommaso Laterza

   This example code is in the public domain.

 */
-#include<WiFiSSLClient.h>
 #include <WiFi101.h>
 #include <SPI.h>
 #include <TelegramBot.h>
+
+//The SleepyDog library is needed to reset the board when something goes wrong.
+//It is not strictly necessary but makes the bot way more reliable.
+#include <Adafruit_SleepyDog.h>

 // Initialize Wifi connection to the router
 char ssid[] = "xxxx";             // your network SSID (name)
@@ -49,10 +52,13 @@

   bot.begin();
+  Watchdog.enable(10000); // set the timer to 10 sec

 }

 void loop() {
+
+    Watchdog.reset(); // if this function is not called within 10 seconds the board will reset itself

     message m = bot.getUpdates(); // Read new messages
     if ( m.chat_id != 0 ){ // Checks if there are some updates


Use median instead of average

Use median instead of average

--- serialtemp.ino
+++ serialtemp.ino
@@ -19,7 +19,8 @@
 // temp. for nominal resistance (almost always 25 C)
 #define TEMPERATURENOMINAL 25
 // how many samples to take and average, more takes longer but is more 'smooth'
-#define NUMSAMPLES 40
+#define NUMSAMPLES 41
+#define MEDIAN 21
 // The beta coefficient of the thermistor (usually 3000-4000)
 #define BCOEFFICIENT 3950
 // the value of the 'other' resistor
@@ -36,7 +37,20 @@
   analogReference(EXTERNAL);
   digitalWrite(led2, HIGH);
 }
-
+ void insertionSort(int list[])
+{
+    int temp;
+    for(long i = 1; i < NUMSAMPLES; i++)
+    {
+        temp = list[i];
+        long j;
+        for(j = i-1; j >= 0 && list[j] > temp; j--)
+        {
+            list[j+1] = list[j];
+        }
+        list[j+1] = temp;
+    }
+}
 float MeasureTemp(int pin) {
   uint8_t i;
   float average =0;
@@ -46,10 +60,12 @@
    delay(5);
   }
   // average all the samples out
-  for (i=0; i< NUMSAMPLES; i++) {
-     average += samples[i];
-  }
-  average /= NUMSAMPLES;
+  //for (i=0; i< NUMSAMPLES; i++) {
+  //   average += samples[i];
+  //}
+  //average /= NUMSAMPLES;
+  insertionSort(samples);
+  average = samples[MEDIAN];
   // convert the value to resistance
   average = 1023 / average - 1;
   average = SERIESRESISTOR / average;


Functions writeErrorToEEPROM() and readErrorFromEEPROM() working correctly. Readings are returned as double, with the same value that was written. Function writeAllToEEPROM() implemented to write the 3 errors.

--- skypointer.ino
+++ skypointer.ino
@@ -59,16 +59,6 @@
  ***************************************************************************/
 void writeErrorToEEPROM (int n, double Z) {
     // Writes to EEPROM the n-th error correction, where n = 1, 2 or 3
-    /*
-    Values are converted to a double int by multiplying by 100.000.000
-    The longest value is 4-byte long:
-        LSB =
-
-        MSB =
-    */
-    for (unsigned int k = 0; k < 12; k++) {
-        EEPROM.write (k, 0);
-    }
     signed long _z = (signed long) (Z * 1e8);
     for (unsigned int k = 0; k < 4; k++) {
         // Write the 3 lowest bytes (not the sign)
@@ -76,24 +66,21 @@
     }
 }

-signed long readErrorFromEEPROM (int n) {
+void writeAllToEEPROM (double z1, double z2, double z3) {
+    writeErrorToEEPROM (1, Z1);
+    writeErrorToEEPROM (2, Z2);
+    writeErrorToEEPROM (3, Z3);
+}
+
+double readErrorFromEEPROM (int n) {
     // Reads the n-th error stored in the EEPROM and converts it to double,
     // where n = 1, 2 or 3
     signed long res = 0;
-    for (unsigned int k = 0; k < 4; k++) {
+    for (int k = 0; k < 4; k++) {
         res |= (signed long) ((signed long) (EEPROM.read(4*(n-1)+k)) << 8*k);
-        //int aux = EEPROM.read(4*(n-1)+k);
-        //Serial.print ("Aux = "); Serial.println(aux, HEX);
-        //signed long aux = (signed long) (EEPROM.read(4*(n-1)+k));
-        //res += (aux << (8*k));
-    }
-    //Serial.print("Res = "); Serial.print(res, HEX); Serial.print(" = ");
-    //Serial.println(res, DEC);
-    return res;
-}
-
-
-
+    }
+    return (double) (res / 1e8);
+}
 /****************************************************************************/
 // Interruption routine
 void ISR_rotate() {
@@ -269,21 +256,22 @@
   motor1->setSpeed(RPM);
   motor2->setSpeed(RPM);

+
+
   // Array with the errors
   double Z[3] = {(double) Z1, (double) Z2, (double) Z3};
-  for (unsigned int k = 0; k < 3; k++) {
-    // Write to EEPROM
-    writeErrorToEEPROM (k+1, Z[k]);
-    // Read from EEPROM
-    signed long aux = readErrorFromEEPROM(k+1);
-    // Print some info
-    Serial.print("Z"); Serial.print(k+1, DEC); Serial.print( " = ");
-    Serial.print(Z[k], 8); Serial.print("  |  ");
-    Serial.print("Res"); Serial.print(k+1, DEC); Serial.print(" = ");
-    Serial.println(aux, DEC);
-  }
+  writeAllToEEPROM ((double) Z1, (double) Z2, (double) Z3);
+
 }

 void loop() {
   sCmd.readSerial();  // Read commands from serial port
-}
+  double a = readErrorFromEEPROM(1);
+  double b = readErrorFromEEPROM(2);
+  double c = readErrorFromEEPROM(3);
+
+  Serial.print(a, 8);
+  Serial.print ("  |  "); Serial.print(b, 8);
+  Serial.print ("  |  "); Serial.print(c, 8);
+  Serial.println("");
+}


Show text "hacklab.jkl" at boot

Show text "hacklab.jkl" at boot


general improvements

general improvements

--- arduino_esp8266/omega_fallblatt_raw/omega_fallblatt_raw.ino
+++ arduino_esp8266/omega_fallblatt_raw/omega_fallblatt_raw.ino
@@ -1,4 +1,7 @@
 #include <Ticker.h>
+
+#define FLAPCOUNT 62
+//#define FLAPCOUNT 40

 #define PIN_TRIAC_N D3
 #define PIN_STROBE D2
@@ -8,11 +11,14 @@
 #define PIN_EC_3 D0
 #define PIN_EC_4 D6
 #define PIN_EC_5 D4
+#define STROBE_READ_DELAY 30
+#define ENCODER_REREAD_DELAY 4

-uint8_t encoder_val = 0;
-uint8_t encoder_desired_val = 0;
-volatile int strobe_int = 0;
-int timer_running = 0;
+volatile int read_error_count = 0;
+volatile uint8_t encoder_val = 1; // last read value
+uint8_t encoder_desired_val = 1; // value to stop at
+volatile int strobe_int = 0; // interrupt counter
+bool timer_running = false; // a timer is active, don't start a new one
 Ticker timerReadEncoder;

 void setup() {
@@ -30,10 +36,14 @@
   attachInterrupt(digitalPinToInterrupt(PIN_STROBE), isr_strobe, FALLING);
 }

-void readEncoder(){
+void readEncoder() {
   int prev_val = encoder_val;
+  int oneflip = prev_val - 1;
+  if (oneflip < 1)
+    oneflip = FLAPCOUNT;
+
   pinMode(PIN_STROBE, OUTPUT);
-  digitalWrite(PIN_STROBE, 0);
+  digitalWrite(PIN_STROBE, 0); // pull down strobe, this lets us read the EC pins

   encoder_val = digitalRead(PIN_EC_0);
   encoder_val += digitalRead(PIN_EC_1) << 1;
@@ -42,56 +52,60 @@
   encoder_val += digitalRead(PIN_EC_4) << 4;
   encoder_val += digitalRead(PIN_EC_5) << 5;

-  pinMode(PIN_STROBE, INPUT);
-
-  if(encoder_val == 63 || encoder_val != prev_val + 1){
-    timerReadEncoder.once_ms(1, readEncoder);
+  if (encoder_val == 63 || encoder_val != oneflip) { // re-trigger a read if we read an unexpected result. this eliminates the need for real-time finetuning of the read interval.
+    encoder_val = prev_val;
+    timerReadEncoder.once_ms(ENCODER_REREAD_DELAY, readEncoder);
+    read_error_count++;
     return;
   }

-  if(encoder_val == encoder_desired_val){
-    digitalWrite(PIN_TRIAC_N, 1);
+  if (encoder_val == encoder_desired_val) {
+    digitalWrite(PIN_TRIAC_N, 1);  // stop the motor when we have reached the desired position.
   }

-  timer_running = 0;
+  pinMode(PIN_STROBE, INPUT); // strobe back to input, this allows the interrupt to be triggered
+  timer_running = false;
   strobe_int = 0;
 }

-void isr_strobe(){
+void isr_strobe() {
   strobe_int++;
 }

 void loop() {
-  static int prev_val = 0;
-  static int display_pos = 1;
+  static int prev_val = 0; // just for printing changes

-  if(strobe_int > 0 && timer_running < 1){
-    timer_running++;
-    timerReadEncoder.once_ms(8, readEncoder);
+  if (strobe_int > 0 && !timer_running) {
+    timer_running = true;
+    timerReadEncoder.once_ms(STROBE_READ_DELAY, readEncoder);
+  }
+
+  if (strobe_int > 1) {
+    Serial.print("b/o ");Serial.println(strobe_int); // bounce or overrun
+  }
+  if (read_error_count > 0) {
+    Serial.print("re ");Serial.println(read_error_count);
+    read_error_count = 0;
   }

-  if(encoder_val != prev_val && encoder_val != 63){
+  if (encoder_val != prev_val) {
     Serial.println(encoder_val);
     prev_val = encoder_val;
-  }
-
-  if(encoder_val != encoder_desired_val){
-    digitalWrite(PIN_TRIAC_N, 0);
-  }else{
-    digitalWrite(PIN_TRIAC_N, 1);
   }

   if (Serial.available() > 0) {
     char ch = Serial.read();
-    if(ch == 'a')
+    if (ch == 'a')
       encoder_desired_val++;
-    if(ch == 's')
+    if (ch == 's')
       encoder_desired_val--;
-    if(encoder_desired_val < 1)encoder_desired_val=62;
-    if(encoder_desired_val > 62)encoder_desired_val=1;
-    if(ch == 'x')
+    if (encoder_desired_val < 1)
+      encoder_desired_val = FLAPCOUNT;
+    if (encoder_desired_val > FLAPCOUNT)
+      encoder_desired_val = 1;
+    if (ch == 'x')
       digitalWrite(PIN_TRIAC_N, 1);
-    if(ch == 'y')
+    if (ch == 'y')
       digitalWrite(PIN_TRIAC_N, 0);
   }
 }


Inicialización del módulo wifi

Inicialización del módulo wifi

--- hardware/wifi-slave/src/wifi-slave.ino
+++ hardware/wifi-slave/src/wifi-slave.ino
@@ -1,23 +1,57 @@
 #include <SoftwareSerial.h>

-//https://www.arduino.cc/en/Reference/SoftwareSerialConstructor
-SoftwareSerial mySerial(2,3);//rxPin, TxPin
+// static or const is in read-only parts of the memory?
+// https://www.arduino.cc/en/Reference/SoftwareSerialConstructor
+SoftwareSerial esp8266(2, 3); // rxPin, TxPin of Arduino rx-tx tx-rx

-void setup()
-{
-  mySerial.begin(115200);
-  Serial.begin(115200);
+static char response[255] = "\0"; // static vs const?
+
+void setup() {
+  Serial.begin(9600);
+  configWIFI();
 }

-void loop()
-{
-  if (mySerial.available()){
-    Serial.write(mySerial.read());
+void loop() { redirSerialAT(); }
+
+void configWIFI() {
+  esp8266.begin(115200);
+  esp8266.println(F("AT"));
+  showResponse();
+  esp8266.println(F("AT+RST")); // for know state
+  showResponse();
+  delay(5000);
+}
+
+void showResponse() {
+  bufferSerial(response);
+  Serial.println(response);
+}
+
+/**
+ * Se utiliza para redirigir los comandos AT del serial del arduino
+ * al puerto del módulo WIFI ESP8266
+ */
+void redirSerialAT() {
+  if (esp8266.available()) {
+    Serial.write(esp8266.read());
   }
   if (Serial.available()) {
-
-    mySerial.write(Serial.read());
-    Serial.write("hi");
+    esp8266.write(Serial.read());
   }
+}

+/**
+ * Realiza la lectura del buffer del serial
+ * caracteres hasta que la transmisión serial termina
+ * Acumulador de caracteres recursivo
+ */
+void bufferSerial(char *cad) {
+  int i = 0;
+  char c = '\0';
+  strcpy(cad, "");
+  while (esp8266.available()) {
+    c = esp8266.read();
+    cad[i] = c;
+    i++;
+  }
 }


Functions writeErrorToEEPROM() and readErrorFromEEPROM() working. Reading returns a long int, must be converted to double.

--- skypointer.ino
+++ skypointer.ino
@@ -17,6 +17,7 @@
 #include "SkyPointer_MotorShield.h"
 #include <TimerOne.h>
 #include <EEPROM.h>
+//#include "EEPROM_Anything/EEPROM_Anything.h"

 // A modulo operator that handles negative numbers
 #define MOD(a,b) ((((a)%(b))+(b))%(b))
@@ -65,30 +66,34 @@

         MSB =
     */
-
     for (unsigned int k = 0; k < 12; k++) {
         EEPROM.write (k, 0);
     }
-
-    long _z = long(Z * 1e8);
-
+    signed long _z = (signed long) (Z * 1e8);
     for (unsigned int k = 0; k < 4; k++) {
         // Write the 3 lowest bytes (not the sign)
-        Serial.println(int((_z >> 8*k) & 0xFF), HEX);
         EEPROM.write(4*(n-1) + k, (int) ((_z >> 8*k) & 0xFF));
     }
 }

-double readErrorFromEEPROM (int n) {
+signed long readErrorFromEEPROM (int n) {
     // Reads the n-th error stored in the EEPROM and converts it to double,
     // where n = 1, 2 or 3
-    long res = 0;
-    for (unsigned int k = 0; k < 3; k++) {
-        res += long((EEPROM.read(4*(n-1)+k)) << 8*k);
-    }
-    Serial.println(res, HEX);
-    return 0;
-}
+    signed long res = 0;
+    for (unsigned int k = 0; k < 4; k++) {
+        res |= (signed long) ((signed long) (EEPROM.read(4*(n-1)+k)) << 8*k);
+        //int aux = EEPROM.read(4*(n-1)+k);
+        //Serial.print ("Aux = "); Serial.println(aux, HEX);
+        //signed long aux = (signed long) (EEPROM.read(4*(n-1)+k));
+        //res += (aux << (8*k));
+    }
+    //Serial.print("Res = "); Serial.print(res, HEX); Serial.print(" = ");
+    //Serial.println(res, DEC);
+    return res;
+}
+
+
+
 /****************************************************************************/
 // Interruption routine
 void ISR_rotate() {
@@ -264,15 +269,19 @@
   motor1->setSpeed(RPM);
   motor2->setSpeed(RPM);

-  long err = Z1 * 1e8;
-  Serial.print ("Val = "); Serial.println (err, DEC);
-  Serial.print ("HEX = "); Serial.println (err, HEX);
-
-  writeErrorToEEPROM (1, Z1);
-
-  readErrorFromEEPROM (1);
-
-
+  // Array with the errors
+  double Z[3] = {(double) Z1, (double) Z2, (double) Z3};
+  for (unsigned int k = 0; k < 3; k++) {
+    // Write to EEPROM
+    writeErrorToEEPROM (k+1, Z[k]);
+    // Read from EEPROM
+    signed long aux = readErrorFromEEPROM(k+1);
+    // Print some info
+    Serial.print("Z"); Serial.print(k+1, DEC); Serial.print( " = ");
+    Serial.print(Z[k], 8); Serial.print("  |  ");
+    Serial.print("Res"); Serial.print(k+1, DEC); Serial.print(" = ");
+    Serial.println(aux, DEC);
+  }
 }

 void loop() {


TODOs

TODOs

--- ardesp/joinme/joinme.ino
+++ ardesp/joinme/joinme.ino
@@ -5,6 +5,11 @@
 #include <ESP8266WiFi.h>
 #include <DNSServer.h>
 #include <ESP8266WebServer.h>
+
+// TODO
+// wifi config form
+// sensor data report, and actuator set form
+// fix the DNS server, http://www.esp8266.com/viewtopic.php?p=21169

 const byte DNS_PORT = 53;
 IPAddress apIP(192, 168, 1, 1);
@@ -27,7 +32,7 @@
   dnsServer.start(DNS_PORT, "*", apIP);

   // reply code, no error
-//  dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
+  // dnsServer.setErrorReplyCode(DNSReplyCode::NoError);

   // reply to all requests with same HTML
   webServer.onNotFound([]() {


Delete proton_pack_buttons_1.0.ino

Delete proton_pack_buttons_1.0.ino

--- proton_pack_buttons_1.0.ino
+++ proton_pack_buttons_1.0.ino
@@ -1,438 +0,0 @@
-// Proton pack
-
-int current_state = 0;  // Tracks what the pack should be doing.
-int previous_state = 0;
-
-// ===============================================================================================
-// TIMEKEEPING
-// ===============================================================================================
-unsigned long currentMillis = 0;
-unsigned long previousMillis_off = 0;  // will store last updated time.
-unsigned long previousMillis_on = 0;
-unsigned long previousMillis_fire = 0;
-unsigned long off_interval = 30;
-unsigned long pwrcl_interval = 70;     // interval at which to cycle lights (milliseconds).
-unsigned long firing_interval = 60;    // interval at which to cycle firing lights (milliseconds).
-unsigned long max_firing_interval = 50;
-unsigned long min_firing_interval = 30;
-unsigned long overheat_interval = 200;
-int overheat_cycles = 7;
-int overheat_counter = overheat_cycles;
-
-// ===============================================================================================
-// BUTTONS
-// ===============================================================================================
-#define DEBOUNCE 5  // button debouncer.
-// Pins 14, 15 and 16 are Analog 0, 1 and 2 respectively.
-int power_button = 14;
-int firing_button = 15;
-int music_button = 16;
-int power_button_state;
-int firing_button_state;
-int music_button_state;
-
-// ===============================================================================================
-// SHIFT REGISTERS
-// ===============================================================================================
-int latchPin = 8;
-int clockPinPWR = 6;  // Power cell
-int clockPinGUN = 18;  // Gun  (18 is analog pin 4 on arduino)
-////Pin connected to DS of 74HC595 (pin 14)
-int dataPinPWR = 7;  // Power cell
-int dataPinGUN = 19; // Gun (19 is analog pin 5 on arduino)
-
-//holders for information we're going to pass to shifting function
-byte dataPWRCL1;
-byte dataPWRCL2;
-byte dataGUN1;
-byte dataGUN2;
-byte dataGUNON1;
-byte dataGUNON2;
-// data arrays
-byte PWRCL1[15];
-byte PWRCL2[15];
-byte GUN1[26];
-byte GUN2[26];
-byte GUNON1[15];
-byte GUNON2[15];
-byte OHPWRCL1[2];
-byte OHPWRCL2[2];
-byte OHGUN1[2];
-byte OHGUN2[2];
-// track array position
-int power_cell_array_pos = 0;
-int gun_array_pos = 0;
-int gunactive_array_pos = 0;
-int overheat_array_pos = 0;
-
-
-int freeRam(void) {
-    extern int  __bss_end;
-    extern int  *__brkval;
-    int free_memory;
-    if((int)__brkval == 0) {
-        free_memory = ((int)&free_memory) - ((int)&__bss_end);
-    }
-    else {
-        free_memory = ((int)&free_memory) - ((int)__brkval);
-    }
-    return free_memory;
-}
-
-
-void setup() {
-    // set up serial port
-    Serial.begin(9600);
-    Serial.print("Free RAM: ");
-    Serial.println(freeRam());      // if this is under 150 bytes it may spell trouble!
-
-    // Make input & enable pull-up resistors on switch pins
-    Serial.println("Pull ups on switches");
-    digitalWrite(power_button, HIGH);
-    digitalWrite(firing_button, HIGH);
-    digitalWrite(music_button, HIGH);
-
-    // Populate light pattern arrays
-    Serial.println("Populating light arrays");
-    // power cell LEDs 0 through 7 then LEDs 8 through 15 (two shift registers)
-    PWRCL1[0] = B10000000;  PWRCL2[0] = B00000000;  //10000000 00000000
-    PWRCL1[1] = B11000000;  PWRCL2[1] = B00000000;  //11000000 00000000
-    PWRCL1[2] = B11100000;  PWRCL2[2] = B00000000;  //11100000 00000000
-    PWRCL1[3] = B11110000;  PWRCL2[3] = B00000000;  //11110000 00000000
-    PWRCL1[4] = B11111000;  PWRCL2[4] = B00000000;  //11111000 00000000
-    PWRCL1[5] = B11111100;  PWRCL2[5] = B00000000;  //11111100 00000000
-    PWRCL1[6] = B11111110;  PWRCL2[6] = B00000000;  //11111110 00000000
-    PWRCL1[7] = B11111111;  PWRCL2[7] = B00000000;  //11111111 00000000
-    PWRCL1[8] = B11111111;  PWRCL2[8] = B10000000;  //11111111 10000000
-    PWRCL1[9] = B11111111;  PWRCL2[9] = B11000000;  //11111111 11000000
-    PWRCL1[10] = B11111111; PWRCL2[10] = B11100000; //11111111 11100000
-    PWRCL1[11] = B11111111; PWRCL2[11] = B11110000; //11111111 11110000
-    PWRCL1[12] = B11111111; PWRCL2[12] = B11111000; //11111111 11111000
-    PWRCL1[13] = B11111111; PWRCL2[13] = B11111100; //11111111 11111100
-    PWRCL1[14] = B11111111; PWRCL2[14] = B11111110; //11111111 11111110
-
-    //Proton wand idle pattern - two shift registers
-    GUN1[0] = B01000000;  GUN2[0] = B00000000;  //01000000 00000000
-    GUN1[1] = B01000000;  GUN2[1] = B00000000;  //01000000 00000000
-    GUN1[2] = B01100000;  GUN2[2] = B00000000;  //01100000 00000000
-    GUN1[3] = B01110000;  GUN2[3] = B00000000;  //01110000 00000000
-    GUN1[4] = B01111000;  GUN2[4] = B00000000;  //01111000 00000000
-    GUN1[5] = B01111100;  GUN2[5] = B00000000;  //01111100 00000000
-    GUN1[6] = B01111110;  GUN2[6] = B00000000;  //01111110 00000000
-    GUN1[7] = B01111111;  GUN2[7] = B10000000;  //01111111 10000000
-    GUN1[8] = B01111111;  GUN2[8] = B11000000;  //01111111 11000000
-    GUN1[9] = B01111111;  GUN2[9] = B11100000;  //01111111 11100000
-    GUN1[10] = B01111111; GUN2[10] = B11110000; //01111111 11110000
-    GUN1[11] = B01111111; GUN2[11] = B11111000; //01111111 11111000
-    GUN1[12] = B01111111; GUN2[12] = B11111100; //01111111 11111100
-    GUN1[13] = B01111111; GUN2[13] = B11111110; //01111111 11111110
-    GUN1[14] = B01111111; GUN2[14] = B11111100; //01111111 11111100
-    GUN1[15] = B01111111; GUN2[15] = B11111000; //01111111 11111000
-    GUN1[16] = B01111111; GUN2[16] = B11110000; //01111111 11110000
-    GUN1[17] = B01111111; GUN2[17] = B11100000; //01111111 11100000
-    GUN1[18] = B01111111; GUN2[18] = B11000000; //01111111 11000000
-    GUN1[19] = B01111111; GUN2[19] = B10000000; //01111111 10000000
-    GUN1[20] = B01111111; GUN2[20] = B00000000; //01111111 00000000
-    GUN1[21] = B01111110; GUN2[21] = B00000000; //01111110 00000000
-    GUN1[22] = B01111100; GUN2[22] = B00000000; //01111100 00000000
-    GUN1[23] = B01111000; GUN2[23] = B00000000; //01111000 00000000
-    GUN1[24] = B01110000; GUN2[24] = B00000000; //01110000 00000000
-    GUN1[25] = B01100000; GUN2[25] = B00000000; //01100000 00000000
-    GUN1[26] = B01000000; GUN2[26] = B00000000; //01000000 00000000
-
-    // Proton wand firing pattern - two shift registers
-    // 10000000 and 00000001 used for GUN strobe
-    GUNON1[0] = B11000000;  GUNON2[0] = B00000010;  //1|1000000  0000001|0
-    GUNON1[1] = B00100000;  GUNON2[1] = B00000101;  //0|0100000  0000010|1
-    GUNON1[2] = B00010000;  GUNON2[2] = B00001000;  //1|0010000  0000100|0
-    GUNON1[3] = B10001000;  GUNON2[3] = B00010001;  //0|0001000  0001000|1
-    GUNON1[4] = B00000100;  GUNON2[4] = B00100000;  //1|0000100  0010000|0
-    GUNON1[5] = B00000010;  GUNON2[5] = B01000001;  //0|0000010  0100000|1
-    GUNON1[6] = B10000001;  GUNON2[6] = B10000000;  //1|0000001  1000000|0
-    GUNON1[7] = B00000001;  GUNON2[7] = B10000001;  //0|0000001  1000000|1
-    GUNON1[8] = B00000001;  GUNON2[8] = B10000000;  //1|0000001  1000000|0
-    GUNON1[9] = B10000010;  GUNON2[9] = B01000001;  //0|0000010  0100000|1
-    GUNON1[10] = B00000100; GUNON2[10] = B00100000; //1|0000100  0010000|0
-    GUNON1[11] = B00001000; GUNON2[11] = B00010001; //0|0001000  0001000|1
-    GUNON1[12] = B10010000; GUNON2[12] = B00001000; //1|0010000  0000100|0
-    GUNON1[13] = B00100000; GUNON2[13] = B00000101; //0|0100000  0000010|1
-    GUNON1[14] = B01000000; GUNON2[14] = B00000010; //1|1000000  0000001|0
-
-    // Overheat patterns
-    OHPWRCL1[0] = B00000000;  OHPWRCL2[0] = B00000000;
-    OHPWRCL1[1] = B11111111;  OHPWRCL2[1] = B11111111;
-    OHGUN1[0] = B00000000;  OHGUN2[0] = B00000000;
-    OHGUN1[1] = B01111111;  OHGUN2[1] = B11111110;
-
-    // Set pins for shift registers:
-    pinMode(latchPin, OUTPUT);      // shared between power cell and thrower
-    pinMode(clockPinPWR, OUTPUT);
-    pinMode(clockPinGUN, OUTPUT);
-    pinMode(dataPinPWR, OUTPUT);
-    pinMode(dataPinGUN, OUTPUT);
-    // Initialise Power cell and gun lights
-    Serial.println("Initialising lights.");
-    digitalWrite(latchPin, 0);
-    shiftOut(dataPinPWR, clockPinPWR, 0x00);
-    shiftOut(dataPinPWR, clockPinPWR, 0x00);
-    shiftOut(dataPinGUN, clockPinGUN, 0x40);
-    shiftOut(dataPinGUN, clockPinGUN, 0x00);
-    digitalWrite(latchPin, 1);
-
-}
-
-
-void loop() {
-    pack_state();
-    if (previous_state != current_state) {
-        Serial.print("STATE: ");
-        Serial.println(current_state);
-    }
-}
-
-
-void pack_state() {
-    previous_state = current_state;
-    switch (current_state) {
-        case 0:  // reset
-            current_state = 1;
-            pwrcl_interval = 70;
-            firing_interval = max_firing_interval;
-            overheat_counter = overheat_cycles;
-            break;
-
-        case 1:  // Start
-            power_button_state = digitalRead(power_button);
-            if (power_button_state == LOW) {
-                current_state = 2;
-            }
-            else {
-                current_state = 0;
-            }
-            break;
-
-        case 2: // Powered on
-            power_button_state = digitalRead(power_button);
-            firing_button_state = digitalRead(firing_button);
-            if (power_button_state == HIGH) {
-                current_state = 3;
-            }
-            if (firing_button_state == LOW) {
-                current_state = 4;
-            }
-            powered_on();
-            break;
-
-        case 3: // Power down
-            Serial.print("array positions: ");
-            Serial.print(power_cell_array_pos);
-            Serial.print(" : ");
-            Serial.println(gun_array_pos);
-            powered_down();
-            break;
-
-        case 4: // Firing
-            power_button_state = digitalRead(power_button);
-            firing_button_state = digitalRead(firing_button);
-            //Serial.print("Button states [power|firing]: ");
-            //Serial.print(power_button_state); Serial.print("|"); Serial.println(firing_button_state);
-            if ((power_button_state == HIGH) && (firing_button_state == LOW)) {
-                current_state = 3;
-            }
-            if (firing_button_state == HIGH) {
-                current_state = 0;
-            }
-            firing();
-            break;
-
-        case 5: // Overheat
-            overheat();
-            break;
-
-        case 6: // Overheat lockout
-            firing_button_state = digitalRead(firing_button);
-            if (firing_button_state == HIGH) {
-                current_state = 0;
-            }
-            break;
-    }
-}
-
-
-void powered_on() {
-    currentMillis = millis();
-    if (currentMillis - previousMillis_on > pwrcl_interval) {
-        previousMillis_on = currentMillis;
-        // Load the light sequence from arrays
-        dataPWRCL1 = PWRCL1[power_cell_array_pos];
-        dataPWRCL2 = PWRCL2[power_cell_array_pos];
-        dataGUN1 = GUN1[gun_array_pos];
-        dataGUN2 = GUN2[gun_array_pos];
-
-        digitalWrite(latchPin, 0);  // Low to send data
-        // Send data to shift registers:
-        shiftOut(dataPinPWR, clockPinPWR, dataPWRCL1);
-        shiftOut(dataPinPWR, clockPinPWR, dataPWRCL2);
-        shiftOut(dataPinGUN, clockPinGUN, dataGUN1);
-        shiftOut(dataPinGUN, clockPinGUN, dataGUN2);
-        digitalWrite(latchPin, 1);  // high to make shift register output data.
-
-        power_cell_array_pos++;
-        if (power_cell_array_pos > 14) {
-             power_cell_array_pos = 0;
-        }
-        gun_array_pos++;
-        if (gun_array_pos > 25) {
-            gun_array_pos = 0;
-        }
-    }
-}
-
-
-void powered_down() {
-    currentMillis = millis();
-    if (currentMillis - previousMillis_on > off_interval) {
-        previousMillis_on = currentMillis;
-        if (gun_array_pos != power_cell_array_pos) {
-            gun_array_pos = power_cell_array_pos;
-        }
-        // Load the light sequence from arrays
-        Serial.print("PWR array: "); Serial.print(power_cell_array_pos);
-        Serial.print("  GUN array: "); Serial.println(gun_array_pos);
-
-        dataPWRCL1 = PWRCL1[power_cell_array_pos];
-        dataPWRCL2 = PWRCL2[power_cell_array_pos];
-        dataGUN1 = GUN1[gun_array_pos];
-        dataGUN2 = GUN2[gun_array_pos];
-
-        digitalWrite(latchPin, 0);  // Low to send data
-        // Send data to shift registers:
-        shiftOut(dataPinPWR, clockPinPWR, dataPWRCL1);
-        shiftOut(dataPinPWR, clockPinPWR, dataPWRCL2);
-        shiftOut(dataPinGUN, clockPinGUN, dataGUN1);
-        shiftOut(dataPinGUN, clockPinGUN, dataGUN2);
-        digitalWrite(latchPin, 1);  // high to make shift register show data.
-
-        power_cell_array_pos--;
-        if (power_cell_array_pos < 0) {
-            power_cell_array_pos = 0;
-            current_state = 0;
-        }
-        gun_array_pos--;
-        if (gun_array_pos < 0) {
-            gun_array_pos = 0;
-            current_state = 0;
-        }
-    }
-}
-
-
-void firing() {
-    currentMillis = millis();
-    if (currentMillis - previousMillis_on > firing_interval) {
-        previousMillis_on = currentMillis;
-        // Load the light sequence from arrays
-        dataPWRCL1 = PWRCL1[power_cell_array_pos];
-        dataPWRCL2 = PWRCL2[power_cell_array_pos];
-        dataGUNON1 = GUNON1[gunactive_array_pos];
-        dataGUNON2 = GUNON2[gunactive_array_pos];
-
-        digitalWrite(latchPin, 0);  // Low to send data
-        // Send data to shift registers:
-        shiftOut(dataPinPWR, clockPinPWR, dataPWRCL1);
-        shiftOut(dataPinPWR, clockPinPWR, dataPWRCL2);
-        shiftOut(dataPinGUN, clockPinGUN, dataGUNON1);
-        shiftOut(dataPinGUN, clockPinGUN, dataGUNON2);
-        digitalWrite(latchPin, 1);  // high to make shift register show data.
-
-        power_cell_array_pos++;
-        if (power_cell_array_pos > 14) {
-            firing_interval--;
-            power_cell_array_pos = 0;
-        }
-        gunactive_array_pos++;
-        if (gunactive_array_pos > 14) {
-            gunactive_array_pos = 0;
-        }
-        Serial.print("firing intervals: ");
-        Serial.print(firing_interval); Serial.print(" | "); Serial.println(min_firing_interval);
-        if (firing_interval < min_firing_interval) {
-            current_state = 5;
-        }
-    }
-}
-
-
-void overheat() {
-    currentMillis = millis();
-    if (currentMillis - previousMillis_on > overheat_interval) {
-        previousMillis_on = currentMillis;
-        overheat_array_pos = 1 - overheat_array_pos;
-        Serial.print("Overheat array pos: "); Serial.println(overheat_array_pos);
-        // Load the light sequence from arrays
-        dataPWRCL1 = OHPWRCL1[overheat_array_pos];
-        dataPWRCL2 = OHPWRCL2[overheat_array_pos];
-        dataGUN1 = OHGUN1[overheat_array_pos];
-        dataGUN2 = OHGUN2[overheat_array_pos];
-
-        digitalWrite(latchPin, 0);  // Low to send data
-        // Send data to shift registers:
-        shiftOut(dataPinPWR, clockPinPWR, dataPWRCL1);
-        shiftOut(dataPinPWR, clockPinPWR, dataPWRCL2);
-        shiftOut(dataPinGUN, clockPinGUN, dataGUN1);
-        shiftOut(dataPinGUN, clockPinGUN, dataGUN2);
-        digitalWrite(latchPin, 1);  // high to make shift register show data.
-
-        overheat_counter--;
-        if (overheat_counter < 0) {
-            current_state = 6;
-        }
-    }
-
-}
-
-
-void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {
-    // This shifts 8 bits out MSB first,
-    // on the rising edge of the clock,
-    // clock idles low
-
-    // internal function setup
-    int i = 0;
-    int pinState;
-    pinMode(myClockPin, OUTPUT);
-    pinMode(myDataPin, OUTPUT);
-
-    //clear everything out just in case to
-    //prepare shift register for bit shifting
-    digitalWrite(myDataPin, 0);
-    digitalWrite(myClockPin, 0);
-
-    //for each bit in the byte myDataOut?
-    //NOTICE THAT WE ARE COUNTING DOWN in our for loop
-    //This means that %00000001 or "1" will go through such
-    //that it will be pin Q0 that lights.
-    for (i = 7; i >= 0; i--)  {
-        digitalWrite(myClockPin, 0);
-
-        //if the value passed to myDataOut and a bitmask result
-        // true then... so if we are at i=6 and our value is
-        // %11010100 it would the code compares it to %01000000
-        // and proceeds to set pinState to 1.
-        if ( myDataOut & (1 << i) ) {
-            pinState = 1;
-        }
-        else {
-            pinState = 0;
-        }
-
-        //Sets the pin to HIGH or LOW depending on pinState
-        digitalWrite(myDataPin, pinState);
-        //register shifts bits on upstroke of clock pin
-        digitalWrite(myClockPin, 1);
-        //zero the data pin after shift to prevent bleed through
-        digitalWrite(myDataPin, 0);
-    }
-    //stop shifting
-    digitalWrite(myClockPin, 0);
-}


pulse func v0.1

pulse func v0.1

--- wip/wip.ino
+++ wip/wip.ino
@@ -122,9 +122,9 @@
     delay(ms);
 }

+//ms = time of pulse
 void pulse(CRGB *leds, int numOfLeds, int red, int green, int blue, int ms){
-  int numOfSteps = 10;
-
+  int numOfSteps = 25;

   for (int step = 0; step < numOfSteps; step++){

@@ -133,9 +133,10 @@
     int tempBlue = blue - (step * (blue / numOfSteps));

     for (int i = 0; i < numOfLeds; i++){
-      leds[i].setRGB(tempGreen, tempBlue, tempRed);
+      leds[i].setRGB(tempGreen, tempBlue, tempRed);
     }
-
   }
+  FastLED.show();
+  delay(ms/numOfSteps);

 }


tested uart between PC and arduino 	modified:   serial_experiment/serial_experiment.ino

--- serial_experiment/serial_experiment.ino
+++ serial_experiment/serial_experiment.ino
@@ -1,18 +1,30 @@
-int incomingByte = 0;   // for incoming serial data
+
+

 void setup() {
         Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
+        pinMode(13, HIGH);
 }

+void getString(int arr[]);
+
 void loop() {
+
+  int container[6] = {0,0,0,0,0,0};
+
+  getString(container);
+
+

-        // send data only when you receive data:
-        if (Serial.available() > 0) {
-                // read the incoming byte:
-                incomingByte = Serial.read();
+}

-                // say what you got:
-                Serial.print("I received: ");
-                Serial.println(incomingByte, DEC);
-        }
+void getString(int arr[])
+{
+  if(Serial.available() > 0)
+  {
+
+  }
+
+
+
 }


Simple twiddle, but I had to include RFM12B.h in the Tower.ino file to allow Simon_Comms to compile.

--- src/Tower/Tower.ino
+++ src/Tower/Tower.ino
@@ -1,4 +1,7 @@
+
 // Compile for Uno.
+
+// minor change, to see if RPi2 can commit.

 // The IDE requires all libraries to be #include’d in the main (.ino) file.  Clutter.
 #include <Streaming.h> // <<-style printing
@@ -7,6 +10,7 @@
 #include <Simon_Indexes.h> // sizes, indexing and comms common to Towers and Console
 #include <EEPROM.h> // saving and loading radio settings
 #include <SPI.h> // for radio board
+#include <RFM12B.h> // shouldn't need this, but Simon_Comms won't compile.
 #include <RFM69.h> // RFM69HW radio transmitter module
 #include <Simon_Comms.h>  // Tower<=>Console

@@ -465,4 +469,4 @@

 void otherOff() {
   digitalWrite(OTHER, HIGH);
-}
+}


Add more doc comments

Add more doc comments

--- skittle-color-sorter.ino
+++ skittle-color-sorter.ino
@@ -36,6 +36,8 @@
 #define PIN_LCD_D7 2
 //    LCD R/W pin to ground

+// Uncomment the following line to enter calibration mode
+// #define F_CALIBRATING true // Is calibration in progress

 // Constants
 #define C_ATIME TCS34725_INTEGRATIONTIME_154MS //  Color sensor integration time 154ms
@@ -49,9 +51,6 @@
 #define C_TOP_SERVO_TIMEOUT 6000 // Timeout to determine if the top servo is stuck

 #define C_COLOR_SIGNAL_TIME 1000 // Each Skittle gets 1s color view signal
-
-// Uncomment the following line to enter calibration mode
-// #define F_CALIBRATING true // Is calibration in progress

 // Include libraries
 #include <LiquidCrystal.h>      // LCD display
@@ -62,23 +61,19 @@
 // Calibrated Skittle's Colors
 // These are the skittle's colors
 #define C_COLOR_EMPTY C_Color(61, 88, 72)
+#define C_SKITTLE_RED C_Color(97, 62, 55)
 #define C_SKITTLE_GREEN C_Color(64, 109, 51)
-#define C_SKITTLE_RED C_Color(97, 62, 55)
 #define C_SKITTLE_YELLOW C_Color(88, 91, 36)
 #define C_SKITTLE_PURPLE C_Color(65, 74, 77)
 #define C_SKITTLE_ORANGE C_Color(107, 66, 40)

 const C_Color colorList [] = {C_SKITTLE_RED, C_SKITTLE_GREEN, C_SKITTLE_YELLOW, C_SKITTLE_PURPLE, C_SKITTLE_ORANGE};

-// Initialize the display with the numbers of the interface pins
-LiquidCrystal lcd(PIN_LCD_RS, PIN_LCD_ENABLE, PIN_LCD_D4, PIN_LCD_D5, PIN_LCD_D6, PIN_LCD_D7);
-// Create the object for the top continuous rotation servo
-Servo servoTop;
-// Create the object for the bottom standard servo
-Servo servoBtm;
-// Create the color sensor object
-Adafruit_TCS34725 tcs = Adafruit_TCS34725(C_ATIME, TCS34725_GAIN_1X);
-
+LiquidCrystal lcd(PIN_LCD_RS, PIN_LCD_ENABLE, PIN_LCD_D4,
+  PIN_LCD_D5, PIN_LCD_D6, PIN_LCD_D7); // Initialize the display with the numbers of the interface pins
+Servo servoTop; // Declare the object for the top continuous rotation servo
+Servo servoBtm; // Declare the object for the bottom standard servo
+Adafruit_TCS34725 tcs = Adafruit_TCS34725(C_ATIME, TCS34725_GAIN_1X); // Initialize the color sensor object

 int skittleCount = 0; // The number of skittles sorted
 unsigned long lastSkittleTime = 0; // Time when the last skittle was being sorted
@@ -133,7 +128,8 @@
 #define MIN_BTM_ANGLE 30 // Minimum bottom servo angle
 #define NUM_OF_CUPS 5 // The number of cups at the bottom
 #define EACH_CUP_ANGLE_INTERVAL ((MAX_BTM_ANGLE - MIN_BTM_ANGLE) / NUM_OF_CUPS)
-  int btmAngle = MIN_BTM_ANGLE + EACH_CUP_ANGLE_INTERVAL * sortingResult;
+  int btmAngle = MIN_BTM_ANGLE + EACH_CUP_ANGLE_INTERVAL *
+    (sortingResult == -1? int(NUM_OF_CUPS/2): sortingResult);
   servoBtm.write(btmAngle);
 }

@@ -146,7 +142,7 @@
   int diff = avg_c.compare(new_color).aggregate();
   Serial.print("Diff: "); Serial.println(diff);
   if (diff > C_ALLOWED_COLOR_VARIANCE) {
-    Serial.println("Difference too big. This data is discarded.");
+    Serial.println("Difference too big. This sample data is discarded.");
   } else {
     avg_c.r = (avg_c.r * count + new_color.r) / (count + 1);
     avg_c.g = (avg_c.g * count + new_color.g) / (count + 1);
@@ -155,8 +151,6 @@
     Serial.println("Average color:");
     avg_c.print();
   }
-
-
 }

 void updateColorSensor() {
@@ -183,11 +177,8 @@
       min_clear = colors.c;
       best_color = colors;
     }
-
     if (colors.c > C_HOLE_CLEAR) {
-
       best_color.maximize(); // Maximize color
-
       if (best_color.compare(C_COLOR_EMPTY).aggregate() < 16) {
         // If this is an empty hole.
         Serial.println("Empty hole");
@@ -197,37 +188,39 @@
         //Serial.println("Maximized colors:");
         //best_color.print();

-        if (F_CALIBRATING) {
+        #if F_CALIBRATING
           // If we are calibrating colors
           __calibrating(best_color);
-        } else {
-
-          int min_diff = C_ALLOWED_COLOR_VARIANCE;
-          sortingResult = -1;
+        #else
+          // Compare the reported color with the pre-defined colors in the colorList
+          // and set the result to the color with the least color variance, if the
+          // variance is still under the allowed variance range (C_ALLOWED_COLOR_VARIANCE)
+
+          int min_diff = C_ALLOWED_COLOR_VARIANCE; // Set the mininum difference to the allowed color variance
+          sortingResult = -1; // Set the result to -1
+
           for (int i = 0; i < sizeof(colorList) / 8; i++) {
+            // Compare the reported color with the color defined in the colorList
             C_Color diff = best_color.compare(colorList[i]);
+
+            // Add the color difference's primary colors (R + G + B) together
             int agg = diff.aggregate();
+            // Check if the aggregated color difference value is less than the minimum color difference
             if (agg < min_diff) {
-              min_diff = agg;
-              sortingResult = i;
-            }
+              // If this is less than the minimun
+              min_diff = agg; // Set the minimun difference to this aggregated color difference
+              sortingResult = i; // Set the result to this color's index
+            }
           }
-
-        }
-
+        #endif
       }
-
       // Serial.println("Finish measuring.");
       isColorBeingMeasured = false;
       lastSkittleTime = millis();
-
-
     }
   }

   // printColors(r, g, b, c);
-
-
 }

 void updateColorView() {


add basic pattern support

add basic pattern support

--- src/blinky.ino
+++ src/blinky.ino
@@ -16,7 +16,7 @@
 #define HSV_SATURATION 255
 /* set this to match the number of patterns you flip
 between when holding the setup button */
-#define N_PATTERNS 5
+#define N_PATTERNS 6
 #define SETUP_BUTTON_HOLD_DURATION 800 // ms

 // PORNJ!!!! These values are selected to look decent on RBG LEDs
@@ -42,6 +42,12 @@
 uint8_t ignore_button_cycles = 0;

 NSFastLED::CFastLED* gLED; // global CFastLED object
+
+// for palette support
+uint8_t gAnimIndex = 0;
+uint8_t gPalette = 0;
+NSFastLED::CRGBPalette16 currentPalette = NSFastLED::RainbowColors_p;
+NSFastLED::TBlendType currentBlending = NSFastLED::LINEARBLEND;

 // make sure we disable wifi cause we dont need that shit!
 SYSTEM_MODE(SEMI_AUTOMATIC);
@@ -122,6 +128,15 @@
   base_hue += HUE_STEP;
 }

+// cycle thru color palettes
+void pattern_color_palettes() {
+  for( int i = 0; i < PIXEL_COUNT; ++i) {
+    uint8_t pIndex = (i + 6*i*PIXEL_COUNT/PIXEL_COUNT + gAnimIndex)%256;
+    leds[i] = NSFastLED::ColorFromPalette(currentPalette, pIndex, 255, currentBlending);
+  }
+  gAnimIndex = (gAnimIndex+3)%256;
+}
+
 // rainbow pulsing with varied breathing cycles
 void pattern_phase_rainbow_pulse() {
   uint8_t cBrightness = NSFastLED::beatsin8(128, 0, 255);
@@ -152,7 +167,7 @@
 // pattern 4
 void pattern_disorient_2(){
   // same as pattern 0, but in quadrants
-  uint8_t offset_0, offset_1, offset_2, offset_3, offset_4;
+  uint8_t offset_0, offset_1, offset_2, offset_3;
   offset_0 = 0;
   offset_1 = PIXEL_COUNT/4;
   offset_2 = PIXEL_COUNT/2;
@@ -203,6 +218,8 @@
     pattern_disorient_2();
   } else if (pattern == 4) {
     pattern_phase_rainbow_pulse();
+  } else if (pattern == 5) {
+    pattern_color_palettes();
   }

   gLED->setBrightness(gBrightness);


removed delays and cleaned up

removed delays and cleaned up

--- BLEBriteLamp.ino
+++ BLEBriteLamp.ino
@@ -34,15 +34,18 @@
 #include <RBL_nRF8001.h>

 #define PROTOCOL_MAJOR_VERSION   0 //
-#define PROTOCOL_MINOR_VERSION   0 //
+#define PROTOCOL_MINOR_VERSION   1 //
 #define PROTOCOL_BUGFIX_VERSION  2 // bugfix

 // Note: the blend micro uses pins 6 and 7 for bluetooth; the blend uses 8 / 9.  Adjust these as needed.
 // standard colors on the Shiftbrite cables are D: white, L: blue, E: green, C: yellow.
-#define DATA_PIN    5
+#define DATA_PIN    9
 #define LATCH_PIN  10
 #define ENABLE_PIN 11
 #define CLOCK_PIN  12
+// override the default REQN and RDYN (new for minor version 1)
+#define REQN		6
+#define RDYN 		7

 #define MAX_COLORS 20
 #define RED_IDX   0
@@ -52,6 +55,7 @@
 ShiftBrite shift(DATA_PIN, LATCH_PIN, ENABLE_PIN, CLOCK_PIN);
 byte colors[MAX_COLORS][3];  // longest chain
 int delayMillis;
+int last = 0;
 int lightCount;
 int currentColor;

@@ -63,9 +67,10 @@
   ble_set_name("BriteLamp");
   currentColor = -1;
   lightCount = 0;
-
+  ble_set_pins(REQN, RDYN);
   // Init. and start BLE library.
   ble_begin();
+  Serial.println("Starting ");
 }

 static byte buf_len = 0;
@@ -95,26 +100,11 @@
   }
 }

-// not using this but it could be useful so I am keeping for now.
-void sendCustomData(uint8_t *buf, uint8_t len)
-{
-  uint8_t data[20] = "Z";
-  memcpy(&data[1], buf, len);
-  ble_write_string(data, len+1);
-}
-
 void readColors(int start, int readCount) {
   for (byte i = start; i < readCount + start; ++i) {
     colors[i][RED_IDX]   = ble_read();
     colors[i][GREEN_IDX] = ble_read();
     colors[i][BLUE_IDX]  = ble_read();
-//    Serial.print("read color ");
-//    Serial.print("#");
-//    Serial.print( colors[i][RED_IDX], HEX);
-//    Serial.print("#");
-//    Serial.print(colors[i][GREEN_IDX], HEX);
-//    Serial.print("#");
-//    Serial.println(colors[i][BLUE_IDX], HEX);
   }
 }
 void loop()
@@ -143,9 +133,6 @@
           Serial.println("too many colors!");
           break;
         }
-//        Serial.print("There are ");
-//        Serial.print((int)readCount);
-//        Serial.println(" colors");
         readColors(lightCount, readCount);
         lightCount += readCount;
       }
@@ -158,9 +145,6 @@
           Serial.println("too many colors!");
           break;
         }
-//        Serial.print("There are ");
-//        Serial.print((int)lightCount);
-//        Serial.println(" colors");
         byte speed = ble_read();
         if (speed == 0) {
           delayMillis = 1000;  // millisecond delay; default 1 second
@@ -169,9 +153,6 @@
           delayMillis = speed * 4;
         }
         currentColor = 0;
-//        Serial.print("Delay is ");
-//        Serial.print( (int)speed);
-//        Serial.println(".");
         readColors(0, lightCount);
         break;
       }
@@ -189,17 +170,16 @@
   // no input or commands, so go ahead and send colors
   // just set the first one.
   // ShiftBrite.
+  if (millis() - last > delayMillis)
+  {
+    last = millis();
+    if (currentColor != -1) {
+      if (currentColor == lightCount)
+        currentColor = 0;

-  if (currentColor != -1) {
-    if (currentColor == lightCount)
-      currentColor = 0;
-//    Serial.print("Updating color ");
-//    Serial.print(currentColor + 1);
-//    Serial.println(" ");
-
-    shift.sendColor((unsigned long)colors[currentColor][RED_IDX], (unsigned long)colors[currentColor][GREEN_IDX], (unsigned long)colors[currentColor][BLUE_IDX]);
-    currentColor++;
-    delay(delayMillis);
+     shift.sendColor((unsigned long)colors[currentColor][RED_IDX], (unsigned long)colors[currentColor][GREEN_IDX], (unsigned long)colors[currentColor][BLUE_IDX]);
+     currentColor++;
+    }
   }

   // No input data, no commands, process analog data


Update Keypad.ino

Update Keypad.ino

--- ComboKeypad/Keypad.ino
+++ ComboKeypad/Keypad.ino
@@ -1,8 +1,12 @@
 //USER VARIABLES, Variables that YOU change for YOUR preferences
 const int buttons[] {7, 6, 5, 4};   //The PIN of all of the buttons
+
 const int combination[] = {3, 1, 2, 4};  //what the combination is, to add just add a "," and a number
+
 const int numOfCombos = sizeof(combination) / sizeof(combination[0]);   //How many combinations
+
 const int numOfButtons = sizeof(buttons) / sizeof(buttons[0]);   //How many buttons you have
+
 const bool useFiveVoltpin = false;   //Change this if you want to use the
 ///////////////////////////////////////5Volt PIN instead of PIN 2(IN MY CASE)
 //USER VARIABLES, Variables that YOU change for YOUR preferences | end


A decrementing while loop saves 2 bytes.

Sketch size is now 27872 bytes.

--- wee_printer.ino
+++ wee_printer.ino
@@ -146,7 +146,8 @@
     }
   } else {
     debug("Couldn't connect");
-    for(byte i=0; i < 10; i++) {
+    byte i = 5;
+    while(i--) {
       digitalWrite(errorLED, HIGH);
       delay(100);
       digitalWrite(errorLED, LOW);


Renamed the output.

Renamed the output.

--- src/sketch.ino
+++ src/sketch.ino
@@ -26,12 +26,12 @@
   /* Serial.println(distance); */
   if (distance > 2150) {
     if (!state) {
-      Serial.println("Turn sound on");
+      Serial.println("InRange");
       state = true;
     }
   } else {
     if (state) {
-      Serial.println("Turn sound off");
+      Serial.println("OutOfRange");
       state = false;
     }
   }


Added time adjust menu and reduced memory size by converting variable types.

--- chicken_door_timer_v2.ino
+++ chicken_door_timer_v2.ino
@@ -13,6 +13,7 @@
 #include <avr/sleep.h>
 #include <avr/power.h>
 #include <avr/wdt.h>
+#include <stdint.h>

 #include <LiquidCrystal.h>
 #include <Wire.h>
@@ -21,6 +22,16 @@
 #include <TimeLord.h>
 #include "RTClib.h"
 #include "encoder.h"
+
+#define LATITUDE -42.9166667
+#define LONGITUDE 147.3333282
+
+#define TIMEOUT_MAX 220
+#define DELAY_MS 10
+#define MAX_DELAY_MINUTES 100
+#define DOOR_RETRY_SECONDS 10
+#define MAX_TIMEDELTA_MINS 240
+#define MIN_TIMEDELTA_MINS -240

 // Pins
 #define PIN_ENC_A     7
@@ -62,22 +73,17 @@
 #define DEBOUNCE_MS 20
 #define PULLUP false
 #define INVERT false
-#define DOOR_RETRY_SECONDS 10
+
+#define MENU_COUNT 2
+
+volatile char f_timer=0;
+
+char menu_pos = 0;
+byte delay_val = 0;
+byte door_retry_seconds_c = 0;

 Button menuButton(PIN_ENC_BTN, PULLUP, INVERT, DEBOUNCE_MS);

-#define MENU_COUNT 2
-
-volatile int f_timer=0;
-
-//const int DELAYTIME_SEC = 20;
-const int TIMEOUT_MAX = 220;
-const int DELAY_MS = 10;
-const int MAX_DELAY_MINUTES = 100;
-int menu_pos = 0;
-int delay_val = 0;
-int door_retry_seconds_c = 0;
-
 RTC_DS1307 rtc;

 LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
@@ -88,27 +94,25 @@

 Encoder encoder(PIN_ENC_A, PIN_ENC_B, PIN_ENC_BTN);

-float const LATITUDE = -42.9166667;
-float const LONGITUDE = 147.3333282;
-
-byte today[6];
 byte sunrise[6];
 byte sunset[6];

 // process logic booleans
 bool is_day_time = false;
 bool door_open = false;
-bool in_setup_menu = false;
+bool in_options_menu = false;
 bool in_pre_delay_menu = false;
 bool in_post_delay_menu = false;
-bool set_delay_value = false;
+bool in_time_adj_menu = false;
+bool in_delay_adj_menu = false;
+
 bool hit_bottom = false;
 bool hit_top = false;
 bool couldnt_close_door = false;
 bool couldnt_open_door = false;

-unsigned int delay_time_before_sunrise;
-unsigned int delay_time_after_sunset;
+byte delay_time_before_sunrise;
+byte delay_time_after_sunset;

 /* Read EEPROM settings
@@ -133,7 +137,7 @@
   byte sunrise_dt_c_calc = CKSUM_SECRET ^ sunrise_dt_v0;
   sunrise_dt_c_calc ^= sunrise_dt_v1;

-  int eeprom_success = 0x00;
+  char eeprom_success = 0x00;

   // if checksum mismatch - something went wrong with EEPROM writing. Try to reset
   if(sunrise_dt_c_calc != sunrise_dt_c){
@@ -336,7 +340,7 @@
   // send high to door open motor pin
   digitalWrite(PIN_DOOR_UP, HIGH);

-  int timeoutcount = 0;
+  char timeoutcount = 0;

   // loop until limit switch is hit (also add timeout)
   Serial.print("Waiting for door to open");
@@ -374,7 +378,7 @@
   lcd.clear();
   lcd.setCursor(0, 0);
   lcd.print("Closing door");
-  int timeoutcount = 0;
+  char timeoutcount = 0;

   // loop until limit switch is hit  (also add timeout)
   Serial.print("Waiting for door to close");
@@ -582,6 +586,9 @@
   //today =  {now.second(), now.minute(), now.hour(), now.day(), now.month(), now.year() } ;
   // check if it is time to open the door

+  byte today[6];
+
+
   now = rtc.now();
   today[0] = now.second();
   today[1] = now.minute();
@@ -599,9 +606,9 @@
     Serial.print("Sunset: ");
     Serial.print((int) sunset[tl_hour]);
     Serial.print(":");
-    Serial.println((int) sunset[tl_minute]);
-
-    int delta_mins = (now.hour() * 60 - sunset[tl_hour] * 60) + now.minute() - sunset[tl_minute];
+    Serial.println((char) sunset[tl_minute]);
+
+    byte delta_mins = (now.hour() * 60 - sunset[tl_hour] * 60) + now.minute() - sunset[tl_minute];

     if(delta_mins > 0){
       Serial.print("Time after sunset: ");
@@ -643,8 +650,8 @@
     Serial.print("Sunrise: ");
     Serial.print((int) sunrise[tl_hour]);
     Serial.print(":");
-    Serial.println((int) sunrise[tl_minute]);
-    int delta_mins;
+    Serial.print((int) sunrise[tl_minute]);
+    byte delta_mins;
     if(!is_day_time){
       if(evening){
         // get total mins including minutes before midnight
@@ -674,23 +681,23 @@

 }

-void tensDigitLCD(int digit){
+void tensDigitLCD(char digit){
   if(digit / 10 < 1){
-    lcd.print("0");
-  }
-  lcd.print(digit);
+    lcd.print('0');
+  }
+  lcd.print((int)digit);
 }

 void updateLCD(){
  lcd.clear();
  tensDigitLCD(now.day());
- lcd.print("/");
+ lcd.print('/');
  tensDigitLCD(now.month());
- lcd.print("/");
+ lcd.print('/');
  lcd.print(now.year());
- lcd.print(" ");
+ lcd.print(' ');
  tensDigitLCD(now.hour());
- lcd.print(":");
+ lcd.print(':');
  tensDigitLCD(now.minute());
   if(is_day_time){
     lcd.setCursor(0, 1);
@@ -716,7 +723,7 @@
   } else if(in_post_delay_menu){
     lcd.print("Post: ");
   }
-  lcd.print(delay_val);
+  lcd.print((int)delay_val);
   lcd.print(" mins");
 }

@@ -739,10 +746,10 @@
 }

 // write new delay value to EEPROM (including checksum)
-void setdelay_valEEPROM(bool sunrise, int val){
-  int val_l = (val & 0b11110000) >> 4;
-  int val_r = val & 0b00001111;
-  int checksum = CKSUM_SECRET ^ val_l;
+void setdelay_valEEPROM(bool sunrise, char val){
+  char val_l = (val & 0b11110000) >> 4;
+  char val_r = val & 0b00001111;
+  char checksum = CKSUM_SECRET ^ val_l;
   checksum ^= val_r;
   if(sunrise){
     EEPROM.write(SUNRISE_DT_0_P, val_l);
@@ -755,8 +762,9 @@
   }
 }

-// When button clicked, change delay value
-void updateDelaySettings(){
+// when user selects pre/post delay, draw
+void updateDelayLoop(){
+  bool set_delay_value = false;
   // get latest EEPROM values..
   readEEPROM();
   if(in_pre_delay_menu){
@@ -781,7 +789,66 @@
   }
 }

-// For drawing main menu
+// read encoder and update time delta value on LCD
+byte updatetime_valLoop(byte prev){
+  encState eState = encoder.read();
+  if (eState == ENC_DEC) {
+    if (prev < MIN_TIMEDELTA_MINS) {
+      prev = MAX_TIMEDELTA_MINS;
+    } else {
+      prev = (prev - 1);
+    }
+    tone(PIN_PIEZO, 100 + prev * 12, 25);
+    drawAdjustTime(prev);
+  } else if (eState == ENC_INC) {
+    prev = (prev + 1) % (MAX_TIMEDELTA_MINS);
+    tone(PIN_PIEZO, 100 + prev * 12, 25);
+    drawAdjustTime(prev);
+  }
+  return prev;
+}
+
+// adjusting the time
+void adjustTimeLoop(){
+  now = rtc.now();
+  drawAdjustTime(0);
+  bool set_time_dt_val = false;
+  byte deltaTimeMins = 0;
+  while(!set_time_dt_val){
+    wdt_reset();
+    deltaTimeMins = updatetime_valLoop(deltaTimeMins);
+    menuButton.read();
+    if(menuButton.wasReleased()){
+      tone(PIN_PIEZO, 500, 100);
+      delay(200);
+      tone(PIN_PIEZO, 500, 100);
+      set_time_dt_val = true;
+
+      // todo: set time
+
+    }
+  }
+
+}
+
+// draw time adjust screen on LCD
+void drawAdjustTime(char delta){
+  lcd.clear();
+  tensDigitLCD(now.hour());
+  lcd.print(":");
+  tensDigitLCD(now.minute());
+  lcd.setCursor(0, 1);
+  if(delta < 0){
+    lcd.print("-");
+  } else if (delta > 0){
+    lcd.print("+");
+  }
+  lcd.print(" ");
+  lcd.print((char)delta);
+  lcd.print(" mins.");
+}
+
+// pre/post selection menu 1 - before sunrise
 void drawPreDelayMenu(){
   lcd.clear();
   lcd.print("Set delay before");
@@ -791,6 +858,7 @@
   in_post_delay_menu = false;
 }

+// pre/post selection menu - after sunset
 void drawPostDelayMenu(){
   lcd.clear();
   lcd.print("Set delay after");
@@ -800,14 +868,43 @@
   in_post_delay_menu = true;
 }

+// time adjust menu option
+void drawTimeOption(){
+  lcd.clear();
+  lcd.print("Adjust time by");
+  lcd.setCursor(0, 1);
+  lcd.print("mins [1/2]");
+  in_time_adj_menu = true;
+  in_delay_adj_menu = false;
+}
+
+// delay adjust menu option
+void drawDelayOption(){
+  lcd.clear();
+  lcd.print("Set pre/post delays");
+  lcd.setCursor(0, 1);
+  lcd.print("[2/2]");
+  in_delay_adj_menu = true;
+  in_time_adj_menu = false;
+}
+
+// cycling through menus (delay / time / pre/post delay)
 void drawSelectedMenu(){
   lcd.setCursor(0, 0);
   if(menu_pos == 0){
-    drawPreDelayMenu();
-    in_pre_delay_menu = true;
+    if(!in_options_menu){
+      drawPreDelayMenu();
+      //in_pre_delay_menu = true;
+    } else {
+      drawTimeOption();
+    }
   } else if (menu_pos == 1){
-    drawPostDelayMenu();
-    in_post_delay_menu = true;
+    if(!in_options_menu){
+      drawDelayOption();
+    } else {
+      drawPostDelayMenu();
+      //in_post_delay_menu = true;
+    }
   }
 }

@@ -839,19 +936,25 @@
   menuButton.read();
   if(menuButton.wasReleased()){
     tone(PIN_PIEZO, 1000, 50);
-    // if in main menu (date/time)
-    if(!in_setup_menu){
+    // if in main menu (date/time) - not in options yet
+    if(!in_options_menu){
+      in_options_menu = true;
+      // show options menu
       lcd.clear();
-      in_setup_menu = true;
-      in_pre_delay_menu = true;
-      in_post_delay_menu = false;
+      // draw first option of options menu - adjust time
+      drawTimeOption();
+
+    } else if(in_delay_adj_menu){ /* user chose delay adjustion - draw first menu, set pre-delay */
       drawPreDelayMenu();
-    } else if (in_pre_delay_menu || in_post_delay_menu){
+      in_options_menu = false;
+    } else if (in_time_adj_menu){ /* user chose time adjustion - run time adjust loop */
+      adjustTimeLoop();
+      in_options_menu = false;
+    } else if (in_pre_delay_menu || in_post_delay_menu){ /* user chose pre/post delay - run delay adjust loop */
       Serial.println("drawing menu screen to update delay value");
-      set_delay_value = false;
-      updateDelaySettings();
-      in_setup_menu = false;
-    }
+      updateDelayLoop();
+      in_options_menu = false;
+    }
   }

 }
@@ -862,7 +965,7 @@
   checkIfButtonPressed();

   // if in menu, update menu
-  if(in_setup_menu){
+  if(in_options_menu){
     updateSetupMenu();
   } else {
     // main loop - sleep for about 4s (maximum for timer?) then check time and update door


Display hello message.

Display hello message.

--- arduino_sds011.ino
+++ arduino_sds011.ino
@@ -72,11 +72,12 @@
     } else {
         display.clear();
     }
-    display.setCursor(0,0);
-    display.print(r.c_str());
 #else
     display.clear();
 #endif
+
+    display.setCursor(0,0);
+    display.println("Hello");

     sensor.set_sleep(false);
     sensor.set_mode(sds011::QUERY);


Explain that some codes are toggle and some are on/off explicit.

--- thecantina.ino
+++ thecantina.ino
@@ -2,7 +2,7 @@
 #include "RCSwitch/RCSwitch.h"
 #include <string.h>

-#define OFFICE_Light_1_Toggle 87489
+#define OFFICE_Light_1_Toggle 87489 //these are light bulb holders that use a toggle code instead of individual on/off codes
 #define OFFICE_Light_2_Toggle 87345
 #define OFFICE_Light_3_Toggle 87309


added ArduinoOTA to Sonoff-Dual, fixed LED and removed debug serial code

--- sonoff-homie-dual/sonoff-homie-dual.ino
+++ sonoff-homie-dual/sonoff-homie-dual.ino
@@ -1,4 +1,7 @@
 #include <Homie.h>
+#include <ArduinoOTA.h>
+
+#define PIN_LED     13      // PIN 12 / HSPI_MOSI; UART0_CTS MTCK

 /**
   * Arduino IDE instructions
@@ -61,11 +64,15 @@
   Homie.disableLogging();
   relayNode1.advertise("on").settable(relayHandler1);
   relayNode2.advertise("on").settable(relayHandler2);
+
+  Homie.setLedPin(PIN_LED, LOW);
   Homie.setup();
   Serial.begin(19200);
-  Serial.println("hello");
+  ArduinoOTA.setHostname(Homie.getConfiguration().deviceId);
+  ArduinoOTA.begin();
 }

 void loop() {
   Homie.loop();
+  ArduinoOTA.handle();
 }


Added some comments

Added some comments

--- Teensy_Quad.ino
+++ Teensy_Quad.ino
@@ -680,6 +680,7 @@
 				Update the controls if the update flag was set in the serialEvent1 callback.
 			*/
 			if(update_flag) {
+				//lock in case there are interrupts.
 				acquireLock();
 				for(int i = 0; i < BUFFERSIZE; i++) {
 					throttle = buffer[0];
@@ -721,8 +722,16 @@
 			#endif
 			//run pids at 100Hz
 			if(oneHunHzEvent.shouldRunEvent()) {
+
+			#if defined(DEBUG)
+				Serial.print("100 Hz Event Time: ");
+				Serial.println(micros());
+			#endif
+				//compute PIDS now.
 				computePID();
 			}
+
+			//update motor values.
 			updateMotors();

 			#ifdef DEBUG
@@ -989,7 +998,7 @@
 }

 /**
-* Copute the next PIDs.
+* Compute the next PIDs.
 */
 inline void computePID() {
 	acquireLock();


Fixed servo in GEN2. Pin ~11 still has problems. We need to debug that. But this is great for prototyping at this point.

--- BackEnd/BackEnd.ino
+++ BackEnd/BackEnd.ino
@@ -147,8 +147,8 @@
   int is_input;
   int is_servo;
   int is_servo_prev;
-//  Servo* poServo;
-  Servo oServo;
+  Servo* poServo;
+ // Servo oServo;
   float input_min;
   float input_max;
 //  float sensitivity;
@@ -849,13 +849,12 @@
     else
       g_aPins[i].is_analog = false;

-    // Setting Servos to ~ pins. We only have 8 servos in the Servo lib.
-    /*
+    // Setting Servos to ~ pins. We only have 8 servos in the Servo lib.
     if( i==3 || i==5 || i==6 || i==9 || i==10 || i==11 )
       g_aPins[i].poServo = new Servo();
     else
       g_aPins[i].poServo = NULL;
-      */
+

     // Initialize digital pins as outputs
     if( i < NUM_OF_DIGITAL_PINS )
@@ -909,23 +908,17 @@
     {
       if( g_aPins[i].is_analog ) // Process analog pins
       {
-        if(i == 3) // DEBUGGING
-        {
           if( !g_aPins[i].is_servo ) // Process servo output pins
           {
      //       Serial.print("Pin #");Serial.print(i);Serial.print(": ");
             analogWrite(i, getTotalPinValue(i)*ANALOG_OUT_MAX_VALUE );
-     //       delay(15);                       // waits 15ms for the servo to reach the position
           }
           else
           {
-//            g_aPins[i].poServo->write(int(getTotalPinValue(i)*ANALOG_OUT_MAX_VALUE));
-            g_aPins[i].oServo.write(int(getTotalPinValue(i)*ANALOG_OUT_MAX_VALUE));
-            delay(15);                       // waits 15ms for the servo to reach the position
+            g_aPins[i].poServo->write(int(getTotalPinValue(i)*ANALOG_OUT_MAX_VALUE));
           }
     //      Serial.print(i);Serial.print(": ");
     //      Serial.println(getTotalPinValue(i)*ANALOG_OUT_MAX_VALUE);
-        }
       }
       else // Process digital pins
         digitalWrite(i, getTotalPinValue(i) );
@@ -1516,28 +1509,22 @@
         g_aPins[i].is_servo = poIsServo->valuebool;

         ////////////////////////// Changing Analog Pin to Servo //////////////////////////
-       if(i == 3) // DEBUGGING
-       {
-          if( g_aPins[i].is_servo_prev != g_aPins[i].is_servo )
+        if( g_aPins[i].is_servo_prev != g_aPins[i].is_servo )
+        {
+          if(!g_aPins[i].is_servo)
           {
-            if(!g_aPins[i].is_servo)
-            {
-//              g_aPins[i].poServo->detach();
-//              g_aPins[i].poServo->setFreqInSysFs(SYSFS_PWM_PERIOD_NS);
-              g_aPins[i].oServo.detach();
-              g_aPins[i].oServo.setFreqInSysFs(SYSFS_PWM_PERIOD_NS);
-              Serial.print("Pin ");Serial.print(i);Serial.println(" detached.");
-            }
-            else
-            {
-             // g_aPins[i].poServo->attach(i);
-              g_aPins[i].oServo.attach(i);
-              Serial.print("Pin ");Serial.print(i);Serial.println(" attached.");
-            }
+            g_aPins[i].poServo->detach();
+            g_aPins[i].poServo->setFreqInSysFs(SYSFS_PWM_PERIOD_NS);
+//              Serial.print("Pin ");Serial.print(i);Serial.println(" detached.");
           }
-
-          g_aPins[i].is_servo_prev = g_aPins[i].is_servo;
+          else
+          {
+            g_aPins[i].poServo->attach(i);
+ //           Serial.print("Pin ");Serial.print(i);Serial.println(" attached.");
+          }
         }
+
+        g_aPins[i].is_servo_prev = g_aPins[i].is_servo;
         ////////////////////////////////////////////////////
       }
       else


latest with RCMM from microtherion

latest with RCMM from microtherion

--- examples/IRrelay/IRrelay.ino
+++ examples/IRrelay/IRrelay.ino
@@ -36,6 +36,9 @@
     }
     else if (results->decode_type == RC6) {
       Serial.print("Decoded RC6: ");
+    }
+    else if (results->decode_type == RCMM) {
+      Serial.print("Decoded RCMM: ");
     }
     Serial.print(results->value, HEX);
     Serial.print(" (");


Fix #337

Fix #337

--- examples/Widgets/RTC/RTC.ino
+++ examples/Widgets/RTC/RTC.ino
@@ -72,6 +72,11 @@
   Blynk.virtualWrite(V2, currentDate);
 }

+BLYNK_CONNECTED() {
+  // Synchronize time on connection
+  rtc.begin();
+}
+
 void setup()
 {
   // Debug console
@@ -79,12 +84,11 @@

   Blynk.begin(auth);

-  // Begin synchronizing time
-  rtc.begin();
-
   // Other Time library functions can be used, like:
   //   timeStatus(), setSyncInterval(interval)...
   // Read more: http://www.pjrc.com/teensy/td_libs_Time.html
+
+  setSyncInterval(10*60); // Sync interval in seconds (10 minutes)

   // Display digital clock every 10 seconds
   timer.setInterval(10000L, clockDisplay);


Change Particle.Publish Data String

Change Particle.Publish Data String

--- firmware/examples/BMP280.ino
+++ firmware/examples/BMP280.ino
@@ -7,7 +7,7 @@
 // #define BMP_CS A2
 // #define BMP_SCK A3
 // #define BMP_MISO A4
-// #define BMP_MOSI A5
+// #define BMP_MOSI A5

 Adafruit_BMP280 bmp; // I2C
 //Adafruit_BMP280 bmp(BMP_CS); // hardware SPI
@@ -39,10 +39,7 @@

 void checkEnvironment() {

-  Particle.publish("DEBUG", "checking the environment...");
-  Particle.publish("environment/temperature", String(cToF(bmp.readTemperature())));
-  Particle.publish("environment/pressure", String(pToHg(bmp.readPressure())));
-  Particle.publish("environment/altitude", String(bmp.readAltitude(seaLevelhPa)));
+    Particle.publish("EnvironmentData", String::format("Temp: %.1f °C / %.1f °F, Pressure %.1f mbar, Humidity %.1f %%", cTemp, fTemp, pressure, humidity), PRIVATE);
 }

 float cToF(float c) {


MQTT status should be sent after reconnecting to MQTT broker

--- src/sonoff-core.ino
+++ src/sonoff-core.ino
@@ -75,14 +75,14 @@
       if (Configuration.debugger) Serial << " - Subsribed to : " << Configuration.mqtt_topic << endl;

       /* Post connection relay set up */
-      if (Eeprom.getRelayStateAfterConnectionRestored() == DEFAULT_RELAY_ON && Relay.get() == RELAY_OFF) {
+      if (Eeprom.getRelayStateAfterConnectionRestored() == DEFAULT_RELAY_ON) {
         Relay.on();
-      } else if (Eeprom.getRelayStateAfterConnectionRestored() == DEFAULT_RELAY_OFF && Relay.get() == RELAY_ON) {
+      } else if (Eeprom.getRelayStateAfterConnectionRestored() == DEFAULT_RELAY_OFF) {
         Relay.off();
       } else if (Eeprom.getRelayStateAfterConnectionRestored() == DEFAULT_RELAY_LAST_KNOWN) {
-        if (Eeprom.getRelayState() == 0 && Relay.get() == RELAY_ON) {
+        if (Eeprom.getRelayState() == 0) {
           Relay.on();
-        } else if (Eeprom.getRelayState() == 1 && Relay.get() == RELAY_OFF) {
+        } else if (Eeprom.getRelayState() == 1) {
           Relay.off();
         }
       } else  {


Add EasyTransfer integration to Music.ino

--- src/Music/Music.ino
+++ src/Music/Music.ino
@@ -52,6 +52,9 @@
 const char dirLose[] = "LOSE";
 const char dirRock[] = "ROCK";

+EasyTransfer easyTransfer;
+PlayMessage message;
+
 void setup() {
     Serial.begin(SERIAL_SPEED);

@@ -60,59 +63,32 @@

     // set random seed from analog noise
     randomSeed(analogRead(A0));
+    easyTransfer.begin(details(message), &Music);

     // setup LED pin
     pinMode(LED_PIN, OUTPUT);
 }

 void toggleLED() {
-    static boolean state=false;
-
-    state=!state;
+    static boolean state = false;
+
+    state = !state;

     digitalWrite(LED_PIN, state);
 }

-// called when a serial message is received.
 void serialEvent() {
-    //  if ( musicPlayer.playingMusic )
-    //    musicPlayer.pausePlaying(true); // hang on.  the music playback has enough interrupt calls that it disrupts serial.
-
-    char command = Serial.read();
-
-    //  if ( musicPlayer.paused )
-    //    musicPlayer.pausePlaying(false); // restart if needed.
-
-    if ( command < '0' || command > 'z' ) return; // spurious characters like line feed.
-    else Serial << command << endl;
-
-    if ( command >= '0' && command <= '9' ) {
-        byte vol = constrain(map(command - '0', 0, 9, MIN_MP3_VOL, 0), 0, MIN_MP3_VOL); // 0 is the loudest.  map 1-9 to 0-255.
-        // Set volume for left, right channels. lower numbers == louder volume!
-        musicPlayer.setVolume(vol, vol);
-        Serial << F("Volume set: ") << vol << endl;
-    } else {
-        switch ( command ) {
-            case 'u': playingWhat = 5; break;
-            case 'p': musicPlayer.pausePlaying(!musicPlayer.paused()); break;
-            case 's': playingWhat = 0; break;
-            case 'r': playingWhat = 1; break;
-            case 'w': playingWhat = 2; break;
-            case 'l': playingWhat = 3; break;
-            case 'b': playingWhat = 4; break;
-            default: Serial << F("Unknown Command(") << command << F(") Try: u,p,s,0-9,r,w,l,b.") << endl;
-        }
+    if (easyTransfer.receiveData()) {
+        playMusic(message);
     }
 }

 void loop() {
     // check playing state, and report if we've stopped
-    if ( playingWhat > 0 && !musicPlayer.playingMusic) {
-        // we've just stopped
-        Serial << endl;
-        playAnotherRandomTrack();
-    } else if( playingWhat == 0 && musicPlayer.playingMusic ) {
-        // we should stop
+    if ( message.type > TYPE_STOP && !musicPlayer.playingMusic) {
+        Serial << endl; // TODO: what does this line do?
+        playRandomTrack(getDirectory(message.type), message.playCount);
+    } else if( message.type == TYPE_STOP && musicPlayer.playingMusic ) {
         musicPlayer.stopPlaying();
     }

@@ -126,16 +102,16 @@
         toggleLED();
         isPlayingTick.reset();
     }
-
-}
-
-void playAnotherRandomTrack() {
-    switch (playingWhat) {
-        case 1: playRandomTrack(dirRock, tracksRock); break;
-        case 2: playRandomTrack(dirWins, tracksWins); break;
-        case 3: playRandomTrack(dirLose, tracksLose); break;
-        case 4: playRandomTrack(dirBaff, tracksBaff); break;
-        case 5: musicUnitTest(); break;
+}
+
+char* getDirectory(int messageType) {
+    switch (messageType) {
+        case TYPE_BAFF: return dirBaff;
+        case TYPE_WIN: return dirWins;
+        case TYPE_LOSE: return dirLose;
+        case TYPE_ROCK: return dirRock;
+        default: dirRock;
+        //case 5: musicUnitTest(); break;
     }
 }

@@ -144,7 +120,6 @@
     musicPlayer.stopPlaying();
     musicPlayer.sciWrite(VS1053_REG_MODE, VS1053_MODE_SM_SDINEW | VS1053_MODE_SM_RESET);

-    // open the directory
     File dir = SD.open(dirName);
     if ( ! dir.isDirectory() ) {
         Serial << F("Error! not a directory: ") << dirName << endl;
@@ -166,7 +141,6 @@
     }
     //  Serial << endl;

-    // close up
     dir.close();

     Serial << endl << F(" -> ") << dir.name() << F("/") << entry.name() << F(" [") << track + 1 << F("/") << totalTracks << F("]") << endl;


RSSI buzzer alarms adjusted

RSSI buzzer alarms adjusted

--- crossbow.ino
+++ crossbow.ino
@@ -428,10 +428,10 @@
     } else if (txDeviceState.isReceiving && (rxDeviceState.flags & 0x1) == 1) {
         //Failsafe reported by RX module
         buzzerContinousMode(BUZZER_MODE_SLOW_BEEP, &buzzer);
-    } else if (txDeviceState.isReceiving && radioState.rssi < 100) {
-        buzzerContinousMode(BUZZER_MODE_DOUBLE_CHIRP, &buzzer);
-    } else if (txDeviceState.isReceiving && radioState.rssi < 128) {
-        buzzerContinousMode(BUZZER_MODE_CHIRP, &buzzer);
+    } else if (txDeviceState.isReceiving && radioState.rssi < 60) {
+        buzzerContinousMode(BUZZER_MODE_DOUBLE_CHIRP, &buzzer); // RSSI below 60dB
+    } else if (txDeviceState.isReceiving && radioState.rssi < 80) {
+        buzzerContinousMode(BUZZER_MODE_CHIRP, &buzzer); // RSSI below 80dB
     } else {
         buzzerContinousMode(BUZZER_MODE_OFF, &buzzer);
     }


change default board settings to Uwe

change default board settings to Uwe

--- examples/Fahrstuhl/Fahrstuhl.ino
+++ examples/Fahrstuhl/Fahrstuhl.ino
@@ -30,8 +30,9 @@

 #define BUTTON_LONG_PRESS_DELAY 2000

-#define AJS_BOARD_SETTINGS
-//#define UWE_BOARD_SETTINGS
+// Uncomment ONE of the next 2 lines to enable AJS or UWE Board Settings
+//#define AJS_BOARD_SETTINGS
+#define UWE_BOARD_SETTINGS

 #if defined(AJS_BOARD_SETTINGS)  // Setting for AJS Dev System

@@ -84,6 +85,7 @@
 #define STEPPER_INC_SPEED             (STEPPER_MAX_SPEED / 2)

 #define OLED_DISPLAY_I2C_ADDRESS  0x3C
+
 #else
 #error No Board Settings Defined
 #endif