update

update

--- mwsSIMDUINO/mwsSIMDUINO.ino
+++ mwsSIMDUINO/mwsSIMDUINO.ino
@@ -1,19 +1,21 @@
 //DEBUG
-#include <MemoryFree.h>
-
+//#include <MemoryFree.h>
 #include <Wire.h> //I2C needed for sensors
+//https://github.com/sparkfun/SparkFun_MPL3115A2_Breakout_Arduino_Library
 #include "MPL3115A2.h" //Pressure sensor
+//https://github.com/sparkfun/SparkFun_HTU21D_Breakout_Arduino_Library
 #include "HTU21D.h" //Humidity sensor
 #include <SoftwareSerial.h> //Needed for GPS
+//http://arduiniana.org/libraries/tinygpsplus/
 #include <TinyGPS++.h> //GPS parsing

-#define DEBUG true
-
-TinyGPSPlus gps;
+
+#define DEBUG false

 //For SIMDUINO GPS/GSM from Simduino
 static const int RXPin = 7, TXPin = 8; //GPS is attached to pin 7(TX from GPS) and pin 8(RX into GPS)
-SoftwareSerial ss(RXPin, TXPin);
+SoftwareSerial ss(RXPin, TXPin);
+//HW serial is RXPin=1 TXPin=0 (to check order) can high baud rate.

 MPL3115A2 myPressure; //Create an instance of the pressure sensor
 HTU21D myHumidity; //Create an instance of the humidity sensor
@@ -79,12 +81,13 @@
 float light_lvl = 455; //[analog value from 0 to 1023]
 //Variables used for GPS
 //unsigned long age;
-//int year;
-//byte month, day, hour, minute, second, hundredths;
+int gpsyear = 2000;
+int gpsmonth, gpsday, gpshour, gpsminute, gpssecond, gpshundredths;
+int gpslng, gpslat, gpsalt, gpssat;

 //Calibrate rain bucket here
 //Rectangle raingauge from Sparkfun.com/MISOL weather sensors
-float rain_bucket_mm = 0.011*25.4;//Each dump is 0.011" of water
+float rain_bucket_mm = 0.011 * 25.4; //Each dump is 0.011" of water
 //DAVISNET Rain Collector 2
 //float rain_bucket_mm = 0.01*25.4;//Each dump is 0.01" of water

@@ -93,7 +96,7 @@

 //for loop
 int i;
-int hourReport=0;
+int hourReport = 0;
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

 //Interrupt routines (these are called by the hardware interrupts, not by the main code)
@@ -105,9 +108,9 @@
   raintime = millis(); // grab current time
   raininterval = raintime - rainlast; // calculate interval between this and last event

-    if (raininterval > 100) // ignore switch-bounce glitches less than 10mS after initial edge
-  {
-    dailyrainin += rain_bucket_mm;
+  if (raininterval > 100) // ignore switch-bounce glitches less than 10mS after initial edge
+  {
+    dailyrainin += rain_bucket_mm;
     rainHour[minutes] += rain_bucket_mm; //Increase this minute's amount of rain
     rainlast = raintime; // set up for next event
   }
@@ -133,28 +136,21 @@
   //Start software serial for GPS/GSM
   ss.begin(19200);  //Default serial port setting for the GPRS modem is 19200bps 8-N-1
   ss.print("\r");
-  delay(1000);                    //Wait for a second while the modem sends an "OK"
-  ss.print("AT+CMGF=1\r");    //Because we want to send the SMS in text mode
   delay(1000);
-
-  ss.print("AT+CSCA=\"+9477000003\"\r");  //Setting for the SMS Message center number,
-  delay(1000);                                  //uncomment only if required and replace with
-  //the message center number obtained from
-  //your GSM service provider.
-  //Note that when specifying a tring of characters
-  // " is entered as \"
-
-  ss.print("AT+CMGS=\"+94716494873\"\r");    //Start accepting the text for the message
-  //to be sent to the number specified.
-  //Replace this number with the target mobile number.
-  delay(1000);
-  ss.print("mws simduino setup\r");   //The text for the message
-  delay(1000);
-  ss.write(0x1A);  //Equivalent to sending Ctrl+Z
-  delay(1000);
-
-  ss.print("AT+CMGD=\"1,4\"\r");    //Try to delete all sms in cache
-  delay(1000);
+  Serial.println(F("SMS part"));
+  do
+  {
+    ss.print("AT+CMGF=1\r");
+    Serial.println(sendData("AT+CMGF=0", 1000, DEBUG));
+       //Because we want to send the SMS in text mode
+  } while((String)"OK"!=sendData("AT+CMGF=1", 1000, DEBUG));
+  //Serial.println(sendData("AT+CSCA=\"+9477000003\"", 1000, DEBUG));  //Setting for the SMS Message center number,
+  //Note that when specifying a String of characters " is entered as \"
+  Serial.println(sendData("AT+CMGS=\"+94774496950\"", 1000, DEBUG));    //Start accepting the text for the message
+  //Serial.println(sendData("AT+CMGS=\"+94716494873\"", 1000, DEBUG));    //Start accepting the text for the message
+  Serial.println(sendData("\"mws simduino setup\"", 1000, DEBUG));   //The text for the message
+  Serial.println(sendData("0x1A", 1000, DEBUG));  //Equivalent to sending Ctrl+Z
+  //Serial.println(sendData("AT+CMGD=\"1,4\"\r", 1000, DEBUG));    //Try to delete all sms in cache

   Serial.print(F("lon,lat,altitude,sats,date,GMTtime,winddir"));
   Serial.print(F(",windspeedms,windgustms,windgustdir,windspdms_avg2m,winddir_avg2m,windgustms_10m,windgustdir_10m"));
@@ -170,7 +166,7 @@
   myPressure.begin(); // Get sensor online
   myPressure.setModeBarometer(); // Measure pressure in Pascals from 20 to 110 kPa
   myPressure.setOversampleRate(7); // Set Oversample to the recommended 128
-  myPressure.enableEventFlags(); // Enable all three pressure and temp event flags
+  myPressure.enableEventFlags(); // Enable all three pressure and temp event flags

   //Configure the humidity sensor
   myHumidity.begin();
@@ -184,16 +180,16 @@

   // turn on interrupts
   interrupts();
-
+
   //GPS on
   getgps();
-  hourReport=gps.time.hour()-1;
-  minutes = gps.time.minute();
-  minutes_10m = gps.time.minute();
-  seconds = gps.time.second();
+  hourReport = gpshour - 1;
+  minutes = gpsminute;
+  minutes_10m = gpsminute;
+  seconds = gpssecond;
   lastSecond = millis();
   //DEBUG
-  Serial.println(freeMemory());
+  //Serial.println(freeMemory());
 }

 void loop()
@@ -203,8 +199,8 @@
   lastSecond = millis();

   //Take a speed and direction reading every second for 2 minute average
-  seconds_2m += loopMSecond/1000;
-  if(++seconds_2m > 119) seconds_2m = 0;
+  seconds_2m += loopMSecond / 1000;
+  if (++seconds_2m > 119) seconds_2m = 0;

   //Calc the wind speed and direction every second for 120 second to get 2 minute average
   float currentSpeed = get_wind_speed();
@@ -213,26 +209,26 @@
   winddiravg[seconds_2m] = currentDirection;

   //Check to see if this is a gust for the minute
-  if(currentSpeed > windgust_10m[minutes_10m])
+  if (currentSpeed > windgust_10m[minutes_10m])
   {
     windgust_10m[minutes_10m] = currentSpeed;
     windgustdirection_10m[minutes_10m] = currentDirection;
   }

   //Check to see if this is a gust for the day
-  if(currentSpeed > windgustms)
+  if (currentSpeed > windgustms)
   {
     windgustms = currentSpeed;
     windgustdir = currentDirection;
   }
-  seconds += loopMSecond/1000;
-  if(++seconds > 59) seconds = 0;
-  if(++minutes > 59) minutes = 0;
-  minutes += seconds/60;
-  minutes_10m += seconds/60;
-  if(++minutes_10m > 9){
+  seconds += loopMSecond / 1000;
+  if (++seconds > 59) seconds = 0;
+  if (++minutes > 59) minutes = 0;
+  minutes += seconds / 60;
+  minutes_10m += seconds / 60;
+  if (++minutes_10m > 9) {
     minutes_10m = 0;
-    for (i=0;i<10;i++) windgust_10m[i] = 0;
+    for (i = 0; i < 10; i++) windgust_10m[i] = 0;
   }
   rainHour[minutes] = 0; //Zero out this minute's rainfall amount
   windgust_10m[minutes_10m] = 0; //Zero out this minute's gust
@@ -240,80 +236,158 @@
   printWeather();
   //Wait 1 second, and gather GPS data
   delay(1000);
-  getgps();
+  getgps();
   //REPORTING
   //Check for a new hour passing
-  Serial.print(hourReport);
-  Serial.print(gps.time.hour());
-  Serial.print(gps.time.minute());
-  if((gps.time.minute()>=0)&&(gps.time.minute()<2)){
-    Serial.print("inside the reporting if 1");
+  //Serial.print(hourReport);
+  //Serial.print(gpshour);
+  //Serial.print(gpsminute);
+  if ((gpsminute >= 0) && (gpsminute < 2)) {
+    //Serial.print(F("inside the reporting if 1"));
     //Check that the actual hour is incremented from last report
-    if(hourReport<gps.time.hour()){
-      Serial.print("inside the reporting if 2");
+    if (hourReport < gpshour) {
+      //Serial.print(F("inside the reporting if 2"));
       //Report all readings hourly
       printWeather();
       //Turn off stat LED
       delay(1000);
-      hourReport=gps.time.hour();
+      hourReport = gpshour;
     }
   }
 }

 void getgps(void)
 {
+  String gpsdata = "";
+  String gpsdatatmp = "";
   //GPS baud rate is 9600 for coms
-  switchGPSonoff( "AT+UART=9600,8,1,0,0",1000,DEBUG);
-  switchGPSonoff( "AT+CGNSPWR=1",1000,DEBUG);
+  switchGPSonoff( "AT+UART=9600,8,1,0,0", 1000, DEBUG);
+  switchGPSonoff( "AT+CGNSPWR=1", 1000, DEBUG);
+  switchGPSonoff( "AT+CGNSSEQ=RMC", 1000, DEBUG);
   do
   {
-    sendData( "AT+CGNSSEQ=RMC",1000,DEBUG);
-  }
-  while(gps.date.year()<2015);
-  switchGPSonoff( "AT+CGNSPWR=0",1000,DEBUG);
+    gpsdata.concat(sendData( "AT+CGNSINF", 1000, DEBUG));
+    delay(1000);
+    gpsdatatmp.concat(gpsdata);
+    Serial.println(gpsdata);
+    //get YEAR
+    gpsdatatmp.remove(31);
+    gpsdatatmp.remove(0, 27);
+    gpsyear = gpsdatatmp.toInt();
+    gpsdatatmp = "";
+    gpsdatatmp.concat(gpsdata);
+    //get MONTH
+    gpsdatatmp.remove(33);
+    gpsdatatmp.remove(0, 31);
+    gpsmonth = gpsdatatmp.toInt() ;
+    gpsdatatmp = "";
+    gpsdatatmp.concat(gpsdata);
+    //get DAY
+    gpsdatatmp.remove(35);
+    gpsdatatmp.remove(0, 33);
+    gpsday = gpsdatatmp.toInt() ;
+    gpsdatatmp = "";
+    gpsdatatmp.concat(gpsdata);
+    //get HOUR
+    gpsdatatmp.remove(37);
+    gpsdatatmp.remove(0, 35);
+    gpshour = gpsdatatmp.toInt() ;
+    gpsdatatmp = "";
+    gpsdatatmp.concat(gpsdata);
+    //get MINUTE
+    gpsdatatmp.remove(39);
+    gpsdatatmp.remove(0, 37);
+    gpsminute = gpsdatatmp.toInt() ;
+    gpsdatatmp = "";
+    gpsdatatmp.concat(gpsdata);
+    //get SECOND
+    gpsdatatmp.remove(41);
+    gpsdatatmp.remove(0, 39);
+    gpssecond = gpsdatatmp.toInt() ;
+
+  }
+  while (gpsyear < 2015 && gpsmonth == 0 && gpsday == 0 && (gpshour == 0 || gpshour > 12));
+  do
+  {
+    gpsdata.concat(sendData( "AT+CGNSINF", 1000, DEBUG));
+    delay(1000);
+    gpsdatatmp.concat(gpsdata);
+    Serial.println(gpsdata);
+    //get LONG
+    gpsdatatmp.remove(31);
+    gpsdatatmp.remove(0, 27);
+    gpslng = gpsdatatmp.toInt();
+    gpsdatatmp = "";
+    gpsdatatmp.concat(gpsdata);
+    //get LAT
+    gpsdatatmp.remove(31);
+    gpsdatatmp.remove(0, 27);
+    gpslat = gpsdatatmp.toInt();
+    gpsdatatmp = "";
+    gpsdatatmp.concat(gpsdata);
+    //get ALT
+    gpsdatatmp.remove(31);
+    gpsdatatmp.remove(0, 27);
+    gpsalt = gpsdatatmp.toInt();
+    gpsdatatmp = "";
+    gpsdatatmp.concat(gpsdata);
+    //get SAT
+    gpsdatatmp.remove(31);
+    gpsdatatmp.remove(0, 27);
+    gpssat = gpsdatatmp.toInt();
+    gpsdatatmp = "";
+  }
+  while (gpslng <= 0.01 && gpslat <= 0.01 && gpsalt <= 0.01);
+  switchGPSonoff( "AT+CGNSPWR=0", 1000, DEBUG);
   //FGSM baud rate is 19200 max through software serial
-  switchGPSonoff( "AT+UART=19200,8,1,0,0",1000,DEBUG);
+  switchGPSonoff( "AT+UART=19200,8,1,0,0", 1000, DEBUG);
+  //FGSM baud rate is 115200 max through HW serial PINs 0-1)
+  //switchGPSonoff( "AT+UART=115200,8,1,0,0",1000,DEBUG);
+  Serial.println(gpslng);
+  Serial.println(gpslat);
+  Serial.println(gpsalt);
+  Serial.println(gpssat);
 }

 String switchGPSonoff(String command, const int timeout, boolean debug)
 {
-  String response = "";
-  ss.println(command);
-  long int time = millis();
-  while( (time+timeout) > millis())
-  {
-    while(ss.available())
-    {
-      char c = ss.read();
-      response+=c;
-    }
-  }
-  if(debug)
-  {
-    Serial.print(response);
-  }
+  //Serial.println("switchGPSonoff");
+  String response = "";
+  ss.println(command);
+  long int time = millis();
+  while ( (time + timeout) > millis())
+  {
+    while (ss.available())
+    {
+      char c = ss.read();
+      response += c;
+    }
+  }
+  if (debug)
+  {
+    Serial.println(response);
+  }
   return response;
 }

 String sendData(String command, const int timeout, boolean debug)
 {
-  String response = "";
-  ss.println(command);
-  long int time = millis();
-  while( (time+timeout) > millis())
-  {
-    while(ss.available())
-    {
-      gps.encode(ss.read());
-      char c = ss.read();
-      response+=c;
-    }
-  }
-  if(debug)
-  {
-    Serial.print(response);
-  }
+  String response = "";
+  ss.println(command);
+  long int time = millis();
+  while ( (time + timeout) > millis())
+  {
+    while (ss.available())
+    {
+      char c = ss.read();
+      response += c;
+    }
+  }
+  if (debug)
+  {
+    Serial.println(response);
+  }
   return response;
 }

@@ -334,14 +408,14 @@

   //Calc windspdms_avg2m
   float temp = 0;
-  for(int i = 0 ; i < 120 ; i++)
+  for (int i = 0 ; i < 120 ; i++)
     temp += windspdavg[i];
   temp /= 120.0;
   windspdms_avg2m = temp;

   //Calc winddir_avg2m
   temp = 0; //Can't use winddir_avg2m because it's an int
-  for(int i = 0 ; i < 120 ; i++)
+  for (int i = 0 ; i < 120 ; i++)
     temp += winddiravg[i];
   temp /= 120;
   winddir_avg2m = temp;
@@ -351,10 +425,10 @@
   //Find the largest windgust in the last 10 minutes
   windgustms_10m = 0;
   windgustdir_10m = 0;
-  //Step through the 10 minutes
-  for(int i = 0; i < 10 ; i++)
-  {
-    if(windgust_10m[i] > windgustms_10m)
+  //Step through the 10 minutes
+  for (int i = 0; i < 10 ; i++)
+  {
+    if (windgust_10m[i] > windgustms_10m)
     {
       windgustms_10m = windgust_10m[i];
       windgustdir_10m = windgustdirection_10m[i];
@@ -363,10 +437,10 @@

   //Calc humidity
   humidity = myHumidity.readHumidity();
-  if(myHumidity.readTemperature())
+  if (myHumidity.readTemperature())
   {
     tempf = myHumidity.readTemperature();
-  }
+  }
   else
   {
     //Calc tempf from pressure sensor
@@ -374,8 +448,8 @@
   }

   //Calculate amount of rainfall for the last 60 minutes
-  rainin = 0;
-  for(int i = 0 ; i < 60 ; i++)
+  rainin = 0;
+  for (int i = 0 ; i < 60 ; i++)
     rainin += rainHour[i];

   //Calc pressure
@@ -396,7 +470,7 @@
   float lightSensor = analogRead(LIGHT);
   operatingVoltage = 3.3 / operatingVoltage; //The reference voltage is 3.3V
   lightSensor = operatingVoltage * lightSensor;
-  return(lightSensor);
+  return (lightSensor);
 }

 //Returns the voltage of the raw pin based on the 3.3V rail
@@ -410,7 +484,7 @@
   operatingVoltage = 3.30 / operatingVoltage; //The reference voltage is 3.3V
   rawVoltage = operatingVoltage * rawVoltage; //Convert the 0 to 1023 int to actual voltage on BATT pin
   rawVoltage *= 4.90; //(3.9k+1k)/1k - multiple BATT voltage by the voltage divider to get actual system voltage
-  return(rawVoltage);
+  return (rawVoltage);
 }

 //Returns the instataneous wind speed
@@ -425,11 +499,11 @@
   windSpeed *= 1.492; //4 * 1.492 = 5.968MPH
   windSpeed *= 1.609344; //5.968MPH * 1.609344 = 9.604564992KMPH
   windSpeed /= 3.6; //9.604564992KMPH / 3.6 = 2.66793472MPS
-  return(windSpeed);
+  return (windSpeed);
 }

 //Read the wind direction sensor, return heading in degrees
-int get_wind_direction()
+int get_wind_direction()
 {
   unsigned int adc;
   adc = analogRead(WDIR); // get the current reading from the sensor
@@ -463,22 +537,22 @@
   calcWeather(); //Go calc all the various sensors

   Serial.println();
-  Serial.print(gps.location.lng(), 6);//[0]
-  Serial.print(",");
-  Serial.print(gps.location.lat(), 6);//[1]
-  Serial.print(",");
-  Serial.print(gps.altitude.meters());//[2]
-  Serial.print(",");
-  Serial.print(gps.satellites.value());//[3]
+  Serial.print(gpslng, 6);//[0]
+  Serial.print(",");
+  Serial.print(gpslat, 6);//[1]
+  Serial.print(",");
+  Serial.print(gpsalt);//[2]
+  Serial.print(",");
+  Serial.print(gpssat);//[3]

   char sz[32];
   Serial.print(",");
-  sprintf(sz, "%02d-%02d-%02d", gps.date.year(), gps.date.month(), gps.date.day());//[4]
+  sprintf(sz, "%02d-%02d-%02d", gpsyear, gpsmonth, gpsday);//[4]
   Serial.print(sz);

   Serial.print(",");
-  sprintf(sz, "%02d:%02d:%02d", gps.time.hour(), gps.time.minute(), gps.time.second());//[5]
-  Serial.print(sz);
+  sprintf(sz, "%02d:%02d:%02d", gpshour, gpsminute, gpssecond);//[5]
+  Serial.print(sz);

   Serial.print(",");
   Serial.print(get_wind_direction());//[6]
@@ -522,3 +596,5 @@

+
+


[FW] Use delayMicroseconds() for write delay.

Delay of 10us is intentional, since the function is only guaranteed
to work reliably with 3us and larger values, so we better stay safe.
A delay of 20us is still faster than the millisecond delay()!

--- firmware/MultiRomVC4000/MultiRomVC4000.ino
+++ firmware/MultiRomVC4000/MultiRomVC4000.ino
@@ -141,7 +141,7 @@
   digitalWrite(WESRAM, HIGH);
   shiftout(address, data);
   digitalWrite(WESRAM, LOW);
-  delay(1);
+  delayMicroseconds(10);
   digitalWrite(WESRAM, HIGH);
 }

@@ -154,6 +154,7 @@
   shiftOut(DATA, CLOCK, MSBFIRST, highbyte);
   shiftOut(DATA, CLOCK, MSBFIRST, lowbyte);
   digitalWrite(LATCH, HIGH);
+  delayMicroseconds(10);
   digitalWrite(LATCH, LOW);
 }


[FW] Allow for (future?) games with up to 8K of ROM/RAM.

--- firmware/MultiRomVC4000/MultiRomVC4000.ino
+++ firmware/MultiRomVC4000/MultiRomVC4000.ino
@@ -21,7 +21,7 @@
 #define DOWNKEY         2
 #define SELECTKEY       3
 #define MAX_ROMS       99
-#define MAX_ROM_SIZE 6144
+#define MAX_ROM_SIZE 8192
 #define GO_MSG          9  // 7-segment Message offset
 #define ER_MSG         11  // 7-segment Message offset


Unsupported.

Unsupported.

--- aquacontrol32.ino
+++ aquacontrol32.ino
@@ -24,7 +24,7 @@
 #if GIT_TAG
 #include "gitTagVersion.h"
 #else
-const char * sketchVersion = "ARDUINO IDE";
+const char * sketchVersion = "unsupported";
 #endif

 /**************************************************************************


Added states for moving item out

Added states for moving item out

--- src/FlappingMaching.ino
+++ src/FlappingMaching.ino
@@ -2,6 +2,7 @@
 #include <Me_InfraredReceiver.h>
 #include <Me_UltrasonicSensor.h>
 #include "MakeblockStepper.h"
+#include <AccelStepper.h>
 #include <Servo.h>
 #include <Me_ServoDriver.h>

@@ -15,7 +16,8 @@
 #define STATE_LOWER_TOP_FLAP 5
 #define STATE_RELEASE_FLAP 6
 #define STATE_RAISE_TOP_FLAP 7
-#define STATE_MOVE_ITEM_OUT 8
+#define STATE_MOVE_ITEM_OUT_PHASE_ONE 8
+#define STATE_MOVE_ITEM_OUT_PHASE_TWO 9

 int fsmState;

@@ -23,7 +25,10 @@
 Me_InfraredReceiver infraredReceiver; /* Note: As the code need to use interrupt 0, it works only when the Me - Infrared Receiver module is connected to the port 4(PORT_4) of Me - Base Shield. */
 Me_UltrasonicSensor ultraSensor( PORT_5 ); //Ultrasonic module can ONLY be connected to port 3, 4, 5, 6, 7, 8 of base shield. ultraSensor.distanceCm()
 MakeblockStepper moveItemStepper( 3200, baseShield, PORT_3 );
-Me_ServoDriver servoDriver(PORT_2); //can ONLY be PORT_1,PORT_2
+Me_ServoDriver servoDriver( PORT_2 ); //can ONLY be PORT_1,PORT_2
+
+int SERVO1_UP = 130;
+int SERVO1_DOWN = 115;

 void setup() {
   // Initailize FSM
@@ -38,14 +43,18 @@
   ultraSensor.begin();
   moveItemStepper.setSpeed( 12 );
   servoDriver.Servo1_begin();
-  servoDriver.writeServo1( 90 );
+  servoDriver.writeServo1( SERVO1_UP );
+  delay( 500 );
+  servoDriver.writeServo1( SERVO1_DOWN );
+  delay( 500 );
+  servoDriver.writeServo1( SERVO1_UP );
 }

 void loop() {
   int remoteKey = infraredReceiver.read();
   int usDistance = ultraSensor.distanceCm();
   int stopMicroSwitch = baseShield.readMePortOutsidePin( PORT_8 );
-
+
   switch ( fsmState ) {
     case STATE_OFF:
       Serial.println( "OFF" );
@@ -61,18 +70,20 @@
       Serial.println( "stopMicroSwitch = ");
       Serial.println( stopMicroSwitch );
       delay( 200 );
-      if ( usDistance < 6 && stopMicroSwitch == HIGH ) {
-        moveItemStepper.step( -100 );
+      if ( usDistance < 10 && stopMicroSwitch == HIGH ) {
+        moveItemStepper.step( 100 );
         fsmState = STATE_MOVE_ITEM_IN;
       }
       break;

     case STATE_MOVE_ITEM_IN:
       Serial.println( "MOVE ITEM IN" );
+      Serial.println( "usDistance = ");
+      Serial.println( usDistance );
       Serial.println( "stopMicroSwitch = ");
       Serial.println( stopMicroSwitch );
-      if ( usDistance < 6 && stopMicroSwitch == HIGH ) {
-        moveItemStepper.step( -100 );
+      if ( stopMicroSwitch == HIGH ) {
+        moveItemStepper.step( 100 );
         fsmState = STATE_MOVE_ITEM_IN;
       } else if ( stopMicroSwitch == LOW ) {
         fsmState = STATE_PULL_BACK_FLAP;
@@ -82,35 +93,45 @@
     case STATE_PULL_BACK_FLAP:
       Serial.println( "PULL BACK FLAP" );
       if ( stopMicroSwitch == LOW ) {
-        moveItemStepper.step( -300 );
+        moveItemStepper.step( 300 );
         fsmState = STATE_LOWER_TOP_FLAP;
       }
       break;

     case STATE_LOWER_TOP_FLAP:
       Serial.println( "LOWER TOP FLAP" );
-      servoDriver.writeServo1( 50 );
+      servoDriver.writeServo1( SERVO1_DOWN );
       delay( 1000 );
       fsmState = STATE_RELEASE_FLAP;
     break;

     case STATE_RELEASE_FLAP:
       Serial.println( "RELEASE FLAP" );
-      moveItemStepper.step( 300 );
+      moveItemStepper.step( -300 );
       fsmState = STATE_RAISE_TOP_FLAP;
       break;

     case STATE_RAISE_TOP_FLAP:
       Serial.println( "RAISE TOP FLAP" );
-      servoDriver.writeServo1( 90 );
-      fsmState = STATE_MOVE_ITEM_OUT;
+      servoDriver.writeServo1( SERVO1_UP );
+      fsmState = STATE_MOVE_ITEM_OUT_PHASE_ONE;
       break;

-    case STATE_MOVE_ITEM_OUT:
-      Serial.println( "MOVE ITEM OUT" );
-      if ( usDistance < 6 ) {
-        moveItemStepper.step( 600 );
-        fsmState = STATE_MOVE_ITEM_OUT;
+    case STATE_MOVE_ITEM_OUT_PHASE_ONE:
+      Serial.println( "MOVE ITEM OUT PHASE ONE" );
+      if ( usDistance > 10 ) {
+        moveItemStepper.step( -600 );
+        fsmState = STATE_MOVE_ITEM_OUT_PHASE_ONE;
+      } else {
+        fsmState = STATE_MOVE_ITEM_OUT_PHASE_TWO;
+      }
+      break;
+
+    case STATE_MOVE_ITEM_OUT_PHASE_TWO:
+      Serial.println( "MOVE ITEM OUT PHASE TWO" );
+      if ( usDistance < 10 ) {
+        moveItemStepper.step( -600 );
+        fsmState = STATE_MOVE_ITEM_OUT_PHASE_TWO;
       } else {
         fsmState = STATE_WAIT_FOR_ITEM;
       }


all functions OK except for auto-dimmer

all functions OK except for auto-dimmer

However, still having issues with both screens flickering/not working
under on "HIGH" state of any input.  I think this may be a hardware
issue.  Perhaps a lack of shielding or loose wires.

--- jacksclock12/jacksclock12.ino
+++ jacksclock12/jacksclock12.ino
@@ -29,16 +29,24 @@
 int brightSwitchIn =    12;      // Auto Brightness
 int dstSwitchIn =       13;      // Savings Time Switch

+const int numReadings = 10;
+
+int readings[numReadings];      // the readings from the analog input
+int index = 0;                  // the index of the current reading
+int total = 0;                  // the running total
+int average = 0;                // the average
+
+
 // Variables
 int dstState;                    // DST
 int reminderState;               // Switch (Reminder)
 int autoBrightState;             // Switch (Auto-Dimmer)
 int photoCellRead;               // Photo Cell
-int autoBrightAverage;           // Photo Cell
+int autoBrightAverage = 0;           // Photo Cell
 long previousMillis;             // For counting of xfade timer
 int counter;                     // Counts notes played
 int fadeAmount = 2;              // 420 LED
-int numReadings = 25;            // Smoothing function: # of Readings
+//int numReadings = 25;            // Smoothing function: # of Readings
 int neoBrightness = 100;         // Neopixel Shield
 boolean running = false;         // Colon On/Off

@@ -216,12 +224,8 @@
 {
   disp.drawColon(true);

-  //Serial.println(reminderState);                        // Turn back on when ready to test this function
   reminderState = digitalRead(reminderSwitchIn);        // Check Reminder Switch
-  if (reminderState == 1)
-  {
-    rainbowCycle(25);
-  }
+  if (reminderState == 1) rainbowCycle(25);
   if (reminderState == 0)
   {
     strip.setBrightness(0);
@@ -232,10 +236,11 @@

 void smooth()                                           // Cleans up photocell input
 {
-  int readings[numReadings];                            // the readings from the analog input
-  int index = 0;                                        // the index of the current reading
-  int total = 0;                                        // the running total
-  int average = 0;                                      // the average
+//  int index = 0;                                        // the index of the current reading
+//  int total = 0;                                        // the running total
+//  int average = 0;                                      // the average
+//  int readings[numReadings];                            // the readings from the analog input
+

   for (int thisReading = 0; thisReading < numReadings; thisReading++)
     readings[thisReading] = 0;
@@ -332,8 +337,8 @@
   int clockBrightness = map(clockKnob, 0, 1023, 2, 15);
   int lightKnob = analogRead(nightLightIn);
   int lightBrightness = map(lightKnob, 0, 1023, 50, 255);        // Backlight
-  int autoBright1 = map(autoBrightAverage, 1, 1023, 2, 15);
-  int autoBright2 = map(autoBrightAverage, 1, 1023, 50, 255);
+  int autoBright1 = map(autoBrightAverage, 390, 1000, 2, 15);
+  int autoBright2 = map(autoBrightAverage, 390, 1000, 50, 255);

   autoBrightState = digitalRead(brightSwitchIn);                 // Adjust Brightness (if Auto Switch On)
   if (autoBrightState == 1)


Used port-constant for web-server creation in NodeMCU-sketch

Co-authored-by: Leon Kiefer <049da16734eec46c49f70a85577cc911f406a0bb@gmx.de>

--- RGB.NET.Devices.WS281X/Sketches/RGB.NET_NodeMCU.ino
+++ RGB.NET.Devices.WS281X/Sketches/RGB.NET_NodeMCU.ino
@@ -35,7 +35,7 @@
 CRGB leds_channel_3[LEDS_CHANNEL_3];
 CRGB leds_channel_4[LEDS_CHANNEL_4];

-ESP8266WebServer server(80);
+ESP8266WebServer server(WEBSERVER_PORT);
 WiFiUDP Udp;

 bool isUDPEnabled;
@@ -292,4 +292,4 @@
     processUDP();
   }
 }
- +


Reapply change to return command status to webserver

--- software/firmware/LogoBotWifiScribbler/LogoBotWifiScribbler.ino
+++ software/firmware/LogoBotWifiScribbler/LogoBotWifiScribbler.ino
@@ -182,9 +182,10 @@
     char c = Serial.read();
     if (c == '\r' || c == '\n') {
       if (cmd != "") {
-        Serial.println("OK:" + cmd);
-        //doLogoCommand(cmd);
-        pushCmd(cmd);
+        if (pushCmd(cmd))
+          Serial.println("OK:" + cmd);
+        else
+          Serial.println("BUSY");
         cmd = "";
       }
     } else {


Made to work with new exiting board...

Made to work with new exiting board...

--- esp-fronius-monitor.ino
+++ esp-fronius-monitor.ino
@@ -131,7 +131,8 @@
     Serial.print("Boot Vers: "); Serial.println(system_get_boot_version());
     Serial.print("CPU: "); Serial.println(system_get_cpu_freq());

-    Wire.pins(0, 2); //on ESP-01.
+    //Wire.pins(2, 14); // esp12e
+    Wire.pins(0, 2); // esp-01
     Wire.begin();
     StartUp_OLED(); // Init Oled and fire up!
     Serial.println("OLED Init...");


add PiZero_owner_t and s_owner

add PiZero_owner_t and s_owner

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

 /*
  * v0.7 2016 Feb 20
+ *  - add [s_owner]
+ *  - add [Pizero_owner_t]
  *  - add proc_hello();
  *  - add debug_outputDebugString();
  * v0.6 2016 Feb 20
@@ -49,6 +51,14 @@
   SIZE_CMD = CMD_BYE + 1,
 } CMD_e;

+// Information of owner
+typedef struct tag_pizero_owner_t {
+  String serialNo;
+  String nickName;
+} Pizero_owner_t;
+
+Pizero_owner_t s_owner;
+
 //-------------------------------------------------------------------------
 // for debug

@@ -88,6 +98,8 @@

   debug_outputDebugString("proc_hello", "line89 > " + csvline);

+  s_owner.nickName = nickName;
+
 #if 1
   Serial.println("Your S/N:" + serNo);
   Serial.println("Your name:" + nickName);


Add rain reporting.

Add rain reporting.

--- arduino/monitor/monitor.ino
+++ arduino/monitor/monitor.ino
@@ -97,13 +97,14 @@

 void sendWeatherUpdate(Stream &out)
 {
-  String msg = "?";
-  msg += "ms=";
-  msg += millis();
-  msg += "wd=";
-  msg += getWindDirection();
-  msg += "&hi2=test2";
-  out.println(msg);
+  out.print("[");
+  out.print("ms=");
+  out.print(millis());
+  out.print("ri=");
+  out.print(getRainInches());
+  out.print("wd=");
+  out.print(getWindDirection());
+  out.println("]");
 }

 int getWindDirection()
@@ -122,6 +123,13 @@
   return (-1);
 }

+float getRainInches()
+{
+  float rainTemp = rainInches;
+  rainInches = 0;
+  return rainTemp;
+}
+
 int averageAnalogRead(int pinToRead)
 {
   byte numberOfReadings = 8;


Better motor speed coordination, values using '=N val' format

--- arduino_arm/arduino_arm.ino
+++ arduino_arm/arduino_arm.ino
@@ -2,10 +2,10 @@
 #include "utility/Adafruit_MS_PWMServoDriver.h"

 Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x62);
-Adafruit_DCMotor *M1 = AFMS.getMotor(4);
-Adafruit_DCMotor *M2 = AFMS.getMotor(3);
-Adafruit_DCMotor *M3 = AFMS.getMotor(2);
-Adafruit_DCMotor *M4 = AFMS.getMotor(1);
+Adafruit_DCMotor *M[4] = { AFMS.getMotor(4),
+                           AFMS.getMotor(3),
+                           AFMS.getMotor(2),
+                           AFMS.getMotor(1) };

 void setup() {
@@ -20,10 +20,8 @@
 // ----- state ------
 int speed = 100;

-int M1_on = 0;
-int M2_on = 0;
-int M3_on = 0;
-int M4_on = 0;
+int M_on[4] = { 0, 0, 0, 0 };
+char label[4][4] = { "MA1", "MA2", "MA3", "MA4" };

 unsigned long counter = 0;

@@ -31,87 +29,36 @@
   int command;
   if (millis() - counter > 10000) {
      counter = millis();
-     Serial.print   ("=A0 ");
-     Serial.println (analogRead(0));
-     Serial.print   ("=A1 ");
-     Serial.println (analogRead(1));
-     Serial.print   ("=A2 ");
-     Serial.println (analogRead(2));
+     announce ((char*)"A0", analogRead(0));
+     announce ((char*)"A1", analogRead(1));
+     announce ((char*)"A2", analogRead(2));
   }
   if (Serial.available()) {
      command = Serial.read();
      switch (command) {
        case '1':
-         M1_on = M1_on ? 0 : 1;
-         if (M1_on) {
-            M1->setSpeed(speed);
-            M1->run(FORWARD);
-         } else {
-            M1->run(RELEASE);
-         }
+         set_motor_speed (0, M_on[0] ? 0.0 : 1.0);
          break;
        case '2':
-         M2_on = M2_on ? 0 : 1;
-         if (M2_on) {
-            M2->setSpeed(speed);
-            M2->run(FORWARD);
-         } else {
-            M2->run(RELEASE);
-         }
+         set_motor_speed (1, M_on[1] ? 0.0 : 1.0);
          break;
        case '3':
-         M3_on = M3_on ? 0 : 1;
-         if (M3_on) {
-            M3->setSpeed(speed);
-            M3->run(FORWARD);
-         } else {
-            M3->run(RELEASE);
-         }
+         set_motor_speed (2, M_on[2] ? 0.0 : 1.0);
          break;
        case '4':
-         M4_on = M4_on ? 0 : 1;
-         if (M4_on) {
-            M4->setSpeed(speed);
-            M4->run(FORWARD);
-         } else {
-            M4->run(RELEASE);
-         }
+         set_motor_speed (3, M_on[3] ? 0.0 : 1.0);
          break;
        case 'q':
-         M1_on = M1_on ? 0 : 1;
-         if (M1_on) {
-            M1->setSpeed(speed);
-            M1->run(BACKWARD);
-         } else {
-            M1->run(RELEASE);
-         }
+         set_motor_speed (0, M_on[0] ? 0.0 : -1.0);
          break;
        case 'w':
-         M2_on = M2_on ? 0 : 1;
-         if (M2_on) {
-            M2->setSpeed(speed);
-            M2->run(BACKWARD);
-         } else {
-            M2->run(RELEASE);
-         }
+         set_motor_speed (1, M_on[1] ? 0.0 : -1.0);
          break;
        case 'e':
-         M3_on = M3_on ? 0 : 1;
-         if (M3_on) {
-            M3->setSpeed(speed);
-            M3->run(BACKWARD);
-         } else {
-            M3->run(RELEASE);
-         }
+         set_motor_speed (2, M_on[2] ? 0.0 : -1.0);
          break;
        case 'r':
-         M4_on = M4_on ? 0 : 1;
-         if (M4_on) {
-            M4->setSpeed(speed);
-            M4->run(BACKWARD);
-         } else {
-            M4->run(RELEASE);
-         }
+         set_motor_speed (3, M_on[3] ? 0.0 : -1.0);
          break;
        case 'x':
          do_stop();
@@ -122,14 +69,33 @@
 }

 void do_stop() {
-  M1_on = 0;
-  M1->run(RELEASE);
-  M2_on = 0;
-  M2->run(RELEASE);
-  M3_on = 0;
-  M3->run(RELEASE);
-  M4_on = 0;
-  M4->run(RELEASE);
+  set_motor_speed (0, 0.0);
+  set_motor_speed (1, 0.0);
+  set_motor_speed (2, 0.0);
+  set_motor_speed (3, 0.0);
+}
+
+void set_motor_speed (int motor, float mspeed) {
+  int new_speed = (int) (mspeed * (float) speed);
+  if (abs(new_speed) < 5) { new_speed = 0; }
+  if (new_speed == 0) { M[motor]->run(RELEASE); } // If the motor should be shut off, don't get confused.
+  if (new_speed == M_on[motor]) { return; }
+  announce (label[motor], new_speed);
+  M_on[motor] = new_speed;
+  if (new_speed < 0) {
+     M[motor]->setSpeed (-new_speed);
+     M[motor]->run (BACKWARD);
+  } else {
+     M[motor]->setSpeed (new_speed);
+     M[motor]->run (FORWARD);
+  }
+}
+
+void announce (char* name, int value) {
+  Serial.print ("=");
+  Serial.print (name);
+  Serial.print (" ");
+  Serial.println (value);
 }


Some changes.

Some changes.

--- Aufgabe4/Aufgabe4.ino
+++ Aufgabe4/Aufgabe4.ino
@@ -220,11 +220,11 @@
   flyROT->getMeasurement(&acc);
   Serial.print("1: ");Serial.print(acc[0]);Serial.print("2: ");Serial.print(acc[1]);Serial.print("3: ");Serial.println(acc[2]);

-  if (fabs(acc[0]) > 8) {
-    Serial.println("Stop");
-    move->stop();
-    step = 0;
-  }
+//  if (fabs(acc[0]) > 8) {
+//    Serial.println("Stop");
+//    move->stop();
+//    step = 0;
+//  }

   if (time - last > 500) {
     if (!move->do_work()) {


- remove gps-type="Point" in the MQTT message because such detailed info should be done on the backend, but not on the sensor node

--- Device_LinkItOne/LASS/LASS.ino
+++ Device_LinkItOne/LASS/LASS.ino
@@ -959,7 +959,6 @@
       msg_tmp.concat(DEVICE_TYPE);
       msg_tmp.concat(sensorUploadString);
       // v0.7.0, added for future integration with backend DB
-      msg_tmp.concat("|gps-type=\"Point\"");
       msg_tmp.concat("|gps-lat=");
       msg_tmp.concat(str_GPS_lat);
       msg_tmp.concat("|gps-lon=");


setting contrast needs to be set in extended instruction mode

--- Nokia_5110/Nokia_5110.ino
+++ Nokia_5110/Nokia_5110.ino
@@ -33,6 +33,7 @@
     if(contrast < 1 || contrast > 17)
         return;

+    extendedInstruction();
     execute(list[contrast - 1]);
 }

@@ -50,8 +51,10 @@
     digitalWrite(RST, LOW);
     digitalWrite(RST, HIGH);

+
+    setContrast(6);
+
     extendedInstruction();
-    setContrast(6);
     execute(0x04); // set temp coefficent
     execute(0x14); // LCD bias mode 1:40
     execute(0x20); // LCD basic commands


make client supports target led commands

--- client/client.ino
+++ client/client.ino
@@ -31,6 +31,7 @@
 int ledStatePin = 13;
 int ledSignalPin = 11;
 int controlledPin = 12;
+int ledTargetPin = 10;

 int RECV_PIN = 8;
 IRrecv irrecv(RECV_PIN);
@@ -156,6 +157,8 @@
         //the rest => turn off led
         if(atoi(p.id) == atoi(deviceId)) {
           digitalWrite(ledStatePin, HIGH);
+          //turn of target led if selected correctly
+          digitalWrite(ledTargetPin, LOW);
         } else {
           digitalWrite(ledStatePin, LOW);
         }
@@ -181,10 +184,13 @@
           statePending = true;
           eighty_twenty = true;
         }
-
-
+      } else if(strcmp(p.data, "TAR")) {
+        //turn on target light and return ack
+        sendXBeePacketFromRaw(&XBee, deviceId, "A", "SEL", "TAR");
+        digitalWrite(ledTargetPin, HIGH);

       }
+
     }
     else if (atoi(p.id) == atoi(deviceId)) {

@@ -193,6 +199,7 @@
         laptopBridging(p);
       } else if(strcmp(deviceId, deviceLamp) == 0) {
         lampClient(p);
+
       }
     }
   }


added comments as headers of the client files

--- client/client.ino
+++ client/client.ino
@@ -1,3 +1,19 @@
+/*
+  client.ino
+
+  This is a general framework to fit in any clients that can be remotely controlled with XBee. Each clients will add additional function of parsing certain commands, while the major application takes charge of external communication.
+
+  Examples of clients include, for now, lamps and laptops.
+
+  Lamps are simple, dump clients that only support on/off.
+  Laptops now are viewed as video players, thus supporting play/pause, volume adjustment, and brightness adjustment, etc.
+
+
+  Created 07/17/2013
+  By benzh@eecs.berkeley.edu
+
+*/
+
 #include <SoftwareSerial.h>
 #include <IRremote.h>
 #include <string.h>


Update jaaf.ino

Update jaaf.ino

Código más limpio
Cambios en el protocolo, ahora acepta cualquier número de parámetros
Los mensajes recibidos pasan de ser `#accion;pin;valor;` a `#accion,val1,val2,val3,...,valN!`
Los mensajes enviados pasan a ser `#accion,val1,val2,val3,...,valN!`

--- jaaf.ino
+++ jaaf.ino
@@ -1,124 +1,105 @@
-/*
- * JAAF es un micro-framework para comunicar placas Arduino
- * con computadoras mediante comunicación serial.
- */
-
+#include <string.h>
 #include <Servo.h>

-Servo servos[48];
-
-#define hash 0x23
-#define semicolon 0x3b
-#define tagLength 5
-
-int tagIndex = 0;
-
-char com[tagLength], val[tagLength], pin[tagLength];
-
-bool comComplete = false;
-bool valComplete = false;
-bool pinComplete = false;
+#define MAX_SERIAL_LEN 20 // Tamaño máximo del mensaje
+#define BAUDRATE 9600
+char j_inData[MAX_SERIAL_LEN];
+char **j_args;
+byte j_index = 0;
+Servo j_servos[48];

 void setup() {
-  // put your setup code here, to run once:
-  Serial.begin(9600);
-  Serial.println("READY");
+  Serial.begin(BAUDRATE);
 }

 void loop() {
-  // put your main code here, to run repeatedly:
-  if(Serial.available() > 0) {
-    delay(15);
-    readData();
-  }
-}
-
-void readData(){
-  char thisChar = Serial.read();
-
-  if(thisChar == hash){
-     while(comComplete == false && Serial.available() > 0){
-        char thisChar = Serial.read();
-        if(thisChar == semicolon){
-           comComplete = true;
-           break;
+  jaaf();
+}
+
+
+// Función principal de jaaf
+void jaaf(){
+  if(Serial.available() > 0)
+  {
+    delay(MAX_SERIAL_LEN);
+    char currChar = Serial.read();
+    if(currChar == '#')
+    {
+      while(Serial.available() > 0){
+        currChar = Serial.read();
+        if(currChar == '!')
+        {
+          // Terminamos de leer, ahora parseamos
+          jaaf_parse(j_inData);
+          jaaf_switch(j_args);
         }
-        else {
-          com[tagIndex] = thisChar;
-          tagIndex++;
+        else
+        {
+          // Comenzamos a guardar los datos
+          j_inData[j_index] = currChar;
+          j_index++;
+          j_inData[j_index] = '\0';
         }
-     }
-     tagIndex = 0;
-     while(pinComplete == false && Serial.available() > 0){
-        char thisChar = Serial.read();
-        if(thisChar == semicolon){
-          pinComplete = true;
-          break;
-        }
-        else {
-          pin[tagIndex] = thisChar;
-          tagIndex++;
-        }
-     }
-     tagIndex = 0;
-     while(valComplete == false && Serial.available() > 0){
-        char thisChar = Serial.read();
-        if(thisChar == semicolon){
-          valComplete = true;
-          break;
-        }
-        else {
-          val[tagIndex] = thisChar;
-          tagIndex++;
-        }
-     }
-     tagIndex = 0;
-
-     if(comComplete && valComplete && pinComplete){
-
-       if(strcmp(com,"pm")==0){    // pin mode
-         pm(pin, val);             // 0 = input; 1 = output
-       }
-
-       if(strcmp(com,"dr")==0){    // digital read
-         dr(pin);
-       }
-       if(strcmp(com,"dw")==0){    // digital write
-         dw(pin, val);             // 0 = low; 1=high;
-       }
-
-       if(strcmp(com,"ar")==0){    // analog read
-         ar(pin);
-       }
-       if(strcmp(com,"aw")==0){    // analog write
-         aw(pin, val);
-       }
-
-       if(strcmp(com,"as")==0){    // attach servo
-         as(pin);
-       }
-
-       if(strcmp(com,"ds")==0){    // detach servo
-         ds(pin);
-       }
-
-       if(strcmp(com,"st")==0){    // servo to position
-         st(pin, val);
-       }
-
-       // Serial.print("com: ");Serial.print(com);Serial.print("; pin: ");Serial.print(pin);Serial.print("; val: ");Serial.println(val);
-     }
-     for (int i=0;i<5;i++){
-       com[i] = 0x00;
-       pin[i] = 0x00;
-       val[i] = 0x00;
-     }
-
-     comComplete = false;
-     pinComplete = false;
-     valComplete = false;
-  }
-}
+      }
+      // Vaciamos el array dejandolo libre para la próxima iteración
+      for( int i = 0; i < j_index;  i++ ){
+        j_inData[i] = '\0';
+      }
+      j_index = 0;
+      j_args = {};
+    }
+  }
+}
+
+// Función para parsear el mensaje recibido
+void jaaf_parse(char *data){
+  char *buf;
+  int i = 0;
+  buf = strtok(data, ",");
+  while(buf != NULL){
+    j_args[++i] = buf;
+    buf = strtok(NULL, ",");
+  }
+}
+
+// Dado un array de parámetros, elegimos la acción correspondiente
+void jaaf_switch(char **args){
+  char *com = args[1];
+  char *pin = args[2];
+  char *val = args[3];
+  if(strcmp(com,"pm")==0){    // pin mode
+    pm(pin, val);             // 0 = input; 1 = output
+  }
+
+  if(strcmp(com,"dr")==0){    // digital read
+    dr(pin);
+  }
+  if(strcmp(com,"dw")==0){    // digital write
+    dw(pin, val);             // 0 = low; 1=high;
+  }
+
+  if(strcmp(com,"ar")==0){    // analog read
+    ar(pin);
+  }
+  if(strcmp(com,"aw")==0){    // analog write
+    aw(pin, val);
+  }
+
+  if(strcmp(com,"as")==0){    // attach servo
+    as(pin);
+  }
+
+  if(strcmp(com,"ds")==0){    // detach servo
+    ds(pin);
+  }
+
+  if(strcmp(com,"st")==0){    // servo to position
+    st(pin, val);
+  }
+}
+
+
+// Funciones generales de arduino

 // Pinmode
 void pm(char *pin, char *val){
@@ -136,7 +117,10 @@
 // Digital read
 void dr(char *pin){
   int p = atoi(pin);
-  Serial.println( digitalRead(p) );
+  int rval = digitalRead(p);
+  char v[12];
+  sprintf(v,"#dr,%i,%i!", p, rval);
+  Serial.println( v );
 }
 // Digital write
 void dw(char *pin, char *val){
@@ -157,10 +141,8 @@
   if(p == -1) return;
   pinMode(p, INPUT);
   int rval = analogRead(p);
-  char m[8];
   char v [12];
-  sprintf(m, "%03d", rval);
-  sprintf(v,"#ar;%s;%i;!",pin,rval);
+  sprintf(v,"#ar,%s,%i!",pin,rval);
   Serial.println( v );
 }
 // Analog write
@@ -179,19 +161,19 @@
 // Attach servo
 void as(char *pin){
   int p = atoi(pin);
-  servos[p].attach(p);
+  j_servos[p].attach(p);
 }
 // Detach servo
 void ds(char *pin){
   int p = atoi(pin);
-  servos[p].detach();
+  j_servos[p].detach();
 }
 // Servo to position
 void st(char *pin, char *val){
   int p = atoi(pin);
   int pos = atoi(val);
   if(pos >= 0 && pos <= 180){
-    servos[p].write(pos);
+    j_servos[p].write(pos);
   }
 }


update controller

update controller

--- document/arduino/motor_control/motor_control.ino
+++ document/arduino/motor_control/motor_control.ino
@@ -17,6 +17,7 @@

 // Debug param
 static const bool debug_mode = false; //for pySerial communication
+static const bool odom_pub = false; //publishing odom info (debug)

 // Pin define
 static const int out1_pin = 5;//Left
@@ -359,14 +360,19 @@
   }

   // report encoder info (deg/sec)
-  if(!debug_mode)
+  if(odom_pub)
   {
     char str[16];
     sprintf(str, "%d,%d\r\n", (int)(average_counter_pin1*(float)encoder_res*timer_hz)
                             , (int)(average_counter_pin2*(float)encoder_res*timer_hz) ); // deg/sec
     Serial.print(str);
   }
-  else//debug mode
+  else
+  {
+    Serial.print("0,0\r\n");
+  }
+
+  if(debug_mode)//debug mode
   {
     char str[96];
     sprintf(str, "%d,%d, %d,%d, %d,%d, %d,%d, %d,%d,%d,%d\r\n",


add #RUN to hello world to unlock screen after advanced demos

--- examples-ltc/3.ChibiScope/1_Hello/HelloWorld.ino
+++ examples-ltc/3.ChibiScope/1_Hello/HelloWorld.ino
@@ -11,13 +11,13 @@
 // Use the alligator clips to connect TXT, +5V and GND
 // between the respective holes on the ChibiChip and ChibiScope

-// IMPORTANT NOTE: If you are running the simple "Hello World"
-// demo after one of our more advanced text positioning demos,
-// you may need to power cycle the Chibi Scope by disconnecting
-// +5V and reconnecting it, to exit its freeze-frame animation mode.
-
 void setup() {
   Serial.begin(9600); // ChibiScope "listens" at a fixed speed of 9600 bits per second
+
+  // the following line is needed to restore the chibiscope mode into
+  // its power-on default in case you were previously running a different,
+  // more complicated demo that uses the control flow verbs to set text position
+  Serial.println("#RUN"); // put the scope into "run" mode, so println's immediately show up
 }

 void loop() {


Updated example

Updated example

--- examples/JsonParserExample/JsonParserExample.ino
+++ examples/JsonParserExample/JsonParserExample.ino
@@ -23,17 +23,17 @@
         return;
     }

-    char* sensor = root.getString("sensor");
+    char* sensor = root["sensor"];
     Serial.println(sensor);

-    long time = root.getLong("time");
+    long time = root["time"];
     Serial.println(time);

-    JsonArray coords = root.getArray("data");
+    JsonArray coords = root["data"];

-    for (int i = 0; i < coords.getLength(); i++)
+    for (int i = 0; i < coords.size(); i++)
     {
-        double value = coords.getDouble(i);
+        double value = coords[i];
         Serial.println(value, 6);
     }
 }


Cleanup.

Cleanup.

--- examples/RS485/CosaRS485slave/CosaRS485slave.ino
+++ examples/RS485/CosaRS485slave/CosaRS485slave.ino
@@ -85,6 +85,6 @@
   }
   DELAY(1000);

-  // Send reply
+  // Send the reply
   if (rs485.send(&msg, sizeof(msg)) < 0) return;
 }


Adding DDR registers to port/pin scanner.

--- examples/Tools/CosaPinScanner/CosaPinScanner.ino
+++ examples/Tools/CosaPinScanner/CosaPinScanner.ino
@@ -30,8 +30,82 @@
   uart.begin(9600);
   trace.begin(&uart, PSTR("CosaPinScanner: started"));
   Watchdog::begin();
+#if defined(DDRA)
+  trace << PSTR("DDRA     ");
+#endif
+#if defined(DDRB)
+  trace << PSTR("DDRB     ");
+#endif
+#if defined(DDRC)
+  trace << PSTR("DDRC     ");
+#endif
+#if defined(DDRD)
+  trace << PSTR("DDRD     ");
+#endif
+#if defined(DDRE)
+  trace << PSTR("DDRE     ");
+#endif
+#if defined(DDRF)
+  trace << PSTR("DDRF     ");
+#endif
+#if defined(DDRG)
+  trace << PSTR("DDRG     ");
+#endif
+#if defined(DDRH)
+  trace << PSTR("DDRH     ");
+#endif
+#if defined(DDRI)
+  trace << PSTR("DDRI     ");
+#endif
+#if defined(DDRJ)
+  trace << PSTR("DDRJ     ");
+#endif
+#if defined(DDRJ)
+  trace << PSTR("DDRK     ");
+#endif
+#if defined(DDRJ)
+  trace << PSTR("DDRL     ");
+#endif
+  trace << endl;
+#if defined(DDRA)
+  print(trace, DDRA);
+#endif
+#if defined(DDRB)
+  print(trace, DDRB);
+#endif
+#if defined(DDRC)
+  print(trace, DDRC);
+#endif
+#if defined(DDRD)
+  print(trace, DDRD);
+#endif
+#if defined(DDRE)
+  print(trace, DDRE);
+#endif
+#if defined(DDRF)
+  print(trace, DDRF);
+#endif
+#if defined(DDRG)
+  print(trace, DDRG);
+#endif
+#if defined(DDRH)
+  print(trace, DDRH);
+#endif
+#if defined(DDRI)
+  print(trace, DDRI);
+#endif
+#if defined(DDRJ)
+  print(trace, DDRJ);
+#endif
+#if defined(DDRK)
+  print(trace, DDRK);
+#endif
+#if defined(DDRL)
+  print(trace, DDRL);
+#endif
+  trace << endl;
 #if defined(PORTA)
-  trace << PSTR("PORTA     ");
+  trace << PSTR("PORTA    ");
 #endif
 #if defined(PORTB)
   trace << PSTR("PORTB    ");


Add DS2482 info to TWI scanner.

Add DS2482 info to TWI scanner.

--- examples/Tools/CosaTWIscanner/CosaTWIscanner.ino
+++ examples/Tools/CosaTWIscanner/CosaTWIscanner.ino
@@ -46,6 +46,7 @@
 const char at24cxx[]  __PROGMEM = "AT24CXX,Serial EEPROM";
 const char bmp085[]   __PROGMEM = "BMP085,Digital Pressure Sensor";
 const char ds1307[]   __PROGMEM = "DS1307,Real-Time Clock";
+const char ds2482[]   __PROGMEM = "DS2482, Single-Channel 1-Wire Master";
 const char ds3231[]   __PROGMEM = "DS3231,Extremely Accurated RTC/TCXO/Crystal";
 const char hmc5883l[] __PROGMEM = "HMC5883L,3-Axis Digital Compass";
 const char pcf8574[]  __PROGMEM = "PCF8574,Remote 8-bit I/O Expander";
@@ -72,6 +73,7 @@
   { 0x77, 0xff, 0,       0, bmp085   },
   { 0x70, 0xf8, 0,       0, pcf8574a },
   { 0xd0, 0xff, 0,       0, ds3231   },
+  { 0x18, 0xfe, 0,       0, ds2482   },
 };

 /**


Ripple effect from TWI refactoring.

Ripple effect from TWI refactoring.

--- examples/Tools/CosaTWIscanner/CosaTWIscanner.ino
+++ examples/Tools/CosaTWIscanner/CosaTWIscanner.ino
@@ -93,10 +93,10 @@
       if (regaddr != 0) {
 	// Read the register and compare with the expected value
 	uint8_t id = 0;
-	twi.begin(dev);
+	twi.acquire(dev);
 	twi.write(regaddr);
 	twi.read(&id, sizeof(id));
-	twi.end();
+	twi.release();
 	// Continue with the next table entry if no match
 	if (id != pgm_read_byte(&dev_tab[i].id)) continue;
       }
@@ -123,10 +123,10 @@
   for (uint8_t addr = 3; addr < 128; addr++) {
     // Attempt to read from the device
     TWI::Driver dev(addr);
-    twi.begin(&dev);
+    twi.acquire(&dev);
     uint8_t data;
     int count = twi.read(&data, sizeof(data));
-    twi.end();
+    twi.release();
     // Continue with the next address if there was no device
     if (count != sizeof(data)) continue;
     // Print information about the device


Remove jsonarduino from station

Remove jsonarduino from station

--- src/station/station.ino
+++ src/station/station.ino
@@ -12,14 +12,13 @@
 #define   SERVER_PORT
 #define   MAX_SIZE        512
 easyMesh  mesh;
-StaticJsonBuffer<512> jsonBuffer;
+DynamicJsonBuffer jsonBuffer;
 char msgString[MAX_SIZE];

 uint32_t nextHopId = 0; //0 se direttamente connesso al server, chipId del nextHop altrimenti
 #define DISCOVERY_REQ 0
 #define DATA 1
 int update = 0;
-
 int lastPId[30];
 uint32_t lastCId[30];
 int packetSendNumber=0;
@@ -88,7 +87,7 @@
 void setup() {
   mesh.init( MESH_PREFIX, MESH_PASSWORD, MESH_PORT );
   mesh.setReceiveCallback(&receivedCallback);
-  mesh.setDebugMsgTypes( ERROR | MESH_STATUS | CONNECTION | SYNC | COMMUNICATION | GENERAL | MSG_TYPES | REMOTE );
+  mesh.setDebugMsgTypes( ERROR); //| MESH_STATUS | CONNECTION | SYNC | COMMUNICATION | GENERAL | MSG_TYPES | REMOTE );
   //Controlla che il server sia raggiungibile
   mesh.setNewConnectionCallback( &newConnectionCallback );
   Serial.begin(115200);
@@ -101,11 +100,11 @@
   /*
    * TODO: Costruire un pacchetto esempio con id, from, msg e id che incrementa
    */
-  JsonObject& message = jsonBuffer.createObject();
-  message["from"]=mesh.getChipId();
-  message["id"]=++packetSendNumber;
-  String msg;
-  message.printTo(msg);
+  char msg[256];
+  sprintf(msg, "{\"from\": %d, \"id\": %d, \"temp\": 34.45}", mesh.getChipId(), ++packetSendNumber);
+
+  Serial.print("MESSAGGIO: ");
+  Serial.println(msg);
   /*if(Serial.available()){
     x = Serial.read();
     if( x == 'P' ){
@@ -116,8 +115,8 @@
     else
       mesh.sendBroadcast(msg);
   }*/
-  mesh.sendBroadcast(msg);
-
-  delay(5000);
+  String p(msg);
+  mesh.sendBroadcast(p);
+  delay(2000);
 }


Changed the funtion name which processes the incoming message from processTouch, to procWebMsg. Also added some code that initializes the output pins to output. Added some debug lines to see the content of the incoming message.

--- ServerSketch/ServerSketch.ino
+++ ServerSketch/ServerSketch.ino
@@ -62,11 +62,18 @@
 //-----------------------------------------------------------
 // Process recieved message from the webpage here....
 //------------------------------------------------------------
-void processTouch(char* in) {
-
+void procWebMsg(char* _in, size_t _len) {
+
+  /*
+  g_abD[i] = false;      digitalWrite(i, LOW);
+  g_aiP[i] = 0;        analogWrite(i, LOW);
+  */
+
   Serial.print("input: ");
-  Serial.println(in);
-  if(String(in) == "trigger"){
+  Serial.println(String(_in));
+    Serial.print("_len: ");
+  Serial.println(String(_len));
+  if(String(_in) == "trigger"){
     Serial.println("Trigger found");
     if(currentLED){
       digitalWrite(led, LOW);
@@ -225,7 +232,10 @@

   case LWS_CALLBACK_RECEIVE:

-    processTouch((char*) in);
+    // **********************************
+    // Process Data Receieved from the Website
+    // **********************************
+    procWebMsg((char*) in, len);

     break;

@@ -401,8 +411,13 @@
   system("/home/root/startAP");

   // Init Galileo HW
-  pinMode(led, OUTPUT);
-  digitalWrite(led, LOW);
+
+  // Enable all digital pins as outputs
+  for(int i=0; i<14; i++)
+  {
+    pinMode(i, OUTPUT);
+    digitalWrite(i, LOW);
+  }

   // Init pin state variables
   int i=0;
@@ -411,15 +426,11 @@
   for(i=0; i<TOTAL_NUM_Px; i++)
     g_aiP[i] = 0;

-
   _udpIn.begin(3333);
   _udpIn.listen();

-
-
   Serial.println("Starting WebSocket");
   initWebsocket();
-

 }


Balancer example: Turn the yellow LED off at the beginning.

--- examples/Balancer/Balancer.ino
+++ examples/Balancer/Balancer.ino
@@ -38,6 +38,7 @@
   // motors.flipLeftMotor(true);
   // motors.flipRightMotor(true);

+  ledYellow(0);
   ledRed(1);
   balanceSetup();
   ledRed(0);


fix compilation bug

fix compilation bug

--- examples/Web_Demo/Web_Demo.ino
+++ examples/Web_Demo/Web_Demo.ino
@@ -27,8 +27,7 @@

 // no-cost stream operator as described at
 // http://sundial.org/arduino/?page_id=119
-template<class T>
-inline Print &operator <<(Print &obj, T arg)
+template<class T> inline Print &operator <<(Print &obj, T arg)
 { obj.print(arg); return obj; }


Correct the angle initialization

Correct the angle initialization

--- script/core/arduino/robot.ino
+++ script/core/arduino/robot.ino
@@ -5,7 +5,7 @@

 void setup(){
   Serial.begin(9600);
-  analogWrite(angle);
+  analogWrite(angle, 90);
   digitalWrite(mAvant, LOW);
   digitalWrite(mArrier, LOW);
 }


Fix invalid test case.

Fix invalid test case.

--- examples/Sandbox/CosaIOBuffer/CosaIOBuffer.ino
+++ examples/Sandbox/CosaIOBuffer/CosaIOBuffer.ino
@@ -125,7 +125,7 @@
   ASSERT(strlen(s) == 3);
   ASSERT(!strcmp_P(s, PSTR("123")));

-  ASSERT(buffer.gets(s, sizeof(s)) == s);
+  ASSERT(buffer.gets(s, sizeof(s)) == NULL);
   ASSERT(strlen(s) == 0);

   // End the test suite


Fixed type conversions

Fixed type conversions

--- examples/reciever/reciever.ino
+++ examples/reciever/reciever.ino
@@ -30,10 +30,10 @@
     //read message to info and if check sum correct - outputs it to the serial port
     if (bl999_get_message(info)) {
         Serial.println("====== Got message from BL999 sensor: ");
-        Serial.println("Channel: " + info.channel);
-        Serial.println("PowerUUID: " + info.powerUUID);
+        Serial.println("Channel: " + String(info.channel));
+        Serial.println("PowerUUID: " + String(info.powerUUID));
         Serial.println("Battery is " + String(info.battery == 0 ? "Ok" : "Low"));
         Serial.println("Temperature: " + String(info.temperature / 10.0));
         Serial.println("Humidity: " + String(info.humidity) + "%");
     }
-}+}


send sms from sketch

send sms from sketch

--- YunFireAlert/YunFireAlert.ino
+++ YunFireAlert/YunFireAlert.ino
@@ -1,7 +1,13 @@
-/* TODO */
+/*
+yun-fire-alert
+Author: Arve Seljebu
+Code: https://github.com/arve0/yun-fire-alert

+Check inputs and alert upon fire alarm or failure.
+*/
 #include <Bridge.h>
 #include <Console.h>
+#include <Process.h>
 #include "MsTimer2.h"

 // pins
@@ -11,71 +17,94 @@
 const byte statusPin = 13;

 void setup() {
+  // relay normally open with external pullup
+  pinMode(failOutPin, OUTPUT);
+  // set failure upon upstart
+  digitalWrite(failOutPin, HIGH);
+  blink(1000);
   // external pullup
   pinMode(firePin, INPUT);
   // internal pullup
   pinMode(failInPin, INPUT_PULLUP);
-  // relay normally open with external pullup
-  pinMode(failOutPin, OUTPUT);
   // internal LED
   pinMode(statusPin, OUTPUT);

   Bridge.begin();
   Console.begin();
-  Console.println("console started");
 }

-void toggleLed() {
-  // change output of led
+void toggleStatus() {
+  // toggle statusPin
   static byte out = HIGH;
   digitalWrite(statusPin, out);
   out = !out;
 }

+void blink(unsigned int period){
+  if (period == 0){
+    MsTimer2::stop();
+    digitalWrite(statusPin, LOW);
+  }
+  else {
+    MsTimer2::stop();
+    MsTimer2::set(period, toggleStatus);
+    MsTimer2::start();
+  }
+}
+
 // status codes
-const byte ALARM = 0;
+const byte FIRE = 0;
 const byte FAILURE = 1;
-const byte FAILURE_INTERNET = 2;
-const byte FAILURE_TWILIO = 3;
 const byte OK = 10;

 byte getState(){
   // Get current state and return it.
-  // FAILURE_INTERNET: failure internet - TODO
-  // FAILURE_TWILIO: failure twilio   - TODO
   byte fire = digitalRead(firePin);
   byte failure = digitalRead(failInPin);
   delay(50); // debounce
-  if (fire == 1 && digitalRead(firePin) == 1) return ALARM;
-  else if (failure == 0 && digitalRead(failInPin) == 0) return FAILURE;
-  else return OK;
+  if (fire == 1 && digitalRead(firePin) == 1)
+    return FIRE;
+  else if (failure == 0 && digitalRead(failInPin) == 0)
+    return FAILURE;
+  else
+    return OK;
+}
+
+void smsAlert(){
+  Process p;
+  p.begin("/root/sms_alert.py");
+  p.run();
+  while (p.available()>0){
+    char c = p.read();
+    Console.write(c);
+  }
+  Console.flush();
 }

 void loop() {
-  static byte currentState;
-  static byte previousState = 10;
+  // initial states
+  static byte currentState = OK;
+  static byte previousState = OK;
+
   // get current state
   currentState = getState();
   if (currentState != previousState) {
     switch (currentState) {
-      case ALARM:
-        Console.println("BRANN");
-        MsTimer2::stop();
-        MsTimer2::set(100, toggleLed);
-        MsTimer2::start();
+      case FIRE:
+        blink(100);
+        Console.println("FIRE ALARM!");
+        smsAlert();
         break;

       case FAILURE:
-        Console.println("FEIL");
-        MsTimer2::stop();
-        MsTimer2::set(1000, toggleLed);
-        MsTimer2::start();
+        blink(1000);
+        Console.println("FIRE ALARM FAILURE");
+        // TODO
         break;

       case OK:
+        blink(0);
         Console.println("OK");
-        MsTimer2::stop();
-        digitalWrite(statusPin, LOW);
     } // end switch state
   } // end if state change
   previousState = currentState;


update

update

--- _09_ir_tx_rx/_09_ir_tx_rx.ino
+++ _09_ir_tx_rx/_09_ir_tx_rx.ino
@@ -351,13 +351,13 @@
     displayTemperature();
     tempMills = millis();

-/*
+
     if (timerOnOff == 0) {
       displaytimeleft(o_tvOnTime - ((millis() - tv_onoff_Mills) / 1000 / 60) );
     } else {
-      displaytimeleft(o_tvOffTime - ((millis() - tv_on_Mills) / 1000 / 60) );
-    }
-*/
+      displaytimeleft(o_tvOffTime - ((millis() - tv_onoff_Mills) / 1000 / 60) );
+    }
+
     // display difference -60 mims Temperature 3600000
     if ( (millis() - o_tempMills) >= 600000 ) {
       Serial.println("o_tempCinside called");


Specify units in CheckFlashConfig example sketch (#4490)

--- libraries/esp8266/examples/CheckFlashConfig/CheckFlashConfig.ino
+++ libraries/esp8266/examples/CheckFlashConfig/CheckFlashConfig.ino
@@ -16,10 +16,10 @@
   FlashMode_t ideMode = ESP.getFlashChipMode();

   Serial.printf("Flash real id:   %08X\n", ESP.getFlashChipId());
-  Serial.printf("Flash real size: %u\n\n", realSize);
+  Serial.printf("Flash real size: %u bytes\n\n", realSize);

-  Serial.printf("Flash ide  size: %u\n", ideSize);
-  Serial.printf("Flash ide speed: %u\n", ESP.getFlashChipSpeed());
+  Serial.printf("Flash ide  size: %u bytes\n", ideSize);
+  Serial.printf("Flash ide speed: %u Hz\n", ESP.getFlashChipSpeed());
   Serial.printf("Flash ide mode:  %s\n", (ideMode == FM_QIO ? "QIO" : ideMode == FM_QOUT ? "QOUT" : ideMode == FM_DIO ? "DIO" : ideMode == FM_DOUT ? "DOUT" : "UNKNOWN"));

   if (ideSize != realSize) {


Printed out readings in JSON format to be easily parsed by Rasppi


Set lower threshold on 1/10th instead of 1/20th

--- shofanduino2/shofanduino2.ino
+++ shofanduino2/shofanduino2.ino
@@ -150,7 +150,7 @@
   // want the fan to turn on pretty quickly, but we don't
   // want it to turn off quickly. This explains the difference
   // in factors between low and high.
-  thresholdLow = env_min + (env_max - env_min) / 20.0f;
+  thresholdLow = env_min + (env_max - env_min) / 10.0f;
   thresholdHigh = env_min + (env_max - env_min) / 2.0f;

   /*


Added options for rain gauges accuracy

Added options for rain gauges accuracy

--- mwsLRWHFv2/mwsLRWHFv2.ino
+++ mwsLRWHFv2/mwsLRWHFv2.ino
@@ -166,7 +166,10 @@
 //byte month, day, hour, minute, second, hundredths;

 //Calibrate rain bucket here
+//Rectangle raingauge from Sparkfun.com weather sensors
 float rain_bucket_mm = 0.011*25.4;//Each dump is 0.011" of water
+//DAVISNET Rain Collector 2
+//float rain_bucket_mm = 0.01*25.4;//Each dump is 0.01" of water

 // volatiles are subject to modification by IRQs
 volatile unsigned long raintime, rainlast, raininterval, rain, Rainindtime, Rainindlast;
@@ -182,11 +185,10 @@
   raintime = millis(); // grab current time
   raininterval = raintime - rainlast; // calculate interval between this and last event

-    if (raininterval > 10) // ignore switch-bounce glitches less than 10mS after initial edge
+  if (raininterval > 10) // ignore switch-bounce glitches less than 10mS after initial edge
   {
     dailyrainin += rain_bucket_mm;
     rainHour[minutes] += rain_bucket_mm; //Increase this minute's amount of rain
-
     rainlast = raintime; // set up for next event
   }


Added powerup/sleep timing mechanism

Added powerup/sleep timing mechanism

--- first_one/first_one.ino
+++ first_one/first_one.ino
@@ -45,6 +45,8 @@

 unsigned long arTime         = millis();
 unsigned long reset          = millis();
+unsigned long powerTime      = 0;
+unsigned long timeBuffer     = 0;
 unsigned int WAIT            = 150*TIME_MULTIPLIER;
 unsigned int waitLynch       = 33*TIME_MULTIPLIER;
 unsigned int actualPin       = 2;
@@ -74,6 +76,9 @@
 /////////////////////////////////////////////////////////

 void setup() {
+
+  ptStart();
+
   randomSeed(analogRead(1));

   for(unsigned int i=0;i<NUM_LEDS;i++){
@@ -86,6 +91,8 @@
   if(DEBUG){
     Serial.begin(9600);
   }
+
+  ptStop();
 }

 /////////////////////////////////////////////////////////
@@ -95,6 +102,10 @@
 void loop() {
   // Avoid arduino calls between loops
   while (true) {
+
+    ptReset(); // reset power time accumulation every 24h
+
+    ptStart(); // start accumulating power time

     // Read voltage, check charge state
     voltage = readVcc();
@@ -116,6 +127,7 @@
           checkLEDS();
         }
       }
+      ptStop(); // stop accumulating power time
     }else{
       if(voltage >= MIN_VOLTAGE && weAreTheNight){
         // We're ON
@@ -126,6 +138,7 @@
           Serial.println("Low battery/It' not dark yet!");
         }
         LEDSOFF();
+        ptStop(); // stop accumulating power time
         // Enter power down state for 8 s with ADC and BOD module disabled
         doPowerDown(SLEEP_8S, TIME_MULTIPLIER);
       }
@@ -160,22 +173,28 @@
   switch (actualStep) {
     case 1:
       lynchLED();
+      ptStop();
       break;
     case 2:
       binaryLED();
+      ptStop();
       break;
     case 3:
       binaryLEDRand();
+      ptStop();
       break;
     case 4:
       sendMorseMessage();
+      ptStop();
       break;
     case 5:
       batteryMeter();
+      ptStop();
       break;
     default:
       actualStep = 1;
       LEDSOFF();
+      ptStop();
       doPowerDown(SLEEP_8S, TIME_MULTIPLIER);
     break;
   }
@@ -242,10 +261,10 @@
  *
  */
 void doPowerDown(period_t sleepTime, uint8_t sleepCount) {
-        do {
-          LowPower.powerDown(sleepTime, ADC_OFF, BOD_OFF);
-          sleepCount--;
-        } while (sleepCount > 0);
+  do {
+    LowPower.powerDown(sleepTime, ADC_OFF, BOD_OFF);
+    sleepCount--;
+  } while (sleepCount > 0);
 }

 /*
@@ -436,3 +455,34 @@
     digitalWriteFast(ledPins[i], HIGH);
   }
 }
+
+/*
+ * Power time check Start
+ *
+ */
+void ptStart(){
+  timeBuffer = millis();
+}
+
+/*
+ * Power time check Stop
+ *
+ */
+void ptStop(){
+  powerTime += ( millis()-timeBuffer );
+  if(DEBUG){
+    Serial.println(powerTime);
+  }
+}
+
+/*
+ * Power time check reset
+ *
+ */
+void ptReset(){
+  // Every 24h
+  if(millis()%86400000 == 0){
+    powerTime = 0;
+  }
+}
+


update logging sytnax

update logging sytnax

--- sheild_sdlog_gps_color_v3/sheild_sdlog_gps_color_v3.ino
+++ sheild_sdlog_gps_color_v3/sheild_sdlog_gps_color_v3.ino
@@ -154,7 +154,7 @@

   Serial.println("Ready!");
   // Print CSV headers to serial
-  Serial.println("Time, Date, Latitude, Longitude, Elevation, Speed (Knots), Angle, Satellites, Color Temp, Lux, R, G, B, C");
+  Serial.println("Time, Date, Latitude, Longitude, Elevation, Speed (Knots), Angle, Satellites, Color Temp, Lux, R, G, B, C\n");
 }

@@ -275,7 +275,7 @@
     // Wait for logging to finish
     logfile.flush();
     // Print to serial
-    Serial.println("Logging: complete");
+    Serial.println("Log: complete");
     Serial.println();
     Serial.println("Logged Data:");
     // Time


babies first set edge runs

babies first set edge runs

--- hb.ino
+++ hb.ino
@@ -78,11 +78,11 @@
   if (run_state) {
     if (message_count > 0) {
       process_message();
-    }
-    #ifdef DUBUG_BUILD
-    Serial.println(message_str);
-    delay(2000);
-    #endif
+      #ifdef DUBUG_BUILD
+      Serial.println(message_str);
+      delay(2000);
+      #endif
+    }
   }
 }

@@ -97,9 +97,9 @@
     set_run_state(0);
     return;
   }
-  e_index = get_edge("msg", msg);
+  e_index = get_edge("msg", msg, -1);
   if (e_index < 0) {
-    e_index = get_edge("flo", msg);
+    e_index = get_edge("flo", msg, -1);
   }
   if (e_index < 0) {
     #ifdef DUBUG_BUILD
@@ -134,13 +134,13 @@
 }

 // get edge
-int get_edge(String e_type, String msg) {
+int get_edge(String e_type, String msg, int from) {
   int i;
   String t, n;
   for (i = 0; i < 10; i++) {
     t = edges[i].type;
     n = edges[i].name;
-    if (t == e_type && n == msg) {
+    if (t == e_type && (n == msg || (msg == "*" && edges[i].from == from))) {
       return i;
     }
   }
@@ -155,9 +155,41 @@
 // run_node(n1);
 void run_node(int n_index) {
   #ifdef DUBUG_BUILD
-  debug("test of run_node");
+  debug("run_node named");
   debug(nodes[n_index].name);
   #endif
+
+  // get, process, set transition
+  //nodes[n_index].value = run_get_edges(n_index);
+  //run_process();
+  run_set_edges(n_index);
+  run_transition();
+
+}
+
+// ToDo handle more than one set edge!
+void run_set_edges(int n_index) {
+  int e_i = get_edge("set", "*", n_index);
+  if (e_i >= 0) {
+    int from_n_i = edges[e_i].from;
+    int to_n_i = edges[e_i].to;
+    #ifdef DUBUG_BUILD
+    Serial.print("set edge ");
+    Serial.print(e_i, DEC);
+    Serial.println(" fired");
+    #endif
+    // set edge transfers the value
+    nodes[to_n_i].value = nodes[from_n_i].value;
+    // ToDo better identification of an IO attribute maybe is_io() or get_io_attr().
+    if (nodes[to_n_i].io != UNDEF_INT) {
+      // ToDo stop assuming digitalWrite(...)
+      digitalWrite(nodes[to_n_i].io, nodes[to_n_i].value);
+    }
+  }
+}
+
+void run_transition() {
+  // put a message in the queue
 }

 void set_run_state(short new_state) {
@@ -165,7 +197,7 @@
   if (graph_loaded) {
     run_state = new_state;
   }
-  // next line... jsut for fun (remove later ;)
+  // next line... just for fun (remove later ;)
   //digitalWrite(led, (int)run_state);
   if (!previous_state && run_state) { // rising edge
     enq_message("graph_init");


update example

update example

--- examples/ESP32-DMX_rdm/ESP32-DMX_rdm.ino
+++ examples/ESP32-DMX_rdm/ESP32-DMX_rdm.ino
@@ -18,6 +18,7 @@
     @section  HISTORY

     v1.0 - First release
+    v1.1 - Improve multi-task compatibility

 */
 /**************************************************************************/
@@ -560,9 +561,13 @@
 void checkInput(LXDMXWiFi* interface, WiFiUDP* iUDP, uint8_t multicast) {
   if ( got_dmx ) {
     interface->setNumberOfSlots(got_dmx);			// set slots & copy to interface
+
+    xSemaphoreTake( ESP32DMX.lxDataLock, portMAX_DELAY );
     for (int i = 1; i <= got_dmx; i++) {
       interface->setSlot(i, ESP32DMX.getSlot(i));
     }
+    xSemaphoreGive( ESP32DMX.lxDataLock );
+
     if ( multicast ) {
       interface->sendDMX(iUDP, DMXWiFiConfig.inputAddress(), WiFi.localIP());
     } else {
@@ -633,7 +638,6 @@
   }
   //digitalWrite(DEBUG_PIN_C, HIGH);
   vTaskDelay(1);
-  //taskYIELD();

 }// loop()


buoy: Fix altitude.

buoy: Fix altitude.

--- arduino_buoy/arduino_buoy.ino
+++ arduino_buoy/arduino_buoy.ino
@@ -48,7 +48,7 @@
 uint8_t buf[60];
 uint8_t lock =0, sats = 0, nolock=0, psm_status = 0;
 int16_t GPSerror = 0,navmode = 0,lat_int=0,lon_int=0;
-int32_t lat = 0, lon = 0, alt = 0, maxalt = 0, lat_dec = 0, lon_dec =0 ,tslf=0;
+int32_t lat = 0, lon = 0, alt = 0, lat_dec = 0, lon_dec =0 ,tslf=0;

 #ifdef ENABLE_BATTV_SENSOR
 float sampleBattv() {
@@ -91,7 +91,7 @@
     nolock=0;
   }

-  sprintf(data,"%sL%s%d.%05ld,%s%d.%05ld,%ldS%d",data,lat < 0 ? "-" : "",lat_int,lat_dec,lon < 0 ? "-" : "",lon_int,lon_dec,maxalt,sats);
+  sprintf(data,"%sL%s%d.%05ld,%s%d.%05ld,%ldS%d",data,lat < 0 ? "-" : "",lat_int,lat_dec,lon < 0 ? "-" : "",lon_int,lon_dec,alt,sats);

   sensors.setWaitForConversion(false);
   sensors.requestTemperatures();


Update master.ino

Update master.ino

--- Modules/i2c_test/i2c_string/master.ino
+++ Modules/i2c_test/i2c_string/master.ino
@@ -1,14 +1,7 @@
-// Wire Master Reader
+// Tested on UNO
+
+// Based on Wire Master Reader
 // by Nicholas Zambetti <http://www.zambetti.com>
-
-// Demonstrates use of the Wire library
-// Reads data from an I2C/TWI slave device
-// Refer to the "Wire Slave Sender" example for use with this
-
-// Created 29 March 2006
-
-// This example code is in the public domain.
-

 #include <Wire.h>


blinky blinky!

blinky blinky!

--- ardesp/hello32/hello32.ino
+++ ardesp/hello32/hello32.ino
@@ -1,14 +1,31 @@

 uint64_t chipid;
+void ledOn();
+void ledOff();

 void setup() {
   Serial.begin(115200);
+  pinMode(BUILTIN_LED, OUTPUT); // turn built-in LED on
+  blink(3);                     // signal we're starting setup
 }

 void loop() {
+  ledOff();
   chipid=ESP.getEfuseMac(); // chip ID is essentially its MAC address (6 bytes)
   Serial.printf("ESP32 Chip ID is %04X", (uint16_t) (chipid>>32)); // high 2
   Serial.printf("%08X\n",(uint32_t)chipid); // print low 4 bytes

-  delay(3000);
+  delay(1500);
+  ledOn();
+  delay(1500);
 }
+
+void ledOn()  { digitalWrite(BUILTIN_LED, LOW); }
+void ledOff() { digitalWrite(BUILTIN_LED, HIGH); }
+void blink(int times) {
+  ledOff();
+  for(int i=0; i<times; i++) {
+    ledOn(); delay(300); ledOff(); delay(300);
+  }
+  ledOff();
+}


Make default hue 120 (green) when hue is on neither axis.

--- xy.ino
+++ xy.ino
@@ -352,7 +352,7 @@
                        ? rp.x.axisIntValues[x]
                        : (rp.yAxisSpace == HUE
                           ? rp.y.axisIntValues[y]
-                          : 0));
+                          : 120));
                   s = (rp.xAxisSpace == SAT
                        ? rp.x.axisFloatValues[x]
                        : (rp.yAxisSpace == SAT


Improved SPIFFS logic.

Improved SPIFFS logic.

--- dimmertask.ino
+++ dimmertask.ino
@@ -160,13 +160,17 @@
   //return true on success
   //return false on error

+  if ( !SPIFFS.exists( defaultTimerFile ) )
+  {
+    ESP_LOGI( TAG, "No default timer file found. [%s]", defaultTimerFile );
+    return false;
+  }
+
   File f = SPIFFS.open( defaultTimerFile, "r" );

-  ESP_LOGI( TAG, "Reading SPIFFS." );
-
-  if (!f)
-  {
-    ESP_LOGI( TAG, "No default timer file found." );
+  if ( !f.available() )
+  {
+    ESP_LOGI( TAG, "Error opening default timer file. [%s]", defaultTimerFile );
     return false;
   }
   String lineBuf;


Comments, man

Comments, man

--- sploder.ino
+++ sploder.ino
@@ -132,7 +132,10 @@

 // -------------- Armed State ---------------
 void enterArmedState() {
-  blePrint("armed");
+  armedStatus();
+  if (armed) {
+    blePrint("armed");
+  }
 }
 void updateArmedState() {
   armedStatus();
@@ -198,5 +201,7 @@

     BluetoothLESerial.write(sendBuffer, sendBufferSize);
   }
+
+  // echo out the message to the serial console, regardless of BLE status
   note(message);
 }


Fix small issue with sms message format

Fix small issue with sms message format


Fix spelling in YunSerialTerminal

Fix spelling in YunSerialTerminal

--- libraries/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino
+++ libraries/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino
@@ -15,7 +15,7 @@
  '~' followed by '1' -> Set the UART speed to 115200 baud
  '~' followed by '2' -> Set the UART speed to 250000 baud
  '~' followed by '3' -> Set the UART speed to 500000 baud
- '~' followeb by '~' -> Sends the bridge's shutdown command to
+ '~' followed by '~' -> Sends the bridge's shutdown command to
                         obtain the console.

  The circuit:


Se implementa codigo Ultrasonido

Se implementa codigo Ultrasonido

--- hardware/sensor-isla/src/sensor-isla.ino
+++ hardware/sensor-isla/src/sensor-isla.ino
@@ -6,18 +6,47 @@
     Programa Emisor:
    --------------------------------------------------------------------
  */
+
+/**
+  * Dependencias módulo RF
+  */
 #include "RF24.h"
 #include "nRF24L01.h"
 #include <SPI.h>
+/*Fin*/

+/**
+ * Variables Módulo RF
+ */
 RF24 radio(9, 10);
+/*Fin*/
+
+/**
+ * Variables Módulo Ultrasonido
+ */
+#define trigPin 6
+#define echoPin 5
+#define ledEstado 8 // Indicador para deteccion del vehículo
+
+int limite = 212; // Distancia max entre el suelo y el vehiculo (cms)
+// 212 cms Toyota Hilux
+long duracion, distancia;
+/*Fin*/

 const uint64_t pipes[2] = {0xF0F0F0F0E1LL,
                            0xF0F0F0F0D2LL}; // LongLong = 64 bits.
+/*Fin*/

 void setup(void) {
+  configSerial();
+  configRF();
+  configUltrasonido();
+}
+
+void configSerial() { Serial.begin(9600); }
+
+void configRF() {
   pinMode(10, OUTPUT);
-  Serial.begin(9600);
   radio.begin();

   radio.setRetries(15, 15); // Maximos reintentos
@@ -28,43 +57,77 @@
   radio.openReadingPipe(1, pipes[1]);
 }

+void configUltrasonido() {
+  pinMode(trigPin, OUTPUT);
+  pinMode(echoPin, INPUT);
+  pinMode(ledEstado, OUTPUT);
+}
+
 void loop(void) {
+  enviarDatoRF();
+  medirDistancia();
+  delay(1000);
+}
+
+void enviarDatoRF() {
   radio.stopListening(); // Paramos la escucha para poder hablar
-  char idIsla = 1;
+  char idIsla = 69;
   char estado = 0;
-  char msg[2]= {idIsla, estado};
-  //unsigned long time = millis();
+  char msg[2] = {idIsla, estado};
+  // unsigned long time = millis();
   Serial.print("Enviando  ");
   Serial.print((int)msg[0]);
+  Serial.print(",");
   Serial.println((int)msg[1]);
-  //bool ok = radio.write(&time, sizeof(unsigned long));
+  // bool ok = radio.write(&time, sizeof(unsigned long));
   bool ok = radio.write(msg, 2);

-  if (ok){
+  if (ok) {
     Serial.println("ok...");
   } else {
-    Serial.println("failed");
+    Serial.println("failedEstado");
   }

   radio.startListening(); // Volvemos a la escucha
+  //
+  // unsigned long started_waiting_at = millis();
+  // bool timeout = false;
+  // while (!radio.available() && !timeout) { // Esperasmos repsuesta hasta
+  // 200ms
+  //   if (millis() - started_waiting_at > 200) {
+  //     timeout = true;
+  //   }
+  // }
+  //
+  // if (timeout) {
+  //   Serial.println("FailedEstado, response timed out");
+  // } else { // Leemos el mensaje recibido
+  //   char got_isla[2];
+  //   radio.read(&got_isla, 2);
+  //
+  //   Serial.print("Respuesta = ");
+  //   Serial.print((int)got_isla[0]);
+  //   Serial.println((int)got_isla[1]);
+  // }
+}

-  unsigned long started_waiting_at = millis();
-  bool timeout = false;
-  while (!radio.available() && !timeout){ // Esperasmos repsuesta hasta 200ms
-    if (millis() - started_waiting_at > 500){
-      timeout = true;
-    }
+void medirDistancia() {
+  digitalWrite(trigPin,
+               LOW); // Nos aseguramos de que el trigger está desactivado
+  // delayMicroseconds(2);              // Para asegurarnos de que el trigger
+  // esta LOW
+  digitalWrite(trigPin, HIGH); // Activamos el pulso de salida
+  // delayMicroseconds(10);             // Esperamos 10µs. El pulso sigue active
+  // este tiempo
+  digitalWrite(trigPin, LOW); // Cortamos el pulso y a esperar el echo
+  duracion = pulseIn(echoPin, HIGH);
+  distancia = duracion / 2 / 29.1;
+  if (distancia < limite) {
+    Serial.println(String(distancia) + " cm.");
+    digitalWrite(ledEstado, HIGH);
+  } else {
+    Serial.println(String(distancia) + " cm.");
+    digitalWrite(ledEstado, LOW);
   }
-
-  if (timeout){
-    Serial.println("Failed, response timed out");
-  } else { // Leemos el mensaje recibido
-    char got_isla[2];
-    radio.read(&got_isla, 2);
-
-    Serial.print("Respuesta = ");
-    Serial.print((int)got_isla[0]);
-    Serial.println((int)got_isla[1]);
-  }
-  delay(5000);
+  // delay (500) ;                  // Para limitar el número de mediciones
 }


Fix retries and post request syntax

Fix retries and post request syntax

--- ins-node/src/wifi_module/wifi_module.ino
+++ ins-node/src/wifi_module/wifi_module.ino
@@ -8,7 +8,7 @@
 ESP8266WiFiClass wifi;
 EspClass espPower;
 const uint8_t DEVICE_ID = 1; // The identification for the specific node
-const int8_t CONNECTION_RETRIES = 3; // The maximum amount of wifi connection attempts
+const int8_t CONNECTION_RETRIES = 20; // The maximum amount of wifi connection attempts
 const uint8_t DEFAULT_TRANSMISSION_SIZE = 10;
 uint8_t currentTransmissionSize = DEFAULT_TRANSMISSION_SIZE;

@@ -65,7 +65,7 @@

   // Compose a request for the server according to the agreed format:
   // /set_rssi/device_id/mac_addr1/rssi1/mac_addr2/ ... /mac_addr10/:rssi10/
-  String request = "/set_rssi/:";
+  String request = "/set_rssi/";
   request += DEVICE_ID;
   request += "/";
   for (auto datapoint : datapoints) {
@@ -80,9 +80,9 @@
   }

   // Send the TCP request to the rest server
-  client.print("PUT " + request + " HTTP/1.1\r\n" +
-               "SERVER_IP: " + SERVER_IP + "\r\n" +
-               "Connection: close\r\n\r\n");
+  client.print("POST " + request + " HTTP/1.1\r\n" +
+                 "Host: " + SERVER_IP + "\r\n" +
+                 "Connection: close\r\n\r\n");

   // Verify whether the request timed out
   bool successfulRequest = true;


Updated unit tests for release V1.0.0

Updated unit tests for release V1.0.0

--- test/test.ino
+++ test/test.ino
@@ -41,8 +41,8 @@
 static void testLibVersion()
   {
   Serial.println("LibVersion");
-  AssertIsEqual(0, ARDUINO_LIB_OTAESGCM_VERSION_MAJOR);
-  AssertIsEqual(2, ARDUINO_LIB_OTAESGCM_VERSION_MINOR);
+  AssertIsEqual(1, ARDUINO_LIB_OTAESGCM_VERSION_MAJOR);
+  AssertIsEqual(0, ARDUINO_LIB_OTAESGCM_VERSION_MINOR);
   }

 //    /**Test on specific simple plaintext/ADATA.key value.


Arkanoid can be run now in Linux (no buttons support yet ;) )


fix: specify led-module-type expliciedly

--- examples/rss_disp/rss_disp.ino
+++ examples/rss_disp/rss_disp.ino
@@ -197,12 +197,12 @@
   delay(100);
   Serial.println("\n\nReset:");

-  LedMat.begin();
+  LedMat.begin(LMMT64x32s16,1,1);
 	LedMat.setImgBuf(imgBuf, sizeof imgBuf);
 	LedMat.setPlane(1);
 	LedMat.setLedMode(1);			// for HSLM-6432P4B
   LedMat.setRotation(0);
-  LedMat.setBright(10);          // 1..100
+  LedMat.setBright(10);     // 1..100
   LedMat.clear();
   LedMat.display();
   scroll.setTextSize(1);


update example

update example

--- examples/fade/fade.ino
+++ examples/fade/fade.ino
@@ -1,5 +1,7 @@
 #include <Helper2.h>
 #include <Wire.h>
+
+bool tapped;

 void setup() {
   initialize();
@@ -11,15 +13,25 @@
 }

 void loop() {
-  led1.debug_print();
-  led1.fadeIn();
-  led2.debug_print();
-  led2.fadeOut();
+  if (tapped){
+    led1.debug_print();
+    led1.fadeIn();
+    led2.debug_print();
+    led2.fadeOut();
+    if (accel.tap()){
+      tapped = false;
+    }
+  }
+  else {
+    led1.debug_print();
+    led1.fadeOut();
+    led2.debug_print();
+    led2.fadeIn();
+    if (accel.tap()){
+      tapped = true;
+    }
+  }
+
   wait(100);
-
-  // led1.fadeOut();
-  // led2.fadeIn();
-  // wait(10000);
-  //
 }


Retries on config menu connections

Retries on config menu connections

git-svn-id: d8bfcd070c2c81762cca1b3912331324182919ba@18727 0d6f1817-ed0e-0410-87c9-987e46238f29

--- zimodem/zconfigmode.ino
+++ zimodem/zconfigmode.ino
@@ -474,7 +474,18 @@
       {
           if(!connectWifi(WiFi.SSID(lastNumber).c_str(),cmd.c_str()))
           {
-            serial.printf("%sUnable to connect to %s. :(%s",EOLNC,WiFi.SSID(lastNumber).c_str(),EOLNC);
+            serial.printf("%sConnection failed.  Retrying %s.%s",EOLNC,WiFi.SSID(lastNumber).c_str(),EOLNC);
+            for(int t=0;t<3;t++)
+            {
+              for(int i=0;i<500;i++)
+              {
+                if(serial.isSerialOut())
+                  serialOutDeque();
+                delay(1);
+              }
+            }
+            if((wifiSSI.length() == 0) || (WiFi.status()!=WL_CONNECTED))
+              serial.printf("%sUnable to connect to %s.%s",EOLNC,WiFi.SSID(lastNumber).c_str(),EOLNC);
           }
           else
           {


Update esp.ino

Update esp.ino

device now works, just fine

--- esp12/esp/esp.ino
+++ esp12/esp/esp.ino
@@ -68,7 +68,7 @@
   WiFi.persistent(false);
 	WiFi.mode(WIFI_OFF);   // this is a temporary line, to be removed after SDK update to 1.5.4
 	WiFi.mode(WIFI_STA);
-  WiFi.begin("your ssid", "pass");
+  WiFi.begin("yourssid", "yourpass");
   while (WiFi.status() != WL_CONNECTED) {
 	  Serial.println(WiFi.status());
       delay(500);
@@ -82,9 +82,8 @@
 	  sendInfo();
 	 // delay(100);
 	  Serial.println(ESP.getFreeHeap());
-
 	 }
-	delay(2000);
+	 delay(200);
 	/*
   while (ss.available() > 0)
   if (gps.encode(ss.read())) {
@@ -106,7 +105,6 @@
   http.sendRequest("GET");
   String payload = http.getString();
   http.end();
-  Serial.println(payload);
   if (payload == "true") {
     return true;
   }
@@ -192,14 +190,16 @@
 }
 */
 void sendInfo() {
+	while(true)
 	while (ss.available() > 0) {
 		if (gps.encode(ss.read())) {
-			float temperature = dht.readTemperature();
-			float humidity = dht.readHumidity();
-			Serial.println(temperature);
-			if (!isnan(temperature) || !isnan(humidity) && gps.date.isValid() && gps.time.isValid()) {
-				Serial.println(ESP.getFreeHeap());
-				StaticJsonBuffer<750> JSONbuffer;
+			 float temperature = dht.readTemperature();
+			 float humidity = dht.readHumidity();
+			// Serial.println(temperature);
+			 if (!isnan(temperature) || !isnan(humidity) && gps.date.isValid()
+				 && gps.time.isValid() && gps.location.isValid() && gps.location.isUpdated()) {
+			//if (gps.date.isValid() && gps.time.isValid() && gps.location.isValid() && gps.location.isUpdated()) {
+			 	StaticJsonBuffer<750> JSONbuffer;
 				JsonObject& root = JSONbuffer.createObject();
 				JsonArray& values = root.createNestedArray("incidentValues");
 				JsonObject& temp = values.createNestedObject();
@@ -249,7 +249,7 @@
 					root.printTo(file);
 				    file.println("");
 				}
-				delay(1000);
+				delay(10000);
 			}
 			delay(1000);
 		}
@@ -258,5 +258,3 @@

-
-


Mise à jour du code Arduino

Mise à jour du code Arduino

--- arduino/main/main.ino
+++ arduino/main/main.ino
@@ -2,11 +2,12 @@

 const int USTrig = 8; // Déclencheur sur la broche 8
 const int USEcho = 9; // Réception sur la broche 9
-const int led = 7; // LED sur la broche 7
-const int warningButton = 3; // Bouton d'arrêt d'urgence sur la broche 3
-const int flowmeter = 2; // Flowmeter sur la broche 2
+const int led = 7; // LED sur la broche 7
+const int flowmeterIn = 3; // Flowmeter In sur la broche 3
+const int flowmeterOut = 2; // Flowmeter Out sur la broche 3
 const int pump = 10; // Pump sur la broche 10 (CH1)
-const int urbanNetwork = 7;
+const int electrovanne = 11; // Electrovanne sur la broche 11 (CH2)
+const int urbanNetwork = 12;

 String command = "";
 boolean commandComplete = false;
@@ -14,9 +15,10 @@
 unsigned long previousTime;

 // Flowmeter variables
-volatile int  flowmeterCounter;     // Measures flow meter pulses
-unsigned int  flowmeterResult;      // Calculated litres/hour
-unsigned long beginFlowmeterDate;   // Begin date
+volatile int  flowmeterInCounter;     // Measures flow meter pulses
+unsigned int  flowmeterInResult;      // Calculated litres/hour
+volatile int  flowmeterOutCounter;     // Measures flow meter pulses
+unsigned int  flowmeterOutResult;      // Calculated litres/hour

 void setup() {
   Serial.begin(9600);
@@ -25,7 +27,7 @@

   currentTime = millis();
   previousTime = currentTime;
-
+
   // Flowmeter 1
   setupFlowmeter();

@@ -35,17 +37,17 @@
   // Pump
   setupPump();

+  // Electrovanne
+  setupElectrovanne();
+
   setupUrbanNetwork();
-
-  // Pump
-  setupWarningButton();
-
 }

 void loop() {
   // Send values
   if (checkSending()) {
-    readFlowmeter();
+    readFlowmeterIn();
+    readFlowmeterOut();
     readWaterDistance();
   }

@@ -94,10 +96,16 @@
     digitalWrite(pump, HIGH);
   } else if (command.startsWith("URBAN_NETWORK=0")) {
     Serial.println("URBAN_NETWORK=0");
-    digitalWrite(urbanNetwork, LOW);
+    digitalWrite(urbanNetwork, HIGH);
   } else if (command.startsWith("URBAN_NETWORK=1")) {
     Serial.println("URBAN_NETWORK=1");
-    digitalWrite(urbanNetwork, HIGH);
+    digitalWrite(urbanNetwork, LOW);
+  } else if (command.startsWith("ELECTROVANNE=0")) {
+    Serial.println("ELECTROVANNE=0");
+    digitalWrite(electrovanne, LOW);
+  } else if (command.startsWith("ELECTROVANNE=1")) {
+    Serial.println("ELECTROVANNE=1");
+    digitalWrite(electrovanne, HIGH);
   }
 }

@@ -143,45 +151,59 @@
   }
 }

+void setupPump() {
+  pinMode(pump, OUTPUT);
+  digitalWrite(pump, LOW);
+  Serial.println("PUMP_IN=0");
+}
+
+void setupElectrovanne() {
+  pinMode(electrovanne, OUTPUT);
+  digitalWrite(electrovanne, LOW);
+  Serial.println("ELECTROVANNE=0");
+}
+
+void setupUrbanNetwork() {
+  pinMode(urbanNetwork, OUTPUT);
+  digitalWrite(urbanNetwork, HIGH);
+  Serial.println("URBAN_NETWORK=0");
+}
+
 void setupFlowmeter() {
-  pinMode(flowmeter, INPUT);
-  attachInterrupt(0, increaseFlowmeterCounter, RISING); // Setup Interrupt
+  pinMode(flowmeterIn, INPUT);
+  pinMode(flowmeterOut, INPUT);
+  attachInterrupt(digitalPinToInterrupt(flowmeterIn), increaseFlowmeterInCounter, RISING); // Setup Interrupt
+  attachInterrupt(digitalPinToInterrupt(flowmeterOut), increaseFlowmeterOutCounter, RISING); // Setup Interrupt
   sei();                                             // Enable interrupts
 }

-void increaseFlowmeterCounter()
+void increaseFlowmeterInCounter()
 {
-   flowmeterCounter++;
+   flowmeterInCounter++;
 }

-void readFlowmeter() {
+void increaseFlowmeterOutCounter()
+{
+   flowmeterOutCounter++;
+}
+
+void readFlowmeterIn() {
   // Every second, calculate and print litres/hour
   // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min. (Results in +/- 3% range)
-  flowmeterResult = (flowmeterCounter * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flow rate in L/hour
-  flowmeterCounter = 0;                   // Reset Counter
+  flowmeterInResult = (flowmeterInCounter * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flow rate in L/hour
+  flowmeterInCounter = 0;                   // Reset Counter

   Serial.print("WATER_FLOW_IN=");
-  Serial.println(flowmeterResult, DEC);
-}
-
-void setupPump() {
-  pinMode(pump, OUTPUT);
-  Serial.println("PUMP_IN=0");
-}
-
-void setupUrbanNetwork() {
-  pinMode(urbanNetwork, OUTPUT);
-  digitalWrite(urbanNetwork, LOW);
-  Serial.println("URBAN_NETWORK=0");
-}
-
-void warningButtonAction() {
-  //Serial.println("ARRETTTTTTTTTTTTTTTTTTTTTTT DURGENCEEEEEE");
-}
-
-void setupWarningButton() {
-  pinMode(warningButton, INPUT);
-  attachInterrupt(1, warningButtonAction, FALLING); // Setup Interrupt
-  sei();                                             // Enable interrupts
-}
-
+  Serial.println(flowmeterInResult, DEC);
+}
+
+void readFlowmeterOut() {
+  // Every second, calculate and print litres/hour
+  // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min. (Results in +/- 3% range)
+  flowmeterOutResult = (flowmeterOutCounter * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flow rate in L/hour
+  flowmeterOutCounter = 0;                   // Reset Counter
+
+  Serial.print("WATER_FLOW_OUT=");
+  Serial.println(flowmeterOutResult, DEC);
+}
+


Using air pressure at sea level.

Using air pressure at sea level.

--- Arduino/MainControl/BarometricPressureAndAirTemp.ino
+++ Arduino/MainControl/BarometricPressureAndAirTemp.ino
@@ -20,7 +20,7 @@
 }

 numvar ap(void) {
-  return getPressure();
+  return getSeaLevel();
 }

 numvar alt(void) {
@@ -89,3 +89,19 @@
     return READ_ERROR;
 }

+double getSeaLevel() {
+  double T, P;
+  char result = bmp.startMeasurment();
+
+  if (result != 0) {
+    delay(result);
+    result = bmp.getTemperatureAndPressure(T, P);
+
+    if (result != 0)
+      return bmp.sealevel(P, bmp.altitude(P, P0));
+    else
+      return READ_ERROR;
+  }
+  else
+    return READ_ERROR;
+}


debug: char of deviceId & re-indent

debug: char of deviceId & re-indent

--- client/client.ino
+++ client/client.ino
@@ -17,7 +17,7 @@
 decode_results results;
 int deviceStatus = 0;
 int pendingTimer;
-const char deviceId = "02";
+char deviceId[2] = "02";
 char XBeeInString[50];
 int state = IDLE;
 unsigned long randomDelay = 0;
@@ -95,42 +95,43 @@
       printXBeePacket(p);

       if (atoi(p.id) == atoi(deviceId) && p.type[0] == 'c') {
-	// have been confirmed
-	Serial.println("[CONNECTED] entering state");
+      	// have been confirmed
+      	Serial.println("[CONNECTED] entering state");

-	// turn on the ligth to indicate
-	digitalWrite(ledPin, HIGH);
+      	// turn on the ligth to indicate
+      	digitalWrite(ledPin, HIGH);

-	state = CONNECTED;
+      	state = CONNECTED;
       }
-      // verifying this selection
+            // verifying this selection
       else if (atoi(p.id) == atoi(deviceId) && p.type[0] == 'v') {
-	// have been confirmed
-	Serial.println("[WAIT] being verified");
+      	// have been confirmed
+      	Serial.println("[WAIT] being verified");

-	// may flash the light to indicate this
-
-	state = PENDING;
+      	// may flash the light to indicate this
+
+      	state = PENDING;
       }
       // verifying this selection
       else if (atoi(p.id) != atoi(deviceId) && p.type[0] == 'v') {
-	// have been confirmed
-	Serial.println("[WAIT] verifying others");
-	state = PENDING;
+      	// have been confirmed
+      	Serial.println("[WAIT] verifying others");
+      	state = PENDING;
       }
       else {
-	Serial.println("[IDLE] id not equal");
-	state = IDLE;
+      	Serial.println("[IDLE] id not equal");
+      	state = IDLE;
       }
     }
     break;
+
   case CONNECTED:

     // temporarily for debugging
     delay(10000);
     state = IDLE;
-
     break;
+
   default:
     break;
   }