added docstring

added docstring

--- wireless_motor_gui_AP/wireless_motor_gui_AP.ino
+++ wireless_motor_gui_AP/wireless_motor_gui_AP.ino
@@ -1,5 +1,43 @@
 /*
-  attempt AP control of robot
+  Wireless Motor Control, with ESP as Access Point
+
+  Usage:
+    Connect phone or laptop to "ESP Whee" wireless network
+    Go to 192.168.4.1.
+    A webpage with four buttons should appear. Click them to move the robot.
+
+  Installation:
+    In Arduino, go to Tools > ESP8266 Sketch Data Upload to upload the files from ./data to the ESP
+    Then, in Arduino, compile and upload sketch to the ESP
+
+  Requirements:
+    Arduino support for ESP8266 board
+      In Arduino, add URL to Files > Preferences > Additional Board Managers URL.
+      See https://learn.sparkfun.com/tutorials/esp8266-thing-hookup-guide/installing-the-esp8266-arduino-addon
+
+    Websockets library
+      To install, Sketch > Include Library > Manage Libraries... > Websockets > Install
+      https://github.com/Links2004/arduinoWebSockets
+
+    ESP8266FS tool
+      To install, create "tools" folder in Arduino, download, and unzip. See
+      https://github.com/esp8266/Arduino/blob/master/doc/filesystem.md#uploading-files-to-file-system
+
+
+  Note that one of the motor pins overlaps with LED pin D4, so when the left wheel is going CW, the LED light close the ESP chip will turn on
+  Note that we opted to swap the motor wires on the right motor so that LOW is backwards for both motors
+
+  We define arbitrarily Left CW = backwards
+
+  Hardware:
+  * NodeMCU Amica DevKit Board (ESP8266 chip)
+  * Motorshield for NodeMCU
+  * 2 motors + 2 wheels + motor chassis with caster
+  * Left motor connected to D3 (BLK/A- and RED/A+ on the shield)
+  * Right motor connected to D4, with wires swapped (RED/B- and BLK/B+ on the shield)
+
+  modified Nov 2016
+  Nancy Ouyang
 */

 #include <Arduino.h>


add read date and time from GPS

add read date and time from GPS

--- test_configSIM808.ino
+++ test_configSIM808.ino
@@ -8,25 +8,39 @@
   static int const prot = 1;          // default value TCP
 #endif

-/*******************************
- * Definition of error codes
- *******************************/
-#define CIPSHUT_FAIL 1
-#define IPR9600_FAIL 2
-#define CSTT_UNINET_FAIL 3
-#define CIICR_FAIL 4
-#define CDNSGIP_FAIL 5
-
-#define NO_GPRS_SIGNAL 20
-#define DNS_ERROR 21
-#define PDP_DEACT 22
-
-#define NO_GPS_DATA_AVAILABLE 31
-
-#define START_GPRS_TCP_FAIL 50
-#define START_GPRS_UDP_FAIL 51
-#define SEND_TCP_DATA_FAIL 52
-#define SEND_UDP_DATA_FAIL 53
+/*********************************************************
+ * Definition of error codes, currently array of 20 errors
+ *********************************************************/
+enum fault{
+  ERRORS = 0,
+  CIPSHUT_FAIL = 1,
+  IPR9600_FAIL = 2,
+  CSTT_UNINET_FAIL = 3,
+  CIICR_FAIL = 4,
+  CDNSGIP_FAIL = 5,
+  NO_GPRS_SIGNAL = 6,
+  DNS_ERROR = 7,
+  PDP_DEACT = 8,
+  NO_GPS_DATA_AVAILABLE = 10,
+  START_GPRS_TCP_FAIL = 11,
+  START_GPRS_UDP_FAIL = 12,
+  SEND_TCP_DATA_FAIL = 13,
+  SEND_UDP_DATA_FAIL = 14,
+  POWER_GPS_FAIL =15,
+  RESTART_GPS_FAIL = 16,
+  INITIAL_TIME_NOT_SET =17,
+};
+enum fault currentError;           //if value 0, there is no error, otherwise check the "Definition of error codes"
+const int ERROR_SIZE = 20;
+byte errorStatus[ERROR_SIZE]={0};
+
+enum initTime{
+  FIRST_TIME,
+  RUNNING_TIME,
+};
+
+// start reading from the first byte (address 0) of the EEPROM
+int addWrite = 0; //write

 //The content of messages sent
@@ -42,6 +56,7 @@
 char smsMessage[64];

+#include <EEPROM.h>
 #include <DFRobot_sim808.h>
 #include <sim808.h>
 #include <SoftwareSerial.h>
@@ -54,8 +69,7 @@
 SoftwareSerial GPRS(rxPin, txPin); // RX, TX
 DFRobot_SIM808 sim808(&GPRS);
 SimpleTimer timer;
-
-//char* key;
+int timerID;
 //All this char variable have reserved one extra char to insert \0 at end
 char gpsMode[4]="000";
 char dateTime[11]="000000.000";
@@ -66,9 +80,16 @@
 char MSL_altitude[8]="00000.0";
 char Speed[8]="000.000";
 char GEOID[5]="00000";
+char startDateTime[22] = "000000000000000000000";//"hhmmss.sss-dd-mm-yyyy"; start time of HW
+
 boolean DNS_OK = true;
 int currentRadioSig = 10;   //currentRadioSig/previousRadioSig = 10 to avoid configure again the data connection
 int previousRadioSig = 10;  //when enter the first time of loop to send data
+//USED FOR EEPROM
+int addr = 0;
+
+//time to GPS acquire signal
+int timeGetGPS=0;  //in seconds

 //byte pos = 0;  //WHAT POSITION WE ARE AT IN THAT BUFFER
@@ -143,26 +164,8 @@
   /*******************************************************
    * configuration of GPRS data
    *******************************************************/
-  InitGPRS();
-
-  /***********************************************************
-  * GPS configuration
-  ***********************************************************/
-  //GPS configuration
-  //GPRS.println("AT+CGPSPWR=1");  //POWER ON of GPS interface
-  //SerialSim808_Read();
-  sim808_check_with_cmd("AT+CGPSPWR=1\r\n","OK\r\n",CMD);
-  delay(50);
-
-  //GPRS.println("AT+CGPSRST=0");  //1 = HOT start of GPS or COLD start = 0
-  //SerialSim808_Read();
-  sim808_check_with_cmd("AT+CGPSRST=0\r\n","OK\r\n",CMD);
-  delay(50);
-
-//  GPRS.println("AT+CGPSSTATUS?");
-//  // SerialSim808_Read();
-//  delay(50);
-
+  InitGPRS(FIRST_TIME);
+
   /*************************************************
    * Special config for SMS and voice call
    *************************************************/
@@ -189,14 +192,21 @@
     sim808_send_cmd("AT+CNETLIGHT=0\r\n");
   #endif

-  //wait
-  wait_GPS_connect(240);  //wait GPS connect 2minutes
-
+  /***********************************************************
+  * GPS configuration
+  ***********************************************************/
+  connect_GPS(240, FIRST_TIME);  //wait GPS connect 2minutes
+
+  if(!GPSAnalyzer128()){
+    setCurrentError(INITIAL_TIME_NOT_SET);
+    printAllError();
+  }

   GetGPSLocation();

-  timer.setInterval(60000, GetGPSLocation); //call subroutine to GetGPSLocation every minute
+  timerID = timer.setInterval(60000, GetGPSLocation); //call subroutine to GetGPSLocation every minute
   //timer.setInterval(1000, PrintSecondsElapsed);
+
 }

@@ -210,6 +220,7 @@
   //Serial.print(".");
   //delay(1000);

+
   //Only for debug purpose, send directly the AT command manually via serial interface
   #ifdef DEBUG
   if(GPRS.available())
@@ -217,8 +228,23 @@
    if(Serial.available())
       GPRS.write(Serial.read());
   #endif
-
-
+
+
+  if ((readCurrentError(NO_GPRS_SIGNAL))== 1){
+    timer.disable(timerID);
+    Serial.println("GetGPSDisabled");
+    connect_GPS(120, RUNNING_TIME);                        //leave GPS ON/COLD START until timeout of 120 sec
+
+    sim808_check_with_cmd("=0\r\AT+CGPSPWRn","OK\r\n",CMD);   //put GPS to sleep either acquire signal or not
+
+    if ((readCurrentError(NO_GPRS_SIGNAL))== 1){              //if still NO_GPRS_SIGNAL keep the routine getGPSLocation() off for 120sec more until another probe
+      delay(30000);                                          //wait 2min before try to acquire GPS signal again
+
+    }else{                                                    //if GPRS_SIGNAL OK activate routine of getGPSLocation() again
+      timer.enable(timerID);
+      Serial.println("GetGPSEnabled");
+    }
+  }

 //  //Receiving call
 //  if(sim808.readable()){
@@ -284,15 +310,14 @@
 }

 /**************************************************************************************
-* InitGPRS()
+* InitGPRS(byte firstTime)
 * This function initialize the GPRS during start/restart of arduino/sim808 or when
 * during normal operation it lost connection signal with GPRS.
-* Return error code:
-* 0 = Init successfull
-* 1 = Error with AT+IPR=9600
-* 2
+* param: firstTime = 1, when is called during setup()
+*        firstTime = 0, when called inside the code
+* Return error code: see error definition
 ***************************************************************************************/
-int InitGPRS(){
+int InitGPRS(enum initTime t){
  byte error = 0;
  /**************************************
   *AT+CGREG?
@@ -318,10 +343,17 @@
     *OK
     ************************************/

-   if(!sim808_check_with_cmd("AT+CIPSHUT\r\n","OK\r\n",CMD)){
-    error = CIPSHUT_FAIL;
+   sim808_check_with_cmd("AT\r\n","OK\r\n",CMD);
+
+   if(t==FIRST_TIME){
+     if(!sim808_check_with_cmd("AT+CIPSHUT\r\n","OK\r\n",CMD)){
+       error = CIPSHUT_FAIL;
+       setCurrentError(CIPSHUT_FAIL);
+     }else{
+       clearCurrentError(CIPSHUT_FAIL);
+     }
+     delay(50);
    }
-   delay(50);

   /***********************************
    *Set GPRS data rate
@@ -329,7 +361,10 @@
    *OK
    ***********************************/
    if(!sim808_check_with_cmd("AT+IPR=9600\r\n","OK\r\n",CMD)){
-    error = IPR9600_FAIL;
+     error = IPR9600_FAIL;
+     setCurrentError(IPR9600_FAIL);
+   }else{
+     clearCurrentError(IPR9600_FAIL);
    }
    delay(50);

@@ -341,6 +376,9 @@
    ******************************************/
   if(!sim808_check_with_cmd("AT+CSTT=\"UNINET\"\r\n","OK\r\n",CMD)){
     error = CSTT_UNINET_FAIL;
+    setCurrentError(CSTT_UNINET_FAIL);
+  }else{
+    clearCurrentError(CSTT_UNINET_FAIL);
   }
   delay(50);

@@ -351,6 +389,9 @@
    *******************************************/
   if(!sim808_check_with_cmd("AT+CIICR\r\n","OK\r\n",CMD)){
     error = CIICR_FAIL;
+    setCurrentError(CIICR_FAIL);
+  }else{
+    clearCurrentError(CIICR_FAIL);
   }
   delay(50);

@@ -370,6 +411,9 @@
    *******************************************/
   if(!sim808_check_with_cmd("AT+CDNSGIP=\"ardugps.hopto.org\"\r\n","OK\r\n",CMD)){
     error = CDNSGIP_FAIL;
+    setCurrentError(CDNSGIP_FAIL);
+  }else{
+    clearCurrentError(CDNSGIP_FAIL);
   }
   delay(50);
   return error;
@@ -531,60 +575,41 @@
 posBuf=0;
 int i = 0;
 int j=0;
-
+  Serial.println("***LOOP***");
+  //readAllError();  //print all errors present in the previous loop
+
 //  //waking up GPS after sleep
-  sim808_check_with_cmd("AT+CGPSPWR=1\r\n","OK\r\n",CMD);
-  delay(1000);
-  sim808_check_with_cmd("AT+CGPSRST=1\r\n","OK\r\n",CMD);
-  delay(1000);
-
-  if(!wait_GPS_connect(25)){ //timeout of 25 seconds to acquire signal
+  //if(!connect_GPS(25, RUNNING_TIME)){ //timeout of 25 seconds to acquire signal, 1h worst case lost 2x
+
+  if(!connect_GPS(30, RUNNING_TIME)){ //timeout of 25 seconds to acquire signal, 1h worst case lost 2x
     sim808_check_with_cmd("AT+CGPSPWR=0\r\n","OK\r\n",CMD);
-    return NO_GPS_DATA_AVAILABLE;
-  }
-
-
+    setCurrentError(NO_GPRS_SIGNAL);
+    printAllError();
+    return NO_GPRS_SIGNAL;
+  }
+
+
+  delay(8000);  //5000 no GPS data 10 times
   sim808_clean_buffer(infoLocation,BUFFER_SIZE);
+  //sim808_check_with_cmd("AT\r\n","OK\r\n",CMD);

   sim808_send_cmd("AT+CGPSINF=2\r\n");
-  delay(50);
-  if(sim808.readable()) {
+  //delay(50);  needed when there is a lot of printout on Serial.print
+  //if(sim808.readable()) {
     sim808_read_buffer(infoLocation,BUFFER_SIZE,DEFAULT_TIMEOUT);
-  }
+  //}
   Serial.println("buffer2:");
   Serial.println(infoLocation);

-//  while(GPRS.available()){
-//    GPRS.read();
-//  }
-//  GPRS.println("AT+CGPSINF=2");
-//
-//  //Read response of SIM808 at Serial Port, Uno buffer all data without other activities
-//  //otherwise it may lose some bytes
-//  //after send the command to GPS, it takes about 100ms to all serial information arrives UNO
-//  delay(50);
-
-
-//  //for(int i=0;i<7;i++){
-//  while((posBuf<=99)&&(i<15)){
-//    while((GPRS.available()>0)){
-//      infoLocation[posBuf++]=GPRS.read();
-//    }
-//    delay(10);
-//    i++;
-//    //delay(15);
-//  }
-
-  if(!GPSAnalyzer(infoLocation)){
+  if(!GPSAnalyzer(infoLocation)){                   //power off GPS and wait another loop of getGPSLocation to turn GPS on again
     //sim808_clean_buffer(infoLocation,BUFFER_SIZE);
-    sim808_check_with_cmd("AT+CGPSPWR=0\r\n","OK\r\n",CMD);
+    sim808_check_with_cmd("AT+CGPSPWR=0\r\n","OK\r\n",CMD);
+
+    setCurrentError(NO_GPS_DATA_AVAILABLE);
+    printAllError();
     return NO_GPS_DATA_AVAILABLE;
   }
-
-
-  //debug until here
-

@@ -600,48 +625,167 @@
   GPSAnalyzer32(infoLocation);

   //Send collected data to mysql server
-  Serial.println("SendError:");
-  Serial.println(SendGPSLocation());
+
+  currentError = SendGPSLocation();  //error already saved inside the SendGPSLocation()
+  Serial.print("ERROR:");
+  Serial.println(currentError);
   //createSMSMessage(smsMessage,latitude, longitude, MSL_altitude, Speed);

   //put GPS to sleep
-  sim808_check_with_cmd("AT+CGPSPWR=0\r\n","OK\r\n",CMD);
+  sim808_check_with_cmd("=0\r\AT+CGPSPWRn","OK\r\n",CMD);
   //delay(5000);
+
+
+  printAllError();
+
   return 0; //success
+
 }

 /****************************************************************************
- * wait_GPS_connect(int seconds)
+ * setCurrentError(enum fault)
+ * param
+ * error = is the error code (position in the array)
+ *  ****************************************************************************/
+ void setCurrentError(enum fault currentError){
+   errorStatus[ERRORS]=1;
+   errorStatus[currentError]=1;
+}
+
+/****************************************************************************
+ * clearCurrentError(enum fault)
+ * param
+ * error = is the error code (position in the array)
+ *  ****************************************************************************/
+ void clearCurrentError(enum fault error){
+   errorStatus[error]=0;
+}
+
+/****************************************************************************
+ * clearAllError()
+ * param
+ * error = is the error code (position in the array)
+ *  ****************************************************************************/
+ void clearAllError(){
+  memset(errorStatus, 0, ERROR_SIZE);
+}
+
+/****************************************************************************
+ * readErrorStatus(enum fault)
+ * readu current error
+ ****************************************************************************/
+ int readCurrentError(enum fault error){
+   return errorStatus[error];
+ }
+
+/****************************************************************************
+ * printAllError()
+ ****************************************************************************/
+ void printAllError(){
+   byte i;
+
+   addWrite=storeString(addWrite,"L:");   //store letter 'L' of Loop to indicate init of one loop
+
+   Serial.println("ErrorList");
+   for (i=1; i<ERROR_SIZE;i++){ //skipp the position 0 where only indicate there is fault no indication where
+    if(errorStatus[i]==1){
+      Serial.print(i);
+      Serial.print("==>");
+      Serial.println(errorStatus[i]);
+      //store EEPROM start write on address zero
+      addWrite=storeData(addWrite,i);
+    }
+   }
+ }
+
+///****************************************************************************
+// * storeLog(byte c )
+// * UNO memory 1K
+// ****************************************************************************/
+// void storeData(byte val){
+//  EEPROM.write(addr, val);
+//  addr = addr + 1;
+//  if (addr == EEPROM.length()) {
+//    addr = 0;
+//  }
+// }
+
+
+/****************************************************************************
+ * boolean connect_GPS(int timeout, int interval)
  * wait GPS acquire signal
+ * parameters
+ * timeout = max time to check if gps acquired in seconds
+ * interval = time between the check of GPSSTATUS command
+ * return
+ * true or false. true if GPS acquired or false if GPS was not acquired
  ****************************************************************************/
-boolean wait_GPS_connect(int timeout){
+boolean connect_GPS(int timeout, enum initTime t){
   unsigned long timerStart;
   timerStart = millis();

-  sim808_flush_serial();
+  //sim808_flush_serial(); //test
+  Serial.println("WaitGPSsync");
+  sim808_check_with_cmd("AT\r\n","OK\r\n",CMD);
+
+  if(!sim808_check_with_cmd("AT+CGPSPWR=1\r\n","OK\r\n",CMD)){
+    setCurrentError(POWER_GPS_FAIL);
+    return false;
+  }else{
+    clearCurrentError(POWER_GPS_FAIL);
+  }
   delay(1000);
-
+
+  if (t == FIRST_TIME){
+    if(!sim808_check_with_cmd("AT+CGPSRST=0\r\n","OK\r\n",CMD)){   //COLD START
+      setCurrentError(POWER_GPS_FAIL);
+      return false;
+    }else{
+      clearCurrentError(POWER_GPS_FAIL);
+    }
+  }else{
+    if(t == RUNNING_TIME){
+      if(!sim808_check_with_cmd("AT+CGPSRST=1\r\n","OK\r\n",CMD)){ //HOT START
+        setCurrentError(POWER_GPS_FAIL);
+      }else{
+        clearCurrentError(POWER_GPS_FAIL);
+      }
+    }
+  }
+  delay(1000);
+
   while (1){
     sim808_clean_buffer(gprsBuffer,64);
+
+    //sim808_flush_serial(); //test
+
     sim808_send_cmd("AT+CGPSSTATUS?\r\n");
-    if(sim808.readable()) {
-      sim808_read_buffer(gprsBuffer,64,DEFAULT_TIMEOUT);
-    }
-
-    Serial.println(gprsBuffer);
+    //if(sim808.readable()) {
+    sim808_read_buffer(gprsBuffer,64,2); //change default timeout to 1s instead of 5s
+    //}
+
+    //Serial.println(gprsBuffer);
     if(strstr(gprsBuffer,"3D Fix")){
       sim808_clean_buffer(gprsBuffer,64);
-      sim808_flush_serial();
+      //sim808_flush_serial();
+      clearCurrentError(NO_GPRS_SIGNAL);
+
+     Serial.print("GPSsync: ");
+     timeGetGPS = ((unsigned long) (millis() - timerStart))/1000UL;
+     Serial.println(timeGetGPS);
+     Serial.println((unsigned long) (millis() - timerStart));
+
       return true;
      }
     if ((unsigned long) (millis() - timerStart) > timeout * 1000UL) {
       sim808_clean_buffer(gprsBuffer,64);
-      sim808_flush_serial();
+      //sim808_flush_serial();
+      setCurrentError(NO_GPRS_SIGNAL);
       return false;
     }

-    delay(10000);
+    delay(5000);
     //sim808_flush_serial();
   }
  }
@@ -695,7 +839,7 @@
   if(sim808.readable()) {
     sim808_read_buffer(gprsBuffer,24,DEFAULT_TIMEOUT);
     currentRadioSig = getSignalQuality(gprsBuffer);
-    Serial.print("sig:");
+    Serial.print("SIG:");
     Serial.println(currentRadioSig);
   }
   sim808_clean_buffer(gprsBuffer,64);
@@ -708,25 +852,31 @@
  * 0                   1                  initGPRS e send data
  * 1                   1                  nao faz nada e send data
  *******************************************************************/
-  sim808_send_cmd("AT+CIPSTATUS\r\n");
+  //sim808_send_cmd("AT+CIPSTATUS\r\n");
   if(sim808.readable()) {
+    sim808_send_cmd("AT+CIPSTATUS\r\n");
     sim808_read_buffer(gprsBuffer,64,DEFAULT_TIMEOUT);
     //Serial.print(gprsBuffer);
   }
   if(currentRadioSig <= 7) {
        Serial.println("NOGPRSsig");
        sim808_send_cmd("AT+CDNSGIP=\"ardugps.hopto.org\"\r\n");
-       previousRadioSig = currentRadioSig;
+       previousRadioSig = currentRadioSig;
+
+       setCurrentError(NO_GPRS_SIGNAL);
        return NO_GPRS_SIGNAL;            //error of weak signal or DNS failed
   }else{                                 //radio signal > 7
+    clearCurrentError(NO_GPRS_SIGNAL);
     if(previousRadioSig > 7){            //signal still good
       previousRadioSig = currentRadioSig;
     }else {                              //signal recovered
-      error = InitGPRS();
+      error = InitGPRS(RUNNING_TIME);   //errors already logged with setCurrentError(error) inside this InitGPRS
       previousRadioSig = currentRadioSig;
       if(error > 0) {                    //initGPRS failed
         Serial.print("GPRSfail: ");
         Serial.println(error);
+
+
         return error;
       }
       Serial.println("GprsInitOK");
@@ -737,18 +887,25 @@

   //get the local ip number
   //GPRS.println("AT+CIFSR");
+  //if(sim808.readable()) {
   sim808_send_cmd("AT+CIFSR\r\n");
+  //}
   delay(50);
+  //if(sim808.readable()) {
   sim808_send_cmd("AT+CDNSGIP=\"ardugps.hopto.org\"\r\n");
+  //}
+  //sim808_flush_serial();
   delay(50);

   //start a connection to TCP to URL and port
   if (prot == TCP){
     if(!SendCIPSTART(TCP)){            //TCP protocol
+      setCurrentError(START_GPRS_TCP_FAIL);
       return START_GPRS_TCP_FAIL;      //"AT+CIPSTART => FAIL";
     }
   }else {                              //UDP protocol
     if(!SendCIPSTART(UDP)){
+      setCurrentError(START_GPRS_UDP_FAIL);
       return START_GPRS_UDP_FAIL;      //"AT+CIPSTART => FAIL";
     }
   }
@@ -768,24 +925,29 @@
   strcat(data2db,",");
   strcat(data2db,Speed);

-  Serial.println("valor de data2db: ");
-  Serial.println(data2db);
+//  Serial.println("valor de data2db: ");
+//  Serial.println(data2db);

   if(!SendDataCIPSEND(data2db,sizeof(data2db))){
     if(prot == TCP){                  //TCP protocol
       if(!SendCIPSTART(TCP)){         //Trying to restart TCP protocol
+
+        setCurrentError(START_GPRS_TCP_FAIL);
         return START_GPRS_TCP_FAIL;
       }

       //delay(1000);
       delay(100);
       if(!SendDataCIPSEND(data2db,sizeof(data2db))){    //Trying to resend TCP data
+
+        setCurrentError(SEND_TCP_DATA_FAIL);
         return SEND_TCP_DATA_FAIL;                      //"CIPSEND =>RESEND FAIL"
       }

     }else{                             //UDP protocol
+      setCurrentError(SEND_UDP_DATA_FAIL);
       return SEND_UDP_DATA_FAIL;
     }
   }
@@ -796,6 +958,9 @@
     sim808_check_with_cmd("AT+CIPCLOSE\r\n", "CLOSE OK\r\n", CMD);
     //Serial.println("Uno have disconnected from Server");
   }
+
+  clearAllError(); //the routine proceed successfully, no error occured
+                   //only place to clear all errors

   return 0; // no error on GPRS

@@ -807,6 +972,7 @@
 boolean SendCIPSTART (Protocol ptl)
 {
   //char bufferC[30];
+  //sim808_check_with_cmd(F("AT\r\n"),"OK",CMD);

   if(ptl == TCP) {
     if(!sim808_check_with_cmd("AT+CIPSTART=\"TCP\",\"ardugps.hopto.org\",6789\r\n","OK\r\n",CMD)){
@@ -818,20 +984,25 @@
   }
   else {
     if(ptl == UDP) {
-      if(!sim808_check_with_cmd("AT+CIPSTART=\"UDP\",\"ardugps.hopto.org\",6789\r\n","ERROR\r\n\r\nALREADY CONNECT\r\n",CMD)){
-        return false;
-      }
-      else {
-
-        //void sim808_read_buffer(char *buffer, int count, unsigned int timeout, unsigned int chartimeout)
-        /*sim808_send_cmd("AT+CDNSGIP=\"ardugps.hopto.org\"\r\n");
-        sim808_read_buffer(bufferC,30,5,500);
-        Serial.println("Result of CDNSGIP");
-        Serial.println(bufferC);*/
-
-
-        return true;
-      }
+
+      delay(1000);
+      sim808_clean_buffer(gprsBuffer,64);
+      sim808_send_cmd("AT+CIPSTART=\"UDP\",\"ardugps.hopto.org\",6789\r\n");
+      return true;
+//      sim808_read_buffer(gprsBuffer,64,DEFAULT_TIMEOUT);
+//      //}
+//      Serial.print("buffer4: ");
+//      Serial.println(gprsBuffer);
+//      if(strstr(gprsBuffer,"CONNECT OK")){
+//        return true;
+//      }else{
+//        //if(strstr(gprsBuffer,"ALREADY CONNECT")){
+//        if(strstr(gprsBuffer,"ALREADY")){
+//          return true;
+//        }else{
+//          return false;
+//        }
+//      }
     }
     else {
       return false;
@@ -968,8 +1139,8 @@
    if(token != NULL) {
       strncpy(latitude,token,sizeof(latitude));
       latitude[sizeof(latitude)-1] = '\0';
-      Serial.print("LATITUDE        : ");
-      Serial.println(latitude);
+//      Serial.print("LATITUDE        : ");
+//      Serial.println(latitude);
    }else return false;

    //Get North or South
@@ -987,8 +1158,8 @@
    if(token != NULL) {
       strncpy(longitude,token,sizeof(longitude));
       longitude[sizeof(longitude)-1] = '\0';
-     // Serial.print("LONGITUDE       : ");
-      //Serial.println(longitude);
+//      Serial.print("LONGITUDE       : ");
+//      Serial.println(longitude);

    }else return false;

@@ -1182,6 +1353,91 @@

 /********************************************************************************
+* GPSAnalyzer128(infoLocation);
+* GPZDA
+* AT+CGPSINF=128
+* at+cgpsinf=128
+* +CGPSINF: 128,045140.000,02,11,2017,00,00
+* Message ID          : $GPZDA = 128 (ZDA protocol header)
+* UTC Time            : hhmmss.sss
+* Day                 : Day of month 1-31
+* Month               : Month of the year 1-12
+* Year                : 1980-2079
+* Local zone hour     : hour (offset from UTC set to 0)
+* Local zone minutes  : minute (offset from UTC set to 0)
+* Checksum            : knots
+* <CR><LF>            : end of message
+ ********************************************************************************/
+boolean GPSAnalyzer128() {
+   char *token;
+  //delay(8000);  //5000 no GPS data 10 times
+  sim808_clean_buffer(gprsBuffer,sizeof(gprsBuffer));
+  sim808_send_cmd("AT+CGPSINF=128\r\n");
+  sim808_read_buffer(gprsBuffer,55,DEFAULT_TIMEOUT);
+
+
+   /* get the first token */
+   Serial.println("****************Content of gpsBuffer*******************");
+   Serial.println("valor do buffer :");
+   Serial.println(gprsBuffer);
+
+   //Get Command sent AT_CGPSINF=128
+   token = strtok(gprsBuffer,"\n\r" );
+   if(token == NULL)  return false;
+
+   //Get "+CGPSINF:" string
+   token = strtok(NULL, ":");
+   if(token == NULL)  return false;
+
+   //Get CGPSINF value 128
+   token = strtok(NULL, ",");
+
+   //Get time and create string of time and date "hhmmss.sss-dd-mm-yyyy";
+   token = strtok(NULL, ",");
+   if(token != NULL){
+       strncpy(startDateTime,token,sizeof(startDateTime)); //Time
+       strcat(startDateTime,"-");
+   }else{
+     return false;
+   }
+
+   //Get Day and create string of time and date "hhmmss.sss-dd-mm-yyyy";
+   token = strtok(NULL, ",");
+   if(token != NULL){
+       //strncpy(startDateTime,token,sizeof(startDateTime)); //Time
+       strcat(startDateTime,token);
+       strcat(startDateTime,"-");
+   }else{
+     return false;
+   }
+
+   //Get Month and create string of time and date "hhmmss.sss-dd-mm-yyyy";
+   token = strtok(NULL, ",");
+   if(token != NULL){
+       //strncpy(startDateTime,token,sizeof(startDateTime)); //Time
+       strcat(startDateTime,token);
+       strcat(startDateTime,"-");
+   }else{
+     return false;
+   }
+
+   //Get Year and create string of time and date "hhmmss.sss-dd-mm-yyyy";
+   token = strtok(NULL, ",");
+   if(token != NULL){
+       //strncpy(startDateTime,token,sizeof(startDateTime)); //Time
+       strcat(startDateTime,token);
+       startDateTime[sizeof(startDateTime)-1] = '\0';
+   }else{
+     return false;
+   }
+
+   Serial.println("startDateTime:");
+   Serial.println(startDateTime);
+   return true;
+}
+
+
+/********************************************************************************
 * GPVTG
 * AT+CGPSINF=64
 * +CGPSINF: 64,299.79,T,,M,0.072,N,0.133,K,A
@@ -1201,4 +1457,54 @@
 *                 R = Coarse Position
 ********************************************************************************/

+
+/****************************************************************************
+ * storeLog(int add, char *val)
+ * UNO memory 1K
+ * Param
+ * add address to write data
+ * val value to write
+ ****************************************************************************/
+ int storeData(int add, byte val){
+  int addTemp;
+  addTemp = add;
+
+  EEPROM.write(add, char(val));
+
+  addTemp = addTemp + 1;
+  if (addTemp == EEPROM.length()) {
+    addTemp = 0;
+  }
+  return  addTemp;
+ }
+
+/****************************************************************************
+ * voi storeString(
+ *
+ ***************************************************************************/
+int storeString(int add, char *val){
+  int addNext, addCurr;
+  char * name = val;
+  int size = 0;
+
+  while(true)
+  {
+    if(*(val + size) == '\0') // returns 5...
+      break;
+
+     size++;
+  }
+  addCurr=add;
+  addNext = add + size;
+  if (addNext >= EEPROM.length()) { //data do not fit EEPROM
+    addCurr = 0;
+    addNext = addCurr + size;
+  }
+
+  for(int j=0;j<size;j++){
+    EEPROM.write(addCurr,name[j]);
+    addCurr++;
+  }
+  return addNext;
+}


Update ArduinoMotionStairLights.ino

Update ArduinoMotionStairLights.ino

Increased data type size in order to support more leds.   I do not have enough leds to test this.

--- ArduinoMotionStairLights.ino
+++ ArduinoMotionStairLights.ino
@@ -1,7 +1,7 @@
 /*
  * Description: Motion activated stair lights.
  * Author: Dean Montgomery
- * Version: 2.4
+ * Version: 2.5
  *
  * Date: Feb 17, 2018
  *
@@ -27,10 +27,10 @@
 #define GO_UP -1                // Direction control - Arduino at top of stairs
 #define GO_DOWN 1               // Direction control - Arduino at top of stairs
 uint8_t gHue = 0;               // track color shifts.
-int8_t  gStair = 0;             // track curent stair.
-int8_t  gStairLeds = 0;         // tracking lights per stair.
+int16_t gStair = 0;             // track curent stair.
+int16_t gStairLeds = 0;         // tracking lights per stair.
 uint8_t gBright = 0;            // track brightness
-uint8_t gUpDown[NUM_LEDS];      // directional array to walk/loop up or down stairs.
+uint16_t gUpDown[NUM_LEDS];     // directional array to walk/loop up or down stairs.
 int8_t  gupDownDir = 1;         // direction of animation up or down
 CRGB    leds[NUM_LEDS];         // setup leds object to access the string
 CRGBPalette16 gPalette;         // some favorite and random colors for display.
@@ -39,14 +39,13 @@
                                 CRGB( BRIGHTNESS, 0, 0));
 CRGBPalette16 z;
 int8_t gLastPalette = 15;       // track last chosen palette.
-uint8_t gLastWalk = 1;
 unsigned long currentMillis = millis(); // define here so it does not redefine in the loop.
 long previousMillis = 0;
 long previousOffMillis = 0;     // countdown power off timer
 long offInterval = 30000;       // 1000mills * 30sec
 long effectInterval = 40;
-enum Effects { ewalk, eflicker, efade6 };
-Effects effect = ewalk;
+enum Effects { effectWalk, effectFlicker, effectFade6 };
+Effects effect = effectWalk;
 enum WalkEffects { sparkle, pulsate1, pulsate2, flash };
 WalkEffects walk_effect = sparkle;
 // Stages of the animation.  Allows for PIR sensor to re-activation the run stage of the animation.
@@ -54,11 +53,10 @@
 Stage stage = off;
 int i = 0;
 int x = 0;
-uint8_t var = 0;
-uint8_t valTop = 200;
+uint8_t topBrightness = 200;  // May preserve LED life if not running at full brightness 255?
 uint8_t rnd = 0;
-uint8_t r = 0, g = 0, b = 0, h = 0, s = 0, v = 0;
-int8_t stair = 0;
+uint8_t r = 0, g = 0, b = 0, h = 0, s = 0, v = 0; // red green blue hue sat val
+int16_t stair = 0;
 CRGB c1;
 CRGB c2;
 CRGB trans;
@@ -122,22 +120,22 @@
 void chooseEffects(){
   randomSeed(millis());
   r = random8(1, 255);
-  //effect = efade6; return;  // temporarily force effect for debugging: ewalk, eflicker, efade6
+  //effect = effectFlicker; return;  // temporarily force effect for debugging: effectWalk, effectFlicker, effectFade6
   if ( r >= 0 && r <= 100 ){
-    effect = ewalk;  // My favorite transition with random effect variations
+    effect = effectWalk;     // My favorite transition with random effect variations
   } else if ( r > 100 && r <= 175 ){
-    effect = eflicker;  // Candle with embers.
+    effect = effectFlicker;  // Candle with embers.
   } else {
-    effect = efade6;  // hueshift rainbow.
+    effect = effectFade6;    // hueshift rainbow.
   }
 }

 void update_effect(){
-  if ( effect == ewalk ){
+  if ( effect == effectWalk ){
     walk();
-  } else if ( effect == eflicker ){
+  } else if ( effect == effectFlicker ){
     flicker();
-  } else if ( effect == efade6 ){
+  } else if ( effect == effectFade6 ){
     fade();
   }
 }
@@ -199,7 +197,7 @@
 void walk() {

   if ( stage == stage_init ){
-    valTop = 200;
+    topBrightness = 200;
     // Pick two colors from the palette.
     choosePalette();
     c1 = gPalette[gLastPalette];
@@ -276,7 +274,7 @@
     gStair = 0;
     stage = stage_dim;
   } else if ( stage == stage_dim ) {
-    if ( gBright <= valTop  ) {
+    if ( gBright <= topBrightness  ) {
       if ( gStair <= ( NUM_LEDS - LEDS_PER_STAIR ) ){
         for ( gStairLeds=0; gStairLeds < LEDS_PER_STAIR; gStairLeds++ ){
           leds[gUpDown[gStair + gStairLeds]].fadeToBlackBy( 6 );
@@ -356,7 +354,7 @@
     EVERY_N_MILLISECONDS( 20 ) { gHue++; }
   }
   for (int tick=0; tick < 64; tick++){
-    for ( uint8_t i = 0; i < NUM_LEDS; i++ ){
+    for ( uint16_t i = 0; i < NUM_LEDS; i++ ){
       leds[i].fadeToBlackBy( 64 );
       FastLED.show();
       FastLED.delay(1);


Changed bencode write to use Serial.write versus Serial.print


Got conveyors running at different speeds

--- hardware/scanner-sorter/multiStepper/multiStepper.ino
+++ hardware/scanner-sorter/multiStepper/multiStepper.ino
@@ -10,7 +10,7 @@
 #include <AccelStepper.h>
 #include <AFMotor.h>

-int motor_speed = 750;
+int motor_speed = 200;
 // two stepper motors one on each port
 AF_Stepper motor1(48, 1);
 AF_Stepper motor2(48, 2);
@@ -18,17 +18,17 @@
 // you can change these to DOUBLE or INTERLEAVE or MICROSTEP!
 // wrappers for the first motor!
 void forwardstep1() {
-  motor1.onestep(FORWARD, INTERLEAVE);
+  motor1.onestep(FORWARD, DOUBLE);
 }
 void backwardstep1() {
-  motor1.onestep(BACKWARD, INTERLEAVE);
+  motor1.onestep(BACKWARD, DOUBLE);
 }
 // wrappers for the second motor!
 void forwardstep2() {
-  motor2.onestep(FORWARD, INTERLEAVE);
+  motor2.onestep(FORWARD, DOUBLE);
 }
 void backwardstep2() {
-  motor2.onestep(BACKWARD, INTERLEAVE);
+  motor2.onestep(BACKWARD, DOUBLE);
 }

 // Motor shield has two motor ports, now we'll wrap them in an AccelStepper object


minor changes

minor changes

--- Twisted_Python_Server_Serial/workingPythonSerialMotorControl_v2/workingPythonSerialMotorControl_v2/workingPythonSerialMotorControl_v2.ino
+++ Twisted_Python_Server_Serial/workingPythonSerialMotorControl_v2/workingPythonSerialMotorControl_v2/workingPythonSerialMotorControl_v2.ino
@@ -13,7 +13,7 @@
 }

 void loop() {
-
+
   if (commandComplete) {

     car.setSpeed(speed);
@@ -34,41 +34,58 @@
  */
 void serialEvent() {
   int i = 0;
-  int speed
   byte tmp;
   byte byteArray[7];
+  for(int i = 0; i < 7; i++){
+    byteArray[i] = 0;
+    }
   while (Serial.available()) {

     byte b = Serial.read();
-
+
     byteArray[i] = b;
     if (b == 0x0d){
       tmp = 0x0d;
     }
-    if(b == 0x0a && tmp == 0x0d){
+    if(b == 0x0a && tmp == 0x0d)
+    {
        Serial.println("got CRLF");
        handleMsg(byteArray);
      }
+
     i++;
   }
+  for(int j = 0; j < 7; j++){
+    Serial.write(byteArray[j]);
+    handleMsg(byteArray);
+  }
+
 }

 void handleMsg(byte arr[])
 {
-    if(arr[1] == 0x46)
+    Serial.println("handleMSG");
+    Serial.write(arr[1]);
+
+
+    if(arr[1] == 70)
     {
+      Serial.println("F");
       speed = arr[3];
     }
     else if(arr[1] == 0x42)
     {
+      Serial.println("B");
       speed = -arr[1];
     }
     if(arr[2] == 0x52)
     {
+      Serial.println("R");
       angle = arr[4];
     }
     else if(arr[2] == 0x4c)
     {
+      Serial.println("L");
       angle = -arr[4];
     }
     commandComplete = true;


Add report and control of temp_ctrl

Add report and control of temp_ctrl

--- arduino/sketch_tc/sketch_tc.ino
+++ arduino/sketch_tc/sketch_tc.ino
@@ -31,16 +31,17 @@
 #define PIN_ON_OFF 9
 #define PIN_MODE 10
 #define PIN_FAN 11
-#define PIN_ADD_TEMP 12
-#define PIN_DEC_TEMP 13
+#define PIN_INC 12
+#define PIN_DEC 13

 #define MIN_ANALOG_V 96
 #define MAX_ANALOG_V 928

-#define MAX_STABLE_CNT 32 /* 去除波动，这么多次数据不变后才上报状态 */
-
-
-const char *g_devid = "air-condition_0";
+#define MAX_STABLE_CNT 32 /* 去除波动，MAX_STABLE_CNT 次数据不变后才上报状态 */
+
+#define SIM_BTN_DELAY 32
+
+const char *g_devid = "temp_ctrl_0";

 uint8_t g_header[HEADER_LEN];
 uint8_t g_buf[BUF_LEN];
@@ -141,8 +142,29 @@
     return;
   }

-  if (strcmp(root["cmd"], "ac_set") == 0) {
-  } else if (strcmp(root["cmd"], "ac_get") == 0) {
+  Serial.println((const char *)root["cmd"]);
+
+  if (strcmp(root["cmd"], "on_off") == 0) {
+    digitalWrite(PIN_ON_OFF, LOW);
+    delay(SIM_BTN_DELAY);
+    digitalWrite(PIN_ON_OFF, HIGH);
+  } else if (strcmp(root["cmd"], "mode") == 0) {
+    digitalWrite(PIN_MODE, LOW);
+    delay(SIM_BTN_DELAY);
+    digitalWrite(PIN_MODE, HIGH);
+  } else if (strcmp(root["cmd"], "fan") == 0) {
+    digitalWrite(PIN_FAN, LOW);
+    delay(SIM_BTN_DELAY);
+    digitalWrite(PIN_FAN, HIGH);
+  } else if (strcmp(root["cmd"], "inc") == 0) {
+    digitalWrite(PIN_INC, LOW);
+    delay(SIM_BTN_DELAY);
+    digitalWrite(PIN_INC, HIGH);
+  } else if (strcmp(root["cmd"], "dec") == 0) {
+    digitalWrite(PIN_DEC, LOW);
+    delay(SIM_BTN_DELAY);
+    digitalWrite(PIN_DEC, HIGH);
+  } else if (strcmp(root["cmd"], "get") == 0) {
     g_need_report = 1;
   }
 }
@@ -163,7 +185,13 @@
   root["devid"] = g_devid;

   JsonArray& st = root.createNestedArray("status");
-
+
+  st.add(g_on_off);
+  st.add(g_mode);
+  st.add(g_fan);
+  st.add(g_set_temp);
+  st.add(g_room_temp);
+
   g_body_len = root.printTo((char *)g_buf + HEADER_LEN, BUF_LEN - HEADER_LEN);

   send_msg();
@@ -414,15 +442,15 @@
   DDRB &= B11111110;

   pinMode(PIN_ON_OFF, OUTPUT);
-  digitalWrite(PIN_ON_OFF, LOW);
+  digitalWrite(PIN_ON_OFF, HIGH);
   pinMode(PIN_MODE, OUTPUT);
-  digitalWrite(PIN_MODE, LOW);
+  digitalWrite(PIN_MODE, HIGH);
   pinMode(PIN_FAN, OUTPUT);
-  digitalWrite(PIN_FAN, LOW);
-  pinMode(PIN_ADD_TEMP, OUTPUT);
-  digitalWrite(PIN_ADD_TEMP, LOW);
-  pinMode(PIN_DEC_TEMP, OUTPUT);
-  digitalWrite(PIN_DEC_TEMP, LOW);
+  digitalWrite(PIN_FAN, HIGH);
+  pinMode(PIN_INC, OUTPUT);
+  digitalWrite(PIN_INC, HIGH);
+  pinMode(PIN_DEC, OUTPUT);
+  digitalWrite(PIN_DEC, HIGH);
 }

 void loop() {
@@ -434,7 +462,7 @@

   if (g_need_report) {
     print_status();
-//    report_status();
+    report_status();
     g_need_report = 0;
   }


Changed timings in actuators

Changed timings in actuators

--- sw/receiver/receiver.ino
+++ sw/receiver/receiver.ino
@@ -80,14 +80,19 @@
   pinMode(MOTOR_1, OUTPUT);
   pinMode(MOTOR_2, OUTPUT);

+  pinMode(A3, OUTPUT);
+
   // Inital state is OFF
   current_state = false;
   setSolenoidState(false);
 }

 void loop(void) {
+  digitalWrite(A3, HIGH);
   // Radio must be awake to send data.
   radio.powerUp();
+
+  goToSleep(WDTO_30MS);

   // Populate request packet with current information.
   packet.command = 0xF5;
@@ -110,12 +115,6 @@
     // Read it
     radio.read(&packet, RF24_PAYLOAD);

-    // TODO: validate packet
-
-    // Debug LED flashing
-    setSolenoidState(true);  goToSleep(WDTO_60MS);
-    setSolenoidState(false); goToSleep(WDTO_120MS);
-
     // If basestation says that the state changed, then change it.
     if (packet.state != current_state) {
       // Change the state only the first time
@@ -129,8 +128,10 @@
   // It's done. Now, rest.
   radio.powerDown();

-  // Make the mcu sleep for about 8 seconds.
-  goToSleep(WDTO_8S);
+  digitalWrite(A3, LOW);
+
+  // Make the mcu sleep for about 1 seconds.
+  goToSleep(WDTO_1S);
 }

 // -----------------------------------------
@@ -160,10 +161,10 @@
 /**
 */
 void setSolenoidState(bool open) {
-  digitalWrite(MOTOR_1, !open); // LOW if open
-  digitalWrite(MOTOR_2,  open); // HIGH if open
-
-  goToSleep(WDTO_120MS);
+  digitalWrite(MOTOR_1,  open); // HIGH if open
+  digitalWrite(MOTOR_2, !open); // LOW  if open
+
+  goToSleep(WDTO_60MS);

   digitalWrite(MOTOR_1, LOW);
   digitalWrite(MOTOR_2, LOW);


Update dht22_ds18b20.ino

Update dht22_ds18b20.ino

--- dragino/dht22_ds18b20.ino
+++ dragino/dht22_ds18b20.ino
@@ -50,6 +50,7 @@

 void loop() {
+ delay(2000);
   float h = dht.readHumidity();
   float t = dht.readTemperature();


Added some extra comments.

Added some extra comments.

--- Elcano_C2_DriveByWire/Elcano_C2_DriveByWire.ino
+++ Elcano_C2_DriveByWire/Elcano_C2_DriveByWire.ino
@@ -75,7 +75,7 @@

 volatile int Stop = TRUE;
-volatile unsigned long TimeOfStopButton_ms;
+volatile unsigned long TimeOfStopButton_ms; //Records the millis() value when stop was last pressed
 volatile int Cruise = FALSE;
 volatile unsigned long TimeOfCruiseButton_ms;
 const int PauseTime_ms = 4000;
@@ -138,50 +138,68 @@
      int FeedbackPin;
      int CurrentPin;
      int CloseEnough;  // in counts; Try for 0-1023
-     int Stuck;        // max number of time steps for not getting to position
+     int Stuck;        // max number of time steps for not getting to position before giving up
      int StepSize;     // controls how quickly the servo moves. 2"/sec servo max
      int QuiescentCurrent;  // Nominally 120 counts
      int CurrentDraw;  // In counts, with 1 Amp = 12 counts
      int CurrentLimit;  // In counts
      // One count from analog input is about 5mV from ACS758lcb050U
      // The ACS758 has sensitivity of 60 mA/V
+     //This does not actually move TO a position, it moves a distance of StepSize towards the position.
+	 //Returns the actual sensed position
      int move(int desired_position)
      {
          int Position = desired_position;    // 0 to 1023
          Feedback = analogRead(FeedbackPin);  // 0 to 1023
+		 //If the sensor says the current position is less than the desired position
+		 //Than go one step towards it.
          if (desired_position > Feedback)
          {
             Position = min(desired_position, Feedback + StepSize);
+			//But do't go any farther than the limit(Use a const here?)
             Position = min (Position, 1023);
          }
+		 //Position>Desired
          else
          {
+			//Go one step just like above and don't exceed limit.
             Position = max(desired_position,  Feedback - StepSize);
             Position = max(0, Position);
          }
+		 //Map the range of the position variable to the expected duty cycle range of the actuator
          int PWMPosition = 127 + Position/8;
          analogWrite(SignalPin, PWMPosition);  // 0 to 255
+		 //debug prints. []Should this be in an ifdef?
          Serial.print(desired_position); Serial.print(", ");
          Serial.print(Feedback); Serial.print(", ");
          Serial.print(Position); Serial.print(", ");
          Serial.println(PWMPosition);
         return Position;
      }
+	//--Currently non-functioning, is a no-op--
+	//Actually go to a position and block util there
      void home(int desired_position)
      {
        return;
        int feedback_after, Position;
        int no_move_count = 0;
+    //Loop while not CloseEnough
        do
        {
          Serial.print("Home ");
          Position = move (desired_position);
          delay(STEP_SIZE_ms);
          feedback_after = analogRead(FeedbackPin);
+		 //If we detect that we have not moved, increment safety counter
+		 //Otherwise reset to zero.
+		 //If somehow it just moved back and forth but never got there
+		 //This could block forever.
          if (abs(feedback_after - Feedback) <= CloseEnough)
            no_move_count++;
          else
+
            no_move_count = 0;
+		//Return if we are stuck []Return error code?
          if (no_move_count > Stuck)
            return;
        } while ((abs(desired_position - Feedback) > CloseEnough));
@@ -190,6 +208,7 @@
  /*---------------------------------------------------------------------------------------*/
 void setup()
 {
+        //Set up pin modes and interrupts, call serial.begin and call initialize.
         pinMode(ReverseButton, INPUT);
         pinMode(CruiseReverse, INPUT);
         pinMode(StopButton, INPUT);  // via interrupt
@@ -275,6 +294,7 @@
         Instrument[Brakes].MinPosition = 85;  // anolog read range is 0 to 1023
         Instrument[Brakes].MaxPosition = 800;

+        //Load current positions from the actual sensors
         Instrument[Motor].Feedback =
           analogRead(Instrument[Motor].FeedbackPin);
          Instrument[Steering].Feedback =
@@ -377,7 +397,9 @@
   static unsigned long EndTime = 0;
   static unsigned long OutsideTime;

+//Calculate how much time was spent outside the loop
   OutsideTime = EndTime - TimeNow;
+//Read the user inputs for the enable switches
   Instrument[Motor].Enabled = digitalRead(EnableMotor);
   Instrument[Brakes].Enabled = digitalRead(EnableBrake);
   Instrument[Steering].Enabled = digitalRead(EnableSteer);
@@ -395,6 +417,9 @@
   StateTransition(Brakes);
   StateTransition(Steering);

+  //Motor stuff
+
+  //This logic determines the source of LastCommand
   if (Instrument[Motor].State == ManualGo)
   {
    Instrument[Motor].LastCommand = Instrument[Motor].Joystick;
@@ -407,8 +432,9 @@
   {
     Instrument[Motor].LastCommand = MinimumThrottle;
   }
+   //Whatever the logic says, move a step towards it.
    Instrument[Motor].move(Instrument[Motor].LastCommand);
-
+//Brakes stuff
   if (Instrument[Brakes].State == ManualGo)
   {
    Instrument[Brakes].LastCommand = Instrument[Brakes].Joystick;
@@ -423,6 +449,7 @@
   }
    Instrument[Brakes].move(Instrument[Brakes].LastCommand);

+//Steering stuff
    if (Instrument[Steering].State == ManualGo)
   {
    Instrument[Steering].LastCommand = Instrument[Steering].Joystick;
@@ -447,7 +474,7 @@
    else
      digitalWrite(CruiseLED, LOW);

-  checkReverse();
+  checkReverse();  //Logic to handle the reverse button.
 #endif  // TEST_MODE
  // TODO: Check out loop speed;
  // make loop faster
@@ -475,9 +502,11 @@
   const int deadBandLow = 32;  // out of 1023
   const int deadBandHigh = 32;
   center = 511; // analogRead(JoystickCenter);
+  //Calculate deadband info
   int tinyDown = center - deadBandLow;
   int tinyUp = center + deadBandHigh;

+ //This appears to make it pause(ignore input?) for PauseTime_ms after the button press
     if (Stop && (millis() < TimeOfStopButton_ms + PauseTime_ms))
     {
       Instrument[Motor].StickMoved = FALSE;
@@ -486,21 +515,26 @@
       return;
     }
     stick = 511; // analogRead(AccelerateJoystick);
+//If stick did not move more than the "up"	deadband.
     if (stick <= tinyUp)  // 543
     {
+		//stick not outside deadBand
       Instrument[Motor].Joystick = 0;
       Instrument[Motor].StickMoved = FALSE;
     }
     else
     {
+		//stick outside of deadband
       Instrument[Motor].Joystick = MinimumThrottle + (FullThrottle - MinimumThrottle)
        * (stick - tinyUp) / (1023 - tinyUp);
       Instrument[Motor].StickMoved =  TRUE;
       Stop = FALSE;
     }

+	//Check if Stick moved beyone "down" deadBand
     if (stick >= tinyDown)
     {
+		//Stick still in deadband
       Instrument[Brakes].Joystick = 0;
       Instrument[Brakes].StickMoved =  FALSE;
     }
@@ -511,8 +545,11 @@
       Instrument[Brakes].StickMoved =  TRUE;
       Stop = FALSE;
     }
+//This line appears to be changed in for testing
+//read the steering pot in the joystick

     stick = 511; // 1023 - analogRead(SteerJoystick);
+	//If the stick is still in the left-right deadband
     if (stick > tinyDown && stick <= tinyUp)
     {
       Instrument[Steering].Joystick = Straight;
@@ -520,6 +557,7 @@
     }
     else if (stick > tinyUp)
     {
+		//Stick moved past "up" deadband limit
       Instrument[Steering].Joystick = Straight + (HardRight - Straight) * (stick - tinyUp) / (1023 - tinyUp);
       Instrument[Steering].StickMoved =  TRUE;
       Stop = FALSE;
@@ -616,10 +654,13 @@
    ReversePushed = digitalRead(ReverseButton);
    if (ReversePushed)
    {
+	//If we are in motor=manual stop and the reverse button is pressed
      TimeNow = millis();
+	 //If the reverse button has not been pressed in the last 2000ms
      if (TimeNow > TimeOfReverseButton_ms + 2000)
      {
          TimeOfReverseButton_ms = TimeNow;
+		 //Toggle reversed state
          Forward = !Forward;
      }
    }


Update Navigation_Array.ino

Update Navigation_Array.ino

--- Arduino/Navigation_Array.ino
+++ Arduino/Navigation_Array.ino
@@ -212,4 +212,3 @@

   Serial.println();
 }
-


discovered motors do not like be run at low speeds

--- L9110_hbridge/L9110_libtest/L9110_libtest.ino
+++ L9110_hbridge/L9110_libtest/L9110_libtest.ino
@@ -19,8 +19,8 @@
   L9110.motorA(1,127); //run both motors forward at half speed
   L9110.motorB(1,127);
   delay(5000);
-  L9110.motorA(1,127); //run motors at half speed in opposite directions
-  L9110.motorB(0,127);
+  L9110.motorA(1,255); //run motors at half speed in opposite directions
+  L9110.motorB(0,255);
   delay(5000);
   L9110.motorA(0,0); //full stop on both motors
   L9110.motorB(0,0);


Now driving 30 LEDs

Now driving 30 LEDs

It requires a little work
Some of the LEDs that I thought I was turning on don't turn on

Signed-off-by: nisha <ba6353e519422079c5746796dcd035c620a84798@gmail.com>


asString on processing_info

asString on processing_info

--- _56-gopro-control/a-91-config-on-rtc/a-91-config-on-rtc.ino
+++ _56-gopro-control/a-91-config-on-rtc/a-91-config-on-rtc.ino
@@ -1552,7 +1552,7 @@
       }
     } else {
       if (root.containsKey("media_id_string")) {
-        if (media_id == root["media_id_string"]) {
+        if (media_id == root["media_id_string"].asString()) {
           if (root.containsKey("processing_info")) {
             rtc_boot_mode.attempt_this  = 0;
             rtc_boot_mode.twitter_phase = 5;
@@ -1808,7 +1808,12 @@

 /* PHASE 5 : STATUS CHECK */
 void tweet_check() {
+  lcd.clear();
+  lcd.setCursor(0, 0);
+  lcd.print("[P:5] CHECKING");
   rtc_boot_mode.twitter_phase++;
+  saveConfig_helper();
+  delay(2000);
 }

 /* PHASE 4 : FINALIZE */


バグ対策・論理誤り

バグ対策・論理誤り

--- 1_practice/esp32_27_goo_lcd2/esp32_27_goo_lcd2.ino
+++ 1_practice/esp32_27_goo_lcd2/esp32_27_goo_lcd2.ino
@@ -167,7 +167,7 @@
         lcdisp(buf[0]);                     // 1行目に1件目の予定を表示
         lcdisp(buf[buf_i],1);               // 2行目に2件目以降の予定を表示
     }
-    if(sec%20 == 0) return;                 // 以下は20秒に1回(1分間に3回実行)
+    if(sec%20 != 0) return;                 // 以下は20秒に1回(1分間に3回実行)
     for(int i=0;i<8;i++){
         if(!strncmp(date+11,buf[i],5)){     // 予定の時刻と一致
             if(!chime) chime = 2;                   // chimeの値が0のとき2に設定


Adds enable pin to the example and disables forced init success.

Now adds an example pin which is set to high for use with TI's chips.
Also ensures that the initialisation is actually successful before trying
to request PID's.

--- examples/reader_softserial/reader_softserial.ino
+++ examples/reader_softserial/reader_softserial.ino
@@ -1,12 +1,13 @@
 #include "Arduino.h"
 // Be sure that the AltSoftSerial library is available, download it from http://www.pjrc.com/teensy/td_libs_AltSoftSerial.html"
-#include <AltSoftSerial.h>
+#include "AltSoftSerial.h"

 #include "OBD9141.h"

-#define RX_PIN 8
-#define TX_PIN 9
+#define RX_PIN 8  // connect to transceiver Rx
+#define TX_PIN 9  // connect to transceiver Tx
+#define EN_PIN 10  //  pin will be set high (connect to EN pin of SN65HVDA100)

 AltSoftSerial altSerial;

@@ -16,6 +17,8 @@
 void setup(){
     Serial.begin(9600);
     delay(2000);
+    pinMode(EN_PIN, OUTPUT);
+    digitalWrite(EN_PIN, HIGH); // enable the transceiver IC.

     obd.begin(altSerial, RX_PIN, TX_PIN);

@@ -28,7 +31,10 @@
     Serial.print("init_success:");
     Serial.println(init_success);

-    init_success = true; // assume that the init was a success (for example with the simulator)
+    //init_success = true;
+    // Uncomment this line if you use the simulator to force the init to be
+    // interpreted as successful. With an actual ECU; be sure that the init is
+    // succesful before trying to request PID's.

     if (init_success){
         bool res;


Afegir recordatori del pinout de la plaqueta

--- BlinkenServer/arduino/SerialBlinken/SerialBlinken.ino
+++ BlinkenServer/arduino/SerialBlinken/SerialBlinken.ino
@@ -1,3 +1,26 @@
+/**
+Connexió plaqueta blinkenlights
+
+Leonardo/Micro:
+
+Groc: MOSI
+Vermell: D	12
+Taronja: CLK
+
+Marró: GROUND
+Verd: +5/+3.3V
+
+================
+
+UNO:
+
+================
+
+MEGA:
+
+**/
+
+
 #include <SPI.h>
 #include <util/parity.h>
 /*


add ota

add ota

--- _68-acir-for-bedroom/_68-acir-for-bedroom.ino
+++ _68-acir-for-bedroom/_68-acir-for-bedroom.ino
@@ -1,9 +1,12 @@
+//
 #include <ESP8266WiFi.h>
+#include <ESP8266mDNS.h>
+#include <WiFiUdp.h>
+#include <ArduinoOTA.h>
 #include <PubSubClient.h>
+#include <lgWhisen.h>
+#include <TimeLib.h>
 #include <ArduinoJson.h>
-#include <lgWhisen.h>
-#include <WiFiUdp.h>
-#include <TimeLib.h>

 #define IR_TX_PIN 4
 #define AC_CONF_TYPE 1    // 0: tower, 1: wall
@@ -134,17 +137,21 @@
   {
     if (root.containsKey("ac_temp"))
     {
-      ir_data.ac_temp = root["ac_temp"];
-    }
-    /*
-        if (root.containsKey("ac_flow"))
+     if (ir_data.ac_temp != root["ac_temp"])
+     {
+        ir_data.ac_temp = root["ac_temp"];
+        /*
+            if (root.containsKey("ac_flow"))
+            {
+                ir_data.ac_flow = root["ac_flow"];
+            }
+        */
+
+        if (ir_data.ac_mode == 1 && bpresence)
         {
-          ir_data.ac_flow = root["ac_flow"];
+            ir_data.haveData = true;
         }
-    */
-    if (ir_data.ac_mode == 1 && bpresence)
-    {
-      ir_data.haveData = true;
+      }
     }
   }
 }
@@ -188,231 +195,43 @@
   return client.connected();
 }

-void wifi_connect()
-{
-  if (WiFi.status() != WL_CONNECTED)
-  {
-    Serial.println();
-    Serial.print("[WIFI] Connecting to ");
-    Serial.println(WIFI_SSID);
-
-    delay(10);
-    WiFi.mode(WIFI_STA);
-    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
-
-    int Attempt = 0;
-    while (WiFi.status() != WL_CONNECTED)
-    {
-      Serial.print(". ");
-      Serial.print(Attempt);
-      delay(100);
-      Attempt++;
-      if (Attempt == 150)
-      {
-        Serial.println();
-        Serial.println("[WIFI] Could not connect to WIFI, restarting...");
-        Serial.flush();
-        ESP.restart();
-        delay(200);
-      }
-    }
-
-    Serial.println();
-    Serial.print("[WIFI] connected");
-    Serial.print(" --> IP address: ");
-    Serial.println(WiFi.localIP());
-  }
-}
-
-void setup()
-{
-  Serial.begin(115200);
-  Serial.println();
-  Serial.println("Starting....... ");
-
-  ir_data.ac_mode          = 0;
-  ir_data.ac_temp          = AC_DEFAULT_TEMP;
-  ir_data.ac_flow          = AC_DEFAULT_FLOW;
-  ir_data.haveData         = false;
-  ir_data.ac_presence_mode = 0;
-
-  lgWhisen.setActype(AC_CONF_TYPE);
-  lgWhisen.setHeating(AC_CONF_HEATING);
-  lgWhisen.setTemp(ir_data.ac_temp);
-  lgWhisen.setFlow(ir_data.ac_flow);
-  lgWhisen.setIrpin(IR_TX_PIN);
-
-  pinMode(PIR_INT, INPUT);
-  bpir_isr = false;
-  attachInterrupt(PIR_INT, pir_isr, RISING);
-
-  wifi_connect();
-
-  clientName += "esp8266-";
-  uint8_t mac[6];
-  WiFi.macAddress(mac);
-  clientName += macToStr(mac);
-  clientName += "-";
-  clientName += String(micros() & 0xff, 16);
-
-  configTime(9 * 3600, 0, "pool.ntp.org", "time.nist.gov");
-
-  // ntp update
-  udp.begin(localPort);
-  if (timeStatus() == timeNotSet)
-  {
-    Serial.println("[NTP] get ntp time");
-    setSyncProvider(getNtpTime);
-    delay(500);
-  }
-
-  // start with ac power down
-  lgWhisen.power_down();
-
-  reconnect();
-  lastReconnectAttempt = 0;
-  startMills = millis();
-}
-
-void loop()
-{
-  if (bpir_isr)
-  {
-    Serial.println("[PIR] ---> pir detected");
-    lastpirMillis = millis();
-    bpir_isr = false;
-  }
-
-  if ((millis() - lastpirMillis < MAX_PIR_TIME) && ( lastpirMillis != 0))
-  {
-    bpresence = true;
-  }
-  else
-  {
-    bpresence = false;
-  }
-
-  if (!bpresence && ir_data.ac_presence_mode == 1)
-  {
-    Serial.println("[IR] -----> AC Power Down");
-    lgWhisen.power_down();
-    ir_data.ac_presence_mode = 0;
-  }
-
-  if (bpresence && ir_data.ac_presence_mode == 0 && ir_data.ac_mode == 1)
-  {
-    ir_data.haveData = true;
-  }
-
-  if (now() != prevDisplay)
-  {
-    prevDisplay = now();
-    if (timeStatus() == timeSet)
-    {
-      digitalClockDisplay();
-    }
-    else
-    {
-      Serial.println("[TIME] time not set");
-    }
-  }
-
-  if (WiFi.status() == WL_CONNECTED)
-  {
-    if (!client.connected())
-    {
-      long now = millis();
-      if (now - lastReconnectAttempt > 5000)
-      {
-        lastReconnectAttempt = now;
-        if (reconnect())
-        {
-          lastReconnectAttempt = 0;
-        }
-      }
-    }
-    else
-    {
-      // ac change, ir tx
-      if (ir_data.haveData)
-      {
-        lgWhisen.setTemp(ir_data.ac_temp);
-        lgWhisen.setFlow(ir_data.ac_flow);
-
-        switch (ir_data.ac_mode)
-        {
-          // ac power down
-          case 0:
-            Serial.println("[IR] -----> AC Power Down");
-            lgWhisen.power_down();
-            break;
-
-          // ac on
-          case 1:
-            Serial.println("[IR] -----> AC Power On");
-            lgWhisen.activate();
-            break;
-
-          default:
-            break;
-        }
-        ir_data.ac_presence_mode = ir_data.ac_mode;
-        ir_data.haveData = false;
-      }
-
-      if ((millis() - startMills) > REPORT_INTERVAL)
-      {
-        sendCheck();
-        startMills = millis();
-      }
-
-      client.loop();
-    }
-  }
-  else
-  {
-    wifi_connect();
-  }
-}
-
-
-String macToStr(const uint8_t* mac)
-{
-  String result;
-  for (int i = 0; i < 6; ++i)
-  {
-    result += String(mac[i], 16);
-    if (i < 5)
-      result += ':';
-  }
-  return result;
+void ArduinoOTA_config()
+{
+  //OTA
+  // Port defaults to 8266
+  ArduinoOTA.setPort(8266);
+  ArduinoOTA.setHostname("esp-irbedroom");
+  ArduinoOTA.setPassword(OTA_PASSWORD);
+  ArduinoOTA.onStart([]()
+  {
+    //sendUdpSyslog("ArduinoOTA Start");
+  });
+  ArduinoOTA.onEnd([]()
+  {
+    //sendUdpSyslog("ArduinoOTA End");
+  });
+  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total)
+  {
+    //syslogPayload = "Progress: ";
+    //syslogPayload += (progress / (total / 100));
+    //sendUdpSyslog(syslogPayload);
+  });
+  ArduinoOTA.onError([](ota_error_t error)
+  {
+    //ESP.restart();
+    if (error == OTA_AUTH_ERROR) abort();
+    else if (error == OTA_BEGIN_ERROR) abort();
+    else if (error == OTA_CONNECT_ERROR) abort();
+    else if (error == OTA_RECEIVE_ERROR) abort();
+    else if (error == OTA_END_ERROR) abort();
+  });
+
+  ArduinoOTA.begin();
 }

 /*-------- NTP code ----------*/
 const int NTP_PACKET_SIZE = 48;
 byte packetBuffer[NTP_PACKET_SIZE];
-
-time_t getNtpTime()
-{
-  while (udp.parsePacket() > 0) ;
-  sendNTPpacket(mqtt_server);
-  uint32_t beginWait = millis();
-  while (millis() - beginWait < 2500)
-  {
-    int size = udp.parsePacket();
-    if (size >= NTP_PACKET_SIZE)
-    {
-      udp.read(packetBuffer, NTP_PACKET_SIZE);
-      unsigned long secsSince1900;
-      secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
-      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
-      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
-      secsSince1900 |= (unsigned long)packetBuffer[43];
-      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
-    }
-  }
-  return 0;
-}

 void sendNTPpacket(IPAddress & address)
 {
@@ -430,6 +249,36 @@
   udp.endPacket();
 }

+time_t getNtpTime()
+{
+  while (udp.parsePacket() > 0) ;
+  sendNTPpacket(mqtt_server);
+  uint32_t beginWait = millis();
+  while (millis() - beginWait < 2500)
+  {
+    int size = udp.parsePacket();
+    if (size >= NTP_PACKET_SIZE)
+    {
+      udp.read(packetBuffer, NTP_PACKET_SIZE);
+      unsigned long secsSince1900;
+      secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
+      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
+      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
+      secsSince1900 |= (unsigned long)packetBuffer[43];
+      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
+    }
+  }
+  return 0;
+}
+
+void printDigits(int digits)
+{
+  Serial.print(":");
+  if (digits < 10)
+    Serial.print('0');
+  Serial.print(digits);
+}
+
 void digitalClockDisplay()
 {
   Serial.print("[TIME] ");
@@ -444,12 +293,205 @@
   Serial.println(year());
 }

-void printDigits(int digits)
-{
-  Serial.print(":");
-  if (digits < 10)
-    Serial.print('0');
-  Serial.print(digits);
+void wifi_connect()
+{
+  if (WiFi.status() != WL_CONNECTED)
+  {
+    Serial.println();
+    Serial.print("[WIFI] Connecting to ");
+    Serial.println(WIFI_SSID);
+
+    delay(10);
+    WiFi.mode(WIFI_STA);
+    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
+
+    int Attempt = 0;
+    while (WiFi.status() != WL_CONNECTED)
+    {
+      Serial.print(". ");
+      Serial.print(Attempt);
+      delay(100);
+      Attempt++;
+      if (Attempt == 150)
+      {
+        Serial.println();
+        Serial.println("[WIFI] Could not connect to WIFI, restarting...");
+        Serial.flush();
+        ESP.restart();
+        delay(200);
+      }
+    }
+
+    Serial.println();
+    Serial.print("[WIFI] connected");
+    Serial.print(" --> IP address: ");
+    Serial.println(WiFi.localIP());
+  }
+}
+
+String macToStr(const uint8_t* mac)
+{
+  String result;
+  for (int i = 0; i < 6; ++i)
+  {
+    result += String(mac[i], 16);
+    if (i < 5)
+      result += ':';
+  }
+  return result;
+}
+
+void setup()
+{
+  Serial.begin(115200);
+  Serial.println();
+  Serial.println("Starting....... ");
+
+  ir_data.ac_mode          = 0;
+  ir_data.ac_temp          = AC_DEFAULT_TEMP;
+  ir_data.ac_flow          = AC_DEFAULT_FLOW;
+  ir_data.haveData         = false;
+  ir_data.ac_presence_mode = 0;
+
+  lgWhisen.setActype(AC_CONF_TYPE);
+  lgWhisen.setHeating(AC_CONF_HEATING);
+  lgWhisen.setTemp(ir_data.ac_temp);
+  lgWhisen.setFlow(ir_data.ac_flow);
+  lgWhisen.setIrpin(IR_TX_PIN);
+
+  pinMode(PIR_INT, INPUT);
+  bpir_isr = false;
+  attachInterrupt(PIR_INT, pir_isr, RISING);
+
+  wifi_connect();
+
+  clientName += "esp8266-";
+  uint8_t mac[6];
+  WiFi.macAddress(mac);
+  clientName += macToStr(mac);
+  clientName += "-";
+  clientName += String(micros() & 0xff, 16);
+
+  configTime(9 * 3600, 0, "pool.ntp.org", "time.nist.gov");
+
+  // ntp update
+  udp.begin(localPort);
+  if (timeStatus() == timeNotSet)
+  {
+    Serial.println("[NTP] get ntp time");
+    setSyncProvider(getNtpTime);
+    delay(500);
+  }
+
+  // start with ac power down
+  lgWhisen.power_down();
+
+  ArduinoOTA_config();
+
+  reconnect();
+  lastReconnectAttempt = 0;
+  startMills = millis();
+}
+
+void loop()
+{
+  if (bpir_isr)
+  {
+    Serial.println("[PIR] ---> pir detected");
+    lastpirMillis = millis();
+    bpir_isr = false;
+  }
+
+  if ((millis() - lastpirMillis < MAX_PIR_TIME) && ( lastpirMillis != 0))
+  {
+    bpresence = true;
+  }
+  else
+  {
+    bpresence = false;
+  }
+
+  if (!bpresence && ir_data.ac_presence_mode == 1)
+  {
+    Serial.println("[IR] -----> AC Power Down");
+    lgWhisen.power_down();
+    ir_data.ac_presence_mode = 0;
+  }
+
+  if (bpresence && ir_data.ac_presence_mode == 0 && ir_data.ac_mode == 1)
+  {
+    ir_data.haveData = true;
+  }
+
+  if (now() != prevDisplay)
+  {
+    prevDisplay = now();
+    if (timeStatus() == timeSet)
+    {
+      digitalClockDisplay();
+    }
+    else
+    {
+      Serial.println("[TIME] time not set");
+    }
+  }
+
+  if (WiFi.status() == WL_CONNECTED)
+  {
+    if (!client.connected())
+    {
+      long now = millis();
+      if (now - lastReconnectAttempt > 5000)
+      {
+        lastReconnectAttempt = now;
+        if (reconnect())
+        {
+          lastReconnectAttempt = 0;
+        }
+      }
+    }
+    else
+    {
+      // ac change, ir tx
+      if (ir_data.haveData)
+      {
+        lgWhisen.setTemp(ir_data.ac_temp);
+        lgWhisen.setFlow(ir_data.ac_flow);
+
+        switch (ir_data.ac_mode)
+        {
+          // ac power down
+          case 0:
+            Serial.println("[IR] -----> AC Power Down");
+            lgWhisen.power_down();
+            break;
+
+          // ac on
+          case 1:
+            Serial.println("[IR] -----> AC Power On");
+            lgWhisen.activate();
+            break;
+
+          default:
+            break;
+        }
+        ir_data.ac_presence_mode = ir_data.ac_mode;
+        ir_data.haveData = false;
+      }
+
+      if ((millis() - startMills) > REPORT_INTERVAL)
+      {
+        sendCheck();
+        startMills = millis();
+      }
+
+      client.loop();
+    }
+  }
+  else
+  {
+    wifi_connect();
+  }
 }

 // end of file


Beta presentation.

Beta presentation.

--- frankenbear.ino
+++ frankenbear.ino
@@ -1,4 +1,5 @@
 #include <Wire.h>
+#include "pitches.h"
 #include <Adafruit_PWMServoDriver.h>

 // Uses the default address 0x40.
@@ -28,7 +29,7 @@
 int kissed_flag = 0;
 int normal_light_flag = 0;

-int photocellPin = 0;     // the cell and 10K pulldown are connected to a0
+int photocellPin = A5;     // the cell and 10K pulldown are connected to a0
 int photocellReading;     // the analog reading from the sensor divider
 int LEDpin = 11;          // connect Red LED to pin 11 (PWM pin)
 int LEDbrightness;
@@ -37,6 +38,13 @@
 int numTones = 10;
 int tones[] = {261, 277, 294, 311, 330, 349, 370, 392, 415, 440};
 //            mid C  C#   D    D#   E    F    F#   G    G#   A
+
+int mary_had_a_little_lamb_notes[] = {
+  NOTE_E4, NOTE_D4, NOTE_C4, NOTE_D4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_C4, NOTE_D4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_D4, NOTE_E4, NOTE_D4, NOTE_C4
+};
+int mary_had_a_little_lamb_lengths[] = {
+  4, 4, 4, 4, 4, 4, 2, 4, 4, 2, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2
+};

 const int buttonPin = 2;     // the number of the pushbutton pin
 const int ledPin =  13;      // the number of the LED pin
@@ -65,40 +73,35 @@
 {
   photocellReading = analogRead(photocellPin);
   Serial.print("Analog reading = ");
-  Serial.println(photocellReading);
+  Serial.print(photocellReading);
+  Serial.print(", ");
+  Serial.println(normal_light_flag);

-  // When kissed or hugged (light sensor), wiggle several times and stop.
-  if ( kissed_flag > 0 )
+  // When it gets bright or dark, make a sound.
+  // Stop playing the sound until it's normal lighting out again.
+  if ( photocellReading >= 700 && photocellReading <= 710 )
   {
-    while ( kissed_flag > 4 )
+    normal_light_flag = 1;
+  }
+
+  if ( photocellReading < 700 && normal_light_flag ) //it is dark
+  {
+    play_song();
+    normal_light_flag = 0;
+  }
+  else if ( photocellReading > 710 && normal_light_flag ) // it is bright
+  {
+//    tone(speakerPin, tones[9]); //play A
+//    delay(500);
+//    noTone(speakerPin);
+    while ( kissed_flag < 4 )
     {
       wiggle_ears();
       kissed_flag++;
     }

     reset_ears();
-  }
-
-  // When it gets bright or dark, make a sound.
-  // Stop playing the sound until it's normal lighting out again.
-  if ( photocellReading > 800 && photocellReading < 950 )
-  {
-    normal_light_flag = 1;
-  }
-
-  if ( photocellReading < 300 && normal_light_flag ) //it is dark
-  {
-    tone(speakerPin, tones[0]);//play mid C
-    delay(500);
-    noTone(speakerPin);
-    normal_light_flag = 0;
-  }
-
-  if ( photocellReading > 950 && normal_light_flag ) // it is bright
-  {
-    tone(speakerPin, tones[9]); //play A
-    delay(500);
-    noTone(speakerPin);
+    kissed_flag = 0;
     normal_light_flag = 0;
   }

@@ -154,3 +157,17 @@
   pwm.setPWM(left_ear, 0, MIDDLE_EAR);
   pwm.setPWM(right_ear, 0, MIDDLE_EAR);
 }
+
+void play_song()
+{
+  // 26 notes long
+  for ( int i = 0; i < 26; i++ )
+  {
+    int note_length = 1000 / mary_had_a_little_lamb_lengths[i];
+    tone(speakerPin, mary_had_a_little_lamb_notes[i], note_length);
+
+    int pause_between_notes = note_length * 1.30;
+    delay(pause_between_notes);
+    noTone(speakerPin);
+  }
+}


more info about how to install needed libraries

--- arduino/WiFi-Car_WEMOS-aRest/WiFi-Car_WEMOS-aRest.ino
+++ arduino/WiFi-Car_WEMOS-aRest/WiFi-Car_WEMOS-aRest.ino
@@ -3,14 +3,16 @@
 // author: Paschaleris Triantafyllos
 //         https://paschaleris.gr
 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-// Get the modified Arduino IDE:
-//    \\192.168.88.1\sd(a1)\ArduinoIDE.zip
-// extract the file
-// replace the contents of C:\Program Files (x86)\Arduino
+// From the folder "files needed\Arduino libraries" of this repository copy the folders:
+//    "Adafruit_SSD1306_WEMOS"
+//    "Adafruit_GFX_Library"
+//
+// paste them inside:  C:\Program Files (x86)\Arduino\libraries\
 //
 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 // Link to add additional boards (File > Preferences): http://arduino.esp8266.com/stable/package_esp8266com_index.json
 // Then open Boards Manager from Tools > Board > Board Manager and search and install "esp8266".
+//                                       then search and install "aREST"
 //
 // Before Upload CHECK in tools for the CORRECT PORT and:
 //   Board: "WeMos D1 R2 & mini"


Ajout d'un contrôle pour la direction.

Ajout d'un contrôle pour la direction.

--- controle_par_mannette/controle_par_mannette.ino
+++ controle_par_mannette/controle_par_mannette.ino
@@ -15,7 +15,7 @@
 //
 /////////////////////////////////////////////////////////////

-#define DEBOGGAGE 0
+#define DEBOGGAGE 1

 // Numéro de pin des sorties vers les moteurs
 const int moteur_avant   =  9;
@@ -34,7 +34,15 @@
 const int mannette_vitesse = A7;

 // Durée minimale de la boucle principale
-const int dt = 10;
+#if DEBOGGAGE
+const int dt = 1000; // 1 fois par seconde en mode déboggage
+#else
+const int dt = 10;   // À 100 Hz en fonctionnement normal
+#endif
+
+// Zone morte du contrôle de direction
+const float direction_assez_precis = 0.1;
+const int direction_vitesse_moteur = 255;

 /////////////////////////////////////////////////////////////
 //
@@ -89,7 +97,8 @@

   // Convertir la lecture analogique entière entre 20% et 100% de 255
   float vitesse_f = (vitesse_i / 1023.0);
-  vitesse_moteur = max(vitesse_f, 0.1) * 255.0;
+  //vitesse_moteur = max(vitesse_f, 0.1) * 255.0;
+  vitesse_moteur = 0.1 * 255.0;

 #if DEBOGGAGE
   Serial.print(F("Vitesse au potentiometre: "));
@@ -109,25 +118,58 @@
     analogWrite(moteur_avant, 0);
   }
   if(bouton_arriere == LOW) {
-      // Activer le moteur arrière
-      analogWrite(moteur_arriere, vitesse_moteur);
+    // Activer le moteur arrière
+    analogWrite(moteur_arriere, vitesse_moteur);
   }
   else {
     analogWrite(moteur_arriere, 0);
   }

   // Lire la direction actuelle
-  int direction_i = analogRead(mesure_direction);
+  int direction_mesure_i = analogRead(mesure_direction);
   // Convertir la lecture analogique entière entre -1 et 1
-  float direction_f = 2.0 * (direction_i - 44.0) / (1023.0 - 44.0) - 1.0;
+  float direction_mesure_f = 2.0 * (direction_mesure_i - 44.0) / (1023.0 - 44.0) - 1.0;

 #if DEBOGGAGE
-  Serial.print(F("Direction au potentiometre: "));
-  Serial.print(direction_i);
+  Serial.print(F("Direction lue au potentiometre: "));
+  Serial.print(direction_mesure_i);
   Serial.print(F(", une fois convertie entre -1 et 1: "));
-  Serial.print(direction_f);
+  Serial.print(direction_mesure_f);
   Serial.println(F("."));
 #endif

+  // Lire la direction voulue (utilisant le contrôle de vitesse pour l'instant)
+  int direction_voulue_i = vitesse_i;
+  // Convertir la lecture analogique entière entre -1 et 1
+  float direction_voulue_f = 2.0 * direction_voulue_i / 1023.0 - 1.0;
+
+  // Calculer l'erreur et la correction
+  float erreur_direction = direction_voulue_f - direction_mesure_f;
+
+  if(erreur_direction < -direction_assez_precis) {
+    // Tourner les roues vers la gauche
+    analogWrite(moteur_gauche, direction_vitesse_moteur);
+    analogWrite(moteur_droite, 0);
+  }
+  else if(erreur_direction > direction_assez_precis) {
+    // Tourner les roues vers la droite
+    analogWrite(moteur_gauche, 0);
+    analogWrite(moteur_droite, direction_vitesse_moteur);
+  }
+  else {
+    // Arrêter les roues
+    analogWrite(moteur_gauche, 0);
+    analogWrite(moteur_droite, 0);
+  }
+
+#if DEBOGGAGE
+  Serial.print(F("Direction desiree: "));
+  Serial.print(direction_voulue_f);
+  Serial.print(F(", erreur: "));
+  Serial.print(erreur_direction);
+  Serial.println(F("."));
+#endif
+
+  // Attendre un peu avant de recommencer
   delay(dt);
 }