Update example header

Update example header

--- libraries/CurieImu/examples/Accelerometer/Accelerometer.ino
+++ libraries/CurieImu/examples/Accelerometer/Accelerometer.ino
@@ -1,33 +1,25 @@
 /*
-  ===============================================
-  Example sketch for CurieIMU library for Intel(R) Curie(TM) devices.
-  Copyright (c) 2015 Intel Corporation.  All rights reserved.
+   Copyright (c) 2015 Intel Corporation.  All rights reserved.

-  Based on I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050
-  class by Jeff Rowberg: https://github.com/jrowberg/i2cdevlib
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 2.1 of the License, or (at your option) any later version.

-  ===============================================
-  I2Cdev device library code is placed under the MIT license
-  Copyright (c) 2011 Jeff Rowberg
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.

-  Permission is hereby granted, free of charge, to any person obtaining a copy
-  of this software and associated documentation files (the "Software"), to deal
-  in the Software without restriction, including without limitation the rights
-  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-  copies of the Software, and to permit persons to whom the Software is
-  furnished to do so, subject to the following conditions:
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, write to the Free Software
+   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

-  The above copyright notice and this permission notice shall be included in
-  all copies or substantial portions of the Software.
+*/

-  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-  THE SOFTWARE.
-  ===============================================
+/*
+   This sketch example demonstrates how the BMI160 on the
+   Intel(R) Curie(TM) module can be used to read accelerometer data
 */

 #include "CurieImu.h"


Implemented the C++ side of timer calibration

--- firmware/node/node.ino
+++ firmware/node/node.ino
@@ -22,9 +22,11 @@
 const uint8_t PACKET_ADDR         = 9;
 const uint8_t PACKET_SPEED        = 10;
 const uint8_t PACKET_CLASSES      = 11;
+const uint8_t PACKET_CALIBRATE    = 12;

 // where in EEPROM our node id is stored
 const int id_address = 0;
+const int calibration_address = 16;

 // ----- globals ------------

@@ -331,6 +333,40 @@

                 break;
             }
+        case PACKET_CALIBRATE:
+            {
+                uint32_t duration = data[0];
+                color_t col;
+
+                col.c[1] = col.c[2] = 0;
+                col.c[0] = 255;
+
+                // clear out any stray characters
+                while(Serial.available() > 0)
+                    Serial.read();
+
+                show_color(&col);
+
+                // Wait for the next character, which starts the calibration interval for duration seconds
+                Serial.read();
+                noInterrupts();
+                TCNT1 = 0;
+                g_time = 0;
+                interrupts();
+
+                // Wait for the next character, which ends the calibration
+                Serial.read();
+
+                // Now calculate our calibration routine
+                noInterrupts();
+                TCNT1 = g_timer_init = 2000 - ((g_time * 1000 + TCNT1) / duration);
+                interrupts();
+                EEPROM.put(calibration_address, g_timer_init);
+
+                col.c[0] = col.c[1] = 0;
+                col.c[2] = 255;
+                show_color(&col);
+            }
     }
 }

@@ -495,9 +531,11 @@

 void setup()
 {
+    uint16_t timer_cal;

     TCNT1 = TIMER1_INIT;
     TIMSK1 |= (1<<TOIE1);
+    interrupts();

     g_pixels.begin();
     startup_animation();
@@ -506,6 +544,9 @@
     Serial.println("led-board hello!");

     g_node_id = EEPROM.read(id_address);
+    EEPROM.get(calibration_address, timer_cal);
+    if (timer_cal > 1)
+        g_timer_init = timer_cal;
 }

 void loop()


Test mit RGB LED

Test mit RGB LED

RGB LED getestet für schnelle Status-Anzeige - beispielsweise Daten über Serielle Schnittstelle übertragen OK (Grün)/Fehler (ROT); das wäre noch zu implementieren

--- tft_weatherstation/tft_weatherstation_v2.ino
+++ tft_weatherstation/tft_weatherstation_v2.ino
@@ -17,6 +17,7 @@
 #define DHTTYPE DHT22
 #define PIN_LED 24 //Serial Data LED
 #define SERIALWAIT 200
+#define interruptPin 19

 // Assign human-readable names to some common 16-bit color values:
 #define BLACK   0x0000
@@ -27,6 +28,16 @@
 #define MAGENTA 0xF81F
 #define YELLOW  0xFFE0
 #define WHITE   0xFFFF
+
+//RGB LED
+#define LEDblau 44 // Farbe blau an Pin 3
+#define LEDrot 45 // Farbe rot an Pin 5
+#define LEDgruen 46 // Farbe gruen an Pin 6
+#define delayRGB 1000 // p ist eine Pause mit 1000ms also 1 Sekunde
+#define brightness1a 150 // Zahlenwert zwischen 0 und 255 – gibt die Leuchtstärke der einzelnen Farbe an
+#define brightness1b 150 // Zahlenwert zwischen 0 und 255 – gibt die Leuchtstärke der einzelnen Farbe an
+#define brightness1c 150 // Zahlenwert zwischen 0 und 255 – gibt die Leuchtstärke der einzelnen Farbe an
+#define dunkel 0 // Zahlenwert 0 bedeutet Spannung 0V – also LED aus.

 //cycle will be increased in the loop(), if cycle == CYCLE_UPDATE_TFT --> update TFT and reset cycle to 0
 //this will avoid updating the TFT each time when a serial data is sent (no need to update the TFT that often)
@@ -106,6 +117,11 @@

   pinMode(PIN_LED, OUTPUT);
   digitalWrite(PIN_LED, LOW);
+  attachInterrupt(digitalPinToInterrupt(interruptPin), interruptCall, RISING);
+
+  pinMode(LEDblau, OUTPUT);
+  pinMode(LEDgruen, OUTPUT);
+  pinMode(LEDrot, OUTPUT);
 }

 void showError(void)
@@ -257,6 +273,52 @@
   }
 }

+void printIPInfoOnTFT(void)
+{
+  tft.fillScreen(BLACK);
+  tft.setCursor(0, 0);
+  tft.setTextSize(1);
+  tft.println(" ");
+  tft.setTextSize(2);
+  tft.setTextColor(WHITE);
+  tft.println("IP:");
+  tft.println("127.0.0.1");
+  tft.println("Signal Staerke:");
+  tft.println("-71 dBm");
+}
+
+void ledTest(void)
+{
+  unsigned long currentTime = millis();
+
+  analogWrite(LEDblau, brightness1a); // blau einschalten
+
+  while(millis() - currentTime > delayRGB);
+  currentTime = millis();
+
+  analogWrite(LEDblau, dunkel); // blau ausschalten
+
+  return;
+  analogWrite(LEDrot, brightness1b); // rot einschalten
+
+  while(millis() - currentTime > delayRGB);
+  currentTime = millis();
+
+  analogWrite(LEDrot, dunkel); // rotausschalten
+  analogWrite(LEDgruen, brightness1c); // gruen einschalten
+
+  while(millis() - currentTime > delayRGB);
+  currentTime = millis();
+
+  analogWrite(LEDgruen, dunkel); // gruenausschalten
+}
+
+void interruptCall(void)
+{
+  printIPInfoOnTFT();
+  //ledTest();
+}
+
 void loop(void)
 {
   processData();


Better results on analog mode switches

Better results on analog mode switches

--- stairs/main.ino
+++ stairs/main.ino
@@ -137,15 +137,15 @@
 uint8_t switchPosition(uint8_t pin) {
     uint16_t analog = analogRead(pin);
     // readings are 91, 128, 176, 235, 509, 605, 767, 695, 930, 958
-    if (analog < 127)   return 0;
-    if (analog < 175)   return 1;
-    if (analog < 234)   return 2;
-    if (analog < 508)   return 3;
-    if (analog < 604)   return 4;
-    if (analog < 694)   return 5;
-    if (analog < 764)   return 7;
-    if (analog < 929)   return 6;
-    if (analog < 955)   return 8;
+    if (analog < 120)   return 0;
+    if (analog < 170)   return 1;
+    if (analog < 230)   return 2;
+    if (analog < 500)   return 3;
+    if (analog < 600)   return 4;
+    if (analog < 690)   return 5;
+    if (analog < 760)   return 7;
+    if (analog < 920)   return 6;
+    if (analog < 950)   return 8;
     return 9;
 }


Removed Serial outputs.

Removed Serial outputs.

--- MorseCodeInterpreter/MorseCodeInterpreter.ino
+++ MorseCodeInterpreter/MorseCodeInterpreter.ino
@@ -75,13 +75,14 @@

 // Init lcd.
 void lcdInit() {
+
     lcd.init(); //initialize the lcd
     lcd.backlight(); //open the backlight
 }

 // Write method for lcd display.
 void lcdWrite(char *message, int row, int column, int delayTime) {
-     Serial.print(column);
+
     lcd.setCursor(column, row);
     lcd.print(message);
     delay(delayTime);
@@ -110,7 +111,7 @@
 }

 void setup() {
-    Serial.begin(9600);
+
     calibrateSensor();
     treeCopy = &tree;
     pinMode(BUTTON_PIN, INPUT);


moved up function to be defined when first used

--- examples/WeatherStationDemo/WeatherStationDemo.ino
+++ examples/WeatherStationDemo/WeatherStationDemo.ino
@@ -91,6 +91,15 @@

 Ticker ticker;

+
+void drawProgress(OLEDDisplay *display, int percentage, String label) {
+  display->clear();
+  display->setTextAlignment(TEXT_ALIGN_CENTER);
+  display->setFont(ArialMT_Plain_10);
+  display->drawString(64, 10, label);
+  display->drawProgressBar(2, 28, 124, 10, percentage);
+  display->display();
+}

 void updateData(OLEDDisplay *display) {
   drawProgress(display, 10, "Updating time...");
@@ -107,14 +116,6 @@
   delay(1000);
 }

-void drawProgress(OLEDDisplay *display, int percentage, String label) {
-  display->clear();
-  display->setTextAlignment(TEXT_ALIGN_CENTER);
-  display->setFont(ArialMT_Plain_10);
-  display->drawString(64, 10, label);
-  display->drawProgressBar(2, 28, 124, 10, percentage);
-  display->display();
-}

 void drawDateTime(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) {


Removed StringToIntRGB example

Removed StringToIntRGB example

like discussed in #3537

--- build/shared/examples/08.Strings/StringToIntRGB/StringToIntRGB.ino
+++ build/shared/examples/08.Strings/StringToIntRGB/StringToIntRGB.ino
@@ -1,235 +0,0 @@
-/*
-  Serial RGB controller
-
- Reads a serial input string looking for three comma-separated
- integers with a newline at the end. Values should be between
- 0 and 255. The sketch uses those values to set the color
- of an RGB LED attached to pins 9 - 11.
-
- The circuit:
- * Common-anode RGB LED cathodes attached to pins 9 - 11
- * LED anode connected to pin 13
-
- To turn on any given channel, set the pin LOW.
- To turn off, set the pin HIGH. The higher the analogWrite level,
- the lower the brightness.
-
- created 29 Nov 2010
- by Tom Igoe
-
- This example code is in the public domain.
- */
-
-String inString = "";    // string to hold input
-int currentColor = 0;
-int red, green, blue = 0;
-
-void setup() {
-  // Open serial communications and wait for port to open:
-  Serial.begin(9600);
-  while (!Serial) {
-    ; // wait for serial port to connect. Needed for Leonardo only
-  }
-
-  // send an intro:
-  Serial.println("\n\nString toInt() RGB:");
-  Serial.println();
-  // set LED cathode pins as outputs:
-  pinMode(9, OUTPUT);
-  pinMode(10, OUTPUT);
-  pinMode(11, OUTPUT);
-  // turn on pin 13 to power the LEDs:
-  pinMode(13, OUTPUT);
-  digitalWrite(13, HIGH);
-}
-
-void loop() {
-  int inChar;
-
-  // Read serial input:
-  if (Serial.available() > 0) {
-    inChar = Serial.read();
-  }
-
-  if (isDigit(inChar)) {
-    // convert the incoming byte to a char
-    // and add it to the string:
-    inString += (char)inChar;
-  }
-
-  // if you get a comma, convert to a number,
-  // set the appropriate color, and increment
-  // the color counter:
-  if (inChar == ',') {
-    // do something different for each value of currentColor:
-    switch (currentColor) {
-      case 0:    // 0 = red
-        red = inString.toInt();
-        // clear the string for new input:
-        inString = "";
-        break;
-      case 1:    // 1 = green:
-        green = inString.toInt();
-        // clear the string for new input:
-        inString = "";
-        break;
-    }
-    currentColor++;
-  }
-  // if you get a newline, you know you've got
-  // the last color, i.e. blue:
-  if (inChar == '\n') {
-    blue = inString.toInt();
-
-    // set the levels of the LED.
-    // subtract value from 255 because a higher
-    // analogWrite level means a dimmer LED, since
-    // you're raising the level on the anode:
-    analogWrite(11,  255 - red);
-    analogWrite(9, 255 - green);
-    analogWrite(10, 255 - blue);
-
-    // print the colors:
-    Serial.print("Red: ");
-    Serial.print(red);
-    Serial.print(", Green: ");
-    Serial.print(green);
-    Serial.print(", Blue: ");
-    Serial.println(blue);
-
-    // clear the string for new input:
-    inString = "";
-    // reset the color counter:
-    currentColor = 0;
-  }
-
-}
-
-
-/*
-Here's a Processing sketch that will draw a color wheel and send a serial
- string with the color you click on:
-
- // Subtractive Color Wheel with Serial
- // Based on a Processing example by Ira Greenberg.
- // Serial output added by Tom Igoe
- //
- // The primaries are red, yellow, and blue. The secondaries are green,
- // purple, and orange. The tertiaries are  yellow-orange, red-orange,
- // red-purple, blue-purple, blue-green, and yellow-green.
- //
- // Create a shade or tint of the subtractive color wheel using
- // SHADE or TINT parameters.
-
- // Updated 29 November 2010.
-
-
-
- import processing.serial.*;
-
- int segs = 12;
- int steps = 6;
- float rotAdjust = TWO_PI / segs / 2;
- float radius;
- float segWidth;
- float interval = TWO_PI / segs;
-
- Serial myPort;
-
- void setup() {
- size(200, 200);
- background(127);
- smooth();
- ellipseMode(RADIUS);
- noStroke();
- // make the diameter 90% of the sketch area
- radius = min(width, height) * 0.45;
- segWidth = radius / steps;
-
- // swap which line is commented out to draw the other version
- // drawTintWheel();
- drawShadeWheel();
- // open the first serial port in your computer's list
- myPort = new Serial(this, Serial.list()[0], 9600);
- }
-
-
- void drawShadeWheel() {
- for (int j = 0; j < steps; j++) {
- color[] cols = {
- color(255-(255/steps)*j, 255-(255/steps)*j, 0),
- color(255-(255/steps)*j, (255/1.5)-((255/1.5)/steps)*j, 0),
- color(255-(255/steps)*j, (255/2)-((255/2)/steps)*j, 0),
- color(255-(255/steps)*j, (255/2.5)-((255/2.5)/steps)*j, 0),
- color(255-(255/steps)*j, 0, 0),
- color(255-(255/steps)*j, 0, (255/2)-((255/2)/steps)*j),
- color(255-(255/steps)*j, 0, 255-(255/steps)*j),
- color((255/2)-((255/2)/steps)*j, 0, 255-(255/steps)*j),
- color(0, 0, 255-(255/steps)*j),
- color(0, 255-(255/steps)*j, (255/2.5)-((255/2.5)/steps)*j),
- color(0, 255-(255/steps)*j, 0),
- color((255/2)-((255/2)/steps)*j, 255-(255/steps)*j, 0)
- };
- for (int i = 0; i < segs; i++) {
- fill(cols[i]);
- arc(width/2, height/2, radius, radius,
- interval*i+rotAdjust, interval*(i+1)+rotAdjust);
- }
- radius -= segWidth;
- }
- }
-
-
- void drawTintWheel() {
- for (int j = 0; j < steps; j++) {
- color[] cols = {
- color((255/steps)*j, (255/steps)*j, 0),
- color((255/steps)*j, ((255/1.5)/steps)*j, 0),
- color((255/steps)*j, ((255/2)/steps)*j, 0),
- color((255/steps)*j, ((255/2.5)/steps)*j, 0),
- color((255/steps)*j, 0, 0),
- color((255/steps)*j, 0, ((255/2)/steps)*j),
- color((255/steps)*j, 0, (255/steps)*j),
- color(((255/2)/steps)*j, 0, (255/steps)*j),
- color(0, 0, (255/steps)*j),
- color(0, (255/steps)*j, ((255/2.5)/steps)*j),
- color(0, (255/steps)*j, 0),
- color(((255/2)/steps)*j, (255/steps)*j, 0)
- };
- for (int i = 0; i < segs; i++) {
- fill(cols[i]);
- arc(width/2, height/2, radius, radius,
- interval*i+rotAdjust, interval*(i+1)+rotAdjust);
- }
- radius -= segWidth;
- }
- }
-
- void draw() {
- // nothing happens here
- }
-
- void mouseReleased() {
- // get the color of the mouse position's pixel:
- color targetColor = get(mouseX, mouseY);
- // get the component values:
- int r = int(red(targetColor));
- int g = int(green(targetColor));
- int b = int(blue(targetColor));
- // make a comma-separated string:
- String colorString = r + "," + g + "," + b + "\n";
- // send it out the serial port:
- myPort.write(colorString );
- }
-
-*/
-
-
-
-
-
-
-
-
-
-


Update twitter example

Update twitter example

--- examples/Widgets/Twitter/Twitter.ino
+++ examples/Widgets/Twitter/Twitter.ino
@@ -16,30 +16,46 @@
  * Simple tweet example
  *
  * App dashboard setup:
- *   Twitter widget
+ *   Twitter widget (connect it to your Twitter account!)
  *
  **************************************************************/
-
+//#define BLYNK_DEBUG
 #define BLYNK_PRINT Serial
 #include <SPI.h>
 #include <Ethernet.h>
 #include <BlynkSimpleEthernet.h>
+#include <SimpleTimer.h>

 // You should get Auth Token in the Blynk App.
 // Go to the Project Settings (nut icon).
 char auth[] = "YourAuthToken";

+SimpleTimer timer;
+
 void setup()
 {
   Serial.begin(9600);
   Blynk.begin(auth);
-  if (Blynk.connect()) {
-    Blynk.tweet("Arduino tweeting!");
+  while (!Blynk.connect()) {
+    // Wait until connected
   }
+
+  // Tweet immediately on startup
+  tweetUptime();
+  // Setup a function to be called every minute
+  timer.setInterval(60000L, tweetUptime);
+}
+
+void tweetUptime()
+{
+  long uptime = millis() / 1000;
+  BLYNK_LOG("Tweet ;)");
+  Blynk.tweet(String("Running for ") + uptime + " seconds.");
 }

 void loop()
 {
   Blynk.run();
+  timer.run();
 }


Update TrebleBoost.ino

Update TrebleBoost.ino

Changing input from on board mic to mic jack

--- examples/01-Basic/TrebleBoost/TrebleBoost.ino
+++ examples/01-Basic/TrebleBoost/TrebleBoost.ino
@@ -55,8 +55,8 @@
   audioHardware.enable(); // activate AIC

   //Choose the desired input
-  audioHardware.inputSelect(TYMPAN_INPUT_ON_BOARD_MIC); // use the on board microphones
-  // audioHardware.inputSelect(TYMPAN_INPUT_JACK_AS_MIC); // use the microphone jack - defaults to mic bias 2.5V
+  //audioHardware.inputSelect(TYMPAN_INPUT_ON_BOARD_MIC); // use the on board microphones
+  audioHardware.inputSelect(TYMPAN_INPUT_JACK_AS_MIC); // use the microphone jack - defaults to mic bias 2.5V
   // audioHardware.inputSelect(TYMPAN_INPUT_JACK_AS_LINEIN); // use the microphone jack - defaults to mic bias OFF

   //Set the desired volume levels


Delete Test5.ino

Delete Test5.ino

--- Test5.ino
+++ Test5.ino
@@ -1,80 +0,0 @@
-/* 内蔵の文字を表示する
- *
- * memo:9/30 00:00
- * memo:10/7 18:30
- * memo:2016/07/26 07:30
- */
-
-#include <SPI.h>
-#include "libGT20L16J1Y.h"
-#include "SJIS.h"
-
-#define CLK 13
-#define MISO 12
-#define MOSI 11
-#define SS 8
-
-
-CGT20L GT20L;
-
-void setup (void){
-
-  GT20L.init(CLK, MOSI, MISO, 8);
-
-  Serial.begin(115200);
-  Serial.println("input word which you want to show");
-  Serial.print("port:");
-  Serial.print(SS);
-  Serial.println("has set as chip select pin");
-
-  setData();
-}
-
-
-void loop (void){
-
-  uint8_t *sendData = nekomata;
-
-  GT20L.setStrings(nekomata);
-
-  for(int i=0; sendData[i]!=NULL ; i++){
-    if ( (sendData[i] < 0x80) || ((0xA0 < sendData[i]) && (sendData[i] <= 0xdF)) ) {
-      uint8_t tmp[16];
-      GT20L.getSJIS1byte(sendData[i], tmp);
-      GT20L.copyMatrix16(tmp, sizeof(tmp));
-      GT20L.showDotsToSerial16();
-    } else {
-      uint16_t data =  ((sendData[i] << 8) + sendData[++i]);
-      uint8_t tmp[32];
-      GT20L.getSJIS2byte(data, tmp);
-      GT20L.copyMatrix32(tmp, sizeof(tmp));
-      GT20L.showDotsToSerial32();
-    }
-  }
-
-  Serial.println("これですね");
-  uint8_t tmp[32];
-  GT20L.getMatrixData(tmp, 2);
-
-
-
-  delay(1000);
-
-  if (Serial.available() > 0){
-    /*Arduinoのシリアルモニタから送られてくる日本語がSJISであることに注意*/
-    delayMicroseconds(200);//最低でも2文字受信したい
-    uint8_t msbdata = Serial.read();//1バイト目 //10/07
-    /*SJISの1バイトコードか否か*/
-    if ( (msbdata < 0x80) || ((0xA0 < msbdata) && (msbdata <= 0xdF)) ) {
-      uint8_t tmp[16];
-      GT20L.getSJIS1byte(msbdata, tmp);
-    } else {
-      uint8_t lsbdata = Serial.read();//2バイト目 //10/07
-      uint16_t data =  ((msbdata << 8) + lsbdata); //2
-      uint8_t tmp[32];
-      GT20L.getSJIS2byte(data, tmp);
-    }
-  }
-}
-
-


Actual, working alarms to some extent

Actual, working alarms to some extent

--- alarm.ino
+++ alarm.ino
@@ -63,8 +63,19 @@
     return NULL;
 }

+static inline action_t * get_action(uint8_t actionno) {
+    linked_list_t * iterator = actions;
+    while (iterator != NULL) {
+        if (GET_MEMBER(iterator, action_t, actionno) == actionno)
+            return GET_ITEM(iterator, action_t);
+        NEXT(iterator);
+    }
+    return NULL;
+}
+
 static inline void prepare_action(alarm_t * alarm, actionspec_t * actionspec, bool invert) {
     time_t action_timestamp = alarm->timestamp + actionspec->offset;
+
     if (invert)
         action_timestamp += actionspec->timeout;

@@ -78,15 +89,14 @@
     action_time->alarmno = alarm->alarmno;
     action_time->timestamp = action_timestamp;
     action_time->actions = actionspec->actions;
-
-    if (invert)
-        action_time->actions.flags.inverted = true;
+    action_time->actions.flags.inverted = invert;

     if (insert_pos == NULL)
         PUSH_FRONT(action_times, action_time);
     else
         PUSH_BEHIND(insert_pos, action_time);
-    if (!actionspec->actions.flags.inverted)
+
+    if (!invert)
         prepare_action(alarm, actionspec, true);
 }

@@ -115,32 +125,48 @@

     alarm_t * alarm = get_alarm(alarm_req->alarmno);

+    // If alarm doesn't exist, create a default action set.
     if (alarm == NULL) {
         alarm = new_alarm(alarm_req->alarmno, alarm_req->timestamp);
         alarm->name = strdup("Default");
-        push_front(alarms, (void *) alarm);
-        action_t * action;
-        if (actions != NULL)
-            action = GET_ITEM(actions, action_t);
-        else {
-            actionspec_t * actionspec = new_actionspec();
-            // TODO This is a temp. default action
-            actionspec->actions.flags.blink_backlight = true;
-            actionspec->actions.flags.snoozable = true;
-            actionspec->timeout = 0x7FFF;
+        PUSH_FRONT(alarms, (void *) alarm);
+
+        action_t * action = get_action(0);
+        if (action == NULL) {
+            actionspec_t * annoy_action = new_actionspec();
+            annoy_action->actions.flags.blink_backlight = true;
+            annoy_action->actions.flags.make_noise = true;
+            annoy_action->actions.flags.snoozable = true;
+            annoy_action->timeout = 0x7FFF;
+            actionspec_t * coffee_action = new_actionspec();
+            coffee_action->actions.flags.enable_relay_4 = true;
+            coffee_action->offset = -60;
+            coffee_action->timeout = 300;
+            actionspec_t * light_action = new_actionspec();
+            light_action->actions.flags.enable_relay_3 = true;
+            light_action->offset = -120;
+            light_action->timeout = 3600;

             action = new_action();
-            PUSH_FRONT(action->actionspecs, (void *) actionspec);
+            PUSH_FRONT(action->actionspecs, (void *) annoy_action);
+            PUSH_FRONT(action->actionspecs, (void *) coffee_action);
+            PUSH_FRONT(action->actionspecs, (void *) light_action);
             PUSH_FRONT(actions, (void *) action);
-            PUSH_FRONT(alarm->actionnos, COPY_ITEM(uint8_t, &action->actionno));
         }
         PUSH_FRONT(alarm->actionnos, COPY_ITEM(uint8_t, &action->actionno));
     }

-    prepare_action(alarm, new_actionspec(), false);
+    // Magical action that tells us the main part of the alarm is running.
+    actionspec_t * main_action = new_actionspec();
+    main_action->actions.flags.snoozable = true;
+    main_action->actions.flags.inverted = true;
+    prepare_action(alarm, main_action, false);
+
+    // Iterate over all actions for the alarm, add them to the queue.
     linked_list_t * iterator = alarm->actionnos;
     while (iterator != NULL) {
         uint8_t actionno = *GET_ITEM(iterator, uint8_t);
+
         linked_list_t * action_iterator = actions;
         while (action_iterator != NULL) {
             if (actionno == GET_MEMBER(action_iterator, action_t, actionno)) {
@@ -181,12 +207,15 @@
             alarm_set_timestamp(&next_run);
         }
         // TODO Remember to keep meta of where we are – are any actions
-        // running, are we snoozed, etc.
-        menu_title("Alarm ringing:");
-        if (alarm != NULL && alarm->name != NULL)
-            menu_content(alarm->name);
-        else
-            menu_content("Unnamed");
+        // running, are we snoozed, etc. ... and also make the menu reflect the
+        // state, showing alarm name etc.
+        menu_title("Alarm ringing!");
+        if (alarm != NULL && alarm->name != NULL) {
+            char content[16];
+            sprintf(content, "\n\n\n%s", alarm->name);
+            menu_content(content);
+        } else
+            menu_content("\n\n\nUnnamed");
     } else
         perform_action(&action_time->actions);


Clean up comments

Clean up comments

--- Sensors/iot-demo-sensors/iot-demo-sensors.ino
+++ Sensors/iot-demo-sensors/iot-demo-sensors.ino
@@ -1,21 +1,15 @@
-#define DEBOUNCE 10  // button debouncer, how many ms to debounce, 5+ ms is usually plenty
+#define DEBOUNCE 10  // button debouncer 5+ ms

-// here is where we define the buttons that we'll use. button "1" is the first, button "6" is the 6th, etc
-byte buttons[] = {3, 4, 5}; // 12
+byte buttons[] = {3, 4, 5}; // D2-D12
 String buttonNames[] = {"pb1", "pb2", "pb3"};
-
-// This handy macro lets us determine how big the array up above is, by checking the size
 #define NUMBUTTONS sizeof(buttons)

 byte potmeters[] = {18}; // A0-14, A5-19 6

 String potmeterNames[] = {"pot1"};
-// This handy macro lets us determine how big the array up above is, by checking the size
 #define NUMPOTMETERS sizeof(potmeters)

-
-
-// we will track if a button is just pressed, just released, or 'currently pressed'
+// pressed buttons
 byte pressed[NUMBUTTONS];

 void setup() {
@@ -26,7 +20,7 @@
   // pin13 LED
   pinMode(13, OUTPUT);

-  // Make input & enable pull-up resistors on switch pins
+  // Make input & enable pull-up resistors on button pins
   for (i=0; i< NUMBUTTONS; i++) {
     pinMode(buttons[i], INPUT);
     digitalWrite(buttons[i], HIGH);
@@ -40,25 +34,22 @@
   static long lasttime;
   byte index;
   if (millis() < lasttime) {
-     lasttime = millis(); // we wrapped around, lets just try again
+     lasttime = millis();
   }

+  // Wait DEBOUNCE time
   if ((lasttime + DEBOUNCE) > millis()) {
-    return; // not enough time has passed to debounce
+    return;
   }
-  // ok we have waited DEBOUNCE milliseconds, lets reset the timer
+  // reset the timer
   lasttime = millis();

   for (index = 0; index < NUMBUTTONS; index++) {
-    /*justpressed[index] = 0;       // when we start, we clear out the "just" indicators
-    justreleased[index] = 0;*/
-
-    currentstate[index] = digitalRead(buttons[index]);   // read the button
+    currentstate[index] = digitalRead(buttons[index]);
     if (currentstate[index] == previousstate[index]) {
-      pressed[index] = !currentstate[index];  // remember, digital HIGH means NOT pressed
+      pressed[index] = !currentstate[index];
     }
-    //Serial.println(pressed[index], DEC);
-    previousstate[index] = currentstate[index];   // keep a running tally of the buttons
+    previousstate[index] = currentstate[index];
   }
 }

@@ -101,7 +92,7 @@
 }

 void loop() {
-  check_switches();      // when we check the switches we'll get the current state
+  check_switches(); // Get current states of the buttons

   reportInputStates();


Added support for RTC and test code for getting date and time.

--- Sensors/Sensor-Main.ino
+++ Sensors/Sensor-Main.ino
@@ -1,7 +1,12 @@
-
+//Imports
 #include <SD.h>
 #include "Wire.h"
+
+//Definations
+#define DS1307_ADDRESS 0x86;//Need to get updated I2C Address
+byte zero = 0x00; //Needed as a workaround for issue #537 RTC Support
 File testFile;
+

 void setup(){
 	Serial.begin(9600);
@@ -30,4 +35,31 @@
     	Serial.println("error opening test.txt");
   	}

+  	//This is for testing the RTC
+  	Wire.beginTransmission(DS1307_ADDRESS);
+ 	Wire.write(zero); //Workaround
+   	Wire.endTransmission();
+
+	Wire.requestFrom(DS1307_ADDRESS, 7);
+
+	int second = bcdToDec(Wire.read());
+  	int minute = bcdToDec(Wire.read());
+ 	int hour = bcdToDec(Wire.read() & 0b111111); //24 hour time
+ 	int weekDay = bcdToDec(Wire.read()); //0-6 -> sunday - Saturday
+ 	int monthDay = bcdToDec(Wire.read());
+  	int month = bcdToDec(Wire.read());
+  	int year = bcdToDec(Wire.read());
+
+  	//print the date EG   3/1/11 23:59:59
+  	Serial.print(month);
+  	Serial.print("/");
+  	Serial.print(monthDay);
+  	Serial.print("/");
+  	Serial.print(year);
+  	Serial.print(" ");
+  	Serial.print(hour);
+  	Serial.print(":");
+  	Serial.print(minute);
+  	Serial.print(":");
+  	Serial.print(second);
 }


Fixed invalid parameter after refactoring.

--- examples/Wireless/CosaWirelessButton/CosaWirelessButton.ino
+++ examples/Wireless/CosaWirelessButton/CosaWirelessButton.ino
@@ -120,7 +120,7 @@
 {
   // Wait for events from the button
   Event event;
-  Event::queue.await(&event, SLEEP_MODE_PWR_DOWN);
+  Event::queue.await(&event);

   // Wake up the hardware
   Power::all_enable();


Added Integrated Motor Encoder

Added Integrated Motor Encoder

I have added the code that measures the values of the motors encoders in
the arduino side. However, I am having issues with one of the arduinos
not functioning properly.

--- Testing_Arduino101_2/Testing_Arduino101_2.ino
+++ Testing_Arduino101_2/Testing_Arduino101_2.ino
@@ -1,6 +1,8 @@
 #include <EnableInterrupt.h>
 #include <NewPing.h>
 #include <Servo.h>
+#include <Wire.h>
+#include <I2CEncoder.h>

 //--------------ORIENTATION------------------
 /*
@@ -76,13 +78,13 @@

 //------------------PINs---------------------
-#define TRIGGER_PIN1 A5
+#define TRIGGER_PIN1 A2
 #define ECHO_PIN1 2

 //DO NOT USE PIN 1, IT CAUSES CONSTANT ZEROS
 //DO NOT USE PIN 2 as an ECHO, IT WILL ALSO CAUSE CONSTANT ZEROS
 #define TRIGGER_PIN2 4
-#define ECHO_PIN2 A4
+#define ECHO_PIN2 A3

 #define MAX_DISTANCE 200

@@ -107,6 +109,8 @@
 NewPing sonar1(TRIGGER_PIN1, ECHO_PIN1, MAX_DISTANCE);
 NewPing sonar2(TRIGGER_PIN2, ECHO_PIN2, MAX_DISTANCE);
 Servo myservo;
+I2CEncoder encoder_B;
+I2CEncoder encoder_A;

@@ -119,15 +123,6 @@
 int command_status = 1;
 int motor_speed[2];
 int ultrasonic1 = 0, ultrasonic2 = 0;
-
-int irA_value = 0;
-int irB_value = 0;
-
-int irA_counter = 0;
-int irB_counter = 0;
-
-int irA_block = 0;
-int irB_block = 0;

 //-------------------FUNCTIONs----------------
 void stop_motor_ALL(){
@@ -347,44 +342,34 @@
   Serial.print("\n");
 }
 */
-void encoderA(){
-  irA_value = !irA_value;
-  irA_counter++;
-}
-void encoderB(){
-  irB_value = !irB_value;
-  irB_counter++;
-}
 void encoder_reset(){
-  irB_counter = 0;
-  irA_counter = 0;
+  encoder_A.zero();
+  encoder_B.zero();
 }
 void encoder_report(){
-  Serial.print(irA_counter);
+  Serial.print(round(encoder_A.getPosition()));
   Serial.print('-');
-  Serial.print(irB_counter);
+  Serial.print(round(encoder_B.getPosition()));
   Serial.print('&');
-}
-void encoder_calibrate(){
-  while(Serial.available () < 2);//wait for the motor speed info
-    irA_block = Serial.parseInt();//motor A speed
-    irB_block = Serial.parseInt();//motor B speed
 }

 //------------------CODEs---------------------
 void setup() {
+        Wire.begin();
         Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
         //Serial.println("Welcome to the Arduino Command HQ");
         myservo.attach(5);
         myservo.write(servoH_top);

-        pinMode(IRA, INPUT_PULLUP);
-        pinMode(IRB, INPUT_PULLUP);
-
+        //pinMode(IRA, INPUT_PULLUP);
+        //pinMode(IRB, INPUT_PULLUP);
+
+        encoder_A.init(MOTOR_393_SPEED_ROTATIONS,MOTOR_393_TIME_DELTA);
+        encoder_B.init(MOTOR_393_SPEED_ROTATIONS,MOTOR_393_TIME_DELTA);

         enableInterrupt(stop_button, stop_motor_ALL , CHANGE);
-        enableInterrupt(IRA,encoderA,CHANGE);
-        enableInterrupt(IRB,encoderB,CHANGE);
+        //enableInterrupt(IRA,encoderA,CHANGE);
+        //enableInterrupt(IRB,encoderB,CHANGE);

         pinMode(AMOTOR, OUTPUT);
         pinMode(BMOTOR, OUTPUT);
@@ -527,13 +512,6 @@
               }
               break;

-            case 'j':
-              if(command_status == 1){
-                encoder_calibrate();
-                //Serial.print("calibrate");
-              }
-              break;
-
             break;
             default:
               //Serial.print("Hello11");


Calibrating findCylinder

Calibrating findCylinder

--- Tests/Ping_findCylinder/Ping_findCylinder.ino
+++ Tests/Ping_findCylinder/Ping_findCylinder.ino
@@ -6,8 +6,9 @@
 Servo servoLeft;
 Servo servoRight;

-const int pingPin = 8;
-const int stepsInFullTurn = 25;
+const int pingPin = 6;
+const int beepPin = 7;
+const int stepsInFullTurn = 38;
 const int discardCylDist = 65;
 const int horizonDist = 300;
 const bool clockwise = true;
@@ -22,7 +23,7 @@
   // initialize serial communication:
   Serial.begin(9600);

-  tone(4, 2000, 500);
+  tone(beepPin, 2000, 500);
   servoLeft.attach(13);
   servoRight.attach(12);

@@ -31,11 +32,18 @@

 void loop(){
   measure();
+  tone(beepPin, 2000, 500);
   Serial.println(arrayToString(measurements,stepsInFullTurn));
   delay(1000);
   stepsToCylinder = findCylinder();
+  Serial.println("Cylinder at index: "+String(stepsToCylinder));
+  tone(beepPin, 2000, 500);
   for(int i=0; i<stepsToCylinder; i++){
     rotateStep(counterClockwise);
+  }
+  tone(beepPin, 5000, 500);
+  while(measurePingDist()>10){
+    moveForward();
   }
   delay(4000);
 }
@@ -46,6 +54,8 @@
   for(int i=0; i<stepsInFullTurn; i++){
     rotateStep(counterClockwise);
     int m = measurePingDist();
+
+    Serial.println("Measured: "+String(m));
     measurements[i] = m;
     if(m > discardCylDist) // TODO Should be "m > discardCylDist"?
       noCylinder[i] = true;
@@ -87,11 +97,11 @@
 // Rotates one step clockwise or counter-clockwise
 void rotateStep(bool clockwise) {
   if(clockwise){
-    servoLeft.writeMicroseconds(1700);
-    servoRight.writeMicroseconds(1700);
+    servoLeft.writeMicroseconds(1600);
+    servoRight.writeMicroseconds(1600);
   } else {
-    servoLeft.writeMicroseconds(1300);
-    servoRight.writeMicroseconds(1300);
+    servoLeft.writeMicroseconds(1400);
+    servoRight.writeMicroseconds(1400);
   }
   delay(100);
   stopMovement();
@@ -102,6 +112,10 @@
 void stopMovement(){
   servoLeft.writeMicroseconds(1500);
   servoRight.writeMicroseconds(1500);
+}
+void moveForward(){
+  servoLeft.writeMicroseconds(1700);
+  servoRight.writeMicroseconds(1300);
 }

 long microsecondsToCentimeters(long microseconds){
@@ -133,10 +147,11 @@

   while(true){
     int nearestIndex = getIndexMin();
+
+    Serial.println("Nearest index found: "+String(nearestIndex));
     if(nearestIndex == -1){
       return getIndexOfLargestOpenInterval();
     }
-
     int iL = prevIndex(nearestIndex,l);
     int iR = nextIndex(nearestIndex,l);
     int intervalLength = 0;
@@ -150,10 +165,13 @@
       intervalLength++;
     }

+
+    Serial.println("intervalLength: "+String(intervalLength));
+
     if(intervalLength <= 5){
       return iL<iR ? (iL + iR)/2 : ((iL + iR+l)/2)%l;
     } else {
-      for(int i=iL; i<iR; i++){
+      for(int i=iL; i<iR; i=nextIndex(i,l)){
         noCylinder[i] = true;
       }
     }


Divided reading first to avoid overflows

--- VernierAnalogVoltage/VernierAnalogVoltage.ino
+++ VernierAnalogVoltage/VernierAnalogVoltage.ino
@@ -19,8 +19,8 @@
   Serial.println("Time (s)    Voltage Readings from A0 (N)");
 }
 void loop() {
-  Time = (ReadingNumber*TimeBetweenReadings);// in ms
-  Serial.print(Time/1000); //display in seconds, not milliseconds
+  //the print below does the division first to avoid overflows
+  Serial.print(ReadingNumber/1000.0*TimeBetweenReadings);
   Count = analogRead(A0);
   Voltage = Count / 1024 * 5.0;// convert from count to raw voltage
   Serial.print("            ");


check for Arduino Due at compile

check for Arduino Due at compile

--- longhand_firmware_due/longhand_firmware_due.ino
+++ longhand_firmware_due/longhand_firmware_due.ino
@@ -6,10 +6,10 @@
 #include "Arduino.h"

 /*------------------------------------------------------------
-
+
  LONGHAND DRAWING MACHINE firmware V2.2

- last update 01/05/2014
+ last update 02/05/2014
  by Tim Knapen
  http://www.longhand.cc/

@@ -18,9 +18,16 @@
  + Longhand PCB V1
  + 4 Pololu A4988 stepper motor driver carriers

- Compiles with Arduino IDE 1.5.2
+ Compiled and tested with IDE
+ - Arduino 1.5.2
+ - Arduino 1.5.6-r2

  ------------------------------------------------------------*/
+
+// This is meant for Arduino DUE!
+#ifndef _VARIANT_ARDUINO_DUE_X_
+#error Please compile for Arduino Due!
+#endif

 // SERIAL
 //#define BAUD 115200			// serialUSB doesn't need a baud rate !


Added code for alarm sounds and for alarmMasterSwitch.

--- SunriseAlarm.ino
+++ SunriseAlarm.ino
@@ -11,7 +11,8 @@
 #include "AT24Cxx.h"
 #include <ClickEncoder.h>
 #include <Adafruit_NeoPixel.h>
-
+#include <SoftwareSerial.h>
+#include "Adafruit_Soundboard.h"

 // 2013-04-06 TODO:  Add a temperature sensor to the lamp and if it exceeds a particular temperature, then turn it off or down
 // 2013-04-06 TODO:  Add three LEDs inside the enclosure to indicate which mode you are in.  E.g. green for alarm, blue for time, and red for sundown.
@@ -180,13 +181,22 @@
 #define TimeButton 9
 #define TimeLED 10
 #define OffButton A0
-#define AlarmEnabledSwitch 8
+#define alarmMasterSwitch 8
 #define RotaryButton A1
+
+// Sound effects serial TX/RX pins:
+#define SFX_TX 5
+#define SFX_RX 6
+// Sound effects reset pin:
+#define SFX_RST 4
+SoftwareSerial ss = SoftwareSerial(SFX_TX, SFX_RX);
+Adafruit_Soundboard sfx = Adafruit_Soundboard(&ss, NULL, SFX_RST);

 #define NUM_LED 32
 #define LED_PIN 6
 Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LED, LED_PIN, NEO_GRB + NEO_KHZ800);

+bool alarmMasterSwitchEnabled = true;
 bool alarmEnabled = true;
 bool alarmActive = false;

@@ -475,7 +485,7 @@
     current_clock_time.minute += minutes_delta;
     current_clock_time.second += (seconds_delta - minutes_delta*60);
     current_clock_time.fixTime();
-    updateTimeDisplay(current_clock_time,false,false);
+    updateTimeDisplay(current_clock_time,false,alarmMasterSwitchEnabled);
   }
 }

@@ -547,11 +557,12 @@
   //pinMode(LEDpinA,OUTPUT); digitalWrite(LEDpinA,0);
   pinMode(AlarmButton,INPUT_PULLUP);
   pinMode(TimeButton,INPUT_PULLUP);
-  pinMode(AlarmEnabledSwitch, INPUT_PULLUP);
+  pinMode(alarmMasterSwitch, INPUT_PULLUP);
   pinMode(RotaryButton, INPUT_PULLUP);
   pinMode(OffButton,INPUT);
   pinMode(AlarmLED, OUTPUT);
   pinMode(TimeLED, OUTPUT);
+  alarmMasterSwitchEnabled = (digitalRead(alarmMasterSwitch) == HIGH);
   strip.begin();
   strip.show(); // Initialize all pixels to 'off'
   encoder = new ClickEncoder(ENCODER_PIN0, ENCODER_PIN1, -1, 4);
@@ -561,6 +572,16 @@
   //timer.pwm(LEDpinA, 0); //set up pin 9
   while (!eeprom.isPresent()) { delay(1); }
   matrix.begin(0x70);
+  ss.begin(9600);
+  if (!sfx.reset()) {
+    Serial.println("SFX board not found");
+    while(1);
+  }
+  // Reduce volume on SFX board:
+  if (sfx.volDown() > 128) {
+    while (sfx.volDown() > 128) {}
+  }
+  // Play an easter-egg message while displaying my name...
   display_todd();
   readBrightnessFromEEPROM();
   matrix.setBrightness(matrixBrightness); // 0-15
@@ -569,6 +590,7 @@
   updateCurrentTime(true);
   readAlarmTimeFromEEPROM();
   updateStartTime();
+
 //  turnLightOn();
 //  delay(1000);
 //  turnLightOff();
@@ -595,16 +617,18 @@
 unsigned long alarmStartMillis = 0;
 const unsigned lightUpdateInterval = 50;
 unsigned long lastLightUpdate = millis();
+bool sfx_playing = false;
 void updateLight() {
   if (!isTimeNow(lastLightUpdate,lightUpdateInterval)) {
     return;
   }
-  if (digitalRead(AlarmEnabledSwitch) == LOW) return;
+  if (digitalRead(alarmMasterSwitch) == LOW) return;
   ClockTime current = current_clock_time;
   int32_t seconds = secondsBtwDates(current,startTime);
   if ((seconds < 0) || (seconds >= maxTime)) {
     if (alarmActive) {
       turnLightOff();
+      sfx.stop();
       alarmActive = false;
     }
     alarmEnabled = true;
@@ -623,18 +647,21 @@
     linearBrightOfStep(totalDimmerSteps);
     return;
   }
+  if (seconds == thirtyminutes && !sfx_playing) {
+    sfx_playing = sfx.playTrack("WAKE.OGG");
+  }
   logisticBrightOfMilliseconds(static_cast<unsigned long>(millis()-alarmStartMillis));
 }

 void updateTime(ClockTime & t, int16_t delta) {
   t.minute += delta;
-  updateTimeDisplay(t,true,true);
+  updateTimeDisplay(t,true,alarmMasterSwitchEnabled);
 }

 void updateAlarm(int16_t delta) {
   alarmTime += delta;
-  updateTimeDisplay(alarmTime,true,true);
+  updateTimeDisplay(alarmTime,true,alarmMasterSwitchEnabled);
 }

@@ -644,7 +671,7 @@
   ClockTime t(currentTime);
   display_Cloc();
   delay(1000);
-  updateTimeDisplay(t,true,true);
+  updateTimeDisplay(t,true,alarmMasterSwitchEnabled);
   waitForButtonDepress(TimeButton, LOW);
   unsigned long modeActive = millis();
   bool normalExit = true;
@@ -660,7 +687,7 @@
   if (normalExit) {
     waitForButtonDepress(TimeButton, LOW);
   }
-  updateTimeDisplay(t,false,false);
+  updateTimeDisplay(t,false,alarmMasterSwitchEnabled);
   RTC.adjust(
     DateTime( currentTime.year(),
               currentTime.month(),
@@ -683,7 +710,7 @@
   analogWrite(AlarmLED,matrixBrightness*255/16+1);
   display_ALAr();
   delay(1000);
-  updateTimeDisplay(alarmTime,true,true);
+  updateTimeDisplay(alarmTime,true,alarmMasterSwitchEnabled);
   waitForButtonDepress(AlarmButton, LOW);
   unsigned long modeActive = millis();
   bool normalExit = true;
@@ -700,10 +727,10 @@
     waitForButtonDepress(AlarmButton, LOW);
   }
   updateStartTime();
-  //updateTimeDisplay(startTime,true,true);
+  //updateTimeDisplay(startTime,true,alarmMasterSwitchEnabled);
   //delay(2000);
   updateCurrentTime(true);
-  updateTimeDisplay(current_clock_time,false,false);
+  updateTimeDisplay(current_clock_time,false,alarmMasterSwitchEnabled);
   writeAlarmTimeToEEPROM();
   digitalWrite(AlarmLED,LOW);
   alarmEnabled = true;
@@ -798,6 +825,7 @@
       alarmActive = false;
       alarmEnabled = false;
       turnLightOff();
+      sfx.stop();
       waitForButtonDepress(OffButton, HIGH);
     }
     else if (sunSetActive) {
@@ -810,6 +838,18 @@
       setSunSet();
     }
   }
+  if (digitalRead(alarmMasterSwitch) == LOW) {
+    alarmMasterSwitchEnabled = false;
+    if (alarmEnabled && alarmActive) {
+      alarmActive = false;
+      alarmEnabled = false;
+      turnLightOff();
+      sfx.stop();
+    }
+  }
+  else {
+    alarmMasterSwitchEnabled = true;
+  }
   updateBrightness();
   updateLight();
   updateCurrentTime();


stability improvement

stability improvement

--- RCTransmitter-USBGamepad.ino
+++ RCTransmitter-USBGamepad.ino
@@ -49,6 +49,7 @@
 volatile uint16_t counter;
 uint16_t pulse;
 uint16_t last;
+boolean first = true;
 unsigned long timer; // the timer
 uint16_t INTERVAL = 1000; // the repeat interval

@@ -56,8 +57,14 @@
 uint16_t rcChannels[RC_CHANNELS_COUNT];
 uint8_t chan = 0; // current channel

+ISR(TIMER1_CAPT_vect) { //Timer1 ISR capture vector
+  counter = ICR1; //grab Timer1 value
+  triggered = true; //we have interrupt
+}
+
 void setup() {
-  pinMode(PPM_CAPTURE_PIN, INPUT_PULLUP);
+  cli(); //disable global interrupts until we are ready to accept them
+  pinMode(PPM_CAPTURE_PIN, INPUT_PULLUP); //set PPM capture pin with pullup enabled

   // Input Capture setup
   // ICNC1: =0 Disable Input Capture Noise Canceler to prevent delay in reading
@@ -72,30 +79,37 @@
   TIFR1 = (1<<ICF1); // clear pending
   TIMSK1 = (1<<ICIE1); // and enable

-	USBGamepad.begin(rcChannels);
+	USBGamepad.begin(rcChannels);  //send empty USB report

 #ifdef DEBUG
   timer = millis(); // start timer
 	Serial.begin(115200);
 #endif
-
+  sei(); //enable global interrupts
 }

 void loop(){
-  if (!triggered)
-    return;
-  pulse = counter - last;
-  last = counter;
-  if(pulse > (NEWFRAME_PULSE_WIDTH * TIMER_COUNT_DIVIDER)) {
-    chan = 0;  // new data frame detected, start again
-    USBGamepad.write(rcChannels);
+  if (!triggered) //wait for interrupt
+    return;
+  pulse = (counter - last) / TIMER_COUNT_DIVIDER; //pulse width
+  last = counter; //store
+  if(pulse > (NEWFRAME_PULSE_WIDTH)) {
+    chan = 0;  // new data frame detected, start again
+    if (first) { //discard first frame data because it may be incomplete
+      first = false;
+      triggered = false;
+      return;
+    } else
+    {
+      USBGamepad.write(rcChannels); //send usb report with channels data
+    }
   }
   else {
-    if(pulse > (MIN_PULSE_WIDTH * TIMER_COUNT_DIVIDER - THRESHOLD)
-      && pulse < (MAX_PULSE_WIDTH * TIMER_COUNT_DIVIDER + THRESHOLD)
-      && chan < RC_CHANNELS_COUNT)
+    if(pulse > (MIN_PULSE_WIDTH - THRESHOLD)
+      && pulse < (MAX_PULSE_WIDTH + THRESHOLD)
+      && chan < RC_CHANNELS_COUNT && !first)
     {
-      rcChannels[chan] = pulse / TIMER_COUNT_DIVIDER; //store detected value
+      rcChannels[chan] = pulse; //store detected value
     }
     chan++; //no value detected within expected range, move to next channel
   }
@@ -118,10 +132,5 @@
   }
   #endif

-  triggered = false;
+  triggered = false; //wait for another interrupt
 }
-
-ISR(TIMER1_CAPT_vect) {
-  counter = ICR1;
-  triggered = true;
-}


readTag now just exports tagMessage on its own

--- firmware/examples/readTag/readtag.ino
+++ firmware/examples/readTag/readtag.ino
@@ -20,25 +20,25 @@
         NfcTag tag = nfc.read();
         if(tag.hasNdefMessage()){
                 NdefMessage tagMessage = tag.getNdefMessage();
+                 // at this point tag.print() will dump a NDefMessage for every record.
                 int i;
                 for (i = 0; i < tagMessage.getRecordCount()   ; i++)  {
                     NdefRecord tagRecord = tagMessage.getRecord(i);
                     int payloadLength = tagRecord.getPayloadLength();
                     byte payload[payloadLength];
                     tagRecord.getPayload(payload);
-                    for (uint8_t i = 0; i < payloadLength; i++) {
-                        char c = payload[i];
-                        if (c <= 0x1f || c > 0x7f) {
-                            Serial.print('.');
-                            } else {
-                            Serial.print(c);
-                        }
-                    }
-                    Serial.println("");
+                    char tagMessage[payloadLength + 1];
+                    memcpy(tagMessage, payload , payloadLength);
+                    tagMessage[payloadLength + 1] =  '\0';
+                    Serial.println(tagMessage);
                 }
         }
     }
     delay(5000);
+    // I have noticed that without the call to Particle Process
+    // I can end up with the code giving me a pusling green; Wifi working but
+    // no communication with the cloud; it will have made one connection
+    // and then it stops listeing to the cloud
     Particle.process();
 }


Fix demo reel build error

Fix demo reel build error

--- firmware/examples/DemoReel100/DemoReel100.ino
+++ firmware/examples/DemoReel100/DemoReel100.ino
@@ -72,6 +72,13 @@
   fill_rainbow( leds, NUM_LEDS, gHue, 7);
 }

+void addGlitter( fract8 chanceOfGlitter)
+{
+  if( random8() < chanceOfGlitter) {
+    leds[ random16(NUM_LEDS) ] += CRGB::White;
+  }
+}
+
 void rainbowWithGlitter()
 {
   // built-in FastLED rainbow, plus some random sparkly glitter
@@ -79,12 +86,6 @@
   addGlitter(80);
 }

-void addGlitter( fract8 chanceOfGlitter)
-{
-  if( random8() < chanceOfGlitter) {
-    leds[ random16(NUM_LEDS) ] += CRGB::White;
-  }
-}

 void confetti()
 {


removed debug info

removed debug info

--- T0/src/AFE-MQTT-listener.ino
+++ T0/src/AFE-MQTT-listener.ino
@@ -19,11 +19,11 @@
   // Serial << endl << "INFO: MQTT message recieved: " << topic << " \\ ";

   if (length >= 1) { // command arrived
-
-    for (uint8_t i = 0; i < length; i++) {
-      Serial << (char)payload[i];
-    }
-
+                     /*
+                         for (uint8_t i = 0; i < length; i++) {
+                           Serial << (char)payload[i];
+                         }
+                     */
     sprintf(_mqttTopic, "%scmd", Relay.getMQTTTopic());
     /*
         Serial << endl


Delete ADS1298_ArduinoDue.ino

Delete ADS1298_ArduinoDue.ino

--- Arduino/ADS1298_ArduinoDue/ADS1298_ArduinoDue.ino
+++ Arduino/ADS1298_ArduinoDue/ADS1298_ArduinoDue.ino
@@ -1,122 +0,0 @@
-// include the libraries:
-
-#include <SPI.h>
-#include "ADS1298.h" //find all definition for ADS1298
-
-//Type
-ADS1298 ADS1298device;
-
-// global variable
-int transmit = 0;
-volatile int interrupt_pin2 = 0;
-int connect;
-byte SampleRate[1];
-byte ModeADS[1];
-byte ADSNum[1];
-byte ChipSelect[1];
-byte TriggerWord[1];
-byte Gain[1];
-
-boolean toggle = 0;
-String ConnectingWord;
-
-void setup() {
-
-  //prova
-  ModeADS[0] = 0x00;
-  ADSNum[0] = 0x00;
-
-  connect=0;  //Disconnect from a user Interface (Java, C++)
-  attachInterrupt(2, SPIInterrupt, FALLING); //Interrupt on ArduinoDue // 2 menas pin 2
-
-  Serial.begin(9600); //USB programming port Init --> for trigger
-  Serial.flush();
-
-  SerialUSB.begin(256000);  // USB Initialization
-  SerialUSB.flush();
-  delay(100);
-
-  pinMode(13, OUTPUT); // LED pin for debug
-  digitalWrite(13, toggle);
-  TriggerWord[0] = 0x00;
-}
-
-
-//interrupt function IR2
-void SPIInterrupt() {
-    interrupt_pin2 = 1;
-}
-
-void loop() {
-
-  //Arduino Connection and ADC initialization
-  while(!connect){
-    if(SerialUSB.available()>6){ // Check if data are available on the serial bus
-      ConnectingWord = SerialUSB.readString(); //Read data
-      if(ConnectingWord.equals("Connect")){ //Check the connecting word
-        connect = 1;
-        SerialUSB.println("Ready"); // Send the ack word //println-->write
-        delay(500);
-
-        while(!SerialUSB.available()>3); // Wait the Sample Rate
-
-        SerialUSB.readBytes(SampleRate,1);  //Read the sample rate;
-        SerialUSB.readBytes(ModeADS,1);  //Read the Mode;
-        SerialUSB.readBytes(ADSNum,1);  //Read the number of ADS;
-        SerialUSB.readBytes(ChipSelect,1);  //Read the Chip Select;
-        SerialUSB.readBytes(Gain,1);  //Read the Chip Select;
-
-        delay(100);
-
-        ADS1298device.initialize(SampleRate[0],ADSNum[0],ChipSelect[0]); //Initialize the ADS
-        delay(100);
-
-        ADS1298device.reINITforMoreADC(SampleRate[0], ModeADS[0]); //Configure the ADS channels
-        delay(100);
-
-        ADS1298device.START(); //Start conversion
-        delay(100);
-
-         if (Serial.available() > 0) //Flush the Trigger buffer
-           Serial.read();
-
-        toggle = !toggle;
-        digitalWrite(13, toggle);
-      }
-    }
-  }
-
-  //ADC Acquisition
-
-  if(interrupt_pin2==1){
-    ADS1298device.RDATA();
-    ADS1298device.writeADSchannelData(TriggerWord[0]);
-    interrupt_pin2 = 0;
-    TriggerWord[0] = 0x00;
-  }
-
-  //Arduino Connection and ADC initialization
-
-  if(connect){
-    if(SerialUSB.available()>9){
-      ConnectingWord = SerialUSB.readStringUntil('\0');
-
-      if(ConnectingWord.equals("Disconnect")){
-        toggle = !toggle;
-        digitalWrite(13, toggle);
-        connect = 0;
-        ADS1298device.STOP();
-        delay(100);
-        SerialUSB.flush();
-      }
-    }
-
-    if(Serial.available()){
-      Serial.readBytes(TriggerWord,1);
-      Serial.println(TriggerWord[0]);
-    }
-  }
-}
-
-
-


Updated comments and pin layout

Updated comments and pin layout

--- examples/DumpInfo/DumpInfo.ino
+++ examples/DumpInfo/DumpInfo.ino
@@ -14,12 +14,12 @@
  * below), load this sketch into Arduino IDE then verify/compile and upload it.
  * To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M).
  * When you present a PICC (that is: a RFID Tag or Card) at reading distance
- * of the MFRC522 Reader/PCD, the output will show the ID, type and any data
- * blocks it can read. Note that you may see some "Timeout in communication"
- * messages when removing the PICC from reading distance to early.
+ * of the MFRC522 Reader/PCD, the serial output will show the ID/UID, type and
+ * any data blocks it can read. Note: you may see "Timeout in communication"
+ * messages when removing the PICC from reading distance too early.
  *
  * If your reader supports it, this sketch/program will read all the PICCs
- * presented (that is: multiple tag reading). So if you stack* two or more
+ * presented (that is: multiple tag reading). So if you stack two or more
  * PICCs on top of each other and present them to the reader, it will first
  * output all details of the first and then the next PICC. Note that this
  * may take some time as all data blocks are dumped, so keep the PICCs at
@@ -27,15 +27,15 @@
  *
  * Typical pin layout used:
  * ------------------------------------------------------------
- *             MFRC522      Arduino   Arduino   Arduino
- *             Reader/PCD   Uno       Mega      Nano v3
- * Signal      Pin          Pin       Pin       Pin
+ *             MFRC522      Arduino       Arduino   Arduino
+ *             Reader/PCD   Uno           Mega      Nano v3
+ * Signal      Pin          Pin           Pin       Pin
  * ------------------------------------------------------------
- * RST/Reset   RST          9         5         D9
- * SPI SS      SDA          10        53        D10
- * SPI MOSI    MOSI         11        51        D11
- * SPI MISO    MISO         12        50        D12
- * SPI SCK     SCK          13        52        D13
+ * RST/Reset   RST          9             5         D9
+ * SPI SS      SDA(SS)      10            53        D10
+ * SPI MOSI    MOSI         11 / ICSP-4   51        D11
+ * SPI MISO    MISO         12 / ICSP-1   50        D12
+ * SPI SCK     SCK          13 / ICSP-3   52        D13
  */

 #include <SPI.h>


fix:rss_disp で日付表示が重なるバグ修正

fix:rss_disp で日付表示が重なるバグ修正

--- examples/rss_disp/rss_disp.ino
+++ examples/rss_disp/rss_disp.ino
@@ -161,6 +161,7 @@
     const char *wd[7] = {"Sun","Mon","Tue","Wed","Thr","Fri","Sat"};
     LedMat.setTextColor("yellow","black");
     LedMat.setTextSize(textSize);
+		LedMat.fillRect(x, y, w, h, 0);
 		LedMat.alignPrintf(x+w/2,y, TA_CENTER, TA_TOP,
 											 "%d/%d(%s)",
 											 tm->tm_mon+1, tm->tm_mday, wd[tm->tm_wday]);
@@ -214,6 +215,13 @@
 	LedMat.setCursor(0,0);
 	LedMat.println("connecting to network");
 	LedMat.display();
+
+	uint8_t mac[6];
+	WiFi.macAddress(mac);
+	Serial.print("mac:");
+	for(int i=0;i<6;i++)
+		Serial.printf("%c%02x",i>0?'-':' ',mac[i]);
+	Serial.println();

 	WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
 	while(WiFi.status() != WL_CONNECTED) {


changed video mode buttons to a more comfortable position


add off timer to switch

add off timer to switch

--- _02-mqtt-sw-temperature/_02-mqtt-sw-temperature.ino
+++ _02-mqtt-sw-temperature/_02-mqtt-sw-temperature.ino
@@ -139,25 +139,20 @@
 } rtc_relaystatus;

 // mqtt
-char* topic       = "esp8266/arduino/s02";
-char* rslttopic   = "esp8266/cmd/light/rlst";
-//
-char* hellotopic  = "HELLO";
-//
-char* radiotopic  = "radio/test";
-char* radiofault  = "radio/test/fault";
-//
-char* willTopic   = "clients/relay";
-char* willMessage = "0";
-//
+char* topic         = "esp8266/arduino/s02";
+char* rslttopic     = "esp8266/cmd/light/rlst";
+char* hellotopic    = "HELLO";
+char* radiotopic    = "radio/test";
+char* radiofault    = "radio/test/fault";
+char* willTopic     = "clients/relay";
+char* willMessage   = "0";
 char* topicAverage  = "esp8266/arduino/s06";
-//
 char* lowpower      = "lowpower";
 // subscribe
 //
-char subtopic[]   = "esp8266/cmd/light";   // light command
-//
-char* substopic[1] = { subtopic } ;
+char subtopic_0[]   = "esp8266/cmd/light";   // light command
+char subtopic_1[]   = "esp8266/cmd/timer1";
+char* substopic[2] = { subtopic_0, subtopic_1 } ;
 //
 unsigned int localPort = 12390;
 const int timeZone = 9;
@@ -194,6 +189,10 @@

 //
 int relayIsReady = HIGH;
+
+// light ogg time
+volatile uint8_t lightoffhour;
+volatile uint8_t lightoffmin;

 // DHT
 //declaration
@@ -275,7 +274,7 @@
       }

       client.loop();
-      for (int i = 0; i < 1; ++i) {
+      for (int i = 0; i < 2; ++i) {
         client.subscribe(substopic[i]);
         client.loop();
       }
@@ -309,32 +308,57 @@
     syslogPayload += receivedpayload;
     sendUdpSyslog(syslogPayload);
   }
-
-  //if ( receivedtopic == "esp8266/cmd/light" ) {
+  parseMqttMsg(receivedpayload, receivedtopic);
+}
+
+void parseMqttMsg(String receivedpayload, String receivedtopic) {
+  char json[] = "{\"Humidity\":43.90,\"Temperature\":22.00,\"DS18B20\":22.00,\"PIRSTATUS\":0,\"FreeHeap\":43552,\"acquireresult\":0}";
+
+  receivedpayload.toCharArray(json, 200);
+  StaticJsonBuffer<200> jsonBuffer;
+  JsonObject& root = jsonBuffer.parseObject(json);
+
+  if (!root.success()) {
+    return;
+  }
+
   if ( receivedtopic == substopic[0] ) {
-
     unsigned long now = millis();
-
-    if ( now < 15000 ) {
-      if ( receivedpayload == "{\"LIGHT\":1}") {
-        relaystatus = HIGH ;
-      }
-      if ( receivedpayload == "{\"LIGHT\":0}") {
-        relaystatus = LOW ;
-      }
-      relayIsReady = LOW;
-    } else if ((now - lastRelayActionmillis) >= BETWEEN_RELAY_ACTIVE ) {
-      if ( receivedpayload == "{\"LIGHT\":1}") {
-        relaystatus = HIGH ;
-      }
-      if ( receivedpayload == "{\"LIGHT\":0}") {
-        relaystatus = LOW ;
+    if (root.containsKey("LIGHT")) {
+      if ( now < 15000 ) {
+        if (root["LIGHT"] == 1) {
+          relaystatus = HIGH ;
+        } else {
+          relaystatus = LOW ;
+        }
+        relayIsReady = LOW;
+      } else if ((now - lastRelayActionmillis) >= BETWEEN_RELAY_ACTIVE ) {
+        if (root["LIGHT"] == 1) {
+          relaystatus = HIGH ;
+        } else {
+          relaystatus = LOW ;
+        }
       }
     }

     if (INFO_PRINT) {
       syslogPayload = " => relaystatus => ";
       syslogPayload += relaystatus;
+      sendUdpSyslog(syslogPayload);
+    }
+  }
+
+  if ( receivedtopic == substopic[1] ) {
+    if (root.containsKey("lightoffhour") && root.containsKey("lightoffmin")) {
+      lightoffhour = root["lightoffhour"];
+      lightoffmin  = root["lightoffmin"];
+    }
+
+    if (INFO_PRINT) {
+      syslogPayload = " => lightoffhour => ";
+      syslogPayload += lightoffhour;
+      syslogPayload += " => lightoffmin => ";
+      syslogPayload += lightoffmin;
       sendUdpSyslog(syslogPayload);
     }
   }
@@ -370,6 +394,9 @@

   time_ackpayload.timestamp = 0;
   time_reqpayload.timestamp = 0;
+
+  lightoffhour = 6;
+  lightoffmin  = 0;

   getResetInfo = "hello from switch ";
   getResetInfo += ESP.getResetInfo().substring(0, 50);
@@ -480,7 +507,7 @@
 time_t prevDisplay = 0;

 void loop() {
-  uint32_t alarmtime = numberOfSecondsSinceEpoch(year(), month(), day(), 6, 0, 0);
+  uint32_t alarmtime = numberOfSecondsSinceEpoch(year(), month(), day(), lightoffhour, lightoffmin, 0);
   timestamp = now();

   if (WiFi.status() == WL_CONNECTED) {


20190507 Fix Bug...

20190507 Fix Bug...

--- slides/20190507-Arduino/example/Main/Main.ino
+++ slides/20190507-Arduino/example/Main/Main.ino
@@ -24,6 +24,9 @@
   Serial.begin(9600);
   BTSerial.begin(38400);
   // Servo motor
+  pinMode(2, OUTPUT);digitalWrite(2, HIGH); // Reduce the difficulty of welding
+  pinMode(7, OUTPUT);digitalWrite(7, LOW); // Reduce the difficulty of welding
+  pinMode(8, OUTPUT);digitalWrite(8, HIGH); // Reduce the difficulty of welding
   Servo_1.attach(Servo_1_Data,500,2400);
   Servo_2.attach(Servo_2_Data,500,2400);
   Servo_1.write(90);


Update fingerprint.ino

Update fingerprint.ino

--- firmware/examples/fingerprint/fingerprint.ino
+++ firmware/examples/fingerprint/fingerprint.ino
@@ -17,7 +17,7 @@
  ****************************************************/

-#include "Adafruit_Fingerprint.h"
+#include "Adafruit_Fingerprint/Adafruit_Fingerprint.h"

 #if defined (SPARK)
 //


--- esp8266_160220_BYOP.ino
+++ esp8266_160220_BYOP.ino
@@ -6,6 +6,7 @@

 /*
+ *  - add [kAuthorizationCode], which is used to protect to clear all the messages
  * v0.23 2016 Feb. 27
  *  - add [CMD_ALL_CLEAR] in Serial command
  *  - update proc_get() > add 3rd parameter [isSecret(0|1)] (ref. protocol v0.7)
@@ -101,6 +102,9 @@
 //-------------------------------------------------------------------------
 // static declarations and enums

+// serail number of the 1st commit of esp8266_160220_BYOP
+static const String kAuthorizationCode = "7975f53";
+
 //-------------------------------------------------------------------------
 // extern declarations
 extern Pizero_owner_t g_owner;
@@ -251,6 +255,16 @@
 bool proc_clear(String csvline)
 {
   debug_outputDebugString("proc_clear", "Line251 > start");
+
+  String athcd = extractCsvRow(csvline, 1);
+  if (athcd != kAuthorizationCode) {
+    return false; // error
+  }
+
+  debug_outputDebugString("proc_clear", "Line263 > cleared");
+
+  // TODO: 0m > clear_allMessages()
+  return true;
 }


Pwm run stop (#59)

Pwm run stop (#59)

* Use pwm for fob stop values
* Set fob_threshold using ros param.

--- Arduino/victoria_teensy_ros_node/victoria_teensy_ros_node.ino
+++ Arduino/victoria_teensy_ros_node/victoria_teensy_ros_node.ino
@@ -84,6 +84,9 @@
 // indicates which fob to check.
 byte fob_mode(0);

+// PWM threshold that a "fob" will be considered activated.
+unsigned int fob_threshold(2000);
+
 // Victoria configuration
 double ticks_per_radian;
 double track_radius;  // in meters
@@ -237,6 +240,9 @@
   motor_controller_acceleration =
     ros_param_helper.getParam("motor_controller_acceleration", 10);

+  fob_threshold =
+    ros_param_helper.getParam("fob_threshold", 2000);
+
   ticks_per_radian =
     ros_param_helper.getParam("victoria_ticks_per_radian", 9072);

@@ -345,16 +351,16 @@

   switch(fob_stop_to_check) {
     case 1:
-      return (digitalRead(FOB_STOP_1_PIN) == LOW);
+      return (pulseIn(FOB_STOP_1_PIN, HIGH) < fob_threshold);

     case 2:
-      return (digitalRead(FOB_STOP_2_PIN) == LOW);
+      return (pulseIn(FOB_STOP_2_PIN, HIGH) < fob_threshold);

     case 3:
-      return (digitalRead(FOB_STOP_3_PIN) == LOW);
+      return (pulseIn(FOB_STOP_3_PIN, HIGH) < fob_threshold);

     case 4:
-      return (digitalRead(FOB_STOP_4_PIN) == LOW);
+      return (pulseIn(FOB_STOP_4_PIN, HIGH) < fob_threshold);

     default:
       return false;


remove arduino includes for application.h

--- examples/StandardFirmata/StandardFirmata.ino
+++ examples/StandardFirmata/StandardFirmata.ino
@@ -29,8 +29,7 @@
  * TODO: use Program Control to load stored profiles from EEPROM
  */

-#include <Servo.h>
-#include <Wire.h>
+#include "application.h"
 #include <Firmata.h>

 // move the following defines to Firmata.h?


Rename functions to match library

Rename functions to match library

--- examples/arduino_mcp2515/arduino_mcp2515.ino
+++ examples/arduino_mcp2515/arduino_mcp2515.ino
@@ -1,9 +1,9 @@
 #include <SPI.h>
 #include <mcp2515.h>

-static can_message_t can_message;
+static CanMessage can_message;

-void spi_transfer_mcp2515(uint8_t *buf, uint8_t len) {
+void mcp2515_spiTransfer(uint8_t *buf, uint8_t len) {
   // TODO: Select the MCP2515 if SPI.transfer(buf,len) doesn't
   SPI.transfer(buf, len);
   // TODO: Deselect the MCP2515 if SPI.transfer(buf,len) doesn't
@@ -26,10 +26,10 @@

   delay(50); // Allow the MCP2515 time to start. May not be necessary.

-  config_interrupts(0x03); // Inturrupt when a message is received
-  config_timing(CNF1_10MHZ_125KBIT, CNF2_10MHZ_125KBIT, CNF3_10MHZ_125KBIT);
-  config_receive_ctrl(0x60, 0x60); // Ignore filters, receive all messages
-  set_mode(MODE_LOOPBACK); // Loopback sends messages to itself for testing
+  mcp2515_setCANINTE(0x03); // Inturrupt when a message is received
+  mcp2515_setCNFn(CNF1_10MHZ_125KBIT, CNF2_10MHZ_125KBIT, CNF3_10MHZ_125KBIT);
+  mcp2515_setRXBnCTRL(0x60, 0x60); // Ignore filters, receive all messages
+  mcp2515_setMode(MODE_LOOPBACK); // Loopback sends messages to itself for testing
 }

 void loop() {


Incremental dependency reactions between boom and main arm works but is slow. Probably from nesting too many functions -- it's a recursive algorithm. Will try simply writing servo positions for the reactive positions instead of using the go_to() or go_towards() functions (servo.write()).

--- Project/demo_just_get_it_working/demo_just_get_it_working.ino
+++ Project/demo_just_get_it_working/demo_just_get_it_working.ino
@@ -154,15 +154,18 @@
   int min_delay_time = 10, max_delay_time = 100, delay_time = max_delay_time;

   int previous_angle;
+  bool continue_flag;
   do {
     previous_angle = angles[servo_number];

     delay(delay_time);

+    continue_flag = go_towards(servo_number, angle);
+
     if ( abs(angle - angles[servo_number]) > 15 && delay_time > min_delay_time )
       delay_time -= min_delay_time;
     else if ( abs(angle - angles[servo_number]) <= 15 && delay_time < max_delay_time)
       delay_time += min_delay_time;
-  } while ( go_towards(servo_number, angle) );
+  } while ( previous_angle - angles[servo_number] != 0 && continue_flag );
 }


wheelwriter control before updating to remove queue

--- beanWheelwriterControl/beanWheelwriterControl.ino
+++ beanWheelwriterControl/beanWheelwriterControl.ino
@@ -70,8 +70,8 @@
 void loop()
 {
       static int charCount = 0;
-      char buffer[200];
-      size_t readLength = 200;
+      char buffer[80];
+      size_t readLength = 80;
       uint8_t length = 0;

       // read as much as is available
@@ -94,7 +94,7 @@
       else if ( length == 1 )
       {
           // print each character
-          for (int i=0; i < length; i++) {
+          for (byte i=0; i < length; i++) {
               if (buffer[i] == '\r' or buffer[i] == '\n') {
                   send_return(charCount);
                   charCount = 0;
@@ -128,7 +128,7 @@
           Bean.sleep(50);
           Bean.setLed(0,0,0);
       }
-      int digital1 = digitalRead(d1);
+      byte digital1 = digitalRead(d1);
       if (digital1 == 0) {
         fastText("this is really fast");
         //send_letter(0b000000001); // 'a'
@@ -513,6 +513,8 @@
     q.enqueue(0b100100001);
     q.enqueue(0b000000110);
     q.enqueue(0b010000000);
+    //Serial.print("queue size: ");
+    //Serial.println(q.count());
     // if odd, send 0:
     if (strlen(s) % 2 == 1 or strlen(s) < 26) {
         q.enqueue(0b000000000);
@@ -547,7 +549,7 @@
     q.enqueue(0b100100001);
     q.enqueue(0b000000101);
     q.enqueue(0b010010000);*/
-    Serial.println("About to send bytes.");
+    //Serial.println("About to send bytes.");
     sendBytes();
     delay(LETTER_DELAY * 2); // a bit more time
 }


Ajout de nouvelles animations LED

Ajout de nouvelles animations LED

--- arduino-app/arduino-app.ino
+++ arduino-app/arduino-app.ino
@@ -234,6 +234,8 @@
     // définitions des paramètres des animations
     int anim1Params[] = {5};
     int anim2Params[] = {300, 75};
+    int anim3Params[] = {300, 75};
+    int anim4Params[] = {150, 0};

     // jouer l'animation
     switch (ledAnimID) {
@@ -243,7 +245,15 @@
         break;

       case 2:
-        playLEDAnimation(3, "blink", RGB_RED, anim2Params);
+        playLEDAnimation(3, "blink", RGB_GREEN, anim2Params);
+        break;
+
+      case 3:
+        playLEDAnimation(3, "blink", RGB_RED, anim3Params);
+        break;
+
+      case 4:
+        playLEDAnimation(1, "blink", RGB_BLUE, anim4Params);
         break;
     }
   }


Fixed bug with re-using the same timer causing other events such as sending stats not to trigger

--- arduino/OpenROV/OpenROV.ino
+++ arduino/OpenROV/OpenROV.ino
@@ -11,6 +11,8 @@
 Device iout("iout", 3, iout.analog, iout.in);
 Device light("light", 5, light.analog, light.out);
 Timer time;
+Timer statustime;
+Timer controltime;

 Servo tilt;
 // IMPORTANT!
@@ -49,6 +51,8 @@
   motors.reset();

   time.reset();
+  statustime.reset();
+  controltime.reset();

 // initialize all the readings to 0:
   for (int thisReading = 0; thisReading < numReadings; thisReading++)
@@ -87,7 +91,7 @@
   }

   //to reduce AMP spikes, smooth large power adjustments out
-  if (time.elapsed (100)) {
+  if (controltime.elapsed (100)) {
     if (p<c_motorp) c_motorp--;
     if (p>c_motorp) c_motorp++;
     if (v<c_motorv) c_motorv--;
@@ -121,7 +125,7 @@
   }

   // send voltage and current
-  if (time.elapsed(1000)) {
+  if (statustime.elapsed(1000)) {
     vout.send(vout.read());
     iout.send(average);
     Serial.print("time:");


fix no further increasing sampling rate after critical value detected

--- ble_heart_rate_template.ino
+++ ble_heart_rate_template.ino
@@ -359,9 +359,11 @@

 void analyseData(int sensorValue) {
 	if(sensorValue > 800 | sensorValue < 0) {
-		Serial.println("Critical value detected, increasing transmission frequency");
-		buffer_limit = 10;
-		sleep_time = 200;
+		if(sleep_time > 200) {
+			Serial.println("Critical value detected, increasing transmission frequency");
+			buffer_limit = 2;
+			sleep_time = 200;
+		}
 	}
 }


v5.2 Bug fix

v5.2 Bug fix

--- GPSLCD.ino
+++ GPSLCD.ino
@@ -603,13 +603,13 @@
     UTCOffset = abs(UTCOffset); // Make offset positive
     if (DST) --UTCOffset; // Compensate for DST
     if (*hour <= UTCOffset) *hour += 24;
-    *hour = *hour - UTCOffset; // Subtract offset
+    *hour -= UTCOffset; // Subtract offset
   }
   else {
     // East of Greenwich, add
     if (DST) ++UTCOffset; // Compensate for DST
     if (*hour <= UTCOffset) *hour += 24;
-    *hour = *hour + UTCOffset; // Add offset
+    *hour += UTCOffset; // Add offset
   }
   // Convert date if convertDate flag is set
   // Portions of the following code (with some modifications) ripped off from Instructables


flashing alarm done

flashing alarm done

--- arduino/alarm/alarm.ino
+++ arduino/alarm/alarm.ino
@@ -2,13 +2,49 @@
 String light_state;

 void serialEvent();
-void dim(unsigned long, boolean);
+boolean dim(unsigned long, boolean);
+void alarm(unsigned long);
+void blink(unsigned long);

-void dim(unsigned long duration, boolean brighten) {
+void alarm(unsigned long duration) {
+  unsigned long startMillis = millis();
+  unsigned long dimDuration = 2ul * duration / 3ul;
+  if (dim(dimDuration, true)) {
+    light_state = "alarm";
+    while (millis() - startMillis < duration) {
+      loop();
+      if (light_state != "alarm") {
+        return;
+      }
+    }
+    blink(500);
+  }
+}
+
+void blink(unsigned long interval) {
+  unsigned int previousMillis;
+  light_state = "blink";
+  while(light_state == "blink") {
+    digitalWrite(gate_pin, LOW);
+    previousMillis = millis();
+    while(millis() - previousMillis < interval) {
+      loop();
+    }
+    if (light_state != "blink") break;
+    digitalWrite(gate_pin, HIGH);
+    previousMillis = millis();
+    while(millis() - previousMillis < interval) {
+      loop();
+    }
+  }
+}
+
+// Returns false if was interrupted, otherwise returns true
+boolean dim(unsigned long duration, boolean brighten) {
   double lnb = log(pow(256.0, 1.0 / (float) duration));
   for (int i = 1; i < 256; i++) {
     if (light_state != "dimming") {
-      return;
+      return false;
     }
     unsigned long interval;
     if (brighten) {
@@ -31,12 +67,16 @@
   } else {
     light_state = "off";
   }
+  return true;
 }

 void serialEvent() {
   String serial_data = Serial.readString();
   Serial.flush();
   if (serial_data == "i") {
+    Serial.println(light_state);
+  } else if (light_state == "alarm" && serial_data == "o") {
+    light_state = "on";
     Serial.println(light_state);
   } else if (light_state != "on" && serial_data == "o") {
     light_state = "dimming";
@@ -48,7 +88,8 @@
     Serial.println(light_state);
   } else if (serial_data == "a" && light_state == "off") {
     light_state = "dimming";
-    dim(1800000, true);
+    //alarm(1800000);
+    alarm(1800000);
   }
 }


Refactored to state machine

Refactored to state machine

--- frontdesk/frontdesk.ino
+++ frontdesk/frontdesk.ino
@@ -6,17 +6,13 @@

 SoftwareSerial RFID(RFID_RX, RFID_TX);
 SoftwareSerial WIFI(WIFI_RX, WIFI_TX);
-
-int coinNotes[] = { 988, 1319 };
-int coinNoteDurations[] = { 125, 400 };
-int numCoinNotes = sizeof(coinNotes) / sizeof(coinNotes[0]);

 int j = 0;
 unsigned long lastLEDchange = 0;
 // nLEDs, dataPin, clockPin
 LPD8806 LED = LPD8806(4, 10, 11);

-int scannedID, prevID = 0;
+int state, scannedID, prevID = 0;
 unsigned char readData[bufferSize];
 volatile bool isValidResponse = false;
 volatile char characterRead[bufferSize];
@@ -36,57 +32,63 @@
 }

 void loop() {
-	// Scan for RFID tags
-	isValidResponse = false;
-
-	while (!isValidResponse) {
+	// Scan
+	if (state == 0) {
 		sendCommand(CMD_GET_SNR, blockID, machineID);
 		delay(waitforSerialResponse);
 		isValidResponse = getResponse(readData);
+
+		// LEDs stay off
 		digitalWrite(ledPin, LOW);
-
-		// if a command is received before a card is
-		// scanned, send an error and clear buffer
-		if (Serial.available() && !isValidResponse) {
-			while (Serial.available()) {
-				Serial.read();
-			}
-			Serial.write(ERROR_CHAR);
-			Serial.write(END_CHAR);
-		}
-
-		//redBeat(1);
-    	//rainbow(1);
-		//colorWipe(LED.Color(127, 0, 0), 0);
-	}
-
-	colorWipe(LED.Color(0, 0, 127), 0);
-	// card detected, get user data
-	digitalWrite(ledPin, HIGH);
-	sendCommand(CMD_READ, blockID, userData);
-	delay(waitforReadResponse);
-	isValidResponse = getResponse(readData);
-	if (isValidResponse) {
-		scannedID = (int)getTime(readData, numUserBytes, userOffset);
-	}
-
-	// send to web app
-	if (scannedID != prevID && scannedID < 100) {
-
-     for (int i = 0; i < numCoinNotes; i++) {
-        tone(speakerPin, coinNotes[i]);
-        delay(coinNoteDurations[i]);
-        noTone(speakerPin);
-     }
-
-		WIFI.listen();
-		scanTest(scannedID);
-		prevID = scannedID;
-	}
-
-	RFID.listen();
-
-
+		redBeat(0);
+
+		// If a tag is detected, go to the next state
+		if (isValidResponse) {
+			state = 1;
+		}
+	}
+	// Read data
+	else if (state == 1) {
+		sendCommand(CMD_READ, blockID, userData);
+		delay(waitforReadResponse);
+		isValidResponse = getResponse(readData);
+
+		// If data is successfully read, alert web app
+		if (isValidResponse) {
+			scannedID = (int)getTime(readData, numUserBytes, userOffset);
+
+			// LEDs on
+			colorWipe(LED.Color(0, 0, 127), 0);
+			digitalWrite(ledPin, HIGH);
+			playCoinSound();
+
+			WIFI.listen();
+			if (id != 6 && id != 12 && id != 0 && id < 100) {
+				scanTest(scannedID);
+			}
+
+			RFID.listen();
+			state = 2;
+		}
+		// If data read fails, go back to scan state
+		else {
+			state = 0;
+		}
+	}
+	// Other tag operations
+	else if (state == 2) {
+		sendCommand(CMD_GET_SNR, blockID, machineID);
+		delay(waitforSerialResponse);
+		isValidResponse = getResponse(readData);
+
+		// If tag is removed, go back to scan state
+		if (!isValidResponse) {
+			state = 0;
+		}
+	}
+	else {
+		state = 0;
+	}
 }

 void serialEvent() {
@@ -159,6 +161,18 @@
 	Serial.print(stringBuffer);
 }

+void playCoinSound() {
+	int coinNotes[] = { 988, 1319 };
+	int coinNoteDurations[] = { 125, 400 };
+	int numCoinNotes = sizeof(coinNotes) / sizeof(coinNotes[0]);
+
+	for (int i = 0; i < numCoinNotes; i++) {
+        tone(speakerPin, coinNotes[i]);
+        delay(coinNoteDurations[i]);
+        noTone(speakerPin);
+    }
+}
+
 void redBeat(uint8_t wait) {
 	int i = 0;

@@ -169,10 +183,10 @@
 				LED.setPixelColor(i, LED.Color(j, 0, 0));
 			}
 			else {
-				LED.setPixelColor(i, LED.Color(32 - j, 0, 0));
-			}
-		}
-		if (j == 32) {
+				LED.setPixelColor(i, LED.Color(24 - j, 0, 0));
+			}
+		}
+		if (j == 24) {
 			j = 0;
 		}
 		LED.show();


v3.1.3 tidy up & version number broadcast

1) Tidy of code to help me understand it.
2) SRF now transmits VERx.x.x when it starts up - needs to be added to
the list of message types

--- OxFloodNet_Sensor/OxFloodNet_Sensor.ino
+++ OxFloodNet_Sensor/OxFloodNet_Sensor.ino
@@ -14,13 +14,14 @@
  *
  * NOTE: For initial testing, wakeup time set to 5mins and battery interval to 4 cycles
  * (c) Andrew D Lindsay 2014
+ * Contributions from Ben Ward
  */

 #include "LLAPSerial.h"	// include the library
 #include <OneWire.h>
 #include <DallasTemperature.h>

-#define VERSION_STRING "V3.1.2"
+#define VERSION_STRING "V3.1.3"

 // Number of readings before a battery reading is taken
 #define BATTERY_READ_INTERVAL 10
@@ -31,7 +32,7 @@
 #define FIVEMINS 2
 #define TWENTYSEC 3

-// Hardware pin defines
+// Set RFu Hardware pins (not board jumpers)
 // Enable SRF
 #define SRF_RADIO_ENABLE 8
 // Enable the sensor, controlled by FET
@@ -44,7 +45,7 @@
 #define SRF_SLEEP 4
 #define WAKE_INT 2

-// Data wire is plugged into port 5 on the Arduino
+// Temperature sensor data line connects to pin 5 on the Arduino
 #define ONE_WIRE_BUS 5

 // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
@@ -59,14 +60,14 @@
 boolean tempSensorFound = false;
 float latestTemperature = 0.0;
 uint16_t lastUncompDistance = 0;
+int batteryCountDown = BATTERY_READ_INTERVAL;
+int pollingInterval = FIFTEENMINS;

 // Define pins that are not used and are to be made inputs
 uint8_t inPin[] = { 9, 10, 11, 12, 13 };

-int batteryCountDown = BATTERY_READ_INTERVAL;
-int pollingInterval = FIFTEENMINS;
-
 uint8_t enterCommandMode();
+
 // Node ID, default 00, set by input pins
 // Stricly speaking this should only be digits, according to the Ciseco LLAP spec.
 char nodeId[2] = { '0', '0' };
@@ -96,15 +97,23 @@
   digitalWrite(12, HIGH);
   digitalWrite(13, HIGH);

-  // Read input and parse value
+  // Set individual registers
+  // TODO: Explain these
   int digit2 = ((PINB & 0x30) >> 4) | ((PINC & 0x03) << 2);
   digit2 ^= 0x0f;
   int digit1 = (PINC & 0x3c) >> 2;
   digit1 ^= 0x0f;
+
+  // set Node ID from jumper pins
   nodeId[0] = '0' + min(digit1,9);
   nodeId[1] = '0' + min(digit2,9);
+
+  // set polling interval from jumper pins
   pollingInterval = ((PINB & 0x06) >> 1) ^ 0x03;

+
+  // DEBUG to serial port
+  // Print the values of Port B & Port C
   Serial.println("Debug: ");
   Serial.print("Port B: ");
   Serial.println(PINB,HEX);
@@ -118,6 +127,8 @@
   Serial.print(digit1,DEC);
   Serial.print(" ");
   Serial.println(digit2,DEC);
+
+  // TODO: Tidy
   // A0, A1 are first part, R, S, T, W
   // A2 - A5 are 0-9, A-F
 /*
@@ -149,6 +160,7 @@
   digitalWrite(12, LOW);
   digitalWrite(13, LOW);
 }
+

 // **************************************
 // Functions used in processing readings
@@ -197,10 +209,12 @@
   }
 }

-// Get the range in cm. Need to enable sensor first then wait briefly for it to power up
-// Also request temperture sensor, if previously detected, to take a reading.
-// Disable sensor after use.
+// Start of Ultrasonic sensor code
 uint16_t getRange() {
+  // Get the range in cm. Need to enable sensor first then wait briefly for it to power up
+  // Also request temperture sensor, if previously detected, to take a reading.
+  // Disable sensor after use.
+
   int16_t pulse;  // number of pulses from sensor
   int i=0;
   // These values are for calculating a mathematical median for a number of samples as
@@ -244,14 +258,13 @@
   }
   return distance;
 }
-
-// End of Maxbotix sensor code
-// **************************************
-
-// Battery monitoring
+// End of Ultrasonic sensor code
+
+// Start of Battery monitoring
 int readVcc() {
   // Read 1.1V reference against AVcc
   // set the reference to Vcc and the measurement to the internal 1.1V reference
+
   #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
     ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
   #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
@@ -274,10 +287,9 @@
   result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
   return (int)result; // Vcc in millivolts
 }
-
-/*
-
- */
+// End of Battery monitoring
+
+// Start of SRF Sleep Code
 uint8_t setSRFSleep()
 {
   if (!enterCommandMode())	// if failed once then try again
@@ -316,8 +328,9 @@
   if (!sendCommand("ATDN")) return 4;
   return 5; // success
 }
-
-
+// End of SRF Sleep Code
+
+// Start of SRF command functions
 uint8_t enterCommandMode()
 {
   delay(1200);
@@ -350,18 +363,27 @@
   }
   return 0;
 }
-
-
+// End of SRF command functions
+
+// BEGIN
 void setup() {
+
   // initialise serial:
   Serial.begin(115200);
+
   // Get device ID
   readJumpers();
+
   // Initialise the LLAPSerial library
   LLAP.init( nodeId );
+
+  // Initialise countdown for number of sleeps before sending battery reading
+  batteryCountDown = BATTERY_READ_INTERVAL;
+
+
+
+  // Set unused digital pins to input and turn on pull-up resistor
   analogReference(DEFAULT);
-
-  // Set unused digital pins to input and turn on pull-up resistor
   for(int i = 0; i< 5; i++ ) {
     pinMode(inPin[i], INPUT);
     digitalWrite(inPin[i], HIGH);
@@ -373,24 +395,25 @@
   pinMode(SENSOR_PIN, INPUT);

   // Setup the SRF pins
-  pinMode(SRF_RADIO_ENABLE, OUTPUT);    // initialize pin 8 to control the radio
+  pinMode(SRF_RADIO_ENABLE, OUTPUT);    // initialize pin to control the radio
   digitalWrite(SRF_RADIO_ENABLE, HIGH); // select the radio
   pinMode(SRF_SLEEP, OUTPUT);
   digitalWrite( SRF_SLEEP, LOW );

-  sensors.begin();
-  tempSensorFound = false;
+  sensors.begin();                      // start OneWire sensors
+  tempSensorFound = false;              // clear flag for sensor discovery
+
+  // Discover OneWire temperature sensor
   if (sensors.getAddress(temperatureSensor, 0)) {
-    // set the resolution to 9 bit (Each Dallas/Maxim device is capable of several different resolutions)
+    // If we find a sensor, set the resolution to 9 bit
+    // (Each Dallas/Maxim device is capable of several different resolutions)
     sensors.setResolution(temperatureSensor, 9);
-    tempSensorFound = true;
-  }
-
-  batteryCountDown = BATTERY_READ_INTERVAL;
-  // Wait for it to be initialised
-  delay(200);
-
-  // Send STARTED message if successful or ERROR if not able to set SleepMode 3.
+
+    tempSensorFound = true;             // set discovery flag
+  }
+  delay(200);                           //   Wait for sensor to be initialised
+
+  // Send "STARTED" message if successful or "ERR" if not able to set SleepMode 3.
   // set up sleep mode 3 (low = awake)
   uint8_t val;
   while ((val = setSRFSleep()) != 5)
@@ -399,10 +422,15 @@
     delay(5000);	// try again in 5 seconds
   }

+
   // Repeat "STARTED" message 5 times to alert
   for(int i=0;i<5;i++) {
     LLAP.sendMessage("STARTED");
     delay(1000);
+    // send version
+//    char* temp =  strcat("VER",VERSION_STRING);
+//    LLAP.sendMessage(temp);
+//    delay(1000);
   }

 }


UI change

UI change

--- Master.ino
+++ Master.ino
@@ -390,6 +390,7 @@
   tcs.getRawData(&r, &g, &b, &c);
   if (g > th_Val[2].g_t)
   {
+    Serial.print("Received:\n");
 listenSTR:
     //send start bacon
     digitalWrite(greenLED, HIGH);
@@ -782,14 +783,17 @@
     else
     {
       digitalWrite(greenLED, HIGH);
-
+      Serial.print("Sent:");
       //Serial.print("\n");
       for (int j = 0; j < inputHOLD.length(); ++j)
       {
+        if ((j % 80) == 0)
+          Serial.print("\n");
+
         flashSequence(inputHOLD[j]);
       }
       flashSequence('\n');
-      Serial.print("\n");
+      //   Serial.print("\n");
     }
     digitalWrite(redLED, LOW);
     digitalWrite(greenLED, LOW);
@@ -805,7 +809,7 @@

   Serial.print(sequence); //for testing **********************************************
-  Serial.print(": ");
+  //Serial.print(": ");

   tcs.getRawData(&r, &g, &b, &c);
   while (g < th_Val[2].g_t)
@@ -858,10 +862,10 @@
     flashDotOrDash(redLED, false);
     flashDotOrDash(blueLED, false);
     flashDotOrDash(greenLED, false);
-    Serial.print(" ");
+    // Serial.print(" ");
     delay(trnsDELAY);
   }
-  Serial.println(); //for testing **************************************
+  //Serial.println(); //for testing **************************************

 }

@@ -914,7 +918,7 @@

 void flashDotOrDash(int color, bool dotOrDash)
 {
-  Serial.print(dotOrDash); //for testing ******************************************
+  // Serial.print(dotOrDash); //for testing ******************************************
   if (dotOrDash)
     digitalWrite(color, HIGH);
   else


Update ArduCAM_Mini_5MP_Plus_Multi_Capture2SD.ino

--- ArduCAM/examples/mini/ArduCAM_Mini_5MP_Plus_Multi_Capture2SD/ArduCAM_Mini_5MP_Plus_Multi_Capture2SD.ino
+++ ArduCAM/examples/mini/ArduCAM_Mini_5MP_Plus_Multi_Capture2SD/ArduCAM_Mini_5MP_Plus_Multi_Capture2SD.ino
@@ -53,10 +53,19 @@
 #endif
 Serial.begin(115200);
 Serial.println(F("ArduCAM Start!"));
+
 // set the CS as an output:
 pinMode(CS, OUTPUT);
+digitalWrite(CS, HIGH);
+
 // initialize SPI:
 SPI.begin();
+//Reset the CPLD
+myCAM.write_reg(0x07, 0x80);
+delay(100);
+myCAM.write_reg(0x07, 0x00);
+delay(100);
+
 while(1){
   //Check if the ArduCAM SPI bus is OK
   myCAM.write_reg(ARDUCHIP_TEST1, 0x55);


horloge_cycles_ultradiens

--- files/horloge_cycles_ultradiens/horloge_cycles_ultradiens.ino
+++ files/horloge_cycles_ultradiens/horloge_cycles_ultradiens.ino
@@ -280,7 +280,7 @@

   // Préparation de l’affichage des minutes
   display.setCursor( 86, 0 );
-  sprintf( texteAffichage, "%2d", now.minute() );
+  sprintf( texteAffichage, "%02d", now.minute() );
   display.print( texteAffichage );

   // Préparation de l’affichage des secondes


Add header

Add header

--- firmware/examples/02_Particle_Electon/02_Particle_Electon.ino
+++ firmware/examples/02_Particle_Electon/02_Particle_Electon.ino
@@ -25,6 +25,7 @@
 //#define BLYNK_DEBUG       // Uncomment this to see detailed prints

 // Uncomment this, if you want to set network credentials
+//#include "cellular_hal.h"
 //STARTUP(cellular_credentials_set("broadband", "", "", NULL));

 // Run "ping blynk-cloud.com", and set Blynk IP to the shown address


Fixed broken JSON string in example (#72)

--- examples/Esp32-mqtt/Esp32-mqtt.ino
+++ examples/Esp32-mqtt/Esp32-mqtt.ino
@@ -98,7 +98,7 @@
       Serial.println("Publish message");

       String payload = String("{\"Uptime\":\"") + msg +
-          String("\",\"Sig:\"") + WiFi.RSSI() +
+          String("\",\"Sig\":\"") + WiFi.RSSI() +
           String("\"}");
       if (encodePayload) {
         rbase64.encode(payload);


domain name change

domain name change

--- examples/getandpost/getandpost.ino
+++ examples/getandpost/getandpost.ino
@@ -29,7 +29,7 @@
   Serial.begin(9600);
   while (!Serial); // wait for serial port to connect. Needed for Leonardo only

-  CS.begin(lora, "dzeta.t.eu.org");
+  CS.begin(lora, "sensor.example.com");

    resLum = CS.addRes(String("/lum"), answer_get);
    resMsg = CS.addRes(String("/msg"), answer_msg);


Working version from 3/11/2017 workday

Working version from 3/11/2017 workday

--- Arduino/victoria_teensy_ros_node/victoria_teensy_ros_node.ino
+++ Arduino/victoria_teensy_ros_node/victoria_teensy_ros_node.ino
@@ -23,22 +23,37 @@
 // ROS includes
 #include <ros.h>
 #include <geometry_msgs/Twist.h>
+#include <geometry_msgs/Pose.h>
 #include <nav_msgs/Odometry.h>
 #include <tf/transform_broadcaster.h>
+#include <std_msgs/String.h>

 // Teensy pin definitions
 #define ENCODER_LEFT_PIN_1 29   // Teensy digital pin 29
 #define ENCODER_LEFT_PIN_2 30   // Teensy digital pin 30
 #define ENCODER_RIGHT_PIN_1 31  // Teensy digital pin 31
 #define ENCODER_RIGHT_PIN_2 32  // Teensy digital pin 32
-#define BUMPER_LEFT_PIN 14      // Teensy analog pin 14
-#define BUMPER_RIGHT_PIN 15     // Teensy analog pin 15
+#define BUMPER_LEFT_PIN A15      // Teensy analog pin 15
+#define BUMPER_RIGHT_PIN A14     // Teensy analog pin 14

 // TRex motor controller
 HardwareSerial trex = HardwareSerial();

+#define BLINK_DURATION 2000
+#define BLINK_PIN 13 // Teensy digital pin 13 for LED
+int blink_state;
+unsigned long next_blink_time;
+
+char debug_str[80];
+
+// Victoria constants
+#define TRACK_RADIUS 0.235  // in meters
+#define WHEEL_RADIUS 0.127  // in meters
+#define MAX_SPEED 4.71      // in meters/second
+
 // Bumper sensors
-#define BUMPER_THRESHOLD 500  // Threshold that will indicate robot should stop
+#define BUMPER_THRESHOLD 300  // Threshold that will indicate robot should stop
+bool bumper_stop = false;
 unsigned int bumper_left_base;
 unsigned int bumper_right_base;

@@ -47,13 +62,66 @@
 Encoder encoder_right(ENCODER_RIGHT_PIN_1, ENCODER_RIGHT_PIN_2);
 unsigned long encoder_left_pos;
 unsigned long encoder_right_pos;
+double motor_left_speed;
+double motor_right_speed;
+
+/*
+double ang_v_l[10];
+double ang_v_r[10];
+int velocity_index = 0;
+ros::Time last_encoder_read_time;
+ros::Time next_encoder_read_time;
+ros::Duration next_encoder_read_duration = ros::Duration(3e-3);
+*/

 // IMU and Magnetometer
 LSM6 imu;
 LIS3MDL mag;
+bool imu_err = false;
+bool mag_err = false;

 // ROS node handle
 ros::NodeHandle ros_nh;
+
+ros::Time last_cmd_vel_time;
+std_msgs::String ros_debug_msg;
+ros::Publisher ros_bumper_pub("bumper_info", &ros_debug_msg);
+ros::Publisher ros_encoder_pub("encoder_info", &ros_debug_msg);
+ros::Publisher ros_imu_pub("imu_info", &ros_debug_msg);
+ros::Publisher ros_magnetometer_pub("magnetometer_info", &ros_debug_msg);
+ros::Publisher ros_debug_pub("v_debug_info", &ros_debug_msg);
+
+void cmdVelCallback(const geometry_msgs::Twist& cmd_vel_msg) {
+  snprintf(debug_str, sizeof(debug_str), "linear: %6f %6f %6f    angular: %6f %6f %6f",
+    cmd_vel_msg.linear.x, cmd_vel_msg.linear.y, cmd_vel_msg.linear.z,
+    cmd_vel_msg.angular.x, cmd_vel_msg.angular.y, cmd_vel_msg.angular.z);
+  ros_debug_msg.data = debug_str;
+  ros_debug_pub.publish(&ros_debug_msg);
+
+  last_cmd_vel_time = ros_nh.now();
+
+  if (bumper_stop) {
+    return;
+  }
+
+  // linear wheel velocity
+  double vl = cmd_vel_msg.linear.x - (cmd_vel_msg.angular.z * TRACK_RADIUS);
+  double vr = cmd_vel_msg.linear.x + (cmd_vel_msg.angular.z * TRACK_RADIUS);
+
+  // angular velocity
+  double wl = vl / WHEEL_RADIUS;
+  double wr = vr / WHEEL_RADIUS;
+
+  // Translate values to between -1 and 1
+  motor_left_speed = max(-1, min(1, wl / MAX_SPEED));
+  motor_right_speed = max(-1, min(1, wr / MAX_SPEED));
+
+  snprintf(debug_str, sizeof(debug_str), "l: %6f %6f %6f    r: %6f %6f %6f",
+    vl, wl, motor_left_speed,
+    vr, wr, motor_right_speed);
+  ros_debug_msg.data = debug_str;
+  ros_debug_pub.publish(&ros_debug_msg);
+}

 // ROS cmd_vel subscriber
 // Threshold, in nanoseconds, to wait for a cmd_vel message else take action
@@ -72,33 +140,41 @@

 ros::Time current_time;
 ros::Time last_time;
-ros::Time last_cmd_vel_time;

 char ros_odom_header_frame_id[] = "/odom";
 char ros_odom_child_frame_id[] = "/base_link";
+
+//Pose pose;

 void setup() {
   // Setup basic I2C master mode pins 18/19, external pullups, 400kHz, 200ms default timeout
   Wire.begin(I2C_MASTER, 0x00, I2C_PINS_18_19, I2C_PULLUP_EXT, 400000);
   Wire.setDefaultTimeout(200000); // 200ms
-
-  // Start serial port to TRex
-  trex.begin(19200);
-
+
   // Setup IMU and magenetometer that use I2C
   if (imu.init()) {
     imu.enableDefault();
     // TODO: set timeout?
   } else {
-    // TODO: How to handle error?
+    imu_err = true;
   }

   if (mag.init()) {
     mag.enableDefault();
     // TODO: set timeout?
   } else {
-    // TODO: How to handle error?
-  }
+    mag_err = true;
+  }
+
+  // Start serial port to TRex
+  trex.begin(19200);
+
+  bumper_left_base = 5000; //analogRead(BUMPER_LEFT_PIN);
+  bumper_right_base = 5000; //analogRead(BUMPER_RIGHT_PIN);
+
+  next_blink_time = millis();
+  blink_state = LOW;
+  pinMode(BLINK_PIN, OUTPUT);

   // Initialize ros node
   ros_nh.initNode();
@@ -112,6 +188,11 @@
   ros_odom_msg.header.frame_id = ros_odom_header_frame_id;
   ros_odom_msg.child_frame_id = ros_odom_child_frame_id;
   ros_nh.advertise(ros_odom_pub);
+  ros_nh.advertise(ros_bumper_pub);
+  ros_nh.advertise(ros_encoder_pub);
+  ros_nh.advertise(ros_imu_pub);
+  ros_nh.advertise(ros_magnetometer_pub);
+  ros_nh.advertise(ros_debug_pub);

   // Initialize ros subscribers
   ros_nh.subscribe(ros_cmd_vel_sub);
@@ -119,14 +200,17 @@
   current_time = ros_nh.now();
   last_time = current_time;
   last_cmd_vel_time = current_time;
+  //last_encoder_read_time = current_time;
+  //next_encoder_read_time = current_time + next_encoder_read_duration;
   encoder_left_pos = 0.0;
   encoder_right_pos = 0.0;
-  bumper_left_base = analogRead(BUMPER_LEFT_PIN);
-  bumper_right_base = analogRead(BUMPER_RIGHT_PIN);
+  motor_left_speed = 0.0;
+  motor_right_speed = 0.0;
 }

 void loop() {
-  ros_nh.spinOnce();
+
+
   current_time = ros_nh.now();

   // If we have not received any cmd_vel messages for a while,
@@ -141,68 +225,147 @@
   unsigned int new_bumper_right = analogRead(BUMPER_RIGHT_PIN);

   // Check bumper thresholds to stop robot
-
+  if (new_bumper_left < 450 || new_bumper_right < 450) {
+    bumper_stop = true;
+    motor_left_speed = 0;
+    motor_right_speed = 0;
+  } else {
+    bumper_stop = false;
+  }
+
+  /*
   // Read encoders
+  if (current_time > next_encoder_read_time) {
+    unsigned long new_encoder_l_pos = encoder_left.read();
+    unsigned long new_encoder_r_pos = encoder_right.read();
+
+    // TODO handle overflow/rest to 0
+    unsigned long diff_l = new_encoder_l_pos - encoder_left_pos;
+    unsigned long diff_r = new_encoder_r_pos - encoder_right_pos;
+    double diff_t = current_time - last_encoder_read_time;
+
+    ang_vel_l[velocity_index] = (diff_l/TICKS_PER_RADIAN)/diff_t;
+    ang_vel_r[velocity_index] = (diff_r/TICKS_PER_RADIAN)/diff_t;
+
+    velocity_index = (velocity_index+1)%10;
+    encoder_left_pos = new_encoder_left_pos;
+    encoder_right_pos = new_encoder_right_pos;
+    last_encoder_read_time = current_time;
+    next_encoder_read_time = current_time + next_encoder_read_duration;
+  }
   unsigned long new_encoder_left_pos = encoder_left.read();
   unsigned long new_encoder_right_pos = encoder_right.read();

-  // Read imu data
+
+  double dt = (current_time - last_time).toSec();
+  */
+
+  // Read the bumper sensors
+  snprintf(debug_str, sizeof(debug_str), "L: %d    R: %d",
+    analogRead(BUMPER_LEFT_PIN), analogRead(BUMPER_RIGHT_PIN));
+  ros_debug_msg.data = debug_str;
+  ros_bumper_pub.publish(&ros_debug_msg);
+
+  // Read the encoders
+  snprintf(debug_str, sizeof(debug_str), "L: %ld    R: %ld",
+    encoder_left.read(), encoder_right.read());
+  ros_debug_msg.data = debug_str;
+  ros_encoder_pub.publish(&ros_debug_msg);
+
+  // Read the IMU
+  if (imu_err) {
+    ros_debug_msg.data = "IMU failure!";
+  } else {
+    long i2c_start_time = millis();
+    imu.read();
+    long i2c_duration = millis() - i2c_start_time;
+
+    snprintf(debug_str, sizeof(debug_str), "A: %6d %6d %6d    G: %6d %6d %6d   I2C Duration: %ld",
+      imu.a.x, imu.a.y, imu.a.z,
+      imu.g.x, imu.g.y, imu.g.z,
+      i2c_duration);
+    ros_debug_msg.data = debug_str;
+  }
+  ros_imu_pub.publish(&ros_debug_msg);
+
+  // Read the Magnetometer
+  if (mag_err) {
+    ros_debug_msg.data = "Magnetometer failure!";
+  } else {
+    long i2c_start_time = millis();
+    mag.read();
+    long i2c_duration = millis() - i2c_start_time;
+
+    snprintf(debug_str, sizeof(debug_str), "M: %6d %6d %6d   I2C Duration: %ld",
+      mag.m.x, mag.m.y, mag.m.z,
+      i2c_duration);
+    ros_debug_msg.data = debug_str;
+  }
+  ros_magnetometer_pub.publish(&ros_debug_msg);

   // Broadcast odometry transform
   ros_odom_transform.header.stamp = current_time;

   // TODO: set all the transform data

-  ros_odom_broadcaster.sendTransform(ros_odom_transform);
+  //ros_odom_broadcaster.sendTransform(ros_odom_transform);

   // Publish Odometry
   ros_odom_msg.header.stamp = current_time;

   // TODO: Set all the odometry data

-  ros_odom_pub.publish(&ros_odom_msg);
+  //ros_odom_pub.publish(&ros_odom_msg);

   last_time = current_time;
-}
-
-void cmdVelCallback(const geometry_msgs::Twist& twist_msg) {
-  last_cmd_vel_time = ros_nh.now();
-
-  // Do something interesting with the cmd_vel
-  setMotors(100, 100);
+
+  ros_nh.spinOnce();
+
+  setMotors(motor_left_speed, motor_right_speed);
+
+  // Indicate to outside world that something is going on
+  if (millis() > next_blink_time) {
+    if (blink_state == LOW) {
+      blink_state = HIGH;
+    } else {
+      blink_state = LOW;
+    }
+    digitalWrite(BLINK_PIN, blink_state);
+    next_blink_time = millis() + BLINK_DURATION;
+  }
 }

 /*
  * Sets the speed for the motors. Values are expected
- * to be between -255 and 255. Values outside this range
+ * to be between -1 and 1. Values outside this range
  * will be pinned.
  */
-void setMotors(int motor_left_speed, int motor_right_speed) {
+void setMotors(double motor_left_speed, double motor_right_speed) {
   byte command_byte_left = 0xC4;
   if (motor_left_speed < 0) {
     command_byte_left = command_byte_left | 0x01;
   } else {
     command_byte_left = command_byte_left | 0x02;
   }
-  motor_left_speed = abs(motor_left_speed);
-  if (motor_left_speed > 255) {
-    motor_left_speed = 255;
-  }
+  int trex_left_speed = min(127, 127.0 * abs(motor_left_speed));

   byte command_byte_right = 0xCC;
   if (motor_right_speed < 0) {
+    command_byte_right = command_byte_right | 0x02;
+  } else {
     command_byte_right = command_byte_right | 0x01;
-  } else {
-    command_byte_right = command_byte_right | 0x02;
-  }
-  motor_right_speed = abs(motor_right_speed);
-  if (motor_right_speed > 255) {
-    motor_right_speed = 255;
-  }
+  }
+  int trex_right_speed = min(127, 127.0 * abs(motor_right_speed));
+
+  snprintf(debug_str, sizeof(debug_str), "cmd_l: %6f %6d %6d    cmd_r: %6f %6d %6d",
+    motor_left_speed, command_byte_left, trex_left_speed,
+    motor_right_speed, command_byte_right, trex_right_speed);
+  ros_debug_msg.data = debug_str;
+  ros_debug_pub.publish(&ros_debug_msg);

   trex.write(command_byte_left);
-  trex.write((byte)motor_left_speed);
+  trex.write((byte)trex_left_speed);
   trex.write(command_byte_right);
-  trex.write((byte)motor_right_speed);
+  trex.write((byte)trex_right_speed);
 }


JsonHttpClient: Close socket even when connection fails (issue #445)

--- examples/JsonHttpClient/JsonHttpClient.ino
+++ examples/JsonHttpClient/JsonHttpClient.ino
@@ -41,8 +41,8 @@
         printUserData(&userData);
       }
     }
-    disconnect();
   }
+  disconnect();
   wait();
 }


Add ST7920 to LCD benchmark suite.

Add ST7920 to LCD benchmark suite.

--- examples/LCD/CosaLCDbench/CosaLCDbench.ino
+++ examples/LCD/CosaLCDbench/CosaLCDbench.ino
@@ -45,16 +45,18 @@
 // VLCD lcd;

 // Select the HD44780 port adapter for the benchmark
-#include "Cosa/LCD/Driver/HD44780.hh"
-// HD44780::Port4b port;
+// #include "Cosa/LCD/Driver/HD44780.hh"
+#include "Cosa/LCD/Driver/ST7920.hh"
+HD44780::Port4b port;
 // HD44780::SR3W port;
-HD44780::SR3WSPI port;
+// HD44780::SR3WSPI port;
 // HD44780::SR4W port;
 // HD44780::MJKDZ port;
 // HD44780::GYIICLCD port;
 // HD44780::DFRobot port;
 // HD44780::ERM1602_5 port;
-HD44780 lcd(&port);
+// HD44780 lcd(&port);
+ST7920 lcd(&port);

 // Connect IOStream to LCD
 IOStream cout(&lcd);