update demo

update demo

--- libraries/ATT_IOT_UART/examples/demo/demo.ino
+++ libraries/ATT_IOT_UART/examples/demo/demo.ino
@@ -1,111 +0,0 @@
-
-#include "ATT_IOT_UART.h"                            //AllThingsTalk IoT library
-#include <SPI.h>                                //required to have support for signed/unsigned long type.
-#include <SoftwareSerial.h>
-/*
-  SmartLiving Makers Arduino UART Demo Sketch
-  version 1.0 dd 25/11/2015
-
-  This file is an example sketch to deploy a digital sensor and actuator in the SmartLiving.io IoT platform.
-
-  ### Instructions
-
-  1. Setup the Arduino hardware
-    - USB2Serial
-    - Grove kit shield
-    - connect a digital sesnor to Pin D8 of the Arduino shield (example push button)
-    - connect a digital sensor to Pin 7
-    - Grove UART wifi to pin D2
-
-  2. Add 'iot_att' library to your Arduino Environment. [Try this guide](http://arduino.cc/en/Guide/Libraries)
-  3. fill in the missing strings (deviceId, clientId, clientKey, mac) and optionally change/add the sensor & actuator names, ids, descriptions, types
-     For extra actuators, make certain to extend the callback code at the end of the sketch.
-  4. Upload the sketch
-
-  ### Troubleshooting
-
-
-*/
-
-// Enter below your client credentials.
-//These credentials can be found in the configuration pane under your device in the smartliving.io website
-
-#define DEVICEID "devId"                                      // Your device id comes here
-#define CLIENTID "clientId"                                   // Your client id comes here;
-#define CLIENTKEY "clientKey"                                 // Your client key comes here;
-#define WIFI_SSID "ssid"
-#define WIFI_PWD "pwd"
-
-SoftwareSerial wifi(2, 3);                                      // 2=RX, 3=TX
-ATTDevice Device(&wifi);
-char httpServer[] = "api.smartliving.io";                       // HTTP API Server host
-char mqttServer[] = "broker.smartliving.io";                    // MQTT Server Address
-
-
-// Define PIN numbers for assets
-
-#define DigitalSensor 8                                        // Digital Sensor is connected to pin D8 on grove shield
-#define DigitalActuator 7
-
-//required for the device
-void callback(int pin, String& value);
-
-
-
-void setup()
-{
-  pinMode(DigitalSensor, INPUT);                                // initialize the digital pin as an input.
-  pinMode(DigitalActuator, OUTPUT);                             // initialize the digital pin as an output.
-  Serial.begin(9600);                                           // init serial link for debugging
-  Serial.println("starting");
-  wifi.begin(19200);                                             //init software serial link for wifi
-
-  while(!Device.Init(DEVICEID, CLIENTID, CLIENTKEY))            //if we can't succeed to initialize and set the device credentials, there is no point to continue
-    Serial.println("retrying...");
-  //while(!Device.StartWifi(WIFI_SSID, WIFI_PWD))
-	//Serial.println("retrying...");
-  while(!Device.Connect(httpServer))                                // connect the device with the IOT platform. No point to continue if we can't succeed at this
-    Serial.println("retrying");
-  Device.AddAsset(DigitalSensor, "sensor", "Digital Sensor Description", false, "boolean");   // Create the Digital Sensor asset for your device
-  Device.AddAsset(DigitalActuator, "acuator", "Digital Sensor Description", true, "boolean");   // Create the Digital Sensor asset for your device
-  delay(1000);                                                      //give the wifi some time to finish everything
-  while(!Device.Subscribe(mqttServer, callback))                           // make certain that we can receive message from the iot platform (activate mqtt). This stops the http connection
-	Serial.println("retrying");
-}
-
-
-bool sensorVal = false;                                         //only send every x amount of time.
-void loop()
-{
-  bool sensorRead = digitalRead(DigitalSensor);                 // read status Digital Sensor
-  if (sensorVal != sensorRead)                                  // verify if value has changed
-  {
-    sensorVal = sensorRead;
-    if (sensorRead == 1)
-        Device.Send("true", DigitalSensor);
-    else
-        Device.Send("false", DigitalSensor);
-  }
-  Device.Process();
-  delay(1000);
-}
-
-
-// Callback function: handles messages that were sent from the iot platform to this device.
-void callback(int pin, String& value)
-{
-    if(pin == DigitalActuator)
-    {
-        Serial.print("incomming data for: ");               //display the value that arrived from the cloud.
-        Serial.print(pin);
-        Serial.print(", value: ");
-        Serial.print(value);
-        if(value == "true")
-            digitalWrite(pin, HIGH);
-        else
-            digitalWrite(pin, LOW);
-        Device.Send(value, pin);                            //send the value back for confirmation
-    }
-
-}
-


check for Serial available

check for Serial available

--- arduino/src/sketch.ino
+++ arduino/src/sketch.ino
@@ -5,9 +5,6 @@
 #define MQ2PIN A2
 #define DHTPIN 8
 #define DHTTYPE DHT11
-
-#define BLURX 0
-#define BLUTX 1

 DHT dht(DHTPIN, DHTTYPE);

@@ -50,7 +47,9 @@
     hid = dht.computeHeatIndex(tmp, hum, false);

     serialize(fmt);
-    Serial.println(fmt);
+    if (Serial.available()) {
+        Serial.println(fmt);
+    }
 }

 void setup() {


Sketch: move logic around to try to prevent hangup

--- sketchbook/thcheckinhw/thcheckinhw.ino
+++ sketchbook/thcheckinhw/thcheckinhw.ino
@@ -192,43 +192,46 @@
   //寻卡，返回卡类型
   status = MFRC522_Request(PICC_REQIDL, str);
   if (status == MI_OK) {   // card detected
-  }
-
-  //防冲撞，返回卡的序列号 4字节
-  status = MFRC522_Anticoll(str);
-  MFRC522_Halt();			//命令卡片进入休眠状态
-  memcpy(serNum, str, 5);
-  if (status == MI_OK) {
-    cardNumber += serNum[0];
-    cardNumber += "-";
-    cardNumber += serNum[1];
-    cardNumber += "-";
-    cardNumber += serNum[2];
-    cardNumber += "-";
-    cardNumber += serNum[3];
-    cardNumber += "-";
-    cardNumber += serNum[4];
-
-    int checkInOut = askCheckInOut(10000);
-    if (checkInOut != CHECKTIMEOUT) {
-      String announce;
-      announce += cardNumber;
-      announce += ',';
-      announce += checkInOut;
-      Serial.println(announce);
-      if (checkInOut == CHECKIN) {
-        fastBlink(checkInLED, 50, 20);
-      } else if (checkInOut == CHECKOUT) {
-        fastBlink(checkOutLED, 50, 20);
+
+    //防冲撞，返回卡的序列号 4字节
+    status = MFRC522_Anticoll(str);
+    memcpy(serNum, str, 5);
+    MFRC522_Halt();			//命令卡片进入休眠状态
+
+    if (status == MI_OK) {
+      cardNumber += serNum[0];
+      cardNumber += "-";
+      cardNumber += serNum[1];
+      cardNumber += "-";
+      cardNumber += serNum[2];
+      cardNumber += "-";
+      cardNumber += serNum[3];
+      cardNumber += "-";
+      cardNumber += serNum[4];
+
+      int checkInOut = askCheckInOut();
+      if (checkInOut != CHECKTIMEOUT) {
+        String announce;
+        announce += cardNumber;
+        announce += ',';
+        announce += checkInOut;
+        Serial.println(announce);
+        if (checkInOut == CHECKIN) {
+          fastBlink(checkInLED, 50, 20);
+        } else if (checkInOut == CHECKOUT) {
+          fastBlink(checkOutLED, 50, 20);
+        }
       }
     }
+  } else {
+    MFRC522_Halt();			//命令卡片进入休眠状态
   }
   delay(10);
 }

-int askCheckInOut(int timeoutms){
-  int timeOutAt = millis() + timeoutms;
-  while (millis() <= timeOutAt) {
+int askCheckInOut(){
+  int loopCount = 0;
+  while (loopCount < 200) {
     checkInState = digitalRead(checkInButton);
     checkOutState = digitalRead(checkOutButton);
     if (checkInState == HIGH) {
@@ -237,12 +240,13 @@
       return(CHECKOUT);
     }
     if (checkInOutCounter % 10 == 0) {
-      fastBlink(checkInLED, 10, 1);
-      delay(50);
-      fastBlink(checkOutLED, 10, 1);
-    }
-    delay(50);
+      fastBlink(checkInLED, 5, 1);
+      delay(40);
+      fastBlink(checkOutLED, 5, 1);
+    }
+    delay(40);
     checkInOutCounter++;
+    loopCount++;
   }
   return(CHECKTIMEOUT);
 }


Add command handler

Add command handler

--- sketch/BLETest/BLETest.ino
+++ sketch/BLETest/BLETest.ino
@@ -14,13 +14,15 @@
 // org.bluetooth.characteristic.user_control_point
 BLEUnsignedCharCharacteristic diceCommandCharacteristic("0x2A9F", BLERead | BLEWrite | BLENotify);

-int diceID = 3;
+int diceID;
 unsigned long last = millis();

 void setup() {
-  delay(5000);
-  pinMode(13, OUTPUT);
-
+  /**
+   * Identify diceID based on jumper
+   */
+  diceID = 3;
+
   blePeripheral.setLocalName("CurieDice");
   blePeripheral.setAdvertisedServiceUuid(diceService.uuid());
   blePeripheral.addAttribute(diceService);
@@ -40,6 +42,10 @@
   if(central) {
     while(central.connected()) {
       blePeripheral.poll();
+
+      /**
+       * This simulates a roll every 5 seconds
+       */
       unsigned long now = millis();
       if(now - last > (5 * 1000)) {
         last = now;
@@ -53,12 +59,21 @@
   diceRollCharacteristic.setValue((diceID << 4) | value);
 }

+/**
+ * Handle commands coming from the server
+ */
 void commandHandler(BLECentral &central, BLECharacteristic &characteristic) {
 }

+/**
+ * On connect
+ */
 void blePeripheralConnectHandler(BLECentral &central) {
 }

+/**
+ * On disconnect
+ */
 void blePeripheralDisconnectHandler(BLECentral &central) {
 }


added player turn logic

added player turn logic

--- tictactoe/tictactoe.ino
+++ tictactoe/tictactoe.ino
@@ -35,6 +35,7 @@
 // square status
 int redStatus [] = {0,0,0,0,0,0,0,0,0};
 int greenStatus [] = {0,0,0,0,0,0,0,0,0};
+int previousGreenStatus [] = {0,0,0,0,0,0,0,0,0};

 // conditions for victory
 int winConditions [][9] = {{1,1,1,0,0,0,0,0,0},
@@ -67,18 +68,68 @@
   // Show the welcome message
   doWelcome();
   // Find other player
-  rival_id = findPlayer(player_id);
+  rival_id = findPlayer();
 }

 // the loop routine runs over and over again forever:
 void loop() {
   delay(200);
-
-
-  /*
+
+  // ******** Player turn *******
+  for (int i = 0; i < 9; i++){
+    previousGreenStatus[i] = greenStatus[i];
+  }
+  // Update color status
+  // Check player move, wait until it happens
+  printMsg("Your turn.");
+  boolean waitForMove = true;
+  int player_move = 0;
+
+  while (waitForMove){
+    updateBoardStatus();
+    player_move = checkPlayerMove();
+    if (player_move == 0){
+      // No move, wait and check again
+      delay(30);
+    }else if (player_move > 0){
+      // Legal move, continue
+      waitForMove = false;
+    } else if (player_move == -1){
+      // Player has moved 2 pieces, illegal move
+      msgAndWait("You moved two pieces! Correct you move.");
+    } else if (player_move == -2){
+      // Player has moved the piece into an square already used.
+      msgAndWait("You moved your piece into an already used square! Correct you move.");
+    }
+  }
+
+  // Send move to server
+  sendMove(player_move);
+
+  // Check victory conditions
+  greenVictory = checkWin(greenStatus);
+  if (greenVictory){
+    printMsg("A winner is you"); //TODO think some proper msgs
+    victoryLoop('g');
+  }
+
+
+
+  // ******* Rival turn *******
+  // Check rival move, wait until it happens
+  // Update color status
+  // Check victory conditions
+
+
+
+
+  int rivalMove = getMove();
+  redStatus[rivalMove] = 1;
+
   if (!redVictory && !greenVictory){
     updateColorStatus();
   }
+

   redVictory = checkWin(redStatus);
   greenVictory = checkWin(greenStatus);
@@ -88,7 +139,7 @@
   } else if (greenVictory){
     victoryLoop('g');
   }
-  */
+

 }

@@ -126,10 +177,11 @@
 }

 /**********************************************
- *   WELCOME SCREEN
+ *   SCREEN PRONTS
  **********************************************/

 void doWelcome(){
+  display.clear();
   display.printText("Welcome to the tictactoe game!", 6, 1, BLUE);
   delay(1000);
   display.clear();
@@ -138,26 +190,59 @@
   while(doLoop){
     if (display.buttonsChanged()) {
       byte reply = display.getButtons();
+      // Green button
       if ((reply & 0x04) == 0x00){
           doLoop = false;
       }
     }
   }
   display.clear();
-  display.printText("Starting new game!", 6, 1, GREEN);
-
-
-}
-
-/**********************************************
- *   GAME INITIALIZATION WITH THE SERVER
- **********************************************/
-
-int findPlayer(int player_id){
+  display.printText("Starting new game!", 6, 1, GREEN);
+}
+
+void msgAndWait(String msg){
+  display.clear();
+  display.printText(msg, 6, 1, RED);
+  boolean doLoop = true;
+  while(doLoop){
+    if (display.buttonsChanged()) {
+      byte reply = display.getButtons();
+      // Green button
+      if ((reply & 0x04) == 0x00){
+          doLoop = false;
+      }
+    }
+  }
+  display.clear();
+}
+
+void printMsg(String msg){
+  display.clear();
+  display.printText(msg, 6, 1, BLUE);
+}
+
+/**********************************************
+ *   COMMUNICATION WITH THE GAME SERVER
+ **********************************************/
+
+int findPlayer(){
   //TODO
-  Serial.println("finding player");
+  // rival_id = send ("REGISTER " + player_id + "\0n")
+  // returns the rival_id
   return 113;

+}
+
+int getMove(){
+  //TODO
+  // move = send ("GET_MOVE " + rival_id)
+  return 0;
+}
+
+void sendMove(int player_move){
+  //TODO
+  // send ("MOVE " + player_move + player_id)
+  return 0;
 }

@@ -183,6 +268,45 @@
 /**********************************************
  *   GAME LOGIC
  **********************************************/
+
+int checkPlayerMove(){
+  int totalMoves = 0;
+  int player_move = 0;
+  char color;
+  for(int i = 0; i < 9; i++){
+    color = squares[i]->checkColor();
+    if (previousGreenStatus[i] != greenStatus[i]){
+      totalMoves++;
+      player_move = i+1;
+    }
+  }
+
+  if (totalMoves == 0) {
+    // The player has not done any move
+    player_move = 0;
+  } else if (totalMoves > 1) {
+    // The player has moved 2 pieces, which is an illegal move
+    player_move = -1;
+  }
+  else if (color == 'r'){
+    // The player has moved his piece into an square already used by the rival
+    player_move = -2;
+  }
+
+  return player_move;
+
+}
+
+
+void updateBoardStatus(){
+  for (int i=0; i < 9; i++){
+    char color = squares[i]->checkColor();
+    if (color == 'g'){
+      squares[i]->setGreen();
+      greenStatus[i] = 1;
+    }
+  }
+}

 void updateColorStatus(){
   for (int i=0; i < 9; i++){


Revert "Added some tmphax in an attempt to get back to the performance of commit b786d3341751833b6a1cde4ed43cd75eb85907ff but it did not work."

The real "problem" is that the old commit was only delaying about
100us between steps.

This reverts commit 2b97e8885a4ab42b7f7a78459508025ae74db05f.

--- examples/StepTest/StepTest.ino
+++ examples/StepTest/StepTest.ino
@@ -33,11 +33,8 @@
   }
   ledYellow(1);

-  //stepper.init(amisSlaveSelect);
-  //stepper.enableDriver();
-
-  SPIwriteParam(12, 10); // tmphax
-  SPIwriteParam(11, 1); // tmphax
+  stepper.init(amisSlaveSelect);
+  stepper.enableDriver();
 }

 void loop()
@@ -52,117 +49,3 @@
   // stepper motor.
   delay(1);
 }
-
-/************************ tmphax below *******************************/
-
-//Commands
-#define READ B000  //  CMD2=0
-#define WRITE B100  //  CMD2=1
-
-//Addresses of control registers
-#define WR 0x0
-#define CR0 0x1
-#define CR1 0x2
-#define CR2 0x3
-#define CR3 0x9
-
-//Addresses of status regusters
-#define SR0 0x4
-#define SR1 0x5
-#define SR2 0x6
-#define SR3 0x7
-#define SR4 0xA
-
-//Control register parameters
-#define DIRCTRL 1
-#define NXTP 2
-#define EMC 3
-#define SLAT 4
-#define SLAG 5
-#define PWMF 6
-#define PWMJ 7
-#define SM 8
-#define ESM 9
-#define SLP 10
-#define MOTEN 11
-#define CUR 12
-#define WDEN 13
-#define WDT 14
-
-
-void SPIwriteParam(int param, byte newData)
-{
-  //Before writing a single param we must read what is already at
-  //that address so we can preserve it.
-  byte prevData;
-
-  switch(param)
-  {
-    case DIRCTRL:
-    prevData = SPItransmit(READ, CR1, 0) & B01111111;
-    SPItransmit(WRITE, CR1, prevData | newData<<7);
-    break;
-    case NXTP:
-    prevData = SPItransmit(READ, CR1, 0) & B10111111;
-    SPItransmit(WRITE, CR1, prevData | newData<<6);
-    break;
-    case EMC:
-    prevData = SPItransmit(READ, CR1, 0) & B11111100;
-    SPItransmit(WRITE, CR1, prevData | newData<<0);
-    break;
-    case SLAT:
-    prevData = SPItransmit(READ, CR2, 0) & B11101111;
-    SPItransmit(WRITE, CR2, prevData | newData<<4);
-    break;
-    case SLAG:
-    prevData = SPItransmit(READ, CR2, 0) & B11011111;
-    SPItransmit(WRITE, CR2, prevData | newData<<5);
-    break;
-    case PWMF:
-    prevData = SPItransmit(READ, CR1, 0) & B11110111;
-    SPItransmit(WRITE, CR1, prevData | newData<<3);
-    break;
-    case PWMJ:
-    prevData = SPItransmit(READ, CR1, 0) & B11111011;
-    SPItransmit(WRITE, CR1, prevData | newData<<2);
-    break;
-    case SM:
-    prevData = SPItransmit(READ, CR0, 0) & B00011111;
-    SPItransmit(WRITE, CR0, prevData | newData<<5);
-    break;
-    case ESM:
-    prevData = SPItransmit(READ, CR3, 0) & B11111000;
-    SPItransmit(WRITE, CR3, prevData | newData<<0);
-    break;
-    case SLP:
-    prevData = SPItransmit(READ, CR2, 0) & B10111111;
-    SPItransmit(WRITE, CR2, prevData | newData<<6);
-    break;
-    case MOTEN:
-    prevData = SPItransmit(READ, CR2, 0) & B01111111;
-    SPItransmit(WRITE, CR2, prevData | newData<<7);
-    break;
-    case CUR:
-    prevData = SPItransmit(READ, CR0, 0) & B11100000;
-    SPItransmit(WRITE, CR0, prevData | newData<<0);
-    break;
-    case WDEN:
-    prevData = SPItransmit(READ, WR, 0) & B01111111;
-    SPItransmit(WRITE, WR, prevData | newData<<7);
-    break;
-    case WDT:
-    prevData = SPItransmit(READ, WR, 0) & B10000111;
-    SPItransmit(WRITE, WR, prevData | newData<<3);
-    break;
-  }
-}
-
-byte SPItransmit(int cmd, int adr, byte dataIn)
-{
-    digitalWrite(amisSlaveSelect, LOW);  //take the ss pin low to select the chip
-    SPI.transfer(cmd<<5 | adr);  //send command and address byte
-    byte dataOut = SPI.transfer(dataIn);  //send data byte for write and read data dyte for read
-    digitalWrite(amisSlaveSelect, HIGH); //take the ss pin high to de-select the chip
-    return dataOut;
-}
-


#20 Single line debug statement

#20 Single line debug statement

--- examples/ttn-otaa/ttn-otaa.ino
+++ examples/ttn-otaa/ttn-otaa.ino
@@ -147,8 +147,8 @@
             if (LMIC.txrxFlags & TXRX_ACK)
               Serial.println(F("Received ack"));
             if (LMIC.dataLen) {
-              Serial.println(F("Received "));
-              Serial.println(LMIC.dataLen);
+              Serial.print(F("Received "));
+              Serial.print(LMIC.dataLen);
               Serial.println(F(" bytes of payload"));
             }
             // Schedule next transmission


changes for Particle

changes for Particle

--- examples/vemltest/vemltest.ino
+++ examples/vemltest/vemltest.ino
@@ -1,4 +1,4 @@
-#include <Wire.h>
+// This #include statement was automatically added by the Particle IDE.
 #include "Adafruit_VEML6070.h"

 Adafruit_VEML6070 uv = Adafruit_VEML6070();
@@ -9,9 +9,8 @@
   uv.begin(VEML6070_1_T);  // pass in the integration time constant
 }

-
 void loop() {
   Serial.print("UV light level: "); Serial.println(uv.readUV());

   delay(1000);
-}+}


working

working

--- usbswitch/usbswitch.ino
+++ usbswitch/usbswitch.ino
@@ -13,10 +13,14 @@
   by Scott Fitzgerald
  */

+static bool StatusUSB = true;
+static bool Status5V = false;
+static bool Status3_3V = false;
+static bool StatusAlwaysON;

 // the setup function runs once when you press reset or power the board
 void setup() {
-  // initialize digital pin 13 as an output.
+
   pinMode(8, OUTPUT); //5V Relay
   pinMode(7, OUTPUT); //USB VCC Relay
   pinMode(6, OUTPUT); //USB D- Relay
@@ -24,25 +28,212 @@
   pinMode(9, OUTPUT); //3.3V PMOSFET
   pinMode(10, OUTPUT); //Yellow Status LED
   pinMode(16, OUTPUT); //Green Status LED
- }
+  pinMode(15, INPUT_PULLUP ); //Always ON/USB Controlled switch
+
+  Serial.begin(9600);
+
+  Set5V(false);
+  Set3_3V(false);
+  digitalWrite(10, LOW); //Yellow Status LED
+  digitalWrite(16, LOW);  //Green Status LED
+  ConnectUSB();
+
+  while (!Serial) {
+    ; // wait for serial port to connect. Needed for native USB port only
+  }
+  Serial.println("[I] USB switcher booted up.");
+}
+
+void Set5V(bool s)
+{
+  Status5V = s;
+  if(s){
+    digitalWrite(8, LOW); //5V ON
+  }else{
+    digitalWrite(8, HIGH); //5V OFF
+  }
+}
+
+void Set3_3V(bool s)
+{
+  Status3_3V = s;
+  if(s){
+    digitalWrite(9, LOW); //3.3V ON
+  }else{
+    digitalWrite(9, HIGH); //3.3V OFF
+  }
+}
+void ConnectUSB()
+{
+  digitalWrite(7, HIGH); // USB VCC Connect
+  delay(100);
+  digitalWrite(6, HIGH);  //USB D- Relay Connect
+  digitalWrite(5, HIGH);  //USB D+ Relay Connect
+  StatusUSB = true;
+}
+
+void DisconnectUSB()
+{
+  StatusUSB = false;
+  digitalWrite(6, LOW);  //USB D- Relay Disconnect
+  digitalWrite(5, LOW);  //USB D+ Relay Disconnect
+  delay(100);
+  digitalWrite(7, LOW); // USB VCC Disconnect
+}
+
+void AlwaysOn()
+{
+  Set5V(true);
+  delay(100);
+  Set3_3V(true);
+  ConnectUSB();
+  digitalWrite(10, LOW); //Yellow Status LED
+}
+
+void USBcontrolled()
+{
+  Set3_3V(false);
+  delay(100);
+  Set5V(false);
+  DisconnectUSB();
+  digitalWrite(10, HIGH); //Yellow Status LED
+}
+
+static char serialReadBuf[16];
+static int serialReadPos = 0;
+
+
+void OnSingleLine(String line)
+{
+  String s;
+  Serial.print("[");
+  Serial.print(line);
+  Serial.print("] ");
+
+  if( line.equalsIgnoreCase( "?" ) ){
+    Serial.println( "OK, available commands: q, enausb, disusb, ena3_3v, dis3_3v, ena5v, dis5v" );
+
+  }else if( line.equalsIgnoreCase( "q" ) ){
+    Serial.print( "OK, " );
+    s = "5V:";
+    s += Status5V;
+    s += ", 3_3V:";
+    s += Status3_3V;
+    s += ", USB:";
+    s += StatusUSB;
+    s += ", MODE:";
+    if( StatusAlwaysON ){
+      s += "AlwaysON";
+    }else{
+      s += "USBcontrolled";
+    }
+    Serial.print( s );
+    Serial.println( "" );
+
+  }else if( line.equalsIgnoreCase( "enausb" ) ){
+    if( StatusAlwaysON ){
+      Serial.println( "ERROR, unable to control under Always ON mode." );
+    }else{
+      ConnectUSB();
+      Serial.println( "OK." );
+    }
+
+  }else if( line.equalsIgnoreCase( "disusb" ) ){
+    if( StatusAlwaysON ){
+      Serial.println( "ERROR, unable to control under Always ON mode." );
+    }else{
+      DisconnectUSB();
+      Serial.println( "OK." );
+    }
+
+  }else if( line.equalsIgnoreCase( "ena3_3v" ) ){
+    if( StatusAlwaysON ){
+      Serial.println( "ERROR, unable to control under Always ON mode." );
+    }else{
+      Set3_3V(true);
+      Serial.println( "OK." );
+    }
+
+  }else if( line.equalsIgnoreCase( "dis3_3v" ) ){
+    if( StatusAlwaysON ){
+      Serial.println( "ERROR, unable to control under Always ON mode." );
+    }else{
+      Set3_3V(false);
+      Serial.println( "OK." );
+    }
+
+  }else if( line.equalsIgnoreCase( "ena5v" ) ){
+    if( StatusAlwaysON ){
+      Serial.println( "ERROR, unable to control under Always ON mode." );
+    }else{
+      Set5V(true);
+      Serial.println( "OK." );
+    }
+
+  }else if( line.equalsIgnoreCase( "dis5v" ) ){
+    if( StatusAlwaysON ){
+      Serial.println( "ERROR, unable to control under Always ON mode." );
+    }else{
+      Set5V(false);
+      Serial.println( "OK." );
+    }
+
+  }else{
+    Serial.println( "ERROR, Unknown command." );
+  }
+}
+
+int FeedChar(int c)
+{
+  if( 0x0D == c || 0x0A == c ){ //is it CR or LF?
+    if( 0 != serialReadPos ){
+      serialReadBuf[serialReadPos] = '\0';
+      String line = serialReadBuf;
+      //Serial.println( line );
+      OnSingleLine(line);
+      serialReadPos = 0;
+      return 1;
+    }
+  }
+  //put the char into the buffer
+  serialReadBuf[serialReadPos] = c;
+  serialReadPos++;
+  if( sizeof(serialReadBuf) <= serialReadPos ){
+    //rewind the buffer when overrun
+    serialReadPos = 0;
+  }
+
+  return 0;
+}

 // the loop function runs over and over again forever
 void loop() {
-  digitalWrite(8, HIGH);   // turn the LED on (HIGH is the voltage level)
-  digitalWrite(7, HIGH);
-  digitalWrite(6, HIGH);   // turn the LED on (HIGH is the voltage level)
-  digitalWrite(5, HIGH);
-  digitalWrite(9, HIGH);   // turn the LED on (HIGH is the voltage level)
-  digitalWrite(10, HIGH);
-  digitalWrite(16, LOW);
-  delay(1000);              // wait for a second
-  digitalWrite(8, LOW);    // turn the LED off by making the voltage LOW
-  digitalWrite(7, LOW);
-  delay(100);
-  digitalWrite(6, LOW);    // turn the LED off by making the voltage LOW
-  digitalWrite(5, LOW);
-  digitalWrite(9, LOW);    // turn the LED off by making the voltage LOW
-  digitalWrite(10, LOW);
-  digitalWrite(16, HIGH);
-  delay(2000);              // wait for a second
-}
+  int sw;
+  static int prevSw = 4949;
+  static int count;
+
+  delay(10);
+  count++;
+
+  if( 0 == (count % 50 ) ){ //blinking Status LED
+    digitalWrite(16, HIGH);  //Green Status LED
+  }else if( 25 == (count % 50 ) ){
+    digitalWrite(16, LOW);  //Green Status LED
+  }
+
+  sw = digitalRead(15);
+  if( sw != prevSw ){
+    if( HIGH == sw ){
+      StatusAlwaysON = false;
+      USBcontrolled();
+    }else{
+      StatusAlwaysON = true;
+      AlwaysOn();
+    }
+  }
+  prevSw = sw;
+
+  if (0 < Serial.available() ) {
+    FeedChar( Serial.read() );
+  }
+}


Adds physical LED count option to extend virtual bulbs on LED strip (#61)

Closes #27

--- ESP8266HueEmulator/ESP8266HueEmulator.ino
+++ ESP8266HueEmulator/ESP8266HueEmulator.ino
@@ -26,10 +26,12 @@
 RgbColor black = RgbColor(0);

 // Settings for the NeoPixels
+#define NUM_PIXELS_PER_LIGHT 10 // How many physical LEDs per emulated bulb
+
 #define pixelCount 30
 #define pixelPin 2 // Strip is attached to GPIO2 on ESP-01
-NeoPixelBus<NeoGrbFeature, NeoEsp8266Uart800KbpsMethod> strip(pixelCount, pixelPin);
-NeoPixelAnimator animator(pixelCount, NEO_MILLISECONDS); // NeoPixel animation management object
+NeoPixelBus<NeoGrbFeature, NeoEsp8266Uart800KbpsMethod> strip(MAX_LIGHT_HANDLERS * NUM_PIXELS_PER_LIGHT, pixelPin);
+NeoPixelAnimator animator(MAX_LIGHT_HANDLERS * NUM_PIXELS_PER_LIGHT, NEO_MILLISECONDS); // NeoPixel animation management object

 HsbColor getHsb(int hue, int sat, int bri) {
   float H, S, B;
@@ -69,7 +71,10 @@
             if (currentHue > 1) currentHue -= 1;
             HslColor updatedColor = HslColor(currentHue, newColor.S, newColor.L);
             RgbColor currentColor = updatedColor;
-            strip.SetPixelColor(lightNumber, updatedColor);
+
+            for(int i=lightNumber * NUM_PIXELS_PER_LIGHT; i < (lightNumber * NUM_PIXELS_PER_LIGHT) + NUM_PIXELS_PER_LIGHT; i++) {
+              strip.SetPixelColor(i, updatedColor);
+            }

             // loop the animation until canceled
             if (param.state == AnimationState_Completed) {
@@ -83,7 +88,10 @@
         {
           // progress will start at 0.0 and end at 1.0
           HslColor updatedColor = HslColor::LinearBlend<NeoHueBlendShortestDistance>(originalColor, newColor, param.progress);
-          strip.SetPixelColor(lightNumber, updatedColor);
+
+          for(int i=lightNumber * NUM_PIXELS_PER_LIGHT; i < (lightNumber * NUM_PIXELS_PER_LIGHT) + NUM_PIXELS_PER_LIGHT; i++) {
+            strip.SetPixelColor(i, updatedColor);
+          }
         };
         animator.StartAnimation(lightNumber, _info.transitionTime, animUpdate);
       }
@@ -93,7 +101,10 @@
         {
           // progress will start at 0.0 and end at 1.0
           HslColor updatedColor = HslColor::LinearBlend<NeoHueBlendShortestDistance>(originalColor, black, param.progress);
-          strip.SetPixelColor(lightNumber, updatedColor);
+
+          for(int i=lightNumber * NUM_PIXELS_PER_LIGHT; i < (lightNumber * NUM_PIXELS_PER_LIGHT) + NUM_PIXELS_PER_LIGHT; i++) {
+            strip.SetPixelColor(i, updatedColor);
+          }
         };
         animator.StartAnimation(lightNumber, _info.transitionTime, animUpdate);
       }


Update comments. Explain how we want the live throttle versus doing a test routine versus stopping to work. No code change, as we've decided the current behavior is correct.

--- Elcano_C2_LowLevel/Elcano_C2_LowLevel.ino
+++ Elcano_C2_LowLevel/Elcano_C2_LowLevel.ino
@@ -651,7 +651,7 @@
     }
   }

-  /*  6th pulse is marked throttle (position 6 on receiver; controlled by Left up/down joystick on transmitter).
+  /* Controlled by Left up/down joystick.
     It will be used for shifting from Drive to Reverse . D40
   */
   //if (RC_Done[RC_RVS]) {
@@ -660,7 +660,7 @@

   // TO DO: Select Forward / reverse based on results[RC_RVS]

-  /*   3rd pulse is elevator (position 4 on receiver; controlled by Right up/down.
+  /* Controlled by Right up/down.
      will be used for throttle/brake: RC_Throttle
   */
   if (RC_Done[RC_TURN]) {
@@ -678,20 +678,33 @@
     }
   }

-  //Accelerating
+  // Accelerating
+  // Note: The doRoutine / squareRoutine code will be moved out to run on
+  // a separate module.  For now, for safety, we want a way to stop the
+  // routine, apart from e-stop.  What we require is that the RC controller
+  // is turned on, and the throttle is in a specific position, the extreme
+  // lower right.  If it is released, we want the routine to stop.  This
+  // can then serve as a dead-man switch, as well.
+  // Similarly, when in normal RC operation, we check for the throttle to
+  // be in a "live" position.  Otherwise, (if the throttle is in neither
+  // the "routine" nor "live" positions, we want to stop.
   if (RC_Done[RC_RDR]) {
     if (liveThrottle(results[RC_RDR])){
+      // Here, the throttle is in a "live" position.
       int going = convertThrottle(results[RC_RDR]);
       moveVehicle(going);
     }
     // @ToDo: Move test code out. Will eventually want to have a separate
     // module execute the tests.
     else {
+      // Not "live".
       if (RC_Done[RC_AUTO]) {
         if(doRoutine(results[RC_RDR])){
+          // Here, the throttle is in the "routine" position.
           moveVehicle(MIN_ACC_OUT);
           squareRoutine(5, results[RC_AUTO]);
         } else {
+          // Here, the throttle is neither "live" nor "routine".
           moveVehicle(MIN_ACC_OUT);
         }
       }


no message

no message

--- Arduino/Base/Base.ino
+++ Arduino/Base/Base.ino
@@ -68,14 +68,12 @@
 		simcomm.HTTPRequest(1, "http://sachleen.com/sachleen/parking/API/nodes/save", "id=" + nodeIds[i] + "&" + "available=" + spacesAvail[i] + "&api_key=" + apiKey);
         //sendResponse = sendRequestServer(nodeIds[i], 'U', spacesAvail[i], totalSpaces[i]);//Sends a message to the server to update the status of the node
 		DEBUG_PRINTLN(response);//Idk what the response is supposed to be yet...
-		/*
-		if(sendResponse == 1){
+		if (response.indexOf("TRUE") < 0) {
+			DEBUG_PRINTLN("Update " + (String)i + " Failed");
+		}
+		else{
 			DEBUG_PRINTLN("Update " + (String)i + " Succeeded");
 		}
-		else{
-			DEBUG_PRINTLN("Update " + (String)i + " Failed");
-		}
-		*/
       }
       qCount = 0;
     }


clean up test output for touch sensor test

--- tests/Console/MPR121_Test/MPR121_Test.ino
+++ tests/Console/MPR121_Test/MPR121_Test.ino
@@ -26,6 +26,7 @@
 #include <MPR121.h>
 #include <Wire.h>
 #include <Streaming.h>
+#include <Metro.h>

 #define numElectrodes 4

@@ -53,20 +54,20 @@

 void loop()
 {
-  static Metro timer(750UL);
+  static Metro timer(500UL);
   while (timer.check()) {
     printTouchData();
     timer.reset();
   }
   // error checking
-  if( MPR121.getError() != NO_ERROR ) {
+  if(MPR121.getError() != NO_ERROR) {
     parseError();
   };

   // check buttons
   for(int i=0; i<numElectrodes; i++){
-    if( MPR121.isNewTouch(i) ) Serial << i << " pressed." << endl;
-    if( MPR121.isNewRelease(i) ) Serial << i << " released." << endl;
+    if(MPR121.isNewTouch(i)) Serial   << "+ " << i << " pressed." << endl;
+    if(MPR121.isNewRelease(i)) Serial << "- " << i << " released." << endl;
   }

   // update data
@@ -87,7 +88,7 @@
   uint16_t data1 = (((uint16_t)MPR121.getRegister(0x07))<<8) | MPR121.getRegister(0x06);
   uint16_t data2 = (((uint16_t)MPR121.getRegister(0x09))<<8) | MPR121.getRegister(0x08);
   uint16_t data3 = (((uint16_t)MPR121.getRegister(0x0B))<<8) | MPR121.getRegister(0x0A);
-  //Serial << count << ", 0, " << base0 << ", " << data0 << endl;
+  Serial << count << ",                         0, " << base0 << ", " << data0 << endl;
   //Serial << count << ", 1, " << base1 << ", " << data1 << endl;
   //Serial << count << ", 2, " << base2 << ", " << data2 << endl;
   Serial << count << ",                         3, " << base3 << ", " << data3 << endl;


Resyncing

Resyncing

--- Sketches/MIDI1/MIDI1.ino
+++ Sketches/MIDI1/MIDI1.ino
@@ -1,4 +1,9 @@
 // ADXL335 Test Program
+
+// Old Values
+// Coincidentally, the difference between these is 127, perfect for MIDI
+//#define MIN 270
+//#define MAX 397

 #define CENTER 371  // Same for x, y, and z
 #define RANGE  100
@@ -10,7 +15,7 @@
 void setup()
 {
 //Serial.begin(31250);     // Raw MIDI
-  Serial.begin(38400);     // Direct connect or XBee
+  Serial.begin(38400);     // Direct connect
   pinMode(LED, OUTPUT);
 }

@@ -66,4 +71,4 @@
     return temp*127;
 }

-
+


Updated ArtnetReceiveCallback example for Particle

--- examples/ArtnetReceiveCallback/ArtnetReceiveCallback.ino
+++ examples/ArtnetReceiveCallback/ArtnetReceiveCallback.ino
@@ -1,32 +1,20 @@
-/*
-This is similar to ArtnetReceive but uses a callback to read the data.
-This example may be copied under the terms of the MIT license, see the LICENSE file for details
-*/
-
-#include <Artnet.h>
-#include <Ethernet.h>
-#include <EthernetUdp.h>
-#include <SPI.h>
+// This #include statement was automatically added by the Particle IDE.
+#include "Artnet/Artnet.h"

 Artnet artnet;

-// Change ip and mac address for your setup
-byte ip[] = {192, 168, 2, 2};
-byte mac[] = {0x04, 0xE9, 0xE5, 0x00, 0x69, 0xEC};
-
-void setup()
-{
-  Serial.begin(115200);
-  artnet.begin(mac, ip);
-
-  // this will be called for each packet received
-  artnet.setArtDmxCallback(onDmxFrame);
+void setup() {
+    Serial.begin(9600);
+
+    artnet.begin();
+    artnet.setArtDmxCallback(onDmxFrame);
+
+    pinMode(D7, OUTPUT);
+    digitalWrite(D7, HIGH);
 }

-void loop()
-{
-  // we call the read function inside the loop
-  artnet.read();
+void loop() {
+    artnet.read();
 }

 void onDmxFrame(uint16_t universe, uint16_t length, uint8_t sequence, uint8_t* data)
@@ -38,7 +26,7 @@
   Serial.print(length);
   Serial.print("\tsequence n0. = ");
   Serial.println(sequence);
-  Serial.print("DMX data: ");
+  Serial.print("\tDMX data: ");
   for (int i = 0 ; i < length ; i++)
   {
     Serial.print(data[i]);
@@ -47,4 +35,5 @@
   Serial.println();
   Serial.println();

-}+    digitalWrite(D7, data[0] != 0);
+}


redact SSID

redact SSID

--- examples/ws2812fx_segments_web/ws2812fx_segments_web.ino
+++ examples/ws2812fx_segments_web/ws2812fx_segments_web.ino
@@ -45,11 +45,11 @@

 extern const char index_html[];

-#define LED_PIN   D1  // digital pin used to drive the LED strip (esp8266)
+#define LED_PIN   D1 // digital pin used to drive the LED strip (esp8266)
 #define LED_COUNT 30 // number of LEDs on the strip

-#define WIFI_SSID "moose.net"     // WiFi network
-#define WIFI_PASSWORD "mooselord" // WiFi network password
+#define WIFI_SSID "xxxxxxxx"     // WiFi network
+#define WIFI_PASSWORD "xxxxxxxx" // WiFi network password

 WS2812FX ws2812fx = WS2812FX(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
 ESP8266WebServer server(80);


Tested RPM interrupt handler, working on Ignition ISR

--- Flameduino/Flameduino.ino
+++ Flameduino/Flameduino.ino
@@ -32,7 +32,7 @@
 // -------------------------
 //        Settings
 // -------------------------
-const bool debug = false;       //true = write to serial monitor, false = bypass
+const bool debug = true;       //true = write to serial monitor, false = bypass
 //Ignition Settings
 const int dwell = 2500;         //Ignition coil charging dwell in microseconds (2.5ms = 2500us)
 const long periodMax = 1000000; //Maximum period between ignitions, in microseconds (min frequency)
@@ -50,12 +50,13 @@
 // -------------------------
 volatile bool active = false;
 unsigned int rpm = 0;
-volatile int tachDuration0 = 0;
-volatile int tachDuration1 = 0;
-volatile int tachDuration2 = 0;
+volatile unsigned long tachDuration0 = 0;
+volatile unsigned long tachDuration1 = 0;
+volatile unsigned long tachDuration2 = 0;
 volatile unsigned long tachLast = 0;
 volatile unsigned int ignitionMode = OFF;
 volatile int remainingCount = 0;
+volatile bool updateTimer = false;
 long period = 0;

 // -------------------------
@@ -78,9 +79,9 @@
   attachInterrupt(TACH_PIN - 2, ISR_TACH, RISING);
   attachInterrupt(ACTIVATION_PIN - 2, ISR_ACTIVE, CHANGE);

-  Timer1.initialize(1000000);
-  Timer1.stop();
+  Timer1.initialize();
   Timer1.attachInterrupt(ISR_IGNITION);
+  Timer1.start();

   if (debug)
   {
@@ -102,11 +103,44 @@
     enableCoil();
   else if (!active)
     disableCoil();
+
+  if (updateTimer)
+  {
+    //Set the delay period (Head of Mode)
+    Timer1.detachInterrupt();
+    switch(ignitionMode)
+    {
+      case OFF:
+        Timer1.stop();
+        break;
+      case DWELL:
+        //Charging Coil
+        Timer1.attachInterrupt(ISR_IGNITION, dwell);
+        Timer1.start();
+        break;
+      case MF_WAIT:
+        //Waiting (MultiFire)
+        Timer1.attachInterrupt(ISR_IGNITION, multiDelay);
+        Timer1.start();
+        break;
+      case MF_DWELL:
+        //Charging Coil
+        Timer1.attachInterrupt(ISR_IGNITION, dwell);
+        Timer1.start();
+        break;
+      case WAIT:
+        //Waiting (Frequency)
+        Timer1.attachInterrupt(ISR_IGNITION, period);
+        Timer1.start();
+        break;
+    }
+    updateTimer = false;
+  }

   if (debug)
   {
     Serial.print("Period: ");
-    Serial.print(period);
+    Serial.print(period / 1000.0);
     Serial.print("ms, dwell: ");
     Serial.print(dwell / 1000.0);
     Serial.print("ms, RPM: ");
@@ -152,24 +186,25 @@
     Serial.print(tachDuration1);
     Serial.print(", t2: ");
     Serial.print(tachDuration2);
-    Serial.println();
+    Serial.print(", ");
   }

   //Calculate Weighted Average
-  return (3*tachDuration0 + 2*tachDuration1 + 1*tachDuration2)/6;
+  unsigned long average = (3*tachDuration0 + 2*tachDuration1 + 1*tachDuration2)/6;
+  return 60.0 * 1000000 / average;
 }

 void enableCoil()
 {
   //Enable Coil Firing
   ignitionMode = WAIT;
-  ISR_IGNITION();
 }

 void disableCoil()
 {
+  //Disable Coil Firing
+  Timer1.stop();
   ignitionMode = OFF;
-  Timer1.stop();
 }

 void chargeCoil()
@@ -197,7 +232,7 @@
 void fireMultiple()
 {
   fireCoil();
-  for(int i = 1; i <= multiCount; i++)
+  for(int i = 1; i < multiCount; i++)
   {
     delayMicroseconds(multiDelay);
     fireCoil();
@@ -216,18 +251,25 @@
 // -------------------------
 void ISR_TACH()
 {
-  int duration = (int)(micros() - tachLast);
-  if (duration < 0)
+  unsigned long duration;
+  unsigned long current = micros();
+
+  if (current >= tachLast)
+  {
+    duration = current - tachLast;
+  }
+  else
   {
     //Handle Rollover
-    duration = 0xFFFFFFFFu - tachLast + micros();
-  }
+    //duration = 0xFFFFFFFFu - tachLast + current;
+  }
+
   //Shift the values
   tachDuration2 = tachDuration1;
   tachDuration1 = tachDuration0;
   tachDuration0 = duration;

-  tachLast = micros();
+  tachLast = current;

   //Calculate RPM
   //rpm = getRPM();
@@ -269,34 +311,7 @@

   //Advance the Mode
   ignitionMode = nextMode(ignitionMode);
-
-  //Set the delay period (Head of Mode)
-  switch(ignitionMode)
-  {
-    case OFF:
-      Timer1.stop();
-      return;
-    case DWELL:
-      //Charging Coil
-      Timer1.setPeriod(dwell);
-      Timer1.restart();
-      break;
-    case MF_WAIT:
-      //Waiting (MultiFire)
-      Timer1.setPeriod(multiDelay);
-      Timer1.restart();
-      break;
-    case MF_DWELL:
-      //Charging Coil
-      Timer1.setPeriod(dwell);
-      Timer1.restart();
-      break;
-    case WAIT:
-      //Waiting (Frequency)
-      Timer1.setPeriod(period);
-      Timer1.restart();
-      break;
-  }
+  updateTimer = true;
 }

 int nextMode(int mode)


Maybe Fixed SD Stuff

Maybe Fixed SD Stuff

--- FlightCode/FlightCode.ino
+++ FlightCode/FlightCode.ino
@@ -392,50 +392,49 @@

   if (sdWorkingFlag) { //Only actually work with the SD card if the SD card is working
     dataLog = SD.open("datalog.txt", FILE_WRITE); //Open the file datalog.txt in write mode
-    delay(5);
+    dataLog.flush();

     if (dataLog) { //log data only if the file opened properly
       dataLog.println(""); //Start a new line
-      delay(5);
       for (int c = 0; c < 2; c++) {
         dataLog.print(timeData[c]);
         dataLog.print(","); //Separate data entries by a comma
       }
-      delay(5);
+      dataLog.flush();
       for (int c = 0; c < 3; c++) {
         dataLog.print(accelData[c]);
         dataLog.print(",");
       }
-      delay(5);
+      dataLog.flush();
       for (int c = 0; c < 3; c++) {
         dataLog.print(gyroData[c]);
         dataLog.print(",");
       }
-      delay(5);
+      dataLog.flush();
       for (int c = 0; c < 3; c++) {
         dataLog.print(baroData[c]);
         dataLog.print(",");
       }
-      delay(5);
+     dataLog.flush();
       dataLog.print(gpsLatitude);
       dataLog.print(",");
       dataLog.print(gpsLatDirect);
       dataLog.print(",");
-      delay(5);
+      dataLog.flush();
       dataLog.print(gpsLongitude);
       dataLog.print(",");
       dataLog.print(gpsLonDirect);
       dataLog.print(",");
-      delay(5);
+      dataLog.flush();
       dataLog.print(gpsAltitude);
       dataLog.print(",");
       dataLog.print(gpsFix);
       dataLog.print(",");
-      delay(5);
+      dataLog.flush();
       dataLog.print(gpsFixQuality);
       dataLog.print(",");
       dataLog.print(batteryLevel);
-      delay(5);
+      dataLog.flush();

       dataLog.close(); //Close the file //Necessary decrease in baud rate to prevent program from crashing when trying to access the SD card (memory overflow?)
     } //Any value lower than 50 ms runs a serious risk of rapid program freeze


Update map and bit mask

Update map and bit mask

--- LightScale/LightScale.ino
+++ LightScale/LightScale.ino
@@ -1,6 +1,7 @@
 const byte SCALE_VALUE[] = { 0b00000100, 0b00001100, 0b00011100, 0b00111100};

-int senzor = A0;
+// fotorezistor - A1, termistor - A0
+int senzor = A1;

 void setup() {
   Serial.begin(9600);
@@ -13,10 +14,10 @@
   int light = analogRead(senzor);
   Serial.println(light);

-  int scale = map(light, 400, 800, 0, 3);
+  int scale = map(light, 300, 1000, 0, 3);
   Serial.println(scale);

-  PORTD = 0b00000000;
+  PORTD &= !0b00111100; // nastaveni vychoziho stavu - zhasnuto
   PORTD |= (0b00000100 << scale);
   // PORTD |= SCALE_VALUE[scale];


added the pins for the us sensor

added the pins for the us sensor

we need to tell OTTO where the trigger and echo pins are

--- OTTO_avoid/OTTO_avoid.ino
+++ OTTO_avoid/OTTO_avoid.ino
@@ -40,7 +40,7 @@
 ///////////////////////////////////////////////////////////////////
 void setup(){
   //Set the servo pins
-  Otto.init(PIN_YL,PIN_YR,PIN_RL,PIN_RR,true);
+  Otto.init(PIN_YL,PIN_YR,PIN_RL,PIN_RR,true, -1, -1, 8, 9);
   Otto.sing(S_connection); //Otto wake up!
   Otto.home();
   delay(50);


broke nightlight-test.ino but will fix soon

--- v2/nightlight-test/nightlight-test.ino
+++ v2/nightlight-test/nightlight-test.ino
@@ -9,6 +9,9 @@
 #define PIXEL_TYPE WS2812B

 Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL_COUNT, PIXEL_PIN, PIXEL_TYPE);
+
+// math values
+float pi = 3.14;

 // eyeball values
 int powerPin=D7;
@@ -20,6 +23,11 @@
 int lightmin = 0; // value of complete darkness
 int lightmax = 300; // value of ambiently bright light

+// brightness smoothing values, defined to start but subject to change
+int b = 90;
+int b0 = 90;
+int period = 6000;
+
 // timing values
 int sunrise = 429;
 int sunriseprebuffermin = 5;
@@ -60,33 +68,70 @@
   rbase=0;
   gbase=255;
   bbase=255;
-  int b = getBrightness();
+
+  int x = getBrightness();
+  int t = millis();
+
+  if (t%period == 0) {
+    b0=x;
+  }
+
+  b=b0+(x-b0)*t/period;

   int red=b*rbase/100;
   int grn=b*gbase/100;
   int blu=b*bbase/100;
   colorAll(strip.Color(b*red, b*grn, b*blu), 0);

-  Serial.print(red);
+  Serial.print(b);
   Serial.print("    ");
-  Serial.print(grn);
-  Serial.print("    ");
-  Serial.print(blu);
-  Serial.print("    ");
-  Serial.println(b);
-
-  delay(50);
-
-}
-
-int smooth(int current, int last, int lastavg, int t) {
-  // smooths out a variable by averaging this value over time t
-  // take modulo of millis with t
-  // if modulo not equal to 0 then can just add this value to the previous value and divide by 2
-  // also will keep a lastavg value so that can smooth between averages a bit.
-  // every interval t, we will reset lastavg and return avg
-  // every noninterval, we will return avg and average last.
-}
+  Serial.println(x);
+
+}
+
+/* whatever this doesn't work and is also dumb
+int *smooth(int x, int t, int avg, int period, int h0, int h2) {
+  // smooths out a variable by averaging this value over a certain period
+  // get the average for every time t and push the value towards that in a cosine curve over the next interval.
+  // variables needed:
+  // period = period
+  // t = time (millis)
+  // a = amplitude
+  // b = where the axis of the curve is centered-- should be h0+diff/2
+  // diff = difference between original point x0 and future point h2.
+  // h0 = starting point for curve, should be h at the end of last period
+  // h2 = ending point for curve, should be the avg from the last period
+  // h = current point, to be output.
+  // avg = the average value, to be kept for resetting h2.
+  // x = the current incoming value, to be added to the average.
+
+  // recalibrate b
+  int b = h0 + (h2-h0)/2;
+  // recalibrate a
+  int a = (h2-h0)/2;
+
+  int h = b + a*cos(pi*t/(period));
+
+  // get averages
+  avg = (avg+x)/2;
+
+  // find out if we're at interval
+
+  if (t % period == 0) {
+    // we are at interval
+    // replace h0
+    h0 = h2;
+    // replace h2
+    h2 = avg;
+    // replace avg
+    avg = x;
+  }
+
+  int r [4] = {h, avg, h0, h2};
+  return r;
+
+}
+*/

 float getBrightness() {
   // calibrates the brightness of the strip based on the incoming light


Clarification on delay logic

Clarification on delay logic

--- fan.ino
+++ fan.ino
@@ -17,8 +17,9 @@
 #define LCD_PIN_1 9 // Pins for LCD shift register control
 #define LCD_PIN_2 10
 #define LCD_PIN_3 11
-
-#define DELAY 150 // Delay in milliseconds the loop should run at, loop will be at least this long and give warning if longer
+//#define SIZE 10 - this is defined in Cabinet.h, number of data points gathered before averaging and calculations
+#define REFRESH 1500  // How long between each calculation/update. This can only be so short before updates become uneven
+#define DELAY REFRESH / SIZE // Delay in milliseconds the loop should run at, loop will be at least this long and give warning if longer

 LiquidCrystal595 lcd(LCD_PIN_1, LCD_PIN_2, LCD_PIN_3);

@@ -31,7 +32,7 @@

 void setup()
 {
-	Serial.begin(19200);
+	Serial.begin(9600);

 	pinMode(LED_BUILTIN, OUTPUT);
 	pinMode(C_PIN_L, OUTPUT);


added description to main sketch

added description to main sketch

--- sms_thermo/sms_thermo.ino
+++ sms_thermo/sms_thermo.ino
@@ -6,12 +6,13 @@
 #include <SoftwareSerial.h>
 #include <math.h>

-SoftwareSerial SIM900 (10, 11); // RX, TX
+SoftwareSerial SIM900 (10, 11); //SIM900 is connected to 10 & 11 PINs RX, TX
+#define ONE_WIRE_BUS 13         //Dallas OneWire sensors is connected to 13 PIN

 String phone_number[] = {"+79000000000"}; // Phone number for SMS notification
-int HighAlarmTemp[] = {28, 28, 28, 28};
-int DestroyAlarmTemp[] = {60, 60, 60, 60};
-int LowAlarmTemp[] = { -28, -28, -28, -28};
+int HighAlarmTemp[] = {28, 28, 28, 28};     // Highest temperature when user is notificated
+int DestroyAlarmTemp[] = {60, 60, 60, 60};  // Temperature used to make forecast
+int LowAlarmTemp[] = { -28, -28, -28, -28}; // Lowest thmperature when user is notificated

 String textForSMS;
 String last_alarm_time;
@@ -19,9 +20,9 @@
 int last_call_hour;
 int last_message_hour;

-int monPeriod1 = 300; // 5 минут
-int monPeriod2 = 600; // 10 минут
-int monPeriod3 = 1800;// 60 минут
+int monPeriod1 = 300; // 5 minutes
+int monPeriod2 = 600; // 10 minutes
+int monPeriod3 = 1800;// 60 minutes

 long count_t1, count_t2, count_t3;
@@ -32,15 +33,12 @@
 float tt1mTrend[4], tt2mTrend[4], tt3mTrend[4];
 int tt1m_avg[4], tt2m_avg[4], tt3m_avg[4];

-
 boolean call_done;
 boolean message_done;
 boolean armed;
 tmElements_t tm;

-#define ONE_WIRE_BUS 13
-
 OneWire oneWire(ONE_WIRE_BUS);
 DallasTemperature sensors(&oneWire);

@@ -49,20 +47,22 @@

 void setup()
 {
-  Serial.begin(9600);
+  Serial.begin(9600);   //Serial debug console initialize at 9k
   Wire.begin();
-  SIM900.begin(57600);
+
+  SIM900.begin(57600);  //SIM900 console initialize at 56k
   sensors.begin();

   startOfPeriod1 = now();
   startOfPeriod2 = now();
   startOfPeriod3 = now();
+
   call_done = false;
   armed = true;

-
+  // SIM900 serial console initialize and hanging off call (just for shure);
   delay(1000);
-  SIM900.println("AT");
+  SIM900.println("AT"); //Sending "AT" to modem for auto baud rate sensing;
   delay(1000);
   SIM900.println("ATH");
   delay(1000);
@@ -74,7 +74,7 @@
     Serial.println("RTC has set the system time");

-  // locate devices on the bus
+  // locate termal sensors on the bus
   Serial.print("Found ");
   Serial.print(sensors.getDeviceCount(), DEC);
   Serial.println(" devices.");
@@ -89,15 +89,15 @@

     Serial.print("Sensor #"); Serial.print(i);
     Serial.print(": "); Serial.println(getAddress(thermalSensor[i]));
-    sensors.setHighAlarmTemp (thermalSensor[i], HighAlarmTemp[i]);     // alarm when temp is higher than
-    sensors.setLowAlarmTemp(thermalSensor[i], LowAlarmTemp[i]);    // alarm when temp is lower than
-    Serial.print("Alarms:");  Serial.println(getAlarms(thermalSensor[i]));
+    sensors.setHighAlarmTemp (thermalSensor[i], HighAlarmTemp[i]);          // alarm when temp is higher than HighAlarmTemp[i]
+    sensors.setLowAlarmTemp(thermalSensor[i], LowAlarmTemp[i]);             // alarm when temp is lower than LowAlarmTemp[i]
+    Serial.print("Alarms:");  Serial.println(getAlarms(thermalSensor[i]));
     tt1m[i] = sensors.getTempC(thermalSensor[i]);
   }
 }

-// function to print a thermo-device address
+// get a termal-sensors device address
 String getAddress(DeviceAddress deviceAddress)
 {
   String datastring;
@@ -109,7 +109,7 @@
   return datastring;
 }

-
+// get a assigned alarms on devices
 String getAlarms(uint8_t deviceAddress[])
 {

@@ -120,6 +120,7 @@
   return datastring;
 }

+// get time in short format
 String getShortTimeString ()
 {
   String shtime;
@@ -131,6 +132,7 @@
   return shtime;
 }

+// update statistical information
 void updateStats(boolean debug)
 {

@@ -196,9 +198,8 @@
   }
   }
 }
-// main function to print information about a device
-
-
+
+// get information about a device
 String getData(DeviceAddress deviceAddress)
 {
   String datastring;
@@ -209,6 +210,7 @@
   return datastring;
 }

+// compose alarm message for SMS sending
 String makeMessage(int deviceid)
 {
   int timeToDeath =  makeForecast(deviceid);
@@ -229,7 +231,7 @@

 }

-
+// check for active alarms on device
 boolean checkAlarm(int deviceid)
 {

@@ -285,8 +287,8 @@
 }

-// phone
-int makeForecast(int deviceid) // расчет в секундах времени до достижения точки разрушения на основе тренда
+// forecast in seconds elasped time to DestroyAlarmTemp[]
+int makeForecast(int deviceid)
 {
   float forecastSeconds ;
   float delta_temp;
@@ -311,6 +313,7 @@
   return int(round(forecastSeconds));
 }

+// proceed a call just for make a loud sound in the middle of the "do not distrub" mode on smartphone
 boolean makecall(String number)
 {
   SIM900.print("ATD");
@@ -325,29 +328,27 @@
   return true;
 }

+// proceed a sending message to number
 boolean sendSMS(String number, String message)
-//boolean sendSMS()
-{
-  SIM900.print("AT+CMGF=1\r");                                                        // AT command to send SMS message
+{
+  SIM900.print("AT+CMGF=1\r");                              // AT command to send SMS message
   delay(100);
   SIM900.print("AT + CMGS = \"");
   SIM900.print(number);
   Serial.println(number);
   SIM900.println("\"");                                     // recipient's mobile number, in international format
   delay(100);
-  SIM900.println(message);        // message to send
+  SIM900.println(message);                                  // message to send
   Serial.println(message);
   delay(100);
-  SIM900.println((char)26);                       // End AT command with a ^Z, ASCII code 26
+  SIM900.println((char)26);                                 // End AT command with a ^Z, ASCII code 26
   delay(100);
   SIM900.println();
-  delay(30000);                                     // give module time to send SMS
+  delay(30000);                                             // give module time to send SMS
   return true;
 }

-
-
-
+// main loop
 void loop()
 {


Minor comment correction.

Minor comment correction.

--- examples/ConvertAndRead/ConvertAndRead.ino
+++ examples/ConvertAndRead/ConvertAndRead.ino
@@ -1,7 +1,7 @@
 #include <Wire.h>
 #include <MCP342x.h>

-/* Demonstate the use of convertAndRead().
+/* Demonstrate the use of convertAndRead().
  */


Fix a couple bugs

Fix a couple bugs

--- src/LCDPrint/LCDPrint.ino
+++ src/LCDPrint/LCDPrint.ino
@@ -10,7 +10,7 @@
 DeviceAddress red   = { 0x28, 0xFF, 0xA9, 0xB4, 0x62, 0x15, 0x03, 0x0C };
 DeviceAddress green = { 0x28, 0xFF, 0xF5, 0xB3, 0x62, 0x15, 0x03, 0x3E };

-LiquidCrystal lcd(0x27, 16, 2);
+LiquidCrystal_I2C lcd(0x27, 16, 2);

 const int delayTime = 500;
 const String topLine = "Derby Grammar";
@@ -19,11 +19,11 @@
   sensors.begin();
   sensors.setResolution(black, 10);
   sensors.setResolution(red, 10);
-  sensors.setResolution(green, 10;
+  sensors.setResolution(green, 10);
 }

 void loop() {
-  sensors.requestTemperatures():
+  sensors.requestTemperatures();

   printToLCD(black, "Black");
   delay(delayTime);
@@ -53,7 +53,7 @@
   if(sensorName.length() == 3) { //ie name is red
     lcd.print(sensorName + ":   " + tempC);
   } else {
-    lcd.print(sensorName + ": " + tempC;
+    lcd.print(sensorName + ": " + tempC);
   }

 }


Optimised output of set color (added 0x and leading zeros to hex-string)

--- examples/serial_control/serial_control.ino
+++ examples/serial_control/serial_control.ino
@@ -99,6 +99,12 @@
     uint32_t c = (uint32_t) strtol(&cmd.substring(2, cmd.length())[0], NULL, 16);
     ws2812fx.setColor(c);
     Serial.print(F("Set color to: "));
+    Serial.print(F("0x"));
+    if(ws2812fx.getColor() < 0x100000) { Serial.print(F("0")); }
+    if(ws2812fx.getColor() < 0x010000) { Serial.print(F("0")); }
+    if(ws2812fx.getColor() < 0x001000) { Serial.print(F("0")); }
+    if(ws2812fx.getColor() < 0x000100) { Serial.print(F("0")); }
+    if(ws2812fx.getColor() < 0x000010) { Serial.print(F("0")); }
     Serial.println(ws2812fx.getColor(), HEX);
   }


Changed execute-loop for multiple commands

ALT-codes are working now!

--- firmware/malduino_elite/malduino_elite.ino
+++ firmware/malduino_elite/malduino_elite.ino
@@ -2,7 +2,7 @@
 #include <SD.h>
 #include "Keyboard.h"

-//#define debug true // <-- uncomment to turn serial output on
+#define debug true // <-- uncomment to turn serial output on
 #define CSpin 4 //Chip-Select of the SD-Card reader
 #define buffersize 256

@@ -74,10 +74,14 @@
     }
     else if(equals(0,space,"REM")){}
     else{
-      do{
-        runCommand(0,space);
-        space = getSpace(space+1,bufSize);
-      }while(space >= 0);
+      runCommand(0,space);
+      while(space >= 0 && space < bufSize){
+        int nSpace = getSpace(space+1,bufSize);
+        if(nSpace == -1) nSpace = bufSize;
+        runCommand(space+1,nSpace);
+        space = nSpace;
+        delay(5);
+      }
     }
   }

@@ -88,7 +92,7 @@
 void runCommand(int s, int e){

   #ifdef debug
-    Serial.println("Press "+String(buf).substring(s,e));
+    Serial.println("Press '"+String(buf).substring(s,e)+"'");
   #endif

   if(s == e) Keyboard.press(buf[s]);
@@ -125,23 +129,23 @@
   else if(equals(s,e,"F11")) Keyboard.press(KEY_F11);
   else if(equals(s,e,"F12")) Keyboard.press(KEY_F12);

-  else if(equals(s,e,"NUM_0")) Keyboard.press(KEYPAD_0);
-  else if(equals(s,e,"NUM_1")) Keyboard.press(KEYPAD_1);
-  else if(equals(s,e,"NUM_2")) Keyboard.press(KEYPAD_2);
-  else if(equals(s,e,"NUM_3")) Keyboard.press(KEYPAD_3);
-  else if(equals(s,e,"NUM_4")) Keyboard.press(KEYPAD_4);
-  else if(equals(s,e,"NUM_5")) Keyboard.press(KEYPAD_5);
-  else if(equals(s,e,"NUM_6")) Keyboard.press(KEYPAD_6);
-  else if(equals(s,e,"NUM_7")) Keyboard.press(KEYPAD_7);
-  else if(equals(s,e,"NUM_8")) Keyboard.press(KEYPAD_8);
-  else if(equals(s,e,"NUM_9")) Keyboard.press(KEYPAD_9);
-  else if(equals(s,e,"NUM_ASTERIX")) Keyboard.press(KEYPAD_ASTERIX);
-  else if(equals(s,e,"NUM_ENTER")) Keyboard.press(KEYPAD_ENTER);
-  else if(equals(s,e,"NUM_Minus")) Keyboard.press(KEYPAD_MINUS);
-  else if(equals(s,e,"NUM_PERIOD")) Keyboard.press(KEYPAD_PERIOD);
-  else if(equals(s,e,"NUM_PLUS")) Keyboard.press(KEYPAD_PLUS);
-  else if(equals(s,e,"NUM_SLASH")) Keyboard.press(KEYPAD_SLASH);
-
+  else if(equals(s,e,"NUM_0")) Keyboard.write(KEYPAD_0);
+  else if(equals(s,e,"NUM_1")) Keyboard.write(KEYPAD_1);
+  else if(equals(s,e,"NUM_2")) Keyboard.write(KEYPAD_2);
+  else if(equals(s,e,"NUM_3")) Keyboard.write(KEYPAD_3);
+  else if(equals(s,e,"NUM_4")) Keyboard.write(KEYPAD_4);
+  else if(equals(s,e,"NUM_5")) Keyboard.write(KEYPAD_5);
+  else if(equals(s,e,"NUM_6")) Keyboard.write(KEYPAD_6);
+  else if(equals(s,e,"NUM_7")) Keyboard.write(KEYPAD_7);
+  else if(equals(s,e,"NUM_8")) Keyboard.write(KEYPAD_8);
+  else if(equals(s,e,"NUM_9")) Keyboard.write(KEYPAD_9);
+  else if(equals(s,e,"NUM_ASTERIX")) Keyboard.write(KEYPAD_ASTERIX);
+  else if(equals(s,e,"NUM_ENTER")) Keyboard.write(KEYPAD_ENTER);
+  else if(equals(s,e,"NUM_Minus")) Keyboard.write(KEYPAD_MINUS);
+  else if(equals(s,e,"NUM_PERIOD")) Keyboard.write(KEYPAD_PERIOD);
+  else if(equals(s,e,"NUM_PLUS")) Keyboard.write(KEYPAD_PLUS);
+  else if(equals(s,e,"NUM_SLASH")) Keyboard.write(KEYPAD_SLASH);
+
   //not implemented
   //else if(equals(s,e,"APP")) Keyboard.press();
   //else if(equals(s,e,"MENU")) Keyboard.press();


Code cleanup

Code cleanup

--- stairs/main.ino
+++ stairs/main.ino
@@ -280,8 +280,8 @@
     for (uint8_t led = 0; led < NUM_LEDS; led++) {
         angle = map(led, 0, NUM_LEDS-1, 0, 255);
         value = ease8InOutCubic(sin8(angle + an));
-        hue = map(value, 0, 255, 0, pots.hue);
-        value = map(value, 0, 255, 0, pots.val);
+        hue = map8(value, 0, pots.hue);
+        value = map8(value, 0, pots.val);
         leds[led] = CHSV(hue, pots.sat, value);
     }
 }


no message

no message

--- Arduino/Base/Base.ino
+++ Arduino/Base/Base.ino
@@ -22,6 +22,8 @@
 //Keeps track of the number of messages to be sent to the server
 int qCount = 0;

+int loopCount = 0;
+
 //These arrays are what hold the different parts of the messages to be sent to the server
 String nodeIds[QMAX];
 int spacesAvail[QMAX];
@@ -45,7 +47,7 @@
 {
   DEBUG_INIT(9600);
   xbee.begin(XBEE_BAUD); // Communicates with node
-  timeout_init(5000);//Starts timer for updates to be sent to server
+  //timeout_init(5000);//Starts timer for updates to be sent to server

   /*This starts the network connection*/
   while (!simcomm.isOn()) {
@@ -65,7 +67,7 @@
   This limits the sending of updates to the server by sending a maximum of 10 once every minute
   or once the array of requests reaches its maximum
   */
-  if(timeout_timedout() || qCount == QMAX){
+  if(loopCount > 9 || qCount == QMAX){
     if(qCount > 0){//will only send if q isn't empty
       DEBUG_PRINT(F("Made it to server update. Number of messages: "));
       DEBUG_PRINTLN(qCount);
@@ -84,7 +86,8 @@
       }
       qCount = 0;
     }
-    timeout_init(5000);
+    //timeout_init(5000);
+	loopCount = 0;
   }

   response = xcomm.getMessage();
@@ -161,43 +164,44 @@
 		}
         delay(2000);
     }
+	loopCount = loopCount + 1;
 }

-/*
-    Software Reset Functions
-*/
-
-/*
-    Enables the watchdog timer and starts an infinite loop so the uC restarts
-*/
-void soft_reset() {
-   wdt_enable(WDTO_15MS);
-   while(1) {};
-}
-
-/*
-    Disabled the watchdog timer as soon as possible on startup (before bootloader) so it doesn't continually restart chip.
-*/
-void wdt_init(void) __attribute__((naked)) __attribute__((section(".init3")));
-void wdt_init(void)
-{
-   MCUSR = 0;
-   wdt_disable();
-
-   return;
-}
-
-// Timeout Functions
-// ========================================
-unsigned long _timeout_end = 0;
-
-void timeout_init(int timeoutms) {
-    _timeout_end = millis() + timeoutms;
-}
-unsigned long timeout_remaining() {
-    return _timeout_end-millis();
-}
-bool timeout_timedout() {
-    return millis() > _timeout_end;
-}
-
+// /*
+    // Software Reset Functions
+// */
+
+// /*
+    // Enables the watchdog timer and starts an infinite loop so the uC restarts
+// */
+// void soft_reset() {
+   // wdt_enable(WDTO_15MS);
+   // while(1) {};
+// }
+
+// /*
+    // Disabled the watchdog timer as soon as possible on startup (before bootloader) so it doesn't continually restart chip.
+// */
+// void wdt_init(void) __attribute__((naked)) __attribute__((section(".init3")));
+// void wdt_init(void)
+// {
+   // MCUSR = 0;
+   // wdt_disable();
+
+   // return;
+// }
+
+// // Timeout Functions
+// // ========================================
+// unsigned long _timeout_end = 0;
+
+// void timeout_init(int timeoutms) {
+    // _timeout_end = millis() + timeoutms;
+// }
+// unsigned long timeout_remaining() {
+    // return _timeout_end-millis();
+// }
+// bool timeout_timedout() {
+    // return millis() > _timeout_end;
+// }
+


turn scenes into patterns

turn scenes into patterns

--- CocaCola/CocaCola.ino
+++ CocaCola/CocaCola.ino
@@ -1,12 +1,15 @@
 #include "Constants.h"

 void setup() {
+    randomSeed(analogRead(0));
+
     for (int i = 0; i < sizeof(Lights); i++) {
         pinMode(Lights[i], PATTERN_INITIALIZE);
     }
 }

 // )'(
+// Scenes

 void lettersAllOn() {
     for (int i = 0; i < 10; i++) {
@@ -62,25 +65,21 @@
     }
 }

-void loop() {
-    lettersAllOff();
+// Patterns

-    lettersOnLeftToRight();
-
+void classicBackground() {
     backgroundOnLeftToRight();
     delay(extended);
+    backgroundOffRightToLeft();
+}

-    backgroundOffRightToLeft();
-    delay(normal);
-
+void outsideInOnInsideOutOffBackground() {
     backgroundOnOutsideIn();
     delay(extended);
+    backgroundOffInsideOut();
+}

-    backgroundOffInsideOut();
-    delay(normal);
-
-    int repeat = random(5, 10);
-    // turn the letters off and on a bit
+void blinkLetters(int times) {
     for (int x = 0; x < repeat; x++) {
         lettersAllOff();
         delay(blinky);
@@ -88,12 +87,23 @@
         lettersAllOn();
         delay(blinky);
     }
+}

-    // and then turn it all off and wait
-    for (int i = 0; i < 10; i++) {
-        digitalWrite(letters[i], PATTERN_OFF);
-        delay(none);
-    }
+// Arduino loop
+
+void loop() {
+    lettersAllOff();
+
+    lettersOnLeftToRight();
+    classicBackground();
+    delay(normal);
+
+    outsideInOnInsideOutOffBackground();
+    delay(normal);
+
+    blinkLetters(random(5, 10));
+
+    lettersAllOff();

     delay(ish);
 }


change interrupt

change interrupt

--- simulator/sim/sim.ino
+++ simulator/sim/sim.ino
@@ -1,39 +1,64 @@

 //#define USE_RC

-#ifdef USE_RC
-#include <RcTrainer.h>
-#else
 #include <Arduino.h>
 #include <util/atomic.h>
-#endif
-

 #define NUM_AXES  4        // 9 axes, X, Y, Z, etc

 #ifndef USE_RC
-//#define PULSE_MIN   (750)       // minimum PWM pulse width which is considered valid
-//#define PULSE_MAX   (2250)      // maximum PWM pulse width which is considered valid
-
-#define PULSE_MIN   (760)       // minimum PWM pulse width which is considered valid
-#define PULSE_MAX   (2280)      // maximum PWM pulse width which is considered valid
-
-#else
- RcTrainer rc(1);
-#endif
+#define PULSE_MIN   (750)       // minimum PWM pulse width which is considered valid
+#define PULSE_MAX   (2250)      // maximum PWM pulse width which is considered valid

 //#define DEBUG

-uint16_t data[NUM_AXES] = {0, 0, 0, 0};//, 0, 0, 0, 0, 0};
-
-
-#ifndef USE_RC
+static volatile uint16_t data[NUM_AXES];
+static volatile uint16_t channels[NUM_AXES];
+
+
+typedef enum {
+   NULL_state=-1, NOT_SYNCHED_state, ACQUIRING_state, READY_state, FAILSAFE_state
+} decodeState_t;
+
+#define ACQUISITION_COUNT  8  // must have this many consecutive valid frames to transition to the ready state.
+static volatile byte Channel;      // number of channels detected so far in the frame (first channel is 1)
+static volatile byte NbrChannels; // the total number of channels detected in a complete frame
+static volatile decodeState_t State;         // this will be one of the following states:
+static volatile byte stateCount;         // counts the number of times this state has been repeated
+
+
+static void processSync(){
+// Sync was detected so reset the channel to 1 and update the system state
+  if(State == READY_state) {
+        if( Channel != NbrChannels){  // if the number of channels is unstable, go into failsafe
+              State = FAILSAFE_state;
+        }
+  }
+  else{
+    if(State == NOT_SYNCHED_state){
+            State = ACQUIRING_state;        // this is the first sync pulse, we need one more to fill the channel data array
+            stateCount = 0;
+      }
+      else if( State == ACQUIRING_state)      {
+         if(++stateCount > ACQUISITION_COUNT) {
+           State = READY_state;           // this is the second sync and all channel data is ok so flag that channel data is valid
+               NbrChannels = Channel; // save the number of channels detected
+           }
+    }
+      else if( State == FAILSAFE_state)      {
+            if(Channel == NbrChannels){  // did we get good data on all channels
+                 State = READY_state;
+           }
+      }
+  }
+  Channel = 0;       // reset the channel counter
+}
+
 static void interruptHandler()
 {
   uint16_t diff;
   static uint16_t now;
   static uint16_t last = 0;
-  static uint8_t chan = 0;
   #ifdef DEBUG
   static uint16_t min = 64000;
   static uint16_t max = 0;
@@ -43,78 +68,223 @@
   last = now;
   now = micros();
   diff = now - last;
-
-  if (diff > 3000 /*2700*/)  { // Per http://www.rcgroups.com/forums/showpost.php?p=21996147&postcount=3960 "So, if you use 2.5ms or higher as being the reset for the PPM stream start, you will be fine. I use 2.7ms just to be safe."
-    chan = 0;
-  }
-  else {
-    if (/*diff > PULSE_MIN && diff < PULSE_MAX && */chan < 4 /*NUM_AXES*/) {   // 750 to 2250 ms is our 'valid' channel range
-     #ifdef DEBUG
-
-     char buffer[7];         //the ASCII of the integer will be stored in this char array
-     itoa(chan,buffer,10);
-
-     char buffer2[7];
-     itoa(diff,buffer2,10);
-
-     char minbuff[7];
-     itoa(min,minbuff,10);
-     char maxbuff[7];
-     itoa(max,maxbuff,10);
-
-
-     if (diff > max) max = diff;
-     if (diff < min) min = diff;
-     Serial.print(buffer); Serial.print(":"); Serial.print(buffer2);Serial.print(":");
-     Serial.print(minbuff);Serial.print(":");Serial.println(maxbuff);
-     #endif
-
-
-     diff = map(diff, 1068, 1916, 0, 1500);
-     diff= constrain(diff, 0, 1500);
-     data[chan] = diff;
-    }
-    chan++;
-  }
+
+  if( diff > 2700){   // is the space between data big enough to be the SYNC
+     processSync();
+   } else if(Channel < NUM_AXES) {  // check if its a valid channel pulse and save it
+     if( (diff > PULSE_MIN && diff < PULSE_MAX ) ){ // check for valid channel data
+          data[++Channel] = diff;  // store pulse length as microsoeconds
+     }
+     else if(State == READY_state){
+       State = FAILSAFE_state;  // use fail safe values if input data invalid
+       Channel = 0; // reset the channel count
+     }
+   }
+
+//
+//  if (diff > 3000 /*2700*/)  { // Per http://www.rcgroups.com/forums/showpost.php?p=21996147&postcount=3960 "So, if you use 2.5ms or higher as being the reset for the PPM stream start, you will be fine. I use 2.7ms just to be safe."
+//    chan = 0;
+//  }
+//  else {
+//    if (diff > PULSE_MIN && diff < PULSE_MAX && chan < 4 /*NUM_AXES*/) {   // 750 to 2250 ms is our 'valid' channel range
+//     #ifdef DEBUG
+//
+//     char buffer[7];         //the ASCII of the integer will be stored in this char array
+//     itoa(chan,buffer,10);
+//
+//     char buffer2[7];
+//     itoa(diff,buffer2,10);
+//
+//     char minbuff[7];
+//     itoa(min,minbuff,10);
+//     char maxbuff[7];
+//     itoa(max,maxbuff,10);
+//
+//
+//     if (diff > max) max = diff;
+//     if (diff < min) min = diff;
+//     Serial.print(buffer); Serial.print(":"); Serial.print(buffer2);Serial.print(":");
+//     Serial.print(minbuff);Serial.print(":");Serial.println(maxbuff);
+//     #endif
+//
+//
+//     diff = map(diff, 1068, 1916, 0, 1500);
+//     diff= constrain(diff, 0, 1500);
+//     data[chan] = diff;
+//    }
+//    chan++;
+//  }
+
 }
 #endif

-uint16_t channels[NUM_AXES] = {0, 0, 0, 0};//, 0, 0, 0, 0, 0};
+

 void loop()
 {
-  #ifndef USE_RC
-  ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
-  {
-    memcpy(channels, data, sizeof(data));
-  }
-
- #else
-
- uint8_t i;
- for (i=0;i<6;i++){
-  uint16_t val = rc.getChannel(i);
-  channels[i] = val;
- }
- #endif
+    ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
+    {
+      if( (State == READY_state)){
+        memcpy((void*)channels, (void*)data, sizeof(data));
+      }
+    }
  #ifndef DEBUG
     Serial.write((uint8_t *)&channels, sizeof(channels));
   #endif
-
   delay(100);
 }

 void setup()
 {
+  memset((void*)channels,0,sizeof(channels));
+  memset((void*)data,0,sizeof(data));
+
   // Set up to listen on interrupt 1 which is digital input pin D3
   // See http://arduino.cc/en/Reference/attachInterrupt for mapping
   // interrupt number to pin number
-
-#ifndef USE_RC
   attachInterrupt(1, interruptHandler, RISING);
-#endif
   Serial.begin(115200);
   delay(200);
-
-}
-
+}
+/*
+/*
+* ServoDecode.cpp
+* this version for Mega only
+*/
+
+//#define icpPin            8         // this interrupt handler must use pin 8
+//#define TICKS_PER_uS      2          // number of timer ticks per microsecond
+//
+//
+//typedef enum {
+//   NULL_state=-1, NOT_SYNCHED_state, ACQUIRING_state, READY_state, FAILSAFE_state
+//} decodeState_t;
+//
+//#define NUM_AXES    8         // maximum number of channels we can store, don't increase this above 8
+//#define MIN_IN_PULSE_WIDTH (750 * TICKS_PER_uS) //a valid pulse must be at least 750us (note clock counts in 0.5 us ticks)
+//#define MAX_IN_PULSE_WIDTH (2250 * TICKS_PER_uS) //a valid pulse must be less than  2250us
+//#define SYNC_GAP_LEN      (3000 * TICKS_PER_uS) // we assume a space at least 3000us is sync (note clock counts in 0.5 us ticks)
+//#define FAILSAFE_PIN   13  // if defined, this will set the given pin high when invalid data is received
+//
+//
+//#define PULSE_START_ON_RISING_EDGE  0
+//#define PULSE_START_ON_FALLING_EDGE (1<<ICES4)
+//#define ACQUISITION_COUNT  8  // must have this many consecutive valid frames to transition to the ready state.
+//volatile byte pulseEnd = PULSE_START_ON_RISING_EDGE ; // default value
+//static volatile unsigned int data[ NUM_AXES + 1]; // array holding channel data width value in microseconds
+//static volatile unsigned int Failsafe[NUM_AXES + 1]; // array holding channel fail safe values
+//static volatile byte Channel;      // number of channels detected so far in the frame (first channel is 1)
+//static volatile byte NbrChannels; // the total number of channels detected in a complete frame
+//static volatile decodeState_t State;         // this will be one of the following states:
+//static volatile byte stateCount;         // counts the number of times this state has been repeated
+//
+//static void processSync(){
+//// Sync was detected so reset the channel to 1 and update the system state
+//  data[0] = ICR4 / TICKS_PER_uS;  // save the sync pulse duration for debugging
+//  if(State == READY_state) {
+//        if( Channel != NbrChannels){  // if the number of channels is unstable, go into failsafe
+//              State = FAILSAFE_state;
+//        }
+//  }
+//  else{
+//    if(State == NOT_SYNCHED_state){
+//            State = ACQUIRING_state;        // this is the first sync pulse, we need one more to fill the channel data array
+//            stateCount = 0;
+//      }
+//      else if( State == ACQUIRING_state)      {
+//         if(++stateCount > ACQUISITION_COUNT) {
+//           State = READY_state;           // this is the second sync and all channel data is ok so flag that channel data is valid
+//               NbrChannels = Channel; // save the number of channels detected
+//           }
+//    }
+//      else if( State == FAILSAFE_state)      {
+//            if(Channel == NbrChannels){  // did we get good data on all channels
+//                 State = READY_state;
+//           }
+//      }
+//  }
+//  Channel = 0;       // reset the channel counter
+//}
+//
+//ISR(TIMER4_OVF_vect){
+// if(State == READY_state){
+//   State = FAILSAFE_state;  // use fail safe values if signal lost
+//   Channel = 0; // reset the channel count
+// }
+//}
+//
+//ISR(TIMER4_CAPT_vect)
+//{
+// // we want to measure the time to the end of the pulse
+// if( (_SFR_BYTE(TCCR4B) & (1<<ICES4)) == pulseEnd ){
+//   TCNT1 = 0;       // reset the counter
+//   if(ICR4 >= SYNC_GAP_LEN){   // is the space between data big enough to be the SYNC
+//     processSync();
+//   }
+//   else if(Channel < NUM_AXES) {  // check if its a valid channel pulse and save it
+//     if( (ICR4 >= MIN_IN_PULSE_WIDTH)  && (ICR4 <= MAX_IN_PULSE_WIDTH) ){ // check for valid channel data
+//       data[++Channel] = ICR4 / TICKS_PER_uS;  // store pulse length as microsoeconds
+//     }
+//     else if(State == READY_state){
+//       State = FAILSAFE_state;  // use fail safe values if input data invalid
+//       Channel = 0; // reset the channel count
+//     }
+//   }
+// }
+//}
+//
+//ServoDecodeClass::ServoDecodeClass(){
+//}
+//
+//void ServoDecodeClass::begin(){
+// pinMode(icpPin,INPUT);
+// Channel = 0;
+// State = NOT_SYNCHED_state;
+// TCCR4A = 0x00;         // COM1A1=0, COM1A0=0 => Disconnect Pin OC from Timer/Counter  -- PWM11=0,PWM10=0 => PWM Operation disabled
+// TCCR4B = 0x02;         // 16MHz clock with prescaler means TCNT increments every .5 uS (cs11 bit set
+// TIMSK4 = _BV(ICIE4)|_BV (TOIE4);   // enable input capture and overflow interrupts for timer 1
+// for(byte chan = 1; chan <=  NUM_AXES; chan++)
+//       Failsafe[chan] = data[chan]= 1500; // set midpoint as default values for pulse and failsafe
+//}
+//
+//decodeState_t ServoDecodeClass::getState(){
+// return State;
+//}
+//
+//byte ServoDecodeClass::getChanCount(){
+// return NbrChannels;
+//}
+//
+//void  ServoDecodeClass::setFailsafe(byte chan, int value){
+//// pulse width to use if invalid data, value of 0 uses last valid data
+// if( (chan > 0) && (chan <=  NUM_AXES)  ) {
+//      Failsafe[chan] = value;
+// }
+//}
+//void  ServoDecodeClass::setFailsafe(){
+//// setFailsafe with no arguments sets failsafe for all channels to their current values
+//// usefull to capture current tx settings as failsafe values
+// if(State == READY_state)
+//   for(byte chan = 1; chan <=  NUM_AXES; chan++) {
+//       Failsafe[chan] = data[chan];
+//   }
+//}
+//
+//int ServoDecodeClass::GetChannelPulseWidth( uint8_t channel)
+//{
+// // this is the access function for channel data
+// int result = 0; // default value
+// if( channel <=  NUM_AXES)  {
+//    if( (State == FAILSAFE_state)&& (Failsafe[channel] > 0 ) )
+//        result = Failsafe[channel]; // return the channels failsafe value if set and State is Failsafe
+//      else if( (State == READY_state) || (State == FAILSAFE_state) ){
+//        cli();       //disable interrupts
+//        result =  data[channel] ;  // return the last valid pulse width for this channel
+//        sei(); // enable interrupts
+//      }
+// }
+// return result;
+//}
+//// make one instance for the user
+//ServoDecodeClass ServoDecode = ServoDecodeClass() ;
+


Bumped the version to v0.01

Bumped the version to v0.01

--- src/BLuB.ino
+++ src/BLuB.ino
@@ -7,9 +7,13 @@
 ////////////////////////////////////////////////////////////////////////////////
 // Version history
 //
+// v0.01  2013-June-19  Line entry, line editing
+//			cmds: help, mem, new, list
+//			      EEPROM: elist, eload, esave, enew
+//
 // v0.00  2013-June-18  Initial test versions

-#define kBLuBVersion	"v0.00  2013-June-18  yorgle@gmail.com"
+#define kBLuBVersion	"v0.01  2013-June-19  yorgle@gmail.com"

 ////////////////////////////////////////////////////////////////////////////////
@@ -207,7 +211,9 @@

 void cmd_list( void )
 {
-	Serial.println( programRam );
+	Serial.println( "" );		// newline before
+	Serial.print( programRam );	// dump it all out
+	// no need for println, since program ram ends with newline
 }

 void cmd_run( void )
@@ -234,6 +240,7 @@

 #define kBufLen (16)
 char buffer[16];
+

 int latoi( char * buf )
 {
@@ -261,6 +268,7 @@
 	return v;
 }

+
 void cmd_removeLine( int lineNo, bool verbose )
 {
 	char *bufc = programRam;
@@ -308,6 +316,60 @@
 		return;
 	}

+	// find the appropriate location to insert it
+
+	int lineNo = latoi( theLine );
+
+	char *bufc = programRam;
+	char *bufn = 0;
+
+	while( *bufc ) {
+		// if we're looking at '\0', error line not found, return
+	    	if( *bufc == '\0' ) break;
+
+		// check the current pointer for the matching line
+		int cline = latoi( bufc );
+
+		// find the end point
+		bufn = bufc;
+		while( *bufn != '\0' && *bufn != '\n' ) bufn++;
+
+		// if it matches,
+		if( cline > lineNo )
+		{
+			// shove the current data out to the end.
+			int moveSz = strlen( bufc ) +1;
+			char * srcpos = bufc + moveSz;
+			char * dstpos = bufc + newSz + moveSz +1;
+
+			do {
+				*dstpos = *srcpos;
+				srcpos--;
+				dstpos--;
+			} while( srcpos != bufc );
+			*dstpos = *srcpos; // copy over the last one...
+
+			// and insert the new content
+			dstpos = bufc;
+			srcpos = theLine;
+
+			while( *srcpos != '\0' ) {
+				*dstpos = *srcpos;
+				dstpos++;
+				srcpos++;
+			}
+			*dstpos = '\n';
+
+			return;
+		}
+
+		// if not, move looking pointer to next line
+		bufc = bufn;
+		bufc++; // move past the newline
+	}
+	// shove the content out the length of the new string
+	// copy the data in
+
 	// append it on the end for now
 	strcat( programRam, theLine );
 	strcat( programRam, "\n" );	// new line
@@ -333,6 +395,7 @@

 	else if( !strcmp( linebuf, "new" )) { cmd_new(); }
 	else if( !strcmp( linebuf, "list" )) { cmd_list(); }
+	else if( !strcmp( linebuf, "help" )) { cmd_help(); }

 	else if( !strcmp( linebuf, "enew" )) { cmd_enew(); }
 	else if( !strcmp( linebuf, "elist" )) { cmd_elist(); }


Changed default brightness and comment

Changed default brightness and comment

--- AnimatedGIFs.ino
+++ AnimatedGIFs.ino
@@ -74,7 +74,9 @@
 // Declared in GIFParseFunctions.cpp
 extern int processGIFFile(const char * pathname);

-const int defaultBrightness = 50;
+// range 0-255
+const int defaultBrightness = 255;
+
 const rgb24 COLOR_BLACK = {
     0, 0, 0 };

@@ -84,7 +86,7 @@
 // Smart Matrix instance
 SmartMatrix matrix;

-// Chip select for SD card on my hardware
+// Chip select for SD card on the SmartMatrix Shield
 #define SD_CS 15

 #define GIF_DIRECTORY "/gifs/"


[Firmware] Add current ssid to scan response

--- firmware/lm-wifilamp/x61_server_api.ino
+++ firmware/lm-wifilamp/x61_server_api.ino
@@ -162,7 +162,10 @@
     n = WiFi.scanComplete();
   }
   if (n == -1) {
-    server.send(200, "text/json", "{\"inprogress\":true,\"networks\":[]}\n");
+    String response = "{\"inprogress\":true,\"current\":\"";
+    response += wifiConfig.ssid;
+    response += "\",\"networks\":[]}\n";
+    server.send(200, "text/json", response);
     return;
   }

@@ -170,7 +173,9 @@
     n = 0;
   }

-  String response = "{\"inprogress\":false,\"networks\":[";
+  String response = "{\"inprogress\":false,\"current\":\"";
+  response += wifiConfig.ssid;
+  response += "\",\"networks\":[";
   for (int16_t i = 0; i < n; i++) {
     if (i) response += ',';
     response += "{\"ssid\":\"";


Fall back to JSON export - keep getting weird lines that are not inserted

--- WxShield2/WxShield2.ino
+++ WxShield2/WxShield2.ino
@@ -68,6 +68,6 @@

 void loop() {
   struct frame data = fetch();
-  sqlinsert(data);
+  json(data);
   delay(1000);
 }


Some refactorization + added LED when reading sensor

--- Particle/THDweeter/src/THDweeter.ino
+++ Particle/THDweeter/src/THDweeter.ino
@@ -1,121 +1,97 @@
-/*
+/*************************************************************************
  * Project THDweeter
- * Description:
- * Author:
- * Date:
- */
- // This #include statement was automatically added by the Particle IDE.
- #include "HttpClient/HttpClient.h"
+ * Description: temperature & umidity dweeter
+ * Author: Giuseppe Lo Presti
+ *
+ * Changelog:
+ * v1.0 - 1-05-2017: initial revision from https://www.hackster.io/shaiss
+ * v2.0 - 6-05-2017: added wifi sleep + readout button + refactorization
+ *
+ *************************************************************************/

- // This #include statement was automatically added by the Particle IDE.
- #include "Adafruit_DHT/Adafruit_DHT.h"
+// This #include statement was automatically added by the Particle IDE.
+#include "HttpClient/HttpClient.h"

- // Example testing sketch for various DHT humidity/temperature sensors
- // Written by ladyada, public domain
+// This #include statement was automatically added by the Particle IDE.
+#include "Adafruit_DHT/Adafruit_DHT.h"

- #define DHTPIN 2     // what pin we're connected to
+#define DHTPIN 2        // what pin we're connected to
+#define DHTTYPE DHT22		// DHT 22 (AM2302)

- // Uncomment whatever type you're using!
- //#define DHTTYPE DHT11		// DHT 11
- #define DHTTYPE DHT22		// DHT 22 (AM2302)
- //#define DHTTYPE DHT21		// DHT 21 (AM2301)
+int led = D7;           // internal LED
+int pushButton = D5;    // Push button is connected to D5

- // Connect pin 1 (on the left) of the sensor to +5V
- // Connect pin 2 of the sensor to whatever your DHTPIN is
- // Connect pin 4 (on the right) of the sensor to GROUND
- // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor
+// Connect pin 1 (on the left) of the sensor to +5V
+// Connect pin 2 of the sensor to whatever your DHTPIN is
+// Connect pin 4 (on the right) of the sensor to GROUND
+// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

- DHT dht(DHTPIN, DHTTYPE);
+DHT dht(DHTPIN, DHTTYPE);
+HttpClient http;

- /**
- * Declaring the variables.
- */
- unsigned int nextTime = 0;    // Next time to contact the server
- HttpClient http;
+// Headers currently need to be set at init, useful for API keys etc.
+http_header_t headers[] = {
+  //  { "Content-Type", "application/json" },
+  //  { "Accept" , "application/json" },
+  { "Accept" , "*/*"},
+  { NULL, NULL } // NOTE: Always terminate headers will NULL
+};

- // Headers currently need to be set at init, useful for API keys etc.
- http_header_t headers[] = {
-     //  { "Content-Type", "application/json" },
-     //  { "Accept" , "application/json" },
-     { "Accept" , "*/*"},
-     { NULL, NULL } // NOTE: Always terminate headers will NULL
- };
+http_request_t request;
+http_response_t response;

- http_request_t request;
- http_response_t response;
-
- void setup() {
+void setup() {
  	Particle.publish("DEBUG","DHT22 veranda");
  	dht.begin();
- }
+  pinMode(led, OUTPUT);               // D7 pin is output
+  pinMode(pushButton, INPUT_PULLUP);  // input with an internal pull-up resistor
+}

- void loop() {
- // Wait a minute between measurements.
- 	delay(60000);
+void readout() {
+  // First wake up WiFi
+  //Wifi.on();
+  // Switch on LED to signal we're reading out the sensor data
+  digitalWrite(led, HIGH);
+  // Reading temperature or humidity takes about 250 milliseconds!
+  // Sensor readings may also be up to 2 seconds 'old' (its a
+  // very slow sensor)
+ 	float h = dht.getHumidity();
+  // Read temperature as Celsius
+ 	float t = dht.getTempCelcius();

- // Reading temperature or humidity takes about 250 milliseconds!
- // Sensor readings may also be up to 2 seconds 'old' (its a
- // very slow sensor)
- 	float h = dht.getHumidity();
- // Read temperature as Celsius
- 	float t = dht.getTempCelcius();
- // Read temperature as Farenheit
- 	float f = dht.getTempFarenheit();
+  // Check if any reads failed and exit early (to try again).
+ 	if (isnan(h) || isnan(t)) {
+    Particle.publish("DEBUG","Failed to read from DHT sensor!");
+ 	  return;
+ 	}
+ 	//float hi = dht.getHeatIndex();
+ 	//float dp = dht.getDewPoint();

- // Check if any reads failed and exit early (to try again).
- 	if (isnan(h) || isnan(t)) {
- 		Particle.publish("DEBUG","Failed to read from DHT sensor!");
- 		return;
- 	}
-
- // Compute heat index
- // Must send in temp in Fahrenheit!
- 	float hi = dht.getHeatIndex();
- 	float dp = dht.getDewPoint();
- 	float k = dht.getTempKelvin();
-
- 	//Serial.print("Humid: ");
- 	//Serial.print(h);
- 	//Serial.print("% - ");
- 	//Serial.print("Temp: ");
- 	//Serial.print(t);
- 	//Serial.print("*C ");
- 	//Serial.print(f);
- 	//Serial.print("*F ");
- 	//Serial.print(k);
- 	//Serial.print("*K - ");
- 	//Serial.print("DewP: ");
- 	//Serial.print(dp);
- 	//Serial.print("*C - ");
- 	//Serial.print("HeatI: ");
- 	//Serial.print(hi);
- 	//Serial.println("*C");
- 	//Serial.println(Time.timeStr());
-
- 	//cast floats to string
+ 	// cast floats to string
  	String st(t, 2);
  	String sh(h, 2);
-
- 	//pblish tests
- 	//Spark.publish("faranheight",f,60,PRIVATE);
- 	Particle.publish("TEMP",st);
- 	Particle.publish("HUMIDITY",sh);
+ 	// publish data
+ 	Particle.publish("TEMP", st);
+ 	Particle.publish("HUMIDITY", sh);

  	//post to dweet
  	request.hostname = "dweet.io";
-     request.port = 80;
-     request.path = "/dweet/for/glp_photon_verandath?temp=" + st + "&humidity=" + sh;
+  request.port = 80;
+  request.path = "/dweet/for/glp_photon_vth?temp=" + st + "&humidity=" + sh + "&time=" + Time.timeStr();
+ 	Particle.publish("DEBUG",request.body);
+  http.get(request, response, headers);
+  //Particle.publish("DEBUG",response.status);
+  Particle.publish("DEBUG",response.body);

- 	//json body doesn't work
- 	//request.body = "{\"humidity\":\"43%\",\"temp\":\"45f\"}"; //"{\"key\":\"value\"}";
+  // Done, switch off LED
+  digitalWrite(led, LOW);
+  // and turn off wifi
+  //Wifi.off()
+ }

- 	Particle.publish("DEBUG",request.body);
-
-     // Get request
-     http.get(request, response, headers);
-     //Spark.publish("DEBUG","Application Response status: ");
-     //Particle.publish("DEBUG",response.status);
-
-     //Spark.publish("DEBUG","Application HTTP Response Body: ");
-     Particle.publish("DEBUG",response.body);
- }
+void loop() {
+  // Wait a minute between measurements.
+  delay(10000);
+  // read and publish sensor data
+  readout();
+}


Changed Call Sign

Changed Call Sign

--- Tracking/habduino_v4/habduino_v4.ino
+++ Tracking/habduino_v4/habduino_v4.ino
@@ -1,16 +1,81 @@
+/*
+ HABDuino Tracker
+ http://www.habduino.org
+ (c) Anthony Stirk M0UPU
+
+ March 2015 Version 4.0.0
+
+ This is for the Version 4 Habduino Hardware.
+
+ Credits :
+
+ Interrupt Driven RTTY Code : Evolved from Rob Harrison's RTTY Code.
+ Thanks to :  http://www.engblaze.com/microcontroller-tutorial-avr-and-arduino-timer-interrupts/
+ http://gammon.com.au/power
+
+ Suggestion to lock variables when making the telemetry string & Compare match register calculation from Phil Heron.
+ APRS Code mainly by Phil Heron MI0VIM
+
+ GPS Code modified from jonsowman and Joey flight computer CUSF
+ https://github.com/cuspaceflight/joey-m/tree/master/firmware
+
+ Thanks to :
+
+ Phil Heron
+ James Coxon
+ Dave Akerman
+
+ The UKHAS Community http://ukhas.org.uk
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program 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 General Public License for more details.
+
+ See <http://www.gnu.org/licenses/>.
+
+ The Habduino kit is supplied as is with no guarantees of performance or operation. Although the HABDuino
+ is designed for short-term Near Space operation, the conditions may exceed the specification of individual
+ components which may fail to operate correctly because of low temperatures or pressures of increased
+ radiation levels. We have no control over the effectiveness of your payload design especially the
+ temperature and electromagnetic conditions  within, thus we make no warrnaty express or implied as to
+ the ability of our products to operate to any degree of effectiveness when used in your application.
+
+ If you decide to use this product under a balloon it’s your responsibility to ensure you comply with the
+ local legislation and laws regarding meteorological balloon launching and radio transmission in the air.
+
+ The Radiometrix MTX2 434Mhz is NOT license exempt in the United States of America and does need a radio
+ amateur license.  Use of APRS requires a radio amateur license in all countries and a number of countries
+ don’t permit the airborne use of APRS under any circumstances.
+ The Habduino cannot do APRS without an addon Radiometrix HX1 module.
+
+ The hardware design & code for Habduino is released under a Creative Commons License 3.0 Attribution-ShareAlike License :
+ See : http://creativecommons.org/licenses/by-sa/3.0/
+ It is YOUR responsibility to ensure this kit is used safely please review the safety section.
+
+ The latest code is available here : https://github.com/HABduino/HABduino
+
+
+ */
+
 /* BITS YOU WANT TO AMEND */

 #define MTX2_FREQ 434.485 // format 434.XXX
-char callsign[9] = "HABDUINO";  // MAX 9 CHARACTERS!!
-
-/* DON"T change unless you know what you are doing */
+char callsign[9] = "WP4NJQ";  // MAX 9 CHARACTERS!!
+
+/* BELOW HERE YOU PROBABLY DON'T WANT TO BE CHANGING STUFF */

 #include <util/crc16.h>
 #include <avr/io.h>
 #include <avr/interrupt.h>
 #include <avr/pgmspace.h>
-#include <OneWire/OneWire.h>
-#include <DallasTemperature/DallasTemperature.h>
+#include <OneWire.h>
+#include <DallasTemperature.h>
 #include <SoftwareSerial.h>
 #include "ax25modem.h"
 static const uint8_t PROGMEM _sine_table[] = {
@@ -92,30 +157,6 @@
 char comment[3]={
   ' ', ' ', '\0'};

-void setupGPS() {
-  // Turning off all GPS NMEA strings apart on the uBlox module
-  // Taken from Project Swift (rather than the old way of sending ascii text)
-  int gps_set_sucess=0;
-  uint8_t setNMEAoff[] = {
-    0xB5, 0x62, 0x06, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x00, 0xD0, 0x08, 0x00, 0x00, 0x80, 0x25, 0x00, 0x00, 0x07, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA0, 0xA9           };
-  sendUBX(setNMEAoff, sizeof(setNMEAoff)/sizeof(uint8_t));
-  while(!gps_set_sucess)
-  {
-    sendUBX(setNMEAoff, sizeof(setNMEAoff)/sizeof(uint8_t));
-    gps_set_sucess=getUBX_ACK(setNMEAoff);
-    if(!gps_set_sucess)
-    {
-      blinkled(2);
-    }
-  }
-  wait(500);
-  setGPS_GNSS();
-  wait(500);
-  setGPS_DynamicModel6();
-  wait(500);
-  setGps_MaxPerformanceMode();
-  wait(500);
-}

 void setup()  {
   pinMode(MTX2_TXD, OUTPUT);
@@ -393,6 +434,30 @@
     Serial.write(MSG[i]);
   }
 }
+void setupGPS() {
+  // Turning off all GPS NMEA strings apart on the uBlox module
+  // Taken from Project Swift (rather than the old way of sending ascii text)
+  int gps_set_sucess=0;
+  uint8_t setNMEAoff[] = {
+    0xB5, 0x62, 0x06, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x00, 0xD0, 0x08, 0x00, 0x00, 0x80, 0x25, 0x00, 0x00, 0x07, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA0, 0xA9           };
+  sendUBX(setNMEAoff, sizeof(setNMEAoff)/sizeof(uint8_t));
+  while(!gps_set_sucess)
+  {
+    sendUBX(setNMEAoff, sizeof(setNMEAoff)/sizeof(uint8_t));
+    gps_set_sucess=getUBX_ACK(setNMEAoff);
+    if(!gps_set_sucess)
+    {
+      blinkled(2);
+    }
+  }
+  wait(500);
+  setGPS_GNSS();
+  wait(500);
+  setGPS_DynamicModel6();
+  wait(500);
+  setGps_MaxPerformanceMode();
+  wait(500);
+}

 void setGPS_DynamicModel6()
 {
@@ -819,7 +884,7 @@
   {
     ax25_frame(
     APRS_CALLSIGN, APRS_SSID,
-    "APRS", 0,
+    "WP4NJQ", 0,
     //0, 0, 0, 0,
     "WIDE1", 1, "WIDE2",1,
     //"WIDE2", 1,
@@ -1025,3 +1090,20 @@

   return(x);
 }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+


Added nconf and linked configuration from both the Arduino and the nconf file to be viewable in the cockpit. Added sliders that are databound to the settings data via knockout. Still read-only at this point.  Added events to signal when setting data is being passed.

--- OpenROV/OpenROV.ino
+++ OpenROV/OpenROV.ino
@@ -106,6 +106,11 @@
     else if (cmd.cmp("stop")) {
       motors.stop();
     }
+    else if (cmd.cmp("reportSetting")) {
+      Serial.print("*settings:");
+      Serial.print("smoothingIncriment|");
+      Serial.print(String(smoothingIncriment) + ";");
+    }
     else {
       motors.stop();
     }


refactor firmware and fix possible pitfall within the time step management

--- arduino/main.ino
+++ arduino/main.ino
@@ -13,35 +13,38 @@
 #include <EEPROM.h>

 #define FRAME_SIZE 5 // Frame size in byte
-#define MAX_FRAME_COUNT 200 // Maximum amount of frames, that can be saved
+#define MAX_FRAME_COUNT 200 // Maximum amount of frames, that can be stored
 #define STEP_DURATION 100 // Time of an animation step
 #define LINE_AMOUNT 5
 #define LINE_OFFSET 1 // It was easier not to connect Q0, so the first line is connected to Q1

-// Pin connected to ST_CP of 74HC595
-int latchPin = 8;
-// Pin connected to SH_CP of 74HC595
-int clockPin = 12;
-// Pin connected to DS of 74HC595
-int dataPin = 11;
+// === Animation management ===
+void loadFrame(int i);
+void restartAnimation();

-// Function definitions
-// Transmission
+// Current frame state
+unsigned short curFrameDuration = 0; // Left duration of the current frame
+unsigned byte curFrame[LINE_AMOUNT]; // Current frame (one byte is one line)
+unsigned byte curLine = 0; // Id of the line, that should be currently on
+unsigned short nextFrameId = 0; // Id of the next frame
+
+// Timestamp of the last step
+unsigned long lastStepTime = 0;
+
+// Pins
+int latchPin = 8; // Pin connected to ST_CP of 74HC595
+int clockPin = 12; // Pin connected to SH_CP of 74HC595
+int dataPin = 11; // Pin connected to DS of 74HC595
+// ========
+
+// === Transmission ===
 void processRequest();
 void processPing();
 void processFrameTransmission();
 // Pin to indicate whether transmission is in progress
 int infoPin = 13;
+// ========

-// Animation management
-void loadFrame(int i);
-void restartAnimation();
-// Current frame
-unsigned short curFrameDuration = 0; // Left duration of the current frame
-unsigned byte curFrame[LINE_AMOUNT]; // Current frame (one byte is one line)
-unsigned byte curLine = 0; // Id of the line, that should be currently on
-unsigned short nextFrameId = 0; // Id of the next frame
-unsigned long lastStepTime = 0; // Timestamp of the last step

 void setup() {
     // Animation setup
@@ -56,12 +59,6 @@

 void loop() {

-    // Determine end of step
-    if ((millis() - lastStepTime) >= STEP_DURATION || (millis() - lastStepTime) < 0) {
-        lastStepTime = millis();
-        curFrameDuration--;
-    }
-
     // Load next frame, when it's over
     if (curFrameDuration < 1) {
         loadFrame(nextFrameId);
@@ -75,6 +72,12 @@
     digitalWrite(latchPin, HIGH);

     curLine = (curLine + 1) % LINE_AMOUNT;
+
+    // Determine end of step
+    if ((millis() - lastStepTime) >= STEP_DURATION || (millis() - lastStepTime) < 0) {
+        lastStepTime = millis();
+        curFrameDuration--;
+    }
 }

 // Serial Event callback


Updated TPSscaler to use a Cubic Root scale

--- TPSscaler.ino
+++ TPSscaler.ino
@@ -1,25 +1,68 @@
 #define INPUT_PIN A0
 #define OUTPUT_PIN 6
-#define LOWER 100
+
+//bounds for the output - changing lower changes the output degree of 0
+//                      - changing upper changes the output degree of MAX_TPS
+#define LOWER 85
+#define UPPER 220
+
+// 100 -> 90 : 23 -> 17
+// 90 -> 80 : 17 - 13
+
+/*  Values: end of 4/7/2017
+ *   LOWER: 100, UPPER: 240
+ *   LOWER: 85, UPPER: 240 - idle
+ *  Test cases:
+ *    Lower|Upper
+ *    100|245
+ *    100|250
+ *    100|251
+ *    100|252
+ *    100|253
+ *    100|254
+ */
+
+#define MAX_TPS_IN 800
+#define MIN_TPS_IN 100
+#define POWER 0.333
+

 //0.52-4.7 -> 3-235
 //0.55-3.9 -> 3-195
+
+unsigned char table[MAX_TPS_IN-MIN_TPS_IN+1];

 void setup() {
   Serial.begin(115200);
   pinMode(INPUT_PIN, INPUT);
   pinMode(OUTPUT_PIN, OUTPUT);
-//  setPwmFrequency(6,1);
+  for (int i = 0; i < MAX_TPS_IN-MIN_TPS_IN+1; i++) {
+    float x = (((float)i)/(MAX_TPS_IN-MIN_TPS_IN+1));
+    //x = sqrt(x);
+    x = pow(x,POWER);
+    x = x * (UPPER-LOWER);
+    unsigned char res = ((unsigned char)x) + LOWER;
+    if (res > UPPER) res = UPPER;
+    if (res < LOWER) res = LOWER;
+    table[i] = res;
+    Serial.print(i+MIN_TPS_IN);
+    Serial.print(" ");
+    Serial.println(table[i]);
+  }
 }

 void loop() {
   int v_in = analogRead(INPUT_PIN);
-  int v_out = map(v_in, 0, 800, LOWER, 240);
-  if (v_out > 240) v_out = 240;
-  if (v_out < LOWER) v_out = LOWER
+  int idx = v_in-MIN_TPS_IN;
+  if (idx < 0) idx = 0;
+  if (idx > MAX_TPS_IN-MIN_TPS_IN) idx = MAX_TPS_IN-MIN_TPS_IN;
+  int v_out = table[idx];
+  //int v_out = map(v_in, MIN_TPS_IN, MAX_TPS_IN, LOWER, UPPER);
+  //if (v_out > UPPER) v_out = UPPER;
+  //if (v_out < LOWER) v_out = LOWER;
   //Serial.print(v_in);
   //Serial.print(" ");
   //Serial.println(v_out);
   analogWrite(OUTPUT_PIN, v_out);
-  //delay(100);
+  //delay(200);
 }