Delete _4-20mA_Data_Logger.ino

Delete _4-20mA_Data_Logger.ino

--- _4-20mA_Data_Logger.ino
+++ _4-20mA_Data_Logger.ino
@@ -1,662 +0,0 @@
-/*
-4 channel 4-20mA Data Logger lite
-companion initialization script required to initialize EEPROM and files for Serial printing large amounts of text
-This is a lite program because it was stripped down to absolute minimal functionality to fit under 32K, so there is no debugging or verbose messaging.
-
-
-
-    53B per record
-    ~364 Records per second measured
-    SD.Open Time = 11ms
-    SD.print one line record time = 0.1ms
-    Get RTC time = 3.8ms
-    SD.Close Time = 15ms
-
-
-
-
-
-
-*/
-
-//Includes
-  #include <EEPROM.h>
-  #include <Time.h>
-  #include <ADS1115_lite.h>
-  #include <SPI.h>
-  #include <SD.h>
-  #include <RtcDS3231.h>
-
-
-   // float sdValues[50];
-  // int sdValuesPTR;
-
-  #define ADC_BITS 32767
-
-  //RTC class definition
-    RtcDS3231 RTC;
-
-  //ADS1115 class definitions
-    ADS1115_lite adc0(ADS1115_DEFAULT_ADDRESS);
-    ADS1115_lite adc1(ADS1115_ADDRESS_ADDR_VDD);
-
-  //ADC Resistor and calibration factors
-    struct ADCChan{
-      int Raw;
-      float Calib; //Calibration factor to multiply things by
-      float ActualLo; //Low value for EngUnits scaling
-      float ActualHi;//High for EngUnits scaling
-      float Current; //Current scaled engineering units from ActualLo and Actual Hi.  This is compared against Actual and Deadband to determine when to update Actual
-      float Actual; //scaled engineering units from ActualLo and Actual Hi
-      float Deadband; //Swinging door deadband to determine how often to save values
-      boolean Change; //Flag set on each scan when the current value has changed outside of its deadband and Actual has been updated.  Check this to log the value.  This is reset at the beggining of each scan
-      byte Precision; //Number of decimal places to show
-      float mA; //Swinging door deadband to determine how often to save values
-    };
-    struct ADCChan Ch0;
-    struct ADCChan Ch1;
-    struct ADCChan Ch2;
-    struct ADCChan Ch3;
-
-  //SDCard
-    String DataFolderLocation = "Data";
-    String DataFileLocation = DataFolderLocation + "/Data0.CSV";
-    #define DataMaxFileSize 1048576 //Maximum file size in bytes, set at 1MB or ~ 17,300 records.
-    int DataFileNumber; //Create a int that will reference the Data file number on the SD card e.g.: 4 would work on the file on : SDCARD/Data/Data4.CSV
-    File file;
-
-  //misc
-      boolean livereadout; //a tag to store if the user has turned on live readout on or off
-
-  //Serial Read tags - delete if not doing Serial Reads, Also delete fucntions SerialMonitor and SerialEvent
-    #define SERIAL_BUFFER_SIZE 20
-    String sSerialBuffer; //Create a global string that is added to character by character to create a final serial read
-    String sLastSerialLine; //Create a global string that is the Last full Serial line read in from sSerialBuffer
-
-//SETUPSETUPSETUPSETUPSETUPSETUPSETUPSETUPSETUPSETUPSETUPSETUP
-void setup() {
-
-
-  //Setup Serial
-    //In case the user uses the default setting in Arduino, give them a message to change BAUD rate
-      Serial.begin(9600);
-      Serial.println("Set Serial baud rate to 115200");
-      Serial.flush ();   // wait for send buffer to empty
-      delay (2);    // let last character be sent
-      Serial.end ();      // close serial
-    Serial.begin(250000);
-      Serial.println();
-
-  //Set serial read buffer size to reserve the space to concatnate all bytes recieved over serial
-    sSerialBuffer.reserve(SERIAL_BUFFER_SIZE);
-
-  //Read the debug boolean and set the debug flag
-    int address = 2; //Temporary EEPROM address pointer
-    EEPROM.get(address,DataFileNumber);
-
-    address = 10; //Repoint EEPROM pointer                    //EEPROM ADDRESSES
-    EEPROM.get(address,Ch0.Calib); address = address + 4;     //10
-    EEPROM.get(address,Ch0.ActualLo); address = address + 4;  //14
-    EEPROM.get(address,Ch0.ActualHi); address = address + 4;  //18
-    EEPROM.get(address,Ch0.Deadband); address = address + 4;  //22
-
-    EEPROM.get(address,Ch1.Calib); address = address + 4;     //26
-    EEPROM.get(address,Ch1.ActualLo); address = address + 4;  //30
-    EEPROM.get(address,Ch1.ActualHi); address = address + 4;  //34
-    EEPROM.get(address,Ch1.Deadband); address = address + 4;  //38
-
-    EEPROM.get(address,Ch2.Calib); address = address + 4;     //42
-    EEPROM.get(address,Ch2.ActualLo); address = address + 4;  //46
-    EEPROM.get(address,Ch2.ActualHi); address = address + 4;  //50
-    EEPROM.get(address,Ch2.Deadband); address = address + 4;  //54
-
-    EEPROM.get(address,Ch3.Calib); address = address + 4;     //58
-    EEPROM.get(address,Ch3.ActualLo); address = address + 4;  //62
-    EEPROM.get(address,Ch3.ActualHi); address = address + 4;  //66
-    EEPROM.get(address,Ch3.Deadband); address = address + 4;  //70
-                                                              //74
-  //SDCard
-    DataFileLocation = FileLocation(DataFileNumber);
-
-  //I2C start
-    Wire.begin();
-
-  //ADS1115 Setup
-    adc0.setSampleRate(ADS1115_REG_CONFIG_DR_8SPS);
-    adc0.setGain(ADS1115_REG_CONFIG_PGA_0_256V);
-    adc1.setSampleRate(ADS1115_REG_CONFIG_DR_8SPS);
-    adc1.setGain(ADS1115_REG_CONFIG_PGA_0_256V);
-    if (!adc0.testConnection() | !adc1.testConnection()) {EndProgram(F("One of the ADCs has failed"));}
-
-
-  //RTC
-    RTC.Begin();
-    if (!RTC.IsDateTimeValid()) {EndProgram(F("ERROR: RTC failure.  Please set time and/or change battery."));}// Common Cuases: the battery on the device is low or even missing and the power line was disconnected
-
-  //SD Card initialization
-    if (!SD.begin(10)) {EndProgram(F("Error: SD Card failure.  Insert SD Card"));}
-
-  //Printout welcome message
-    SerialPrintFile(F("Menu/_01_Wel.txt"));
-
-  //Pin Setup
-    pinMode(2, INPUT);
-}
-//SETUPSETUPSETUPSETUPSETUPSETUPSETUPSETUPSETUPSETUPSETUPSETUP
-
-
-
-
-
-
-
-
-//MAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOP
-//MAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOP
-void loop() {
-
-
-  SerialMonitor(); //Monitor Serial Inputs
-
-  //Get and process inputs then log data
-      Data();
-
-  //Sleep for some time
-
-   // LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF);   //deep powered down sleep
-
-}
-//MAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOP
-//MAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOPMAINLOOP
-
-
-//==============================================================================================
-void SerialPrintFile(String s) {
-    //Print an entire file to the Serial stream
-    file = SD.open(s);
-    while (file.available()) {
-      Serial.write(file.read());
-    }
-    file.close();
-}
-//==============================================================================================
-String FileLocation(int number) {
-  //Pass in the number to append to the file name. Returns the file name
-    String f;
-    f += DataFolderLocation;
-    f += "/Data";
-    f += String(number);
-    f += ".CSV";
-    return f;
-}
-//==============================================================================================
-void Data() {
-  //See if data has changed, if so, write to SD
-
-  //Get Inputs
-      getInputs();
-
-  //print live readouts if enabled
-  if (livereadout) {
-    PrintChannelLive(&Ch0);
-    PrintChannelLive(&Ch1);
-    PrintChannelLive(&Ch2);
-    PrintChannelLive(&Ch3);
-    Serial.println();
-  }
-
-  //Check to see if any values changed, if not return
-      if (!Ch0.Change && !Ch1.Change && !Ch2.Change && !Ch3.Change) {
-        return;
-      }
-
-  //Check to see if the data file exists, if not, try to create it
-      if (!SD.exists(DataFileLocation)) {
-        Serial.print(F("creating file: ")); Serial.println(DataFileLocation);
-        if (!SD.mkdir(DataFolderLocation)) {
-          Serial.println(F("Failed to make folder on SD Card, no data will be saved"));
-          return;
-        }
-        File temp = SD.open(DataFileLocation, FILE_WRITE); //Open file SDCard\Data\Data.CSV
-        temp.println(F("Date,Ch0,Ch1,Ch2,Ch3")); //print header
-        temp.close();
-      }
-
-  //Check to see if the file has reached the max file size, if so make a new one
- File dataFile = SD.open(DataFileLocation, FILE_WRITE); //Open file SDCard\Data\Data.CSV
-        if (dataFile.size() > DataMaxFileSize) { //Data/DataX.CSV is too big, make another file one.
-          dataFile.close(); //Close the file
-          DataFileNumber++;
-          EEPROM.put(2,DataFileNumber);
-          DataFileLocation = FileLocation(DataFileNumber);
-          File dataFile = SD.open(DataFileLocation, FILE_WRITE); //Open file SDCard\Data\Data.CSV
-        }
-
-  //Concatenate the line to print
-      String line;
-      line += getDateString();
-      line += ",";
-      line += String(Ch0.Actual,Ch0.Precision);
-      line += ",";
-      line += String(Ch1.Actual,Ch1.Precision);
-      line += ",";
-      line += String(Ch2.Actual,Ch2.Precision);
-      line += ",";
-      line += String(Ch3.Actual,Ch3.Precision);
-      line += ",";
-
-  dataFile.println(line);
-  dataFile.close(); //Close the file
-}
-//==============================================================================================
-String getDateString() {
-
-   if (!RTC.IsDateTimeValid()) {
-    Serial.println(F("ERROR: RTC failure.  Please set time and/or change battery."));
-    return "Time Error";
-   }// Common causes: the battery on the device is low or even missing and the power line was disconnected
-
-    RtcDateTime now = RTC.GetDateTime();
-    String s;
-    byte temp;
-
-      s = now.Year();  s += "/";
-
-        temp = now.Month();
-        if (temp < 10) {s += "0";}
-        s += String(temp);  s += "/";
-
-        temp = now.Day();
-        if (temp < 10) {s += "0";}
-        s += String(temp);  s += " ";
-
-        temp = now.Hour();
-        if (temp < 10) {s += "0";}
-        s += String(temp);  s += ":";
-
-        temp = now.Minute();
-        if (temp < 10) {s += "0";}
-        s += String(temp);  s += ":";
-
-        temp = now.Second();
-        if (temp < 10) {s += "0";}
-        s += String(temp);
-
-    return s;
-}
-//==============================================================================================
-int ADCProcessing(struct ADCChan *Ch) {
-  //Reset the Change bit
-      Ch->Change = 0;
-
-  //Scale the Raw value(0-32767) to mA (0-25.6)
-      Ch->mA = SCP(Ch->Raw, 0.0, ADC_BITS, 0.0, 25.6) * Ch->Calib;
-
-  //Scale the Raw value to Eng Units
-      Ch->Current = SCP(Ch->mA, 4.0, 20.0, Ch->ActualLo, Ch->ActualHi);
-
-  //Check to see if it has moved outside of the Actual value
-      if ((Ch->Current >= Ch->Actual + Ch->Deadband) || (Ch->Current <= Ch->Actual - Ch->Deadband)) { //If it moved outside of the deadband update the actual
-        Ch->Actual = Ch->Current;
-        Ch->Change = 1; //Set Change bit true if Actual has been updated
-      }
-
-  //Determine number of decimal places that are important
-      float ftemp = (Ch->ActualHi - Ch->ActualLo)/ADC_BITS;
-      if (ftemp > 0.305185095) {
-          Ch->Precision = 0;
-      } else if (ftemp >= 0.030518509) {
-          Ch->Precision = 1;
-      } else if (ftemp >= 0.003051851) {
-          Ch->Precision = 2;
-      } else if (ftemp >= 0.000305185) {
-          Ch->Precision = 3;
-      } else if (ftemp >= 0.0000305185) {
-          Ch->Precision = 4;
-      } else {
-          Ch->Precision = 5;
-      }
-}
-//==============================================================================================
-float SCP(float Raw, float RawLo, float RawHi, float ScaleLo, float ScaleHi) {
-  return (Raw - RawLo) * (ScaleHi - ScaleLo) / (RawHi - RawLo) + ScaleLo;
-}
-//==============================================================================================
-void getInputs() {
-  //Read both channels on both ADCs
-
-
-  //Trigger both channels on both ADCs. Each read takes 128ms, the reads are staggered.  Total measured time is 256.2ms
-
-      adc0.setMux(ADS1115_REG_CONFIG_MUX_DIFF_0_1);   //time = 0
-      adc0.TriggerConversion();
-      adc1.setMux(ADS1115_REG_CONFIG_MUX_DIFF_0_1);
-      adc1.TriggerConversion();
-
-      Ch0.Raw = adc0.getLastConversionResults();
-      adc0.setMux(ADS1115_REG_CONFIG_MUX_DIFF_2_3);
-      adc0.TriggerConversion();
-
-      Ch2.Raw = adc1.getLastConversionResults();
-      adc1.setMux(ADS1115_REG_CONFIG_MUX_DIFF_2_3);
-      adc1.TriggerConversion();
-
-      Ch1.Raw = adc0.getLastConversionResults();
-      Ch3.Raw = adc1.getLastConversionResults();
-
-  ADCProcessing(&Ch0);
-  ADCProcessing(&Ch1);
-  ADCProcessing(&Ch2);
-  ADCProcessing(&Ch3);
-
-    //Std Dev Code Below
-    /*
-    sdValues[sdValuesPTR] = float(Ch0.mA);
-   sdValuesPTR++;
-   if (sdValuesPTR >= 50) {
-      int i;
-      float ftemp=0;
-      float AVG;
-      float VAR;
-      float sd;
-
-      //Calculate average
-        for (i=0;i<=49;i++) {ftemp = ftemp + sdValues[i];}//Add them up
-        AVG = ftemp / 50.0;
-
-        Serial.print(F("SUM after= "));
-        Serial.print(ftemp,4);
-        Serial.println();
-        Serial.print(F("AVG = "));
-        Serial.print(AVG,4);
-        Serial.print("mA");
-        Serial.println();
-
-      //Calculate Varience
-        for (i=0;i<=49;i++) { //calculate varience
-          VAR = VAR + pow(sdValues[i] - AVG,2);
-        }
-
-        Serial.print(F("VAR = "));
-        Serial.print(VAR,4);
-        Serial.print("mA");
-        Serial.println();
-      //Calculate std dev
-        sd = pow(VAR/50 ,0.5);
-        Serial.print(F("Std Dev = "));
-        Serial.print(sd,6);
-        Serial.print("mA");
-        Serial.println();
-
-    sdValuesPTR=0;
-   }
-   */
-}
-
-
-
-
-//==============================================================================================
-void SerialMonitor() {
-  //Edit this function to process all Serial commands.
-  //This function should be called every scan as it will only do something when data with a LF char has been read from the serial port
-  //  aka: the full command has been recieved
-
-  //Create some temporary variables
-      String aSerialStringParse[8]; //Create a small array to store the parsed strings 0-7
-      int StringStart=0;
-      int i;
-  //Make Serial String all lower case:
-      sLastSerialLine.toLowerCase()    ;
-  if (sLastSerialLine.equalsIgnoreCase("")==false) { //A full line has been read from the Serial buffer, do something!
-    //This should be full of If..Then statemens from all of the different possible commands that can be read and processed over serial
-
-    //Set the String parse 0th element to the number of CSVs recieved, and set the first element to the string
-      aSerialStringParse[0]=1;
-      aSerialStringParse[1]=sLastSerialLine;
-
-
-    //--Search incoming data for a CSV command and modify the stringParseArray
-        int CommaPosition = sLastSerialLine.indexOf(',');
-          if (CommaPosition>0) { //Comma separated values detected, do a string split
-
-            //Perform a String split to a string Array and place the size in [0]
-            for (i=1;i<=7;i++) { //Start at 1 and increment only 5 times
-              aSerialStringParse[i] = sLastSerialLine.substring(StringStart,CommaPosition); //Get the string
-              if (CommaPosition == -1) { //Check if its the last one
-                aSerialStringParse[0] = i; //Set the 0th element to the length
-                break;
-               }
-              StringStart = CommaPosition + 1; //Set the start position of the next search based on the end position of this search
-              CommaPosition = sLastSerialLine.indexOf(',',StringStart); //Find the next comma
-              if (i==7 && CommaPosition !=-1) {
-                aSerialStringParse[0] = i; //Set the 0th element to the length
-                Serial.println(F("Bad Syntax"));
-                break;
-              }
-
-            }
-
-          }
-
-    //SERIAL COMMANDS
-
-    /*
-     Commands can be any text that you can trigger off of.
-     It can also be paramaterized via a CSV Format with no more than five(5) CSVs: 'Param1,Param2,Param3,Param4,Param5'
-     For Example have the user type in '9,255' for a command to manually set pin 9 PWM to 255.
-     */
-    //--------Edit the Help menu
-     if (aSerialStringParse[0].toInt() == 1) { //Process single string serial commands
-          //MAIN MENU
-             if (aSerialStringParse[1] == "?" ) {
-                SerialPrintFile(F("Menu/_10_Main.txt"));
-                Serial.print(F("Time: "));  Serial.println(getDateString());
-              }
-
-              //1. (c)onfig - channel config and calibration"));
-                  if (aSerialStringParse[1] == "c") {
-                    getInputs();
-                    SerialPrintFile(F("Menu/_20_Cfg.txt"));
-
-                       Serial.print(F(" 0\t"));
-                    PrintChannelConfigHor(&Ch0);
-                       Serial.print(F(" 1\t"));
-                    PrintChannelConfigHor(&Ch1);
-                       Serial.print(F(" 2\t"));
-                    PrintChannelConfigHor(&Ch2);
-                       Serial.print(F(" 3\t"));
-                    PrintChannelConfigHor(&Ch3);
-                    Serial.println();
-                    SerialPrintFile(F("Menu/_21_Cfg.txt"));
-                  }
-              //2. (f)ile managemant and data
-                  if (aSerialStringParse[1] == "f") {SerialPrintFile(F("Menu/_30_File.txt"));}
-
-                  //File/dir
-                      if (aSerialStringParse[1] == "dir") {
-                        File DataFolder = SD.open(DataFolderLocation);
-                          printDirectory(DataFolder);
-                      }
-
-                  //Deltree
-
-                        if (aSerialStringParse[1]=="deltree") {
-                            SD.rmdir(DataFolderLocation);
-                            SD.mkdir("Menu");
-                        }
-
-               //Channel Config /Live
-                  if (sLastSerialLine.equalsIgnoreCase("l")) {
-                      if (livereadout) {
-                         livereadout=0;
-                      } else {
-                         livereadout=1;
-                      }
-                  }
-
-              //3. (Future)"));
-                 // if (sLastSerialLine.equalsIgnoreCase("t")) {Serial.print(F("Time: "));  Serial.println(getDateString()); }
-
-      } else if(aSerialStringParse[0].toInt() > 1) {//Process multiple serial commands
-
-            //MAIN/Time
-                if (aSerialStringParse[1]=="t" && aSerialStringParse[0].toInt() == 7) {
-                  if (aSerialStringParse[0].toInt() == 7) {
-                    RtcDateTime t = RtcDateTime(aSerialStringParse[2].toInt(),aSerialStringParse[3].toInt(),aSerialStringParse[4].toInt(),aSerialStringParse[5].toInt(),aSerialStringParse[6].toInt(),aSerialStringParse[7].toInt());
-                    RTC.SetDateTime(t);
-                    Serial.print(F("Time: "));  Serial.println(getDateString());
-                  } else {
-                    Serial.println(F("Bad syntax"));
-                  }
-                }
-            //File Print
-                  if (aSerialStringParse[1]=="p") {
-                      if(aSerialStringParse[0].toInt() == 2) {
-                           File dataFile = SD.open(FileLocation(aSerialStringParse[2].toInt())); //Get the full file name of the selected file, then open it
-                          if (dataFile) {
-                              while (dataFile.available()) { Serial.write(dataFile.read());} //print entire file to Serial
-                              dataFile.close();
-                          }
-                      } else {
-                          Serial.println(F("Bad syntax"));
-                      }
-                  }
-
-            //Del File
-
-                  if (aSerialStringParse[1]=="del") {
-                      if(aSerialStringParse[0].toInt() == 2) {
-                          SD.remove(FileLocation(aSerialStringParse[2].toInt())); //Get the full file name of the selected file, then delete it
-                          Serial.println(F("file deleted"));
-                          Serial.println(FileLocation(aSerialStringParse[2].toInt()));
-                      } else {
-                          Serial.println(F("Bad syntax"));
-                      }
-                  }
-
-            //Channel configuration
-                if (aSerialStringParse[1]=="c") {
-                    if (aSerialStringParse[0].toInt() == 6 && aSerialStringParse[2].toInt() <=3) {
-                        if (aSerialStringParse[5].toFloat()> 0) {
-                            int ChNumber = aSerialStringParse[2].toInt();
-                            int EEPROMAddress;
-                            struct ADCChan  * Ch;
-                            if (ChNumber == 0) {
-                                Ch = &Ch0;
-                                EEPROMAddress = 10;
-                            } else if (ChNumber == 1) {
-                                Ch = &Ch1;
-                                EEPROMAddress = 26;
-                            } else if (ChNumber == 2) {
-                                Ch = &Ch2;
-                                EEPROMAddress = 42;
-                            } else if (ChNumber == 3) {
-                                Ch = &Ch3;
-                                EEPROMAddress = 58;
-                            }
-                            //Update Channel cfg
-                               Ch->ActualLo = aSerialStringParse[3].toFloat();
-                               Ch->ActualHi = aSerialStringParse[4].toFloat();
-                               Ch->Deadband = aSerialStringParse[5].toFloat();
-                               Ch->Calib    = aSerialStringParse[6].toFloat();
-                            //Update EEPROM
-                                EEPROM.put(EEPROMAddress,Ch->Calib); EEPROMAddress = EEPROMAddress + 4;
-                                EEPROM.put(EEPROMAddress,Ch->ActualLo); EEPROMAddress = EEPROMAddress + 4;
-                                EEPROM.put(EEPROMAddress,Ch->ActualHi); EEPROMAddress = EEPROMAddress + 4;
-                                EEPROM.put(EEPROMAddress,Ch->Deadband);
-
-                              getInputs(); //Update inputs with new config data
-
-                          Serial.print(F("Ch")); Serial.print(ChNumber); Serial.println(F(" Updated"));
-                        } else {
-                          Serial.println(F("Deadband cannot be 0"));
-                        }
-                    } else {
-                      Serial.println(F("Bad syntax"));
-                    }
-                }
-      }
-
-      sLastSerialLine = ""; //Clear out buffer, This should ALWAYS be the last line in this if..then
-  }
-
-
-
-
-
-}
-//==============================================================================================
-void serialEvent() {
-  while (Serial.available()) {
-
-    char inChar = (char)Serial.read();// get the new byte:
-
-    if (inChar == '\n' || inChar == '\r' ) {//if the incoming character is a LF or CR finish the string
-      sLastSerialLine = sSerialBuffer; //Transfer the entire string into the last serial line
-      sSerialBuffer = ""; // clear the string buffer to prepare it for more data:
-      break;
-    }
-
-    sSerialBuffer += inChar;// add it to the inputString:
-  }
-}
-//==============================================================================================
-void EndProgram(String ErrorMessage ) {
-
-  //An unrecoverable error occured
-  //Loop forever and display the error message
-  while(1) {
-    Serial.print(F("Major Error: "));
-    Serial.println(ErrorMessage);
-    Serial.println(F("Unit is not recorded data.  Cycle power to restart (probably won't help)"));
-    delay(5000);
-  }
-}
-
-
-//==============================================================================================
-void PrintChannelLive(struct ADCChan *Ch) {
-  //Print Channel Config Horizontally
-
-     Serial.print(Ch->mA,4); Serial.print("mA/"); Serial.print(Ch->Actual,Ch->Precision); Serial.print(F("\t"));
-  }
-//==============================================================================================
-void PrintChannelConfigHor(struct ADCChan *Ch) {
-  //Print Channel Config Horizontally
-  Serial.print(Ch->mA,3);
-  Serial.print("\t\t");
-  Serial.print(Ch->Current,Ch->Precision);
-  Serial.print("\t\t");
-  Serial.print(Ch->Actual,Ch->Precision);
-  Serial.print("\t\t");
-  Serial.print(Ch->ActualLo,Ch->Precision);
-  Serial.print("\t\t");
-  Serial.print(Ch->ActualHi,Ch->Precision);
-  Serial.print("\t\t");
-  Serial.print(Ch->Deadband,Ch->Precision);
-  Serial.print("\t\t");
-  Serial.print(Ch->Calib,6);
-  Serial.println("");
-
-  }
-
-//==============================================================================================
-
-void printDirectory(File dir) {
-
-  Serial.println(F("Name\t\tsize(bytes)\tEst print Time(sec)"));
-  while (true) {
-    File entry =  dir.openNextFile();
-    if (! entry) { break;}// no more files
-      //Serial.print('\t');
-    Serial.print(entry.name());
-    Serial.print("\t");
-    unsigned long SIZE = entry.size();
-    Serial.print(SIZE, DEC);
-    Serial.print("\t\t");
-    Serial.println(SIZE/20000);
-
-    entry.close();
-  }
-}


Update theftprotection_BLE.ino

Update theftprotection_BLE.ino

--- theftprotection_BLE/theftprotection_BLE.ino
+++ theftprotection_BLE/theftprotection_BLE.ino
@@ -479,11 +479,10 @@
 // End of Bluetooth setup

 typedef struct {
-  int mode;
   bool theftprotection;
   float lat;
   float lng;
-  //float temperature;
+  int temperature;
 } Payload;

 void loop()
@@ -579,11 +578,10 @@
 //        Serial.println(" *C");
 //    }

-    p.mode = 1;
     p.theftprotection = ftheftprotection;
     p.lat = flat;
     p.lng = flon;
-    //p.temperature = temp;
+    p.temperature = 0;

     // IF FLOAT is to long for SigFox-Message
     //int temp = (int) DHT.temperature;


testing

testing

--- programmaNano/programmaNano.ino
+++ programmaNano/programmaNano.ino
@@ -18,6 +18,8 @@
 int coilb2 = 9;
 int enable = 10;

+int draainaarbeneden = 40;
+int positie = 0;

 int maximumRange = 200;                   // Maximum range needed
 int minimumRange = 0;                     // Minimum range needed
@@ -57,9 +59,53 @@

      if (currentMillis - previousMillis >= interval) {
         Distance();
+            if(draainaarbeneden>0){
+
+
+              switch(positie){
+                case 0:
+                  a1Enb2();
+                  positie++;
+                  break;
+                case 1:
+                  b2();
+                  positie++;
+                  break;
+                case 2:
+                  b2Ena2();
+                  positie++;
+                  break;
+                case 3:
+                  a2();
+                  positie++;
+                  break;
+                case 4:
+                  a2Enb1();
+                  positie++;
+                  break;
+                case 5:
+                  b1();
+                  positie++;
+                  break;
+                case 6:
+                  b1Ena1();
+                  positie++;
+                  break;
+                case 7:
+                  a1();
+                  positie = 0;
+                  draainaarbeneden--;
+                  break;
+              }
+
+            }
         previousMillis = currentMillis;
-     }
-    }
+
+    }
+
+
+
+
 }

 void Distance() { // meet de afstand van de sensor
@@ -92,65 +138,62 @@
   Serial.println(distance);
 }

-void 1draaiNaarBeneden(){
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor && currentMillis - previousMillisStappenmotor < intervalStappenmotor+10) {
-    digitalWrite(coila1, HIGH);
-    digitalWrite(coila2, LOW);
-    digitalWrite(coilb1, LOW);
-    digitalWrite(coilb2, HIGH);
-  }
-
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor+10 && currentMillis - previousMillisStappenmotor < intervalStappenmotor+20) {
-
-    digitalWrite(coila1, LOW);
-    digitalWrite(coila2, LOW);
-    digitalWrite(coilb1, LOW);
-    digitalWrite(coilb2, HIGH);
-  }
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor+20 && currentMillis - previousMillisStappenmotor < intervalStappenmotor+30) {
-
-    digitalWrite(coila1, LOW);
-    digitalWrite(coila2, HIGH);
-    digitalWrite(coilb1, LOW);
-    digitalWrite(coilb2, HIGH);
-
-  }
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor+30 && currentMillis - previousMillisStappenmotor < intervalStappenmotor+40) {
-
-    digitalWrite(coila1, LOW);
-    digitalWrite(coila2, HIGH);
-    digitalWrite(coilb1, LOW);
-    digitalWrite(coilb2, LOW);
-  }
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor+40&& currentMillis - previousMillisStappenmotor < intervalStappenmotor+50) {
-
-    digitalWrite(coila1, LOW);
-    digitalWrite(coila2, HIGH);
-    digitalWrite(coilb1, HIGH);
-    digitalWrite(coilb2, LOW);
-  }
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor+50 && currentMillis - previousMillisStappenmotor < intervalStappenmotor+60) {
-
-    digitalWrite(coila1, LOW);
-    digitalWrite(coila2, LOW);
-    digitalWrite(coilb1, HIGH);
-    digitalWrite(coilb2, LOW);
-  }
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor+60 && currentMillis - previousMillisStappenmotor < intervalStappenmotor+70) {
-
-    digitalWrite(coila1, HIGH);
-    digitalWrite(coila2, LOW);
-    digitalWrite(coilb1, HIGH);
-    digitalWrite(coilb2, LOW);
-  }
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor+70) {
-  previousMillisStappenmotor = currentMillis;
-    digitalWrite(coila1, HIGH);
-    digitalWrite(coila2, LOW);
-    digitalWrite(coilb1, LOW);
-    digitalWrite(coilb2, LOW);
-  }
-}
+
+
+void a1Enb2(){
+    digitalWrite(coila1, HIGH);
+    digitalWrite(coila2, LOW);
+    digitalWrite(coilb1, LOW);
+    digitalWrite(coilb2, HIGH);
+}
+
+void b2(){
+    digitalWrite(coila1, LOW);
+    digitalWrite(coila2, LOW);
+    digitalWrite(coilb1, LOW);
+    digitalWrite(coilb2, HIGH);
+}
+void b2Ena2(){
+    digitalWrite(coila1, LOW);
+    digitalWrite(coila2, HIGH);
+    digitalWrite(coilb1, LOW);
+    digitalWrite(coilb2, HIGH);
+}
+void a2(){
+    digitalWrite(coila1, LOW);
+    digitalWrite(coila2, HIGH);
+    digitalWrite(coilb1, LOW);
+    digitalWrite(coilb2, LOW);
+}
+void a2Enb1(){
+    digitalWrite(coila1, LOW);
+    digitalWrite(coila2, HIGH);
+    digitalWrite(coilb1, HIGH);
+    digitalWrite(coilb2, LOW);
+}
+void b1(){
+    digitalWrite(coila1, LOW);
+    digitalWrite(coila2, LOW);
+    digitalWrite(coilb1, HIGH);
+    digitalWrite(coilb2, LOW);
+}
+void b1Ena1(){
+    digitalWrite(coila1, HIGH);
+    digitalWrite(coila2, LOW);
+    digitalWrite(coilb1, HIGH);
+    digitalWrite(coilb2, LOW);
+}
+void a1(){
+    digitalWrite(coila1, HIGH);
+    digitalWrite(coila2, LOW);
+    digitalWrite(coilb1, LOW);
+    digitalWrite(coilb2, LOW);
+}
+
+
+
+
+

 void 1draaiNaarBoven(){
   if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor && currentMillis - previousMillisStappenmotor < intervalStappenmotor+10) {


version str

version str

--- d_BacpacCommands.ino
+++ d_BacpacCommands.ino
@@ -1,4 +1,4 @@
-#define MEWPRO_VERSION_STRING "2015100800"
+#define MEWPRO_VERSION_STRING "2016020200"

 void _sendTD()
 {


Updated MRLComm so that it compilies on other platforms than the ESP8266

--- src/resource/Arduino/MRLComm/MRLComm.ino
+++ src/resource/Arduino/MRLComm/MRLComm.ino
@@ -107,7 +107,9 @@
 	// send back load time and memory
         // driven by getBoardInfo now !!!
         // mrlComm.publishBoardStatus();
-  webSocket.loop();
+  #if defined(ESP8266)
+    webSocket.loop();
+  #endif
 } // end of big loop


Using setTextColor with background instead of fillRect for wiping off invalid pixels before re-drawing text

--- ArduinoAudioSpectrumAnalyzer.ino
+++ ArduinoAudioSpectrumAnalyzer.ino
@@ -26,10 +26,10 @@
 {
 	// TODO:
 	// TIMSK0 = 0; // turn off timer0 for lower jitter
+
 	setupADC();

-	// Use this initializer (uncomment) if you're using a 1.44" TFT
-	tft.initR(ST7735_INITR_144GREENTAB);   // initialize a ST7735S chip, black tab
+	tft.initR(ST7735_INITR_144GREENTAB);   // initialize a ST7735S chip, 1.44" TFT, black tab
 	tft.fillScreen(ST7735_BLACK);
 	tft.setTextWrap(false);
 	tft.setTextSize(2);
@@ -149,18 +149,15 @@
 	//tft.setCursor(0, 0);
 	//tft.print(minSampleValue);

-	tft.fillRect(45, 0, 40, 25, ST7735_BLACK);
-	tft.setTextColor(RGB_to_565(255, 0, 10));
+	tft.setTextColor(RGB_to_565(255, 0, 10), RGB_to_565(0, 0, 0));
 	tft.setCursor(45, 0);
 	tft.print(maxSampleValue);

-	tft.fillRect(90, 0, 40, 25, ST7735_BLACK);
-	tft.setTextColor(RGB_to_565(0, 255, 10));
+	tft.setTextColor(RGB_to_565(0, 255, 10), RGB_to_565(0, 0, 0));
 	tft.setCursor(90, 0);
 	tft.print(averageSampleValue);

-	tft.fillRect(0, 0, 40, 25, ST7735_BLACK);
-	tft.setTextColor(RGB_to_565(0, 200, 255));
+	tft.setTextColor(RGB_to_565(0, 200, 255), RGB_to_565(0, 0, 0));
 	tft.setCursor(0, 0);
 	tft.print(millis() - start);
 }


Bugfixes; peak level animation added

Bugfixes; peak level animation added

--- ArduinoAudioSpectrumAnalyzer.ino
+++ ArduinoAudioSpectrumAnalyzer.ino
@@ -137,7 +137,7 @@
 #define RGB_to_565(R, G, B) static_cast<uint16_t>(((R & 0xF8) << 8) | ((G & 0xFC) << 3) | (B >> 3))

 constexpr uint16_t textYpos = 0;
-constexpr uint16_t vuYpos = textYpos + 5, vuHeight = 10;
+constexpr uint16_t vuYpos = textYpos + 25 + 5, vuHeight = 10;
 constexpr uint16_t spectrumYpos = vuYpos + vuHeight;

 constexpr int ScreenWidth = 128, ScreenHeight = 128;
@@ -179,7 +179,7 @@

 	tft.setTextColor(RGB_to_565(0, 255, 10), RGB_to_565(0, 0, 0));
 	tft.setCursor(90, 0);
-	tft.print(paddedString(String(minSampleValue), 4));
+	tft.print(paddedString(String(rmsHistory.back()), 4));

 	tft.setTextColor(RGB_to_565(0, 200, 255), RGB_to_565(0, 0, 0));
 	tft.setCursor(0, 0);
@@ -196,14 +196,27 @@
 	//const auto rmsExtremums = findMinMax(rmsHistory);
 	const int8_t db = 10.0f * log10(rmsHistory.back() / 1024.0f);

-	constexpr int vuTextWidth = 50;
+	constexpr int vuTextWidth = 6 * 6;
+
+	static auto previousPeak = peakHistory.back();
+
+	auto peak = peakHistory.back();
+	if (peak < previousPeak && peak >= 48)
+		peak = previousPeak - 48;
+
+	previousPeak = peak;
+
 	const auto barWidth = rmsHistory.back() * (ScreenWidth - vuTextWidth) / 1024;
+	auto peakLevelXpos = peak * (ScreenWidth - vuTextWidth) / 1024;
+	if (peakLevelXpos < barWidth)
+		peakLevelXpos = barWidth;

 	tft.fillRect(0, vuYpos, barWidth, vuHeight, RGB_to_565(0, 255, 30));
 	tft.fillRect(barWidth + 1, vuYpos, ScreenWidth - vuTextWidth - barWidth, vuHeight, RGB_to_565(0, 0, 0));
-	tft.drawFastVLine(peakHistory.back(), vuYpos, vuHeight, RGB_to_565(255, 0, 0));
+	tft.drawFastVLine(peakLevelXpos, vuYpos, vuHeight, RGB_to_565(255, 0, 30));

 	tft.setTextSize(1);
+	tft.setCursor(ScreenWidth - vuTextWidth, vuYpos);
 	tft.setTextColor(RGB_to_565(0, 255, 0), RGB_to_565(0, 0, 0));
 	tft.print(paddedString(String(db), 3, false) + " dB");
 }


speed limit changed

speed limit changed

--- stacks/undercarriage/src/SpaceShuttleDrive/SpaceShuttleDrive.ino
+++ stacks/undercarriage/src/SpaceShuttleDrive/SpaceShuttleDrive.ino
@@ -53,15 +53,15 @@
 long act_y = 0;
 long act_rotate = 0;

-long maxRotSpeed = 1000L;  // 16000L
-long maxMoveSpeed = 1000L; // 16000L
-long moveSpeed = 40L; // 2000L
+long maxMoveSpeed = 5000L; // 16000L
+long maxRotSpeed = 5000L;  // 16000L
+long moveSpeed = 5000L; // 2000L

 int millivoltAvg;
 int millivolt;
 int loopCnt = 0;

-#define DTIMEOUT 2000
+#define DTIMEOUT 500
 uint16_t driveTimeout = 0;

 void setup()
@@ -115,8 +115,10 @@
   Serial.begin(38400);
 }

+int calcspeed_interval = 0;
+
 void loop() {
-  serialParser();
+
   stepper1.runSpeed();
   stepper2.runSpeed();
   stepper3.runSpeed();
@@ -124,6 +126,12 @@
   if(((uint16_t)millis() - driveTimeout) > DTIMEOUT) {
     driveTimeout = millis();
     drive(0,0,0);
+  }
+
+  if(calcspeed_interval++>500) {
+    serialParser();
+    calcspeed_interval = 0;
+    calcSpeed();
   }

   if(loopCnt++ > 5000) {
@@ -141,8 +149,45 @@
   }
 }

-
-
+long target_x = 0L;
+long target_y = 0L;
+long target_r = 0L;
+
+
+void calcSpeed()
+{
+  long delta_x = target_x - act_x;
+  long delta_y = target_y - act_y;
+  long delta_r = target_r - act_rotate;
+
+  if(abs(delta_x)>10L)
+  {
+    act_x = act_x + round(delta_x/10L);
+  } else {
+    act_x = target_x;
+  }
+
+  if(abs(delta_y)>10L)
+  {
+    act_y = act_y + round(delta_y/10L);
+  } else {
+    act_y = target_y;
+  }
+
+  if(abs(delta_r)>10L)
+  {
+    act_rotate = act_rotate + round(delta_r/10L);
+  } else {
+    act_rotate = target_r;
+  }
+
+
+  // act_x = constrain(x*32L,-16000L,16000L);
+  // act_y = constrain(y*32L,-16000L,16000L);
+  // act_rotate = constrain(rotate*-64L,-16000L,16000L);
+
+  updateWheels();
+}

 void updateWheels() {
   // calculate wheel speeds
@@ -151,7 +196,7 @@
   lr = -act_x + act_y + act_rotate;
   rr = -act_x - act_y + act_rotate;

-  if((lf == 0) && (rf == 0) && (lr == 0) && (rr == 0)) {
+  if((lf == 0L) && (rf == 0L) && (lr == 0L) && (rr == 0L)) {
     digitalWrite(STEPPER1_STEP_EN, HIGH); // enable pin LOW = on
     digitalWrite(STEPPER2_STEP_EN, HIGH); // enable pin LOW = on
     digitalWrite(STEPPER3_STEP_EN, HIGH); // enable pin LOW = on
@@ -171,11 +216,10 @@

 void drive(long x, long y, long rotate) {
   // later: add acceleration here
-  act_x = constrain(x*32L,-16000L,16000L);
-  act_y = constrain(y*32L,-16000L,16000L);
-  act_rotate = constrain(rotate*-64L,-16000L,16000L);
-
-  updateWheels();
+
+  target_x = x;
+  target_y = y;
+  target_r = rotate;
 }

 void serialParser() {
@@ -227,6 +271,13 @@
           case 'd':
             drive(moveSpeed,0L,0L);
             driveTimeout = millis();
+            break;
+          case 'i':
+            Serial.print(act_x);
+            Serial.print(',');
+            Serial.print(act_y);
+            Serial.print(',');
+            Serial.println(act_rotate);
             break;

           case 'm': // move


Double checking Conditional

Double checking Conditional

--- DebugManchester.ino
+++ DebugManchester.ino
@@ -122,13 +122,13 @@
       }//end of dealing with ones
       else{  //bitState==0 could first error, first zero or packet
         // if it is header there must be no "zeroes" or errors
-        if((headerHits<headerBits)&&(!firstZero)){
+        if(headerHits<headerBits){
           //Still in header checking phase, more header hits required
           noErrors=false;//landing here means header is corrupted, so it is probably an error
         }//end of detecting a "zero" inside a header
         else{
           //we have our header, chewed up any excess and here is a zero
-          if (!firstZero){ //if first zero, it has not been found previously
+          if (!firstZero && (headerHits>=headerBits)){ //if first zero, it has not been found previously
             firstZero=true;
           }//end of finding first zero
           add(bitState);


Finished squareRoutine. Prototype only! In need of review!

--- Elcano_C2_LowLevel/Elcano_C2_LowLevel.ino
+++ Elcano_C2_LowLevel/Elcano_C2_LowLevel.ino
@@ -78,6 +78,7 @@
 int max_rc = MAX_RC;
 int mid = MIDDLE;
 int min_rc = MIN_RC;
+#define LED_PIN_OUT 16
 //==========================================================================================
 void ISR_TURN_rise() {
   noInterrupts();
@@ -229,7 +230,7 @@
   steer(STRAIGHT_TURN_OUT);
   brake(MAX_BRAKE_OUT);
   moveVehicle(MIN_ACC_OUT);
-  setup7seg();    // Initialize 7 segment display for speedometer
+  //setup7seg();    // Initialize 7 segment display for speedometer
   delay(500);   // let vehicle stabilize
   //brake(MIN_BRAKE_OUT);
   Serial.begin(9600);
@@ -243,7 +244,7 @@
   {
     speed_errors[i] = 0;
   }
-  setupWheelRev(); // WheelRev4 addition
+  //setupWheelRev(); // WheelRev4 addition
   CalibrateTurnAngle(32, 20);
   calibrationTime_ms = millis();
         attachInterrupt(digitalPinToInterrupt(IRPT_TURN),  ISR_TURN_rise,  RISING);
@@ -284,10 +285,10 @@
     processHighLevel(&Results);
   //    Print7( true, local_results);

-//  Results.Clear();
-//  Results.kind = MSG_SENSOR;
-//  Results.angle_deg = TurnAngle_degx10() / 10;
-  show_speed (&Results);
+  Results.Clear();
+  Results.kind = MSG_SENSOR;
+  Results.angle_deg = TurnAngle_degx10() / 10;
+  //show_speed (&Results);

   // Report how long the loop took.
   unsigned long endTime = micros();
@@ -429,17 +430,19 @@
 /*---------------------------------------------------------------------------------------*/
 //squareRoutine
 void squareRoutine(unsigned long seconds, unsigned long &results) {
+  Serial.println("Starting square routine...");
   results = HIGH;
   long straightSpeed = 2500;
   long turnSpeed = 1250;
   unsigned long startTime = millis();
+  unsigned long loopTime;
   seconds = seconds * 1000;
   while(millis() < (startTime + seconds)){
     //steer(LEFT_TURN_OUT);
     steer(STRAIGHT_TURN_OUT);
     delay(1000);

-    unsigned long loopTime = millis();
+    loopTime = millis();
     while (millis() < (loopTime + 2000)) {
       Throttle_PID(straightSpeed);
     }
@@ -450,6 +453,7 @@
     float turnDist = TURN_RADIUS_CM * PI / 2 * 10; //turnDist == 1/4 turn circumference in mm
     long turnSec = (long)turnDist / turnSpeed * 1000; //turnSec == time for 90-degree turn at 1250 mm/s

+    loopTime = millis();
     while (millis() < (loopTime + turnSec)) {
       Throttle_PID(turnSpeed);
     }
@@ -595,7 +599,7 @@
   int turn_signal = convertDeg(results->angle_deg);
   steer(turn_signal);
   //End Steer
-   //Throttle
+  //Throttle
   Throttle_PID(10*results->speed_cmPs);
   //End Throttle
   writeSerial(&Serial3, results);
@@ -659,7 +663,7 @@
   const int actuatorRange = LEFT_TURN_OUT - RIGHT_TURN_OUT;
   const int degRange = TURN_MAX_DEG * 2;
   deg += TURN_MAX_DEG;
-  float operand = (float)deg / (float)degRange;
+  double operand = (double)deg / (double)degRange;
   operand *= actuatorRange;
   operand += RIGHT_TURN_OUT;
   //set max values if out of range
@@ -870,7 +874,8 @@
 } history;

 /*---------------------------------------------------------------------------------------*/
-// WheelRev is called by an interrupt pin.
+// WheelRev is called by an interrupt.
+// This is all WAY TOO LONG for an interrupt
 void WheelRev()
 {
   //static int flip = 0;


Fine-tuning of squareRoutine(). Still unfinished!

--- Elcano_C2_LowLevel/Elcano_C2_LowLevel.ino
+++ Elcano_C2_LowLevel/Elcano_C2_LowLevel.ino
@@ -437,8 +437,8 @@

 /*---------------------------------------------------------------------------------------*/
 //circleRoutine
-void circleRoutine(unsigned long seconds, unsigned long &results) {
-  results = HIGH;
+void circleRoutine(unsigned long seconds, unsigned long &rcAuto) {
+  rcAuto = HIGH;

   steer(LEFT_TURN_OUT);
   delay(1000);
@@ -447,19 +447,21 @@
   while (millis() < (loopTime + seconds)) {
     moveVehicle(128);
   }
-  results = LOW;
+  rcAuto = LOW;
 }
 /*---------------------------------------------------------------------------------------*/
 //squareRoutine
-void squareRoutine(unsigned long sides, unsigned long &results) {
+void squareRoutine(unsigned long sides, unsigned long &rcAuto) {
   Serial.println("Starting square routine...");
-  results = HIGH;
-  long straightSpeed = 128;        //mmPs
-  long turnSpeed = 96;            //mmPs
+  rcAuto = HIGH;
+  long straightSpeed = 2750;        //mmPs
+  long turnSpeed = 1400;            //mmPs
   sides = sides * 1000;             //convert side length to mm
   unsigned long sideSec = sides / straightSpeed;  //calculate seconds per side at set speed
   sideSec = sideSec * 1000;         //convert to ms
   unsigned long loopTime;           //start time of while loops for throttle
+  float turnDist = TURN_RADIUS_CM * PI / 2 * 10; //turnDist == 1/4 turn circumference in mm
+  unsigned long turnSec = (long)turnDist / turnSpeed * 1000; //turnSec == time for 90-degree turn at 1250 mmPs
   for(int i = 0; i < 4; i++){
     //steer(LEFT_TURN_OUT);
     steer(STRAIGHT_TURN_OUT);
@@ -467,21 +469,20 @@

     loopTime = millis();
     while (millis() < (loopTime + sideSec)) {
-      moveVehicle(straightSpeed);
+      moveVehicle(112);
     }

     steer(LEFT_TURN_OUT);
     delay(100);

-    float turnDist = TURN_RADIUS_CM * PI / 2 * 10; //turnDist == 1/4 turn circumference in mm
-    unsigned long turnSec = (long)turnDist / turnSpeed * 1000; //turnSec == time for 90-degree turn at 1250 mmPs
+

     loopTime = millis();
     while (millis() < (loopTime + turnSec)) {
-      moveVehicle(turnSpeed);
+      moveVehicle(96);
     }
   }
-  results = LOW;
+  rcAuto = LOW;
 }
 /*---------------------------------------------------------------------------------------*/
 void startCapturingRCState(){
@@ -549,10 +550,10 @@
   results[RC_ESTP] = (results[RC_ESTP] > MIDDLE ? HIGH : LOW);

   if (results[RC_ESTP] == HIGH){
+    Serial.println("Exiting processRC due to E-stop.");
     E_Stop();  // already done at interrupt level
     if ((results[RC_AUTO] == LOW)  && (NUMBER_CHANNELS > 5)) // under RC control
       ;//steer(results[RC_TURN]);
-    Serial.println("Exiting processRC due to E-stop.");
     return 0x00;
   }

@@ -594,7 +595,7 @@
   }
   else if(doRoutine(results[RC_RDR])){
     moveVehicle(MIN_ACC_OUT);
-    squareRoutine(20, results[RC_AUTO]);
+    squareRoutine(5, results[RC_AUTO]);
   }
   else {
     moveVehicle(MIN_ACC_OUT);


Fix whitespace woes

Fix whitespace woes

--- MagnusCore/MagnusCore.ino
+++ MagnusCore/MagnusCore.ino
@@ -1,8 +1,8 @@
 #include <Adafruit_NeoPixel.h>
 #include <stdlib.h>
 #include <string.h>
-#include "animation.hpp"
-#include "circbuff.hpp"
+#include "animation.hpp"
+#include "circbuff.hpp"

 // first communication pin for neo pixel string
 #define BASE_PIN 2
@@ -49,7 +49,7 @@

 // Serial I/O
 const int ioSize = 64;
-char command[32];
+char command[32];
 int8_t in_index = 0;

 void start_serial(void)
@@ -125,107 +125,107 @@
 {
   uint16_t i, val;

-  if( collect_serial() )
-  {
-      // we have valid buffer of serial input
-      char cmd = command[0] & CASE_MASK;
-      switch (cmd) {
+  if( collect_serial() )
+  {
+      // we have valid buffer of serial input
+      char cmd = command[0] & CASE_MASK;
+      switch (cmd) {
           case '*':
             Serial.println("Magnus Core Node");
             break;
-          case 'E':
-          case 'R':
-              owner = cmd == 'E' ? enlightened : resistance;
-              percent = getPercent(&command[1]);
-              uint8_t red, green, blue, white;
-              Color c;
-              c = ToColor(0x00,
-                  owner == enlightened ? 0xff : 0x00,
-                  owner == resistance ? 0xff : 0x00,
-                  0x00);
-              animations.pulse.init(states[0], strip, c);
-//              pCurrAnimation = &animations.pulse;
-              animationQueue.setTo(&animations.pulse);
-              break;
-
-          case 'N':
-              owner = neutral;
-              animations.redFlash.init(states[0], strip, RGBW_SUPPORT);
-              animationQueue.setTo(&animations.redFlash);
-              animationQueue.add(&animations.solid);
-              percent = 20;
-              break;
-
-          default:
-              Serial.print("Unkwown command "); Serial.println(cmd);
-              break;
-      }
-      Serial.print((char *)command); Serial.print(" - ");Serial.print(command[0],DEC);Serial.print(": ");
-      Serial.print("owner "); Serial.print(owner,DEC); Serial.print(", percent "); Serial.println(percent,DEC);
-  }
-
-  if(strings[dir].timing < millis() )
-  {
-      strings[dir].timing += 10; // every 100 milliseconds we will check this direction
-
-      strip.setPin(dir+BASE_PIN);  // pick the string
-
-      uint8_t red, green, blue, white;
-      red = 0x20; green = 0; blue = 0x20; white = 0x20;
-      bool useAnimations = false;
-      if( owner == neutral )
-      {
-          red = 0x40; green = 0x40; blue = 0x40; white = 0x40;
-          //      red = 0; green = 0; blue = 0; white = 0x40;
-          useAnimations = true;
-      }
-      else if( owner == resistance )
-      {
-          red = 0; green = 0x1f; blue = 0xff;; white = 0;
-          useAnimations = true;
-      }
-      else if( owner == enlightened )
-      {
-          red = 0x1f; green = 0xff; blue = 0; white = 0;
-          useAnimations = true;
-      }
-
-      if (useAnimations) {
-          unsigned int queueSize = animationQueue.size();
-          if (queueSize > 1) {
-              if (animationQueue.peek()->done(states[0])) {
-                  animationQueue.remove();
-                  queueSize--;
-                  animationQueue.peek()->start(states[0]);
-              }
-          }
-          if (queueSize > 0) {
-              //strip.setBrightness(255);
-              strip.setBrightness((uint8_t)((uint16_t)(255*(percent/100.0))));
-              //pCurrAnimation->doFrame(states[0], strip);
-              animationQueue.peek()->doFrame(states[0], strip);
-          }
-      } else {
-          for(i=0; i < strip.numPixels(); i++)
-          {
-              //strip.setPixelColor(i, green,blue,red); // for RGB order is funny?
-              //        strip.setPixelColor(i, green, red, blue,white);
-              strip.setPixelColor(i, red, green, blue);
-              //        float scale = ((millis()/100)%100)/200.0 + 0.5;
-              float scale = 1.0f;
-              float pct = percent * scale;
-              //        Serial.print("Percent: "); Serial.println(pct, 4);
-              strip.setBrightness((uint8_t)((uint16_t)(255*(pct/100.0))));
-          }
-          strip.show();
-      }
-
-      dir++;
-      if( dir >= NUM_STRINGS )
-          dir = 0;
-  }
-
-
-}
-
-
+          case 'E':
+          case 'R':
+              owner = cmd == 'E' ? enlightened : resistance;
+              percent = getPercent(&command[1]);
+              uint8_t red, green, blue, white;
+              Color c;
+              c = ToColor(0x00,
+                  owner == enlightened ? 0xff : 0x00,
+                  owner == resistance ? 0xff : 0x00,
+                  0x00);
+              animations.pulse.init(states[0], strip, c);
+//              pCurrAnimation = &animations.pulse;
+              animationQueue.setTo(&animations.pulse);
+              break;
+
+          case 'N':
+              owner = neutral;
+              animations.redFlash.init(states[0], strip, RGBW_SUPPORT);
+              animationQueue.setTo(&animations.redFlash);
+              animationQueue.add(&animations.solid);
+              percent = 20;
+              break;
+
+          default:
+              Serial.print("Unkwown command "); Serial.println(cmd);
+              break;
+      }
+      Serial.print((char *)command); Serial.print(" - ");Serial.print(command[0],DEC);Serial.print(": ");
+      Serial.print("owner "); Serial.print(owner,DEC); Serial.print(", percent "); Serial.println(percent,DEC);
+  }
+
+  if(strings[dir].timing < millis() )
+  {
+      strings[dir].timing += 10; // every 100 milliseconds we will check this direction
+
+      strip.setPin(dir+BASE_PIN);  // pick the string
+
+      uint8_t red, green, blue, white;
+      red = 0x20; green = 0; blue = 0x20; white = 0x20;
+      bool useAnimations = false;
+      if( owner == neutral )
+      {
+          red = 0x40; green = 0x40; blue = 0x40; white = 0x40;
+          //      red = 0; green = 0; blue = 0; white = 0x40;
+          useAnimations = true;
+      }
+      else if( owner == resistance )
+      {
+          red = 0; green = 0x1f; blue = 0xff;; white = 0;
+          useAnimations = true;
+      }
+      else if( owner == enlightened )
+      {
+          red = 0x1f; green = 0xff; blue = 0; white = 0;
+          useAnimations = true;
+      }
+
+      if (useAnimations) {
+          unsigned int queueSize = animationQueue.size();
+          if (queueSize > 1) {
+              if (animationQueue.peek()->done(states[0])) {
+                  animationQueue.remove();
+                  queueSize--;
+                  animationQueue.peek()->start(states[0]);
+              }
+          }
+          if (queueSize > 0) {
+              //strip.setBrightness(255);
+              strip.setBrightness((uint8_t)((uint16_t)(255*(percent/100.0))));
+              //pCurrAnimation->doFrame(states[0], strip);
+              animationQueue.peek()->doFrame(states[0], strip);
+          }
+      } else {
+          for(i=0; i < strip.numPixels(); i++)
+          {
+              //strip.setPixelColor(i, green,blue,red); // for RGB order is funny?
+              //        strip.setPixelColor(i, green, red, blue,white);
+              strip.setPixelColor(i, red, green, blue);
+              //        float scale = ((millis()/100)%100)/200.0 + 0.5;
+              float scale = 1.0f;
+              float pct = percent * scale;
+              //        Serial.print("Percent: "); Serial.println(pct, 4);
+              strip.setBrightness((uint8_t)((uint16_t)(255*(pct/100.0))));
+          }
+          strip.show();
+      }
+
+      dir++;
+      if( dir >= NUM_STRINGS )
+          dir = 0;
+  }
+
+
+}
+
+


fix bug:screen display was sisturbed

fix bug:screen display was sisturbed

--- RssDisp/RssDisp.ino
+++ RssDisp/RssDisp.ino
@@ -99,8 +99,8 @@

 AppState gState;
 int httpCode;
-int iItem;
-int iLayout;
+uint8_t iItem;
+uint8_t iLayout;

 RssBuf rssBuf;
 RssParser rss;
@@ -238,10 +238,11 @@
   if(bInit || t != t0){
     struct tm *tm = localtime(&t);
     const char *wd[7] = {"日","月","火","水","木","金","土"};
+		oled.fillRect(x,y,w,h,0);
 		oled.setTextColor(1,0);
     oled.setTextSize(textSize);
 		oled.alignPrintf(x+w-1,y, TA_RIGHT, TA_TOP,
-										 "%2d/%2d(%s) %d:%d",
+										 "%d/%d(%s) %2d:%02d",
 										 tm->tm_mon+1, tm->tm_mday, wd[tm->tm_wday],
 										 tm->tm_hour, tm->tm_min);
     t0 = t;
@@ -264,9 +265,10 @@
     const char *wd[7] = {"日","月","火","水","木","金","土"};
 		oled.setTextColor(1,0);
     oled.setTextSize(textSize);
+		oled.fillRect(x,y,w,h,0);
 		if(textSize == 1)
 			oled.alignPrintf(x+w-1,y, TA_RIGHT, TA_TOP,
-											 "%04d年%0d月%2d(%s)", tm->tm_year + 1900,
+											 "%04d年%d月%d(%s)", tm->tm_year + 1900,
 											 tm->tm_mon+1, tm->tm_mday, wd[tm->tm_wday]);
 		else if(textSize == 2)
 			oled.alignPrintf(x+w-1,y, TA_RIGHT, TA_TOP,
@@ -288,10 +290,11 @@

   if(t != t0){
     struct tm *tm = localtime(&t);
+		oled.fillRect(x,y,w,h,0);
     oled.setTextSize(textSize);
 		oled.setTextColor(1,0);
     oled.alignPrintf(x+w-1,y, TA_RIGHT, TA_TOP,
-										 "%02d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec);
+										 "%2d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec);
     t0 = t;
   }
 }


The colon blinks faster (two transitions per second)

--- SetTime/SetTime.ino
+++ SetTime/SetTime.ino
@@ -350,19 +350,21 @@
 {
   static int checkInterval = 0;
   static uint32_t prevTime = 0;
+  static bool prevShowColon = 0;
   if (++checkInterval == 1000) {
     checkInterval = 0;
     if (knowTime) {
       noInterrupts();
       uint32_t now = curTime;
+      bool curShowColon = !(curTimeFractions >> 31);
       interrupts();
-      if (now != prevTime) {
+      if (now != prevTime || prevShowColon != curShowColon) {
         prevTime = now;
         struct tm tm;
         gmtime_r(now, &tm);
         int offset = tzOffset(&tm);
         gmtime_r(now + offset, &tm);
-        int colon = (now & 2) == 0 ? B8(0110000) : 0;
+        int colon = curShowColon ? B8(0110000) : 0;
         sendHHMM(tm.tm_hour, tm.tm_min, colon);
         Serial.print(tm.tm_year);
         Serial.print("-");
@@ -379,6 +381,7 @@
         Serial.print(tm.tm_sec);
         Serial.println();
       }
+      prevShowColon = curShowColon;
     }
   }
 }


adding powerAC

adding powerAC

--- _49-emontxv2-esp-01-i2c/esp-01/esp-01.ino
+++ _49-emontxv2-esp-01-i2c/esp-01/esp-01.ino
@@ -8,9 +8,11 @@
 #include <ESP8266mDNS.h>
 #include <WiFiUdp.h>
 #include <ArduinoOTA.h>
+#include <Average.h>
 #include "/usr/local/src/ap_setting.h"

-extern "C" {
+extern "C"
+{
 #include "user_interface.h"
 }

@@ -36,7 +38,8 @@
 static const uint8_t RTC_READ_ADDRESS  = 0;

 //
-static uint32_t fnv_1_hash_32(uint8_t *bytes, size_t length) {
+static uint32_t fnv_1_hash_32(uint8_t *bytes, size_t length)
+{
   static const uint32_t FNV_OFFSET_BASIS_32 = 2166136261U;
   static const uint32_t FNV_PRIME_32 = 16777619U;
   uint32_t hash = FNV_OFFSET_BASIS_32;;
@@ -49,7 +52,8 @@
   return fnv_1_hash_32(((uint8_t*)&data) + sizeof(data.hash), sizeof(T) - sizeof(data.hash));
 }

-struct {
+struct
+{
   uint32_t hash;
   uint32_t pls_no;
   uint16_t pls_ts;
@@ -97,12 +101,15 @@
 WiFiClient wifiClient;
 WiFiUDP udp;
 PubSubClient client(mqtt_server, 1883, callback, wifiClient);
-
-void data_isr() {
+Average<float> ave1(10);
+
+void data_isr()
+{
   bdata_is_rdy = digitalRead(DATA_IS_RDY_PIN);
 }

-void ICACHE_RAM_ATTR sendUdpmsg(String msgtosend) {
+void ICACHE_RAM_ATTR sendUdpmsg(String msgtosend)
+{
   unsigned int msg_length = msgtosend.length();
   byte* p = (byte*)malloc(msg_length);
   memcpy(p, (char*) msgtosend.c_str(), msg_length);
@@ -114,7 +121,8 @@
   delay(100);
 }

-void ICACHE_RAM_ATTR sendUdpSyslog(String msgtosend) {
+void ICACHE_RAM_ATTR sendUdpSyslog(String msgtosend)
+{
   unsigned int msg_length = msgtosend.length();
   byte* p = (byte*)malloc(msg_length);
   memcpy(p, (char*) msgtosend.c_str(), msg_length);
@@ -126,13 +134,15 @@
   free(p);
 }

-void ICACHE_RAM_ATTR sendmqttMsg(char* topictosend, String payload) {
+void ICACHE_RAM_ATTR sendmqttMsg(char* topictosend, String payload)
+{
   unsigned int msg_length = payload.length();

   byte* p = (byte*)malloc(msg_length);
   memcpy(p, (char*) payload.c_str(), msg_length);

-  if (client.publish(topictosend, p, msg_length, 1)) {
+  if (client.publish(topictosend, p, msg_length, 1))
+  {
     /*
       syslogPayload = topictosend;
       syslogPayload += " - ";
@@ -141,7 +151,9 @@
       sendUdpSyslog(syslogPayload);
     */
     free(p);
-  } else {
+  }
+  else
+  {
     syslogPayload = topictosend;
     syslogPayload += " - ";
     syslogPayload += payload;
@@ -152,11 +164,13 @@
   client.loop();
 }

-void ICACHE_RAM_ATTR callback(char* intopic, byte* inpayload, unsigned int length) {
+void ICACHE_RAM_ATTR callback(char* intopic, byte* inpayload, unsigned int length)
+{
   String receivedtopic = intopic;
   String receivedpayload ;

-  for (int i = 0; i < length; i++) {
+  for (int i = 0; i < length; i++)
+  {
     receivedpayload += (char)inpayload[i];
   }

@@ -165,12 +179,14 @@
   syslogPayload += receivedpayload;
   sendUdpSyslog(syslogPayload);

-  if ( receivedpayload == "{\"DOOR\":\"CHECKING\"}") {
+  if ( receivedpayload == "{\"DOOR\":\"CHECKING\"}")
+  {
     String check_doorpayload = "{\"DOOR\":";
     if ( sensor_data.door == 0 ) {
       check_doorpayload += "\"CHECK_CLOSED\"";
     }
-    else {
+    else
+    {
       check_doorpayload += "\"CHECK_OPEN\"";
     }
     check_doorpayload += "}";
@@ -179,18 +195,25 @@
 }

 boolean reconnect() {
-  if (!client.connected()) {
-    if (client.connect((char*) clientName.c_str(), willTopic, 0, true, willMessage)) {
+  if (!client.connected())
+  {
+    if (client.connect((char*) clientName.c_str(), willTopic, 0, true, willMessage))
+    {
       client.publish(willTopic, "1", true);
-      if ( ResetInfo == false) {
+      if ( ResetInfo == false)
+      {
         client.publish(hellotopic, (char*) getResetInfo.c_str());
         ResetInfo = true;
-      } else {
+      }
+      else
+      {
         client.publish(hellotopic, "hello again 1 from esp-power");
       }
       client.subscribe(subtopic);
       sendUdpSyslog("---> mqttconnected");
-    } else {
+    }
+    else
+    {
       syslogPayload = "failed, rc=";
       syslogPayload += client.state();
       sendUdpSyslog(syslogPayload);
@@ -200,7 +223,8 @@
   return client.connected();
 }

-void wifi_connect() {
+void wifi_connect()
+{
   //wifi_set_phy_mode(PHY_MODE_11N);
   //system_phy_set_max_tpw(1);

@@ -209,7 +233,8 @@
   WiFi.hostname("esp-emontxv2");

   int Attempt = 0;
-  while (WiFi.status() != WL_CONNECTED) {
+  while (WiFi.status() != WL_CONNECTED)
+  {
     delay(100);
     Attempt++;
     if (Attempt == 300)
@@ -222,7 +247,8 @@
 String macToStr(const uint8_t* mac)
 {
   String result;
-  for (int i = 0; i < 6; ++i) {
+  for (int i = 0; i < 6; ++i)
+  {
     result += String(mac[i], 16);
     if (i < 5)
       result += ':';
@@ -230,7 +256,8 @@
   return result;
 }

-void ICACHE_RAM_ATTR send_raw_data() {
+void ICACHE_RAM_ATTR send_raw_data()
+{

   syslogPayload = "pls_no : ";
@@ -255,7 +282,8 @@
   syslogPayload += sensor_data.door;

   _hash = calc_hash(sensor_data);
-  if (_hash != sensor_data.hash) {
+  if (_hash != sensor_data.hash)
+  {
     syslogPayload += " - hash : ";
     syslogPayload += sensor_data.hash;
     syslogPayload += " != ";
@@ -265,7 +293,8 @@
   sendUdpSyslog(syslogPayload);
 }

-void ICACHE_RAM_ATTR sendtoInfluxdb() {
+void ICACHE_RAM_ATTR sendtoInfluxdb()
+{
   String udppayload = "emontxv2,device=esp-01 ";
   udppayload += "F=";
   udppayload += ESP.getCpuFreqMHz();
@@ -294,8 +323,10 @@
   sendUdpmsg(udppayload);
 }

-bool ICACHE_RAM_ATTR get_i2c_data() {
-  if (digitalRead(DATA_IS_RDY_PIN)) {
+bool ICACHE_RAM_ATTR get_i2c_data()
+{
+  if (digitalRead(DATA_IS_RDY_PIN))
+  {
     pinMode(DATA_IS_RDY_PIN, OUTPUT);
     digitalWrite(DATA_IS_RDY_PIN, LOW);
     delayMicroseconds(5);
@@ -307,12 +338,15 @@
     digitalWrite(DATA_IS_RDY_PIN, HIGH);
     pinMode(DATA_IS_RDY_PIN, INPUT_PULLUP);
     return true;
-  } else {
+  }
+  else
+  {
     return false;
   }
 }

-void setup() {
+void setup()
+{
   system_update_cpu_freq(SYS_CPU_160MHz);
   Serial.swap();
   //
@@ -340,18 +374,22 @@
   ArduinoOTA.setPort(8266);
   ArduinoOTA.setHostname("esp-emontxv2");
   ArduinoOTA.setPassword(otapassword);
-  ArduinoOTA.onStart([]() {
+  ArduinoOTA.onStart([]()
+  {
     sendUdpSyslog("ArduinoOTA Start");
   });
-  ArduinoOTA.onEnd([]() {
+  ArduinoOTA.onEnd([]()
+  {
     sendUdpSyslog("ArduinoOTA End");
   });
-  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
+  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total)
+  {
     syslogPayload = "Progress: ";
     syslogPayload += (progress / (total / 100));
     sendUdpSyslog(syslogPayload);
   });
-  ArduinoOTA.onError([](ota_error_t error) {
+  ArduinoOTA.onError([](ota_error_t error)
+  {
     //ESP.restart();
     if (error == OTA_AUTH_ERROR) abort();
     else if (error == OTA_BEGIN_ERROR) abort();
@@ -372,40 +410,55 @@
 }

 void loop() {
-  if (WiFi.status() == WL_CONNECTED) {
-    if (bdata_is_rdy) {
-      while (!digitalRead(DATA_IS_RDY_PIN)) {
+  if (WiFi.status() == WL_CONNECTED)
+  {
+    if (bdata_is_rdy)
+    {
+      while (!digitalRead(DATA_IS_RDY_PIN))
+      {
         delay(5);
       }
       ok = get_i2c_data();
-      if (sensor_data.pls_ts > 1) {
+      if (sensor_data.pls_ts > 1)
+      {
         pls_p = (float(( 3600  * 1000 ) / ( 600 * float(sensor_data.pls_ts) ) ) * 1000);
-      } else {
+      }
+      else
+      {
         pls_p = 0;
       }
+      ave1.push(sensor_data.ct3_rp);
       //send_raw_data();
       sendtoInfluxdb();
       bdata_is_rdy = false;
     }
-    if (!client.connected()) {
+    if (!client.connected())
+    {
       syslogPayload = "failed, rc= ";
       syslogPayload += client.state();
       sendUdpSyslog(syslogPayload);

       unsigned long now = millis();
-      if (now - lastReconnectAttempt > 200) {
+      if (now - lastReconnectAttempt > 200)
+      {
         lastReconnectAttempt = now;
-        if (reconnect()) {
+        if (reconnect())
+        {
           lastReconnectAttempt = 0;
         }
       }
-    } else {
-      if (bdoor_status != sensor_data.door) {
+    }
+    else
+    {
+      if (bdoor_status != sensor_data.door)
+      {
         doorpayload = "{\"DOOR\":";
-        if ( sensor_data.door == 0 ) {
+        if ( sensor_data.door == 0 )
+        {
           doorpayload += "\"CLOSED\"";
         }
-        else {
+        else
+        {
           doorpayload += "\"OPEN\"";
         }
         doorpayload += "}";
@@ -413,9 +466,19 @@
         bdoor_status = sensor_data.door;
       }

-        if (_hash != sensor_data.hash) {
+        if (_hash != sensor_data.hash)
+        {
         payload = "{\"powerAvg\":";
         payload += sensor_data.ct1_rp;
+        payload = "{\"powerAC\":";
+        if (ave1.mean() > 50)
+        {
+          payload += "1";
+        }
+        else
+        {
+          payload += "0";
+        }
         payload += ",\"FreeHeap\":";
         payload += ESP.getFreeHeap();
         payload += ",\"RSSI\":";
@@ -431,7 +494,9 @@
     }

     ArduinoOTA.handle();
-  } else {
+  }
+  else
+  {
     wifi_connect();
   }
 }


Add logic to attempt to fix zero issue

Add logic to attempt to fix zero issue

--- WirelessTrigger.ino
+++ WirelessTrigger.ino
@@ -45,7 +45,7 @@
 #if ROLE == ROLE_GROUND
 #define HEARTBEAT_INTERVAL_MILLIS 300
 // Altitude is in feet
-#define ALTITUDE_TARGET_THRESH_FEET 10
+#define ALTITUDE_TARGET_THRESH_FEET 100

 // can be digital pinsa
 uint8_t triggerButtonPin = A0;
@@ -78,6 +78,7 @@

 // Should be a PWM pin
 uint8_t servoPin = 5;
+uint8_t resetPin = 9;
 Servo actuationServo;

 float lastAltitudes[ALTITUDE_SMOOTHING];
@@ -118,6 +119,9 @@
 #else
     actuationServo.attach(servoPin);
     actuationServo.write(RESET_SERVO_ANGLE);
+
+    pinMode(resetPin, OUTPUT);
+    digitalWrite(resetPin, HIGH);

     pinMode(bmpPowerPin, OUTPUT);
     digitalWrite(bmpPowerPin, HIGH);
@@ -155,7 +159,7 @@
         float currentAlt = bmp.pressureToAltitude(seaLevelPressure, event.pressure, temperature) * METERS_TO_FEET_RATIO;
         return smoothAltitude(currentAlt);
     }
-
+
     return -1;
 }
 float smoothAltitude(float newAlt) {
@@ -172,6 +176,24 @@
         sum += lastAltitudes[i];
     }
     return sum / ALTITUDE_SMOOTHING;
+}
+// this is to check and see if our barometer is just returning 0s and reset the arduino
+void checkBarometerDataIntegrity() {
+    // only check when our altitude is at the end in order to avoid the initial {0,0,0...}
+    if (lastAltitudeIndex != ALTITUDE_SMOOTHING) {
+        return;
+    }
+    bool allZeros = true;
+    for (int i = 0; i < ALTITUDE_SMOOTHING; i++) {
+        if (lastAltitudes[i] != 0.0f) {
+            allZeros = false;
+        }
+    }
+    if (allZeros) {
+        Serial.println("RESETTING ARDUINO");
+        digitalWrite(resetPin, LOW);
+    }
+
 }

 #endif
@@ -281,9 +303,12 @@
             Serial.println((int)recvByte);
             break;
         }
-    }
-#endif
-}
+        checkBarometerDataIntegrity();
+
+    }
+#endif
+}
+

 void validateAck(byte ackResponse) {
     boolean correctResponse = (ackResponse == ackVal);
@@ -336,8 +361,8 @@
     for (int i = 0; i < numBytes; i++)
     {
         Serial.print(((byte*)val)[i]);
-        if(i < numBytes - 1)
-        Serial.print(F(", "));
+        if (i < numBytes - 1)
+            Serial.print(F(", "));
     }
     Serial.println(F("}"));


grammar corrections in L abd C display

grammar corrections in L abd C display

--- hal100/hal100.ino
+++ hal100/hal100.ino
@@ -57,7 +57,7 @@
 char DisplayValueC2[6];
 char DisplayValueC2pF[6];
 char DisplayValueL[6];
-char DisplayValueLUH[4];
+char DisplayValueL1uH[6];
 char DisplayValueSWR[6];
 char input; //buffer for input characters for calculations

@@ -196,7 +196,7 @@
 }

-double stepsToMh(float x) {
+double stepsToUH(float x) {
   return  3.2408606623203362e-001 * pow(x, 0)
           +  4.8175734249036963e-005 * pow(x, 1)
           + -8.2394558534492893e-009 * pow(x, 2)
@@ -213,7 +213,7 @@
 }

 void displayLSteps() {                                         // display L steps values
-  dtostrf(valueRotateL, 5, 0, DisplayValueL);
+  dtostrf(valueRotateL, 6, 0, DisplayValueL);
   if (isBusy) {
     TFTscreen.stroke(255, 255, 0);
   } else {
@@ -230,20 +230,20 @@
 }

 void displayValueLuH() {                                         // display L values in uH
-  dtostrf(stepsToMh(valueRotateL), 4, 2, DisplayValueLUH);
-  if (isBusy) {
-    TFTscreen.stroke(255, 255, 0);
-  } else {
-    TFTscreen.stroke(0, 255, 0);
-  }
-  TFTscreen.setTextSize(2);
-  TFTscreen.text(DisplayValueLUH, 40, 25);
+  dtostrf(stepsToUH(valueRotateL), 4, 2, DisplayValueL1uH);
+  if (isBusy) {
+    TFTscreen.stroke(255, 255, 0);
+  } else {
+    TFTscreen.stroke(0, 255, 0);
+  }
+  TFTscreen.setTextSize(2);
+  TFTscreen.text(DisplayValueL1uH, 40, 25);
 }

 void ErasDisplayValueLuH() {                                   // erase display L values in uH
   TFTscreen.stroke(0, 20, 30);
   TFTscreen.setTextSize(2);
-  TFTscreen.text(DisplayValueLUH, 40, 25);
+  TFTscreen.text(DisplayValueL1uH, 40, 25);
 }

 void displayL() {                                             // display L steps and uH


Joystick

Joystick

--- keyboard/keyboard.ino
+++ keyboard/keyboard.ino
@@ -2,6 +2,12 @@
  */
 #include <Keypad.h>

+int X;
+int Y;
+int SW;
+const int analogInPinX = A0;  // Analog input pin that the potentiometer is attached to
+const int analogInPinY = A1;  // Analog input pin that the potentiometer is attached to
+const int PinSW = 9;  // Analog input pin that the potentiometer is attached to
 const byte ROWS = 4; // Four rows
 const byte COLS = 4; // Three columns
 // Define the Keymap
@@ -24,10 +30,27 @@
 void setup()
 {
   Serial.begin(9600);
+  pinMode(PinSW, INPUT_PULLUP);       // turn on pullup resistors
 }

 void loop()
 {
+  // read the analog in value:
+  X = analogRead(analogInPinX);
+  Y = analogRead(analogInPinY);
+  SW =digitalRead(PinSW);
+  // map it to the range of the analog out:
+//  outputValue = map(sensorValue, 0, 1023, 0, 255);
+  // change the analog out value:
+//  analogWrite(analogOutPin, outputValue);
+
+  // print the results to the serial monitor:
+  Serial.print("X = " );
+  Serial.print(X);
+  Serial.print("\t Y = ");
+  Serial.print(Y);
+  Serial.print("\t SW = ");
+  Serial.println(SW);
   char key = kpd.getKey();
   if(key)  // Check for a valid key.
   {


ZumoReflectanceSensorArray, SensorCalibration.ino:  Changed the object name from "reflectance" to "reflectanceSensors"

--- ZumoReflectanceSensorArray/examples/SensorCalibration/SensorCalibration.ino
+++ ZumoReflectanceSensorArray/examples/SensorCalibration/SensorCalibration.ino
@@ -28,7 +28,7 @@
 directly under sensor 5 or was last seen by sensor 5 before being lost.
 */

-ZumoReflectanceSensorArray reflectance;
+ZumoReflectanceSensorArray reflectanceSensors;

 // Define an array for holding sensor values.
 #define NUM_SENSORS 6
@@ -36,7 +36,7 @@

 void setup()
 {
-  reflectance.init();
+  reflectanceSensors.init();

   delay(500);
   pinMode(13, OUTPUT);
@@ -45,7 +45,7 @@
   unsigned long startTime = millis();
   while(millis() - startTime < 10000)   // make the calibration take 10 seconds
   {
-    reflectance.calibrate();
+    reflectanceSensors.calibrate();
   }
   digitalWrite(13, LOW);         // turn off LED to indicate we are through with calibration

@@ -53,7 +53,7 @@
   Serial.begin(9600);
   for (byte i = 0; i < NUM_SENSORS; i++)
   {
-    Serial.print(reflectance.calibratedMinimumOn[i]);
+    Serial.print(reflectanceSensors.calibratedMinimumOn[i]);
     Serial.print(' ');
   }
   Serial.println();
@@ -61,7 +61,7 @@
   // print the calibration maximum values measured when emitters were on
   for (byte i = 0; i < NUM_SENSORS; i++)
   {
-    Serial.print(reflectance.calibratedMaximumOn[i]);
+    Serial.print(reflectanceSensors.calibratedMaximumOn[i]);
     Serial.print(' ');
   }
   Serial.println();
@@ -74,10 +74,10 @@
   // read calibrated sensor values and obtain a measure of the line position.
   // Note: the values returned will be incorrect if the sensors have not been properly
   // calibrated during the calibration phase.
-  unsigned int position = reflectance.readLine(sensorValues);
+  unsigned int position = reflectanceSensors.readLine(sensorValues);

   // To get raw sensor values instead, call:
-  //reflectance.read(sensorValues);
+  //reflectanceSensors.read(sensorValues);

   for (byte i = 0; i < NUM_SENSORS; i++)
   {


cc3200 firmware update

cc3200 firmware update

--- devices/cc3200_launchpad/example_energia/example_energia.ino
+++ devices/cc3200_launchpad/example_energia/example_energia.ino
@@ -18,9 +18,8 @@
 volatile int green_state = LOW;

 //access point should only work for b and g
-char ssid[] = "nsynapse";
+char ssid[] = "hellfire";
 char password[] = "elec6887";
-WiFiClient client;
 WiFiServer server(8000);
 WiFiUDP Udp;

@@ -35,7 +34,8 @@
 enum {IDLE = 0, ANNOUNCE=100, SERVICE=200 };
 unsigned int process_state = IDLE;

-aJsonObject* root = aJson.createObject();
+aJsonObject* announce = aJson.createObject();
+aJsonObject* frame = aJson.createObject();

 void setup()
 {
@@ -66,14 +66,21 @@
   Udp.begin(DEFAULT_UDP_PORT);

   //device profile
-  if(root) {
-    aJson.addStringToObject(root, "devicename", "TI_cc3200_1");
-    aJson.addStringToObject(root, "componentname", "cc3200button");
-    aJson.addStringToObject(root, "protocol", "tcp");
-    aJson.addNumberToObject(root, "port", 8000);
-  }
-
-  client = server.available();
+  if(announce) {
+    aJson.addStringToObject(announce, "devicename", "TI_cc3200_1");
+    aJson.addStringToObject(announce, "componentname", "cc3200button");
+    aJson.addStringToObject(announce, "protocol", "tcp");
+    aJson.addNumberToObject(announce, "port", 8000);
+    aJson.addStringToObject(announce, "command","auth");
+  }
+
+  if(frame) {
+    aJson.addStringToObject(frame, "devicename", "TI_cc3200_1");
+    aJson.addStringToObject(frame, "componentname", "cc3200button");
+    aJson.addStringToObject(frame, "command","buttonread");
+    aJson.addBooleanToObject(frame, "button1", false);
+    aJson.addBooleanToObject(frame, "button2", false);
+  }
 }

 void loop()
@@ -94,104 +101,74 @@
     //////////////////////// service announce
     case ANNOUNCE:
     {
-      connect_led();
-      if(root)
+      digitalWrite(YELLOW_LED, HIGH);
+      if(announce)
       {
         Udp.beginPacket(DEFAULT_UDP_MEMBERSHIP, DEFAULT_UDP_PORT);
-        Udp.write(aJson.print(root));
+        Udp.write(aJson.print(announce));
         Udp.endPacket();
-        process_state++;
+        process_state = SERVICE;
       }
     }
     break;

-    case ANNOUNCE+1:
-    {
-      if(client) {
-        process_state=SERVICE;
-        digitalWrite(YELLOW_LED, HIGH);
-      }
-      else {
-        process_state = ANNOUNCE;
-        delay(1000);
-      }
-    }
-    break;

     //////////////////////// service run
     case SERVICE:
     {
+      WiFiClient client = server.available();
       if(client) {
+        Serial.println("new client");
         while(client.connected()) {
           digitalWrite(RED_LED, HIGH);
+
+          push1_state = digitalRead(PUSH1);
+          push2_state = digitalRead(PUSH2);
+
+          if(push1_state!=prev_push1_state) {
+            if(push1_state==HIGH) {
+              Serial.println("Push1 High");
+              update(PUSH1, true);
+            }
+            else if(push1_state==LOW) {
+              Serial.println("Push1 Low");
+              update(PUSH1, false);
+            }
+            client.print(aJson.print(frame));
+            delay(50);
+          }
+
+          if(push2_state!=prev_push2_state)
+          {
+            if(push2_state==HIGH) {
+              Serial.println("Push2 High");
+              update(PUSH2, true);
+            }
+            else if(push2_state==LOW) {
+              Serial.println("Push2 Low");
+              update(PUSH2, false);
+            }
+            client.print(aJson.print(frame));
+            delay(50);
+          }
+
+
+
+          prev_push1_state = push1_state;
+          prev_push2_state = push2_state;
         }
+        Serial.println("connection closed");
+        digitalWrite(RED_LED, LOW);
         client.stop();
-        digitalWrite(RED_LED, LOW);
-        process_state = IDLE;
-      }
-    }
-    break;
-  }
-
-  /*
-  int i=0;
-  client = server.available();
-
-  int push1_state = LOW;
-  int prev_push1_state = LOW;
-  int push2_state = LOW;
-  int prev_push2_state = LOW;
-
-  unsigned char btn = 0x00;
-  unsigned char btn_value = 0x00;
-
-
-
-  if(client)
-  {
-    Serial.println("New client is connected.");
-    //send(btn, btn_value);
-
-    while(client.connected())
-    {
-      digitalWrite(YELLOW_LED, HIGH);
-
-      push1_state = digitalRead(PUSH1);
-      push2_state = digitalRead(PUSH2);
-
-      if(push1_state!=prev_push1_state) {
-        if(push1_state==HIGH) {
-          Serial.println("Push1 High");
-          send(PUSH1, HIGH);
-        }
-        else if(push1_state==LOW) {
-          Serial.println("Push1 Low");
-          send(PUSH1, LOW);
+
+        if(WiFi.status()!=WL_CONNECTED) {
+          digitalWrite(YELLOW_LED, LOW);
+          process_state = IDLE;
         }
       }
-
-      if(push2_state!=prev_push2_state)
-      {
-        if(push2_state==HIGH) {
-          Serial.println("Push2 High");
-          send(PUSH2, HIGH);
-        }
-        else if(push2_state==LOW) {
-          Serial.println("Push2 Low");
-          send(PUSH2, LOW);
-        }
-      }
-
-      prev_push1_state = push1_state;
-      prev_push2_state = push2_state;
-
-      delay(10);
-    }
-    Serial.println("Client disconnected");
-    client.stop();
-  }
-
-  delay(300);*/
+    }
+    break;
+  }
 }

@@ -248,20 +225,16 @@
   digitalWrite(RED_LED, red_state);
 }

-///////////////////////////// IPAddress to string
-String ip2string(IPAddress& ip)
-{
-  String addr="";
-  for(int i=0;i<4;i++)
-  {
-    //addr+=ip[0]/100;
-  }
-  return addr;
-}
-
-void send(unsigned char b, unsigned char v) {
-  if(client.connected()) {
-    unsigned char data[12] = {'/','S','T','A','R','T',b,v, '/','E','N','D'};
-    client.write(data, sizeof(data));
-  }
-}
+
+void update(unsigned char button, boolean value)
+{
+  if(button==PUSH1) {
+    aJsonObject* button1 = aJson.getObjectItem(frame, "button1");
+    button1->valuebool = value;
+  }
+
+  if(button==PUSH2) {
+    aJsonObject* button2 = aJson.getObjectItem(frame, "button2");
+    button2->valuebool = value;
+  }
+}


Update ant_switch_arduino_netshield.ino

Update ant_switch_arduino_netshield.ino

--- docs/arduino-nano-netshield/ant_switch_arduino_netshield.ino
+++ docs/arduino-nano-netshield/ant_switch_arduino_netshield.ino
@@ -3,7 +3,7 @@
  *
  * Arduino nano + ENC29J60 ethernet shield antenna switch
  *
- * 8 selecteable antennas in digital outputus d2,d3,d4,d5,d6,d7,d8,d9
+ * 8 selecteable antennas in digital outputs d2,d3,d4,d5,d6,d7,d8,d9
  *
  * curl http://172.16.50.19/?cmd=1 set antenna 1 (only)
  * curl http://172.16.50.19/?cmd=+1 add antenna 1
@@ -20,8 +20,6 @@

 EthernetServer server = EthernetServer(80);
 boolean alreadyConnected = false; // whether or not the client was connected previously
-String commandString;
-String commandStringTmp;

 void setup()
 {
@@ -35,7 +33,7 @@
   uint8_t mac[6] = {0x00, 0x02, 0x2d, 0x01, 0x02, 0x03};

   // the dns server ip
-  IPAddress dnServer(172, 16, 49, 2);
+  IPAddress dnServer(8, 8, 8, 8);
   // the router's gateway address:
   IPAddress gateway(172, 16, 50, 1);
   // the subnet:


Wait 1 timestep before moving out the next led

--- countdown/countdown.ino
+++ countdown/countdown.ino
@@ -32,6 +32,8 @@
 void step_led(){
   // First, turn off completely the led at step_counter (the light will leave this spot)
   leds[step_counter] = CRGB::Black;
+  // Re-set the step period 'countdown timer'
+  step_period = 1000/(1+leds_index);

   // Then, check whether we still have steps left on the current led
   if(step_counter==0){
@@ -44,6 +46,11 @@
     }
     colour_counter--;
     step_counter = leds_index;
+    // Pause 1 step before moving out this new led
+    return;
+  }
+
+  if(step_counter==leds_index){
     // Turn off the current colour in the current 'source' led
     if(colour_counter==2){
       // moved out blue
@@ -55,12 +62,10 @@
       leds[leds_index] = CRGB::Black;
     }
   }
+
   step_counter--;
   // Light up the properly-coloured led in the current position
   leds[step_counter] = moving_colours[colour_counter];
-
-  // take just as long for the first as for the last leds to move out:
-  step_period = 1000/(1+leds_index);
 }

 void update(){


Set baudrate using a Long type

Set baudrate using a Long type

--- arduino/rflink/rflink.ino
+++ arduino/rflink/rflink.ino
@@ -267,7 +267,7 @@

 void setup(void)
 {
-    serial_init(57600);
+    serial_init(57600L);

     // read node id from eeprom
     node_id = id_read();


modified:   mcu_main/mcu_main.ino

modified:   mcu_main/mcu_main.ino

--- mcu_main/mcu_main.ino
+++ mcu_main/mcu_main.ino
@@ -63,7 +63,13 @@
     state.running = true;
     state.cw = cmd[0] & 0x01;

-    wave(&state);
+    switch (cmd[0] >> 4)
+    {
+      case 1  :  micr(&state);  break;
+      case 2  :  half(&state);  break;
+      case 4  :  full(&state);  break;
+      case 8  :  wave(&state);  break;
+    }
   }

   if(cmd.length() > 0)


Testing signal detection again

Testing signal detection again

--- module/module.ino
+++ module/module.ino
@@ -298,7 +298,7 @@
 	unsigned int sum = periodX + periodY;
 	unsigned int maximumValue = 2 * upperBound;

-	if ( 0 < sum && sum <= maximumValue) {
+	if (sum <= maximumValue) {
 		return true;
 	}
 	else {


meant to make those static

meant to make those static

--- src/examples/InternetWindowOfLife.ino
+++ src/examples/InternetWindowOfLife.ino
@@ -50,13 +50,13 @@
 } GameOfLife;

 // Allocate buffers and GameOfLife objects for R, G and B universes:
-uint8_t sg_red_buffer[BUFFER_SIZE];
+static uint8_t sg_red_buffer[BUFFER_SIZE];
 static GameOfLife sg_red_universe;

-uint8_t sg_green_buffer[BUFFER_SIZE];
+static uint8_t sg_green_buffer[BUFFER_SIZE];
 static GameOfLife sg_green_universe;

-uint8_t sg_blue_buffer[BUFFER_SIZE];
+static uint8_t sg_blue_buffer[BUFFER_SIZE];
 static GameOfLife sg_blue_universe;


Don't push update in first frame change/iteration

--- arduino/arduino.ino
+++ arduino/arduino.ino
@@ -56,8 +56,8 @@
 void ethernetConnect();
 void serverCheck();
 String serverHeader(String);
-String requestHeader(String url);
-bool networkRequest(IPAddress server, String url);
+String requestHeader(String);
+bool networkRequestIP(IPAddress, String);

 void triggerCheck();
 void gotTriggered();
@@ -71,7 +71,9 @@

 void pointerLoop();
 void pointerChanged();
-
+// -- end of prototypes
+
+// Set up the corresponding network device
 #ifdef USE_ETHERNET_SHIELD
   #define USE_NETWORK
   EthernetClient client;
@@ -102,7 +104,7 @@
 byte storage[timeStorage];

 bool useNetwork = false;
-int storagePointer = 0;
+int storagePointer = -1;

 void setup() {
   Serial.begin(9600);
@@ -265,9 +267,13 @@
   if (pointer != storagePointer)
   {
     #ifdef USE_NETWORK
-      push();
+      // Only push if this is not the first iteration
+      if (storagePointer != -1)
+      {
+        push();
+      }
     #endif
-
+
     storagePointer = pointer;
     pointerChanged();
   }
@@ -297,22 +303,23 @@
 #ifdef USE_XS1_SERVER
 void xs1Push()
 {
-  IPAddress server XS1_IP;
-  String url = XS1_URL+String(storage[storagePointer]);
-  if (networkRequest(server, url) == true)
-  {
-    Serial.println("XS1 updated");
+  IPAddress ip XS1_IP;
+  String url = XS1_URL+String(storageSum(60/TIMEFRAME*5)/5*1.25*60);
+  Serial.println("[XS1] Update URL: "+url);
+  if (networkRequestIP(ip, url) == true)
+  {
+    Serial.println("[XS1] updated");
   } else
   {
-    Serial.println("XS1 update failed");
-  }
-}
+    Serial.println("[XS1] update failed");
+  }
+}
 #endif

 #ifdef USE_NETWORK
-bool networkRequest(IPAddress server, String url)
-{
-  if (client.connect(server, 80))
+bool networkRequestIP(IPAddress ip, String url)
+{
+  if (client.connect(ip, 80))
   {
     requestHeader(url).toCharArray(requestBuffer, 128);
     client.write(requestBuffer);
@@ -321,12 +328,11 @@
   {
     return false;
   }
-
 }

 String requestHeader(String url)
 {
- return "GET "+url+"HTTP/1.1\r\nConnection: close\r\n\r\n";
+  return "GET "+url+"HTTP/1.1\r\nConnection: close\r\n\r\n";
 }
 #endif


Many changes not saved in previous commit

--- arduino/src/src.ino
+++ arduino/src/src.ino
@@ -8,9 +8,8 @@

  The circuit:
   - a water level sensor http://composants.e44.com/capteurs/capteurs-niveau-d-eau/capteur-niveau-eau-normalement-ouvert-SCR4.html is linking 0V to analog pin A0 (with a 10kohm pull up resistor to 5V)
-  - an electromechanical relay commanding a pump is connected to digital output pin 4
-  - an electromechanical relay commanding an electrovanne is connected to pin 3
- * LED connected from digital pin 9 to ground
+  - an electromechanical relay commanding a 12V pump is connected to digital output pin 4 (and to ground and 5V)
+  - an electromechanical relay commanding an 220V electrovanne is connected to pin 3 (and to ground and 5V)

  Program by Baptiste LABAT, 2013

@@ -19,7 +18,7 @@

 // These constants won't change.  They're used to give names
 // to the pins used:
-const int analogOutPin = 3; // Analog output pin that the LED is attached to
+const int valvePin = 3; // Analog output pin that the LED is attached to
 const int analogInPin = A0;
 const int pumpPin = 4;
 const int ledPin = 13;
@@ -31,16 +30,17 @@
 boolean stringComplete = false;  // Whether the string is complete
 int outputValue = 0;
 float receivedValue = 0.0;
+int sensorMax = 1024;

-boolean levelWasDown = true;
-boolean levelIsDown = true;
+boolean waterLevelWasUp = true;
+boolean waterLevelIsUp = true;
 boolean freeze = false;

 void setup() {
   // initialize serial communications at 9600 bps:
   Serial.begin(9600);
     pinMode(pumpPin, OUTPUT);
-    pinMode(analogOutPin, OUTPUT);
+    pinMode(valvePin, OUTPUT);
 }

 void serialEvent() {
@@ -68,23 +68,22 @@
 }

 void loop() {
+  Serial.print("dropCounter: ");
+  Serial.println(dropCounter);
+  managePump();
+  makeADrop();
+}

-  // print the results to the serial monitor:
-
-
-  // wait 2 milliseconds before the next loop
-  // for the analog-to-digital converter to settle
-  // after the last reading:
+void managePump() {
   sensorValue = analogRead(analogInPin);
   Serial.print("Sensor: ");
   Serial.println(sensorValue);
-  levelIsDown = sensorValue>512;
-  Serial.print("dropCounter: ");
-  Serial.println(dropCounter);

-  if (dropCounter>150) //This should normaly never happen
+  waterLevelIsUp = sensorValue>sensorMax/2;
+
+  if (dropCounter>150) //This should normaly never happen, the sensor should start the pump before
   {
-    if (levelIsDown)
+    if (waterLevelIsUp)
     { //Too many drops without sensor activation: sensor is not working, stop everything!
       freeze = true;
     }
@@ -94,18 +93,19 @@
     }
   }

-  if (!levelIsDown) //It is time to activate the pump
+  if (!waterLevelIsUp) //Not enough water, it is time to activate the pump
   {

-    if (levelWasDown) //normal case, the level was previously low
+    if (waterLevelWasUp) //normal case, the level was previously up
     {
       //Active the pump for a few seconds (if not freezed)
       if (!freeze)
       {
         digitalWrite(pumpPin, HIGH);
-        Serial.println("Pump");
+        Serial.println("Pumping");
         delay(1000);
         digitalWrite(pumpPin, LOW);
+        Serial.println("Stop pumping");
         delay(2000);
         dropCounter = 0; //Reset the drop counter
       }
@@ -119,22 +119,23 @@
   }
   else
   {
-    if (!levelWasDown) // The level was previously up, the sensor is working
+    if (!waterLevelWasUp) // The level was previously up, the sensor is working
     {
       freeze = false;
     }
     digitalWrite(pumpPin, LOW);
   }
-  levelWasDown = (sensorValue>512);
+  waterLevelWasUp = waterLevelIsUp;
+}

-  // change the analog out value:
-  analogWrite(analogOutPin, int(receivedValue));
+void makeADrop() {
+  /* Map the drop frequency to the precipitation (0-0.4inch/hr normalised to 0-255)*/
   Serial.println(int(receivedValue));
   if (receivedValue < 1)
   {
       Serial.println("No rain");
       digitalWrite(ledPin, LOW);    // turn the LED off by making the voltage LOW
-      digitalWrite(analogOutPin, LOW);    // turn the LED off by making the voltage LOW
+      digitalWrite(valvePin, LOW);    // turn the LED off by making the voltage LOW
       delay(1000);               // wait for a second
   }
   else
@@ -165,15 +166,18 @@
        Serial.print("Delay: ");
        Serial.println(delayValue);
        digitalWrite(ledPin, LOW);    // turn the LED off by making the voltage LOW
-       digitalWrite(analogOutPin, LOW);    // turn the LED off by making the voltage LOW
+       digitalWrite(valvePin, LOW);    // turn the valve off by making the voltage LOW
        delay(delayValue);         // wait for a second
        digitalWrite(ledPin, HIGH);   // turn the LED on (HIGH is the voltage level)
-       if (!freeze) //only if not problem
+       if (!freeze) //only if no problem
        {
-         digitalWrite(analogOutPin, HIGH);   // turn the flow on (HIGH is the voltage level)
+         digitalWrite(valvePin, HIGH);   // turn the flow on (HIGH is the voltage level)
          dropCounter++;
        }
        delay(1100);               // wait for a second

+       digitalWrite(ledPin, LOW);
+       digitalWrite(valvePin, LOW);
+
    }
 }


Trying to get the thing stable

Trying to get the thing stable

--- Calibrate/Calibrate.ino
+++ Calibrate/Calibrate.ino
@@ -5,96 +5,61 @@
 ////////////////////////////////////////////////////////////////////////////////

 #include <SPI.h>
-//#include <Adafruit_GFX.h>
 #include <Adafruit_ILI9341.h>
 #include <XPT2046_Touchscreen.h>

 const char *ProgramName = "Calibrate";
-const char *Version = "1.0";
-const char *MinorVersion = "1";
+const char *Version = "1.2";
+const char *MinorVersion = "0";

 // TFT display chip-select and data/control pins
-#define TFT_RST 8
-#define TFT_DC  9
-#define TFT_CS  10
+#define TFT_RST     8
+#define TFT_DC      9
+#define TFT_CS      10

 // pins for touchscreen and IRQ line
-#define T_CS    4
-#define T_IRQ   3
+#define TS_CS       4
+#define TS_IRQ      3

-#define SCREEN_BG           ILI9341_BLACK
-#define CROSS_FG            ILI9341_RED
+#define SCREEN_BG   ILI9341_BLACK
+#define CROSS_FG    ILI9341_RED

-#define SPI_SETTING         SPISettings(2000000, MSBFIRST, SPI_MODE0)
+// variables
+typedef struct cal_data
+{
+  uint16_t x;
+  uint16_t y;
+  uint16_t raw_x;
+  uint16_t raw_y;
+} CalData;

-#define MIN_REPEAT_PERIOD   20
+#define NumCalPoints  9
+CalData calibrate[NumCalPoints];
+
+int cal_index = 0;    // index into calibrate[]
+
+int state;
+int count;

 // Declare the display interface
 Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);

-// variables
-bool PenDown = false;
-
-int minx = 5000;
-int miny = 5000;
-int maxx = -1;
-int maxy = -1;
-
-int last_minx = 5000;
-int last_miny = 5000;
-int last_maxx = -1;
-int last_maxy = -1;
-
-
-//-----------------------------------------------
-// Read touch screen, return raw coordinates if touched.
-//
-//     x, y  address of X & Y coordinates to update
-//
-// Returns 'true' if touched, X and Y updated
-//-----------------------------------------------
-
-bool touch_read(int *x, int *y)
-{
-  // if finger not down, do nothing
-  if (! PenDown) return false;
-
-  // otherwise, read the device
-  SPI.beginTransaction(SPI_SETTING);
-  digitalWrite(T_CS, LOW);      // enable comms with slave
-
-  SPI.transfer16(0x91 /* X */);   // we seem to read a few times
-  SPI.transfer16(0xD1 /* Y */);
-  SPI.transfer16(0x91 /* X */);
-  SPI.transfer16(0xD1 /* Y */);
-  SPI.transfer16(0x91 /* X */);
-  *x = SPI.transfer16(0xD0 /* Y */) >> 3;
-  *y = SPI.transfer16(0) >> 3;
-
-  digitalWrite(T_CS, HIGH);     // finished comms with slave
-  SPI.endTransaction();
-
-  return true;
-}
+// declare the touchscreen interface
+XPT2046_Touchscreen ts(TS_CS);

 //----------------------------------------
-// Interrupt - pen went down or up.
+// Interrupt - pen went down (or up).
 //
-// Maintain the correct PenDown state and call touch_read() if DOWN.
-// Also push a event_Up event if going UP.
+// Maintain the correct PenDown state.
 //----------------------------------------

+#if 0
 void touch_isr(void)
 {
-  static uint32_t  msraw = 0L;
-  uint32_t now = millis();
-
-  // ignore interrupt if too quick
-  if ((now - msraw) < MIN_REPEAT_PERIOD) return;
-  msraw = now;
-
-  PenDown = (digitalRead(T_IRQ) == 0);
+  PenDown = (digitalRead(TS_IRQ) == 0);
+  Serial.printf("%d:PenDown=%s\n", millis(), (PenDown) ? "true" : "false");
 }
+#endif

 //-----------------------------------------------
 // Initialize PixelVFO.
@@ -107,12 +72,34 @@
   Serial.printf("%s %s.%s\n", ProgramName, Version, MinorVersion);

   // initialize the pins, mode and level
-  pinMode(T_CS, OUTPUT);
-  digitalWrite(T_CS, HIGH);
-  pinMode(T_IRQ, INPUT_PULLUP);
+  pinMode(TS_CS, OUTPUT);
+  digitalWrite(TS_CS, HIGH);
+  pinMode(TS_IRQ, INPUT);  // has external pullup & smothing

-  // initiaize some state
-  PenDown = false;
+  // setup the target points array 'calibrate'
+  int ndx = 0;
+  int save_x = 0;
+  int save_y = 0;
+
+  for (int y = 0; y <= 240; y += 120)
+  {
+    for (int x = 0; x <= 320; x += 160)
+    {
+      save_x = x;
+      save_y = y;
+      if (save_x >= 320) save_x = 319;
+      if (save_y >= 240) save_y = 239;
+      calibrate[ndx].x = save_x;
+      calibrate[ndx].y = save_y;
+      calibrate[ndx].raw_x = 0;
+      calibrate[ndx].raw_y = 0;
+      ++ndx;
+    }
+  }
+  cal_index = 0;
+
+  count = 1;
+  state = 0;

   // kick off the SPI system
   SPI.begin();
@@ -125,8 +112,26 @@
   tft.fillScreen(SCREEN_BG);
   tft.setTextWrap(false);

-  // link the irq_pin pint to it's interrupt handler
-  attachInterrupt(digitalPinToInterrupt(T_IRQ), touch_isr, CHANGE);
+  // draw the initial target
+  draw_target(cal_index);
+}
+
+void draw_target(int ndx)
+{
+  int x = calibrate[ndx].x;
+  int y = calibrate[ndx].y;
+
+  for (int i = 2; i <= 10; ++i)
+    tft.fillCircle(x, y, i, ILI9341_RED);
+}
+
+void undraw_target(int ndx)
+{
+  int x = calibrate[ndx].x;
+  int y = calibrate[ndx].y;
+
+  for (int i = 2; i <= 10; ++i)
+    tft.fillCircle(x, y, i, SCREEN_BG);
 }

 //-----------------------------------------------
@@ -135,28 +140,40 @@

 void loop(void)
 {
-  int pen_x;
-  int pen_y;
+  switch (state)
+  {
+    case 0:
+      if (ts.touched())
+      {
+        TS_Point p = ts.getPoint();
+        uint16_t pen_x = p.x;
+        uint16_t pen_y = p.y;

-  if (touch_read(&pen_x, &pen_y))
-  {
-    if (pen_x < minx) minx = pen_x;
-    if (pen_y < miny) miny = pen_y;
-    if (pen_x > maxx) maxx = pen_x;
-    if (pen_y > maxy) maxy = pen_y;
-  }
-
-  if (minx != last_minx || miny != last_miny || maxx != last_maxx || maxy != last_maxy)
-  {
-    Serial.printf("// touchscreen calibration data\n");
-    Serial.printf("#define TS_MINX %d\n", minx);
-    Serial.printf("#define TS_MINY %d\n", miny);
-    Serial.printf("#define TS_MAXX %d\n", maxx);
-    Serial.printf("#define TS_MAXY %d\n\n", maxy);
-
-    last_minx = minx;
-    last_miny = miny;
-    last_maxx = maxx;
-    last_maxy = maxy;
+        undraw_target(cal_index);
+        calibrate[cal_index].raw_x = (int) (calibrate[cal_index].raw_x * (count-1)/count + pen_x/count);
+        calibrate[cal_index].raw_y = (int) (calibrate[cal_index].raw_y * (count-1)/count + pen_y/count);
+        state = 1;
+      }
+      break;
+    case 1:
+      if (! ts.touched())
+      {
+        if (++cal_index >= NumCalPoints)
+        {
+          Serial.printf("count=%d\n", count);
+          for (int ndx = 0; ndx < NumCalPoints; ndx += 1)
+          {
+            Serial.printf("%02d: x=%3d, y=%3d, raw_x=%4d, raw_y=%4d\n",
+                          ndx, calibrate[ndx].x, calibrate[ndx].y,
+                          calibrate[ndx].raw_x, calibrate[ndx].raw_y);
+          }
+          cal_index = 0;
+          ++count;
+        }
+        state = 0;
+        draw_target(cal_index);
+      }
+      break;
   }
 }
+


changed speed

changed speed

--- master/master.ino
+++ master/master.ino
@@ -21,12 +21,13 @@
 #include <PID.h>
 #include <DebugUtils.h>

+//#define PHASING
 #define DEBUG_SERIAL

 #define LED 13

-#define RAMMING_SPEED 200
-#define NORMAL_SPEED 150
+#define SUPER_SPEED 170
+#define NORMAL_SPEED 130

 uint32_t loopCount = 0;