read encoder button for pause, blink encoder (needs forked encoder library)

--- musicbox/musicbox.ino
+++ musicbox/musicbox.ino
@@ -6,6 +6,7 @@
      on key press play a music file from the micro SD card from a specific folder and blink the respective key (/)
      on pressing the same key or when playback stops jump to the next file in the folder, until all music is played (/)
      read the rotary decoder to change the volume, the maximum volume can be configured (/)
+     press the rotary decoder to pause/resume (/)
      detect when a headphone is plugged in and mute the amplifier for the internal speakers (/)
      switch the music box off automatically after an idle period

@@ -29,6 +30,7 @@
 // Delays [ms]
 #define IDLE_PAUSE    2000
 #define BLINK_DELAY    100
+#define PAUSE_DELAY   1000
 #define READ_DELAY      50
 #define IDLE_TIMEOUT (1000L * 60L)
 #define ROLLOVER_GAP (1000L * 60L * 60L)
@@ -39,8 +41,8 @@
 #define BRIGHTNESS_PLAYING   10

 // Trellis setup
-#define NUMKEYS 4
-#define INT_PIN 1
+#define NUMKEYS            4
+#define INT_PIN            1

 // Feather/Wing pin setup
 #define MUSIC_RESET_PIN   12     // VS1053 reset pin (not used!)
@@ -57,7 +59,7 @@
 // Rotary Encoder with Switch and LED
 #define ENCODER_A           A0
 #define ENCODER_B           A1
-#define ENCODER_SWITCH      A2
+#define ENCODER_SWITCH_PIN  A2
 #define GREEN_LED_PIN       A4
 #define BLUE_LED_PIN        A5

@@ -66,7 +68,8 @@
 #define IDLE_TURN_OFF   2
 #define IDLE_WAIT_OFF   3
 #define PLAY_SELECTED   4
-#define TIMEOUT_WAIT    5
+#define PLAY_PAUSED     5
+#define TIMEOUT_WAIT    6

 // Volume
 #define VOLUME_MIN       130    // max. 254 moderation
@@ -80,7 +83,7 @@

 Adafruit_Trellis trellis = Adafruit_Trellis();
 Adafruit_VS1053_FilePlayer player = Adafruit_VS1053_FilePlayer(MUSIC_RESET_PIN, MUSIC_CS_PIN, MUSIC_DCS_PIN, MUSIC_DREQ_PIN, CARD_CS_PIN);
-ClickEncoder encoder = ClickEncoder(ENCODER_A, ENCODER_B, ENCODER_SWITCH, 2, LOW);
+ClickEncoder encoder = ClickEncoder(ENCODER_A, ENCODER_B, ENCODER_SWITCH_PIN, 2, LOW, HIGH);

 unsigned long nextReadTick = millis() + 1;
@@ -262,6 +265,11 @@
     trellis.writeDisplay();
     state = IDLE_LIGHT_UP;
     return BLINK_DELAY;
+
+  // Blink in pause mode
+  } else if (state == PLAY_PAUSED) {
+    blinkLED(BLUE_LED_PIN);
+    return PAUSE_DELAY;
   }
 }

@@ -289,9 +297,13 @@
 }

 void onWatchdogPing() {
-  digitalWrite(BLUE_LED_PIN, LOW); // LED on
+  blinkLED(BLUE_LED_PIN);
+}
+
+void blinkLED(int pin) {
+  digitalWrite(pin, LOW); // LED on
   delay(1);
-  digitalWrite(BLUE_LED_PIN, HIGH); // LED off
+  digitalWrite(pin, HIGH); // LED off
 }

 void trellisIsr() {
@@ -335,6 +347,16 @@
     int encoderChange = encoder.getValue() * VOLUME_DIRECTION;
     if (encoderChange != 0) {
       changeVolume(encoderChange);
+    }
+  }
+
+  // Read encoder switch
+  ClickEncoder::Button button = encoder.getButton();
+  if (button == ClickEncoder::Clicked) {
+    if (state == PLAY_SELECTED) {
+      onPause (true);
+    } else if (state == PLAY_PAUSED) {
+      onPause (false);
     }
   }

@@ -356,8 +378,13 @@
 void onKey(byte index) {
   nextTimeoutTick = 0;

+  // No keys when paused
+  if (state == PLAY_PAUSED) {
+    // nop
+    Serial.println("Still paused");
+
   // Same key pressed again
-  if (state == PLAY_SELECTED && playingAlbum == index) {
+  } else if (state == PLAY_SELECTED && playingAlbum == index) {
     stopPlaying();
     onTryNextTrack();

@@ -396,6 +423,22 @@
   }
 }

+void onPause(bool pause) {
+  if (pause) {
+    Serial.println("Pause");
+    trellis.blinkRate(HT16K33_BLINK_HALFHZ);
+    player.pausePlaying(true);
+    enableAmplifier(false);
+    state = PLAY_PAUSED;
+  } else {
+    Serial.println("Resume");
+    trellis.blinkRate(HT16K33_BLINK_1HZ);
+    enableAmplifier(!headset);
+    player.pausePlaying(false);
+    state = PLAY_SELECTED;
+  }
+}
+
 void onStopPlaying() {
   enableAmplifier(false);
   enablePlayer(false);


really took out hall stuff

really took out hall stuff

--- v2/01dec/01dec.ino
+++ v2/01dec/01dec.ino
@@ -33,8 +33,8 @@
 const byte RMO = A6;          // right-middle IR distance sensor
 const byte RRO = A7;          // right-peripheral IR distance sensor

-const byte L_Hall = 2;        // left Hall sensor
-const byte R_Hall = 3;        // right Hall sensor
+// const byte L_Hall = 2;        // left Hall sensor
+// const byte R_Hall = 3;        // right Hall sensor
 const byte startModule = 4;   // remote start module

 // Window size of the median filter (odd number, 1 = no filtering)
@@ -67,16 +67,16 @@
 int lineFlag;       // flag to mark if line has been met
 boolean pivotFlag;  // flag to mark if the robot has pivoted
 boolean pastNear; // flag to mark if the opponent was near the robot last
-int speedArrR[5]; //running average for calculating velocity
-int speedArrL[5];
-int expectedVelR; //expected velocity
-int expectedVelL;
-bool prevHallR; //if at previous measurement the hallsensor was on
-bool prevHallL;
-int arrPosR; //pointer to insert values in the speed array
-int arrPosL;
-bool pastStalled;
-int stalled;
+// int speedArrR[5]; //running average for calculating velocity
+// int speedArrL[5];
+// int expectedVelR; //expected velocity
+// int expectedVelL;
+// bool prevHallR; //if at previous measurement the hallsensor was on
+// bool prevHallL;
+// nt arrPosR; //pointer to insert values in the speed array
+// int arrPosL;
+// bool pastStalled;
+// int stalled;
 int initial;

 // thresholds for distance sensors
@@ -96,8 +96,8 @@
 int pivotSpinR = 1000; // time spinning right at pivot
 int pivotTurnL = 1000; // time turning left at pivot
 int pivotSpinL = 1000; // time spinning left at pivot
-int stallThresh = 500; // time stalled
-int hallTimeThresh = 100;
+// int stallThresh = 500; // time stalled
+// int hallTimeThresh = 100;

 // max and minimum motor speeds
 int maxS = 200;
@@ -111,8 +111,8 @@
   R_ESC.writeMicroseconds(1500);
   L_ESC.writeMicroseconds(1500);

-  pinMode(L_Hall, INPUT);
-  pinMode(R_Hall, INPUT);
+  // pinMode(L_Hall, INPUT);
+  // pinMode(R_Hall, INPUT);

   // basic start module: wait 5s after pressing start
   // IMPLEMENT ON/OFF functionality
@@ -141,17 +141,17 @@
   pivotFlag = true;
   pastNear = false;
   prevFlag = prevLine;
-  for (int i = 0; i < 5; i++) {
-    speedArrR[i] = prevLine;
-    speedArrL[i] = prevLine;
-  }
-  arrPosR = 0;
-  arrPosL = 0;
-  prevHallR = false;
-  prevHallL = false;
+  // for (int i = 0; i < 5; i++) {
+  //   speedArrR[i] = prevLine;
+  //   speedArrL[i] = prevLine;
+  // }
+  // arrPosR = 0;
+  // arrPosL = 0;
+  // prevHallR = false;
+  // prevHallL = false;
   state = 11; // at start, movement state is the startup state
-  pastStalled = false;
-  stalled = false;
+  // pastStalled = false;
+  // stalled = false;
 }

 void loop() {
@@ -265,17 +265,18 @@
       perLeftDist = leftPerIR.getDist();

       //attack code with sensors
-      if (expectedVelL > getVelL() + hallTimeThresh || expectedVelR > getVelR() + hallTimeThresh) {
-        if (!pastStalled){
-          stalled = cur;
-          pastStalled = true;
-        } else if (cur - stalled > stallThresh) {
+      if (past == 'f' && attackCount < 50) {
+        // if (!pastStalled){
+        //   stalled = cur;
+        //   pastStalled = true;
+        // } else if (cur - stalled > stallThresh) {
           state = 12;
           pivotFlag = true;
-        }
-      } else if (pastStalled) {
-        pastStalled = false;
-      }
+        // }
+      }
+      // else if (pastStalled) {
+      //   pastStalled = false;
+      // }

       if (!pivotFlag) { // first check if the robot hasn't pivoted in the past (if it has, don't do any of the actions below)
         if (past == 'f' && pastNear && attackCount < 100) {
@@ -290,12 +291,14 @@
           attackCount = 0; // clear attack counter
           state = 0;
           pastNear = true;
-        } else if ((expectedVelL > getVelL() + hallTimeThresh || expectedVelR > getVelR() + hallTimeThresh) && pastStalled && cur - stalled <= stallThresh) {
-          past = 'f';
-          state = 1;
-          attackCount++; // increment attack counter
-          pastNear = true;
-        } else if (perLeftDist <= near) {
+        }
+        // else if ((expectedVelL > getVelL() + hallTimeThresh || expectedVelR > getVelR() + hallTimeThresh) && pastStalled && cur - stalled <= stallThresh) {
+        //   past = 'f';
+        //   state = 1;
+        //   attackCount++; // increment attack counter
+        //   pastNear = true;
+        // }
+        else if (perLeftDist <= near) {
           //if opponent within near of the left peripheral sensor, spin left
           state = 4;
           past = 'l'; // set past movement to left


Update EPROM_Dumper.ino

Update EPROM_Dumper.ino

--- EPROM_Dumper/EPROM_Dumper.ino
+++ EPROM_Dumper/EPROM_Dumper.ino
@@ -5,19 +5,11 @@
 {
    Serial.begin(9600); // Opens Serial Port to receive data

-<<<<<<< HEAD
+
    DDRL = B00000000;  //Sets up L register pins as 8-bit input
    DDRA = B11111111;  //Lower address (A register pins)
    DDRC = B11111111;  //Upper address (C register pins)
-=======
-   /*
-    *Sets up L-pins as 8-bit input A + C as 16 bit output
-    */
-
-   DDRL = B00000000;
-   DDRA = B11111111;  //Lower address
-   DDRC = B11111111;  //Upper address
->>>>>>> d0c85a7447b102450b42ee327ca71672e6da813a
+

    PORTA = B00000000; //Sets output data on pin register A as 0
    PORTC = B00000000; //Sets output data on pin register C as 0


use debug_mode

use debug_mode

--- ir_targets/ir_targets.ino
+++ ir_targets/ir_targets.ino
@@ -110,11 +110,13 @@
 }

 void printScores() {
-  Serial.println("Scores:");
-  Serial.print("BLUE: ");
-  Serial.print(scores[BLUE_LASER]);
-  Serial.print(" RED: ");
-  Serial.println(scores[RED_LASER]);
+  if(DEBUG_MODE) {
+    Serial.println("Scores:");
+    Serial.print("BLUE: ");
+    Serial.print(scores[BLUE_LASER]);
+    Serial.print(" RED: ");
+    Serial.println(scores[RED_LASER]);
+  }
 }

 void printRawbufLast(unsigned int rawbuf_last) {


Allow defining channel of RGB

Allow defining channel of RGB

--- examples/DmxSerialRecv/DmxSerialRecv.ino
+++ examples/DmxSerialRecv/DmxSerialRecv.ino
@@ -4,10 +4,10 @@
 // address 1 (red) -> PWM Port 9
 // address 2 (green) -> PWM Port 6
 // address 3 (blue) -> PWM Port 5
-//
+//
 // Copyright (c) 2011-2015 by Matthias Hertel, http://www.mathertel.de
 // This work is licensed under a BSD style license. See http://www.mathertel.de/License.aspx
-//
+//
 // Documentation and samples are available at http://www.mathertel.de/Arduino
 // 25.07.2011 creation of the DmxSerial library.
 // 10.09.2011 fully control the serial hardware register
@@ -25,18 +25,23 @@
 const int GreenPin =  6;  // PWM output pin for Green Light.
 const int BluePin =   5;  // PWM output pin for Blue Light.

+// This Example receives the 3 values starting with this channel:
+const int startChannel = 58 * 3 + 1;
+
 #define RedDefaultLevel   100
 #define GreenDefaultLevel 200
 #define BlueDefaultLevel  255

-void setup () {
+void setup() {
+  Serial.begin(115200);
+
   DMXSerial.init(DMXReceiver);
-
+
   // set some default values
   DMXSerial.write(1, 80);
   DMXSerial.write(2, 0);
   DMXSerial.write(3, 0);
-
+
   // enable pwm outputs
   pinMode(RedPin,   OUTPUT); // sets the digital pin as output
   pinMode(GreenPin, OUTPUT);
@@ -47,12 +52,12 @@
 void loop() {
   // Calculate how long no data backet was received
   unsigned long lastPacket = DMXSerial.noDataSince();
-
+
   if (lastPacket < 5000) {
-    // read recent DMX values and set pwm levels
-    analogWrite(RedPin,   DMXSerial.read(1));
-    analogWrite(GreenPin, DMXSerial.read(2));
-    analogWrite(BluePin,  DMXSerial.read(3));
+    // read recent DMX values and set pwm levels
+    analogWrite(RedPin,   DMXSerial.read(startChannel));
+    analogWrite(GreenPin, DMXSerial.read(startChannel + 1));
+    analogWrite(BluePin,  DMXSerial.read(startChannel + 2));

   } else {
     // Show pure red color, when no data was received since 5 seconds or more.


Updated example to include the helper methods and an initArduino() function

--- examples/SerialControl/SerialControl.ino
+++ examples/SerialControl/SerialControl.ino
@@ -27,27 +27,39 @@
 #include <WifiUartNetwork.h>
 #include <WifiUartTransparent.h>
 #include <SoftwareSerial.h>
-
-// pin for the led to show if the module is in command mode(high) or not (low)
+#include <WifiUartHelper.h>
+
+// EXAMPLE: Connect an LED to this pin to show the state of the wifi module (if it is in command
+//          mode or not)
 #define COMMAND_LED 13
-// RX pin the wifi module is connected to (rx pin goes to tx on wifi module)
+
+// EXAMPLE: Connect the TX pin on the wifi module to this pin (the rx pin on the software serial
+//          port will connect to the tx pin on the wifi module)
 #define WIFI_RX 10
-// TX pins the wifi module is connected to (tx pin goes to rx on wifi module)
+
+// EXAMPLE: Connect the RX pin on the wifi module to this pin (the tx pin on the software serial
+//          port will connect to the rx pin on the wifi module)
 #define WIFI_TX 11
-// The pin connected to the hardware reset pin on wifi module (optional)
+
+// EXAMPLE: Connect the reset pin on the wifi module to this pin
 #define RESET_PIN 12
-// Used to show how an LED can be turned on or off via the transparent connection
+
+// EXAMPLE: Connect an LED to this pin to show how an LED can be turned on or off via the
+//          transparent connection
 #define TEST_LED 6

-// userOne() uses these bits of information to setup the wifi card to use wpa
-// encryption, using the ssid and password below, setting up dns.
+// EXAMPLE: Fill in these bits so the initArduino() method can initialise the wifi card for your
+//          network. Alternativly modify the initArduino() method to setup your card the way you
+//          want.
 #define SSID "YOUR_SSID_HERE"
-#define SECURITY_PASSWORD "YOUR_WPA_PASSWORD_HERE"
-
-// userTwo() and userThree() uses these bits to listen/connect to a TCP port
-#define TCP_LISTEN_PORT 7777
-#define TCP_CONNECT_PORT 7777
-#define TCP_CONNECT_SERVER "YOUR_IP_HERE"
+#define SECURITY_PASSWORD "YOUR_WPA2_PASSWORD_HERE"
+#define WEB_ADMIN_ENABLED false
+#define WEB_ADMIN_PORT 80
+// NOTE: Passcode must be 6 characters, no more, no less
+#define WEB_ADMIN_PASSCODE "789789"
+#define TCP_SERVER true // Setup as a server, set to false to setup as a client
+#define TCP_PORT 7777 // client and server option
+#define TCP_SERVERNAME "YOUR_SERVER_IP_HERE" // client option

 // Commands
 #define TOGGLE_INPUT '^'
@@ -61,56 +73,178 @@
 #define NETWORK_SETTINGS 'N'
 #define WEB_STATE 'w'
 #define WEB_TOGGLE 'W'
-#define USER1 '1'
-#define USER2 '2'
-#define USER3 '3'
+//#define USER1 '1'
+//#define USER2 '2'
+//#define USER3 '3'
+
+// Error Blink Codes
+#define ERR_UNKNOWN 1
+#define ERR_INIT_COMMAND 2
+#define ERR_INIT_WIRELESS 3
+#define ERR_INIT_DHCP 4
+#define ERR_INIT_WEB 5
+#define ERR_INIT_CLIENTSERVER 6

 SoftwareSerial wifiSerial(WIFI_RX, WIFI_TX); // RX TX
 WifiUart wifi = WifiUart(&wifiSerial);
 bool writeToWifi = false;
-
+bool isTestLedOn = false;
+
+/**
+ * Put the arduino in an error state.
+ *
+ * This will blink the LED's constantly to give a visual display that the program is erroring out
+ * and will not be processing any further commands
+ */
+void errorState(int errorCode) {
+    while (true) {
+        Serial.print("Error ");
+        Serial.print(errorCode);
+        Serial.println("!");
+        for (int x = 0; x < errorCode; x++) {
+            digitalWrite(COMMAND_LED, HIGH);
+            digitalWrite(TEST_LED, HIGH);
+            delay(100);
+            digitalWrite(COMMAND_LED, LOW);
+            digitalWrite(TEST_LED, LOW);
+            delay(100);
+        }
+        delay(900);
+    }
+}
+void errorState() {
+    errorState(ERR_UNKNOWN);
+}
+
+/**
+ * This gets called at the end of the setup() function. I am using this method as a way to
+ * initialize the wifi card on boot (showing the use of the helper init methods)
+ */
+void initArduino() {
+    Serial.println("Init Arduino - start with a hardware reset");
+    wifi.hardwareReset();
+    bool needsReset = false;
+    if (!wifi.enterCommandMode()) {
+        errorState(ERR_INIT_COMMAND);
+        return; // calling errorState should never return
+    }
+
+    // Init the wireless settings
+    bool success = WifiUartHelper::initWireless(
+            &wifi,
+            WIFIU_NET_MODE_INFRASTRUCTURE,
+            SSID,
+            WIFIU_NET_ENC_WPA2,
+            SECURITY_PASSWORD,
+            WIFIU_NET_KEY_FORMAT_ASCII,
+            0);
+    if (success == WIFIU_HELPER_RESPONSE_ERR) {
+        errorState(ERR_INIT_WIRELESS);
+        return; // calling errorState should never return
+    }
+    else if (success == WIFIU_HELPER_RESPONSE_MODIFIED) {
+        Serial.println("Modified the wireless settings");
+        needsReset = true;
+        success = WIFIU_HELPER_RESPONSE_OK;
+    }
+
+    // Init DHCP/StaticIP settings
+    success = WifiUartHelper::initNetworkDHCP(&wifi);
+    if (success == WIFIU_HELPER_RESPONSE_ERR) {
+        errorState(ERR_INIT_DHCP);
+        return; // calling errorState should never return
+    }
+    else if (success == WIFIU_HELPER_RESPONSE_MODIFIED) {
+        Serial.println("Modified the dhcp settings");
+        needsReset = true;
+        success = WIFIU_HELPER_RESPONSE_OK;
+    }
+
+    // Init web service settings
+    success = WifiUartHelper::initMisc(&wifi, WEB_ADMIN_ENABLED, WEB_ADMIN_PORT, WEB_ADMIN_PASSCODE);
+    if (success == WIFIU_HELPER_RESPONSE_ERR) {
+        errorState(ERR_INIT_WEB);
+        return; // calling errorState should never return
+    }
+    else if (success == WIFIU_HELPER_RESPONSE_MODIFIED) {
+        Serial.println("Modified the misc settings");
+        needsReset = true;
+        success = WIFIU_HELPER_RESPONSE_OK;
+    }
+
+    // Initialise to connect to a sever, or act as a client
+    if (TCP_SERVER) {
+        success = WifiUartHelper::initServer(&wifi, TCP_PORT, WIFIU_NET_ATRM_TCP, WIFIU_TRANS_DEFAULT_TIMEOUT);
+    }
+    else {
+        success = WifiUartHelper::initClient(&wifi, TCP_SERVERNAME, TCP_PORT, WIFIU_NET_ATRM_TCP);
+    }
+    if (success == WIFIU_HELPER_RESPONSE_ERR) {
+        errorState(ERR_INIT_CLIENTSERVER);
+        return; // calling errorState should never return
+    }
+    else if (success == WIFIU_HELPER_RESPONSE_MODIFIED) {
+        Serial.println("Modified the client/server settings");
+        needsReset = true;
+        success = WIFIU_HELPER_RESPONSE_OK;
+    }
+
+    if (needsReset) {
+        Serial.println("Wifi card settings have been corrected. We need to reset the module before we continue...");
+        reportSuccess (wifi.reset());
+    }
+    else {
+        Serial.println("Wifi card settings correct");
+    }
+    Serial.println("Done");
+}

 void userOne() {
-    // set module to connect to home wifi
-    if (!WifiUartNetwork::setWirelessMode(&wifi, WIFIU_NET_MODE_INFRASTRUCTURE)) {
-        Serial.println("Could not set wireless mode");
-    }
-    if (!WifiUartNetwork::setSSID(&wifi, SSID)) {
-        Serial.println("Could not set SSID");
-    }
-    if (!WifiUartNetwork::setSecurity(&wifi, WIFIU_NET_ENC_WPA, SECURITY_PASSWORD)) {
-        Serial.println("Could not set security");
-    }
-    if (!WifiUartNetwork::setNetworkSettingsToDHCP(&wifi)) {
-        Serial.println("Could not set dhcp");
-    }
-    Serial.print("Done (Don't forget to reset the module ");
-    Serial.println("for the changes to take effect)");
+    //// set module to connect to home wifi
+    //if (!WifiUartNetwork::setWirelessMode(&wifi, WIFIU_NET_MODE_INFRASTRUCTURE)) {
+    //    Serial.println("Could not set wireless mode");
+    //}
+    //if (!WifiUartNetwork::setSSID(&wifi, SSID)) {
+    //    Serial.println("Could not set SSID");
+    //}
+    //if (!WifiUartNetwork::setSecurity(&wifi, WIFIU_NET_ENC_WPA, SECURITY_PASSWORD)) {
+    //    Serial.println("Could not set security");
+    //}
+    //if (!WifiUartNetwork::setNetworkSettingsToDHCP(&wifi)) {
+    //    Serial.println("Could not set dhcp");
+    //}
+    //Serial.print("Done (Don't forget to reset the module ");
+    //Serial.println("for the changes to take effect)");
 }

 void userTwo() {
-    // Set module to listen to a TCP port
-    // Connect to this port over TCP using telnet and send either 1 or 0
-    // characters to turn the TEST_LED on or off
-    if (!WifiUartTransparent::setServer(&wifi, TCP_LISTEN_PORT)) {
-        Serial.println("Could not set server mode");
-    }
-    Serial.print("Done (Don't forget to reset the module ");
-    Serial.println("for the changes to take effect)");
+    //// Set module to listen to a TCP port
+    //// Connect to this port over TCP using telnet and send either 1 or 0
+    //// characters to turn the TEST_LED on or off
+    //if (!WifiUartTransparent::setServer(&wifi, TCP_LISTEN_PORT)) {
+    //    Serial.println("Could not set server mode");
+    //}
+    //Serial.print("Done (Don't forget to reset the module ");
+    //Serial.println("for the changes to take effect)");
 }

 void userThree() {
-    // Try running the nodejs script in examples/server.js to test. You will need
-    // enter write to wifi mode (^) and then use the T (note case) character to
-    // toggle the led on the TEST_LED pin
-    if (!WifiUartTransparent::setClient(&wifi, TCP_CONNECT_SERVER, TCP_CONNECT_PORT)) {
-        Serial.println("Could not set client mode");
-    }
-    Serial.print("Done (Don't forget to reset the module ");
-    Serial.println("for the changes to take effect)");
-}
-
-
+    //// Try running the nodejs script in examples/server.js to test. You will need
+    //// enter write to wifi mode (^) and then use the T (note case) character to
+    //// toggle the led on the TEST_LED pin
+    //if (!WifiUartTransparent::setClient(&wifi, TCP_CONNECT_SERVER, TCP_CONNECT_PORT)) {
+    //    Serial.println("Could not set client mode");
+    //}
+    //Serial.print("Done (Don't forget to reset the module ");
+    //Serial.println("for the changes to take effect)");
+}
+
+/**
+ * Helper method to easily report success on the serial based on a boolean value
+ *
+ * @param bool success
+ * @return bool
+ */
 bool reportSuccess(bool success) {
     if (success) {
         Serial.println("Success");
@@ -121,15 +255,25 @@
     return success;
 }

+/**
+ * Sets the COMMAND_LED to the correct state based on the value of the wifi module
+ */
 void updateCommandLed () {
-    if (!wifi.isInCommandMode()) {
+    if (wifi.isInCommandMode()) {
+        digitalWrite(COMMAND_LED, HIGH);
+    }
+    else {
         digitalWrite(COMMAND_LED, LOW);
     }
-    else {
-        digitalWrite(COMMAND_LED, HIGH);
-    }
-}
-
+}
+
+/**
+ * Helper method to print out a line in the help menu
+ *
+ * @param char shortCut
+ * @param char* description
+ * @return void
+ */
 void helpLine(char shortCut, char* description) {
     Serial.print("    ");
     Serial.print(shortCut);
@@ -137,8 +281,10 @@
     Serial.println(description);
 }

-void help()
-{
+/**
+ * Print out a list of commands that may be used when using the example
+ */
+void help() {
     Serial.println("Commands available:");
     helpLine(TOGGLE_INPUT, "Toggle input to wifimodule");
     helpLine(HELP, "This help message");
@@ -147,14 +293,18 @@
     helpLine(FACTORY_RESET, "Factory Reset");
     helpLine(RESET, "Reset");
     helpLine(HARDWARE_RESET, "Hardware Reset");
-    helpLine(NETWORK_STATE, "Network State");
-    helpLine(NETWORK_SETTINGS, "Network Settings");
+    helpLine(NETWORK_STATE, "Print Network State");
+    helpLine(NETWORK_SETTINGS, "Print Network Settings");
     Serial.print("Wifi module is currently ");
     Serial.print(wifi.isInCommandMode() ? "" : "not ");
     Serial.println("in command mode");
-    updateCommandLed();
-}
-
+}
+
+/**
+ * Print the network state
+ *
+ * TODO: Move this to the helper module
+ */
 void networkState() {
     Serial.println("-----");
     WifiUartNetModeResponse mode = WifiUartNetwork::getWirelessMode(&wifi);
@@ -194,6 +344,11 @@
     Serial.println("-----");
 }

+/**
+ * Prints the netowrk settings
+ *
+ * TODO: Move this to the helper module
+ */
 void networkSettings() {
     Serial.println("-----");
     WifiUartNetSettingsResponse state = WifiUartNetwork::getNetworkSettings(&wifi);
@@ -213,6 +368,7 @@
     Serial.println("-----");
 }

+// Web State Methods
 bool currentWebState () {
     bool ret = true; // always assume the worst!
     WifiUartMiscWebServiceResponse web = WifiUartMisc::getWebServiceStatus(&wifi);
@@ -225,7 +381,6 @@
     Serial.print("Webservice state: ");
     Serial.println(currentWebState() ? "Enabled" : "Disabled");
 }
-
 void webToggle() {
     bool newState = !currentWebState();
     Serial.print("Setting state to: ");
@@ -233,9 +388,14 @@
     reportSuccess(WifiUartMisc::setWebServiceStatus(&wifi, newState, 80));
 }

-bool isTestLedOn = false;
+/**
+ * Takes a character (from the wifi card) and does something with it
+ */
 void receiveChar(char c) {
     if (!wifi.isInCommandMode()) {
+        // We only want to do commands on input coming in through the transparent interface
+        // EXAMPLE: You can modify what happens here for any character input. For more advaned
+        //          functionality you may want to implement a state machine.
         switch (c) {
             case '0':
                 // Turn the test led off
@@ -258,93 +418,111 @@
         }
     }
     else {
+        // We want to see on the console what the wifi card is giving us while we are in command mode
         Serial.write(c);
     }
-
-}
-
+}
+
+/**
+ * Takes a character and runs the associated command
+ *
+ * @param char r
+ * @returns void
+ */
+void runMenuCommand (char r) {
+    switch (r) {
+        case HELP:
+            help();
+            break;
+        case ENTER_COMMAND:
+            Serial.println("Enter Command Mode");
+            reportSuccess (wifi.enterCommandMode());
+            break;
+        case EXIT_COMMAND:
+            Serial.println("Exit Command Mode");
+            reportSuccess (wifi.exitCommandMode());
+            break;
+        case FACTORY_RESET:
+            Serial.println("Factory Reset");
+            reportSuccess (wifi.factoryReset());
+            break;
+        case RESET:
+            Serial.println("Reset");
+            reportSuccess (wifi.reset());
+            break;
+        case HARDWARE_RESET:
+            Serial.println("Hardware Reset");
+            reportSuccess (wifi.hardwareReset());
+            break;
+        case NETWORK_STATE:
+            Serial.println("Network State");
+            networkState();
+            break;
+        case NETWORK_SETTINGS:
+            Serial.println("Network Settings");
+            networkSettings();
+            break;
+        case WEB_STATE:
+            webState();
+            break;
+        case WEB_TOGGLE:
+            webToggle();
+            break;
+        //case USER1:
+        //    userOne();
+        //    break;
+        //case USER2:
+        //    userTwo();
+        //    break;
+        //case USER3:
+        //    userThree();
+        //    break;
+    }
+}
+
+// The arduino setup method
 void setup() {
     Serial.begin(115200);
     wifiSerial.begin(9600);
-    help();
     pinMode(COMMAND_LED, OUTPUT);
     pinMode(TEST_LED, OUTPUT);
     wifi.setHardwareResetPin(RESET_PIN, true);
-}
-
+    initArduino();
+    help();
+}
+
+// The arduino run loop
 void loop() {
     if (wifiSerial.available()) {
+        // Any character received from the wifi serial, at the moment just gets output to the
+        // arduino console
         while (wifiSerial.available()) {
             receiveChar(wifiSerial.read());
         }
     }
     if (Serial.available()) {
+        // We got a character.
         char r = Serial.read();
         if (r == TOGGLE_INPUT) {
+            // It is the shortcut to toggle input between the wifi module and arduino
             writeToWifi = !writeToWifi;
             Serial.print("Write to wifi is now ");
             Serial.println(writeToWifi ? "on" : "off");
         }
         else if (writeToWifi) {
+            // We are writing to the wifi
             wifiSerial.print(r);
             if (r == '\r') {
                 wifiSerial.print('\n');
             }
         }
         else {
-            switch (r) {
-                case HELP:
-                    help();
-                    break;
-                case ENTER_COMMAND:
-                    Serial.println("Enter Command Mode");
-                    reportSuccess (wifi.enterCommandMode());
-                    updateCommandLed();
-                    break;
-                case EXIT_COMMAND:
-                    Serial.println("Exit Command Mode");
-                    reportSuccess (wifi.exitCommandMode());
-                    updateCommandLed();
-                    break;
-                case FACTORY_RESET:
-                    Serial.println("Factory Reset");
-                    reportSuccess (wifi.factoryReset());
-                    updateCommandLed();
-                    break;
-                case RESET:
-                    Serial.println("Reset");
-                    reportSuccess (wifi.reset());
-                    updateCommandLed();
-                    break;
-                case HARDWARE_RESET:
-                    Serial.println("Hardware Reset");
-                    reportSuccess (wifi.hardwareReset());
-                    updateCommandLed();
-                    break;
-                case NETWORK_STATE:
-                    Serial.println("Network State");
-                    networkState();
-                    break;
-                case NETWORK_SETTINGS:
-                    Serial.println("Network Settings");
-                    networkSettings();
-                    break;
-                case WEB_STATE:
-                    webState();
-                    break;
-                case WEB_TOGGLE:
-                    webToggle();
-                    break;
-                case USER1:
-                    userOne();
-                    break;
-                case USER2:
-                    userTwo();
-                    break;
-                case USER3:
-                    userThree();
-                    break;
-            }
+            // We are not writing to wifi, and its not the command to toggle between. Enter our menu
+            // and pick the right one for the job being asked.
+            runMenuCommand(r);
+            // One of the above commands may have changed the state of the wifi module, so we want
+            // to update the command LED just in case
+            updateCommandLed();
         }
     }
 }


Added the workaround for issue #118 in StringExample.ino

--- examples/StringExample/StringExample.ino
+++ examples/StringExample/StringExample.ino
@@ -33,7 +33,12 @@

   // You can get a String from a JsonObject or JsonArray:
   // No duplication is done, at least not in the JsonBuffer.
-  String sensor = root[String("sensor")];
+  String sensor = root["sensor"];
+
+  // Unfortunately, the following doesn't work (issue #118):
+  // sensor = root["sensor"]; // <-  error "ambiguous overload for 'operator='"
+  // As a workaround, you need to replace by:
+  sensor = root["sensor"].as<String>();

   // You can set a String to a JsonObject or JsonArray:
   // WARNING: the content of the String will be duplicated in the JsonBuffer.


Standardize serial printing modes

Standardize serial printing modes

--- roof_sensor_serial/roof_sensor_serial.ino
+++ roof_sensor_serial/roof_sensor_serial.ino
@@ -22,9 +22,10 @@
 #define TEMP_PIN_1_DELAY 10   // How often to update sensor

 #define TEXT_RAIN_FLIP "RAIN FLIP" // serial text to print on rain flip
-#define TEXT_OUTSIDE   "T:"        // serial text to print for temperature
-#define TEXT_HUMIDITY  "H:"        // serial text to print for humidity
-#define TEXT_BATTERY   "B:"        // serial text to print for voltage
+#define TEXT_WIND_UPDATE "W:"      // serial text to print on wind update
+#define TEXT_OUTSIDE     "T:"      // serial text to print for temperature
+#define TEXT_HUMIDITY    "H:"      // serial text to print for humidity
+#define TEXT_BATTERY     "B:"      // serial text to print for voltage

 #define WIND_DEBOUNCE_TIME 200     // MICROseconds before accepting more wind
 #define RAIN_DEBOUNCE_TIME 2000    // MILLIseconds before accepting new rain
@@ -54,6 +55,7 @@
 void loop() {
   if (millis() - lastmillis >= 1000) {    // if it's been more than 1000ms:
     noInterrupts();                         // disable interrupts when calculating
+    Serial.print(TEXT_WIND_UPDATE);         // print header
     Serial.println(getWind(), DEC);         // print the rpm to serial

     if (tempCounter > TEMP_PIN_1_DELAY) { // if we've ran this loop 10 times


Update YunMQTT.ino

Update YunMQTT.ino

--- reference-realtime/arduino-yun/sketch/YunMQTT/YunMQTT.ino
+++ reference-realtime/arduino-yun/sketch/YunMQTT/YunMQTT.ino
@@ -79,6 +79,10 @@
  */
 void callback(char* topic, byte* payload, unsigned int length);

+
+/******************************************
+* Globlals
+******************************************/
 // Update these with values suitable for your network.
 char * server = "stream.smartdatanet.it";


Update OnewireKeypad_Final.ino

Update OnewireKeypad_Final.ino

--- Examples/OnewireKeypad_Final/OnewireKeypad_Final.ino
+++ Examples/OnewireKeypad_Final/OnewireKeypad_Final.ino
@@ -1,3 +1,5 @@
+//Original Creator: Andrew Mascolo
+
 #include <Wire.h>
 #include <LiquidCrystal_I2C.h>
 #include <OnewireKeypad.h>


Delete usage of Serial to save space

Delete usage of Serial to save space

--- Valokepakko.ino
+++ Valokepakko.ino
@@ -47,7 +47,6 @@
   strip.setBrightness(32);
   // Initialize all pixels to 'off'
   strip.show();
-  Serial.begin(9600);
 }

 // Sensor reading when there is no tilt on the accelerometer.
@@ -70,15 +69,7 @@

   pulseX = pulseIn(ACCEL_X_PIN, HIGH);
   pulseY = pulseIn(ACCEL_Y_PIN, HIGH);
-
   angle = atan2(pulseX-NO_TILT, pulseY-NO_TILT);
-
-  /* Display result */
-  Serial.print(pulseX);
-  Serial.print("\t");
-  Serial.print(pulseY);
-  Serial.print("\t");
-  Serial.println(mapfloat(angle, -PI, PI, 0.0, 360.0));

   for (int led = 0; led < LEDS; led++) {
     const float originX = IMAGE_WIDTH / 2;
@@ -96,12 +87,6 @@
     int x = int(originX + deltaX);
     int y = int(originY + deltaY);

-    if (led == 59) {
-      Serial.print(x);
-      Serial.print("\t");
-      Serial.println(y);
-    }
-
     if (x < 0 || x > IMAGE_WIDTH - 1 || y < 0 || y > IMAGE_HEIGHT - 1) {
       rgb = {0, 0, 0};
     } else {
@@ -109,15 +94,9 @@
       int colorIndex = pgm_read_byte_near(PIXELS + pixelIndex);
       memcpy_PF(&rgb, (uint_farptr_t) &PALETTE[colorIndex], sizeof(RGB));
     }
-    /* Serial.print(rgb.r); */
-    /* Serial.print(", "); */
-    /* Serial.print(rgb.g); */
-    /* Serial.print(", "); */
-    /* Serial.println(rgb.b); */
     uint32_t c = strip.Color(rgb.r, rgb.g, rgb.b);
     strip.setPixelColor(led, c);
   }
-  /* Serial.println("###"); */

   strip.show();
 }


Add time info

Add time info

--- RouterReset.ino
+++ RouterReset.ino
@@ -1,8 +1,21 @@
 /*** RouterReset: test if internet is working; if not, reset router
-***/
-
+ *
+ * Karlduino, Dec 2013
+ *
+ * Parts taken from Arduino wifi examples:
+ *   WifiWebClient by dlf, srl, and Tom Igoe
+ *   WifiUdpNtpClient by Michael Margolis and Tom Igoe
+ *   SD/Datalogger by Tom Igoe
+ *
+ ***/
+
+#include <stdio.h>
 #include <SPI.h>
 #include <WiFi.h>
+#include <SPI.h>
+#include <WiFiUdp.h>
+#include <Time.h>
+

 // private info [made generic here]
 char ssid[] = "SSID";
@@ -16,15 +29,25 @@

 WiFiClient client;

+// checking connection
 unsigned long lastConnectionTime = 0;
 boolean lastConnected = false;
 const unsigned long postingInterval = 10*1000; // wait 10 seconds
 boolean canConnect = false;

+// setting time
+unsigned int localPort = 2390;      // local port to listen for UDP packets
+const int TIMEZONE = -6;            // central standard time
+// const int TIMEZONE = -5;         // central daylight time
+IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server
+const int NTP_PACKET_SIZE = 48;
+byte packetBuffer[NTP_PACKET_SIZE];
+WiFiUDP Udp;
+char time_as_string[] = "12/20/1969 00:00:00";
+
 const int redLed = 3;
 const int greenLed = 5;
 const int yellowLed = 6;
-

 void setup() {
   // Initial LEDs
@@ -56,10 +79,18 @@
     Serial.println(ssid);
     status = WiFi.begin(ssid, pass);

-    delay(3000);
+    delay(1000);
   }
   Serial.println("Connected to wifi");
   printWifiStatus();
+
+  Serial.println("Connecting to time server.");
+  Udp.begin(localPort);
+
+  Serial.println("Getting time.");
+  sendNTPpacket(timeServer); // send an NTP packet to a time server
+  delay(500);
+  if(  Udp.parsePacket() ) get_and_print_time();
 }

 void loop() {
@@ -76,8 +107,12 @@
     digitalWrite(yellowLed, HIGH);
     connect_to_server();
     digitalWrite(yellowLed, LOW);
-  }
-
+
+    Serial.print("Current time: ");
+    time_to_string(now(), time_as_string);
+    Serial.println(time_as_string);
+  }
+
   lastConnected = client.connected();
   if(canConnect) {
     digitalWrite(greenLed, HIGH);
@@ -89,7 +124,6 @@
   }

 }
-

 void printWifiStatus() {
   // print the SSID of the network you're attached to:
@@ -107,8 +141,6 @@
   Serial.print(rssi);
   Serial.println(" dBm");
 }
-
-

 void connect_to_server(void) {
   Serial.println("\nStarting connection to server...");
@@ -145,3 +177,48 @@
     delay(time);
   }
 }
+
+// send an NTP request to the time server at the given address
+unsigned long sendNTPpacket(IPAddress& address)
+{
+  memset(packetBuffer, 0, NTP_PACKET_SIZE);
+  packetBuffer[0] = 0b11100011;
+  packetBuffer[1] = 0;
+  packetBuffer[2] = 6;
+  packetBuffer[3] = 0xEC;
+  packetBuffer[12]  = 49;
+  packetBuffer[13]  = 0x4E;
+  packetBuffer[14]  = 49;
+  packetBuffer[15]  = 52;
+  Udp.beginPacket(address, 123);
+  Udp.write(packetBuffer, NTP_PACKET_SIZE);
+  Udp.endPacket();
+}
+
+void get_and_print_time(void) {
+    Serial.println("packet received");
+    Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
+
+    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
+    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
+    unsigned long secsSince1900 = highWord << 16 | lowWord;
+
+    // now convert NTP time into everyday time:
+    const unsigned long seventyYears = 2208988800UL;
+    // subtract seventy years:
+    unsigned long epoch = secsSince1900 - seventyYears;
+    setTime(epoch);
+
+    Serial.print("Current time: ");
+    time_to_string(epoch, time_as_string);
+    Serial.println(time_as_string);
+}
+
+void time_to_string(unsigned long epoch, char* time_as_string) {
+
+  epoch = epoch + TIMEZONE * 3600;
+
+  sprintf(time_as_string, "%02d/%02d/%4d %d:%02d:%02d",
+          month(epoch), day(epoch), year(epoch),
+          hour(epoch), minute(epoch), second(epoch));
+}


fix range of Servo

fix range of Servo

--- Servo/Servo.ino
+++ Servo/Servo.ino
@@ -16,16 +16,16 @@
 	  for(int cou = 0;cou < 5;cou++){
 		digitalWrite(3,HIGH);
                 digitalWrite(4,HIGH);
-               while(i < 45){
+               while(i < 270){
 		  delay(10);
-		  val = 45 - i;
+		  val = 270 - i;
 		  myservo.write(val);
 		  i++;
 		}
 		i = 0;
                 digitalWrite(3,LOW);
                digitalWrite(4,LOW);
-		while(i < 45){
+		while(i < 270){
 		  delay(10);
 		  val = i;
 		  myservo.write(val);


Fixed include for missing (unnecessary) header

--- eeZeeRGB/firmware/Arduino_WS2812/Arduino_WS2812.ino
+++ eeZeeRGB/firmware/Arduino_WS2812/Arduino_WS2812.ino
@@ -14,7 +14,6 @@
   https://code.google.com/p/bot-thoughts-eezee/wiki/eeZeeRGB
 */
 #include <Adafruit_NeoPixel.h>
-#include "WS2812_Definitions.h"

 #define PIN 8        // Arduino pin connected to WS2812B's DIN


コンテンツ一覧表示の時の先頭のスラッシュを削除

コンテンツ一覧表示の時の先頭のスラッシュを削除


laser scanner

laser scanner

--- Arduino/laser-radar/laser-radar.ino
+++ Arduino/laser-radar/laser-radar.ino
@@ -4,21 +4,17 @@
 #include "VL53L0X.h"

 // Laser
-#define XSHUT_pin4 8
-#define XSHUT_pin3 7
-#define XSHUT_pin2 6
-#define XSHUT_pin1 5
-
-//ADDRESS_DEFAULT 0b0101001 or 41
-//#define Sensor1_newAddress 41 not required address change
-#define Sensor2_newAddress 42
-#define Sensor3_newAddress 43
-#define Sensor4_newAddress 44
-
 VL53L0X Sensor1;
 VL53L0X Sensor2;
-VL53L0X Sensor3;
-VL53L0X Sensor4;
+
+const uint8_t Sensor1_xshut = 4;
+const uint8_t Sensor2_xshut = 5;
+
+const uint8_t Sensor1_address = 22;
+const uint8_t Sensor2_address = 25;
+
+const uint16_t minDistance = 30;
+const uint16_t maxDistance = 1200;

 // Servo
@@ -46,41 +42,25 @@

 void setup()
 {
-    pinMode(XSHUT_pin1, OUTPUT);
-    pinMode(XSHUT_pin2, OUTPUT);
-    pinMode(XSHUT_pin3, OUTPUT);
-    pinMode(XSHUT_pin4, OUTPUT);
+    pinMode(Sensor1_xshut, OUTPUT);
+    pinMode(Sensor2_xshut, OUTPUT);
+    digitalWrite(Sensor1_xshut, LOW);
+    digitalWrite(Sensor2_xshut, LOW);

+    Wire.begin();
     Serial.begin(115200);

-    Wire.begin();
-
-    Sensor4.setAddress(Sensor4_newAddress);
-    pinMode(XSHUT_pin3, INPUT);
-    delay(10);
-
-    Sensor3.setAddress(Sensor3_newAddress);
-    pinMode(XSHUT_pin2, INPUT);
-    delay(10);
-
-    Sensor2.setAddress(Sensor2_newAddress);
-    pinMode(XSHUT_pin1, INPUT);
-    delay(10);
-
+    pinMode(Sensor1_xshut, INPUT);
     Sensor1.init();
+    Sensor1.setAddress(Sensor1_address);
+    Sensor1.setTimeout(500);
+    Sensor1.startContinuous();
+
+    pinMode(Sensor2_xshut, INPUT);
     Sensor2.init();
-    Sensor3.init();
-    Sensor4.init();
-
-    Sensor1.setTimeout(500);
+    Sensor2.setAddress(Sensor2_address);
     Sensor2.setTimeout(500);
-    Sensor3.setTimeout(500);
-    Sensor4.setTimeout(500);
-
-    Sensor1.startContinuous();
     Sensor2.startContinuous();
-    Sensor3.startContinuous();
-    Sensor4.startContinuous();

     // attach servo pin and set to initial direction
     ServoMotor.attach(servoPin, 450, 2400); // 400, 2600 to fix rotation issues
@@ -91,24 +71,24 @@

 long GetRange(int id)
 {
-    if(id == 1)
+    if(id == 1 || id == 2)
     {
-        return Sensor1.readRangeContinuousMillimeters();
-    }
+        int dist = 0;
+
+        if(id == 1)
+        {
+            dist = Sensor1.readRangeContinuousMillimeters();
+        }
+
+        if(id == 2)
+        {
+            dist = Sensor2.readRangeContinuousMillimeters();
+        }
+
+        if(dist < minDistance) { dist = maxDistance; }
+        if(dist > maxDistance) { dist = maxDistance; }

-    if(id == 2)
-    {
-        return Sensor2.readRangeContinuousMillimeters();
-    }
-
-    if(id == 2)
-    {
-        return Sensor3.readRangeContinuousMillimeters();
-    }
-
-    if(id == 2)
-    {
-        return Sensor4.readRangeContinuousMillimeters();
+        return dist;
     }

     return 0;
@@ -154,33 +134,30 @@
         if(data == "fast")
         {
             servoRotationAngel = servoRotationAngelFast;
-            averageScanAmount = averageScanAmountFast;
             return;
         }

         if(data == "medium")
         {
             servoRotationAngel = servoRotationAngelMedium;
-            averageScanAmount = averageScanAmountMedium;
             return;
         }

         if(data == "detail")
         {
             servoRotationAngel = servoRotationAngelDetailed;
-            averageScanAmount = averageScanAmountDetailed;
             return;
         }
     }
 }

-void SendData(name, position, distance)
+void SendData(String sensorName, int pos, int distance)
 {
     Serial.print("Laser");
     Serial.print("|");
-    Serial.print(name);
+    Serial.print(sensorName);
     Serial.print("|");
-    Serial.print(position);
+    Serial.print(pos);
     Serial.print("|");
     Serial.println(distance);
 }
@@ -200,12 +177,9 @@

     long laserOne = GetRange(1);
     long laserTwo = GetRange(2);
-    long laserThree = GetRange(3);
-    long laserFrour = GetRange(4);

     SendData("One", servoPos, laserOne);
-    SendData("Two", (servoPos+90%360), laserTwo);
-    SendData("Three", (servoPos+180%360), laserThree);
-    SendData("Four", (servoPos+270%360), laserFour);
+    SendData("Two", (servoPos+180%360), laserTwo);
 }

+


Universal Arduino Firmware

Universal Arduino Firmware

--- Arduio/ArduinoUniFirmware/ArduinoUniFirmware.ino
+++ Arduio/ArduinoUniFirmware/ArduinoUniFirmware.ino
@@ -53,6 +53,7 @@
     int pin = line.substring(0, div_index).toInt();
     int value = line.substring(div_index + 1).toInt();
     pinMode(pin, OUTPUT);
+    line = "";
     if(value == 0)
     {
       digitalWrite(pin, LOW);
@@ -73,8 +74,9 @@
     {
       return line.length();
     }
-    line += inbyte;
+    line += (char)inbyte;
   }
   return -1;
 }

+


Improving CosaTinyReceiver LCD output; Added Vcc and ticks.

--- examples/Tiny/CosaTinyReceiver/CosaTinyReceiver.ino
+++ examples/Tiny/CosaTinyReceiver/CosaTinyReceiver.ino
@@ -41,10 +41,10 @@
 #include "Cosa/VWI/Codec/VirtualWireCodec.hh"

 PCD8544 lcd;
+
 VirtualWireCodec codec;
 VWI::Receiver rx(Board::D4, &codec);
 const uint16_t SPEED = 4000;
-#undef putchar

 void setup()
 {
@@ -90,12 +90,16 @@
   nr = msg.nr + 1;

   // Display received message and statistics
+  uint16_t vcc = AnalogPin::bandgap(1100);
+  uint16_t ert = (err * 100L) / cnt;
   trace << clear;
-  trace << msg.nr << ':';
-  trace << msg.luminance << PSTR(", ");
-  trace << msg.temperature << endl;
+  trace << msg.nr << ':'
+	<< msg.luminance << PSTR(", ")
+	<< msg.temperature << endl;
   trace << PSTR("cnt = ") << cnt << endl;
   trace << PSTR("err = ") << err << endl;
-  trace << PSTR("err% = ") << (err * 100L) / cnt << '%' << endl;
+  trace << PSTR("err% = ") << ert << '%' << endl;
+  trace << PSTR("Vcc = ") << vcc << PSTR(" mV") << endl;
+  trace << PSTR("ticks = ") << Watchdog::ticks();
 }


cambiado el string del serial

cambiado el string del serial

--- pulsadores/pulsadores.ino
+++ pulsadores/pulsadores.ino
@@ -62,7 +62,7 @@
         }
         else if (digitalRead(botonNext) == LOW) {
           a = false;
-          sprintf(respuesta50, "%d|%d", rojoCounter, blancoCounter);
+          sprintf(respuesta50, "%d|%d\n", rojoCounter, blancoCounter);
           Serial.write(respuesta50);
           delay(300);
         }
@@ -80,7 +80,7 @@
       sprintf(amar,'\0');
       sprintf(azul,'\0');
       sprintf(plata,'\0');
-      sprintf(respuesta51, '\0');
+      sprintf(respuesta51, '\0');
       while(a) {
         //interaccion 7 pulsadores
         if (digitalRead(botonRojo) == LOW) {
@@ -89,27 +89,28 @@
           delay(300);
         }
         else if (digitalRead(botonBlanco) == LOW) {
-          sprintf(blanco, "%d|",3);
+          sprintf(blanco, "%d|",3);
           strcat(respuesta51,blanco);
           delay(300);
         }
         else if (digitalRead(botonAmarillo) == LOW) {
-          sprintf(amar, "%d|",2);
+          sprintf(amar, "%d|",2);
           strcat(respuesta51,amar);
           delay(300);
         }
         else if (digitalRead(botonPlata) == LOW) {
-          sprintf(plata, "%d|",0);
+          sprintf(plata, "%d|",0);
           strcat(respuesta51,plata);
           delay(300);
         }
         else if (digitalRead(botonAzul) == LOW) {
-          sprintf(azul, "%d|",1);
+          sprintf(azul, "%d|",1);
           strcat(respuesta51,azul);
           delay(300);
         }
         else if (digitalRead(botonNext) == LOW) {
           a = false;
+          strcat(respuesta51, "\n")
           Serial.write(respuesta51);
           delay(300);
         }
@@ -126,4 +127,3 @@
     }
   }
 }
-


added chip id to mDNS

added chip id to mDNS

--- ESP8266_Base.ino
+++ ESP8266_Base.ino
@@ -48,7 +48,7 @@
  */
 void handleRoot()
 {
-  server.send(200, "text/html", "<!doctype html>
You are connected

Setup WLAN");
+  server.send(200, "text/html", "<!doctype html>
You are connected

Setup WLAN
Value: " + String(curPwmOut) + "");
 }

 void handleWlanSetup()
@@ -118,6 +118,7 @@
     Serial.print(".");
     timeout++;
   }
+  Serial.println();

   if (WiFi.status() != WL_CONNECTED)
   {
@@ -125,12 +126,19 @@
     startAp = true;
     switchSetup = true;
   }
-
-
-
-  if (MDNS.begin("OPENHAB_TESTLUDER"))
-  {
-    Serial.println("mDNS responder started");
+  else
+  {
+    Serial.print("connected. IP is: ");
+    Serial.println(WiFi.localIP());
+  }
+
+
+  String id_prefix = "OPENHAB_TESTLUDER_";
+  String id = id_prefix + ESP.getFlashChipId();
+  if (MDNS.begin(id.c_str()))
+  {
+    Serial.print("mDNS responder started: ");
+    Serial.println(id);
     MDNS.addService("http", "tcp", 80);
   }
   else


Reordering lpg sense method

Reordering lpg sense method

--- MID/MID.ino
+++ MID/MID.ino
@@ -266,7 +266,7 @@
 #ifdef LPG_DET_IN_TIMER
 //TIMER0_COMPA_vect
 // https://github.com/NicoHood/PinChangeInterrupt/#pinchangeinterrupt-table
-ISR(TIMER0_COMPA_vect) {
+ISR(TIMER3_COMPA_vect) {
     carSens.sensLpg();
 };


Moved serial inject data to main functions.

--- MID/MID.ino
+++ MID/MID.ino
@@ -288,11 +288,7 @@
     shutDown.listener();
     //
     //  Read main buttons
-//    readButtons(BTN_PIN_UP, BTN_PIN_DW);
     midMenu.listener(cursorMenu);
-    //
-    // Handle navigation
-//    navigateMenu();
     //
     //  Switch to shutdown menu
     shutDown.cursor(cursorMenu);
@@ -300,7 +296,6 @@
     // Display menu
 #ifdef ARDUINOMID_LCD_DISPLAY_16x2_H
     switch (cursorMenu) {
-
         case MidMenu::MENU_ENTER:
             midMenu.lcdDisplay(&lcd);
             break;


Fix analog read afer Deep Sleep

Fix analog read afer Deep Sleep

--- FX-SaberOS.ino
+++ FX-SaberOS.ino
@@ -1158,7 +1158,6 @@
 #ifdef DEEP_SLEEP
   else if (SaberState == S_SLEEP) {
     if (PrevSaberState == S_CONFIG) { // just entered Sleep mode
-
       byte old_ADCSRA = ADCSRA;
       // disable ADC to save power
       // disable ADC
@@ -1167,11 +1166,12 @@

       // .. and the code will continue from here

-      ADCSRA = old_ADCSRA;   // re-enable ADC conversion
+
       SleepModeExit();
       SaberState = S_STANDBY;
       PrevSaberState = S_SLEEP;
       // play boot sound
+      ADCSRA = old_ADCSRA;   // re-enable ADC conversion
       SinglePlay_Sound(11);
       delay(20);
     }


fixbug

fixbug

--- RGB_matrix.ino
+++ RGB_matrix.ino
@@ -4,7 +4,8 @@

 #define BUZZER_PIN 8
 #define SWITCH_PIN 9
-#define isPress() digitalRead(SWITCH_PIN)
+//#define isPress() digitalRead(SWITCH_PIN)
+#define isPress() (false)

 PlayMelody song1(BUZZER_PIN);
 PlayMelody song2(BUZZER_PIN);
@@ -19,6 +20,8 @@
     song1.setMelody(melody1,noteDurations1,82);
     song2.setMelody(melody2,noteDurations2,68);

+    Serial.begin(115200);
+    Serial.println("Ready.");
 }

 void loop(){
@@ -27,16 +30,19 @@
     while( !isPress() ){
         delay(500);
         song1.play();
-        while( song1.isPlaying() || !isPress() ){
+        while( song1.isPlaying() && !isPress() ){
             static unsigned long cnt=0;
             cnt += song1.play();
             Led::setAll(OFF);
             Led::set(cnt%9,WHITE);
-            Led::lighting();
+//            Led::lighting();
+            Serial.print(song1.isPlaying());
+            Serial.print("_");
+            Serial.println( song1.isPlaying() && !isPress());
         }
         song1.stop();
         Led::setAll(OFF);
-        Led::lighting();
+//        Led::lighting();
     }
     while( isPress() );  //スイッチが離されるまで待つ

@@ -59,6 +65,7 @@
         song2.stop();
         Led::setAll(OFF);
         Led::lighting();
+        Serial.println("_");
     }
     while( isPress() );  //スイッチが離されるまで待つ


1.0 RC5

1.0 RC5

- Improved Swing detection
- Improved Clash detection
- Improved sound relaunch detection
- Improved RGB LEDs colors management
- 2ko less on produced hex files
- Added a "Wrist Twist" movement (in case you want to bury your saber in
an airlock)
- Added "Force effect" (short press on main button in action mode)
- Corrected a major bug that prevented LSOS from building in ArduinoIDE
- Code cleaning  (again)
- Many minor bug correction

--- Lightsaber.ino
+++ Lightsaber.ino
@@ -60,7 +60,11 @@
 #define LEDSTRING5 			10
 #define LEDSTRING6 			11
 #ifdef LUXEON
-#define COLORS		 		48   // Number of RGB (not RGBW) colors in our array. Has to be  6x2^X. Default value is 48=6x2^4
+/* COLORS
+ * Number of colors to chose from
+ * Range : 6-600
+ */
+#define COLORS		 		48
 #define LED_RED 			3
 #define LED_GREEN 			5
 #define LED_BLUE 			6


Add two new options to main loop : SSDP and Discovery

--- _36_Bricks.ino
+++ _36_Bricks.ino
@@ -14,6 +14,8 @@
 //#define MODULE_CURRENT

 #define OPTION_AUTO_UPDATE
+#define OPTION_SSDP
+#define OPTION_DISCOVERY
 #define OPTION_MQTT
 #define OPTION_NTP

@@ -26,6 +28,11 @@
 //#define BRICK_TYPE "Muscle"

 #define FIRMWARE_VERSION "36Brick Firmware v0.40.0"
+
+
+#define DEBUG_ESP_HTTP_CLIENT
+#define DEBUG_ESP_PORT Serial
+

 #include <ESP8266WiFi.h>
 #include <ESP8266WebServer.h>
@@ -67,6 +74,18 @@
     #define AUTO_UPDATE_URL  "http://192.168.2.8/bricks/update.php" // Update server url
     #include "AutoUpdate.h"
     autoUpdateOption autoUpdate;
+#endif
+
+#if defined(OPTION_DISCOVERY)               // Discovery option
+    #include <ESP8266Ping.h>                // Ping library
+    #include "Discovery.h"
+    discoveryOption discovery;
+#endif
+
+#if defined(OPTION_SSDP)                    // SSDP option
+    #include <ESP8266SSDP.h>
+    #include "SSDP.h"
+    ssdpOption SSPD;
 #endif

 #if defined(MODULE_OUTPUTS)                 // Outputs module
@@ -136,8 +155,9 @@
  * Main setup : setups all chosen modules and options
  */
 void setup() {
+    ping_option a;
     Log::setup();
-    Log::Logln("[NFO] Power ON");
+    Log::Logln("[NFO] Power ON - " + String(FIRMWARE_VERSION));
     Log::Logln("[NFO] Serial started");

     Settings::read();                       // Read config from EEPROM


Commenting out barometer and compass for now

--- TeensyQuad.ino
+++ TeensyQuad.ino
@@ -35,8 +35,8 @@
 // Hold sensor values and calibration
 L3G gyro;
 ADXL345 accel;
-HMC5883L compass;
-Adafruit_BMP085 barometer;
+//HMC5883L compass;
+//Adafruit_BMP085 barometer;
 int calIdx = 0;
 float rollCalibration, pitchCalibration, yawCalibration;
 float gyroRollRaw, gyroPitchRaw, gyroYawRaw;
@@ -126,6 +126,7 @@
   Serial.println(F("Accel initialized"));
   delay(250);

+/*
   Serial.println(F("Finding Compass..."));
   compass = HMC5883L();
   int error;
@@ -139,7 +140,9 @@
   }
   Serial.println(F("Compass initialized"));
   delay(250);
-
+*/
+
+/*
   Serial.println(F("Finding Barometer..."));
   if (!barometer.begin()) {
     Serial.println(F("Failed to detect barometer!"));
@@ -147,6 +150,7 @@
   }
   Serial.println(F("Barometer initialized"));
   delay(250);
+*/

   // Set the PID values
   rollKp = ROLL_PID_KP;
@@ -278,6 +282,7 @@
   // Final values are angle in degrees.
 }

+/*
 void readCompass() {
   MagnetometerScaled scaled = compass.ReadScaledAxis();
   heading = atan2(scaled.YAxis, scaled.XAxis);
@@ -288,7 +293,9 @@

   heading *= RAD_TO_DEG;
 }
-
+*/
+
+/*
 void readAltitude() {
   // Get altitude in meters.
   altitude = (altitude * 0.98f) + (barometer.readAltitude() * 0.02f);
@@ -297,6 +304,7 @@
   // Get pressure in Pa.
 //  pressure = (pressure * 0.98f) + (barometer.readPressure() * 0.02f);
 }
+*/

 void Motors_init() {
   // Adjust the PWM frequency to 250kHz


Added names into Credits

Added names into Credits

--- arduboy-game/arduboy-game.ino
+++ arduboy-game/arduboy-game.ino
@@ -150,26 +150,31 @@

 void creditsScreen() {
   // TODO, this is placeholder
-  const char* credits[] = {"CREDITS", "p1", "p2", "p3", "p4", "p5", "p6"};
+  playMusic(1);
+  const char* credits[] = {"CREDITS", "Jay Garcia", "Simon Prickett", "Stan Bershadskiy", "Andrew Owen",
+                           "Andy Dennis", "Timothy Eagan", "Drew Griffith", "JD Jones",
+                           "Jon Van Dalen", "Lucas Still", "Matt McCants"};
   unsigned short arrsize = sizeof(credits) / sizeof(int);
-  scrollCredits(5, arrsize, credits, false);
-  delay(1000);
+  scrollCredits(4, arrsize, credits, false);
+  stopMusic();
 }

 void scrollCredits(int y, unsigned short arrsize, char* credits[], bool quit) {
   /**
      Recursive function for scrolling
-     creddits up screen
+     credits up screen
   */
   byte padding = 7;
   byte textSize = 1;
-
+  int origY = y;
   arduboy.clear();
   for (unsigned short i = 0; i < arrsize; i++) {
     if (i == 0) {
       textSize = 2;
+      y = y - 4;
     } else {
       textSize = 1;
+      y = origY;
     }
     printText(credits[i], 20, y + padding, textSize);
     arduboy.display();


Test bluetooth with Arduino

Test bluetooth with Arduino

--- arduino/mazeball/mazeball.ino
+++ arduino/mazeball/mazeball.ino
@@ -1,27 +1,36 @@
 #define DELAY 100

+/**
+ * Inicialmente vamos usar Serial1 (18 e 19) para o shield bluetooth
+ * e Serial (0 e 1) para monitoraçao/depuraçao
+ */
+
 void setup() {
-  Serial.begin(9600); // Pins 0 (RX) and 1 (TX)
+  Serial.begin(115200); // Pins 0 (RX) and 1 (TX)
   Serial1.begin(9600); // Pins 19 (RX) and 18 (TX), Serial2 on 17 and 16, Serial3 on 15 and 14
 }

 void loop() {
-  if (Serial.available() > 0) {
-    char c = Serial.read();
+  if (Serial1.available() > 0) {
+    char c = Serial1.read();
     if (c == 't') { // Move top
       // Do something
+      Serial.println("Veio t");
       goto skip;
     }
     if (c == 'b') { // Move bottom
       // Do something
+      Serial.println("Veio b");
       goto skip;
     }
     if (c == 'l') { // Move left
       // Do something
+      Serial.println("Veio l");
       goto skip;
     }
     if (c == 'r') { // Move right
       // Do something
+      Serial.println("Veio r");
       goto skip;
     }
   }


InterruptGenerator example ok.

InterruptGenerator example ok.

--- examples/InterruptGenerator/InterruptGenerator.ino
+++ examples/InterruptGenerator/InterruptGenerator.ino
@@ -1,3 +1,10 @@
+/**
+ * @file InterruptGenerator.ino
+ * Example of accelerometer interruptio generator usage.
+ *
+ * Copyright (c) 2015 Circuitar
+ * This software is released under the MIT license. See the attached LICENSE file for details.
+ */
 #include <Wire.h>
 #include <Nanoshield_IMU.h>
 #include <PinChangeInterrupt.h>
@@ -38,25 +45,30 @@
 void loop() {
   bool movDetected = false;

+  // Read interruption flag atomically to avoid concurrency.
   ATOMIC_BLOCK(ATOMIC_FORCEON) {
     movDetected = movementDetected;
   }

   if(movDetected) {
+    // Check the interrupt generator status to find what happened.
     int intStatus = imu.getAccelIntGenerator1Status();

+    // Check if movement in Z positive axis.
     if((intStatus & LSM303D_ZONE_ZH) != 0) {
       Serial.print("Movement on Z: ");
       Serial.print(imu.readAccelZ());
       Serial.println("g");
     }

+    // Check if movement in Y positive or negative axes.
     if((intStatus & (LSM303D_ZONE_YH | LSM303D_ZONE_YL)) != 0) {
       Serial.print("Movement on Y: ");
       Serial.print(imu.readAccelY());
       Serial.println("g");
     }

+    // Check if movement in X positive or negative axes.
     if((intStatus & (LSM303D_ZONE_XH | LSM303D_ZONE_XL)) != 0) {
       Serial.print("Movement on X: ");
       Serial.print(imu.readAccelX());
@@ -65,6 +77,7 @@

     Serial.println();

+    // Atomically reset interruption flag.
     ATOMIC_BLOCK(ATOMIC_FORCEON) {
       movementDetected = false;
     }


Examples: removing unneeded #include

Examples: removing unneeded #include

--- examples/03-Intermediate/WDRC_FIR_8Band/WDRC_FIR_8Band.ino
+++ examples/03-Intermediate/WDRC_FIR_8Band/WDRC_FIR_8Band.ino
@@ -26,15 +26,9 @@

 // Include all the of the needed libraries
-//include "AudioStream_Mod.h" //include my custom AudioStream.h...this prevents the default one from being used
-//include <Audio.h>      //Teensy Audio Library
-#include <Wire.h>
-#include <SPI.h>
-//include <SD.h>
-//include <SerialFlash.h>
 #include <Tympan_Library.h>

-
+// Define the digital audio parameters
 const float sample_rate_Hz = 24000.0f ; //24000 or 44117.64706f (or other frequencies in the table in AudioOutputI2S_F32
 const int audio_block_samples = 32;  //do not make bigger than AUDIO_BLOCK_SAMPLES from AudioStream.h (which is 128)
 AudioSettings_F32   audio_settings(sample_rate_Hz, audio_block_samples);


changing byte to a 16bit uint, to make it slower but safer

--- examples/CaroloCar/CaroloCar.ino
+++ examples/CaroloCar/CaroloCar.ino
@@ -27,7 +27,7 @@
 volatile boolean steeringSignalPending = false;
 volatile unsigned int steeringSignalFreq = 0;

-volatile byte qualityControl = 0; //if this byte is 11111111, that means the measurements we received were of good quality (controller is turned on)
+volatile unsigned int qualityControl = 0; //if this byte is 1111111111111111, that means the measurements we received were of good quality (controller is turned on)
 const unsigned short MINIMUM_FREQUENCY = 900; //frequencies below this will be disregarded
 unsigned int throttleFreq = 0;
 unsigned int servoFreq = 0;
@@ -66,7 +66,7 @@

 void handleOverride() {
   noInterrupts();
-  boolean qualityCheck = (qualityControl == B11111111); //true if the last 8 measurements were valid
+  boolean qualityCheck = (qualityControl == 0xFFFF); //true if the last 16 measurements were valid
   interrupts();
   if (qualityCheck) { //good quality, means that the RC controller is turned on, therefore we should go on override mode
     overrideTriggered = true;


Update Discovery.ino to work in ardunio

Update Discovery.ino to work in ardunio

--- examples/Discovery/Discovery.ino
+++ examples/Discovery/Discovery.ino
@@ -25,13 +25,13 @@
 #include <fstream>
 #include <iostream>

-#include "OpenSSLConnection.hpp"
+#include "aws-iot-device-sdk-cpp.h"

 #include "util/logging/Logging.hpp"
 #include "util/logging/LogMacros.hpp"
 #include "util/logging/ConsoleLogSystem.hpp"

-#include "ConfigCommon.hpp"
+#include "Arduino.h"
 #include "Discovery.hpp"

 #define LOG_TAG_DISCOVERY_SAMPLE "[Sample - Discovery]"
@@ -330,7 +330,7 @@
     }
 }

-int main(int argc, char **argv) {
+void setup() {
     std::shared_ptr<awsiotsdk::util::Logging::ConsoleLogSystem> p_log_system =
         std::make_shared<awsiotsdk::util::Logging::ConsoleLogSystem>(awsiotsdk::util::Logging::LogLevel::Info);
     awsiotsdk::util::Logging::InitializeAWSLogging(p_log_system);
@@ -348,6 +348,8 @@
 #endif

     awsiotsdk::util::Logging::ShutdownAWSLogging();
-    return static_cast<int>(rc);
 }

+void loop() {
+  delay(100);
+}


use_camel case

use_camel case

--- examples/mqtt_test/mqtt_test.ino
+++ examples/mqtt_test/mqtt_test.ino
@@ -23,8 +23,8 @@
 MqttWrapper *mqtt;
 DHT *dht;

-void initDht(DHT **dht, uint8_t pin, uint8_t dht_type);
-void readDht(DHT *dht, float *temp, float *humid);
+void init_dht(DHT **dht, uint8_t pin, uint8_t dht_type);
+void read_dht(DHT *dht, float *temp, float *humid);

 static float t_dht;
 static float h_dht;
@@ -35,7 +35,7 @@
     Serial.println(pub.payload_string());
 }

-void connectWifi()
+void connect_wifi()
 {
     WiFi.begin(ssid, pass);

@@ -52,7 +52,7 @@

 void hook_before_publish(JsonObject** root) {
   JsonObject& data = (*(*root))["d"];
-  readDht(dht, &t_dht, &h_dht);
+  read_dht(dht, &t_dht, &h_dht);

   data["myName"] = "NAT";
   data["temp"] = t_dht;
@@ -80,9 +80,6 @@
         //     result += ':';
     }

-    // topic_pub = String("esp8266-") + result;
-
-
     *(config.clientId) = String("d:quickstart:arduino:") + (result);
     *(config.topic_pub) = "iot-2/evt/status/fmt/json";

@@ -98,9 +95,9 @@
     delay(10);
     Serial.println("GO");

-    initDht(&dht, DHTPIN, DHTTYPE);
+    init_dht(&dht, DHTPIN, DHTTYPE);

-    connectWifi();
+    connect_wifi();

     // mqtt = new MqttWrapper("128.199.104.122", 1883, hook_before_connect);
     mqtt = new MqttWrapper("quickstart.messaging.internetofthings.ibmcloud.com", 1883, hook_before_connect);
@@ -113,7 +110,7 @@
 }

-void initDht(DHT **dht, uint8_t pin, uint8_t dht_type) {
+void init_dht(DHT **dht, uint8_t pin, uint8_t dht_type) {
     // Connect pin 1 (on the left) of the sensor to +5V
     // NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
     // to 3.3V instead of 5V!
@@ -137,10 +134,10 @@
 }

-void readDht(DHT *dht, float *temp, float *humid) {
+void read_dht(DHT *dht, float *temp, float *humid) {

     if (dht == NULL) {
-        DEBUG_PRINTLN(F("[dht22] is not initialised. please call initDht() first."));
+        DEBUG_PRINTLN(F("[dht22] is not initialised. please call init_dht() first."));
         return;
     }


massive update

massive update

--- short-circuit-limiter/short-circuit-limiter.ino
+++ short-circuit-limiter/short-circuit-limiter.ino
@@ -1,7 +1,7 @@
 #include <U8g2lib.h>
 #include "CTSensor.h"

-#define CURRENT_ENABLE_THRESHOLD 0.2
+#define CURRENT_ENABLE_THRESHOLD 0.23
 #define CURRENT_MCB_CUT 16

 #define PIN_LED 26
@@ -15,7 +15,7 @@

 #define BUZZER_BEEP_ON_TIME 20
 #define BUZZER_BEEP_OFF_TIME 300
-#define BUZZER_LONG_BEEP_TIME 500
+#define BUZZER_LONG_BEEP_TIME 2000

 #define CT_CALIBRATION_VALUE 60.6  // (100A / 0.05A) / 33 ohms
 #define INITIAL_SETTLE_TIME 20000 //20 seconds
@@ -28,7 +28,11 @@
 //The MCU can take 5500 samples/s.
 //0.05s seconds will require 275 samples/set
 #define NUM_CT_SAMPLES 275
-#define INTERVAL_PRINT 1000
+
+//Delay between LCD Print to avoid slowing down data collection
+#define INTERVAL_PRINT 500
+
+#define BACKLIGHT_BLINK_RATE 200

 typedef enum {
   STATE_MCB_TRIPPED, STATE_WINDOW_BEFORE, STATE_WINDOW_WITHIN, STATE_WINDOW_EXITED
@@ -40,12 +44,6 @@

 U8G2_UC1701_MINI12864_F_4W_SW_SPI u8g2(U8G2_R2, 21, 20, 19, 22);
 CTSensor clamp(PIN_CT, CT_CALIBRATION_VALUE);
-
-unsigned long lastDisplayTime = 0;
-double runningTotal = 0;
-int samplesTaken = 0;
-
-unsigned long enableWindowTime = 0;

 double mcbTrippedCurrent;

@@ -86,7 +84,7 @@

     u8g2.drawStr(80, 35, secondsBuffer);
     u8g2.setFont(u8g2_font_5x8_tr);
-    u8g2.drawStr(0,60, "Designer: Yeo Kheng Meng");
+    u8g2.drawStr(0,63, "Designer: Yeo Kheng Meng");

     u8g2.sendBuffer();

@@ -143,42 +141,100 @@
 }

 void displayToScreen(double currentValue){
-
   long long currentTime = millis();

-  runningTotal += currentValue;
-  samplesTaken++;
-
-  //We don't want to keep printing to screen as it is slow so we just do a running average
-  if((currentTime - lastDisplayTime) >= INTERVAL_PRINT){
-    float temperature = getTemperature();
-
-    lastDisplayTime = currentTime;
-    double average = runningTotal / samplesTaken;
-    Serial.println(average);
-
-    runningTotal = 0;
-    samplesTaken = 0;
-
-    u8g2.setFont(u8g2_font_9x18_tr);
-    char buffer[10];
-
-    dtostrf(currentValue, 4, 2, buffer);
-
+  if(currentState == STATE_MCB_TRIPPED){
     u8g2.clearBuffer();
-
-    u8g2.drawStr(0,20, buffer);
-
-    dtostrf(temperature, 4, 0, buffer);
-
-    u8g2.drawStr(0,40, buffer);
-
+    u8g2.setFont(u8g2_font_7x13_tr);
+    u8g2.drawStr(0,10, "Overcurrent!!!");
+
+    u8g2.drawStr(0,31, "Reset MCB >>>>>>>>");
+
+    char valueBuff[10];
+    char fullBuff[30];
+
+    dtostrf(mcbTrippedCurrent, 4, 1, valueBuff);
+    sprintf(fullBuff,"Tripped at: %sA", valueBuff);
+    u8g2.drawStr(0,50, fullBuff);
+
+    u8g2.setFont(u8g2_font_5x8_tr);
+    dtostrf(CURRENT_MCB_CUT, 4, 1, valueBuff);
+    sprintf(fullBuff,"Trip threshold: %sA", valueBuff);
+    u8g2.drawStr(0,63, fullBuff);
+
     u8g2.sendBuffer();
+
+  } else {
+
+    static double runningTotal = 0;
+    static int samplesTaken = 0;
+
+    runningTotal += currentValue;
+    samplesTaken++;
+
+    static unsigned long lastDisplayTime;
+    //We don't want to keep printing to screen as it is slow so we just do a running average
+    if((currentTime - lastDisplayTime) >= INTERVAL_PRINT){
+      float temperature = getTemperature();
+
+      lastDisplayTime = currentTime;
+      double average = runningTotal / samplesTaken;
+
+      runningTotal = 0;
+      samplesTaken = 0;
+
+      u8g2.clearBuffer();
+      u8g2.setFont(u8g2_font_7x13_tr);
+
+
+      switch(nextState){
+        case STATE_WINDOW_BEFORE:
+          u8g2.drawStr(0,10, "Limiter: In Effect");
+          break;
+        case STATE_WINDOW_WITHIN:
+          u8g2.drawStr(0,10, "Limiter:");
+          u8g2.drawStr(0,20, "Ready to Bypass...");
+          break;
+        case STATE_WINDOW_EXITED:
+          u8g2.drawStr(0,10, "Limiter: Bypassed");
+          break;
+        case STATE_MCB_TRIPPED:
+          //Fallthrough
+        default:
+          Serial.println("LCD Printing shouldn't come to this mode!");
+          break;
+       }
+
+       char valueBuff[10];
+       char fullBuff[30];
+
+       dtostrf(currentValue, 4, 2, valueBuff);
+       sprintf(fullBuff,"Current  : %sA", valueBuff);
+       u8g2.drawStr(0,33, fullBuff);
+
+       dtostrf(temperature, 2, 0, valueBuff);
+       sprintf(fullBuff,"Int. Temp: %sC", valueBuff);
+       u8g2.drawStr(0,47, fullBuff);
+
+       u8g2.setFont(u8g2_font_5x8_tr);
+       dtostrf(CURRENT_ENABLE_THRESHOLD, 4, 2, valueBuff);
+       sprintf(fullBuff,"Enable Current: %sA", valueBuff);
+       u8g2.drawStr(0,63, fullBuff);
+
+
+
+       u8g2.sendBuffer();
+    }
   }

 }

 STATE enterMCBTrippedMode(double currentValue){
+
+  static bool initialWarningTriggered = false;
+  static unsigned long initialWarningStart = 0;
+
+  unsigned long currentTime = millis();

   if(currentState != STATE_MCB_TRIPPED){
     changeMCBRelayState(false);
@@ -188,9 +244,35 @@
     mcbTrippedCurrent = currentValue;
     Serial.print("MCB tripped at: ");
     Serial.println(mcbTrippedCurrent);
-    longBeep();
-
-  }
+
+    initialWarningTriggered = true;
+    initialWarningStart = currentTime;
+    digitalWrite(PIN_BUZZER, HIGH);
+  }
+
+  //This is to sound the buzzer and blink the Backlight for BACKLIGHT_BLINK_RATE duration
+  if(initialWarningTriggered){
+
+    static bool displayBacklightCurrentlyOn = false;
+    static unsigned long displayBacklightLastChanged = 0;
+
+    if((currentTime - displayBacklightLastChanged) > BACKLIGHT_BLINK_RATE){
+      displayBacklightLastChanged = currentTime;
+      displayBacklightCurrentlyOn = !displayBacklightCurrentlyOn;
+      changeDisplayBacklight(displayBacklightCurrentlyOn);
+    }
+
+
+    if((currentTime - initialWarningStart) > BUZZER_LONG_BEEP_TIME){
+      initialWarningTriggered = false;
+      digitalWrite(PIN_BUZZER, LOW);
+      changeDisplayBacklight(true);
+
+    }
+
+  }
+
+

   int buttonPressed = digitalRead(PIN_BUTTON_ENTER);

@@ -206,6 +288,7 @@

     passFullCurrentThrough(false);
     changeMCBRelayState(true);
+    changeDisplayBacklight(false);

     currentState = STATE_WINDOW_BEFORE;
     Serial.println("Window Before");
@@ -223,6 +306,8 @@

 STATE enterWindowWithinMode(double currentValue){
   unsigned long currentTime = millis();
+
+  static unsigned long enableWindowTime = 0;

   if(currentState != STATE_WINDOW_WITHIN){
     currentState = STATE_WINDOW_WITHIN;
@@ -233,6 +318,7 @@
   if(currentValue < CURRENT_ENABLE_THRESHOLD){
     return STATE_WINDOW_BEFORE;
   } else if((currentTime - enableWindowTime) >= DELAY_BEFORE_LIMITER_RELAY_ENABLE){
+    //Exit window if no overcurrent is detected in this time
     return STATE_WINDOW_EXITED;
   } else {
     return STATE_WINDOW_WITHIN;
@@ -243,6 +329,7 @@

   if(currentState != STATE_WINDOW_EXITED){
     currentState = STATE_WINDOW_EXITED;
+    changeDisplayBacklight(true);
     Serial.println("Exited window, bypass resistor");
     shortBeepXTimes(1);
   }
@@ -316,10 +403,3 @@
   }

 }
-
-void longBeep(){
-  digitalWrite(PIN_BUZZER, HIGH);
-  delay(BUZZER_LONG_BEEP_TIME);
-  digitalWrite(PIN_BUZZER, LOW);
-}
-


fix default_keys example for avoid skipping first key

--- examples/rfid_default_keys/rfid_default_keys.ino
+++ examples/rfid_default_keys/rfid_default_keys.ino
@@ -81,12 +81,7 @@
     byte buffer[18];
     byte block = 0;
     MFRC522::StatusCode status;
-
-    // http://arduino.stackexchange.com/a/14316
-    if ( ! mfrc522.PICC_IsNewCardPresent())
-        return false;
-    if ( ! mfrc522.PICC_ReadCardSerial())
-        return false;
+
     // Serial.println(F("Authenticating using key A..."));
     status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, key, &(mfrc522.uid));
     if (status != MFRC522::STATUS_OK) {
@@ -153,5 +148,11 @@
             // no need to try other keys for this PICC
             break;
         }
+
+        // http://arduino.stackexchange.com/a/14316
+        if ( ! mfrc522.PICC_IsNewCardPresent())
+            break;
+        if ( ! mfrc522.PICC_ReadCardSerial())
+            break;
     }
 }


添加BlockPorcess（）函数

添加BlockPorcess（）函数

--- src/BaseNode/BaseNode.ino
+++ src/BaseNode/BaseNode.ino
@@ -19,7 +19,17 @@

 #define EEPROM_PHY_ADDR_START 0
 #define RF24_PAYLOAD 32
-
+#define BLOCK_S 0x40
+#define BLOCK_R 0x80
+#define BLOCK_I 0xC0
+#define BLOCK_S_RESQUEST              0x00
+#define BLOCK_S_REPLY                 0x01
+#define BLOCK_S_CMD_CONNECT           0x00
+#define BLOCK_S_CMD_DISCONNECT        0x01
+#define BLOCK_S_CMD_WAKEUP            0x02
+#define BLOCK_S_CMD_SYNC              0x03
+#define BLOCK_S_CMD_LINK              0x04
+#define BLOCK_S_CMD_CELL_PARAM        0x05
 RF24 radio(7,8);
 byte LocalPhyAddress[5];
 byte RemotePhyAddress[5];
@@ -56,8 +66,56 @@
   Serial.write(EEPROM.read(EEPROM_PHY_ADDR_START+4));
   return 0;
 }
+int BlockPorcess(byte* datain, byte* dataout)
+{
+  byte CTL = *datain;
+  byte LEN = *(datain + 1);
+  byte CRC = *(datain + LEN + 1);
+  byte BlockType;
+  byte cmd;
+  bit link;// more 1, last 0
+  bit reqp;//request 0 , reply 1
+  BlockType = (CTL&0xC0);
+  if(BLOCK_S == BlockType)
+  {
+    cmd = (CTL&0x1F);
+    reqp= (CTL&(1<<5));
+    switch(cmd)
+    {
+      case :
+
+      break;
+      default:
+      break;
+    }
+  }
+  else if(BLOCK_R == BlockType)
+  {    switch()
+    {
+      case :
+      break;
+      default:
+      break;
+    }
+  }
+  else if(BLOCK_I == BlockType)
+  {
+        switch()
+    {
+      case :
+      break;
+      default:
+      break;
+    }
+  }
+  else
+  {
+    // block type error
+  }
+}
 /*##################################################################################################*/
 void setup(){
+  uint64_t addr;
   Serial.begin(115200);

   LocalPhyAddress[0] = EEPROM.read(EEPROM_PHY_ADDR_START);
@@ -67,10 +125,12 @@
   LocalPhyAddress[4] = EEPROM.read(EEPROM_PHY_ADDR_START+4);
   memcpy( RemotePhyAddress,LocalPhyAddress,5);
   RemotePhyAddress[0] = 0x00;
-
-  radio.openWritingPipe(RemotePhyAddress);
-  radio.openReadingPipe(0,BroadCastAddress);
-  radio.openReadingPipe(1,LocalPhyAddress);
+  memcpy(addr,RemotePhyAddress,5);
+  radio.openWritingPipe(addr);
+  memcpy(addr,BroadCastAddress,5);
+  radio.openReadingPipe(0,addr);
+  memcpy(addr,LocalPhyAddress,5);
+  radio.openReadingPipe(1,addr);
   #if 0
   radio.begin();
   #endif
@@ -86,8 +146,8 @@
       {
         radio.read( data, RF24_PAYLOAD);             // Get the payload
       }
-
       radio.stopListening();                                        // First, stop listening so we can talk
+      BlockPorcess(data,data);
       radio.write( data, RF24_PAYLOAD);              // Send the final one back.
       radio.startListening();                                       // Now, resume listening so we catch the next packets.
    }


Update loop procedure to include all servos

--- Arduino/Arduino.ino
+++ Arduino/Arduino.ino
@@ -11,11 +11,13 @@
 Servo upDown;

 // VARIABLES
-int pos1 = 90;
-int pos2 = 90;
-int pos3 = 90;
-int pos4 = 90;
-int pos5 = 90;
+// Default positions for servos
+int pos1 = 0;
+int pos2 = 0;
+int pos3 = 0;
+int pos4 = 0;
+int pos5 = 0;
+
 int ByteReceived;   // store byte recieved via serial

 // INITIALIZE
@@ -40,18 +42,51 @@

 // UPDATE
 void loop() {
-  // Read information from Serial
+  // Get information from Serial
+  // First byte: Servo to write to
+  // Second byte: Value to write
+  //bool success = true;
   int Read = Serial.read();
-  if (Read != -1) {
-    ByteReceived = Read;
-    Serial.print(ByteReceived);
+  switch (Read) {
+    case 1:
+      // Throttle
+      int newPosition = Serial.read()
+      pos1 = newPosition;
+      throttle.write(pos1);
+      break;
+    case 2:
+      // Rotating Front
+      int newPosition = Serial.read()
+      pos2 = newPosition;
+      rotatingFront.write(pos2);
+      break;
+    case 3:
+      // Rotating Back
+      int newPosition = Serial.read()
+      pos3 = newPosition;
+      rotatingBack.write(pos3);
+      break;
+    case 4:
+      // Left-Right
+      int newPosition = Serial.read()
+      pos4 = newPosition;
+      leftRight.write(pos4);
+      break;
+    case 5:
+      // Up-Down
+      int newPosition = Serial.read()
+      pos5 = newPosition;
+      upDown.write(pos);
+      break;
+
+    default:
+      // if nothing else matches, do the default
+      // default is optional
+    break;
   }
-
-  // Write new positions
-  throttle.write(ByteReceived);
-  delay(1000);
-  ByteReceived = 0;

   // Send information to Serial

+  // Delay
+  delay(1000);
 }


Fixed soldered perf board and new trim pot


Some updates to attempt robustness of data transfer protocol

--- VendingMachineRFID.ino
+++ VendingMachineRFID.ino
@@ -18,23 +18,69 @@
 MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
 uint32_t lastCardScan; // Debounce RFID reads
 uint32_t timeBetweenScans;
-
 uint16_t credits_in_machine;//Serial.parseInt();
-char parseBuffer[2];

 void setup() {
   lastCardScan = 0;
-  timeBetweenScans = 1500; // TODO: Set to 1500 when in production
-  Serial.begin(9600); // Initialize serial communications with master vending arduino
+  timeBetweenScans = 800; // TODO: Set to 1500 when in production
+  Serial.begin(19200); // Initialize serial communications with master vending arduino
+  Serial.setTimeout(400);
   SPI.begin(); // Init SPI bus
   mfrc522.PCD_Init(); // Init MFRC522 card
 }

+uint8_t recieve_error;
+uint16_t rfid_recieve(){
+  char parseBuffer[10];
+  uint8_t recieveAttemptsRemaining = 11;
+  uint16_t number = 0;
+  while(recieveAttemptsRemaining-- > 0){
+    if(Serial.readBytes(parseBuffer, sizeof(parseBuffer)) == sizeof(parseBuffer)){
+      // Recieved correct ammount of bytes - check message integrity
+      if(memcmp(parseBuffer,parseBuffer+2,sizeof(parseBuffer)-2) == 0){
+        // OK
+        recieve_error = 0;
+        // Let other party know we do not need a retransmission
+        Serial.write(0);
+        memcpy(&number,parseBuffer,sizeof(number));
+        return number;
+      }
+    }
+    // Recieved incorrect ammount of bytes - Retry only if we are going to run function again
+    if(recieveAttemptsRemaining > 0)
+      Serial.write(recieveAttemptsRemaining+48);
+  }
+  recieve_error = 1; // timed out
+//number = 0;
+  // Let other party know we do not need a retransmission
+  Serial.write(0);
+  return number;
+}
+
+char rfid_transmit(uint16_t number){
+//uint16_t number;                      // 0001 0110 0100 0111
+  uint16_t mask   = B11111111;          // 0000 0000 1111 1111
+  uint8_t first_half   = number >> 8;   // >>>> >>>> 0001 0110
+  uint8_t sencond_half = number & mask; // ____ ____ 0100 0111
+  char waiting_for_ok = 1;
+  uint8_t transmitAttemptsRemaining = 10;
+  while(waiting_for_ok && transmitAttemptsRemaining-- > 0){
+    // Flush incoming buffer
+    while(Serial.available()){Serial.read();}
+    for (int i = 0; i < 10; i = i+2) {
+      Serial.write(sencond_half);
+      Serial.write(first_half);
+    }
+    Serial.readBytes(&waiting_for_ok,1);
+  }
+  return waiting_for_ok;
+}
+
 void loop() {
   // Look for new cards
-  if(!mfrc522.PICC_IsNewCardPresent()) {return;}
+  if(!mfrc522.PICC_IsNewCardPresent()) return;
   // Select one of the cards
-  if(!mfrc522.PICC_ReadCardSerial()) {return;}
+  if(!mfrc522.PICC_ReadCardSerial()) return;
   // Now a card is selected. The UID and SAK is in mfrc522.uid.

   // Dump UID
@@ -52,25 +98,28 @@
       while(Serial.available()){Serial.read();}
       // Fetch current credit count for the vending machine, in order to know whether to withdraw or deposit
       Serial.print("C");
+      credits_in_machine = rfid_recieve();
       //Serial.println(addr);
       // Attempt to recieve response from vending machine
       // If no response from has been recieved within a second, assume it is not powered/booted yet, stop processing
+      if(recieve_error == 1) return;
+      /*
       if(Serial.readBytes(parseBuffer, sizeof(parseBuffer)) != 2){
         //Serial.print("No response - aborting.");
         return;
       }
       //Serial.println(parseBuffer[0],DEC);
       //Serial.println(parseBuffer[1],DEC);
-      memcpy(&credits_in_machine,parseBuffer,sizeof(parseBuffer));
+      memcpy(&credits_in_machine,parseBuffer,sizeof(parseBuffer));*/
       // Zero credits in machine - done now to avoid race-conditions of people buying when saving credits
-      Serial.print("Z");
+      Serial.print("ZZZZZ"); // Zero five times
       //Serial.println(credits_in_machine);

       if(credits_in_machine == 0){ // Attempt withdrawal               ## WITHDRAW
         if(addr == 65535){ // New card!
           // ERR Beep + display "NO CREDITS"?
           //Serial.println("NO CREDITS - UNKNOWN CARD");
-          Serial.println("N");
+          Serial.print("N");
           // Halt PICC
           mfrc522.PICC_HaltA();
           // Return
@@ -82,7 +131,7 @@
           if(card.credits == 0){
             // ERR Beep + display "NO CREDITS"?
             //Serial.println("NO CREDITS - KNOWN CARD");
-            Serial.println("N");
+            Serial.print("N");
             // Halt PICC
             mfrc522.PICC_HaltA();
             // Return
@@ -95,16 +144,16 @@
             // Check if card has been changed
             // OK Beep + Set credits on vending machine
             Serial.print("S");
-            uint16_t number = current_credits;            // 0001 0110 0100 0111
-            uint16_t mask   = B11111111;          // 0000 0000 1111 1111
-            uint8_t first_half   = number >> 8;   // >>>> >>>> 0001 0110
-            uint8_t sencond_half = number & mask; // ____ ____ 0100 0111
-            Serial.write(sencond_half);
-            Serial.write(first_half);
+            char error = rfid_transmit(current_credits);
+            if(error != 0){
+              // Could not update machine credits - attempt to save credits to card again!
+              card.credits = current_credits;
+              updateAndVerify(addr,card);
+            }
           } else {
             // ERR Beep + display "ERR  EEPROM BAD" ?
             //Serial.println("ERR  EEPROM BAD");
-            Serial.println("B");
+            Serial.print("B");
             // Halt PICC
             mfrc522.PICC_HaltA();
             // Return
@@ -122,15 +171,10 @@
           if(addr == 65535){
             // Reset credits on vending machine
             Serial.print("S");
-            uint16_t number = credits_in_machine;            // 0001 0110 0100 0111
-            uint16_t mask   = B11111111;          // 0000 0000 1111 1111
-            uint8_t first_half   = number >> 8;   // >>>> >>>> 0001 0110
-            uint8_t sencond_half = number & mask; // ____ ____ 0100 0111
-            Serial.write(sencond_half);
-            Serial.write(first_half);
+            rfid_transmit(credits_in_machine);
             // ERR Beep + display "ERR  OUT OF MEMORY" ?
             //Serial.println("ERR  OUT OF MEMORY");
-            Serial.println("O");
+            Serial.print("O");
             // Halt PICC
             mfrc522.PICC_HaltA();
             // Return
@@ -148,17 +192,12 @@
         // Card found! (Known card OR found free spot for new card)
         // Attempt to add credits to card
         if(updateAndVerify(addr,card)){
+          Serial.print("C");
           // OK Beep
         } else{
           // Reset credits on vending machine
           Serial.print("S");
-          uint16_t number = credits_in_machine;            // 0001 0110 0100 0111
-          uint16_t mask   = B11111111;          // 0000 0000 1111 1111
-          uint8_t first_half   = number >> 8;   // >>>> >>>> 0001 0110
-          uint8_t sencond_half = number & mask; // ____ ____ 0100 0111
-          Serial.write(sencond_half);
-          Serial.write(first_half);
-
+          rfid_transmit(credits_in_machine);
           // ERR Beep + display "ERR  EEPROM BAD" ?
           //Serial.println("ERR  EEPROM BAD");
           Serial.print("B");
@@ -177,7 +216,7 @@
   EEPROM_updateAnything(addr,card);
   if(EEPROM_compareAnything(addr,card)){
     //Serial.print("Update OK - new credits:");
-    Serial.println(card.credits);
+    //Serial.println(card.credits);
     return true;
   }
   //Serial.print("Update verify error at address: ");


COH-71: bringing in sensor definition

COH-71: bringing in sensor definition

--- Arduino/COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
+++ Arduino/COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
@@ -70,6 +70,60 @@

 // Primary radio module.
 extern OTRadioLink::OTRadioLink &PrimaryRadio;
+
+// Sense (usually non-linearly) over full likely internal ambient lighting range of a (UK) home,
+// down to levels too dark to be active in (and at which heating could be set back for example).
+#ifdef ENABLE_AMBLIGHT_SENSOR
+// Sensor for ambient light level; 0 is dark, 255 is bright.
+typedef OTV0P2BASE::SensorAmbientLight AmbientLight;
+#else // !defined(ENABLE_AMBLIGHT_SENSOR)
+typedef OTV0P2BASE::DummySensorAmbientLight AmbientLight; // Dummy stand-in.
+#endif // ENABLE_AMBLIGHT_SENSOR
+// Singleton implementation/instance.
+extern AmbientLight AmbLight;
+
+// Create very light-weight standard-speed OneWire(TM) support if a pin has been allocated to it.
+// Meant to be similar to use to OneWire library V2.2.
+// Supports search but not necessarily CRC.
+// Designed to work with 1MHz/1MIPS CPU clock.
+#if defined(ENABLE_MINIMAL_ONEWIRE_SUPPORT)
+#define SUPPORTS_MINIMAL_ONEWIRE
+extern OTV0P2BASE::MinimalOneWire<> MinOW_DEFAULT_OWDQ;
+#endif
+
+// Cannot have internal and external use of same DS18B20 at same time...
+#if defined(ENABLE_EXTERNAL_TEMP_SENSOR_DS18B20) && !defined(ENABLE_PRIMARY_TEMP_SENSOR_DS18B20) && defined(ENABLE_MINIMAL_ONEWIRE_SUPPORT)
+#define SENSOR_EXTERNAL_DS18B20_ENABLE_0 // Enable sensor zero.
+extern OTV0P2BASE::TemperatureC16_DS18B20 extDS18B20_0;
+#endif
+
+// Ambient/room temperature sensor, usually on main board.
+#if defined(ENABLE_PRIMARY_TEMP_SENSOR_SHT21)
+extern OTV0P2BASE::RoomTemperatureC16_SHT21 TemperatureC16; // SHT21 impl.
+#elif defined(ENABLE_PRIMARY_TEMP_SENSOR_DS18B20)
+  #if defined(ENABLE_MINIMAL_ONEWIRE_SUPPORT)
+  // DSB18B20 temperature impl, with slightly reduced precision to improve speed.
+  extern OTV0P2BASE::TemperatureC16_DS18B20 TemperatureC16;
+  #endif // defined(ENABLE_MINIMAL_ONEWIRE_SUPPORT)
+#else // Don't use TMP112 if SHT21 or DS18B20 have been selected.
+extern OTV0P2BASE::RoomTemperatureC16_TMP112 TemperatureC16;
+#endif
+
+// HUMIDITY_SENSOR_SUPPORT is defined if at least one humidity sensor has support compiled in.
+// Simple implementations can assume that the sensor will be present if defined;
+// more sophisticated implementations may wish to make run-time checks.
+// If SHT21 support is enabled at compile-time then its humidity sensor may be used at run-time.
+#if defined(ENABLE_PRIMARY_TEMP_SENSOR_SHT21)
+#define HUMIDITY_SENSOR_SUPPORT // Humidity sensing available.
+#endif
+
+#if defined(ENABLE_PRIMARY_TEMP_SENSOR_SHT21)
+// Singleton implementation/instance.
+extern OTV0P2BASE::HumiditySensorSHT21 RelHumidity;
+#else
+// Dummy implementation to minimise coding changes.
+extern OTV0P2BASE::DummyHumiditySensorSHT21 RelHumidity;
+#endif

 #ifdef ALLOW_CC1_SUPPORT_RELAY_IO // REV9 CC1 relay...
 // Call this on even numbered seconds (with current time in seconds) to allow the CO UI to operate.
@@ -146,23 +200,14 @@
 static uint8_t minuteCount;

-
-
-
 // Indicate that the system is broken in an obvious way (distress flashing the main LED).
 // DOES NOT RETURN.
 // Tries to turn off most stuff safely that will benefit from doing so, but nothing too complex.
 // Tries not to use lots of energy so as to keep distress beacon running for a while.
 void panic()
   {
-#ifdef ENABLE_RADIO_PRIMARY_MODULE
   // Reset radio and go into low-power mode.
   PrimaryRadio.panicShutdown();
-#endif
-#ifdef ENABLE_RADIO_SECONDARY_MODULE
-  // Reset radio and go into low-power mode.
-  SecondaryRadio.panicShutdown();
-#endif
   // Power down almost everything else...
   OTV0P2BASE::minimisePowerWithoutSleep();
 #ifdef LED_HEATCALL
@@ -209,6 +254,65 @@
   OTV0P2BASE::serialPrintAndFlush(_YYYYMmmDD);
   OTV0P2BASE::serialPrintlnAndFlush(F(" " __TIME__));
   }
+
+
+#ifdef ENABLE_AMBLIGHT_SENSOR
+// Normal 2 bit shift between raw and externally-presented values.
+static const uint8_t shiftRawScaleTo8Bit = 2;
+#ifdef ENABLE_AMBIENT_LIGHT_SENSOR_PHOTOTRANS_TEPT4400
+// This implementation expects a phototransitor TEPT4400 (50nA dark current, nominal 200uA@100lx@Vce=50V) from IO_POWER_UP to LDR_SENSOR_AIN and 220k to ground.
+// Measurement should be taken wrt to internal fixed 1.1V bandgap reference, since light indication is current flow across a fixed resistor.
+// Aiming for maximum reading at or above 100--300lx, ie decent domestic internal lighting.
+// Note that phototransistor is likely far more directionally-sensitive than LDR and its response nearly linear.
+// This extends the dynamic range and switches to measurement vs supply when full-scale against bandgap ref, then scales by Vss/Vbandgap and compresses to fit.
+// http://home.wlv.ac.uk/~in6840/Lightinglevels.htm
+// http://www.engineeringtoolbox.com/light-level-rooms-d_708.html
+// http://www.pocklington-trust.org.uk/Resources/Thomas%20Pocklington/Documents/PDF/Research%20Publications/GPG5.pdf
+// http://www.vishay.com/docs/84154/appnotesensors.pdf
+static const int LDR_THR_LOW = 270U;
+static const int LDR_THR_HIGH = 400U;
+#else // LDR (!defined(ENABLE_AMBIENT_LIGHT_SENSOR_PHOTOTRANS_TEPT4400))
+// This implementation expects an LDR (1M dark resistance) from IO_POWER_UP to LDR_SENSOR_AIN and 100k to ground.
+// Measurement should be taken wrt to supply voltage, since light indication is a fraction of that.
+// Values below from PICAXE V0.09 impl approx multiplied by 4+ to allow for scale change.
+#ifdef ENABLE_AMBLIGHT_EXTRA_SENSITIVE // Define if LDR not exposed to much light, eg for REV2 cut4 sideways-pointing LDR (TODO-209).
+static const int LDR_THR_LOW = 50U;
+static const int LDR_THR_HIGH = 70U;
+#else // Normal settings.
+static const int LDR_THR_LOW = 160U; // Was 30.
+static const int LDR_THR_HIGH = 200U; // Was 35.
+#endif // ENABLE_AMBLIGHT_EXTRA_SENSITIVE
+#endif // ENABLE_AMBIENT_LIGHT_SENSOR_PHOTOTRANS_TEPT4400
+// Singleton implementation/instance.
+AmbientLight AmbLight(LDR_THR_HIGH >> shiftRawScaleTo8Bit);
+#endif // ENABLE_AMBLIGHT_SENSOR
+
+#if defined(ENABLE_MINIMAL_ONEWIRE_SUPPORT)
+OTV0P2BASE::MinimalOneWire<> MinOW_DEFAULT;
+#endif
+
+#if defined(SENSOR_EXTERNAL_DS18B20_ENABLE_0) // Enable sensor zero.
+OTV0P2BASE::TemperatureC16_DS18B20 extDS18B20_0(MinOW_DEFAULT, 0);
+#endif
+
+#if defined(ENABLE_PRIMARY_TEMP_SENSOR_SHT21)
+// Singleton implementation/instance.
+OTV0P2BASE::HumiditySensorSHT21 RelHumidity;
+#else
+OTV0P2BASE::DummyHumiditySensorSHT21 RelHumidity;
+#endif
+
+// Ambient/room temperature sensor, usually on main board.
+#if defined(ENABLE_PRIMARY_TEMP_SENSOR_SHT21)
+OTV0P2BASE::RoomTemperatureC16_SHT21 TemperatureC16; // SHT21 impl.
+#elif defined(ENABLE_PRIMARY_TEMP_SENSOR_DS18B20)
+#if defined(ENABLE_MINIMAL_ONEWIRE_SUPPORT)
+// DSB18B20 temperature impl, with slightly reduced precision to improve speed.
+OTV0P2BASE::TemperatureC16_DS18B20 TemperatureC16(MinOW_DEFAULT, 0, OTV0P2BASE::TemperatureC16_DS18B20::MAX_PRECISION - 1);
+#endif
+#else // Don't use TMP112 if SHT21 or DS18B20 are selected.
+OTV0P2BASE::RoomTemperatureC16_TMP112 TemperatureC16;
+#endif

 // Singleton FHT8V valve instance (to control remote FHT8V valve by radio).
 static const uint8_t _FHT8V_MAX_EXTRA_TRAILER_BYTES = (1 + max(OTV0P2BASE::MESSAGING_TRAILING_MINIMAL_STATS_PAYLOAD_BYTES, OTV0P2BASE::FullStatsMessageCore_MAX_BYTES_ON_WIRE));
@@ -1076,17 +1180,6 @@

 //  posPOST(1, F("Radio OK, checking buttons/sensors and xtal"));

-// FIXME FIXME FIXME
-//  // Collect full set of environmental values before entering loop() in normal mode.
-//  // This should also help ensure that sensors are properly initialised.
-//  const int heat = TemperatureC16.read();
-//#if defined(ENABLE_AMBLIGHT_SENSOR)
-//  const int light = AmbLight.read();
-//#endif
-//#if defined(HUMIDITY_SENSOR_SUPPORT)
-//  const uint8_t rh = RelHumidity.read();
-//#endif
-
   // Seed RNGs, after having gathered some sensor values in RAM...
   OTV0P2BASE::seedPRNGs();


Code formatting

Code formatting

--- freeduino_74hc595/freeduino_74hc595.ino
+++ freeduino_74hc595/freeduino_74hc595.ino
@@ -22,7 +22,7 @@
 int ledState = 0;
 const int ON = HIGH;
 const int OFF = LOW;
-
+

 /*
  * setup() - this function runs once when you turn your Arduino on
@@ -43,11 +43,10 @@
 {
   int delayTime = 100; //the number of milliseconds to delay between LED updates
   for(int i = 0; i < 256; i++){
-   updateLEDs(i);
-   delay(delayTime);
+    updateLEDs(i);
+    delay(delayTime);
   }
 }
-

 /*
@@ -64,19 +63,23 @@
  * updateLEDsLong() - sends the LED states set in ledStates to the 74HC595
  * sequence. Same as updateLEDs except the shifting out is done in software
  * so you can see what is happening.
- */
+ */
 void updateLEDsLong(int value){
   digitalWrite(latch, LOW);    //Pulls the chips latch low
   for(int i = 0; i < 8; i++){  //Will repeat 8 times (once for each bit)
-  int bit = value & B10000000; //We use a "bitmask" to select only the eighth
-                               //bit in our number (the one we are addressing this time through
-  value = value << 1;          //we move our number up one bit value so next time bit 7 will be
-                               //bit 8 and we will do our math on it
-  if(bit == 128){digitalWrite(data, HIGH);} //if bit 8 is set then set our data pin high
-  else{digitalWrite(data, LOW);}            //if bit 8 is unset then set the data pin low
-  digitalWrite(clock, HIGH);                //the next three lines pulse the clock pin
-  delay(1);
-  digitalWrite(clock, LOW);
+    int bit = value & B10000000; //We use a "bitmask" to select only the eighth
+    //bit in our number (the one we are addressing this time through
+    value = value << 1;          //we move our number up one bit value so next time bit 7 will be
+    //bit 8 and we will do our math on it
+    if(bit == 128){
+      digitalWrite(data, HIGH);
+    } //if bit 8 is set then set our data pin high
+    else{
+      digitalWrite(data, LOW);
+    }            //if bit 8 is unset then set the data pin low
+    digitalWrite(clock, HIGH);                //the next three lines pulse the clock pin
+    delay(1);
+    digitalWrite(clock, LOW);
   }
   digitalWrite(latch, HIGH);  //pulls the latch high shifting our data into being displayed
 }
@@ -84,14 +87,20 @@

 //These are used in the bitwise math that we use to change individual LEDs
 //For more details http://en.wikipedia.org/wiki/Bitwise_operation
-int bits[] = {B00000001, B00000010, B00000100, B00001000, B00010000, B00100000, B01000000, B10000000};
-int masks[] = {B11111110, B11111101, B11111011, B11110111, B11101111, B11011111, B10111111, B01111111};
+int bits[] = {
+  B00000001, B00000010, B00000100, B00001000, B00010000, B00100000, B01000000, B10000000};
+int masks[] = {
+  B11111110, B11111101, B11111011, B11110111, B11101111, B11011111, B10111111, B01111111};
 /*
  * changeLED(int led, int state) - changes an individual LED
  * LEDs are 0 to 7 and state is either 0 - OFF or 1 - ON
  */
- void changeLED(int led, int state){
-   ledState = ledState & masks[led];  //clears ledState of the bit we are addressing
-   if(state == ON){ledState = ledState | bits[led];} //if the bit is on we will add it to ledState
-   updateLEDs(ledState);              //send the new LED state to the shift register
- }
+void changeLED(int led, int state){
+  ledState = ledState & masks[led];  //clears ledState of the bit we are addressing
+  if(state == ON){
+    ledState = ledState | bits[led];
+  } //if the bit is on we will add it to ledState
+  updateLEDs(ledState);              //send the new LED state to the shift register
+}
+
+


remove trailing space

remove trailing space

--- examples/FirebaseStream_ESP8266/FirebaseStream_ESP8266.ino
+++ examples/FirebaseStream_ESP8266/FirebaseStream_ESP8266.ino
@@ -57,7 +57,7 @@
      auto type = fbase.read(event);
      Serial.print("event: ");
      Serial.println(type);
-     if (type != Firebase::Event::UNKNOWN) {
+     if (type != Firebase::Event::UNKNOWN) {
        Serial.print("data: ");
        Serial.println(event);


Split interrupt handler to multiple parts to allow using SPI interrupts later

--- avr/avr.ino
+++ avr/avr.ino
@@ -54,8 +54,8 @@
 uint8_t col_i = 0;
 uint8_t row_i = 0;
 volatile uint8_t may_flip = 0;
-int pwm_lengths[] = { 0x30, 0x10, 0x06 }; // PWM cycle lengths
-volatile int pwm_i = 0; // Current PWM cycle
+volatile uint16_t pwm_lengths[] = { 0x30, 0x10, 0x06 }; // PWM cycle lengths
+uint8_t pwm_i = 0; // Current PWM cycle

 // Hardware configuration
 #define PIN_COL_BIT0 A2
@@ -70,6 +70,8 @@

 inline static void frame_store(uint8_t intensity);
 inline static void set_pixel(uint8_t *plane);
+static void screen_on(void);
+inline static void pick_column(void);

 void buf_swap(void) {
 	uint8_t (*tmp)[56] = buf_front;
@@ -89,11 +91,13 @@
 	pinMode(9, OUTPUT); // OC1A main screen turn on
 	pinMode(PIN_ROW_LATCH, OUTPUT);
 	pinMode(PIN_COL_LATCH, OUTPUT);
+	pinMode(MOSI, OUTPUT);
+	pinMode(SCK, OUTPUT);

 	// Initialize serial and SPI
 	Serial.begin(19200);
-	SPI.begin();
-
+	SPCR = _BV(SPE) | _BV(MSTR) | _BV(SPR0); // SPI master, clock rate fck/16
+
 	// Timer magic
 	cli();
 	TCCR1A = 0;
@@ -209,26 +213,43 @@
 ISR(TIMER1_COMPA_vect)
 {
 	// Screen is off when we hit here (OC1A has been set LOW)
-
+
 	// Load new data to LED driver
 	digitalWrite(PIN_COL_LATCH, HIGH);

 	// Are we moving to next segment?
 	if (pwm_i == 0) {
-		// Switch the row on row driver if needed
 		if (col_i == 0) {
-			SPI.transfer(1 << row_i);
-
-			// Latch it
+			// Busy-write
+			SPDR = 1 << row_i;
+			while(!(SPSR & (1<<SPIF)));
+
+			// Latch the written row info
 			digitalWrite(PIN_ROW_LATCH, LOW);
 			digitalWrite(PIN_ROW_LATCH, HIGH);
-		}
-		// Pick correct column
-		digitalWrite(PIN_COL_BIT2, col_i & 0b100);
-		digitalWrite(PIN_COL_BIT1, col_i & 0b010);
-		digitalWrite(PIN_COL_BIT0, col_i & 0b001);
-      	}
-
+
+			pick_column();
+			screen_on();
+		} else {
+			// Switch column and turn on the screen.
+			pick_column();
+			screen_on();
+		}
+      	} else {
+		// Just turn on the screen, going to next PWM plane.
+		screen_on();
+	}
+}
+
+inline static void pick_column(void)
+{
+	digitalWrite(PIN_COL_BIT2, col_i & 0b100);
+	digitalWrite(PIN_COL_BIT1, col_i & 0b010);
+	digitalWrite(PIN_COL_BIT0, col_i & 0b001);
+}
+
+static void screen_on(void)
+{
 	// Main screen turn on! (Use Compare Output magic with OC1A)
 	TCCR1A = _BV(COM1A1) | _BV(COM1A0); // Set HIGH on match
 	TCCR1C = _BV(FOC1A); // Force match (turns the screen on)