Added switch code

Added switch code

--- Pan_Tilt_laser/Pan_Tilt_laser.ino
+++ Pan_Tilt_laser/Pan_Tilt_laser.ino
@@ -30,8 +30,30 @@

 #define DIRECTION_CHANGE_PROBABILITY 15

+volatile int sleepState = 0;
+const int ledPin =  4;      // the number of the LED pin
+
+
+void sleepInt(){
+  detachInterrupt(0);
+  sleepState = 1;
+  digitalWrite(ledPin, HIGH);
+
+
+}
+
+void wake(){
+  detachInterrupt(0);
+ sleepState = 0;
+
+digitalWrite(ledPin, LOW);
+
+}
+

 #define BAUD_RATE 115200
+
+const int switchPin = 3;     // the number of the pushbutton pin

 //X Position: lower numbers == Right
@@ -45,15 +67,46 @@

 StuLaser laser(5);

-
+int switchState = 0;

 void setup() {
-
+  pinMode(switchPin, INPUT);
   Serial.begin(BAUD_RATE);
+  pinMode(ledPin, OUTPUT);
+  digitalWrite(ledPin, HIGH);
+  delay(100);
+  digitalWrite(ledPin, LOW);
+  delay(100);
+  digitalWrite(ledPin, HIGH);
+  delay(100);
+  digitalWrite(ledPin, LOW);
+  delay(100);
+  digitalWrite(ledPin, HIGH);
+  delay(100);
+  digitalWrite(ledPin, LOW);
+
+
+
+  switchState = digitalRead(switchPin);
+   if (switchState == LOW) {
+    // turn LED off:
+    digitalWrite(ledPin, HIGH);
+    sleepState = 1;
+    //attachInterrupt(0, wake, RISING);
+    while(digitalRead(switchPin) == LOW){
+      millis();
+    }
+  }
+  else {
+    // turn LED on:
+    digitalWrite(ledPin, LOW);
+   // attachInterrupt(0, sleepInt, FALLING);
+  }
+

   panTilt.begin();
   laser.begin();
-
+
   panTiltX.angle = panTiltX.minAngle;
   panTiltY.angle = panTiltY.minAngle;
   panTilt.updateAngles();
@@ -73,11 +126,35 @@
   delay(2000);

   Serial.println("setup complete");
+//  attachInterrupt(0, sleepInt, FALLING);
 }

 void loop() {
+
+  if(digitalRead(switchPin) == LOW){
+
+    laser.fire(0);
+    digitalWrite(ledPin, HIGH);
+    panTiltX.angle = panTiltX.midAngle;
+    panTiltY.angle = panTiltY.midAngle;
+    panTilt.updateAngles();
+
+    delay(50);
+//    attachInterrupt(0, wake, RISING);
+
+    panTilt.detach();
+    while(digitalRead(switchPin) == LOW){
+      delay(10);
+
+    }
+    digitalWrite(ledPin, LOW);
+    panTilt.begin();
+    laser.fire(1);
+
+  }
+  //attachInterrupt(0, sleepInt, FALLING);
   randomSeed(analogRead(0));
   static unsigned long timePassed;
   static int changeVal;
@@ -210,6 +287,7 @@
   unsigned int delayVal = random(minSec, maxSec);
   laser.fire(0);
   panTilt.detach();
+
   unsigned long startTime = millis();
   for(unsigned long i = 0; i < delayVal; i++){
     while(millis() - startTime < 1000){
@@ -230,15 +308,15 @@
 void heartBeat(unsigned long mSeconds, int hbInterval){
   static unsigned long oldTime;
   if(mSeconds - oldTime > hbInterval){
-    uint8_t ledPin = 13;
+
     pinMode(ledPin, OUTPUT);
+    digitalWrite(ledPin, LOW);
+    delay(100);
     digitalWrite(ledPin, HIGH);
     delay(100);
     digitalWrite(ledPin, LOW);
     delay(100);
     digitalWrite(ledPin, HIGH);
-    delay(100);
-    digitalWrite(ledPin, LOW);
     oldTime = mSeconds;
   }
 }


Add missing include to DU-RDT example.

Add missing include to DU-RDT example.

--- examples/rdt/rdt.ino
+++ examples/rdt/rdt.ino
@@ -49,6 +49,7 @@
 #include <du-ino_indicators.h>
 #include <du-ino_save.h>
 #include <du-ino_clock.h>
+#include <du-ino_utils.h>
 #include <avr/pgmspace.h>

 #define CLOCK_BPM_MAX 300


saveConfigCallback has been finished

saveConfigCallback has been finished

We have to test it on the real environment

--- nodemcu-rgbstrip.ino
+++ nodemcu-rgbstrip.ino
@@ -33,7 +33,6 @@
 }

 void saveWifiConfigCallback() {
-  // TODO: Save the WiFiManager configuration
   Serial.println(FPSTR(SAVEWCONF));
   // Store the credentials for using it in the program
   stassid = WiFi.SSID();
@@ -41,12 +40,17 @@
   File configFile = SPIFFS.open(CONFNAME, "w");
   if (configFile) {
         Serial.println("saveConfigCallback: opened config file for writing the config");
+  } else {
+        Serial.println("saveConfigCallback: cannot opent the config file for write");
+        return;
   }
-  DynamicJsonBuffer jsonBuffer;
   Serial.println("saveConfigCallback: config file has been opened for savig the config and JSON buffer has been created successfully");
-  // TODO: PUT stassid and stapass to jsonBuffer
-  // TODO: print jsonBuffer to configFile
-  // ...
+  StaticJsonBuffer<200> jsonBuffer;
+  JsonObject& json = jsonBuffer.createObject();
+  json["sta_ssid"] = stassid;
+  json["sta_pass"] = stapass;
+  json.printTo(configFile);
+  Serial.println("saveConfigCallback: config save ok");
 }

 void configModeCallback(WiFiManager *myWfMan) {
@@ -123,7 +127,7 @@
     wfMan.startConfigPortal(ssid.c_str(), AP_PASSW);
   }

-  // Connect to the AP if not connected by the WiFiManager
+  /* Connect to the AP if not connected by the WiFiManager */
   WiFi.setAutoConnect(false);
   WiFi.setAutoReconnect(true);
   for (uint8_t count = 5; count > 0; count--) {
@@ -152,5 +156,5 @@
 void loop() {
   // put your main code here, to run repeatedly:
   // myServer.handleClient();
-  delay(1000);
+  delay(200);
 }


modified esc_throttle code

modified esc_throttle code

--- arduino/src/T-80AFLAME/esc_throttle/esc_throttle.ino
+++ arduino/src/T-80AFLAME/esc_throttle/esc_throttle.ino
@@ -33,8 +33,8 @@
 #define RC_MIN       1100
 #define RC_MID       1500
 #define RC_MAX       1900
-#define ESC_MIN      1400
-#define ESC_MAX      1750
+#define ESC_MIN      1450
+#define ESC_MAX      1830

 // Various global variables
 int channels[4];


Specific MQTT library to use

Specific MQTT library to use

--- examples/DimSwitchTester-ESP-MQTT/DimSwitchTester-ESP-MQTT.ino
+++ examples/DimSwitchTester-ESP-MQTT/DimSwitchTester-ESP-MQTT.ino
@@ -87,6 +87,7 @@
 #define LAMP_STATE_COMMAND "control/LightSwitch"
 #define SENSOR_CALIBRATE "control/Calibrate"
 //
+// Use MQTT library by @Imroy - https://github.com/Imroy/pubsubclient
 #include <PubSubClient.h>
 WiFiClient mqttClient;
 PubSubClient MQTTclient(mqttClient, "test.mosquitto.org");


Added more info

Added more info

--- examples/mqtt_arbitrary_data/mqtt_arbitrary_data.ino
+++ examples/mqtt_arbitrary_data/mqtt_arbitrary_data.ino
@@ -137,7 +137,8 @@
   arbPac.s.val3 = 3354;

   /*
-    // Alternate Union with anonymous struct
+   // Alternate Union with anonymous struct
+   // (see union declaration above)

      strcpy_P(arbPac.charAry, strVal);
      arbPac.val1 = -4533;


Update ST_Anything_Generic_Test_Sketch.ino


Update Wrench-Mask-BLE_Unicorn-Hat-HD.ino

Added color parameter to drawFace function used with single mask faces for consistency in implementation of the function.

--- NRF52832/Unicorn_Hat_HD/Wrench-Mask-BLE_Unicorn-Hat-HD.ino
+++ NRF52832/Unicorn_Hat_HD/Wrench-Mask-BLE_Unicorn-Hat-HD.ino
@@ -92,7 +92,7 @@
   startAdv();

   // Draw Initial Face Pattern
-  drawFace(face001_Left, face001_Right);
+  drawFace(colorWhite, face001_Left, face001_Right);
 }

 void startAdv(void)
@@ -121,28 +121,28 @@
    {
     case 0x2B: incrementBrightness(); break;
     case 0x2D: decrementBrightness(); break;
-    case 0x30: drawFace(face010_Left, face010_Right); break; // Draw Face010
-    case 0x31: drawFace(face001_Left, face001_Right); break; // Draw Face001
-    case 0x32: drawFace(face002_Left, face002_Right); break; // Draw Face002
-    case 0x33: drawFace(face003_Left, face003_Right); break; // Draw Face003
-    case 0x34: drawFace(face004_Left, face004_Right); break; // Draw Face004
-    case 0x35: drawFace(face005_Left, face005_Right); break; // Draw Face005
-    case 0x36: drawFace(face006_Left, face006_Right); break; // Draw Face006
-    case 0x37: drawFace(face007_Left, face007_Right); break; // Draw Face007
-    case 0x38: drawFace(face008_Left, face008_Right); break; // Draw Face008
-    case 0x39: drawFace(face009_Left, face009_Right); break; // Draw Face009
-    case 0x41: drawFace(face011_Left, face011_Right); break; // Draw Face011
-    case 0x42: drawFace(face012_Left, face012_Right); break; // Draw Face012
-    case 0x43: drawFace(face013_Left, face013_Right); break; // Draw Face013
-    case 0x44: drawFace(face014_Left, face014_Right); break; // Draw Face014
-    case 0x45: drawFace(face015_Left, face015_Right);break; // Draw Face015
-    case 0x46: drawFace(face016_Left, face016_Right); break; // Draw Face016
-    case 0x47: drawFace(face017_Left, face017_Right); break; // Draw Face017
-    case 0x48: drawFace(face018_Left, face018_Right); break; // Draw Face018
-    case 0x49: drawFace(face019_Left, face019_Right); break; // Draw Face019
-    case 0x4A: drawFace(face020_Left, face020_Right); break; // Draw Face020
-    case 0x4B: drawFace(face021_Left, face021_Right); break; // Draw Face021
-    case 0x4C: drawFace(face022_Left, face022_Right); break; // Draw Face022
+    case 0x30: drawFace(color, face010_Left, face010_Right); break; // Draw Face010
+    case 0x31: drawFace(color, face001_Left, face001_Right); break; // Draw Face001
+    case 0x32: drawFace(color, face002_Left, face002_Right); break; // Draw Face002
+    case 0x33: drawFace(color, face003_Left, face003_Right); break; // Draw Face003
+    case 0x34: drawFace(color, face004_Left, face004_Right); break; // Draw Face004
+    case 0x35: drawFace(color, face005_Left, face005_Right); break; // Draw Face005
+    case 0x36: drawFace(color, face006_Left, face006_Right); break; // Draw Face006
+    case 0x37: drawFace(color, face007_Left, face007_Right); break; // Draw Face007
+    case 0x38: drawFace(color, face008_Left, face008_Right); break; // Draw Face008
+    case 0x39: drawFace(color, face009_Left, face009_Right); break; // Draw Face009
+    case 0x41: drawFace(color, face011_Left, face011_Right); break; // Draw Face011
+    case 0x42: drawFace(color, face012_Left, face012_Right); break; // Draw Face012
+    case 0x43: drawFace(color, face013_Left, face013_Right); break; // Draw Face013
+    case 0x44: drawFace(color, face014_Left, face014_Right); break; // Draw Face014
+    case 0x45: drawFace(color, face015_Left, face015_Right);break; // Draw Face015
+    case 0x46: drawFace(color, face016_Left, face016_Right); break; // Draw Face016
+    case 0x47: drawFace(color, face017_Left, face017_Right); break; // Draw Face017
+    case 0x48: drawFace(color, face018_Left, face018_Right); break; // Draw Face018
+    case 0x49: drawFace(color, face019_Left, face019_Right); break; // Draw Face019
+    case 0x4A: drawFace(color, face020_Left, face020_Right); break; // Draw Face020
+    case 0x4B: drawFace(color, face021_Left, face021_Right); break; // Draw Face021
+    case 0x4C: drawFace(color, face022_Left, face022_Right); break; // Draw Face022
     case 0x4D: drawFace(colorRed, colorWhite, face023_Red, face023_White); break; // Draw Face023
     case 0x4E: drawFace(colorRed, colorWhite, face024_Red, face024_White); break; // Draw Umbrella Corp logo
     case 0x57: setFaceColor(colorRed); break;
@@ -176,7 +176,7 @@
   waitForEvent();
 }

-void drawFace(byte leftEye[][ROW_SIZE], byte rightEye[][ROW_SIZE])
+void drawFace(uint32_t color, byte leftEye[][ROW_SIZE], byte rightEye[][ROW_SIZE])
 {
 maskedColorWipeEye("leftEye", color, leftEye);
 maskedColorWipeEye("rightEye", color, rightEye);


Bridge, TemperatureWebPanel example: mention that the REST API must be "open"

--- libraries/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino
+++ libraries/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino
@@ -8,7 +8,7 @@
  * TMP36 temperature sensor on analog pin A1
  * SD card attached to SD card slot of the Arduino Yún

- This sketch must be uploaded via wifi.
+ This sketch must be uploaded via wifi. REST API must be set to "open".

  Prepare your SD card with an empty folder in the SD root
  named "arduino" and a subfolder of that named "www".


Use the arduino encoder library and interrupts for speed

--- DRO.ino
+++ DRO.ino
@@ -1,13 +1,19 @@

 // DRO.ino
+//#define ENCODER_OPTIMIZE_INTERRUPTS
+#include <Encoder.h>

 #include "utility/twi.h"
 #include "Wire.h"

 #include "LCDSmoothiePanel.h"

+
+
 #define LE_ENCA 2
 #define LE_ENCB 3
+
+Encoder lme(LE_ENCA, LE_ENCB);

 int readEncoderDelta(char &old_AB)
 {
@@ -18,7 +24,6 @@
     state = enc_states[(old_AB & 0x0f)];
     return state;
 }
-

 void setup()
 {
@@ -48,7 +53,9 @@
     // }
     // Wire.endTransmission();

-    pos += readEncoderDelta(enc1);
+    // pos += readEncoderDelta(enc1);
+    pos= lme.read();
+
     if(pos != lastpos && millis() > lt1) {
         //Serial.println(pos);
         //lcd_setCursor(0, 1);
@@ -60,14 +67,15 @@
         lcd_setCursor(0, 2);
         lcd_printf("%5ld.%04ld mm", p/1000, abs(p%1000));
         lastpos = pos;
-        lt1 = millis() + 1000;
+        lt1 = millis() + 100;
     }

     if(millis() > lt2) {
         // read buttons
         uint8_t b= lcd_readButtons();
         if(b & BUTTON_LEFT) {
-            pos= 0;
+            //pos= 0;
+            lme.write(0);
         }
         lt2= millis() + 200;
     }


HOLY SHIT IT WORKS

HOLY SHIT IT WORKS

moveForward

--- 2018-FirefighterL1/2018-FirefighterL1.ino
+++ 2018-FirefighterL1/2018-FirefighterL1.ino
@@ -5,11 +5,11 @@

 #include "FreqCount.h"

-#define LEFT_MOTOR_1 8
-#define LEFT_MOTOR_2 9
-
-#define RIGHT_MOTOR_1 10
-#define RIGHT_MOTOR_2 11
+#define LEFT_MOTOR_1 6
+#define LEFT_MOTOR_2 7
+
+#define RIGHT_MOTOR_1 8
+#define RIGHT_MOTOR_2 9

 #define IR_PIN_LEFT 6
 #define IR_PIN_RIGHT 20
@@ -36,15 +36,15 @@

 // Bounds for start sound frequency:
 #define LOW_START 3306
-#define HIGH_START 4294
+#define HIGH_START 4200

 Motor leftMotor(LEFT_MOTOR_1, LEFT_MOTOR_2);
 Motor rightMotor(RIGHT_MOTOR_1,RIGHT_MOTOR_2);
 Servo extinguisher;

 //Motor top speeds
-double rightSpeed = 0.3;
-double leftSpeed = 0.3;
+double rightSpeed = 0.5;
+double leftSpeed = 0.5;

 //dog flags
 bool dog1 = false;
@@ -56,8 +56,8 @@
 Ultrasonic backUltrasonic(B_ECHO, B_TRIG, true);

 //Move controls
-float v_max = 5;
-float t_acceleration = 0.5;
+float v_max = 24;
+float t_acceleration = 0;

 float getRotation();

@@ -88,7 +88,7 @@
   float time_travel = (distance/v_max) - t_acceleration;
   leftMotor.set(leftSpeed);
   rightMotor.set(rightSpeed);
-  delay(time_travel/1000);
+  delay(time_travel*1000);
   leftMotor.set(0);
   rightMotor.set(0);
 }
@@ -290,6 +290,8 @@
 }

 void setup() {
+  stopRobot();
+
   // put your setup code here, to run once:
   Serial.begin(115200);
   Serial.println("Setting up extinguisher");
@@ -310,9 +312,15 @@
   setup_gyro();
   resetGyro();

-  Serial.println("Listening for microphone");
-  FreqCount.begin(200); // Begin measuring sound
-  checkMicrophone();  //robot stays in setup until frequency is heard
+  stopRobot();  //for the love of god stop
+
+  while(true){
+    Serial.println("Listening for microphone");
+    FreqCount.begin(200); // Begin measuring sound
+    checkMicrophone();  //robot stays in setup until frequency is heard
+
+    moveForward(36);
+  }
 }

 void loop() {


Reformat indentaion

Reformat indentaion

--- cirkit_unit03_driver/arduino/steer_ctrl/steer_ctrl.ino
+++ cirkit_unit03_driver/arduino/steer_ctrl/steer_ctrl.ino
@@ -33,6 +33,7 @@

 /* Define pulse width time of the stepping motor. */
 #define PULSE_WIDTH_MICRO_SECOND 500
+
 /* Define direction of angular z. */
 enum {
   LEFT,
@@ -60,8 +61,8 @@
 void setup() {
   /* Set pins Mode. */
   for (int i = cw_plus; i < ccw_minus + 1; i++) { // 3: CW+, 4: CW-, 5: CCW+, 6:CCW-
-      pinMode(i, OUTPUT);
-      digitalWrite(i, LOW); // Default pin status is LOW.
+    pinMode(i, OUTPUT);
+    digitalWrite(i, LOW); // Default pin status is LOW.
   }
   /* Node handle setting. */
   nh.initNode(); // First setup the node handle.
@@ -84,7 +85,7 @@
   if (msg.angular.z < 0 && time > 50) gen_pluse(LEFT, time); // Minus mean CCW or right.
   else if (msg.angular.z > 0 && time > 50) gen_pluse(RIGHT, time); // Plus mean CW or left.
   else gen_pluse(KEEP, 0); // Zero mean keep steer.
-   /* move task */
+  /* move task */
 }

 /**
@@ -96,17 +97,16 @@
 void gen_pluse(const char direction, double time) {
   switch (direction) {
   case LEFT: // Task steer left.
-      noTone(cw_plus); // Unset tone. If don't running tone, not happen.
-      tone(ccw_plus, PULSE_FREQUENCY, time); // Write pulse to CCW pin. turn to CW.
-      break;
+    noTone(cw_plus); // Unset tone. If don't running tone, not happen.
+    tone(ccw_plus, PULSE_FREQUENCY, time); // Write pulse to CCW pin. turn to CW.
+    break;
   case RIGHT: // Task steer right.
-      noTone(ccw_plus); // Unset tone. If don't running tone, not happen.
-      tone(cw_plus, PULSE_FREQUENCY, time); // Write pulse to CW pin. turn to CCW.
-      break;
+    noTone(ccw_plus); // Unset tone. If don't running tone, not happen.
+    tone(cw_plus, PULSE_FREQUENCY, time); // Write pulse to CW pin. turn to CCW.
+    break;
   case KEEP: default: // set CW and CCW to low.
-      noTone(cw_plus); // Unset tone. If don't running tone, not happen.
-      noTone(ccw_plus); // Unset tone. If don't running tone, not happen.
-      break;
+    noTone(cw_plus); // Unset tone. If don't running tone, not happen.
+    noTone(ccw_plus); // Unset tone. If don't running tone, not happen.
+    break;
   }
 }
-


Fix door logic

Fix door logic

--- Arduino/coopController/coopController.ino
+++ Arduino/coopController/coopController.ino
@@ -89,6 +89,7 @@
 unsigned long lastLEDBlink       = 0;
 unsigned long remoteLockStart    = 0;
 String        doorState          = "open"; // Values will be one of: closed, closing, open, opening
+String        doorStatePrev      = "";
 boolean       heaterState        = false;
 boolean       lampState          = false;
 boolean       fanState           = false;
@@ -108,7 +109,10 @@
 OneWire ds(tempSense);
 LiquidCrystal lcd(lcd_4, lcd_5, lcd_6, lcd_11, lcd_12, lcd_13, lcd_14);

-ESP esp(&espPort, &debugger, chpdPin);
+ESP esp(&espPort, chpdPin);
+// Replace previous line with following line to enable ESP debug output.
+// ESP esp(&espPort, &debugger, chpdPin);
+
 MQTT mqtt(&esp);
 boolean wifiConnected = false;

@@ -442,6 +446,8 @@
  */
  void doorMove() {
    debounceDoor();
+   doorStatePrev = doorState;
+
    if (doorState == "closed" || doorState == "closing") {
      if (doorBottomState != 0) {
        // Door isn't closed, run motor until it is.
@@ -454,6 +460,10 @@
        digitalWrite(doorClose, LOW);
        digitalWrite(doorOpen, LOW);
        digitalWrite(doorSpeed, LOW);
+       doorState = "closed";
+       if (doorStatePrev != doorState && wifiConnected) {
+         mqtt.publish("coop/status", "door|closed", 2, 0);
+       }
      }
    }
    else {
@@ -468,6 +478,10 @@
        digitalWrite(doorClose, LOW);
        digitalWrite(doorOpen, LOW);
        digitalWrite(doorSpeed, LOW);
+       doorState = "open";
+       if (doorStatePrev != doorState && wifiConnected) {
+         mqtt.publish("coop/status", "door|open", 2, 0);
+       }
      }
    }
  }
@@ -746,25 +760,26 @@
  */
 void loop() {
   esp.process();
-
+  // 5 second pause on initial startup to let devices settle, wifi connect, etc.
+  if (millis() > 5000) {
     // Only fetch new sensor data if it's been long enough since the last reading.
     if (lastReading == 0 ||
         ((unsigned long)(millis() - remoteLockStart) > remoteOverride &&
         (unsigned long)(millis() - lastReading) > readingInterval)) {
       // Read new data from sensors
       readSensors();
-
+
       // Respond ot sensor data
       handleSensorReadings();
     }
-
+
     // Move the door as needed
     doorMove();
-
+
     // Update door LEDs as needed
     doorLEDs();
-
+
     // Update the LCD display
     updateLCD();
-
-}
+  }
+}


Used Arduino 1.0.5's internal Serial library on the water sensors.

--- arduinoWorkspace/SubWaterSensorController/SubWaterSensorController.ino
+++ arduinoWorkspace/SubWaterSensorController/SubWaterSensorController.ino
@@ -1,7 +1,7 @@
 /**************************
 * Water Sensor Controller *
 * ************************/
-#include <Serial.h>
+//#include <Serial.h>

 #define BAUD 115200
 #define MIN_PACKET_LENGTH 2
@@ -11,6 +11,7 @@

 void setup()
 {
+
   Serial.begin(BAUD);
 }


more case tweaks

more case tweaks

--- examples/RF12/rf12cmd/rf12cmd.ino
+++ examples/RF12/rf12cmd/rf12cmd.ino
@@ -1,4 +1,4 @@
-/// @dir RF12cmd
+/// @dir rf12cmd
 /// Command-based central node for RF12 packets.
 // 2012-10-14 <jc@wippler.nl> http://opensource.org/licenses/mit-license.php

@@ -20,7 +20,7 @@
 static void pushGreeting () {
   encoder.startList();
   encoder.push("hi");
-  encoder.push("RF12cmd");
+  encoder.push("rf12cmd");
   encoder.push(RF12CMD_VERSION);
   encoder.push(sizeof embuf);
   encoder.endList();


Bugfix: Respect intensity for RGB strip. V1.2.1

--- arduino/HandshakeInterface/HandshakeInterface.ino
+++ arduino/HandshakeInterface/HandshakeInterface.ino
@@ -108,7 +108,7 @@
   global_debug = debug;
   global_state = STATE_HANDSHAKE; // Handshake is always on
   Serial.println();
-  Serial.println("HELLO handshake V1.2");
+  Serial.println("HELLO handshake V1.2.1");
   if (global_debug) Serial.println("DEBUG handshake");
   printCommands();
 }
@@ -120,7 +120,7 @@
   if (strip == 3) {
     // Handle RGB strips
     for (uint8_t i=0;i<3;i++) {
-      analogWrite(rgbStripPins[panel][i], 255-color[i]);
+      analogWrite(rgbStripPins[panel][i], 255-newcol[i]);
     }
     return;
   }


remove simple example

remove simple example

--- examples/Lesson3/new_infrared_Blink/new_infrared_Blink.ino
+++ examples/Lesson3/new_infrared_Blink/new_infrared_Blink.ino
@@ -1,32 +0,0 @@
-#include "Arduino.h"
-#define WOKE
-#include <EBot.h>
-
-#define L 16738455
-
-volatile int state = LOW;
-unsigned long RED;
-
-EBot eBot = EBot();
-
-void setup() {
-  pinMode(LED_BUILTIN, OUTPUT);
-  Serial.begin(9600);
-  eBot.begin();
-}
-
-void stateChange() {
-  state = !state;
-  digitalWrite(LED_BUILTIN, state);
-}
-
-void loop() {
-  RED = eBot.getIR();
-  if (RED != 0) {
-    Serial.println(RED);
-  }
-  if (RED == L) {
-    Serial.println("state changed!");
-    stateChange();
-  }
-}


Add logging to SerialPacketSocket

Add logging to SerialPacketSocket

--- examples/MqttSnOverSerialBridge/MqttSnOverSerialBridge.ino
+++ examples/MqttSnOverSerialBridge/MqttSnOverSerialBridge.ino
@@ -1,14 +1,14 @@
 /*
   Basic MQTT-SN over Serial Bridge example
-  (experimental)
+  (experimental)

    Setup:
    - Sends the MQTT-SN packages not over the nRF24L01+ Transceiver but over SoftwareSerial to a PC
    - On the PC run the Serial Port Bridge from https://github.com/njh/mqtt-sn-tools to forward them via TCP to a MQTT-SN Broker
-
+
    Function:
    - reads a string from Serial and publishes the PUBLISH_TOPIC ("Bt/Ex/PubSub/Out") topic
-   - subscribes to the SUBSCRIBE_TOPIC ("Bt/Ex/PubSub/In") topic and writes the reiceived data to the Serial
+   - subscribes to the SUBSCRIBE_TOPIC ("Bt/Ex/PubSub/In") topic and writes the reiceived data to the Serial
 */

 #include <SPI.h>
@@ -28,51 +28,71 @@

 class SerialPacketSocket : public Bt::I_RfPacketSocket {

-   public:
-      SerialPacketSocket(Stream& iStream): mStream(&iStream) {
+  public:
+    SerialPacketSocket(Stream& iStream): mStream(&iStream) {
+    }
+
+    virtual bool send(uint8_t* iPayload, size_t iSize, uint8_t iNodeId ) {
+#if BT_LOGGING >= BT_LOG_LEVEL_DEBUG
+      Serial.print(BT_LOG_STR("send to Serial Bridge > "));
+      for (size_t i = 0 ; i < iSize ; i++) {
+        int c = iPayload[i];
+        char buffer[20];
+        sprintf(buffer, "0x%x", c);
+        Serial.print(buffer);
+        Serial.print(" ");
+      }
+      Serial.println();
+#endif
+      return mStream->write(iPayload, iSize) == iSize;
+    }
+
+    virtual int32_t receive(uint8_t* oPayload, size_t iMaxSize, uint8_t* oNodeId) {
+      if (mStream->available() < 1) {
+        return 0;
+      }
+      uint8_t length = mStream->read();
+      if (length == 0x01) {
+        BT_LOG_DEBUG("Messages with length over 255 not supported");
+        // todo cleanup/flush stream
+        return 0;
+      }
+      if (length > iMaxSize) {
+        BT_LOG_DEBUG("oPayload buffer too small");
+        // todo cleanup/flush stream
+        return 0;
       }

-      virtual bool send(uint8_t* iPayload, size_t iSize, uint8_t iNodeId ) {
-         return mStream->write(iPayload,iSize) == iSize;
+      *oNodeId = GATEWAY_NODE_ID;
+      oPayload[0] = length;
+      mStream->readBytes(oPayload + 1, length - 1);
+
+#if BT_LOGGING >= BT_LOG_LEVEL_DEBUG
+      Serial.print(BT_LOG_STR("recv from Serial Bridge < "));
+      for (size_t i = 0 ; i < length ; i++) {
+        int c = oPayload[i];
+        char buffer[20];
+        sprintf(buffer, "0x%x", c);
+        Serial.print(buffer);
+        Serial.print(" ");
       }
+      Serial.println();
+#endif
+      return length;
+    }

-      virtual int32_t receive(uint8_t* oPayload, size_t iMaxSize, uint8_t* oNodeId) {
-         BT_LOG_DEBUG_AND_PARAMETER("SerialPacketSocket::receive available = ",mStream->available());
-         if(mStream->available() < 1) {
-            return 0;
-         }
-         uint8_t length = mStream->read();
-         if(length == 0x01) {
-            BT_LOG_DEBUG("Messages with length over 255 not supported");
-            // todo cleanup/flush stream
-            return 0;
-         }
-         if(length > iMaxSize) {
-            BT_LOG_DEBUG("oPayload buffer too small");
-            // todo cleanup/flush stream
-            return 0;
-         }
+    virtual bool available() {
+      return mStream->available() > 0;
+    }

-         *oNodeId = GATEWAY_NODE_ID;
-         oPayload[0] = length;
-         mStream->readBytes(oPayload+1, length-1);
-
-         BT_LOG_DEBUG_AND_PARAMETER("SerialPacketSocket::receive return length = ", length);
-         return length;
-      }
+    virtual void suspend() {
+    }

-      virtual bool available() {
-         return mStream->available() > 0;
-      }
+    virtual void resume() {
+    }

-      virtual void suspend() {
-      }
-
-      virtual void resume() {
-      }
-
-   private:
-      Stream* mStream;
+  private:
+    Stream* mStream;
 };

 //-----
@@ -84,48 +104,48 @@
 Bt::MqttSnClient client(serialPacketSocket, GATEWAY_NODE_ID, CLIENT_ID, &subscribeCallback);

 void setup() {
-   while (!Serial);
-   Serial.begin(9600);
-   Serial1.begin(9600);
-   Serial << endl << endl << endl << "*** MQTT-SN PubSub example ***" << endl;
-   Serial << endl;
-   Serial << " - Node      = " << CLIENT_NODE_ID << endl;
-   Serial << " - Pup-Topic = " << PUBLISH_TOPIC << endl;
-   Serial << " - Sub-Topic = " << SUBSCRIBE_TOPIC << endl;
-   Serial << "try connect ..." << endl;
+  while (!Serial);
+  Serial.begin(9600);
+  Serial1.begin(9600);
+  Serial << endl << endl << endl << "*** MQTT-SN PubSub example ***" << endl;
+  Serial << endl;
+  Serial << " - Node      = " << CLIENT_NODE_ID << endl;
+  Serial << " - Pup-Topic = " << PUBLISH_TOPIC << endl;
+  Serial << " - Sub-Topic = " << SUBSCRIBE_TOPIC << endl;
+  Serial << "try connect ..." << endl;

-   while (!client.connect(30)) {
-      Serial << "... connect failed ..." << endl;
-      delay(1000);
-      Serial << "... retry connect ..." << endl;
-   }
-
-   Serial << "... connected" << endl;
+  while (!client.connect(30)) {
+    Serial << "... connect failed ..." << endl;
+    delay(1000);
+    Serial << "... retry connect ..." << endl;
+  }

-   Serial << "subscribe" << endl;
+  Serial << "... connected" << endl;

-   client.subscribe(SUBSCRIBE_TOPIC);
+  Serial << "subscribe" << endl;

-   Serial << "out> <Start>" << endl;
+  client.subscribe(SUBSCRIBE_TOPIC);

-   client.publish(PUBLISH_TOPIC,"<Start>");
-
+  Serial << "out> <Start>" << endl;
+
+  client.publish(PUBLISH_TOPIC, "<Start>");
+
 }

 void loop() {
-   client.loop();
-   if (Serial.available()) {
-      String out = readString();
-      Serial << "out> " << out << endl;
-      client.publish(PUBLISH_TOPIC,out.c_str());
-      if (out == String("<quit>")) {
-         quit();
-      }
-   }
+  client.loop();
+  if (Serial.available()) {
+    String out = readString();
+    Serial << "out> " << out << endl;
+    client.publish(PUBLISH_TOPIC, out.c_str());
+    if (out == String("<quit>")) {
+      quit();
+    }
+  }
 }

 void subscribeCallback(const char* iTopic, const char*  iData) {
-  Serial << "in> " << iData << endl;
+  Serial << "in> " << iData << endl;
 }

 String readString() {
@@ -136,8 +156,9 @@
 }

 void quit() {
-   Serial << "<quit>" << endl;
-   client.disconnect();
-   Serial << "Hit reboot" << endl;
-   while(true){}
+  Serial << "<quit>" << endl;
+  client.disconnect();
+  Serial << "Hit reboot" << endl;
+  while (true) {}
 }
+


[Arduino] Refactoring.

[Arduino] Refactoring.

Signed-off-by: Juri Berlanda <5bfdca9e82c53adb0603ce7083f4ba4f2da5cacf@hotmail.com>

--- Arduino/vj-flight-controller/vj-flight-controller.ino
+++ Arduino/vj-flight-controller/vj-flight-controller.ino
@@ -102,6 +102,40 @@
 // ================================================================
 // ===                      Helper                              ===
 // ================================================================
+void checkFifo() {
+  // get current FIFO count
+  fifoCount = mpu.getFIFOCount();
+
+  // check for overflow (this should never happen unless our code is too inefficient)
+  if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
+    Serial.println(F("FIFO overflow!"));
+    // reset so we can continue cleanly
+    mpu.resetFIFO();
+    // otherwise, check for DMP data ready interrupt (this should happen frequently)
+  } else if (mpuIntStatus & 0x02 && fifoCount < packetSize)
+    // wait for correct available data length, should be a VERY short wait
+    while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
+}
+
+void readData() {
+  if (mpuIntStatus & 0x02) {
+    // read a packet from FIFO
+    mpu.getFIFOBytes(fifoBuffer, packetSize);
+
+    // track FIFO count here in case there is > 1 packet available
+    // (this lets us immediately read more without waiting for an interrupt)
+    //fifoCount -= packetSize;
+
+    // Get Euler angles in degrees and Acceleration in world-frame
+    mpu.dmpGetQuaternion(&q, fifoBuffer);
+    mpu.dmpGetAccel(&aa, fifoBuffer);
+    mpu.dmpGetGravity(&gravity, &q);
+    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
+    mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
+    mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
+    mpu.resetFIFO();
+  }
+}

 void sendData() {
   char command;
@@ -208,35 +242,9 @@

   mpuIntStatus = mpu.getIntStatus();

-  // get current FIFO count
-  fifoCount = mpu.getFIFOCount();
-
-  // check for overflow (this should never happen unless our code is too inefficient)
-  if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
-    Serial.println(F("FIFO overflow!"));
-    // reset so we can continue cleanly
-    mpu.resetFIFO();
-    // otherwise, check for DMP data ready interrupt (this should happen frequently)
-  } else if (mpuIntStatus & 0x02) {
-    // wait for correct available data length, should be a VERY short wait
-    while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
-
-    // read a packet from FIFO
-    mpu.getFIFOBytes(fifoBuffer, packetSize);
-
-    // track FIFO count here in case there is > 1 packet available
-    // (this lets us immediately read more without waiting for an interrupt)
-    fifoCount -= packetSize;
-
-    // Get Euler angles in degrees and Acceleration in world-frame
-    mpu.dmpGetQuaternion(&q, fifoBuffer);
-    mpu.dmpGetAccel(&aa, fifoBuffer);
-    mpu.dmpGetGravity(&gravity, &q);
-    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
-    mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
-    mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
-    mpu.resetFIFO();
-  }
+  checkFifo();
+
+  readData();

   // blink LED to indicate activity
   blinkState = !blinkState;


Update IP address.

Update IP address.

--- examples/Ethernet/CosaWebClient/CosaWebClient.ino
+++ examples/Ethernet/CosaWebClient/CosaWebClient.ino
@@ -34,7 +34,8 @@
 #define FILESERVER 192,168,0,2
 #define WIFIBRIDGE 192,168,0,30
 #define UNDEFINED 74,125,232,128
-#define WWW_GOOGLE_COM 74,125,232,128
+#define WWW_GOOGLE_COM 173,194,71,99
+#define DEST WWW_GOOGLE_COM
 #define DEST WWW_GOOGLE_COM
 #define PORT 80


update button test

update button test

--- proj/ledvo_lounge_button_test/ledvo_lounge_button_test.ino
+++ proj/ledvo_lounge_button_test/ledvo_lounge_button_test.ino
@@ -17,11 +17,11 @@
 #define DJ_POT 3

 // Digital Pins for LED output
-#define LED_IH 22
-#define LED_OH 23
-#define LED_D0 24
-#define LED_D1 25
-#define LED_D2 26
+#define LED_IH 8
+#define LED_OH 9
+#define LED_D0 10
+#define LED_D1 11
+#define LED_D2 12
 //#define LED_D3 15
 //#define LED_D4 29
 //#define LED_D5 11


ArduinoISP: Disabled usage of LEDs, to allow having modules connected to non-programming headers when programming.

--- arduino/libraries/BuildingBlocks/examples/ArduinoISP/ArduinoISP.ino
+++ arduino/libraries/BuildingBlocks/examples/ArduinoISP/ArduinoISP.ino
@@ -1,4 +1,4 @@
-// This is the same standard ArduinoISP example, with only the RESET pin set to match the one used in the Mainboard module (4).
+// This is the same standard ArduinoISP example, with only the RESET pin set to match the one used in the Mainboard module (4) and SS pins set to 1, and LEDs disabled.

 // ArduinoISP
 // Copyright (c) 2008-2011 Randall Bohn
@@ -73,9 +73,9 @@
 #ifndef ARDUINO_HOODLOADER2

 #define RESET     4 // Use BuildingBlocks MainBoard specific pin for reseting the target.
-#define LED_HB    9
-#define LED_ERR   8
-#define LED_PMODE 7
+//#define LED_HB    9
+//#define LED_ERR   8
+//#define LED_PMODE 7

 // Uncomment following line to use the old Uno style wiring
 // (using pin 11, 12 and 13 instead of the SPI header) on Leonardo, Due...
@@ -222,13 +222,19 @@
 void setup() {
   SERIAL.begin(BAUDRATE);

-  pinMode(LED_PMODE, OUTPUT);
-  pulse(LED_PMODE, 2);
-  pinMode(LED_ERR, OUTPUT);
-  pulse(LED_ERR, 2);
-  pinMode(LED_HB, OUTPUT);
-  pulse(LED_HB, 2);
-
+  //pinMode(LED_PMODE, OUTPUT);
+  //pulse(LED_PMODE, 2);
+  //pinMode(LED_ERR, OUTPUT);
+  //pulse(LED_ERR, 2);
+  //pinMode(LED_HB, OUTPUT);
+  //pulse(LED_HB, 2);
+
+  pinMode(5, OUTPUT); digitalWrite(5, HIGH);
+  pinMode(6, OUTPUT); digitalWrite(6, HIGH);
+  pinMode(7, OUTPUT); digitalWrite(7, HIGH);
+  pinMode(8, OUTPUT); digitalWrite(8, HIGH);
+  pinMode(9, OUTPUT); digitalWrite(9, HIGH);
+  pinMode(10,OUTPUT); digitalWrite(10,HIGH);
 }

 int error = 0;
@@ -269,7 +275,7 @@
   if (hbval > 192) hbdelta = -hbdelta;
   if (hbval < 32) hbdelta = -hbdelta;
   hbval += hbdelta;
-  analogWrite(LED_HB, hbval);
+  //analogWrite(LED_HB, hbval);
 }

 static bool rst_active_high;
@@ -280,17 +286,17 @@

 void loop(void) {
   // is pmode active?
-  if (pmode) {
-    digitalWrite(LED_PMODE, HIGH);
-  } else {
-    digitalWrite(LED_PMODE, LOW);
-  }
+  //if (pmode) {
+  //  digitalWrite(LED_PMODE, HIGH);
+  //} else {
+  //  digitalWrite(LED_PMODE, LOW);
+  //}
   // is there an error?
-  if (error) {
-    digitalWrite(LED_ERR, HIGH);
-  } else {
-    digitalWrite(LED_ERR, LOW);
-  }
+  //if (error) {
+  //  digitalWrite(LED_ERR, HIGH);
+  //} else {
+  //  digitalWrite(LED_ERR, LOW);
+  //}

   // light the heartbeat LED
   heartbeat();
@@ -320,9 +326,9 @@
 }

 void prog_lamp(int state) {
-  if (PROG_FLICKER) {
-    digitalWrite(LED_PMODE, state);
-  }
+  //if (PROG_FLICKER) {
+  //  digitalWrite(LED_PMODE, state);
+  //}
 }

 uint8_t spi_transaction(uint8_t a, uint8_t b, uint8_t c, uint8_t d) {
@@ -457,14 +463,14 @@
                   data);
 }
 void commit(unsigned int addr) {
-  if (PROG_FLICKER) {
-    prog_lamp(LOW);
-  }
+  //if (PROG_FLICKER) {
+  //  prog_lamp(LOW);
+  //}
   spi_transaction(0x4C, (addr >> 8) & 0xFF, addr & 0xFF, 0);
-  if (PROG_FLICKER) {
-    delay(PTIME);
-    prog_lamp(HIGH);
-  }
+  //if (PROG_FLICKER) {
+  //  delay(PTIME);
+  //  prog_lamp(HIGH);
+  //}
 }

 unsigned int current_page() {


wip Changed Plant Monitor polling interval to 10 seconds

--- examples/MeeoCrowtailBasic/SimplePlantMonitor/SimplePlantMonitor.ino
+++ examples/MeeoCrowtailBasic/SimplePlantMonitor/SimplePlantMonitor.ino
@@ -74,7 +74,7 @@
   Meeo.run();

   unsigned long now = millis();
-  if (now - previous > 3000) {
+  if (now - previous > 10000) {
     previous = now;

     sensors_event_t event;


now totally works

now totally works

--- led_sequence_combined_momentary/led_sequence_combined_momentary.ino
+++ led_sequence_combined_momentary/led_sequence_combined_momentary.ino
@@ -1,8 +1,6 @@
 // *******libraries
 #include <Adafruit_NeoPixel.h>
-#include <Wire.h>
-#include <Adafruit_MotorShield.h>
-#include "utility/Adafruit_MS_PWMServoDriver.h"
+#include <Stepper.h>

 // *******these constants won't change:
 const int  buttonPin = 2;    // the pin that the pushbutton is attached to
@@ -14,7 +12,7 @@
 const int upPin = 4;
 const int pingPin = 3;
 const int downPin = 5;
-// how long the on operiod should be
+// how long the on period should be
 const int onTime = 300;

@@ -28,16 +26,16 @@
 //LED variables
 int redVal = 255;            // used to fade out LED. Starts at 255 to match startup val
 int greenVal = 0;             //used to fade in LED
+//stepper variables
+//number of steps you want the motor to take
+#define STEPS 600

 //********other initialization things
 // intitialize neopixel object
 Adafruit_NeoPixel strip = Adafruit_NeoPixel(pixelQuant, neoPin, NEO_RGB + NEO_KHZ800);
-// Create the motor shield object with the default I2C address
-Adafruit_MotorShield AFMS = Adafruit_MotorShield();
-// Connect a stepper motor with 200 steps per revolution (1.8 degree)
-// to motor port #2 (M3 and M4)
-Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2);
+// create an instance of the stepper, specifiying number of steps and pins
+Stepper stepper(STEPS, 7, 8, 9, 10);

@@ -54,8 +52,8 @@
   strip.show(); // Initialize all pixels to 'off'

   //initialize the stepper
-  AFMS.begin();  // create with the default frequency 1.6KHz
-  myMotor->setSpeed(100);  // 100 rpm - to get faster need to change code
+  // speed in RPM - keep it below 25
+  stepper.setSpeed(10);

   //initilizes the audio pin
   pinMode(upPin,OUTPUT);
@@ -153,11 +151,13 @@
   digitalWrite(upPin, HIGH);

   //*******Stepper section
-  myMotor->step(1000, FORWARD, SINGLE);
+  //goes up STEPS steps
+  stepper.step(STEPS);

   //*******cleanup section
   counter = 1;
   stateTracker = 1;
+  pingTracker = 0;
   Serial.println("Startup complete");

 }
@@ -168,6 +168,7 @@

   //***** Tone Section
   //trigger the ping
+  //^^^^^^^^NOTE: ping won't trigger if the startup song ends after the stepper stops in startup()^^^^^
   if (pingTracker == 0) {
     digitalWrite(pingPin, LOW);
     delay(200);
@@ -202,14 +203,6 @@
   Serial.println("shutdown");

-  //*****LED section
-  // turns off neopixels
-  strip.setPixelColor(0, 0, 0, 0); //pixel number, r,g,b
-  strip.show();
-
-  //*****stepper section
-  myMotor->step(1000, BACKWARD, SINGLE);
-
   //***** Tone Section
   //trigger the down music
   digitalWrite(downPin, LOW);
@@ -217,6 +210,18 @@
   digitalWrite(downPin, HIGH);
   //this is for the on ping reset
   pingTracker = 0;
+
+  //*****LED section
+  // turns off neopixels
+  strip.setPixelColor(0, 0, 0, 0); //pixel number, r,g,b
+  strip.show();
+
+
+  //*****stepper section
+  // goes down STEPS steps (down because it is negative)
+  stepper.step(-STEPS);
+
+

   //*****cleanup section
   counter = 0;


Found another badly formatted example

Found another badly formatted example

--- pic32/libraries/SoftSPI/examples/PmodJstkSoftSPI/PmodJstkSoftSPI.ino
+++ pic32/libraries/SoftSPI/examples/PmodJstkSoftSPI/PmodJstkSoftSPI.ino
@@ -129,12 +129,9 @@
 **    Initialize the system.
 */

-void
-setup() {
-
+void setup() {
     DeviceInit();
     AppInit();
-
 }

 /* ------------------------------------------------------------ */
@@ -153,11 +150,8 @@
 **    Main application loop.
 */

-void
-loop() {
-
-  AppTask();
-
+void loop() {
+    AppTask();
 }

 /* ------------------------------------------------------------ */
@@ -176,35 +170,28 @@
 **    Perform basic board/device level initialization.
 */

-void
-DeviceInit()
-{
-
-  /* Set the LED pins to be outputs. Some boards support more
-  ** than two LEDs. On those boards, also blink the additional
-  ** LEDs.
-  */
-  pinMode(PIN_LED1, OUTPUT);
-  pinMode(PIN_LED2, OUTPUT);
-
-  #if defined(PIN_LED3)
-  pinMode(PIN_LED3, OUTPUT);
-  #endif
-
-  #if defined(PIN_LED4)
-  pinMode(PIN_LED4, OUTPUT);
-  #endif
-
-  /* Initialize the SPI port.
-  ** Note: The pmodJSTK requires a delay of at least 6uS between
-  ** bytes, so the delay is set to 6uS below.
-  */
-  spi.begin(pinSS, pinMOSI, pinMISO, pinSCK);
-  spi.setSpeed(250000);
-  spi.setMode(SSPI_MODE0);
-  spi.setDirection(SSPI_SHIFT_LEFT);
-  spi.setDelay(6);
-
+void DeviceInit() {
+    /* Set the LED pins to be outputs. Some boards support more
+    ** than two LEDs. On those boards, also blink the additional
+    ** LEDs.
+    */
+    pinMode(PIN_LED1, OUTPUT);
+    pinMode(PIN_LED2, OUTPUT);
+#if defined(PIN_LED3)
+    pinMode(PIN_LED3, OUTPUT);
+#endif
+#if defined(PIN_LED4)
+    pinMode(PIN_LED4, OUTPUT);
+#endif
+    /* Initialize the SPI port.
+    ** Note: The pmodJSTK requires a delay of at least 6uS between
+    ** bytes, so the delay is set to 6uS below.
+    */
+    spi.begin(pinSS, pinMOSI, pinMISO, pinSCK);
+    spi.setSpeed(250000);
+    spi.setMode(SSPI_MODE0);
+    spi.setDirection(SSPI_SHIFT_LEFT);
+    spi.setDelay(6);
 }

 /* ------------------------------------------------------------ */
@@ -224,23 +211,18 @@
 **    init functions to initalize the application subsystems.
 */

-void
-AppInit()
-  {
-
-  /* Init program state variables.
-  */
-  cntBtnBlink = cntBlinkInit;
-  fbLedPmod = 0x01;
-  fbBtnPmod = 0;
-  xcoPmod = 0;
-  ycoPmod = 0;
-
-  /* Start with LED3 on and LED4 off
-  */
-  fLed3 = HIGH;
-  fLed4 = LOW;
-
+void AppInit() {
+    /* Init program state variables.
+    */
+    cntBtnBlink = cntBlinkInit;
+    fbLedPmod = 0x01;
+    fbBtnPmod = 0;
+    xcoPmod = 0;
+    ycoPmod = 0;
+    /* Start with LED3 on and LED4 off
+    */
+    fLed3 = HIGH;
+    fLed4 = LOW;
 }

 /* ------------------------------------------------------------ */
@@ -260,58 +242,51 @@
 **    each time through the main program loop.
 */

-void
-AppTask()
-  {
-  unsigned int	dwBtn;
-
-  /* Check the state of button 1 on the PmodJSTK and set LED 1
-  ** accordingly
-  */
-  dwBtn = fbBtnPmod & 0x01;
-  if (dwBtn == 0) {
-    digitalWrite(PIN_LED1, LOW);
-  }
-  else {
-    digitalWrite(PIN_LED1, HIGH);
-  }
-
-  /* Check the state of button 2 and set LED 2 accordingly
-  */
-  dwBtn = fbBtnPmod & 0x02;
-  if (dwBtn == 0) {
-    digitalWrite(PIN_LED2, LOW);
-  }
-  else {
-    digitalWrite(PIN_LED2, HIGH);
-  }
-
-  /* Check if it is time to blink LED3 & LED4 and update
-  ** the joystick.
-  */
-  cntBtnBlink -= 1;
-  if (cntBtnBlink == 0) {
-
-  #if defined(PIN_LED3)
-    digitalWrite(PIN_LED3, fLed3);
-    fLed3 = (fLed3 == HIGH) ? LOW : HIGH;
-  #endif
-
-  #if defined(PIN_LED4)
-    digitalWrite(PIN_LED4, fLed4);
-    fLed4 = (fLed4 == HIGH) ? LOW : HIGH;
-  #endif
-
-    /* Toggle the setting for the LEDs on the joystick.
-    */
-    fbLedPmod ^= 0x03;
-
-    /* Update the joystick.
-    */
-    ReadJoystick(fbLedPmod, &fbBtnPmod, &xcoPmod, &ycoPmod);
-
-    cntBtnBlink = cntBlinkInit;
-  }
+void AppTask() {
+    unsigned int	dwBtn;
+    /* Check the state of button 1 on the PmodJSTK and set LED 1
+    ** accordingly
+    */
+    dwBtn = fbBtnPmod & 0x01;
+
+    if (dwBtn == 0) {
+        digitalWrite(PIN_LED1, LOW);
+    } else {
+        digitalWrite(PIN_LED1, HIGH);
+    }
+
+    /* Check the state of button 2 and set LED 2 accordingly
+    */
+    dwBtn = fbBtnPmod & 0x02;
+
+    if (dwBtn == 0) {
+        digitalWrite(PIN_LED2, LOW);
+    } else {
+        digitalWrite(PIN_LED2, HIGH);
+    }
+
+    /* Check if it is time to blink LED3 & LED4 and update
+    ** the joystick.
+    */
+    cntBtnBlink -= 1;
+
+    if (cntBtnBlink == 0) {
+#if defined(PIN_LED3)
+        digitalWrite(PIN_LED3, fLed3);
+        fLed3 = (fLed3 == HIGH) ? LOW : HIGH;
+#endif
+#if defined(PIN_LED4)
+        digitalWrite(PIN_LED4, fLed4);
+        fLed4 = (fLed4 == HIGH) ? LOW : HIGH;
+#endif
+        /* Toggle the setting for the LEDs on the joystick.
+        */
+        fbLedPmod ^= 0x03;
+        /* Update the joystick.
+        */
+        ReadJoystick(fbLedPmod, &fbBtnPmod, &xcoPmod, &ycoPmod);
+        cntBtnBlink = cntBlinkInit;
+    }
 }

 /* ------------------------------------------------------------ */
@@ -332,42 +307,35 @@
 **  Description:
 **    Read the current position of the joystick and buttons.
 */
-void
-ReadJoystick(uint8_t fbLed, uint8_t * pfbBtn, int * pxco, int * pyco)
-  {
-  uint8_t    rgbSnd[5];
-  uint8_t    rgbRcv[5];
-  int	     ib;
-
-  /* Initialize the transmit buffer.
-  */
-  for (ib = 0; ib < 5; ib++) {
-    rgbSnd[ib] = 0x50 + ib;
-  }
-  rgbSnd[0] = fbLedPmod + 0x80;  //first byte sent sets the LEDs
-
-  /* Bring SS low to begin the transaction.
-  */
-  spi.setSelect(LOW);
-
-  /* Wait 10us for Pmod to become ready
-  */
-  Delay10us();
-
-  /* Send the data to the Pmod and get the response.
-  */
-  spi.transfer(5, rgbSnd, rgbRcv);
-
-  /* Bring SS high to end the transaction.
-  */
-  spi.setSelect(HIGH);
-
-  /* Set up the return values.
-  */
-  *pfbBtn = rgbRcv[4] >> 1;
-  *pxco = (uint16_t)((rgbRcv[1] << 8) + rgbRcv[0]);
-  *pyco = (uint16_t)((rgbRcv[3] << 8) + rgbRcv[2]);
-
+void ReadJoystick(uint8_t fbLed, uint8_t * pfbBtn, int * pxco, int * pyco) {
+    uint8_t    rgbSnd[5];
+    uint8_t    rgbRcv[5];
+    int	     ib;
+
+    /* Initialize the transmit buffer.
+    */
+    for (ib = 0; ib < 5; ib++) {
+        rgbSnd[ib] = 0x50 + ib;
+    }
+
+    rgbSnd[0] = fbLedPmod + 0x80;  //first byte sent sets the LEDs
+    /* Bring SS low to begin the transaction.
+    */
+    spi.setSelect(LOW);
+    /* Wait 10us for Pmod to become ready
+    */
+    Delay10us();
+    /* Send the data to the Pmod and get the response.
+    */
+    spi.transfer(5, rgbSnd, rgbRcv);
+    /* Bring SS high to end the transaction.
+    */
+    spi.setSelect(HIGH);
+    /* Set up the return values.
+    */
+    *pfbBtn = rgbRcv[4] >> 1;
+    *pxco = (uint16_t)((rgbRcv[1] << 8) + rgbRcv[0]);
+    *pyco = (uint16_t)((rgbRcv[3] << 8) + rgbRcv[2]);
 }

 /* ------------------------------------------------------------ */
@@ -386,18 +354,15 @@
 **    Delay loop for ~10uS
 */

-void
-Delay10us()
-  {
-  volatile int		cnt;
-
-  for (cnt = 0; cnt < 100; cnt++) {
-  }
-
-}
-
-/* ------------------------------------------------------------ */
-
-/************************************************************************/
-
-
+void Delay10us() {
+    volatile int		cnt;
+
+    for (cnt = 0; cnt < 100; cnt++) {
+    }
+}
+
+/* ------------------------------------------------------------ */
+
+/************************************************************************/
+
+


added support for low-power sleep mode

added support for low-power sleep mode

--- MyTransmitter_softSPI_dht/MyTransmitter_softSPI_dht.ino
+++ MyTransmitter_softSPI_dht/MyTransmitter_softSPI_dht.ino
@@ -1,5 +1,6 @@
 #define DHT_DEBUG

+#include "LowPower.h"
 #include <nRF24L01p.h>
 #include <DHT.h>
 #include <ws_common.h>
@@ -8,6 +9,7 @@
 #define DHT_PIN 3                       // data pin for DHT sensor
 #define DHT_TYPE DHT22                  // DHT 22  (AM2302)
 #define SENSOR_POWER_HEATUP_DELAY 2000  // wait for power stabilization (millis)
+#define DEVICE_WATCHDOG_SLEEP_SECONDS 8 // use multiples of 8

 const byte sensor_id = 2;

@@ -20,42 +22,52 @@
   delay(150);

   #ifdef DHT_DEBUG
-    Serial.begin(9600);
+    Serial.begin(115200);
   #endif

   DEBUG_PRINT("Hello, I'm sensor: ");
   DEBUG_PRINTLN(sensor_id);

+  DEBUG_PRINT("Power-safe sleep mode in seconds: ");
+  DEBUG_PRINTLN(DEVICE_WATCHDOG_SLEEP_SECONDS);
+
   DEBUG_PRINT("Powering sensors from pin ");
   DEBUG_PRINTLN(SENSOR_POWER_PIN);
   pinMode(SENSOR_POWER_PIN, OUTPUT);
-
+  powerUpSensors();
+
+  // DHT22 module
   dht.begin();

+  // RF module
   DEBUG_PRINT("Setting up RF module ... ");
   transmitter.channel(WS_CHANNEL);
   transmitter.TXaddress(WS_TXADDR);
   transmitter.RXaddress(WS_RXADDR);
   transmitter.init();
   DEBUG_PRINTLN("done");
+
+  DEBUG_PRINTLN("Now entering normal operation...");
+}
+
+void powerUpSensors() {
+  DEBUG_PRINTLN("power-up sensors");
+  Serial.flush();
+  digitalWrite(SENSOR_POWER_PIN, HIGH);
+  delay(SENSOR_POWER_HEATUP_DELAY);
+}
+
+void powerDownSensors() {
+  DEBUG_PRINTLN("power-down sensors");
+  digitalWrite(SENSOR_POWER_PIN, LOW);
 }

 void loop() {
-
-  // turn off power from sensors to save battery
-  digitalWrite(SENSOR_POWER_PIN, LOW);
-
-  // Wait a few seconds between measurements.
-  delay(2000);
-  digitalWrite(SENSOR_POWER_PIN, HIGH);
-  delay(SENSOR_POWER_HEATUP_DELAY);

   // Reading temperature or humidity takes about 250 milliseconds!
   // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
   const float h = dht.readHumidity();
   const float t = dht.readTemperature();
-
-  digitalWrite(SENSOR_POWER_PIN, LOW);

   ws_sensor_msg_t tosend = {
     sensor_id,
@@ -71,9 +83,7 @@
   DEBUG_PRINT("DHT-Hum: ");
   DEBUG_PRINT(tosend.h);
   DEBUG_PRINT(" % ");
-//  DEBUG_PRINT("csum: ");
-//  DEBUG_PRINT(tosend.csum);
-//  DEBUG_PRINT(" ");
+  Serial.flush();

   // Now sending a message through RF module
   transmitter.txPL( tosend.sid );
@@ -85,15 +95,29 @@
   int i;
   for (i = 10; i>0 && !transmitter.send(SLOW); --i) {
     DEBUG_PRINT(".");
+    Serial.flush();
     delay(100);
   }
+  transmitter.flushTX(); // TODO

   if (i == 0) {
     DEBUG_PRINTLN("timeout");
   } else {
     DEBUG_PRINTLN("sent");
   }
+  Serial.flush();

-  delay(3000); // later, we will use watchdog to sleep
+  // turn off power from sensors to save battery
+  powerDownSensors();
+
+  // Wait a few seconds between measurements.
+  for(int i = DEVICE_WATCHDOG_SLEEP_SECONDS / 8; i>0; --i) {
+    DEBUG_PRINT("sleep 8s in cycle: ");
+    DEBUG_PRINTLN(i);
+    Serial.flush();
+    // Enter power down state for 8 s with ADC and BOD module disabled
+    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
+  }
+  powerUpSensors();
 }


Added comments regarding use of the example and use of flash memory segments

--- hardware/msp430/libraries/MspFlash/examples/flash_readwrite/flash_readwrite.ino
+++ hardware/msp430/libraries/MspFlash/examples/flash_readwrite/flash_readwrite.ino
@@ -55,14 +55,40 @@
   area. You need to find the pointer to the start of the next segment. There is a macro define to do this: SEGPTR(x)
   A example that makes 2 segments available for flashing by allocating 3 segments of constant data:

+
+  Using the example:
+  ~~~~~~~~~~~~~~~~~~
+
+  On the launchpad; put the two UART jumpers in HARDWARE SERIAL position (horizontal position) and use the terminal window to connect
+  to the board (9600baud).
+
+  'e' Erase the flash segment
+  'w' Write "Hello World" to the flash
+  'r' Read the contents of the flash, and print as byte values and characters. stop at the first NULL byte
+
+  - When you program the launchpad and read the flash, a single "0" character should be read (mem contains zero values)
+    Writing the flash before you have erased it is not possible (you cannot program OFF bits to ON bits)
+  - When you erase the flash, 0xFF values will be read back
+  - When you write the flash, "Hello World" will be read back
+
+
 */

 #include "MspFlash.h"

-const unsigned char data[2*SEGMENT_SIZE] = {0};

+// Two options to use for flash: One of the info flash segments, or a part of the program memory
+// either define a bit of constant program memory, and pass a pointer to the start of a segment to the flash functions,
+
+//*** Option 1: use program memory, uncomment these lines and you have 512 bytes of flash available (1024 bytes allocated) ****
+//const unsigned char data[2*SEGMENT_SIZE] = {0};
+//#define flash SEGPTR(data)
+//
+
+//*** Option 2: use one of the 64 byte info segments, uncomment this line. Use SEGMENT_B, SEGMENT_C or SEGMENT_D (each 64 bytes, 192 bytes in total)
 #define flash SEGMENT_D
-#define flash SEGPTR(data)
+//
+

 void setup()
 {
@@ -122,4 +148,4 @@
   Serial.println("flash test: e, r, w");
   Serial.println(F_CPU);
   Serial.println(div);
-}
+}


Fixes robot to allow it to enter idle mode.

--- Chapter_8/CompetitiveSumoRobot.ino
+++ Chapter_8/CompetitiveSumoRobot.ino
@@ -101,6 +101,7 @@
 			Serial.println("Good luck!");
 			begin_countdown();
 		} else {
+			state = 1;
 			Serial.println("Robot entering idle mode.");
 		}
 	}


adding watering the plants functionality in anticipation of last sensors to come in. Once water level sensors are wired, we can complete this task

--- plantstation.ino
+++ plantstation.ino
@@ -1,16 +1,23 @@
-//=====for Keen Integration====================
+//=====General Deployment Definitions==========
+String appId = "Plant01";
+String location = "Dinning Room Window";
+
+//=====For private keys, params================
+#include "params.h"
+
+//=====For Keen Integration====================
 #include "ApiClient.h"
 #include "KeenClient.h"
 KeenClient myKeen;

-//=====for writting to the console=============
+//=====For writting to the console=============
 #include "Bridge.h"
 #include "Console.h"

-//=====for 4 Relay Module======================
+//=====For 4 Relay Module======================
 #define LightSwitch 4

-//=====for Probe Thermometer===================
+//=====For Probe Thermometer===================
 #include "OneWire.h"
 const byte probePin = 3;
 OneWire myPT(probePin);
@@ -21,41 +28,43 @@
 } SoilMeasurement;
 SoilMeasurement sm;

-//=====for Digital Thermo, Humidity Sensor=====
+//=====For Digital Thermo, Humidity Sensor=====
 #include "DHT.h"
 const byte dhtPin = 2;
 DHT myDHT(dhtPin, DHT11);

 typedef struct my_airmeasurement {
   byte humidityAir;
+  float heatIndex;
   float tempAirC;
   float tempAirF;
-  float heatIndex;
 } AirMeasurement;
 AirMeasurement am;

-//=====for keys, params========================
-#include "params.h"
-
-//=====for photoresistor=======================
+//=====For photoresistor=======================
+const byte lightOnThreshold = 90;
 const byte lightPin = A0;
+boolean lightIsOn = false;
 int lightResistorVal;
-boolean lightIsOn = false;
-const byte lightOnThreshold = 90;

 //=====for hygrometer==========================
 const byte hygroPin = A1;
-int moistureSensor;
-
-//=====these i am still thinking about=========
-String appId = "Plant01";
-String location = "Dinning Room Window";
-String waterLevelStatus = "OK";
+// todo - find right value for this
+const int moistureThreshold = 500; // <- made this up
+int moistureSensorVal;
+
+//=====for Water Level=========================
+const byte waterSensorPin = A2;
+// todo - find right value for this
+const int waterLevelThreshold = 400; // <- made this up
 boolean waterPumpIsOn = false;
+int waterLevelVal;
+String waterLevel = "OK";

 //=====for timed events, etc===================
 long prevMinOneMillis = 0;
 long minOneInterval = 60000;
+
 long prevMinFiveMillis = 0;
 long minFiveInterval = 300000;

@@ -63,8 +72,8 @@
   pinMode(LightSwitch, OUTPUT);
   Serial.begin(9600);
   Serial.println("PlantStation is warming up\n");
+
   myDHT.begin();
-
   Bridge.begin();
   Console.begin();

@@ -80,9 +89,9 @@

   readAirMeasurements();
   readSoilMeasurements();
-  readMoistureSensor();
-
   readLightResistor();
+  readMoistureSensor();
+  readWaterLevelSensor();

   outputEvent();

@@ -102,20 +111,22 @@
 }

 void waterPlants() {
+  if (moistureThreshold < moistureSensorVal && !waterPumpIsOn && waterLevel == "OK") {
+    // todo - water for ten seconds at a time and no more than twice a day?!?
+    // digitalWrite(WaterPump, HIGH);
+    waterPumpIsOn = true;
+  }
 }

 void switchLights() {
-
   if (lightOnThreshold > lightResistorVal && !lightIsOn) {
     digitalWrite(LightSwitch, HIGH);
     lightIsOn = true;
   }
-
   if (lightOnThreshold < lightResistorVal && lightIsOn) {
     digitalWrite(LightSwitch, LOW);
     lightIsOn = false;
-  }
-
+  }
 }

 void readLightResistor() {
@@ -123,7 +134,17 @@
 }

 void readMoistureSensor() {
-  moistureSensor = analogRead(hygroPin);
+  moistureSensorVal = analogRead(hygroPin);
+}
+
+void readWaterLevelSensor() {
+  waterLevelVal = analogRead(waterSensorPin);
+
+  if (waterLevelVal < waterLevelThreshold) {
+    waterLevel = "LOW";
+  } else {
+   waterLevel = "OK";
+  }
 }

 void readAirMeasurements() {
@@ -201,9 +222,9 @@
   my_output += ",\"ProbeTemperatureFahrenheit\":";
   my_output += sm.tempSoilF;
   my_output += ",\"Moisture\":";
-  my_output += moistureSensor;
+  my_output += moistureSensorVal;
   my_output += ",\"WaterLevelStatus\":\"";
-  my_output += waterLevelStatus;
+  my_output += waterLevel;
   my_output += "\",\"Location\":\"";
   my_output += location;
   my_output += "\",\"LightIsOn\":";
@@ -225,8 +246,8 @@
     char c = myKeen.read();
     Console.print(c);
   }
+
   Console.println();
-
   Console.flush();
 }

@@ -245,18 +266,16 @@
   my_output += ";Light:";
   my_output += lightResistorVal;
   my_output += ";ProbeTemperatureCelcius:";
-  my_output += sm.tempSoilC;
-
+  my_output += sm.tempSoilC;
   my_output += ";ProbeTemperatureFahrenheit:";
   my_output += sm.tempSoilF;
   my_output += ";Moisture:";
-  my_output += moistureSensor;
+  my_output += moistureSensorVal;
   my_output += ";WaterLevelStatus:";
-  my_output += waterLevelStatus;
+  my_output += waterLevel;
   my_output += ";LightIsOn:";
   my_output += lightIsOn;
-  my_output += ";Location:";
-
+  my_output += ";Location:";
   my_output += location;
   my_output += ";WaterPumptIsOn:";
   my_output += waterPumpIsOn;


COH-78: WIP

COH-78: WIP

--- Arduino/COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
+++ Arduino/COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
@@ -3,7 +3,7 @@
 //#define CONFIG_REV9 // REV9 as CC1 relay, cut 2 of the board.

 // IF DEFINED: entire comms model switches to secure.
-//#define ENABLE_OTSECUREFRAME_ENCODING_SUPPORT
+#define ENABLE_OTSECUREFRAME_ENCODING_SUPPORT

 #define DEBUG // Uncomment for debug output.

@@ -868,6 +868,7 @@
 // Assigns radio to PrimaryRadio alias.
 OTRadioLink::OTRadioLink &PrimaryRadio = RFM23B;

+// Quickly filter RX traffic to preserve queue space for stuff likely to be of interest.
 #if defined(ALLOW_CC1_SUPPORT_RELAY)
 // For a CC1 relay, ignore everything except FTp2_CC1PollAndCmd messages.
 // With care (not accessing EEPROM for example) this could also reject anything with wrong house code.
@@ -875,11 +876,14 @@
   {
 #ifndef ENABLE_OTSECUREFRAME_ENCODING_SUPPORT
   if((buflen < 8) || (OTRadioLink::FTp2_CC1PollAndCmd != buf[0])) { return(false); }
-  // TODO: filter for only this unit address/housecode as FHT8V.getHC{1,2}() are thread-safe.
+  // Filter for only this unit address/housecode as FHT8V.getHC{1,2}() are thread-safe.
+  if((FHT8V.getHC1() == buf[1]) || (FHT8V.getHC2() == buf[2])) { return(false); }
 #else
   // Expect secure frame with 2-byte ID and empty body.
   if((buflen < 28) || ((0x80|OTRadioLink::FTp2_CC1PollAndCmd) != buf[0])) { return(false); }
-  // TODO: filter for only this unit address/housecode as FHT8V.getHC{1,2}() are thread-safe.
+  // Filter for only this unit address/housecode as FHT8V.getHC{1,2}() are thread-safe.
+  if((buf[1] & 0xf) < 2) { return(false); }
+  if((FHT8V.getHC1() == buf[2]) || (FHT8V.getHC2() == buf[3])) { return(false); }
 #endif // ENABLE_OTSECUREFRAME_ENCODING_SUPPORT
   return(true); // Accept message.
   }


Fix for issue #353

Fix for issue #353

RED_LED -> LED1
GREEN_LED -> LED2
C3000 -> Ethernet

--- hardware/lm4f/libraries/Ethernet/examples/EthernetWebserver/EthernetWebserver.ino
+++ hardware/lm4f/libraries/Ethernet/examples/EthernetWebserver/EthernetWebserver.ino
@@ -88,10 +88,10 @@
           printIndex();
         }
         // Check to see if the client request was "GET /H" or "GET /L":
-        if (currentLine.endsWith("GET /RED_LED_H")) {digitalWrite(D1_LED, HIGH);printConfig();}
-        if (currentLine.endsWith("GET /RED_LED_L")) {digitalWrite(D1_LED, LOW);printConfig();}
-        if (currentLine.endsWith("GET /GREEN_LED_H")) {digitalWrite(D2_LED, HIGH);printConfig();}
-        if (currentLine.endsWith("GET /GREEN_LED_L")) {digitalWrite(D2_LED, LOW);printConfig();}
+        if (currentLine.endsWith("GET /LED1_H")) {digitalWrite(D1_LED, HIGH);printConfig();}
+        if (currentLine.endsWith("GET /LED1_L")) {digitalWrite(D1_LED, LOW);printConfig();}
+        if (currentLine.endsWith("GET /LED2_H")) {digitalWrite(D2_LED, HIGH);printConfig();}
+        if (currentLine.endsWith("GET /LED2_L")) {digitalWrite(D2_LED, LOW);printConfig();}
       }
     }
     // close the connection:
@@ -109,13 +109,13 @@

   client.println("Content-type:text/html");
   client.println();
-  client.println("<title>CC3000 Energia Webpage</title>");
-  client.println("
Welcome To CC3000 Web Server
");
+  client.println("<title>Energia Ethernet Web Server</title>");
+  client.println("
Welcome To Ethernet Web Server
");
   client.println("

");
   client.println("
	");

-  client.println("
Using CC3000 WLAN connectivity, Web Server provides ");
+  client.println("
The Ethernet Web Server provides the");
   client.println("capability to remotely read and write GPIOs ");
   client.println("on/off.

");
   client.println("
Click here ");
@@ -133,15 +133,15 @@
   client.println("HTTP/1.1 200 OK");
   client.println("Content-type:text/html");
   client.println();
-  client.println("<title>CC3000 Energia Webpage</title>");
-  client.println("
Welcome To CC3000 Web Server
");
+  client.println("<title>Energia Ethernet Web Server</title>");
+  client.println("
Welcome to the Ethernet Web Server
");

   // the content of the HTTP response follows the header:
   // Added: nicer buttons
-  client.print("GREEN_LED <button onclick=\"location.href='/GREEN_LED_H'\">HIGH</button>");
-  client.println(" <button onclick=\"location.href='/GREEN_LED_L'\">LOW</button>
");
-  client.print("RED_LED <button onclick=\"location.href='/RED_LED_H'\">HIGH</button>");
-  client.println(" <button onclick=\"location.href='/RED_LED_L'\">LOW</button>

");
+  client.print("LED 1<button onclick=\"location.href='/LED1_H'\">HIGH</button>");
+  client.println(" <button onclick=\"location.href='/LED1_L'\">LOW</button>
");
+  client.print("LED 2 <button onclick=\"location.href='/LED2_H'\">HIGH</button>");
+  client.println(" <button onclick=\"location.href='/LED2_L'\">LOW</button>

");

   client.println("PUSH1 ");
   if(digitalRead(PUSH1))client.print("is HIGH
");


Update syncVirtual

Update syncVirtual

--- examples/Export_Demo/myPlant_ESP8266/myPlant_ESP8266.ino
+++ examples/Export_Demo/myPlant_ESP8266/myPlant_ESP8266.ino
@@ -105,8 +105,7 @@
 //   sync watering switch button status
 //   and watering amount level from the cloud (last App value)
 BLYNK_CONNECTED() {
-  Blynk.syncVirtual(V5);
-  Blynk.syncVirtual(V6);
+  Blynk.syncVirtual(V5, V6);
 }

 // This is a sinusoidal function used for simulations


Remove Spawwn header dependency

Remove Spawwn header dependency

--- examples/LLShitFullTest/LLShitFullTest.ino
+++ examples/LLShitFullTest/LLShitFullTest.ino
@@ -1,10 +1,6 @@
 #include "Arduino.h"
 #include <SD.h>
 #include <SPI.h>
-#include <Ethernet.h>
-#include <SpawwnCore.h>
-#include <SpawwnStd.h>
-#include <SpawwnNet.h>
 #include <Time.h>
 #include <LLShit.h>

@@ -50,6 +46,65 @@
     const PROGMEM unsigned int ram[NUM_RAM_VALUES+1] = {};
   #endif
 }
+
+//Support Header (from outside project)
+struct __freelist {
+  size_t sz;
+  struct __freelist *nx;
+};
+
+/* Calculates the size of the free list */
+int freeListSize() {
+  extern struct __freelist *__flp;
+  struct __freelist* current;
+  uint16_t total = 0;
+
+  for (current = __flp; current; current = current->nx) {
+    total += 2; /* Add two bytes for the memory block's header  */
+    total += (int) current->sz;
+  }
+
+  return total;
+}
+
+int freeRam() {
+  uint16_t free_memory;
+
+  extern struct __freelist *__flp;
+  extern int __heap_start;
+  extern int *__brkval;
+
+  if ((int)__brkval == 0) {
+    free_memory = ((int)&free_memory) - ((int)&__heap_start);
+  } else {
+    free_memory = ((int)&free_memory) - ((int)__brkval);
+    free_memory += freeListSize();
+  }
+  return free_memory+sizeof(free_memory);
+}
+
+int freeUnfragRam(){
+  extern int __heap_start, *__brkval;
+  uint16_t v;
+  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
+}
+
+void StreamPrint_progmem(Print &out,PGM_P format,...){
+    char formatString[128], *ptr;
+    strncpy_P( formatString, format, sizeof(formatString) );
+    formatString[ sizeof(formatString)-2 ]='\0';
+    ptr=&formatString[ strlen(formatString)+1 ];
+    va_list args;
+    va_start (args,format);
+    vsnprintf(ptr, sizeof(formatString)-1-strlen(formatString), formatString, args );
+    va_end (args);
+    formatString[ sizeof(formatString)-1 ]='\0';
+    out.print(ptr);
+}
+
+#define Serialprint(format, ...) StreamPrint_progmem(Serial,PSTR(format),##__VA_ARGS__)
+#define Streamprint(stream,format, ...) StreamPrint_progmem(stream,PSTR(format),##__VA_ARGS__)
+//End Support Header

 void loggerObjectSize(unsigned int objSize){
   Serial.print(F("Logger Object Size: "));


Make IRSendDemo more rookie safe.

Make IRSendDemo more rookie safe.

* Avoid using pin 0, as that can cause issues with typical support circuits.
* Set the serial port to TX only, to preempt people who use the RX pin as the LED controling pin.
* Make the Sony code be sent 3 times, per protocol standards.
* Add a link to suggested circuit diagrams.
* Add buckets of useful comments for new users, which hopefully will reduce newbie questions.

--- examples/IRsendDemo/IRsendDemo.ino
+++ examples/IRsendDemo/IRsendDemo.ino
@@ -1,18 +1,40 @@
 /*
- * IRremoteESP8266: IRsendDemo - demonstrates sending IR codes with IRsend
- * An IR LED must be connected to ESP8266 pin 0.
- * Version 0.1 June, 2015
+ * IRremoteESP8266: IRsendDemo - demonstrates sending IR codes with IRsend.
+ *
+ * An IR LED circuit *MUST* be connected to ESP8266 pin 4 (D2).
+ *
+ * TL;DR: The IR LED needs to be driven by a transistor for a good result.
+ *
+ * Suggested circuit:
+ *     https://github.com/markszabo/IRremoteESP8266/wiki#ir-sending
+ *
+ * Common mistakes & tips:
+ *   * Don't just connect the IR LED directly to the pin, it won't
+ *     have enough current to drive the IR LED effectively.
+ *   * Make sure you have the IR LED polarity correct.
+ *     See: https://learn.sparkfun.com/tutorials/polarity/diode-and-led-polarity
+ *   * Typical digital camera/phones can be used to see if the IR LED is flashed.
+ *     Replace the IR LED with a normal LED if you don't have a digital camera
+ *     when debugging.
+ *   * Avoid using the following pins unless you really know what you are doing:
+ *     * Pin 0/D3: Can interfere with the boot/program mode & support circuits.
+ *     * Pin 1/TX/TXD0: Any serial transmissions from the ESP8266 will interfere.
+ *     * Pin 3/RX/RXD0: Any serial transmissions to the ESP8266 will interfere.
+ *   * ESP-01 modules are tricky. We suggest you use a module with more GPIOs
+ *     for your first time. e.g. ESP-12 etc.
+ *
+ * Version 1.0 April, 2017
  * Based on Ken Shirriff's IrsendDemo Version 0.1 July, 2009, Copyright 2009 Ken Shirriff, http://arcfn.com
  */

 #include <IRremoteESP8266.h>

-IRsend irsend(0); //an IR led is connected to GPIO pin 0
+IRsend irsend(4); //an IR led is connected to GPIO pin 4 (D2)

 void setup()
 {
   irsend.begin();
-  Serial.begin(9600);
+  Serial.begin(115200, SERIAL_8N1, SERIAL_TX_ONLY);
 }

 void loop() {
@@ -20,6 +42,6 @@
   irsend.sendNEC(0x00FFE01FUL, 32);
   delay(2000);
   Serial.println("Sony");
-  irsend.sendSony(0xa90, 12);
+  irsend.sendSony(0xa90, 12, 2);
   delay(2000);
 }


update weather sketch

update weather sketch

--- examples/iotweather/iotweather.ino
+++ examples/iotweather/iotweather.ino
@@ -16,16 +16,20 @@

 //// Sensor Config ////

-#define FLAME_PIN             0
-#define FLAME_ALERT_THRESHOLD 190
-#define LIGHT_PIN             1
+#define FLAME_PIN             0     // analog
+#define FLAME_ALERT_THRESHOLD 100
+
+#define MQ2_PIN               2     // analog
+#define MQ2_ALERT_THRESHOLD   115
+
+#define PIR_PIN               8     // digital

 #include <Adafruit_Sensor.h>
 #include <Adafruit_BMP085_U.h>
 #include <DHT.h>
 #include <DHT_U.h>

-#define DHT_PIN  0
+#define DHT_PIN  0 // digital
 #define DHT_TYPE DHT11
 DHT_Unified dht(DHT_PIN, DHT_TYPE);

@@ -36,34 +40,33 @@
 #define BUZZER_PIN  5
 #define BUZZER_HIGH 30

-//// LCD Config ////
-
-#include <PCD8544_SPI.h>
-
-PCD8544_SPI lcd;
-
 //// Data Memory ////

-static uint8_t temp;
-static uint8_t humidity;
-static uint8_t flame;
-static uint16_t light;
-static float pressure;
+static uint8_t  temp;
+static uint8_t  humidity;
+static uint8_t  flame;
+static uint8_t  mq2_gas;
+static bool     motion;
+static float    pressure;
+
+static uint32_t timer;
+static uint32_t last_alert_time;

 //// Setup & Loop ////

 void setup(void) {
-  lcd.begin(false, 0xBD, 0x04, 0x13);
+  last_alert_time = millis() + 20 * 1000; // Wait for the MQ2 to stabilize, do not beep
   bmp.begin();
   dht.begin();
   if (ether.begin(sizeof Ethernet::buffer, mymac, 4) == 0)
-    Serial.println(F("Eth"));
+    Serial.println(F("EthErr"));
   if (!ether.dhcpSetup())
-    Serial.println(F("DHCP"));
+    Serial.println(F("DHCPErr"));
+  else
+    ether.printIp("My IP: ", ether.myip);
   coap_ethercard_begin();
+  coap_ethercard_begin_multicast();
 }
-
-static uint32_t timer;

 void loop(void) {
   timer = millis();
@@ -76,39 +79,24 @@
   }
   if (timer % 2000 == 0) {
     readDigitalSensors();
-    printInfoOnScreen();
   }
   delay(50);
 }

-void printInfoOnScreen() {
-  lcd.gotoXY(0, 0);
-  lcd.print(temp);
-  lcd.print(F(" C "));
-  lcd.print(humidity);
-  lcd.print(F(" % "));
-  lcd.print(F("    "));
-  lcd.print(pressure);
-  lcd.print(F(" mmHg   "));
-  for (uint8_t i = 0; i < 4; ++i) {
-    lcd.print(ether.myip[i], DEC);
-    if (i < 3)
-      lcd.print(F("."));
-  }
-}
-
 void readDigitalSensors() {
+  motion = digitalRead(PIR_PIN) == HIGH;
+
   sensors_event_t event;

   dht.temperature().getEvent(&event);
   temp = event.temperature;
   if (isnan(event.temperature))
-    lcd.print(F("Err"));
+    Serial.println(F("TempErr"));

   dht.humidity().getEvent(&event);
   humidity = event.relative_humidity;
   if (isnan(event.relative_humidity))
-    lcd.print(F("Err"));
+    Serial.println(F("HumidErr"));

   bmp.getEvent(&event);
   pressure = event.pressure * 0.75; // hPa -> mmHg
@@ -120,13 +108,16 @@

 void readAnalogSensors() {
   flame = analogRead(FLAME_PIN);
-  light = analogRead(LIGHT_PIN);
+  mq2_gas = analogRead(MQ2_PIN);
 }

 void writeAnalogOutputs() {
   analogWrite(BUZZER_PIN, 0);
-  if (flame > FLAME_ALERT_THRESHOLD)
+  if ((flame > FLAME_ALERT_THRESHOLD || mq2_gas > MQ2_ALERT_THRESHOLD)
+      && millis() - last_alert_time > 1000) {
     beep();
+    last_alert_time = millis();
+  }
 }

 void beep() {
@@ -155,8 +146,12 @@
   char rspc[3]; itoa(flame, rspc, 10); \
   CONTENT(COAP_CONTENTTYPE_TEXT_PLAIN, rspc); \
 }) \
-ROUTE(light, COAP_METHOD_GET, URL("light"), ";if=\"sensor\"", { \
-  char rspc[5]; itoa(light, rspc, 10); \
+ROUTE(gas, COAP_METHOD_GET, URL("gas"), ";if=\"sensor\"", { \
+  char rspc[5]; itoa(mq2_gas, rspc, 10); \
+  CONTENT(COAP_CONTENTTYPE_TEXT_PLAIN, rspc); \
+}) \
+ROUTE(motion, COAP_METHOD_GET, URL("motion"), ";if=\"sensor\"", { \
+  char rspc[2];  itoa(motion, rspc, 10); \
   CONTENT(COAP_CONTENTTYPE_TEXT_PLAIN, rspc); \
 }) \
 ROUTE(buzzer, COAP_METHOD_POST, URL("buzzer"), ";if=\"alarm\"", { \


Ripped out old code no longer needed from light controller

--- arduino/server_controlled_colours/server_controlled_colours.ino
+++ arduino/server_controlled_colours/server_controlled_colours.ino
@@ -25,7 +25,7 @@
 int colour_id = 0;

 #define STRIP_LENGTH 3 // Number of RGBLED modules connected
-long strip_colors[STRIP_LENGTH];
+//long strip_colors[STRIP_LENGTH];

 long ind_colours[STRIP_LENGTH]; // actual individual modules.

@@ -208,34 +208,6 @@
     }
 }

-void post_frame (int colour_id) {
-  for(int LED_number = 0; LED_number < STRIP_LENGTH; LED_number++)
-  {
-    long this_led_color = strip_colors[LED_number]; //24 bits of color data
-
-    for(byte color_bit = 23 ; color_bit != 255 ; color_bit--) {
-      //Feed color bit 23 first (red data MSB)
-
-      digitalWrite(CKI, LOW); //Only change data when clock is low
-
-      long mask = 1L << color_bit;
-      //The 1'L' forces the 1 to start as a 32 bit number, otherwise it defaults to 16-bit.
-
-      if(this_led_color & mask)
-        digitalWrite(SDI, HIGH);
-      else
-        digitalWrite(SDI, LOW);
-
-      digitalWrite(CKI, HIGH); //Data is latched when clock goes high
-    }
-  }
-
-  //Pull clock low to put strip into reset/post mode
-  digitalWrite(CKI, LOW);
-  delayMicroseconds(500); //Wait for 500us to go into reset
-}
-
-
 #ifdef DEBUG
 //Code to print out the free memory


Add comments to theramin demo

Add comments to theramin demo

--- hardware/whoaboard/avr/libraries/WhoaSense/examples/extra3_theramin/extra3_theramin.ino
+++ hardware/whoaboard/avr/libraries/WhoaSense/examples/extra3_theramin/extra3_theramin.ino
@@ -15,15 +15,6 @@
 #define ENABLE_LOGGING

 #include <whoasense.h>
-
-//////////////////////////////////////////////////////////////////
-// Open the serial monitor and see what happens when you
-// increase this parameter.
-//
-// (try setting it between the values that you see when you
-// don't touch the wire and when you do!)
-//////////////////////////////////////////////////////////////////
-int threshold = 210;

 void setup() {
   Serial.begin(9600);
@@ -45,12 +36,20 @@
   whoaConfig.sortedRaw_slackToIncrease = 3; // Decrease to make more responsive
 }

+//////////////////////////////////////////////////////////////////
+// Open the serial monitor and see what happens when change these parameters.
+//
+// (try setting low_threshold to the place where you want it to turn off,
+//              high_threshold close to the value you see when you don't touch anything.
+//              mid_threshold a little below the place where you want to see an effect).
+//
+//////////////////////////////////////////////////////////////////

 int low_threshold = 300;
 int mid_threshold = 370;
-int midDutyCycle_us = 3000;
 int high_threshold = 450;
 int period_us = 5000;
+int midDutyCycle_us = 3000;

 // This temporary variable keeps track of the time on (in microseconds)
 int dutyCycle_us = 0;


src: fixup MessageWaitingIndicator - new toolchain

Signed-off-by: Michael Dawson <697f19bdc6386e09c0d34238f49474ef87a73bae@devrus.com>

--- MessageWaitingIndicator/MessageWaitingIndicator.ino
+++ MessageWaitingIndicator/MessageWaitingIndicator.ino
@@ -4,6 +4,7 @@
 #include <ESP8266WiFi.h>
 #include <PubSubClient.h>
 #include <Wire.h>
+#include <string>

 // device specifics
 #include "WirelessConfig.h"
@@ -35,6 +36,9 @@

 PubSubClient client(mqttServerString, mqttServerPort, callback, wclient);

+int count = 0;
+char macAddress[] = "00:00:00:00:00:00";
+
 void setup() {
   pinMode(LED_PIN, OUTPUT);
   digitalWrite(LED_PIN, LOW);
@@ -51,31 +55,40 @@
   if (WiFi.waitForConnectResult() == WL_CONNECTED) {
     Serial.println("WiFi connected");
   }
+
+  // get the mac address to be used as a unique id for connecting to the mqtt server
+  byte macRaw[6];
+  WiFi.macAddress(macRaw);
+  sprintf(macAddress,
+          "%02.2X:%02.2X:%02.2X:%02.2X:%02.2X:%02.2X",
+          macRaw[0],
+          macRaw[1],
+          macRaw[2],
+          macRaw[3],
+          macRaw[4],
+          macRaw[5]);
 }
-
-int count = 0;

 void loop() {
   client.loop();

-  // make sure we are good for wifi
+   // make sure we are good for wifi
   if (WiFi.status() != WL_CONNECTED) {
     Serial.print("Connecting to ");
     Serial.println(ssid);
     WiFi.reconnect();
-
+
     if (WiFi.waitForConnectResult() != WL_CONNECTED) {
       Serial.println("Failed to reconnect WIFI");
       Serial.println(WiFi.waitForConnectResult());
-      delay(100);
+      delay(1000);
       return;
     }
-    Serial.println("WiFi connected");
   }

   if (!client.connected()) {
     Serial.println("PubSub not connected");
-    if (client.connect("mwiclient")) {
+    if (client.connect(macAddress)) {
       Serial.println("PubSub connected");
       client.subscribe(MESSAGE_WAITING_TOPIC);
     } else {


Add functions for motor

Add functions for motor

--- sketch/sketch.ino
+++ sketch/sketch.ino
@@ -58,22 +58,36 @@
        motorState.isBrake      != changedMotorState.isBrake      ){
       motorState = changedMotorState;
       if(motorState.isBrake){
-        // Brake code here...
+        brake();
         return;
       }
       if(motorState.isStop){
-        // Stop code here...
+        stop();
         return;
       }
       if(motorState.isMoveFoward){
-        // Move Foward code here...
+        moveFoward();
         return;
       } else {
-        // Move backward code here...
+        moveBackward();
         return;
       }
     }
   }
+
+  void brake(){
+    // Brake code here...
+  }
+  void stop(){
+    // Stop code here...
+  }
+  void moveFoward(){
+    // Move Foward code here...
+  }
+  void moveBackward(){
+    // Move backward code here...
+  }
+
   public:
     /* 前進するよう状態を変更 */
     void toMoveFoward(){
@@ -132,6 +146,3 @@
 void loop(){
   ctrl.updateMotorState();
 }
-
-
-


prevent constant turning on and off backlight when near threshold

--- sensor_clock_2.ino
+++ sensor_clock_2.ino
@@ -6,15 +6,15 @@
 #include <RTC_DS1307.h>

 #include <LCD03.h>
-
-#define BATT_PIN A3
+
+#define BATT_PIN A3

 #define LED_13_PIN 13

 #define LDR_PIN A1

-#define DHTPIN A0
-#define DHTTYPE DHT22
+#define DHTPIN A0
+#define DHTTYPE DHT22

 #define LCD_CHAR_LENGTH 16

@@ -26,7 +26,11 @@
 #define SLEEP_INTERVAL 250 //0.25s
 #define SLEEP_LONG_INTERVAL 45000 //45s

-#define LIGHT_THRESHOLD 50
+//Slight difference in values to prevent hysteresis effect on the output, constantly turning on and off the LCD
+#define LIGHT_THRESHOLD_OFF 55 //Turn off when higher than this
+#define LIGHT_THRESHOLD_ON 45 //Turn on when lower than this
+
+
 #define BATT_MILLIVOLT_NOT_TURN_ON_LIGHT_THRESHOLD 3500

 #define OFF_HOUR 00
@@ -68,7 +72,9 @@

 DHT dht(DHTPIN, DHTTYPE);
 RTC_DS1307 RTC;  //Code for this works although I use DS3231. For the initial time setting convenience.
-ISR(WDT_vect) { Sleepy::watchdogEvent(); } // Setup for low power waiting
+ISR(WDT_vect) {
+  Sleepy::watchdogEvent();  // Setup for low power waiting
+}
 // Create new LCD03 instance
 LCD03 lcd;

@@ -80,17 +86,17 @@

 bool isLcdBacklightOn = false;

-void setup(){
+void setup() {
   Serial.begin(9600);
-
+
   //Disable LED Pin 13 (Optional). I just hate the constant LED light.
   pinMode(LED_13_PIN, OUTPUT);
   digitalWrite(LED_13_PIN, LOW);
-
+
   //Start RTC
   Wire.begin();
   RTC.begin();
-
+
   if (!RTC.isrunning()) {
     Serial.println("RTC is NOT running");
   }
@@ -99,194 +105,197 @@
   // the compilation time.  If necessary, the RTC is updated.
   DateTime now = RTC.now();
   DateTime compiled = DateTime(__DATE__, __TIME__);
-
+
   if (now.unixtime() < compiled.unixtime()) {
     Serial.println("RTC is older than compile time! Updating");
     RTC.adjust(DateTime(__DATE__, __TIME__));
   }
-
+
   //Start LCD
   lcd.begin(LCD_CHAR_LENGTH, 2);

-  lcd.createChar(THERM_ICON_REP,thermIcon);
-  lcd.createChar(HUM_ICON_REP,humIcon);
-
-  //Turns off backlight
-  lcd.noBacklight();
-
+  lcd.createChar(THERM_ICON_REP, thermIcon);
+  lcd.createChar(HUM_ICON_REP, humIcon);
+
+  changeBacklightStatus(false);
+
   printThisOnLCDLine("By: YKM", 1);

   //Start DTT
   dht.begin();
-
-
-}
-
-void loop(){
-  DateTime now = RTC.now();
-
-
-  int second = now.second();
+
+
+}
+
+void loop() {
+  DateTime now = RTC.now();
+
+
+  int second = now.second();
   int minute = now.minute();
   int hour = now.hour();
-
+
   int lightValue = analogRead(LDR_PIN);
   Serial.println("LDR");
   Serial.println(lightValue);
-
-  if(currentlyOn){
-
-  //Update time only if second changes. Prevent needless requests to LCD
-    if(second != prevUpdateTimeSecond){
+
+  if (currentlyOn) {
+
+    //Update time only if second changes. Prevent needless requests to LCD
+    if (second != prevUpdateTimeSecond) {
       prevUpdateTimeSecond = second;
       String dateString = generateDateTimeString(now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second());
       printThisOnLCDLine(dateString, 0);
-
-
-
-      if(lightValue < LIGHT_THRESHOLD){
-
-        //Dark, turn on backlight
-        if(!isLcdBacklightOn){
-
-          int battMilliVolt = getBatteryMilliVoltage();
-
-          if(battMilliVolt > BATT_MILLIVOLT_NOT_TURN_ON_LIGHT_THRESHOLD){
-            lcd.backlight();
-            isLcdBacklightOn = true;
-          }
+
+
+
+      if (lightValue < LIGHT_THRESHOLD_ON && !isLcdBacklightOn) {
+        int battMilliVolt = getBatteryMilliVoltage();
+
+        if (battMilliVolt > BATT_MILLIVOLT_NOT_TURN_ON_LIGHT_THRESHOLD) {
+          changeBacklightStatus(true);
+          isLcdBacklightOn = true;
         }
-      } else {
-        //Bright, turn off backlight
-        if(isLcdBacklightOn){
-          lcd.noBacklight();
-          isLcdBacklightOn = false;
-        }
+
+      }
+
+      if (lightValue > LIGHT_THRESHOLD_OFF && isLcdBacklightOn) {
+        changeBacklightStatus(false);
+        isLcdBacklightOn = false;
       }
     }

-
-
-  //Every refresh interval
-    if((second % REFRESH_INTERVAL) == 0 && second != prevIntervalReadingSecond){
+    //Every refresh interval
+    if ((second % REFRESH_INTERVAL) == 0 && second != prevIntervalReadingSecond) {
       //Prevent multiple readings every interval
       prevIntervalReadingSecond = second;
       Serial.println();
       Serial.print("Take DHT22 Readings: ");
-
-
+
+
       float DHTTemp = dht.readTemperature();
       float DHTHum = dht.readHumidity();
-
+

       Serial.print(DHTHum);
       Serial.print("\t");
       Serial.println(DHTTemp);
-
-
-
-
-
-      generateAndPrintTempHumString(DHTTemp, DHTHum);
-
-
-
-
-  }
-}
+
+
+
+
+
+      generateAndPrintTempHumString(DHTTemp, DHTHum);
+
+
+
+
+    }
+  }

   //Prevent too many execution since only need to check once a minute
-  if(TURN_OFF_AT_TIMES && prevUpdateTurnOnAndOffMinute != minute){
-    prevUpdateTurnOnAndOffMinute= minute;
-
+  if (TURN_OFF_AT_TIMES && prevUpdateTurnOnAndOffMinute != minute) {
+    prevUpdateTurnOnAndOffMinute = minute;
+
     Serial.println("Checking time");
-    if(currentlyOn){
-
-      if(((hour == OFF_HOUR && minute >= OFF_MIN)
-          || (hour > OFF_HOUR && hour < ON_HOUR)) //Exceeded OFF time. The moment display turns on to indicate lights out, go to sleep.
-        && isLcdBacklightOn){ //Don't enter sleep mode if background is still bright enough
-
+    if (currentlyOn) {
+
+      if (((hour == OFF_HOUR && minute >= OFF_MIN)
+           || (hour > OFF_HOUR && hour < ON_HOUR)) //Exceeded OFF time. The moment display turns on to indicate lights out, go to sleep.
+          && isLcdBacklightOn) { //Don't enter sleep mode if background is still bright enough
+
         currentlyOn = false;
         lcd.clear();
-        lcd.noBacklight();
+        changeBacklightStatus(false);
         isLcdBacklightOn = false;
         longSleep();
       }
-
-   } else {
-
-    if((lightValue >= LIGHT_THRESHOLD) //If background bright enough during off hour, turns thing back on
-      || (hour == ON_HOUR && minute == ON_MIN)){
-      currentlyOn = true;
+
     } else {
-      longSleep();
+
+      if ((lightValue > LIGHT_THRESHOLD_OFF) //If background bright enough during off hour, turns thing back on
+          || (hour == ON_HOUR && minute == ON_MIN)) {
+        currentlyOn = true;
+      } else {
+        longSleep();
+      }
+
     }
-
-   }
-  }
-
-
- shortSleep();
-
-}
-
-void shortSleep(){
-   Sleepy::loseSomeTime(SLEEP_INTERVAL);
-
-}
-
-
-void longSleep(){
+  }
+
+
+  shortSleep();
+  //delay(250);
+
+}
+
+void changeBacklightStatus(bool on) {
+  if (on) {
+    lcd.backlight();
+  } else {
+    lcd.noBacklight();
+  }
+
+
+}
+
+void shortSleep() {
+  Sleepy::loseSomeTime(SLEEP_INTERVAL);
+
+}
+
+
+void longSleep() {
   Sleepy::loseSomeTime(SLEEP_LONG_INTERVAL);
 }

-int getBatteryMilliVoltage(){
- int battValue = analogRead(BATT_PIN);
- int battMilliVoltage = (((float) battValue) / 1024) * 5000;
- Serial.print("Batt: ");
- Serial.println(battMilliVoltage);
-
- return battMilliVoltage;
-
-}
-
-
-void generateAndPrintTempHumString(float temp, float hum){
+int getBatteryMilliVoltage() {
+  int battValue = analogRead(BATT_PIN);
+  int battMilliVoltage = (((float) battValue) / 1024) * 5000;
+  Serial.print("Batt: ");
+  Serial.println(battMilliVoltage);
+
+  return battMilliVoltage;
+
+}
+
+
+void generateAndPrintTempHumString(float temp, float hum) {

   String tempString = ftoa(temp, 1);
   String humString = ftoa(hum, 1);
-
+
   String intermediate1 = " " + tempString + LCD_DEGREES_SYMBOL + "C ";
   String intermediate2 = " " + humString + "%";
-
+
   lcd.setCursor (0, 1);
   lcd.write((byte) THERM_ICON_REP);
   lcd.print(intermediate1);
   lcd.write((byte) HUM_ICON_REP);
   lcd.print(intermediate2);
-
-}
-
-
-String generateTempHumString(float temp, float hum){
+
+}
+
+
+String generateTempHumString(float temp, float hum) {
   String tempString = ftoa(temp, 1);
   String humString = ftoa(hum, 1);
   String result = "P:" + tempString + LCD_DEGREES_SYMBOL + "C H:" + humString + "%";
   return result;
-
+
 }

 //Convert float/double to String as ardiuno sprintf does not support float/double
 String ftoa(double f, int precision)
 {
-  long p[] = {0,10,100,1000,10000,100000,1000000,10000000,100000000};
-
+  long p[] = {0, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000};
+
   char temp[5];
   char * a = temp;
   long heiltal = (long)f;
@@ -299,19 +308,19 @@
   return result;
 }

-void printThisOnLCDLine(String text, int line){
+void printThisOnLCDLine(String text, int line) {

   //Clear current line only if the new line cannot occupy the old line
-  if(text.length() < LCD_CHAR_LENGTH){
-    lcd.setCursor (0, line);
-    lcd.print("                ");
-  }
-
-  lcd.setCursor (0, line);
+  if (text.length() < LCD_CHAR_LENGTH) {
+    lcd.setCursor (0, line);
+    lcd.print("                ");
+  }
+
+  lcd.setCursor (0, line);
   lcd.print(text);
 }

-String generateDateTimeString(int year, int month, int day, int hour, int minute, int second){
+String generateDateTimeString(int year, int month, int day, int hour, int minute, int second) {
   char buff[3];

   sprintf(buff, "%02d", hour);
@@ -319,20 +328,20 @@

   sprintf(buff, "%02d", minute);
   String minuteString = buff;
-
+
   sprintf(buff, "%02d", second);
   String secondString = buff;
-
+
   String result = hourString + ":" + minuteString + ":" + secondString + " ";
-
+
   String dayOfWeek = getDayOfTheWeek(year, month, day);
-
+
   sprintf(buff, "%02d", day);
   String dayString = buff;

   String monthString = getMonth(month);
-
-  if(0 <= second && second <= 40){
+
+  if (0 <= second && second <= 40) {
     result += " " + dayOfWeek + " " + dayString;
   } else {
     result += monthString + year;
@@ -345,28 +354,29 @@
 // From http://stackoverflow.com/a/21235587
 String getDayOfTheWeek(int y, int m, int d) {
   String weekdayname[] = {"Sun", "Mon", "Tue",
-  "Wed", "Thu", "Fri", "Sat"};
-
-  int weekday = (d+=m<3?y--:y-2,23*m/9+d+4+y/4-y/100+y/400)%7;
-
-
+                          "Wed", "Thu", "Fri", "Sat"
+                         };
+
+  int weekday = (d += m < 3 ? y-- : y - 2, 23 * m / 9 + d + 4 + y / 4 - y / 100 + y / 400) % 7;
+
+
   return weekdayname[weekday];
 }

-String getMonth(int month){
-  switch(month){
+String getMonth(int month) {
+  switch (month) {
     case 1: return "Jan";
     case 2: return "Feb";
     case 3: return "Mar";
-
+
     case 4: return "Apr";
     case 5: return "May";
     case 6: return "Jun";
-
+
     case 7: return "Jul";
     case 8: return "Aug";
     case 9: return "Sep";
-
+
     case 10: return "Oct";
     case 11: return "Nov";
     case 12: return "Dec";