refactoring

refactoring

--- WifiWeatherGuy.ino
+++ WifiWeatherGuy.ino
@@ -228,11 +228,13 @@
 struct Forecast {

   time_t epoch;
+  char day[4];
   int temp_high;
   int temp_low;
   int max_wind;
   int ave_wind;
   char wind_dir[8];
+  int wind_degrees;
   int ave_humidity;
   char conditions[32];
   char icon[16];
@@ -246,6 +248,7 @@
     JsonObject &day = days[i];
     struct Forecast &f = forecasts[i];
     f.epoch = (time_t)atoi(day["date"]["epoch"]);
+    strncpy(f.day, day["date"]["weekday_short"], sizeof(f.day));
     if (metric) {
       f.temp_high = atoi(day["high"]["celsius"]);
       f.temp_low = atoi(day["low"]["celsius"]);
@@ -258,6 +261,7 @@
       f.ave_wind = day["avewind"]["mph"];
     }
     f.ave_humidity = day["avehumidity"];
+    f.wind_degrees = day["avewind"]["degrees"];
     strncpy(f.wind_dir, day["avewind"]["dir"], sizeof(f.wind_dir));
     strncpy(f.conditions, day["conditions"], sizeof(f.conditions));
     strncpy(f.icon, day["icon"], sizeof(f.icon));
@@ -284,35 +288,75 @@
   return 3;
 }

-void display_weather(struct Conditions &c) {
-
-  tft.fillScreen(WHITE);
-  tft.setTextColor(BLACK);
-
+static void display_time(time_t &epoch) {
+  char buf[32];
+  strftime(buf, sizeof(buf), metric? "%H:%S": "%I:%S%p", localtime(&epoch));
+  tft.setCursor(centre_text(buf, tft.width()/2, 1), 109);
+  tft.print(buf);
+  strftime(buf, sizeof(buf), "%a %d", localtime(&epoch));
+  tft.setCursor(centre_text(buf, tft.width()/2, 1), 118);
+  tft.print(buf);
+}
+
+static void display_wind(int wind_degrees, int wind_speed) {
+    // http://www.iquilezles.org/www/articles/sincos/sincos.htm
+  int rad = tft.width()/3, cx = tft.width()/2, cy = 68;
+  const float a = 0.999847695, b = 0.017452406;
+  // wind dir is azimuthal angle with N at 0
+  float sin = 1.0, cos = 0.0;
+  for (uint16_t i = 0; i < wind_degrees; i++) {
+    const float ns = a*sin + b*cos;
+    const float nc = a*cos - b*sin;
+    cos = nc;
+    sin = ns;
+  }
+  // wind dir rotates clockwise so compensate
+  int ex = cx-rad*cos, ey = cy-rad*sin;
+  tft.fillCircle(ex, ey, 3, BLACK);
+  tft.drawLine(ex, ey, ex+wind_speed*(cx-ex)/50, ey+wind_speed*(cy-ey)/50, BLACK);
+}
+
+static void display_wind_speed(int wind_speed, const char *wind_dir, const char *wind_unit) {
   tft.setTextSize(2);
   tft.setCursor(1, 1);
-  tft.print(c.wind);
+  tft.print(wind_speed);
   tft.setTextSize(1);
-  tft.print(c.wind_unit);
+  tft.print(wind_unit);
   tft.setCursor(1, 17);
-  tft.print(c.wind_dir);
-
+  tft.print(wind_dir);
+}
+
+static void display_temperature(int temp, int temp_min, char temp_unit) {
   tft.setTextSize(2);
   tft.setCursor(1, tft.height() - 16);
-  tft.print(c.temp);
+  tft.print(temp);
   tft.setTextSize(1);
-  tft.print(c.temp_unit);
-  if (c.temp != c.feelslike) {
+  tft.print(temp_unit);
+  if (temp != temp_min) {
     tft.setCursor(1, tft.height() - 24);
-    tft.print(c.feelslike);
-  }
-
+    tft.print(temp_min);
+  }
+}
+
+static void display_humidity(int humidity) {
   tft.setTextSize(2);
-  tft.setCursor(right(val_len(c.humidity), tft.width(), 2) - 6, tft.height() - 16);
-  tft.print(c.humidity);
+  tft.setCursor(right(val_len(humidity), tft.width(), 2) - 6, tft.height() - 16);
+  tft.print(humidity);
   tft.setTextSize(1);
   tft.setCursor(tft.width() - 6, tft.height() - 16);
   tft.print('%');
+}
+
+void display_weather(struct Conditions &c) {
+
+  tft.fillScreen(WHITE);
+  tft.setTextColor(BLACK);
+
+  display_wind_speed(c.wind, c.wind_dir, c.wind_unit);
+
+  display_temperature(c.temp, c.feelslike, c.temp_unit);
+
+  display_humidity(c.humidity);

   tft.setTextSize(2);
   tft.setCursor(right(val_len(c.atmos_pressure), tft.width(), 2)-6*strlen(c.pres_unit), 1);
@@ -332,29 +376,10 @@
   tft.setCursor(centre_text(c.weather, tft.width()/2, 1), 34);
   tft.print(c.weather);
   bmp_draw(tft, c.icon, tft.width()/2 - 25, 42);
-  char buf[32];
-  strftime(buf, sizeof(buf), metric? "%H:%S": "%I:%S%p", localtime(&c.epoch));
-  tft.setCursor(centre_text(buf, tft.width()/2, 1), 109);
-  tft.print(buf);
-  strftime(buf, sizeof(buf), "%a %d", localtime(&c.epoch));
-  tft.setCursor(centre_text(buf, tft.width()/2, 1), 118);
-  tft.print(buf);
-
-  // http://www.iquilezles.org/www/articles/sincos/sincos.htm
-  int rad = tft.width()/3, cx = tft.width()/2, cy = 68;
-  const float a = 0.999847695, b = 0.017452406;
-  // wind dir is azimuthal angle with N at 0
-  float sin = 1.0, cos = 0.0;
-  for (uint16_t i = 0; i < c.wind_degrees; i++) {
-    const float ns = a*sin + b*cos;
-    const float nc = a*cos - b*sin;
-    cos = nc;
-    sin = ns;
-  }
-  // wind dir rotates clockwise so compensate
-  int ex = cx-rad*cos, ey = cy-rad*sin;
-  tft.fillCircle(ex, ey, 3, BLACK);
-  tft.drawLine(ex, ey, ex+c.wind*(cx-ex)/50, ey+c.wind*(cy-ey)/50, BLACK);
+
+  display_time(c.epoch);
+
+  display_wind(c.wind_degrees, c.wind);
 }

 void display_astronomy(struct Conditions &c) {
@@ -397,64 +422,36 @@
   strcpy(buf, "moon");
   strcat(buf, c.age_of_moon);
   bmp_draw(tft, buf, tft.width()/2 - 25, 42);
-
+
   tft.setCursor(centre_text(c.moon_phase, tft.width()/2, 1), 92);
   tft.print(c.moon_phase);

-  strftime(buf, sizeof(buf), metric? "%H:%S": "%I:%S%p", localtime(&c.epoch));
-  tft.setCursor(centre_text(buf, tft.width()/2, 1), 109);
-  tft.print(buf);
-  strftime(buf, sizeof(buf), "%a %d", localtime(&c.epoch));
-  tft.setCursor(centre_text(buf, tft.width()/2, 1), 118);
-  tft.print(buf);
+  display_time(c.epoch);
 }

 void display_forecast(struct Forecast &f) {
-
-  char buf[32];

   tft.fillScreen(WHITE);
   tft.setTextColor(BLACK);

-  tft.setTextSize(2);
-  tft.setCursor(1, 1);
-  tft.print(f.ave_wind);
-  tft.setTextSize(1);
-  tft.print(conditions.wind_unit);
-  tft.setCursor(1, 17);
-  tft.print(f.wind_dir);
-
-  tft.setTextSize(2);
-  tft.setCursor(1, tft.height() - 16);
-  tft.print(f.temp_high);
-  tft.setTextSize(1);
-  tft.print(conditions.temp_unit);
-  tft.setCursor(1, tft.height() - 24);
-  tft.print(f.temp_low);
-
-  tft.setTextSize(2);
-  tft.setCursor(right(val_len(f.ave_humidity), tft.width(), 2) - 6, tft.height() - 16);
-  tft.print(f.ave_humidity);
-  tft.setTextSize(1);
-  tft.setCursor(tft.width() - 6, tft.height() - 16);
-  tft.print('%');
+  display_wind_speed(f.ave_wind, f.wind_dir, conditions.wind_unit);
+
+  display_temperature(f.temp_high, f.temp_low, conditions.temp_unit);
+
+  display_humidity(f.ave_humidity);

   tft.setTextSize(2);
   tft.setCursor(right(3, tft.width(), 2), 1);
-  strftime(buf, sizeof(buf), "%a", localtime(&f.epoch));
-  tft.print(buf);
+  tft.print(f.day);

   tft.setTextSize(1);
   tft.setCursor(centre_text(f.conditions, tft.width()/2, 1), 34);
   tft.print(f.conditions);
   bmp_draw(tft, f.icon, tft.width()/2 - 25, 42);

-  strftime(buf, sizeof(buf), metric? "%H:%S": "%I:%S%p", localtime(&f.epoch));
-  tft.setCursor(centre_text(buf, tft.width()/2, 1), 109);
-  tft.print(buf);
-  strftime(buf, sizeof(buf), "%a %d", localtime(&f.epoch));
-  tft.setCursor(centre_text(buf, tft.width()/2, 1), 118);
-  tft.print(buf);
+  display_time(f.epoch);
+
+  display_wind(f.wind_degrees, f.ave_wind);
 }

 void update_display(int screen) {


clearing a little the code removing inncessary comments

--- Arduino/receiver/receiver.ino
+++ Arduino/receiver/receiver.ino
@@ -1,7 +1,12 @@
 /*
+
 Written by Stanley Seow
  stanleyseow@gmail.com
- */
+Modified by p431i7o
+pablito dot federico at gmail dot com
+
+Arduino sends the message throught the IR led,  it receives throught the nrf24l01
+*/

 #include <SPI.h>
 #include "nRF24L01.h"
@@ -14,28 +19,15 @@
 // Set up nRF24L01 radio on SPI pin for CE, CSN
 RF24 radio(8,9);

-// Example below using pipe5 for writing
-// // const uint64_t pipes[2] = {0xF0F0F0F0E1LL, 0x7365727631LL };
 const uint64_t pipes[2] = {0x7365727631LL, //para escribir
                            0xF0F0F0F0E1LL}; //para leer

 char receivePayload[32];
 uint8_t counter=0;
-//int outpin = 6; // pin de salida
-//int indiceActual =0;
-//int maxLongitud =0;
-//char textLargo[] = "Un texto muy largo, muy muy largo... que nunca termina porque es largo";
- int verde,amarillo,rojo;
+int amarillo;
 IRsend irsend;
 void setup(void){
-  // Conor Switch
-//  pinMode(outpin, OUTPUT);
-  //verde=LOW;
- // rojo=;
- // amarillo=0;
-  //pinMode(4,OUTPUT);// verde
   pinMode(2,OUTPUT);// amarillo
-  //pinMode(3,OUTPUT);// rojo

   Serial.begin(57600);
   printf_begin();
@@ -78,145 +70,14 @@
     }else{
       Serial.println("Numero con longitud errada, no se envia");
     }
-    /*******
-    if(strcmp(receivePayload,"encendido")==0){
-     Serial.println("Enviando encendido");
-     irsend.sendLG(0x880094D,28);
-    }else if (strcmp(receivePayload,"apagado")==0){
-      Serial.println("Enviando apagado");
-     irsend.sendLG(0x88C0051,28);
-    }else{
-      Serial.println("ninguna de las anteriores");
-    }
-    *****/
-    /******
-    if( strcmp(receivePayload,"verde")==0 ){
-      verde = turnOnOff(4,verde);
-    }else if( strcmp(receivePayload,"rojo")==0 ){
-      rojo =  turnOnOff(3,rojo);
-    }else if( strcmp(receivePayload,"amarillo")==0 ){
-      amarillo =  turnOnOff(2,amarillo);
-    }
-    *****/
-    /*
-    for(int i=0;i<len;i++){
-      sprintf(temp2,"%c",receivePayload[i]);
-      printf(temp2);
-    }
-    radio.stopListening();
-    radio.write(receivePayload,len);
-    receivePayload[len]=0;
-    Serial.println("Enviando Informacion de vuelta");
-    printf("size=%i payload=%s pipe=%i \n\r",len,receivePayload,pipe);*/
+
     delay(1000);
     Serial.println("Reanudando escucha");
-    radio.startListening();
-
+    radio.startListening();

   } //end while
   delay(1000);
 }
-/*****
-int turnOnOff(int pin,int estado){
-  if(estado==LOW ){
-    estado= HIGH;
-  }else{
-    estado= LOW;
-  }
-  digitalWrite(pin,estado);
-  return estado;
-
-} ***/
-/*
-void loop2(void){
-  maxLongitud  = strlen(textLargo);
-
-
-  uint8_t Data1,Data2,Data3,Data4 = 0;
-
-  char temp[5];
-  char temp2[1];
-  bool timeout=0;
-
-  // Get the last two Bytes as node-id
-  uint16_t nodeID = pipes[0] & 0xff;
-
-  char outBuffer[32]=""; // Clear the outBuffer before every loop
-  unsigned long send_time, rtt = 0;
-
-  // Get readings from sensors, change codes below to read sensors
-  Data1 = counter++;
-  Data2 = digitalRead(inPin); //cambiar
-  if(Data2 == HIGH){
-	if(indiceActual+1>=maxLongitud){
-       indiceActual = 0;
-    }
-	Data3 = textLargo[indiceActual];
-	indiceActual++;
-  }else{
-	Data3 =0;
-  }
-  if ( counter > 999 ){
-    counter = 0;
-  }
-
-  // Append the hex nodeID to the beginning of the payload
-  sprintf(outBuffer,"%2X",nodeID);
-  strcat(outBuffer,",");
-
-  // Convert int to strings and append with zeros if number smaller than 3 digits
-  // 000 to 999
-
-  sprintf(temp,"%03d",Data1);
-  strcat(outBuffer,temp);
-
-  strcat(outBuffer,",");
-
-  sprintf(temp,"%04d",Data2);
-  strcat(outBuffer,temp);
-
-  strcat(outBuffer,"|");
-  sprintf(temp2,"%c",Data3);
-  strcat(outBuffer,temp2);
-  printf("outBuffer: %s len: %d\n\r",outBuffer, strlen(outBuffer));
-
-  send_time = millis();
-
-  // Stop listening and write to radio
-  radio.stopListening();
-
-  // Send to hub
-  if ( radio.write( outBuffer, strlen(outBuffer)) ) {
-    printf("Enviado Correctamente\n\r");
-  }
-  else{
-    printf("FAllo al enviar\n\r");
-  }
-
-  radio.startListening();
-  delay(20);
-
-  while ( radio.available() && !timeout ){
-    uint8_t len = radio.getDynamicPayloadSize();
-    radio.read( receivePayload, len);
-    receivePayload[len] = 0;
-    printf("inBuffer:  %s\n\r",receivePayload);
-    // Compare receive payload with outBuffer
-    if ( !strcmp(outBuffer, receivePayload) ){
-      rtt = millis() - send_time;
-      printf("inBuffer --> rtt: %i \n\r",rtt);
-    }
-    // Check for timeout and exit the while loop
-    if ( millis() - send_time > 500 ) {
-      Serial.println("Timeout!!!");
-      timeout = 1;
-    }
-    delay(10);
-  } // End while
-  delay(250);
-} //end void

-*/

-


Changed thermocouple library and sample rate

--- TempLog/TempLog.ino
+++ TempLog/TempLog.ino
@@ -9,13 +9,14 @@
 This software is released under the MIT license. See the attached LICENSE file for details.
 */
 #include <Wire.h>
+#include <SPI.h>
 #include <stdio.h>
-#include "Adafruit_MAX31855.h"
+#include "Nanoshield_Thermocouple.h"
 #include "Nanoshield_EEPROM.h"
 #include "Nanoshield_RTC.h"

 // Define the temperature sampling interval in milliseconds
-#define SAMPLING_INTERVAL 60000
+#define SAMPLING_INTERVAL 10000

 // EEPROM record size in bytes
 #define RECORD_SIZE 9
@@ -23,7 +24,7 @@
 // Maximum number of records
 #define MAX_RECORDS 3640

-Adafruit_MAX31855 thermocouple(13, 8, 12);
+Nanoshield_Thermocouple thermocouple;
 Nanoshield_EEPROM eeprom(0, 0, 0);
 Nanoshield_RTC rtc;
 unsigned int nextRecord;
@@ -41,6 +42,7 @@
   // Initialize EEPROM and RTC
   eeprom.begin();
   rtc.begin();
+  thermocouple.begin();

   // Delay to let thermocouple stabilize
   delay(500);
@@ -58,6 +60,7 @@
 void loop()
 {
   // Keep saving records to EEPROM and printing the into the serial port
+  thermocouple.read();
   rtc.read();
   saveRecord(
     nextRecord,
@@ -68,8 +71,8 @@
     rtc.getWeekday(),
     rtc.getMonth(),
     rtc.getYear(),
-    thermocouple.readInternal(),
-    thermocouple.readCelsius()
+    thermocouple.getInternal(),
+    thermocouple.getExternal()
   );
   printRecord(nextRecord++);


Fix function name for voltage alarm

Fix function name for voltage alarm

--- src/rx5808-pro-diversity/rx5808-pro-diversity.ino
+++ src/rx5808-pro-diversity/rx5808-pro-diversity.ino
@@ -473,7 +473,7 @@
 #endif
 #ifdef USE_VOLTAGE_MONITORING
             readVoltage();
-            voltage_alarm();
+            voltageAlarm();
             drawScreen.updateVoltageScreenSaver(voltage, warning_alarm || critical_alarm);
 #endif
         do{
@@ -487,7 +487,7 @@

 #ifdef USE_VOLTAGE_MONITORING
             readVoltage();
-            voltage_alarm();
+            voltageAlarm();

             drawScreen.updateVoltageScreenSaver(voltage, warning_alarm || critical_alarm);
 #endif
@@ -509,7 +509,7 @@
             do {
                 drawScreen.updateVoltage(voltage);
                 readVoltage();
-                voltage_alarm();
+                voltageAlarm();
                 //delay(100); // timeout delay
             }
             while((digitalRead(PIN_BUTTON_MODE) == HIGH) && (digitalRead(PIN_BUTTON_UP) == HIGH) && (digitalRead(PIN_BUTTON_DOWN) == HIGH)); // wait for next key press
@@ -949,7 +949,7 @@
     }
 #ifdef USE_VOLTAGE_MONITORING
     readVoltage();
-    voltage_alarm();
+    voltageAlarm();
 #endif
 }

@@ -1058,7 +1058,7 @@
         warning_alarm = false;
     }
 }
-void voltage_alarm(){
+void voltageAlarm(){
     if(millis() > time_last_vbat_alarm + ALARM_EVERY_MSEC){
         if(critical_alarm){
             //continue playint the critical alarm


v4.2 Add maxRandomNumber

v4.2 Add maxRandomNumber

--- WeatherDisplay.ino
+++ WeatherDisplay.ino
@@ -283,10 +283,11 @@
   };

   // Get random number
-  randomColor =  random(0, 7);
+  byte maxRandomNumber = sizeof(textColor) / sizeof(unsigned int);
+  randomColor =  random(maxRandomNumber);
   // If random number repeats, try again
   while (randomColor == lastRandomNumber) {
-    randomColor = random(0, 7);
+    randomColor = random(maxRandomNumber);
   }
   lastRandomNumber = randomColor;
   if (randomColor == 0) {


v3.3 Fix time display, again

v3.3 Fix time display, again

--- WeatherDisplay.ino
+++ WeatherDisplay.ino
@@ -441,20 +441,24 @@
   int month = monthS.toInt();
   String dayS = timeS.substring(8, 10);
   int day = dayS.toInt();
-
+
   timeS = timeS.substring(length - 8, length - 6); // Strip out the hours
   int time = timeS.toInt();

 #ifdef CONVERTTIMETOLOCAL
-  // For some reason, time is off by some (???) hours from UTC. Need to compensate
+  // For some reason, openweathermap.org time is off by some (???)
+  // hours from UTC. Need to compensate
   int TimeErrorOffset = -3;
   if (((time > 18) && (time < 21)) ||
-      (time == 12) ||
-      (time == 15)) {
+      (time == 12)) {
     time += (TimeErrorOffset + 2);
+  }
+  else if (time == 15) {
+    time += (TimeErrorOffset + 0);
   }
   else if (time == 0) {
     time += (TimeErrorOffset + 0);
+    convertDate(time, &year, &month, &day);
   }
   else {
     time += TimeErrorOffset;
@@ -462,7 +466,7 @@
   // Convert UTC time & date to local time & date
   bool DST = convertToLocal(&time, &year, &month,
                             &day, (double)longitude.toFloat(), true); // true means date and DST conversion
-
+
 #endif

   *monthI = month;
@@ -846,290 +850,318 @@
   return (DST);
 }

-/*
-  SUNRISET.C - Computes Sun rise/set times, start/end of twilight, and
-             the length of the day at any date and latitude
-
-  Written as DAYLEN.C, 1989-08-16
-
-  Modified to SUNRISET.C, 1992-12-01
-
-  (c) Paul Schlyter, 1989, 1992
-
-  Released to the public domain by Paul Schlyter, December 1992
-
-  http://stjarnhimlen.se/comp/sunriset.c
-
-*/
-
-/* The "workhorse" function for sun rise/set times */
-int __sunriset__( int year, int month, int day, double lon, double lat,
-                  double altit, int upper_limb, double *trise, double *tset )
-/***************************************************************************/
-/* Note: year,month,date = calendar date, 1801-2099 only.             */
-/*       Eastern longitude positive, Western longitude negative       */
-/*       Northern latitude positive, Southern latitude negative       */
-/*       The longitude value IS critical in this function!            */
-/*       altit = the altitude which the Sun should cross              */
-/*               Set to -35/60 degrees for rise/set, -6 degrees       */
-/*               for civil, -12 degrees for nautical and -18          */
-/*               degrees for astronomical twilight.                   */
-/*         upper_limb: non-zero -> upper limb, zero -> center         */
-/*               Set to non-zero (e.g. 1) when computing rise/set     */
-/*               times, and to zero when computing start/end of       */
-/*               twilight.                                            */
-/*        *rise = where to store the rise time                        */
-/*        *set  = where to store the set  time                        */
-/*                Both times are relative to the specified altitude,  */
-/*                and thus this function can be used to compute       */
-/*                various twilight times, as well as rise/set times   */
-/* Return value:  0 = sun rises/sets this day, times stored at        */
-/*                    *trise and *tset.                               */
-/*               +1 = sun above the specified "horizon" 24 hours.     */
-/*                    *trise set to time when the sun is at south,    */
-/*                    minus 12 hours while *tset is set to the south  */
-/*                    time plus 12 hours. "Day" length = 24 hours     */
-/*               -1 = sun is below the specified "horizon" 24 hours   */
-/*                    "Day" length = 0 hours, *trise and *tset are    */
-/*                    both set to the time when the sun is at south.  */
-/*                                                                    */
-/**********************************************************************/
-{
-  double  d,  /* Days since 2000 Jan 0.0 (negative before) */
-          sr,         /* Solar distance, astronomical units */
-          sRA,        /* Sun's Right Ascension */
-          sdec,       /* Sun's declination */
-          sradius,    /* Sun's apparent radius */
-          t,          /* Diurnal arc */
-          tsouth,     /* Time when Sun is at south */
-          sidtime;    /* Local sidereal time */
-
-  int rc = 0; /* Return cde from function - usually 0 */
-
-  /* Compute d of 12h local mean solar time */
-  d = days_since_2000_Jan_0(year, month, day) + 0.5 - lon / 360.0;
-
-  /* Compute the local sidereal time of this moment */
-  sidtime = revolution( GMST0(d) + 180.0 + lon );
-
-  /* Compute Sun's RA, Decl and distance at this moment */
-  sun_RA_dec( d, &sRA, &sdec, &sr );
-
-  /* Compute time when Sun is at south - in hours UT */
-  tsouth = 12.0 - rev180(sidtime - sRA) / 15.0;
-
-  /* Compute the Sun's apparent radius in degrees */
-  sradius = 0.2666 / sr;
-
-  /* Do correction to upper limb, if necessary */
-  if ( upper_limb )
-    altit -= sradius;
-
-  /* Compute the diurnal arc that the Sun traverses to reach */
-  /* the specified altitude altit: */
-  {
-    double cost;
-    cost = ( sind(altit) - sind(lat) * sind(sdec) ) /
-           ( cosd(lat) * cosd(sdec) );
-    if ( cost >= 1.0 )
-      rc = -1, t = 0.0;       /* Sun always below altit */
-    else if ( cost <= -1.0 )
-      rc = +1, t = 12.0;      /* Sun always above altit */
-    else
-      t = acosd(cost) / 15.0; /* The diurnal arc, hours */
-  }
-
-  /* Store rise and set times - in hours UT */
-  *trise = tsouth - t;
-  *tset  = tsouth + t;
-
-  return rc;
-}  /* __sunriset__ */
-
-/* The "workhorse" function */
-double __daylen__( int year, int month, int day, double lon, double lat,
-                   double altit, int upper_limb )
-/**********************************************************************/
-/* Note: year,month,date = calendar date, 1801-2099 only.             */
-/*       Eastern longitude positive, Western longitude negative       */
-/*       Northern latitude positive, Southern latitude negative       */
-/*       The longitude value is not critical. Set it to the correct   */
-/*       longitude if you're picky, otherwise set to to, say, 0.0     */
-/*       The latitude however IS critical - be sure to get it correct */
-/*       altit = the altitude which the Sun should cross              */
-/*               Set to -35/60 degrees for rise/set, -6 degrees       */
-/*               for civil, -12 degrees for nautical and -18          */
-/*               degrees for astronomical twilight.                   */
-/*         upper_limb: non-zero -> upper limb, zero -> center         */
-/*               Set to non-zero (e.g. 1) when computing day length   */
-/*               and to zero when computing day+twilight length.      */
-/**********************************************************************/
-{
-  double  d,  /* Days since 2000 Jan 0.0 (negative before) */
-          obl_ecl,    /* Obliquity (inclination) of Earth's axis */
-          sr,         /* Solar distance, astronomical units */
-          slon,       /* True solar longitude */
-          sin_sdecl,  /* Sine of Sun's declination */
-          cos_sdecl,  /* Cosine of Sun's declination */
-          sradius,    /* Sun's apparent radius */
-          t;          /* Diurnal arc */
-
-  /* Compute d of 12h local mean solar time */
-  d = days_since_2000_Jan_0(year, month, day) + 0.5 - lon / 360.0;
-
-  /* Compute obliquity of ecliptic (inclination of Earth's axis) */
-  obl_ecl = 23.4393 - 3.563E-7 * d;
-
-  /* Compute Sun's ecliptic longitude and distance */
-  sunpos( d, &slon, &sr );
-
-  /* Compute sine and cosine of Sun's declination */
-  sin_sdecl = sind(obl_ecl) * sind(slon);
-  cos_sdecl = sqrt( 1.0 - sin_sdecl * sin_sdecl );
-
-  /* Compute the Sun's apparent radius, degrees */
-  sradius = 0.2666 / sr;
-
-  /* Do correction to upper limb, if necessary */
-  if ( upper_limb )
-    altit -= sradius;
-
-  /* Compute the diurnal arc that the Sun traverses to reach */
-  /* the specified altitude altit: */
-  {
-    double cost;
-    cost = ( sind(altit) - sind(lat) * sin_sdecl ) /
-           ( cosd(lat) * cos_sdecl );
-    if ( cost >= 1.0 )
-      t = 0.0;                      /* Sun always below altit */
-    else if ( cost <= -1.0 )
-      t = 24.0;                     /* Sun always above altit */
-    else  t = (2.0 / 15.0) * acosd(cost); /* The diurnal arc, hours */
-  }
-  return t;
-}  /* __daylen__ */
-
-/* This function computes the Sun's position at any instant */
-void sunpos( double d, double *lon, double *r )
-/******************************************************/
-/* Computes the Sun's ecliptic longitude and distance */
-/* at an instant given in d, number of days since     */
-/* 2000 Jan 0.0.  The Sun's ecliptic latitude is not  */
-/* computed, since it's always very near 0.           */
-/******************************************************/
-{
-  double M,         /* Mean anomaly of the Sun */
-         w,         /* Mean longitude of perihelion */
-         /* Note: Sun's mean longitude = M + w */
-         e,         /* Eccentricity of Earth's orbit */
-         E,         /* Eccentric anomaly */
-         x, y,      /* x, y coordinates in orbit */
-         v;         /* True anomaly */
-
-  /* Compute mean elements */
-  M = revolution( 356.0470 + 0.9856002585 * d );
-  w = 282.9404 + 4.70935E-5 * d;
-  e = 0.016709 - 1.151E-9 * d;
-
-  /* Compute true longitude and radius vector */
-  E = M + e * RADEG * sind(M) * ( 1.0 + e * cosd(M) );
-  x = cosd(E) - e;
-  y = sqrt( 1.0 - e * e ) * sind(E);
-  *r = sqrt( x * x + y * y );          /* Solar distance */
-  v = atan2d( y, x );                  /* True anomaly */
-  *lon = v + w;                        /* True solar longitude */
-  if ( *lon >= 360.0 )
-    *lon -= 360.0;                   /* Make it 0..360 degrees */
-}
-
-void sun_RA_dec( double d, double *RA, double *dec, double *r )
-/******************************************************/
-/* Computes the Sun's equatorial coordinates RA, Decl */
-/* and also its distance, at an instant given in d,   */
-/* the number of days since 2000 Jan 0.0.             */
-/******************************************************/
-{
-  double lon, obl_ecl, x, y, z;
-
-  /* Compute Sun's ecliptical coordinates */
-  sunpos( d, &lon, r );
-
-  /* Compute ecliptic rectangular coordinates (z=0) */
-  x = *r * cosd(lon);
-  y = *r * sind(lon);
-
-  /* Compute obliquity of ecliptic (inclination of Earth's axis) */
-  obl_ecl = 23.4393 - 3.563E-7 * d;
-
-  /* Convert to equatorial rectangular coordinates - x is unchanged */
-  z = y * sind(obl_ecl);
-  y = y * cosd(obl_ecl);
-
-  /* Convert to spherical coordinates */
-  *RA = atan2d( y, x );
-  *dec = atan2d( z, sqrt(x * x + y * y) );
-
-}  /* sun_RA_dec */
-
-/******************************************************************/
-/* This function reduces any angle to within the first revolution */
-/* by subtracting or adding even multiples of 360.0 until the     */
-/* result is >= 0.0 and < 360.0                                   */
-/******************************************************************/
+void convertDate(int hour, int* year, int* month, int* day) {
+
+  uint8_t DaysAMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
+
+  if (*year % 4 == 0) DaysAMonth[1] = 29; //leap year check (the simple method)
+  if (hour < 24) {
+    *day -= 1;
+    if (*day < 1) {
+      if (*month == 1) {
+        *month = 12;
+        *year -= 1;
+      } // if (*month == 1)
+      else {
+        *month -= 1;
+      }
+      *day = DaysAMonth[*month - 1];
+    } // if (*day < 1)
+  } // if (*hour < 24)
+  else if (hour >= 24) {
+    *day += 1;
+    if (*day > DaysAMonth[*month - 1]) {
+      *day = 1;
+      *month += 1;
+      if (*month > 12) *year += 1;
+    } // if (*day > DaysAMonth[*month - 1])
+  }
+}
+
+  /*
+    SUNRISET.C - Computes Sun rise/set times, start/end of twilight, and
+               the length of the day at any date and latitude
+
+    Written as DAYLEN.C, 1989-08-16
+
+    Modified to SUNRISET.C, 1992-12-01
+
+    (c) Paul Schlyter, 1989, 1992
+
+    Released to the public domain by Paul Schlyter, December 1992
+
+    http://stjarnhimlen.se/comp/sunriset.c
+
+  */
+
+  /* The "workhorse" function for sun rise/set times */
+  int __sunriset__( int year, int month, int day, double lon, double lat,
+                    double altit, int upper_limb, double * trise, double * tset )
+  /***************************************************************************/
+  /* Note: year,month,date = calendar date, 1801-2099 only.             */
+  /*       Eastern longitude positive, Western longitude negative       */
+  /*       Northern latitude positive, Southern latitude negative       */
+  /*       The longitude value IS critical in this function!            */
+  /*       altit = the altitude which the Sun should cross              */
+  /*               Set to -35/60 degrees for rise/set, -6 degrees       */
+  /*               for civil, -12 degrees for nautical and -18          */
+  /*               degrees for astronomical twilight.                   */
+  /*         upper_limb: non-zero -> upper limb, zero -> center         */
+  /*               Set to non-zero (e.g. 1) when computing rise/set     */
+  /*               times, and to zero when computing start/end of       */
+  /*               twilight.                                            */
+  /*        *rise = where to store the rise time                        */
+  /*        *set  = where to store the set  time                        */
+  /*                Both times are relative to the specified altitude,  */
+  /*                and thus this function can be used to compute       */
+  /*                various twilight times, as well as rise/set times   */
+  /* Return value:  0 = sun rises/sets this day, times stored at        */
+  /*                    *trise and *tset.                               */
+  /*               +1 = sun above the specified "horizon" 24 hours.     */
+  /*                    *trise set to time when the sun is at south,    */
+  /*                    minus 12 hours while *tset is set to the south  */
+  /*                    time plus 12 hours. "Day" length = 24 hours     */
+  /*               -1 = sun is below the specified "horizon" 24 hours   */
+  /*                    "Day" length = 0 hours, *trise and *tset are    */
+  /*                    both set to the time when the sun is at south.  */
+  /*                                                                    */
+  /**********************************************************************/
+  {
+    double  d,  /* Days since 2000 Jan 0.0 (negative before) */
+            sr,         /* Solar distance, astronomical units */
+            sRA,        /* Sun's Right Ascension */
+            sdec,       /* Sun's declination */
+            sradius,    /* Sun's apparent radius */
+            t,          /* Diurnal arc */
+            tsouth,     /* Time when Sun is at south */
+            sidtime;    /* Local sidereal time */
+
+    int rc = 0; /* Return cde from function - usually 0 */
+
+    /* Compute d of 12h local mean solar time */
+    d = days_since_2000_Jan_0(year, month, day) + 0.5 - lon / 360.0;
+
+    /* Compute the local sidereal time of this moment */
+    sidtime = revolution( GMST0(d) + 180.0 + lon );
+
+    /* Compute Sun's RA, Decl and distance at this moment */
+    sun_RA_dec( d, &sRA, &sdec, &sr );
+
+    /* Compute time when Sun is at south - in hours UT */
+    tsouth = 12.0 - rev180(sidtime - sRA) / 15.0;
+
+    /* Compute the Sun's apparent radius in degrees */
+    sradius = 0.2666 / sr;
+
+    /* Do correction to upper limb, if necessary */
+    if ( upper_limb )
+      altit -= sradius;
+
+    /* Compute the diurnal arc that the Sun traverses to reach */
+    /* the specified altitude altit: */
+    {
+      double cost;
+      cost = ( sind(altit) - sind(lat) * sind(sdec) ) /
+             ( cosd(lat) * cosd(sdec) );
+      if ( cost >= 1.0 )
+        rc = -1, t = 0.0;       /* Sun always below altit */
+      else if ( cost <= -1.0 )
+        rc = +1, t = 12.0;      /* Sun always above altit */
+      else
+        t = acosd(cost) / 15.0; /* The diurnal arc, hours */
+    }
+
+    /* Store rise and set times - in hours UT */
+    *trise = tsouth - t;
+    *tset  = tsouth + t;
+
+    return rc;
+  }  /* __sunriset__ */
+
+  /* The "workhorse" function */
+  double __daylen__( int year, int month, int day, double lon, double lat,
+                     double altit, int upper_limb )
+  /**********************************************************************/
+  /* Note: year,month,date = calendar date, 1801-2099 only.             */
+  /*       Eastern longitude positive, Western longitude negative       */
+  /*       Northern latitude positive, Southern latitude negative       */
+  /*       The longitude value is not critical. Set it to the correct   */
+  /*       longitude if you're picky, otherwise set to to, say, 0.0     */
+  /*       The latitude however IS critical - be sure to get it correct */
+  /*       altit = the altitude which the Sun should cross              */
+  /*               Set to -35/60 degrees for rise/set, -6 degrees       */
+  /*               for civil, -12 degrees for nautical and -18          */
+  /*               degrees for astronomical twilight.                   */
+  /*         upper_limb: non-zero -> upper limb, zero -> center         */
+  /*               Set to non-zero (e.g. 1) when computing day length   */
+  /*               and to zero when computing day+twilight length.      */
+  /**********************************************************************/
+  {
+    double  d,  /* Days since 2000 Jan 0.0 (negative before) */
+            obl_ecl,    /* Obliquity (inclination) of Earth's axis */
+            sr,         /* Solar distance, astronomical units */
+            slon,       /* True solar longitude */
+            sin_sdecl,  /* Sine of Sun's declination */
+            cos_sdecl,  /* Cosine of Sun's declination */
+            sradius,    /* Sun's apparent radius */
+            t;          /* Diurnal arc */
+
+    /* Compute d of 12h local mean solar time */
+    d = days_since_2000_Jan_0(year, month, day) + 0.5 - lon / 360.0;
+
+    /* Compute obliquity of ecliptic (inclination of Earth's axis) */
+    obl_ecl = 23.4393 - 3.563E-7 * d;
+
+    /* Compute Sun's ecliptic longitude and distance */
+    sunpos( d, &slon, &sr );
+
+    /* Compute sine and cosine of Sun's declination */
+    sin_sdecl = sind(obl_ecl) * sind(slon);
+    cos_sdecl = sqrt( 1.0 - sin_sdecl * sin_sdecl );
+
+    /* Compute the Sun's apparent radius, degrees */
+    sradius = 0.2666 / sr;
+
+    /* Do correction to upper limb, if necessary */
+    if ( upper_limb )
+      altit -= sradius;
+
+    /* Compute the diurnal arc that the Sun traverses to reach */
+    /* the specified altitude altit: */
+    {
+      double cost;
+      cost = ( sind(altit) - sind(lat) * sin_sdecl ) /
+             ( cosd(lat) * cos_sdecl );
+      if ( cost >= 1.0 )
+        t = 0.0;                      /* Sun always below altit */
+      else if ( cost <= -1.0 )
+        t = 24.0;                     /* Sun always above altit */
+      else  t = (2.0 / 15.0) * acosd(cost); /* The diurnal arc, hours */
+    }
+    return t;
+  }  /* __daylen__ */
+
+  /* This function computes the Sun's position at any instant */
+  void sunpos( double d, double * lon, double * r )
+  /******************************************************/
+  /* Computes the Sun's ecliptic longitude and distance */
+  /* at an instant given in d, number of days since     */
+  /* 2000 Jan 0.0.  The Sun's ecliptic latitude is not  */
+  /* computed, since it's always very near 0.           */
+  /******************************************************/
+  {
+    double M,         /* Mean anomaly of the Sun */
+           w,         /* Mean longitude of perihelion */
+           /* Note: Sun's mean longitude = M + w */
+           e,         /* Eccentricity of Earth's orbit */
+           E,         /* Eccentric anomaly */
+           x, y,      /* x, y coordinates in orbit */
+           v;         /* True anomaly */
+
+    /* Compute mean elements */
+    M = revolution( 356.0470 + 0.9856002585 * d );
+    w = 282.9404 + 4.70935E-5 * d;
+    e = 0.016709 - 1.151E-9 * d;
+
+    /* Compute true longitude and radius vector */
+    E = M + e * RADEG * sind(M) * ( 1.0 + e * cosd(M) );
+    x = cosd(E) - e;
+    y = sqrt( 1.0 - e * e ) * sind(E);
+    *r = sqrt( x * x + y * y );          /* Solar distance */
+    v = atan2d( y, x );                  /* True anomaly */
+    *lon = v + w;                        /* True solar longitude */
+    if ( *lon >= 360.0 )
+      *lon -= 360.0;                   /* Make it 0..360 degrees */
+  }
+
+  void sun_RA_dec( double d, double * RA, double * dec, double * r )
+  /******************************************************/
+  /* Computes the Sun's equatorial coordinates RA, Decl */
+  /* and also its distance, at an instant given in d,   */
+  /* the number of days since 2000 Jan 0.0.             */
+  /******************************************************/
+  {
+    double lon, obl_ecl, x, y, z;
+
+    /* Compute Sun's ecliptical coordinates */
+    sunpos( d, &lon, r );
+
+    /* Compute ecliptic rectangular coordinates (z=0) */
+    x = *r * cosd(lon);
+    y = *r * sind(lon);
+
+    /* Compute obliquity of ecliptic (inclination of Earth's axis) */
+    obl_ecl = 23.4393 - 3.563E-7 * d;
+
+    /* Convert to equatorial rectangular coordinates - x is unchanged */
+    z = y * sind(obl_ecl);
+    y = y * cosd(obl_ecl);
+
+    /* Convert to spherical coordinates */
+    *RA = atan2d( y, x );
+    *dec = atan2d( z, sqrt(x * x + y * y) );
+
+  }  /* sun_RA_dec */
+
+  /******************************************************************/
+  /* This function reduces any angle to within the first revolution */
+  /* by subtracting or adding even multiples of 360.0 until the     */
+  /* result is >= 0.0 and < 360.0                                   */
+  /******************************************************************/
 #define INV360    ( 1.0 / 360.0 )

-double revolution( double x )
-/*****************************************/
-/* Reduce angle to within 0..360 degrees */
-/*****************************************/
-{
-  return ( x - 360.0 * floor( x * INV360 ) );
-}  /* revolution */
-
-double rev180( double x )
-/*********************************************/
-/* Reduce angle to within +180..+180 degrees */
-/*********************************************/
-{
-  return ( x - 360.0 * floor( x * INV360 + 0.5 ) );
-}  /* revolution */
-
-
-/*******************************************************************/
-/* This function computes GMST0, the Greenwich Mean Sidereal Time  */
-/* at 0h UT (i.e. the sidereal time at the Greenwhich meridian at  */
-/* 0h UT).  GMST is then the sidereal time at Greenwich at any     */
-/* time of the day.  I've generalized GMST0 as well, and define it */
-/* as:  GMST0 = GMST - UT  --  this allows GMST0 to be computed at */
-/* other times than 0h UT as well.  While this sounds somewhat     */
-/* contradictory, it is very practical:  instead of computing      */
-/* GMST like:                                                      */
-/*                                                                 */
-/*  GMST = (GMST0) + UT * (366.2422/365.2422)                      */
-/*                                                                 */
-/* where (GMST0) is the GMST last time UT was 0 hours, one simply  */
-/* computes:                                                       */
-/*                                                                 */
-/*  GMST = GMST0 + UT                                              */
-/*                                                                 */
-/* where GMST0 is the GMST "at 0h UT" but at the current moment!   */
-/* Defined in this way, GMST0 will increase with about 4 min a     */
-/* day.  It also happens that GMST0 (in degrees, 1 hr = 15 degr)   */
-/* is equal to the Sun's mean longitude plus/minus 180 degrees!    */
-/* (if we neglect aberration, which amounts to 20 seconds of arc   */
-/* or 1.33 seconds of time)                                        */
-/*                                                                 */
-/*******************************************************************/
-
-double GMST0( double d )
-{
-  double sidtim0;
-  /* Sidtime at 0h UT = L (Sun's mean longitude) + 180.0 degr  */
-  /* L = M + w, as defined in sunpos().  Since I'm too lazy to */
-  /* add these numbers, I'll let the C compiler do it for me.  */
-  /* Any decent C compiler will add the constants at compile   */
-  /* time, imposing no runtime or code overhead.               */
-  sidtim0 = revolution( ( 180.0 + 356.0470 + 282.9404 ) +
-                        ( 0.9856002585 + 4.70935E-5 ) * d );
-  return sidtim0;
-}  /* GMST0 */
+  double revolution( double x )
+  /*****************************************/
+  /* Reduce angle to within 0..360 degrees */
+  /*****************************************/
+  {
+    return ( x - 360.0 * floor( x * INV360 ) );
+  }  /* revolution */
+
+  double rev180( double x )
+  /*********************************************/
+  /* Reduce angle to within +180..+180 degrees */
+  /*********************************************/
+  {
+    return ( x - 360.0 * floor( x * INV360 + 0.5 ) );
+  }  /* revolution */
+
+
+  /*******************************************************************/
+  /* This function computes GMST0, the Greenwich Mean Sidereal Time  */
+  /* at 0h UT (i.e. the sidereal time at the Greenwhich meridian at  */
+  /* 0h UT).  GMST is then the sidereal time at Greenwich at any     */
+  /* time of the day.  I've generalized GMST0 as well, and define it */
+  /* as:  GMST0 = GMST - UT  --  this allows GMST0 to be computed at */
+  /* other times than 0h UT as well.  While this sounds somewhat     */
+  /* contradictory, it is very practical:  instead of computing      */
+  /* GMST like:                                                      */
+  /*                                                                 */
+  /*  GMST = (GMST0) + UT * (366.2422/365.2422)                      */
+  /*                                                                 */
+  /* where (GMST0) is the GMST last time UT was 0 hours, one simply  */
+  /* computes:                                                       */
+  /*                                                                 */
+  /*  GMST = GMST0 + UT                                              */
+  /*                                                                 */
+  /* where GMST0 is the GMST "at 0h UT" but at the current moment!   */
+  /* Defined in this way, GMST0 will increase with about 4 min a     */
+  /* day.  It also happens that GMST0 (in degrees, 1 hr = 15 degr)   */
+  /* is equal to the Sun's mean longitude plus/minus 180 degrees!    */
+  /* (if we neglect aberration, which amounts to 20 seconds of arc   */
+  /* or 1.33 seconds of time)                                        */
+  /*                                                                 */
+  /*******************************************************************/
+
+  double GMST0( double d )
+  {
+    double sidtim0;
+    /* Sidtime at 0h UT = L (Sun's mean longitude) + 180.0 degr  */
+    /* L = M + w, as defined in sunpos().  Since I'm too lazy to */
+    /* add these numbers, I'll let the C compiler do it for me.  */
+    /* Any decent C compiler will add the constants at compile   */
+    /* time, imposing no runtime or code overhead.               */
+    sidtim0 = revolution( ( 180.0 + 356.0470 + 282.9404 ) +
+                          ( 0.9856002585 + 4.70935E-5 ) * d );
+    return sidtim0;
+  }  /* GMST0 */


Posting to Phant implemented.

Posting to Phant implemented.

Data is now posted to a Phat data stream.
Data collection is now moved from ISR to the main program loop.

--- WeatherStation.ino
+++ WeatherStation.ino
@@ -36,7 +36,7 @@
 #include <NtpClientLib.h>
 #include <Adafruit_Sensor.h>
 #include <Adafruit_BME280.h>
-#include <Adafruit_MQTT.h>
+#include "Adafruit_MQTT.h"
 #include "Adafruit_MQTT_Client.h"
 #include <SparkFunTSL2561.h>
 #include <Wire.h>
@@ -48,16 +48,14 @@
 //
 //  Definitions used in the code for pins etc.
 //
-#define VERSION                 "0.18"
-//
-#define PIN_READ_SENSORS        11
+#define VERSION                 "0.19"
+//
 #define PIN_ONBOARD_LED         1
 #define PIN_WIND_SPEED          9
 #define PIN_PLUVIOMETER         8
 #define PIN_GROUND_TEMPERATURE  7
 #define PIN_RTC_INTERRUPT       5
 #define PIN_WIND_DIRECTION      A0
-#define SLEEP_PERIOD            0.5

 //
 //  Weather Sensor definitions.
@@ -75,6 +73,12 @@
 Ticker _fiveSecondTicker;

 //
+//  Indicate if we should read the sesnosrs.
+//
+bool _readSensors = false;
+unsigned int _readingNumber = 0;
+
+//
 //  DS3234 real time clock object.
 //
 DS3231 *rtc;
@@ -84,7 +88,7 @@
 //  We are logging to Phant and we need somewhere to store the client and keys.
 //
 #define PHANT_DOMAIN        "data.sparkfun.com"
-#define PHANT_PAGE          "/input/YGY7EV1WwpToK65bNa56"
+#define PHANT_PAGE          "/input/zDA9M8dQlahOqo4bx5Dd"
 #define PHANT_PORT          80

 //
@@ -134,13 +138,6 @@
 Adafruit_MQTT_Publish _airPressureFeed = Adafruit_MQTT_Publish(&mqtt, AIR_PRESSURE_FEED);

 //
-//  UDP Debugging definitions.
-//
-#define UDP_DEBUG_PORT      5000
-WiFiUDP _udpDebug;
-IPAddress _udpDestination;
-
-//
 //  Used for debugging, determine the output state of the onboard LED.
 //
 bool _ledOutput = false;
@@ -153,31 +150,22 @@
     char number[20];

     String url = PHANT_PAGE "?private_key=" PHANT_PRIVATE_KEY;
-    url += "&When=";
-    ts *currentDateTime = rtc->GetDateTime();
-    String dateTime = rtc->DateTimeString(currentDateTime);
-    dateTime.replace(" ", "T");
-    url += dateTime;
-    delete(currentDateTime);
     url += "&airpressure=";
     url += Debugger::FloatToAscii(number, _sensors->GetAirPressure() / 100, 0);
-    url += "&groundmoisture=0";
     url += "&groundtemperature=";
     url += Debugger::FloatToAscii(number, _sensors->GetGroundTemperatureReading(), 2);
-    url += "&temperature=";
+    url += "&airtemperature=";
     url += Debugger::FloatToAscii(number, _sensors->GetAirTemperature(), 2);
     url += "&humidity=";
     url += Debugger::FloatToAscii(number, _sensors->GetHumidity(), 2);
     url += "&luminosity=";
     url += Debugger::FloatToAscii(number, _sensors->GetLuminosityReading(), 2);
     url += "&rainfall=";
-    url += Debugger::FloatToAscii(number, _sensors->GetRainfall(), 2);
-    url += "&ultravioletlight=";
-    url += Debugger::FloatToAscii(number, _sensors->GetUltravioletLightStrength(), 2);
-    url += "&winddirection=0";
+    url += Debugger::FloatToAscii(number, _pluviometerCountToday, 2);
+    url += "&winddirection=";
+    url += _sensors->GetWindDirectionAsString();
     url += "&windspeed=";
-    url += Debugger::FloatToAscii(number, _sensors->GetWindSpeed(), 2);
-    _udpDebug.println(url);
+    url += Debugger::FloatToAscii(number, (_lastFiveSecondWindSpeedCount * 1.492) / 5, 2);
     //
     //  Send the data to Phant (Sparkfun's data logging service).
     //
@@ -270,48 +258,6 @@
     {
         Debugger::DebugMessage("MQTT Failed: " + readingType);
     }
-}
-
-//
-//  Read the sensors and publish the data.
-//
-void ReadAndPublishSensorData()
-{
-    digitalWrite(PIN_ONBOARD_LED, HIGH);
-    Debugger::DebugMessage("Reading sensor data.");
-    _sensors->ReadAllSensors();
-    Debugger::LogLuminosityData(_sensors->GetLuminosityReading());
-    Debugger::LogTemperatureHumidityAndPressureData(_sensors->GetAirTemperature(), _sensors->GetHumidity(), _sensors->GetAirPressure());
-    //Debugger::LogUltravioletData(_sensors->GetUltravioletLightStrength());
-    Debugger::LogGroundTemperature(_sensors->GetGroundTemperatureReading());
-    Debugger::LogRainfall(0, _pluviometerCountToday * 0.2794);
-    //
-    String message;
-    char buffer[20];
-    message = "Wind speed pulse count: ";
-    message += itoa(_lastFiveSecondWindSpeedCount, buffer, 10);
-    Debugger::DebugMessage(message);
-    //
-    message = "Wind speed: ";
-    message += Debugger::FloatToAscii(buffer, (_lastFiveSecondWindSpeedCount * 1.492) / 5, 2);
-    message += "mph";
-    Debugger::DebugMessage(message);
-    //
-    //  Now post to the Internet.
-    //
-    //Debugger::DebugMessage("Posting to Internet.");
-    //MQTT_connect();
-    //CheckMQTTLoggingResult(_airPressureFeed.publish(_sensors->GetAirPressure() / 100), "Air Pressure");
-    //CheckMQTTLoggingResult(_airTemperatureFeed.publish(_sensors->GetAirTemperature()), "Air Temperature");
-    //CheckMQTTLoggingResult(_daylightFeed.publish(_sensors->GetLuminosityReading()), "Daylight");
-    //CheckMQTTLoggingResult(_groundTemperatureFeed.publish(_sensors->GetGroundTemperatureReading()), "Ground Temperature");
-    //CheckMQTTLoggingResult(_humidityFeed.publish(_sensors->GetHumidity()), "Humidity");
-    //CheckMQTTLoggingResult(_rainFallFeed.publish(_sensors->GetTotalRainfallToday()), "Rainfall");
-    //CheckMQTTLoggingResult(_uvLightFeed.publish(_sensors->GetUltravioletLightStrength()), "Ultraviolet Light");
-    //CheckMQTTLoggingResult(_windSpeedFeed.publish(_sensors->GetWindSpeed()), "Wind Speed");
-    //CheckMQTTLoggingResult(_windDirectionFeed.publish(_sensors->GetWindDirectionAsString()), "Wind Direction");
-    //Debugger::DebugMessage("Posting complete'");
-    digitalWrite(PIN_ONBOARD_LED, LOW);
 }

 //
@@ -349,6 +295,10 @@
         Debugger::DebugMessage("Setting RTC to: " + rtc->DateTimeString(dateTime));
         delay(1000);
     }
+    else
+    {
+        Debugger::DebugMessage("NTP retry count exceeded.");
+    }
     ntp->stop();
 }

@@ -378,6 +328,50 @@
     delete(dateTime);
 }

+void ReadAndPublishData()
+{
+    char _buffer[20];
+    String _message;
+
+    digitalWrite(PIN_ONBOARD_LED, HIGH);
+    _message = "Reading sensor data (";
+    _message += itoa(_readingNumber, _buffer, 10);
+    _message += ")";
+    Debugger::DebugMessage(_message);
+    _sensors->ReadAllSensors();
+    Debugger::LogLuminosityData(_sensors->GetLuminosityReading());
+    Debugger::LogTemperatureHumidityAndPressureData(_sensors->GetAirTemperature(), _sensors->GetHumidity(), _sensors->GetAirPressure());
+    Debugger::LogGroundTemperature(_sensors->GetGroundTemperatureReading());
+    //Debugger::LogUltravioletData(_sensors->GetUltravioletLightStrength());
+    Debugger::LogRainfall(0, _pluviometerCountToday * 0.2794);
+    //
+    _message = "Wind speed pulse count: ";
+    _message += itoa(_lastFiveSecondWindSpeedCount, _buffer, 10);
+    Debugger::DebugMessage(_message);
+    //
+    _message = "Wind speed: ";
+    _message += Debugger::FloatToAscii(_buffer, (_lastFiveSecondWindSpeedCount * 1.492) / 5, 2);
+    _message += "mph";
+    Debugger::DebugMessage(_message);
+    //
+    //  Now post to the Internet.
+    //
+    Debugger::DebugMessage("Posting to Internet.");
+    PostDataToPhant();
+    //MQTT_connect();
+    //CheckMQTTLoggingResult(_airPressureFeed.publish(_sensors->GetAirPressure() / 100), "Air Pressure");
+    //CheckMQTTLoggingResult(_airTemperatureFeed.publish(_sensors->GetAirTemperature()), "Air Temperature");
+    //CheckMQTTLoggingResult(_daylightFeed.publish(_sensors->GetLuminosityReading()), "Daylight");
+    //CheckMQTTLoggingResult(_groundTemperatureFeed.publish(_sensors->GetGroundTemperatureReading()), "Ground Temperature");
+    //CheckMQTTLoggingResult(_humidityFeed.publish(_sensors->GetHumidity()), "Humidity");
+    //CheckMQTTLoggingResult(_rainFallFeed.publish(_sensors->GetTotalRainfallToday()), "Rainfall");
+    //CheckMQTTLoggingResult(_windSpeedFeed.publish(_sensors->GetWindSpeed()), "Wind Speed");
+    //CheckMQTTLoggingResult(_windDirectionFeed.publish(_sensors->GetWindDirectionAsString()), "Wind Direction");
+    //CheckMQTTLoggingResult(_uvLightFeed.publish(_sensors->GetUltravioletLightStrength()), "Ultraviolet Light");
+    //Debugger::DebugMessage("Posting complete'");
+    digitalWrite(PIN_ONBOARD_LED, LOW);
+}
+
 //
 //  Handle the RTC interrupt.
 //
@@ -395,9 +389,9 @@
     //
     SetAlarm(rtc, 1);
     //
-    //  Now read the sensor data.
-    //
-    ReadAndPublishSensorData();
+    //  Indicate that the sensors should be read.
+    //
+    _readSensors = true;
 }

 //
@@ -450,13 +444,6 @@
         delay(1000);
     }
     Debugger::DebugMessage("WiFi connected, IP address: " + WiFi.localIP().toString());
-    //
-    //  Complete the network set up with the UDP port being used for debugging.
-    //
-    _udpDestination = WiFi.localIP();
-    _udpDestination[3] = 106;
-    _udpDebug.begin(UDP_DEBUG_PORT);
-    Debugger::DebugMessage("UDP debugging initialised.");
     //
     //  Get the current date and time from the RTC or a time server.
     //
@@ -481,7 +468,13 @@
 //
 void loop()
 {
+    if (_readSensors)
+    {
+        _readSensors = false;
+        _readingNumber++;
+        ReadAndPublishData();
+    }
     digitalWrite(PIN_ONBOARD_LED, _ledOutput ? 1 : 0);
     _ledOutput = !_ledOutput;
-    delay(SLEEP_PERIOD * 1000);
+    delay(1000);
 }


fix to master

fix to master

--- projects/YunHub/YunHub_MASTER/YunHub_MASTER.ino
+++ projects/YunHub/YunHub_MASTER/YunHub_MASTER.ino
@@ -84,7 +84,7 @@

   rf12_initialize(1, RF12_868MHZ, 0); // group id = 0 to receive from all groups

-  // Connect to MQTT server if not available
+  // Initial connect to MQTT server
   client.connect("arduinoYunClient");
   client.publish("ConnectMessage", "YunChen setup: connected.");
 }


Clean up Arduino test; remove Scout-specific includes. (#28)

--- test/ecc_test/ecc_test.ino
+++ test/ecc_test/ecc_test.ino
@@ -1,20 +1,3 @@
-#include <uECC.h>
-
-#include <j0g.h>
-#include <js0n.h>
-
-#include <lwm.h>
-
-#include <bitlash.h>
-
-#include <GS.h>
-
-#include <SPI.h>
-#include <Wire.h>
-#include <Scout.h>
-#include <Shell.h>
-
-
 #include <uECC.h>

 extern "C" {
@@ -56,8 +39,7 @@

 void setup()
 {
-  Scout.setup();
-
+  Serial.begin(115200);
   Serial.print("Testing ecc\n");

   uECC_set_rng(&RNG);


Implemented functionality to write to sector 0 on UID changeable MIFARE cards, using Chinese 'magic sequence' commands.

--- examples/ChangeUID/ChangeUID.ino
+++ examples/ChangeUID/ChangeUID.ino
@@ -10,8 +10,7 @@
  *
  * Released into the public domain.
  *
- * This sample shows how to setup a block on a MIFARE Classic PICC to be in "Value Block" mode.
- * In Value Block mode the operations Increment/Decrement/Restore and Transfer can be used.
+ * This sample shows how to set the UID on a UID changeable MIFARE card.
  *
  ----------------------------------------------------------------------------- empty_skull


Add SimpleGet.ino loop code

Add SimpleGet.ino loop code

--- examples/SimpleGet/SimpleGet.ino
+++ examples/SimpleGet/SimpleGet.ino
@@ -29,5 +29,23 @@
 }

 void loop() {
-    // TODO
+    // HTTP GET request
+    HttpClient httpClient = HttpClient(wifi, "www.example.com", 80);
+    httpClient.get("/");
+
+    // Check response status code
+    int status = httpClient.responseStatusCode();
+    if(status != 200) {
+        Serial.print("HTTP status code: ");
+        Serial.println(status);
+        delay(1000);
+        return;
+    }
+
+    // Print response body
+    String body = httpClient.responseBody();
+    Serial.println(body);
+
+    Serial.println("----------");
+    delay(5000);
 }


Delete box.ino

Delete box.ino

--- sensores-nodemcu/box-001.ino
+++ sensores-nodemcu/box-001.ino
@@ -1 +0,0 @@
-


arduino BitSmang

arduino BitSmang

--- Arduino/TurquoiseBicuspidBLE.ino
+++ Arduino/TurquoiseBicuspidBLE.ino
@@ -4,8 +4,6 @@

 // Global
 String BUFFER = "";
-char DELIMETER = ':';
-int LED = 11;
 int BUT = 2;
 int BUTT_STATE = 0;
 int TIME_START = 0;
@@ -14,46 +12,68 @@
 int BLUPIN = 5;

 // Defaults
-String TYPE = "blink";   // blink, pulse
-int LOOP = 3;            // 3, 2, 1
-int TIME = 100;          // 500, 250, 100, 50 (milliseconds)
-int REPT = 15000;        // 30000, 15000, 5000, 3000, -1 (milliseconds)
-int RED = 255;           // 0-255
-int GRE = 255;           // 0-255
-int BLU = 255;           // 0-255
-
-boolean REPEATING = false;
+/*
+Type:
+    Blink: 0
+    Pulse: 1
+    On: 2
+Number:
+    1: 0
+    2: 1
+    3: 2
+    5: 3
+Time:
+    50: 0
+    100: 1
+    250: 2
+    500: 3
+Repeat:
+    0: 0
+    5000: 1
+    15000: 2
+    30000: 3
+*/
+//00-00-00-00-00000000-00000000-00000000
+int TYPE = 0;
+int NUMB = 0;
+int TIME = 0;
+int PETE = 0;
+
+char API;
+char R;
+char G;
+char B;

 void setup()
 {
-   pinMode(BUT, INPUT);
-   pinMode(REDPIN, OUTPUT);
-   pinMode(GREPIN, OUTPUT);
-   pinMode(BLUPIN, OUTPUT);
-
-   Serial.begin(9600);
-   delay(500);
-   Serial.println("Type AT commands!");
-
-   // AC-BT v4 defaults to 9600.
-   btSerial.begin(9600);
-   //btSerial.write("AT+RENEW"); // Reset all settings.
-   delay(250);
-   btSerial.write("AT+ROLE0"); // Slave mode (0: Peripheral, 1: Central, default: 0)
-   delay(250);
-   btSerial.write("AT+MODE2"); // (0: Tranmission, 1: PIO+0, 2: Remote Control+0, default: 0)
-   delay(250);
-   btSerial.write("AT+IMME1"); // (0: work immediately, 1: wait for AT+ commands, wait for AT+START to resume work, default: 0) Don't enter transmission mode until told. ("AT+IMME0" is wait until "AT+START" to work. "AT+WORK1" is connect right away.)
-   delay(250);
-   btSerial.write("AT+BAUD0");
-   delay(250);
-   btSerial.write("AT+NAMETurquoiseB");
-   delay(250);
-   btSerial.write("AT+PASS123456");
-   delay(250);
-   btSerial.write("AT+START"); // Work immediately when AT+IMME1 is set.
-
-   TIME_START = millis();
+  pinMode(BUT, INPUT);
+  pinMode(REDPIN, OUTPUT);
+  pinMode(GREPIN, OUTPUT);
+  pinMode(BLUPIN, OUTPUT);
+
+  Serial.begin(9600);
+  delay(500);
+  Serial.println("Type AT commands!");
+
+  // AC-BT v4 defaults to 9600.
+  btSerial.begin(9600);
+  //btSerial.write("AT+RENEW"); // Reset all settings.
+  delay(250);
+  btSerial.write("AT+ROLE0"); // Slave mode (0: Peripheral, 1: Central, default: 0)
+  delay(250);
+  btSerial.write("AT+MODE2"); // (0: Tranmission, 1: PIO+0, 2: Remote Control+0, default: 0)
+  delay(250);
+  btSerial.write("AT+IMME1"); // (0: work immediately, 1: wait for AT+ commands, wait for AT+START to resume work, default: 0) Don't enter transmission mode until told. ("AT+IMME0" is wait until "AT+START" to work. "AT+WORK1" is connect right away.)
+  delay(250);
+  btSerial.write("AT+BAUD0");
+  delay(250);
+  btSerial.write("AT+NAMETurquoiseB");
+  delay(250);
+  btSerial.write("AT+PASS123456");
+  delay(250);
+  btSerial.write("AT+START"); // Work immediately when AT+IMME1 is set.
+
+  TIME_START = millis();
 }

 void loop()
@@ -62,91 +82,50 @@
   BUTT_STATE = digitalRead(BUT);
   if(BUTT_STATE == HIGH) {
     Serial.println("Clear");
-    REPEATING = false;
   }
   // read from bluetooth
+  int index = 0;
   if(btSerial.available()) {
     while(btSerial.available()) {
-      BUFFER += (char)btSerial.read();
+      if(index == 0) {
+        API = btSerial.read();
+      }
+      else if(index == 1) {
+        R = btSerial.read();
+      }
+      else if(index == 2) {
+        G = btSerial.read();
+      }
+      else if(index == 3) {
+        B = btSerial.read();
+      }
+      index++;
       delay(1);
     }
-
-    Serial.println("BUFFER: "+BUFFER);
-    String buff = "";
-    int index = 0;
-    for(int i=0; i<BUFFER.length(); i++) {
-      // copy buffer
-      buff += BUFFER[i];
-
-      // clear buffer
-      if(BUFFER[i] == ':') {
-        buff = "";
-      }
-
-      // get a value
-      if(BUFFER[i+1] == ':') {
-        if(index == 0) {
-          TYPE = buff;
-          index++;
-        }
-        else if(index == 1) {
-          LOOP = buff.toInt();
-          index++;
-        }
-        else if(index == 2) {
-          TIME = buff.toInt();
-          index++;
-        }
-        else if(index == 3) {
-          REPT = buff.toInt();
-          if(REPT > 0)
-          {
-            REPEATING = true;
-          }
-          else if(REPT == -1) {
-            REPEATING = false;
-          }
-          index++;
-        }
-        else if(index == 4) {
-          RED = HEXToRGB(buff[0], buff[1]);
-          GRE = HEXToRGB(buff[2], buff[3]);
-          BLU = HEXToRGB(buff[4], buff[5]);
-          index++;
-        }
-        buff = "";
-      }
-    }
-    BUFFER = "";
-    Serial.println(TYPE+":"+LOOP+":"+TIME+":"+REPT+":"+RED+":"+GRE+":"+BLU);
-
-    if(TYPE == "blink") {
-      blinkRGB(LOOP, TIME, RED, GRE, BLU);
-    }
-    else if(TYPE == "pulse") {
-      pulseRGB(LOOP, TIME, RED, GRE, BLU);
-    }
-    else if(TYPE == "clear") {
-      REPEATING = false;
-    }
-    else {
-      blinkRGB(LOOP, TIME, RED, GRE, BLU);
-    }
-  }
-
-  int time_end = millis();
-  int time_diff = time_end - TIME_START;
-  if(time_diff > REPT) {
-    TIME_START = millis();
-    if(REPEATING) {
-      Serial.println("repeat");
-      blinkRGB(LOOP, TIME, RED, GRE, BLU);
-    }
-  }
-
-  // AT commands
-  if(Serial.available()){
-    btSerial.write(Serial.read());
+    Serial.print("API:");
+    Serial.print(API, DEC);
+    Serial.print(", Binary:");
+    Serial.println(API, BIN);
+
+    Serial.print("R:");
+    Serial.print(R, DEC);
+    Serial.print(", Binary:");
+    Serial.println(R, BIN);
+
+    Serial.print("G:");
+    Serial.print(G, DEC);
+    Serial.print(", Binary:");
+    Serial.println(G, BIN);
+
+    Serial.print("B:");
+    Serial.print(B, DEC);
+    Serial.print(", Binary:");
+    Serial.println(B, BIN);
+
+    // AT commands
+    if(Serial.available()){
+      btSerial.write(Serial.read());
+    }
   }
 }


main code for arduino vehicle

main code for arduino vehicle

--- vehicle/arduino-code/bluetooth_test/bluetooth_test.ino
+++ vehicle/arduino-code/bluetooth_test/bluetooth_test.ino
@@ -7,29 +7,55 @@
   // set the data rate for the SoftwareSerial port
   mySerial.begin(9600);
   Serial.begin(9600);
-  pinMode(2, OUTPUT);
-  pinMode(3, OUTPUT);
+  pinMode(9, OUTPUT);
+  pinMode(10, OUTPUT);
+  pinMode(11, OUTPUT);
+  pinMode(12, OUTPUT);
 }

 void loop() // run over and over
 {
     //String Data = "";
     //Serial.print(mySerial.read());
-
-    while(mySerial.available()) {
-     character = mySerial.read();
-     //Data.concat(character);
-     mySerial.println(character);
-     Serial.println(character);
-     digitalWrite(2,1);
-     digitalWrite(3,1);
-     delay(1000);
+    if(mySerial.available()){
+      character = mySerial.read();
+      Serial.println(character);
+       switch(character) {
+         case 'a':
+         digitalWrite(9,0);
+         digitalWrite(10,1);
+         digitalWrite(11,0);
+         digitalWrite(12,1);
+         break;
+          case 'e':
+         digitalWrite(9,1);
+         digitalWrite(10,0);
+         digitalWrite(11,1);
+         digitalWrite(12,0);
+         break;
+          case 'd':
+         digitalWrite(9,0);
+         digitalWrite(10,1);
+         digitalWrite(11,1);
+         digitalWrite(12,0);
+         break;
+          case 'b':
+         digitalWrite(9,1);
+         digitalWrite(10,0);
+         digitalWrite(11,0);
+         digitalWrite(12,1);
+         break;
+         case 'c':
+         digitalWrite(9,0);
+         digitalWrite(10,0);
+         digitalWrite(11,0);
+         digitalWrite(12,0);
+         break;
+         default:
+         break;
+     }
+    }

-     //count++;
-    }
-    digitalWrite(2,0);
-     digitalWrite(3,0);
-    Serial.print("S\n");
-    mySerial.print("a\n");
-    delay(1000);
+     delay(500);
+
 }


finish name change

finish name change

--- RouterReset.ino
+++ RouterReset.ino
@@ -1,4 +1,4 @@
-/*** coffeeShopWifi: test if internet is working; if not, reset router
+/*** RouterReset: test if internet is working; if not, reset router
 ***/

 #include <SPI.h>


Bug: Corrected Left & Right I2S Channel numbering for PDM Mics

This also required swapping the left and right outputs.

--- examples/AIC_Shield/FunctionalTestForEarpieceAndShield/FunctionalTestForEarpieceAndShield.ino
+++ examples/AIC_Shield/FunctionalTestForEarpieceAndShield/FunctionalTestForEarpieceAndShield.ino
@@ -38,16 +38,17 @@
 AudioSDWriter_F32             audioSDWriter(audio_settings);  //this is stereo by default

 //Connect the front and rear mics (from each earpiece) to input mixers
-AudioConnection_F32           patchcord1(i2s_in, 3, inputMixerL, 0);  //Left-Front Mic
-AudioConnection_F32           patchcord2(i2s_in, 2, inputMixerL, 1);  //Left-Rear Mic
-AudioConnection_F32           patchcord3(i2s_in, 1, inputMixerR, 0);  //Right-Front Mic
-AudioConnection_F32           patchcord4(i2s_in, 0, inputMixerR, 1);  //Right-Rear Mic
+AudioConnection_F32           patchcord1(i2s_in, 1, inputMixerL, 0);  //Left-Front Mic
+AudioConnection_F32           patchcord2(i2s_in, 0, inputMixerL, 1);  //Left-Rear Mic
+AudioConnection_F32           patchcord3(i2s_in, 3, inputMixerR, 0);  //Right-Front Mic
+AudioConnection_F32           patchcord4(i2s_in, 2, inputMixerR, 1);  //Right-Rear Mic

 //Connect the input mixers to both the Tympan and Shield audio outputs
+//NOTE: The left and right RIC is correct, but the headphone jacks have the left and right swapped.
 AudioConnection_F32           patchcord11(inputMixerL, 0, i2s_out, 1); //Tympan AIC, left output
-AudioConnection_F32           patchcord12(inputMixerR, 0, i2s_out, 2); //Tympan AIC, right output
-AudioConnection_F32           patchcord13(inputMixerL, 0, i2s_out, 2); //Shield AIC, left output
-AudioConnection_F32           patchcord14(inputMixerR, 0, i2s_out, 3); //Shield AIC, right output
+AudioConnection_F32           patchcord12(inputMixerR, 0, i2s_out, 0); //Tympan AIC, right output
+AudioConnection_F32           patchcord13(inputMixerL, 0, i2s_out, 3); //Shield AIC, left output
+AudioConnection_F32           patchcord14(inputMixerR, 0, i2s_out, 2); //Shield AIC, right output

 //Connect the input mixer to the SD card
 AudioConnection_F32           patchcord21(inputMixerL, 0, audioSDWriter, 0);   //connect Raw audio to queue (to enable SD writing)
@@ -190,10 +191,10 @@
       break;
     case ALL_MICS:
       myTympan.print("All Mic Gain: ");
-      inputMixerL.gain(0,gainVal);  //first aic (left earpiece), left mic
-      inputMixerL.gain(1,gainVal);  //first aic (left earpiece), left mic
-      inputMixerR.gain(0,gainVal);  //first aic (left earpiece), left mic
-      inputMixerR.gain(1,gainVal);  //first aic (left earpiece), left mic
+      inputMixerL.gain(0,gainVal);  //Left-Front Mic
+      inputMixerL.gain(1,gainVal);  //Left-Rear Mic
+      inputMixerR.gain(0,gainVal);  //Right-Front Mic
+      inputMixerR.gain(1,gainVal);  //Right-Rear Mic
       break;
   }
   myTympan.println(gainVal);


Added print(msg) function for debugging. Also added, in articulateWheel, a case for when direction == None (meaning we don't turn). I'm not sure how the wheels knew to stop without this case before...may be source of another bug?

--- src/SabertoothDriverROS/SabertoothDriverROS.ino
+++ src/SabertoothDriverROS/SabertoothDriverROS.ino
@@ -105,8 +105,8 @@
 void newManualCommandCallback(const command2ros::ManualCommand& newManualCommand)
 {
   //TODO: Do we need to stop the robot at this point, Sherry and Matt H say no
-  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
-
+  print("start cb");
+
   //Set articulation target values
   wheelTarget.fl_articulation_angle = newManualCommand.fl_articulation_angle;
   wheelTarget.ml_articulation_angle = newManualCommand.ml_articulation_angle;
@@ -147,6 +147,12 @@
 }
 ros::Subscriber<command2ros::ManualCommand> commandSubscriber("ManualCommand", &newManualCommandCallback);

+// Print error message to "sabertooth_debugger" topic
+void print(char* errorMsg){
+  debugMsg.data = errorMsg;
+  pubDebug.publish(&debugMsg);
+}
+
 void setupWheelStatus() {
   wheelStatus.fl_articulation_angle = 0;
   wheelStatus.fr_articulation_angle = 180;
@@ -233,7 +239,6 @@

   direction = getArticulationDirection(REAR_RIGHT_DRIVE_MOTOR_ID, wheelStatus.rr_articulation_angle, wheelTarget.rr_articulation_angle); //RR
   articulateWheel(REAR_RIGHT_DRIVE_MOTOR_ID, direction);
-
 }

 /**
@@ -245,9 +250,6 @@

   int moveRange = (motorInMotion[motorID]) ? DELTA_STOP_RANGE : DELTA_START_RANGE;
   if (delta >= -moveRange && delta <= moveRange) {
-    char msg[] = "Determined direction: NONE...";
-    debugMsg.data = msg;
-    pubDebug.publish(&debugMsg);
     return ARTICULATION_DIRECTION_NONE;
   }

@@ -282,15 +284,11 @@
     }
   }

-
   //Now we compare the two distances and move in the diection that is fastest
   int counterClockwiseDistance = to;
   int clockwiseDistance = 360 - to;

   if(counterClockwiseDistance > clockwiseDistance){
-    char msg[] = "Determined direction: CLOCKWISE!";
-    debugMsg.data = msg;
-    pubDebug.publish(&debugMsg);
     return ARTICULATION_DIRECTION_CLOCKWISE;
   }
   else{
@@ -317,14 +315,10 @@
     driveCounterclockwise(articulationID, articulationSpeed);
     driveCounterclockwise(motorID, wheelSpeed);
   }
-  //wheelStatus.ml_articulation_angle = wheelTarget.ml_articulation_angle;
-  //wheelStatus.rl_articulation_angle = wheelTarget.rl_articulation_angle;
-  //wheelStatus.fl_articulation_angle = wheelTarget.fl_articulation_angle;
-  //wheelStatus.mr_articulation_angle = wheelTarget.mr_articulation_angle;
-  //wheelStatus.rr_articulation_angle = wheelTarget.rr_articulation_angle;
-  //wheelStatus.fr_articulation_angle = wheelTarget.rr_articulation_angle;
-
-
+  else if(direction == ARTICULATION_DIRECTION_NONE){
+    driveCounterclockwise(articulationID, 0);
+    driveCounterclockwise(motorID, 0);
+  }
 }

 //TODO: Rename to driveAllWheels
@@ -345,11 +339,11 @@
 void driveMotor(int motorID, int speed) {

   if (speed < 0) {
-    speed = speed * -50;
+    speed = speed * -1;
     driveClockwise(motorID, speed);
   }
   else {
-    speed = speed * 50;
+    speed = speed;
     driveCounterclockwise(motorID, speed);
   }

@@ -454,6 +448,16 @@
 */
 void updateArticulationValues()
 {
+  /*
+  // Code for command line testing purposes
+  wheelStatus.ml_articulation_angle = wheelTarget.ml_articulation_angle;
+  wheelStatus.rl_articulation_angle = wheelTarget.rl_articulation_angle;
+  wheelStatus.fl_articulation_angle = wheelTarget.fl_articulation_angle;
+  wheelStatus.mr_articulation_angle = (int)wheelTarget.mr_articulation_angle;
+  wheelStatus.rr_articulation_angle = (int)wheelTarget.rr_articulation_angle;
+  wheelStatus.fr_articulation_angle = (int)wheelTarget.fr_articulation_angle;
+  */
+
   int encoderPostition = EncoderFL::getPosition();
   if (encoderPostition < 0)
   {
@@ -496,8 +500,6 @@
   }

   wheelStatus.rr_articulation_angle = (int)((encoderPostition * 9L) / 10L);
-
-  pubwheelStatus.publish(&wheelStatus);
 }

 void unitTest(){
@@ -597,7 +599,6 @@
  *
  */
 void setup(){
-  pinMode(13, OUTPUT);
   // To start, no motor is moving.
   for(int i = 0; i < 12; ++i)
   {
@@ -620,7 +621,9 @@

   // Open communication with Saberteeth
-  Serial3.begin(9600);
+  // Serial3.begin(9600);
+
+  stopAllMotors(false);
   //unitTest();

@@ -646,17 +649,17 @@
   }

   if (currentStatus == ARTICULATING) {
-
+    print("needs to articulate: true");
     if (needsToArticulate() == true) {
       articulateAllWheels();
     }
     else {
+      print("needs to articulate: false");
       currentStatus = START_DRIVING;
     }
   }

   if (currentStatus == START_DRIVING) {
-
     //TODO: Check with MEs about possibility of losing correct articulation (by going over an obstacle or something)

     //Check if we need to articulate
@@ -667,8 +670,11 @@
     //   return;
     // }

+    print("current status: start_driving");
     //Set stop drive time
     driveStopTime = millis() + wheelTarget.drive_duration*1000;
+
+    print("after millis(), drive all motors");

     //Send drive start command
     driveAllMotors();
@@ -678,6 +684,7 @@

   if (currentStatus == IS_DRIVING) {
     if (millis() >= driveStopTime) {
+      print("over time limit: stop driving");
       stopAllMotors(false);
     }
   }


Minor changes

Minor changes

--- utils/emontxv3_firmware/raspimon_firmware/VoltageAndCurrent/VoltageAndCurrent.ino
+++ utils/emontxv3_firmware/raspimon_firmware/VoltageAndCurrent/VoltageAndCurrent.ino
@@ -1,13 +1,13 @@
 #define emonTxV3                                                                   // Tell emonLib this is the emonTx V3 - don't read Vcc assume Vcc = 3.3V as is always the case on emonTx V3 eliminates bandgap error and need for calibration http://harizanov.com/2013/09/thoughts-on-avr-adc-accuracy/
 #define RF69_COMPAT 1                                                              // Set to 1 if using RFM69CW or 0 is using RFM12B

-#include <JeeLib.h>                                                                      //https://github.com/jcw/jeelib - Tested with JeeLib 3/11/14
-ISR(WDT_vect) { Sleepy::watchdogEvent(); }                            // Attached JeeLib sleep function to Atmega328 watchdog -enables MCU to be put into sleep mode inbetween readings to reduce power consumption
+#include <JeeLib.h>                                                                //https://github.com/jcw/jeelib - Tested with JeeLib 3/11/14
+ISR(WDT_vect) { Sleepy::watchdogEvent(); }                                         // Attached JeeLib sleep function to Atmega328 watchdog -enables MCU to be put into sleep mode inbetween readings to reduce power consumption

-#include "EmonLib.h"                                                                    // Include EmonLib energy monitoring library https://github.com/openenergymonitor/EmonLib
+#include "EmonLib.h"                                                               // Include EmonLib energy monitoring library https://github.com/openenergymonitor/EmonLib
 EnergyMonitor ct1, ct2, ct3, ct4;

-#include <OneWire.h>                                                  //http://www.pjrc.com/teensy/td_libs_OneWire.html
+#include <OneWire.h>                                                               // http://www.pjrc.com/teensy/td_libs_OneWire.html

 // All CTs are considered as enabled
 const byte version = 10;
@@ -73,7 +73,8 @@
   if (ACAC)
   {
     Serial.println("ACAC found");
-    for (int i=0; i<10; i++)                                              // indicate AC has been detected by flashing LED 10 times
+    // indicate AC has been detected by flashing LED 10 times
+    for (int i=0; i<10; i++)
     {
       digitalWrite(LEDpin, HIGH); delay(200);
       digitalWrite(LEDpin, LOW); delay(300);
@@ -94,7 +95,7 @@
   ct3.voltage(0, Vcal3, phase_shift3);          // ADC pin, Calibration, phase_shift
   ct4.voltage(0, Vcal4, phase_shift4);          // ADC pin, Calibration, phase_shift

-  pinMode(LEDpin, OUTPUT);                                              // Setup indicator LED
+  pinMode(LEDpin, OUTPUT);                      // Setup indicator LED
   digitalWrite(LEDpin, HIGH);
   delay(200);
   digitalWrite(LEDpin, LOW);
@@ -127,7 +128,7 @@
   unsigned long sum = 0;
   for (int i=0; i<samples; i++) // 178 samples takes about 20ms
   {
-    int raw = (analogRead(0)-512);
+    int raw = (analogRead(pin)-512);
     sum += (unsigned long)raw * raw;
   }
   double rms = sqrt((double)sum / samples);


Update DMASpi_example1.ino

Update DMASpi_example1.ino

The example sketch now also demonstrates the use of the ActiveLowChipSelect class.

--- examples/DMASpi_example1/DMASpi_example1.ino
+++ examples/DMASpi_example1/DMASpi_example1.ino
@@ -1,24 +1,243 @@
-#include <ChipSelect.h>
+#include <WProgram.h>
+
+#include <SPI.h>
+
 #include <DmaSpi.h>

-// create a chip select object. This one uses pin 14.
-ActiveLowChipSelect<14> cs;
-
-void setup() {
+
+
+/** Hardware setup:
+ plain Teensy 3.1 with DOUT connected to DIN
+ nothing else
+**/
+
+/** buffers to send from and to receive to **/
+#define DMASIZE 100
+uint8_t src[DMASIZE];
+volatile uint8_t dest[DMASIZE];
+volatile uint8_t dest1[DMASIZE];
+
+/** Wait for and consume a keypress over USB **/
+void waitForKeyPress()
+{
+  Serial.println("\nPress a key to continue\n");
+  while(!Serial.available());
+  while(Serial.available())
+  {
+    Serial.read();
+  }
+}
+
+void dumpBuffer(const volatile uint8_t* buf, const char* prefix)
+{
+  Serial.print(prefix);
+  for (size_t i = 0; i < DMASIZE; i++)
+  {
+    Serial.printf("0x%02x ", buf[i]);
+  }
+  Serial.print('\n');
+}
+/** Compare the buffers and print the destination contents if there's a mismatch **/
+void compareBuffers(const uint8_t* src_, const uint8_t* dest_)
+{
+  int n = memcmp((const void*)src_, (const void*)dest_, DMASIZE);
+  if (n == 0)
+  {
+    Serial.println("src and dest match");
+  }
+  else
+  {
+    Serial.println("src and dest don't match");
+    dumpBuffer(src_, " src: " );
+    dumpBuffer(dest_, "dest: ");
+  }
+}
+
+void setSrc()
+{
+  for (size_t i = 0; i < DMASIZE; i++)
+  {
+    src[i] = i;
+  }
+}
+
+void clrDest(uint8_t* dest_)
+{
+  memset((void*)dest_, 0x00, DMASIZE);
+}
+
+void setup()
+{
+  waitForKeyPress();
+  Serial.println("Hi!");
+
+  /** Prepare source and destination **/
+  setSrc();
+  clrDest((uint8_t*)dest);
+  Serial.println("Buffers are prepared");Serial.flush();
+
+  /** set up SPI **/
+  SPISettings spiSettings;
+  SPI.begin();
+
+  // transmit 10 bytes and measure time to get a feel of how long that takes
+  SPI.beginTransaction(spiSettings);
+  elapsedMicros us;
+  for (size_t i = 0; i < DMASIZE; i++)
+  {
+    dest[i] = SPI.transfer(src[i]);
+  }
+  uint32_t t = us;
+  Serial.print("Time for non-DMA transfer: ");Serial.print(t);Serial.println("us");
+  SPI.endTransaction();
+  compareBuffers(src, (const uint8_t*)dest);
+
+  waitForKeyPress();
+
   DMASPI0.begin();
-  // create a transfer object
-  DmaSpi0::Transfer trx(nullptr, 100, nullptr, 0xFF, &cs);
-
-  // and register it. If the DMA SPI is idle, it will immediately start transmitting. Otherwise the transfer is added to a queue.
-  DMASPI0.registerTransfer(trx);
-
-  /** FREE CPU TIME YOU DIDN'T HAVE BEFORE! DO SOMETHING USEFUL! **/
-
-  // wait for the transfer to finish
+
+  DMASPI0.start();
+
+
+  Serial.println("Testing src -> dest, single transfer");
+  Serial.println("--------------------------------------------------");
+  DmaSpi0::Transfer trx(src, DMASIZE, dest);
+  clrDest((uint8_t*)dest);
+  DMASPI0.registerTransfer(trx);
+  while(trx.busy())
+  {
+  }
+  Serial.println("Finished DMA transfer");
+  compareBuffers(src, (const uint8_t*)dest);
+  Serial.println("==================================================\n\n");
+
+
+  Serial.println("Testing src -> discard, single transfer");
+  Serial.println("--------------------------------------------------");
+  trx = DmaSpi0::Transfer(src, DMASIZE, nullptr);
+  DMASPI0.registerTransfer(trx);
+  while(trx.busy())
+  {
+  }
+  Serial.println("Finished DMA transfer");
+  Serial.printf("last discarded value is 0x%02x\n", DMASPI0.devNull());
+  if (DMASPI0.devNull() == src[DMASIZE-1])
+  {
+    Serial.println("That appears to be correct");
+  }
+  else
+  {
+    Serial.printf("That appears to be wrong, it should be src[DMASIZE-1] which is 0x%02x\n", src[DMASIZE-1]);
+  }
+  Serial.println("==================================================\n\n");
+
+
+  Serial.println("Testing 0xFF dummy data -> dest, single transfer");
+  Serial.println("--------------------------------------------------");
+  trx = DmaSpi0::Transfer(nullptr, DMASIZE, dest, 0xFF);
+  memset((void*)src, 0xFF, DMASIZE); // we need this for checking the dest buffer
+  clrDest((uint8_t*)dest);
+  DMASPI0.registerTransfer(trx);
+  while(trx.busy())
+  {
+  }
+  Serial.println("Finished DMA transfer");
+  compareBuffers(src, (const uint8_t*)dest);
+  Serial.println("==================================================\n\n");
+
+
+  Serial.println("Testing multiple queued transfers");
+  Serial.println("--------------------------------------------------");
+  trx = DmaSpi0::Transfer(src, DMASIZE, dest, 0xFF);
+  setSrc();
+  clrDest((uint8_t*)dest);
+  clrDest((uint8_t*)dest1);
+  DmaSpi0::Transfer trx1(src, DMASIZE, dest1);
+  DMASPI0.registerTransfer(trx);
+  DMASPI0.registerTransfer(trx1);
   while(trx.busy());
-}
-
-void loop() {
-
-}
-
+  Serial.println("Finished DMA transfer");
+  while(trx1.busy());
+  Serial.println("Finished DMA transfer1");
+  compareBuffers(src, (const uint8_t*)dest);
+  compareBuffers(src, (const uint8_t*)dest1);
+  Serial.println("==================================================\n\n");
+
+
+  Serial.println("Testing pause and restart");
+  Serial.println("--------------------------------------------------");
+  clrDest((uint8_t*)dest);
+  clrDest((uint8_t*)dest1);
+  DMASPI0.registerTransfer(trx);
+  DMASPI0.registerTransfer(trx1);
+  DMASPI0.stop();
+  us = elapsedMicros();
+  while(!DMASPI0.stopped());
+  t = us;
+  while(trx.busy());
+  Serial.printf("Time until stopped: %lu us\n", t);
+  Serial.println("Finished DMA transfer");
+
+  if (DMASPI0.stopped())
+  {
+    Serial.println("DMA SPI appears to have stopped (this is good)\nrestarting");
+  }
+  else
+  {
+    Serial.println("DMA SPI does not report stopped state, but it should. (this is bad)");
+  }
+
+  DMASPI0.start();
+  while(trx1.busy());
+  Serial.println("Finished DMA transfer1");
+  compareBuffers(src, (const uint8_t*)dest);
+  compareBuffers(src, (const uint8_t*)dest1);
+  Serial.println("==================================================\n\n");
+
+
+  Serial.println("Testing src -> dest, with chip select object");
+  Serial.println("--------------------------------------------------");
+  ActiveLowChipSelect cs(0, SPISettings());
+  trx = DmaSpi0::Transfer(src, DMASIZE, dest, 0, &cs);
+  clrDest((uint8_t*)dest);
+  DMASPI0.registerTransfer(trx);
+  while(trx.busy())
+  {
+  }
+  Serial.println("Finished DMA transfer");
+  compareBuffers(src, (const uint8_t*)dest);
+  Serial.println("==================================================\n\n");
+
+
+  DmaSpi0::Transfer(src, DMASIZE, dest, 0, &cs);
+
+  if (DMASPI0.stopped())
+  {
+    Serial.println("DMA SPI stopped.");
+  }
+  else
+  {
+    Serial.println("DMA SPI is still running");
+  }
+  DMASPI0.stop();
+  if (DMASPI0.stopped())
+  {
+    Serial.println("DMA SPI stopped.");
+  }
+  else
+  {
+    Serial.println("DMA SPI is still running");
+  }
+
+  DMASPI0.end();
+  SPI.end();
+  pinMode(LED_BUILTIN, OUTPUT);
+}
+
+void loop()
+{
+  digitalWriteFast(LED_BUILTIN, true);
+  delay(500);
+  digitalWriteFast(LED_BUILTIN, false);
+  delay(500);
+}


extend arduino code

extend arduino code

--- Arduino/base_subscriber.ino
+++ Arduino/base_subscriber.ino
@@ -2,24 +2,38 @@
 #include <std_msgs/String.h>
 #include <Arduino.h>

+// **********
+// Variables
+// **********
+
 ros::NodeHandle nh;

+String messageData[3];

-void messageCb( const std_msgs::String& incoming_msg )
+// **********
+// ROS Messages
+// **********
+
+void messageCallback( const std_msgs::String& incoming_msg )
 {
     messageTTL = messageTTLInit;

     String data = incoming_msg.data;

-    int splitPos = data.indexOf('|');
+    int firstDelimiter = data.indexOf('|');
+    int secondDelimiter = data.lastIndexOf('|');

-    String leftData = data.substring(0, splitPos);
-    String rightData = data.substring(splitPos+1);
-
+    messageData[0] = data.substring(0, firstDelimiter);
+    messageData[1] = data.substring(firstDelimiter+1, secondDelimiter);
+    messageData[2] = data.substring(secondDelimiter+1);

 }

-ros::Subscriber<std_msgs::String> sub("to_arduino", &messageCb );
+ros::Subscriber<std_msgs::String> sub("to_arduino", &messageCallback );
+
+// **********
+// Setup
+// **********

 void setup()
 {
@@ -27,6 +41,10 @@
     nh.subscribe(sub);
 }

+// **********
+// Main Loop
+// **********
+
 void loop()
 {
     nh.spinOnce();


format bluetooth building control system fuzzy ir

--- Sketches/Bluetooth_Building_Control_System_fuzzy_IR/Bluetooth_Building_Control_System_fuzzy_IR.ino
+++ Sketches/Bluetooth_Building_Control_System_fuzzy_IR/Bluetooth_Building_Control_System_fuzzy_IR.ino
@@ -3,11 +3,17 @@
    temperature and humidity min and max limit checking
    by Dr. Aung Win Htut
 */
-#include<SoftwareSerial.h>
-#include <dht.h>
-#include <LiquidCrystal_I2C.h>
+#include<SoftwareSerial.h>  //for bluetooth
+#include <dht.h> //for DHT22
+
+
+#include <LiquidCrystal_I2C.h>
 //LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); //16*4
 LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); //20*4
+
+
+
+//pin configuration
 #define DHT22_PIN 4
 #define ldr A0
 #define MQ2 A1
@@ -15,23 +21,29 @@
 #define IRreceiver 2
 #define Buzzer 11
 #define led1 8
-#define led2 9
-#define led3 10
-#define maxgas 200
-#define mingas 20
-
-
+#define Relay1 10
+#define Relay2 9
+
+//Config values
+static int maxgas=200;
+static int mingas= 20;
+
+
+//flags and key parameters
 static int sgas = 0;
 static int stemperature = 3; // 1-very cold <10  2-cold <20  3-normal 20-30 4-hot 30-35 5-very hot >35
 static int shumidity = 3; //  1-very humid >60  2-humid 50-60 3-normal 40-50 4-dry 40-30 5-very dry <30
 static int tflag[5] = {0, 0, 0, 0, 0}; //flag =3 trigger
 static int hflag[5] = {0, 0, 0, 0, 0}; //flag =3 trigger
-
-
+static int status = 1;
+static int show = 0;
+
+//creating dht and blueooth objects
 dht DHT;
 SoftwareSerial BlueTooth(6, 7);       //TXD11  RXD12
-int status = 1;
-int show = 0;
+
+
+//creating structure for dht22
 struct
 {
   uint32_t total;
@@ -45,6 +57,7 @@
 } stat = { 0, 0, 0, 0, 0, 0, 0, 0};

+//Setting up for the very first time and once only
 void setup() {
   Serial.begin(9600);
   lcd.begin(20, 4);
@@ -53,20 +66,23 @@
   lcd.print("Weather Station");
   lcd.setCursor(0, 1);
   lcd.print("Welcome!");
+  //pinmode settings
   pinMode(led1, OUTPUT);
-  pinMode(led2, OUTPUT);
-  pinMode(led3, OUTPUT);
+  pinMode(Relay1, OUTPUT);
+  pinMode(Relay2, OUTPUT);
   pinMode(Buzzer, OUTPUT);

-  Serial.println("Goodnight moon!");
+  Serial.println("Hello,Green Hackers!"); //$
   BlueTooth.begin(9600);
   delay(500);
 }

-
+////////////////////////////////////////
+//Main Loop Start Here
 void loop() {
-  Serial.println("Loop Started");
-  funReadSensor();
+  Serial.println("Loop Started");//$
+
+  funReadSensor(); //calling fun to read sensor values
   delay(1000);

   if (BlueTooth.available()) {
@@ -75,32 +91,41 @@
   if (Serial.available() > 0)
   {
     int incomingByte = Serial.read();
-
   }
 }
-
+//Main Loop End Here
+//////////////////////////////////////////
+
+
+//////////////////////////////////////////////
+//Function for Reading Sensor value start here
 void funReadSensor()
 {
+  //sensor variables
   float temp = 0;
   float temp1;
   float light;
   float humidity;
   float gas;

-
-
+  //if you want to read lm35 temperature sensor
   //Serial.print("Reading Temp");
   //temp = analogRead(lm35);
   //temp = temp * 0.48828125;

+  //Reading Light value (10kOhm pull up)
   light = analogRead(ldr);
+
+  //Reading Gas vlue (10kOhm pull up)
   gas = analogRead(MQ2);
-
   if ((gas > mingas) && (gas < maxgas))
   {
     sgas = gas;
   }

+  //Read DHT sensor to measure Temperature and Humidity
+  //(10kOhm pull down)
+  //checking error!
   int chk = DHT.read22(DHT22_PIN);
   switch (chk)
   {
@@ -133,12 +158,11 @@
       Serial.println("Unknown error,\t");
       break;
   }
-
+  //if no error read humidity and temperature
   humidity = DHT.humidity;
   temp1 = DHT.temperature;

-
-
+  //sending to serial port //$
   Serial.print("Light");
   Serial.print(",\t");
   Serial.print(",\t");
@@ -146,9 +170,7 @@
   Serial.print(",\t");
   Serial.print("Temp(DHT22)");
   Serial.print(",\t");
-  Serial.println("Humidity");
-  //Serial.print(",\t");
-  //Serial.println("CO");
+  Serial.println("Humidity");
   Serial.print(light);
   Serial.print(",\t");
   Serial.print(",\t");
@@ -158,22 +180,19 @@
   Serial.print(temp1);
   Serial.print(",\t");
   Serial.print(",\t");
-  Serial.print(humidity);
-  //Serial.print(",\t");
-  //Serial.print(",\t");
-  //Serial.println(co);
+  Serial.print(humidity);
   Serial.println("");
-
+  //sending serial data end here
+
+  //copying measured variables
   int L = light;
   int T = temp;
   int T1 = temp1;
   int H = humidity;
   int G = sgas;
-
-
-
-
-
+
+  //Checking fuzzy levels for temperature
+  //Call funShowFuzzyResult onlyif the result actually change 3 times
   if (T1 < 10)
   {
     for (int i = 1; i < 5; i++)
@@ -184,7 +203,7 @@
     if (tflag[0] == 3)
     {
       stemperature = 1;
-      funShowResult();
+      funShowFuzzyResult();
     }
   }
   else if ((T1 >= 10) && (T1 < 20))
@@ -198,7 +217,7 @@
     if (tflag[1] == 3)
     {
       stemperature = 2;
-      funShowResult();
+      funShowFuzzyResult();
     }
   }
   else if ((T1 >= 20) && (T1 < 30))
@@ -212,7 +231,7 @@
     if (tflag[2] == 3)
     {
       stemperature = 3;
-      funShowResult();
+      funShowFuzzyResult();
     }
   }
   else if ((T1 >= 30) && (T1 <= 35))
@@ -226,7 +245,7 @@
     if (tflag[3] == 3)
     {
       stemperature = 4;
-      funShowResult();
+      funShowFuzzyResult();
     }
   }
   else if (T1 > 35)
@@ -240,11 +259,11 @@
     if (tflag[4] == 3)
     {
       stemperature = 5;
-      funShowResult();
-    }
-  }
-
-
+      funShowFuzzyResult();
+    }
+  }
+
+  //Checking fuzzy levels for humidity
   if (H > 60)
   {
     for (int i = 1; i < 5; i++)
@@ -255,7 +274,7 @@
     if (hflag[0] == 3)
     {
       shumidity = 1;
-      funShowResult();
+      funShowFuzzyResult();
     }
   }
   else if ((H >= 50) && (H < 60))
@@ -269,7 +288,7 @@
     if (hflag[1] == 3)
     {
       shumidity = 2;
-      funShowResult();
+      funShowFuzzyResult();
     }
   }
   else if ((H >= 40) && (H < 50))
@@ -283,7 +302,7 @@
     if (hflag[2] == 3)
     {
       shumidity = 3;
-      funShowResult();
+      funShowFuzzyResult();
     }
   }
   else if ((H >= 30) && (H <= 40))
@@ -297,7 +316,7 @@
     if (hflag[3] == 3)
     {
       shumidity = 4;
-      funShowResult();
+      funShowFuzzyResult();
     }
   }
   else if (H < 30)
@@ -311,25 +330,26 @@
     if (hflag[4] == 3)
     {
       shumidity = 5;
-      funShowResult();
-    }
-  }
-
-
-
+      funShowFuzzyResult();
+    }
+  }
+
+  //Checking light value whether dark and switch led on buzzer on
+  //Call funShowFuzzyResult onlyif the result actually change 3 times
   if (L > 400)
   {
     digitalWrite(led1, LOW);
   }
   else
   {
-    funBuzzerLed();
-  }
-
+    funBuzzerLed(); //calling buzzer on led on function
+  }
+
+  //Must change int to string to send by bluetooth and serial
   String l, t, t1, h, g;
   String st,sh;
-  //change integer to string
-  //to send by serial
+
+  //change integer to string
   l = String(L);
   t = String(T);
   t1 = String(T1);
@@ -338,6 +358,7 @@
   st = String(stemperature);
   sh = String(shumidity);

+  //Sending Serial again //$
   Serial.print(L);
   Serial.print(",\t");
   Serial.print(",\t");
@@ -348,11 +369,14 @@
   Serial.print(",\t");
   Serial.print(",\t");
   Serial.println(H);
-
+  Serial.println(t1 + '@' + h + '@' + l + '@' + g );
+  //Sending Serial End here
+
+  //Sending to bluetooth , separating by special @ char
   BlueTooth.println(t1 + '@' + t1 + '@' + h + '@' + l + '@' + g + '@' + st + '@' + sh );
-  //Serial.println(l + '@' + g + '@' + t1 + '@' + h );
-  Serial.println(t1 + '@' + h + '@' + l + '@' + g );
-
+  //Sending to bluetooth end here
+
+  //LCD print out start here
   lcd.clear();
   lcd.setCursor(0, 0);
   lcd.print("Temp ");
@@ -366,34 +390,39 @@
   lcd.setCursor(0, 3);
   lcd.print("GAS  ");
   lcd.print(g);
+  //LCD print out end here
 }
-
-
-
-void funShowResult()
+//Function for Reading Sensor value end here
+////////////////////////////////////////////////
+
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+//Showing FUZZY results on LCD
+void funShowFuzzyResult()
 {
   lcd.clear();
   switch (stemperature)
   {
     case 1: lcd.setCursor(0, 0); lcd.print("Temperature is Very Cold"); lcd.setCursor(0, 1); lcd.print("Fuzzy 1"); break;
-    case 2: lcd.setCursor(0, 0); lcd.print("Temperature is Cold"); lcd.setCursor(0, 1); lcd.print("Fuzzy 2"); break; break;
-    case 3: lcd.setCursor(0, 0); lcd.print("Temperature is Normal"); lcd.setCursor(0, 1); lcd.print("Fuzzy 3"); break; break;
-    case 4: lcd.setCursor(0, 0); lcd.print("Temperature is Hot"); lcd.setCursor(0, 1); lcd.print("Fuzzy 4"); break; break;
-    case 5: lcd.setCursor(0, 0); lcd.print("Temperature is Very Hot"); lcd.setCursor(0, 1); lcd.print("Fuzzy 5"); break; break;
+    case 2: lcd.setCursor(0, 0); lcd.print("Temperature is Cold");      lcd.setCursor(0, 1); lcd.print("Fuzzy 2"); break; break;
+    case 3: lcd.setCursor(0, 0); lcd.print("Temperature is Normal");    lcd.setCursor(0, 1); lcd.print("Fuzzy 3"); break; break;
+    case 4: lcd.setCursor(0, 0); lcd.print("Temperature is Hot");       lcd.setCursor(0, 1); lcd.print("Fuzzy 4"); break; break;
+    case 5: lcd.setCursor(0, 0); lcd.print("Temperature is Very Hot");  lcd.setCursor(0, 1); lcd.print("Fuzzy 5"); break; break;
   }
   switch (shumidity)
   {
-    case 1: lcd.setCursor(0, 2); lcd.print("Humidity is Very Humid"); lcd.setCursor(0, 3); lcd.print("Fuzzy 1"); break;
-    case 2: lcd.setCursor(0, 2); lcd.print("Humidity is Humid"); lcd.setCursor(0, 3); lcd.print("Fuzzy 2"); break; break;
-    case 3: lcd.setCursor(0, 2); lcd.print("Humidity is Normal"); lcd.setCursor(0, 3); lcd.print("Fuzzy 3"); break; break;
-    case 4: lcd.setCursor(0, 2); lcd.print("Humidity is Dry"); lcd.setCursor(0, 3); lcd.print("Fuzzy 4"); break; break;
-    case 5: lcd.setCursor(0, 2); lcd.print("Humidity is Very Dry"); lcd.setCursor(0, 3); lcd.print("Fuzzy 5"); break; break;
+    case 1: lcd.setCursor(0, 2); lcd.print("Humidity is Very Humid");   lcd.setCursor(0, 3); lcd.print("Fuzzy 1"); break;
+    case 2: lcd.setCursor(0, 2); lcd.print("Humidity is Humid");        lcd.setCursor(0, 3); lcd.print("Fuzzy 2"); break; break;
+    case 3: lcd.setCursor(0, 2); lcd.print("Humidity is Normal");       lcd.setCursor(0, 3); lcd.print("Fuzzy 3"); break; break;
+    case 4: lcd.setCursor(0, 2); lcd.print("Humidity is Dry");          lcd.setCursor(0, 3); lcd.print("Fuzzy 4"); break; break;
+    case 5: lcd.setCursor(0, 2); lcd.print("Humidity is Very Dry");     lcd.setCursor(0, 3); lcd.print("Fuzzy 5"); break; break;
   }
   funBuzzerLed();
   delay(5000);
-
 }
-
+//function End here
+//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+//function for buzzer on led on
 void funBuzzerLed()
 {
   digitalWrite(led1, HIGH);
@@ -402,4 +431,7 @@
   digitalWrite(Buzzer, LOW);
   delay(100);
 }
-
+//function end here
+
+
+


Basic one-way communiaction over Wifi implemented

--- Arduino/EspIoThunder/EspIoThunder.ino
+++ Arduino/EspIoThunder/EspIoThunder.ino
@@ -1,13 +1,120 @@
+#include <ESP8266WiFi.h>
+
+//how many clients should be able to telnet to this ESP8266
+#define MAX_SRV_CLIENTS 1
+#define PORT 8081
+
+const char* ssid     = "***************";
+const char* password = "***************";
+
+// how much serial data we expect before a newline
+const unsigned int MAX_INPUT = 1024;
+
+WiFiServer server(PORT);
+WiFiClient serverClients[MAX_SRV_CLIENTS];
+
 void setup() {
-  pinMode(0, OUTPUT);  // Red led on the ESP, might be used later for debugging
+  // Initializing the used pins
+  // pinMode(0, OUTPUT);  // Red led on the ESP, might be used later for debugging
   pinMode(12, OUTPUT);
   pinMode(13, OUTPUT);
   pinMode(14, OUTPUT);
   pinMode(15, OUTPUT);
+
+  Serial.begin(115200);
+  delay(100);
+
+  // We start by connecting to a WiFi network
+  Serial.println("===========================");
+  Serial.print("Connecting to ");
+  Serial.println(ssid);
+
+  WiFi.begin(ssid, password);
+
+  while (WiFi.status() != WL_CONNECTED) {
+    delay(500);
+    Serial.print(".");
+  }
+
+  Serial.println("");
+  Serial.println("WiFi connected");
+  Serial.println("IP address: ");
+  Serial.println(WiFi.localIP());
+
+  // Start the server
+  server.begin();
+  server.setNoDelay(true);
+
+  Serial.print("Ready! Use 'telnet ");
+  Serial.print(WiFi.localIP()); Serial.print(" "); Serial.print(PORT);
+  Serial.println("' to connect");
 }

 void loop() {
-  digitalWrite(0, HIGH);
+  uint8_t i;
+  //check if there are any new clients
+  if (server.hasClient()) {
+    for (i = 0; i < MAX_SRV_CLIENTS; i++) {
+      //find free/disconnected spot
+      if (!serverClients[i] || !serverClients[i].connected()) {
+        if (serverClients[i]) serverClients[i].stop();
+        serverClients[i] = server.available();
+        Serial.print("New client: "); Serial.print(i);
+        continue;
+      }
+    }
+    //no free/disconnected spot so reject
+    WiFiClient serverClient = server.available();
+    serverClient.stop();
+  }
+
+  //check clients for data
+  for (i = 0; i < MAX_SRV_CLIENTS; i++) {
+    if (serverClients[i] && serverClients[i].connected()) {
+      if (serverClients[i].available()) {
+        //get data from the telnet client and push it to the UART
+        while (serverClients[i].available()) {
+          processIncomingByte (serverClients[i].read ());
+        }
+      }
+    }
+  }
+}
+
+void processIncomingByte (const byte inByte)
+{
+  static char input_line [MAX_INPUT];
+  static unsigned int input_pos = 0;
+
+  switch (inByte)
+  {
+    case '\n':   // end of text
+      input_line [input_pos] = 0;  // terminating null byte
+
+      // terminator reached! process input_line here ...
+      process_data (input_line);
+
+      // reset buffer for next time
+      input_pos = 0;
+      break;
+    case '\r':   // discard carriage return
+      break;
+    default:
+      // keep adding if not full ... allow for terminating null byte
+      if (input_pos < (MAX_INPUT - 1))
+        input_line [input_pos++] = inByte;
+      break;
+  }
+}
+
+// here to process incoming serial data after a terminator received
+void process_data (const char * data)
+{
+  Serial.println (data);
+  blink();
+}
+
+void blink() {
   digitalWrite(12, HIGH);
   delay(50);
   digitalWrite(12, LOW);
@@ -15,7 +122,6 @@
   digitalWrite(13, HIGH);
   delay(50);
   digitalWrite(13, LOW);
-  digitalWrite(0, LOW);
   delay(50);
   digitalWrite(14, HIGH);
   delay(50);
@@ -26,3 +132,4 @@
   digitalWrite(15, LOW);
   delay(50);
 }
+


avoid INPUT_PULLUP for ATtiny

avoid INPUT_PULLUP for ATtiny

--- examples/DIJN/test2/test2.ino
+++ examples/DIJN/test2/test2.ino
@@ -11,7 +11,8 @@
   rf12_initialize(1, RF12_868MHZ, 100);

   // need to enable the pull-up to get a voltage drop over the LDR
-  pinMode(14+LDR, INPUT_PULLUP);
+  pinMode(14+LDR, INPUT);
+  digitalWrite(14+LDR, 1); // pull-up
 }

 void loop () {