Version 1.0 Update!!!

Version 1.0 Update!!!

Reconfigured the servo control for the new mode, meaning the flight
code should be completely operable! Still some streamlining and lots of
testing to do, though.

--- FlightCode/FlightCode.ino
+++ FlightCode/FlightCode.ino
@@ -1,4 +1,5 @@
 /*
+<<<<<<< Updated upstream
  * Notre Dame Rocket Team Roll Control Payload Master Code V. 0.91
  * Aidan McDonald, 2/1/17
  * Kyle Miller, 2/2/17
@@ -34,6 +35,42 @@
    *  Etc., etc.
  *
  */
+=======
+   Notre Dame Rocket Team Roll Control Payload Master Code V. 1.0.0
+   Aidan McDonald, 2/4/17
+
+   Most recent changes:
+   Reconfigured the roll control subroutine for the new, increment-based servo mode
+   To that end, added a Set_Servo subroutine that quickly takes the current and intended positions and translates that to a servo output
+   Also removed a whole bunch of now-unnecessary tracking flags and simplified the packet transmission code accordingly
+   Finally ran the auto-formatter, making the code readable
+
+   To-dones:
+    Basic switch-case structure
+    Incorporation of Adafruit sensor code
+    Added GPS functionality
+    Integration of radio-transmission/reception code
+    Datalogging capacity (untested)
+    Running-average calcs for critical sensor values and Simpson's Rule integration of gyro data
+    Multi-sensor verification of flight progress switch-case transitions
+    Github Sync system working
+    Packet transmission/reception over radio (ADD THIS TO GROUND STATION CODE TOO!!)
+    Roll control subroutine reconfigured for new servo mode
+
+   To-dos:
+    Confirm which gyro axis is vertical, and whether positive=clockwise for the gyro and servo
+    Revise and enhance the staging/thresholds, particularly burnout/apogee accel values
+    Reconfigure the SD datalogging section to allow for easy spreadsheet conversion
+    TEST EVERYTHING
+    NO REALLY, EVERYTHING
+      Ada Sensors
+      SD Saving
+      Servo Control
+      Flight Staging
+      Etc., etc.
+
+*/
+>>>>>>> Stashed changes

 #include <Wire.h>
 #include <SPI.h>
@@ -69,10 +106,10 @@
 float baroData[3]; //Char buffers for storing sensor data
 unsigned long timeData[2];

-int accelZBuffer[5] = {0,0,0,0,0};
-float baroAltBuffer[5] = {0,0,0,0,0};
-int gyroZBuffer[7] = {0,0,0,0,0,0,0}; //The other values are arbitrary; this one is used in Simpsons Rule, so it MUST BE ODD!
-unsigned long timeBuffer[7] = {0,0,0,0,0,0,0}; //Must equal the size of gyroZBuffer; used for the same calculations.
+int accelZBuffer[5] = {0, 0, 0, 0, 0};
+float baroAltBuffer[5] = {0, 0, 0, 0, 0};
+int gyroZBuffer[7] = {0, 0, 0, 0, 0, 0, 0}; //The other values are arbitrary; this one is used in Simpsons Rule, so it MUST BE ODD!
+unsigned long timeBuffer[7] = {0, 0, 0, 0, 0, 0, 0}; //Must equal the size of gyroZBuffer; used for the same calculations.

 byte accelAverage;
 byte baroAverage;
@@ -93,10 +130,20 @@
 long flightTime = 0;

 //Constants for servo pin output
+<<<<<<< Updated upstream
 const int controlPin = 0; //"control" is the master switch- must be 1 to enable servo, pulse this pin to trigger a move
 const int inputA = 1; //The inputA and inputB pins control which way the fins will increment when the move is triggered
 const int inputB = 2; //inputA = 0, inputB = 0 is +4 Degrees, inputA = 1, inputB = 0 is -4 Degrees, inputA = 0, inputB = 1 is +8 Degrees,
 					  // inputA = 1, inputB = 1 is -8 Degrees
+=======
+const int controlPin = 0; //"control" is the pin which is pulsed to trigger the servo to move
+const int statePinA = 1; //The state of pins A and B determines which of four motions the servo takes when the control pin is pulsed.
+const int statePinB = 2; // If B is low, move 1 position, if B is high, move two positions. High A is negative (counterclockwise?), low A is positive (clockwise?)
+const int LEFT = 0;
+const int CENTER = 1;
+const int RIGHT = 2;
+int finPosition = CENTER; //Since the servo moves based on increments and not absolute positions, these constants and variable are needed to track the fins' position.
+>>>>>>> Stashed changes

 //Constants for flight staging
 const int waiting = 0;
@@ -119,9 +166,6 @@

 bool startRollFlag = false;
 bool endRollFlag = false; //Flags for tracking roll/counter-roll progress
-bool finState = false; //Variable for tracking current fin position
-bool servoOnFlag;
-bool servoHomeFlag; //Two flags to keep track of the other two digital outputs to the servo. ALWAYS CHANGE THESE WHEN CHANGING SERVO OUTPUTS!

 float rotationCounter = 0; //Variable for tracking rotation, in revolutions

@@ -137,21 +181,31 @@
 void setup() {
   pinMode(RFM95_RST, OUTPUT); //Initialize radio; Reset pin must be high for normal function
   digitalWrite(RFM95_RST, HIGH);
-
+
   pinMode(controlPin, OUTPUT);
+<<<<<<< Updated upstream
   pinMode(inputA, OUTPUT);
   pinMode(inputB, OUTPUT);
+=======
+  pinMode(statePinA, OUTPUT);
+  pinMode(statePinB, OUTPUT);
+>>>>>>> Stashed changes

   accel.begin();
   bmp.begin();
   gyro.enableAutoRange(true);
-  gyro.begin();
+  gyro.begin();
   SD.begin(cardSelectPin);//Initialize the sensors and SD card
+<<<<<<< Updated upstream

   digitalWrite(controlPin, HIGH); //Enable servo
   servoOnFlag = true;
   digitalWrite(inputA, HIGH); //Set servo to "home" position
   servoHomeFlag = true;
+=======
+
+  digitalWrite(controlPin, LOW); //Set the servo control pin to low to make sure it doesn't pulse accidentally
+>>>>>>> Stashed changes

   //Manual radio reset
   digitalWrite(RFM95_RST, LOW);
@@ -159,10 +213,10 @@
   digitalWrite(RFM95_RST, HIGH);
   delay(10);

-  if(!rf95.init()) { //Confirm radio was initialized properly and set frequency; note if a failure occurs
+  if (!rf95.init()) { //Confirm radio was initialized properly and set frequency; note if a failure occurs
     radioWorkingFlag = false;
   }
-  if(!rf95.setFrequency(RF95_FREQ)) {
+  if (!rf95.setFrequency(RF95_FREQ)) {
     radioWorkingFlag = false;
   }
   rf95.setTxPower(23, false); //Set transmitter power to maximum (23 dBm); not sure what the bool value is for but all the examples used it
@@ -171,7 +225,7 @@
   sensors_event_t event;
   bmp.getEvent(&event);
   startAlt = bmp.pressureToAltitude(seaLevelPressure, event.pressure); //Set starting altitude for later reference
-
+

   flightState = waiting; //Initialize switch variable
 }
@@ -180,85 +234,88 @@

 void loop() {

-  if(masterEnableFlag) //Only save/buffer data if we're actively sensing data
-  {
-/* Get a new sensor event */
+  /* Get a new sensor event */
   sensors_event_t mainEvent;
   gyro.getEvent(&mainEvent);
   accel.getEvent(&mainEvent); // Assume Z-axis is vertical for accel/gyro?
   bmp.getEvent(&mainEvent);
-
-  Record_Data(mainEvent);//Save sensor data (accel, baro, time, GPS) to the SD card
-  BufferUpdate(mainEvent);
-  }
-
-  if(gpsOnFlag)
-  char c = GPS.read(); //Must call GPS.read() at some point for data transmission to occur
-
-  if(startTime != 0)
-  flightTime = millis() - startTime; //Timer backup variable
-
-  if(radioWorkingFlag) {
-  Radio_Transmit(); //Transmit/receive select data
-  }
-
-switch(flightState) { //Switch statement for entire rocket flight
-  /*
-   * Switch conditions have been greatly improved (running averages with multiple sensors)
-   * However, I do want to look at the Accel conditions again, maybe mess with the time as well?
-   * Getting this part right is really, really important
-   */
-
-case waiting:
-if(accelAverage > LIFTOFF_ACCEL_THRESHOLD && masterEnableFlag)
-{
-  flightState = launched;
-  startTime = millis();
+
+  if (masterEnableFlag) //Only save/buffer data if we're actively sensing data
+  {
+    Record_Data(mainEvent);//Save sensor data (accel, baro, time, GPS) to the SD card
+    BufferUpdate(mainEvent);
+  }
+
+  if (gpsOnFlag)
+    char c = GPS.read(); //Must call GPS.read() at some point for data transmission to occur
+
+  if (startTime != 0)
+    flightTime = millis() - startTime; //Variable tracking post-launch time for backup flight staging
+
+  if (radioWorkingFlag)
+    Radio_Transmit(); //Transmit/receive select data
+
+
+  switch (flightState) { //Switch statement for entire rocket flight
+    /*
+       Switch conditions have been greatly improved (running averages with multiple sensors)
+       However, I do want to look at the Accel conditions again, maybe mess with the time as well?
+       Getting this part right is really, really important
+    */
+
+    case waiting:
+      if (accelAverage > LIFTOFF_ACCEL_THRESHOLD && masterEnableFlag)
+      {
+        flightState = launched;
+        startTime = millis();
+      }
+      break;
+
+
+    case launched:
+      if (abs(accelAverage) < BURNOUT_ACCEL_THRESHOLD || baroAverage > BURNOUT_BARO_THRESHOLD || flightTime > BURNOUT_TIME_THRESHOLD)
+      {
+        flightState = burnout;
+      }
+      break;
+
+
+    case burnout:
+
+      Roll_Control(mainEvent);
+
+      if (accelAverage > APOGEE_ACCEL_THRESHOLD || flightTime > APOGEE_TIME_THRESHOLD) //Add a baro test here?
+      {
+        flightState = falling;
+      }
+      break;
+
+
+    case falling:
+      if (baroAverage < LANDED_BARO_THRESHOLD)
+      {
+        flightState = landed;
+      }
+
+      if (baroAverage < GPS_BARO_THRESHOLD) //Enable GPS if we're low enough
+      {
+        GPS.begin(9600); //Initialize GPS; define output set and data rate
+        GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
+        GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);
+        gpsOnFlag = true;
+      }
+
+      break;
+
+    case landed:
+
+      break;
+  }
 }
-break;
-
-
-case launched:
-if(abs(accelAverage) < BURNOUT_ACCEL_THRESHOLD || baroAverage > BURNOUT_BARO_THRESHOLD || flightTime > BURNOUT_TIME_THRESHOLD)
-{
-  flightState = burnout;
-}
-break;
-
-
-case burnout:
-Roll_Control(mainEvent);
-if(accelAverage > APOGEE_ACCEL_THRESHOLD || flightTime > APOGEE_TIME_THRESHOLD) //Add a baro test here?
-{
-  flightState = falling;
-}
-break;
-
-
-case falling:
-if(baroAverage < LANDED_BARO_THRESHOLD)
-{
-  flightState = landed;
-}
-
-if(baroAverage < GPS_BARO_THRESHOLD) //Enable GPS if we're low enough
-{
-  GPS.begin(9600); //Initialize GPS; define output set and data rate
-  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
-  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);
-  gpsOnFlag = true;
-}
-
-break;
-
-case landed:
-
-break;
-  }
-}

 void Roll_Control(sensors_event_t event) {

+<<<<<<< Updated upstream
   if(!startRollFlag) { //For roll initialization, cant fins in the direction of current roll
     digitalWrite(inputA, LOW);
     servoHomeFlag = false;
@@ -277,12 +334,28 @@
     if(rotationCounter > 2) {
       finState = !finState;
       digitalWrite(inputB, finState);
+=======
+  if (!startRollFlag) { //For roll initialization, cant fins in the direction of current roll
+    startRollFlag = true;
+    if (event.gyro.z > 0) {
+      Set_Servo(finPosition, LEFT); //This assumes positive gyro values are clockwise. CONFIRM THIS!!!
+    }
+    else {
+      Set_Servo(finPosition, RIGHT);
+    }
+  }
+  else if (!endRollFlag) { //Wait until two revolutions have ben completed to begin counter-roll
+
+    if (rotationCounter > 2) {
+      Set_Servo(finPosition, abs(finPosition - 2)); //This will output LEFT if finPosition = RIGHT, and vice-versa
+>>>>>>> Stashed changes
       endRollFlag = true;
     }
   }
   else { //At this point, continue to make adjustments to prevent roll
-    if(abs(event.gyro.z) < MIN_ROLL_THRESHOLD)
+    if (abs(event.gyro.z) < MIN_ROLL_THRESHOLD)
     {
+<<<<<<< Updated upstream
       digitalWrite(inputA, HIGH);
       servoHomeFlag = true;
     }
@@ -300,16 +373,51 @@
       digitalWrite(inputB, HIGH);
       finState = true;
       }
-  }
-
+=======
+      Set_Servo(finPosition, CENTER);
+    }
+    else if (event.gyro.z > 0) //Again, this assumes positive gyro values are clockwise.
+    {
+      Set_Servo(finPosition, RIGHT);
+    }
+    else if (event.gyro.z < 0)
+    {
+      Set_Servo(finPosition, LEFT);
+    }
+>>>>>>> Stashed changes
+  }
+
 }

-
-void Record_Data(sensors_event_t event){ //Subroutine for saving sensor data to the SD card
-
-float temperature;
-bmp.getTemperature(&temperature);
+void Set_Servo(int current, int goal) { //Subroutine which takes current position and intended position and turns those into a servo output.
+  //(I think this is more efficient/adaptive than writing the same thing out multiple times in Roll_Control()?
+
+  if (current != goal) { //Only run the fin-setting pulse and delay if motion is necessary
+    if (abs(current - goal) == 2)
+      digitalWrite(statePinB, HIGH); //If moving from right to left, or vice-versa, pin B needs to be high.
+    else
+      digitalWrite(statePinB, LOW);
+
+    if (current - goal > 0) //This assumes positive servo direction is clockwise. CONFIRM THIS IS THE CASE!!!
+      digitalWrite(statePinA, LOW);
+    else
+      digitalWrite(statePinB, HIGH);
+
+    digitalWrite(controlPin, HIGH); //Once the output pins have been set properly, pulse the control pin to update the servo.
+    delay(2);
+    digitalWrite(controlPin, LOW);
+
+    finPosition = goal; //Update the fin state tracking variable
+  }
+
+}
+
+
+void Record_Data(sensors_event_t event) { //Subroutine for saving sensor data to the SD card
+
+  float temperature;
+  bmp.getTemperature(&temperature);

   //Fill data buffers with sensor readings
   accelData[0] = event.acceleration.x;
@@ -324,241 +432,239 @@
   timeData[0] = millis();
   timeData[1] = millis() - startTime;

-if(!gpsOnFlag) {
-  dataFlag = true; //If the GPS isn't on yet, set the dataFlag to true automatically
+  if (!gpsOnFlag) {
+    dataFlag = true; //If the GPS isn't on yet, set the dataFlag to true automatically
+  }
+
+
+  if (GPS.newNMEAreceived() && gpsOnFlag) { //Update GPS data if an update is available
+    if (!GPS.parse(GPS.lastNMEA())) // this sets the newNMEAreceived() flag to false; prevents double(+)-update loop
+      return;
+    dataFlag = true; //Set flag to tell radio new data is ready
+    gpsLatitude = GPS.latitude;
+    gpsLongitude = GPS.longitude;
+    gpsAltitude = GPS.altitude;
+    gpsLatDirect = GPS.lat;
+    gpsLonDirect = GPS.lon;
+    gpsFix = GPS.fix;
+    gpsFixQuality = GPS.fixquality;
+  }
+
+
+  dataLog = SD.open("flight_data.txt", FILE_WRITE); //Open the file flight_data.txt in write mode
+
+  if (dataLog) { //log data only if the file opened properly
+    dataLog.println(); //Start a new line
+
+    for (int c = 0; c < 1; c++) {
+      dataLog.print(timeData[c]);
+      dataLog.print(", "); //Separate data entries by a comma and a space
+    }
+
+    for (int c = 0; c < 2; c++) {
+      dataLog.print(accelData[c]);
+      dataLog.print(", ");
+    }
+
+    for (int c = 0; c < 2; c++) {
+      dataLog.print(gyroData[c]);
+      dataLog.print(", ");
+    }
+
+    for (int c = 0; c < 2; c++) {
+      dataLog.print(baroData[c]);
+      dataLog.print(", ");
+    }
+
+    dataLog.print(gpsLatitude);
+    dataLog.print(gpsLatDirect);
+    dataLog.print(", ");
+    dataLog.print(gpsLongitude);
+    dataLog.print(gpsLonDirect);
+    dataLog.print(", ");
+    dataLog.print(gpsAltitude);
+    dataLog.print(", ");
+    dataLog.print(gpsFix);
+    dataLog.print(", ");
+    dataLog.print(gpsFixQuality);
+
+    dataLog.close(); //Close the file
+  }
+
 }
-
-
-if(GPS.newNMEAreceived() && gpsOnFlag) { //Update GPS data if an update is available
-  if (!GPS.parse(GPS.lastNMEA())) // this sets the newNMEAreceived() flag to false; prevents double(+)-update loop
-      return;
-      dataFlag = true; //Set flag to tell radio new data is ready
-gpsLatitude = GPS.latitude;
-gpsLongitude = GPS.longitude;
-gpsAltitude = GPS.altitude;
-gpsLatDirect = GPS.lat;
-gpsLonDirect = GPS.lon;
-gpsFix = GPS.fix;
-gpsFixQuality = GPS.fixquality;
+
+
+
+void Radio_Transmit(void) {
+
+  if (dataFlag && sendFlag) //Send data mode, only if GPS is ready
+  {
+    dataFlag = false; //Only turn off this flag if Arduino is actively sending data
+    sendFlag = false; //Once we send data, wait for data to be received
+
+    uint8_t radioPacket[20]; //Buffer of bytes for radio transmission
+    int packetSize = 20; //Depending on the flight state, the actual packet size may change
+
+    radioPacket[0] = flightState; //Start every packet with the current flight staging (lets the receiver know what data is going to come at the end of the packet)
+    radioPacket[1] = masterEnableFlag;
+    radioPacket[2] = finOverrideFlag; //Report back on the perceived state of affairs with the critical flags, in order for adjustments to be made if necessary.
+    radioPacket[3] = 42; //Answer to life, the universe, and everything. Used to confirm packet validity.
+
+    radioPacket[4] = gpsOnFlag;
+    radioPacket[5] = finPosition; //The next items in each packet report the outputs to the servo and whether we are running GPS.
+
+    union { //Float-to-byte-string converter, needed for floating-point sensor data
+      float tempFloat;
+      byte tempArray[3];
+    } u;
+
+    if (!masterEnableFlag) {
+      packetSize = 5; //If sensors aren't enabled yet, only send the above data
+    }
+
+    else if (gpsOnFlag)
+    {
+      u.tempFloat = gpsLatitude;
+      for (int c = 0; c < 4; c++) {
+        radioPacket[c + 6] = u.tempArray[c];
+      }
+      radioPacket[4] = gpsLatDirect; //N or S
+      u.tempFloat = gpsLongitude;
+      for (int c = 0; c < 4; c++) {
+        radioPacket[(c + 10)] = u.tempArray[c];
+      }
+      radioPacket[9] = gpsLonDirect; //E or W
+      u.tempFloat = gpsAltitude;
+      for (int c = 0; c < 4; c++) {
+        radioPacket[(c + 15)] = u.tempArray[c];
+      }
+      radioPacket[19] = gpsFix;
+      radioPacket[20] = gpsFixQuality; //Useful for determining valid/invalid GPS data; if fix or quality are 0 the data isn't reliable
+    }
+
+    else if (flightState = burnout) {
+
+      radioPacket[6] = endRollFlag; //If we're in burnout, send the "end roll flag." It determines whether we send the running tally (float) or the current rotation speed (int)
+
+      if (endRollFlag) {
+        union { //Since we're sending an integer, we need a different-sized memory union to work with
+          int tempInt;
+          byte tempArray[1];
+        } uInt;
+
+        uInt.tempInt = gyroData[2]; //Remember: THIS ASSUMES Z-AXIS IS VERTICAL!!!
+        radioPacket[7] = uInt.tempArray[0];
+        radioPacket[8] = uInt.tempArray[1];
+        packetSize = 8;
+      }
+
+      else {
+        u.tempFloat = rotationCounter;
+        for (int c = 0; c < 4; c++) {
+          radioPacket[(c + 7)] = u.tempArray[c];
+        }
+        packetSize = 10;
+      }
+
+    }
+
+    else { //If we're not in the burnout phase and haven't turned on the GPS, then send current altitude
+      u.tempFloat = baroData[2];
+      for (int c = 0; c < 4; c++) {
+        radioPacket[(c + 6)] = u.tempArray[c];
+      }
+      packetSize = 9;
+    }
+
+
+    rf95.send((uint8_t *)radioPacket, packetSize); //Once packet has been constructed, transmit
+    rf95.waitPacketSent(); //Short, necessary wait for packet transmission to complete
+  }
+
+  else { //Receive data mode
+
+    if (rf95.available())
+    {
+      sendFlag = true; //If data is received, return to data-send mode
+      uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
+      uint8_t len = sizeof(buf); //Variables to contain received message
+      if (rf95.recv(buf, &len)) //If message is intact; this call also fills buf and len with data
+      {
+
+        //Two very important flags from the ground station, sent in triplicate.
+        //masterEnableFlag enables the flight sensors to begin liftoff detection; finOverrideFlag acts as a master interrupt to halt in-flight fin rotation.
+
+        if (buf[0] || buf[1] || buf[2])
+          masterEnableFlag = true;
+        else
+          masterEnableFlag = false;
+
+        if (buf[3] || buf[4] || buf[5])
+          finOverrideFlag = true;
+        else
+          finOverrideFlag = false;
+      }
+    }
+  }
 }

-dataLog = SD.open("flight_data.txt", FILE_WRITE); //Open the file flight_data.txt in write mode
-
-if (dataLog) { //log data only if the file opened properly
-  dataLog.println(); //Start a new line
-
-for(int c = 0; c < 1; c++){
-dataLog.print(timeData[c]);
-dataLog.print(", "); //Separate data entries by a comma and a space
+
+void BufferUpdate(sensors_event_t event) { //Function to keep a running buffer of select sensor values needed for data averaging (or numerical integration)
+
+  accelAverage = 0;
+  baroAverage = 0;
+
+  for (int c = 0; c < 4; c++) {
+    accelZBuffer[4 - c] = accelZBuffer[3 - c];
+    baroAltBuffer[4 - c] = baroAltBuffer[3 - c];
+  }
+  accelZBuffer[0] = event.acceleration.z;
+  baroAltBuffer[0] = bmp.pressureToAltitude(seaLevelPressure, event.pressure);
+
+  for (int c = 0; c < 5; c++) {
+    accelAverage = accelAverage + accelZBuffer[c];
+    baroAverage = baroAverage + baroAltBuffer[c];
+  }
+  accelAverage = accelAverage / 5;
+  baroAverage = baroAverage / 5;
+  baroAverage = baroAverage - startAlt; //Have to compare the average to the ground, not sea level
+
+  if (flightState == burnout && !endRollFlag) { //Keep track of rotations once we transition to the burnout stage
+    /*
+       This section functions stepwise. Once the two buffers are full, the algorithm performs numerical
+       integration, increments rollCounter, and flushes the buffers before starting over.
+    */
+    if (timeBuffer[6] < 1) { //If the buffers are not yet full; avoiding == 0 because it's an unsigned long
+
+      for (int c = 0; c < 6; c++) {
+        timeBuffer[6 - c] = timeBuffer[5 - c];
+        gyroZBuffer[6 - c] = gyroZBuffer[5 - c];
+      }
+      timeBuffer[0] = millis();
+      gyroZBuffer[0] = event.gyro.z;
+
+    }
+
+    else { //Once the buffers are full, perform the integration!
+
+      float deltaT = (timeBuffer[6] - timeBuffer[0]) / 18; //Note: the average is technically /6, but since Simpson's Rule adds a /3 anyways, it's just more efficient to combine them
+      float simpsonSum = gyroZBuffer[0] + gyroZBuffer[6];
+      simpsonSum = simpsonSum + 4 * (gyroZBuffer[1] + gyroZBuffer[3] + gyroZBuffer[5]);
+      simpsonSum = simpsonSum + 2 * (gyroZBuffer[2] + gyroZBuffer[4]);
+      simpsonSum = simpsonSum * deltaT; //Hooray for numerical integration! Should look into whether there's a more efficient way to perform Simpson's rule here.
+
+      rotationCounter = rotationCounter + (simpsonSum / 6.28318531); //Convert from radians to revolutions and increment the counter!
+
+      for (int c = 0; c < 7; c++) {
+        timeBuffer[c] = 0;
+        gyroZBuffer[c] = 0; //Don't forget to clear the buffers for the next step!
+      }
+
+    }
+
+  }
+
 }

-for(int c = 0; c < 2; c++){
-dataLog.print(accelData[c]);
-dataLog.print(", ");
-}
-
-for(int c = 0; c < 2; c++){
-dataLog.print(gyroData[c]);
-dataLog.print(", ");
-}
-
-for(int c = 0; c < 2; c++){
-dataLog.print(baroData[c]);
-dataLog.print(", ");
-}
-
-dataLog.print(gpsLatitude);
-dataLog.print(gpsLatDirect);
-dataLog.print(", ");
-dataLog.print(gpsLongitude);
-dataLog.print(gpsLonDirect);
-dataLog.print(", ");
-dataLog.print(gpsAltitude);
-dataLog.print(", ");
-dataLog.print(gpsFix);
-dataLog.print(", ");
-dataLog.print(gpsFixQuality);
-
-  dataLog.close(); //Close the file
-}
-
-}
-
-
-
-void Radio_Transmit(void) {
-
-if(dataFlag && sendFlag) //Send data mode, only if GPS is ready
-  {
-      dataFlag = false; //Only turn off this flag if Arduino is actively sending data
-      sendFlag = false; //Once we send data, wait for data to be received
-
-      uint8_t radioPacket[21]; //Buffer of bytes for radio transmission
-      int packetSize = 21; //Depending on the flight state, the actual packet size may change
-
-      radioPacket[0] = flightState; //Start every packet with the current flight staging (lets the receiver know what data is going to come at the end of the packet)
-      radioPacket[1] = masterEnableFlag;
-      radioPacket[2] = finOverrideFlag; //Report back on the perceived state of affairs with the critical flags, in order for adjustments to be made if necessary.
-      radioPacket[3] = 42; //Answer to life, the universe, and everything. Used to confirm packet validity.
-
-      radioPacket[4] = gpsOnFlag;
-      radioPacket[4] = servoOnFlag;
-      radioPacket[5] = servoHomeFlag; //The next items in each packet report the outputs to the servo and whether we are running GPS.
-      radioPacket[6] = finState;
-
-union{ //Float-to-byte-string converter, needed for GPS data
-  float tempFloat;
-  byte tempArray[3];
-} u;
-
-if(!masterEnableFlag) {
-  packetSize = 6; //If sensors aren't enabled yet, only send the above data
-}
-
-else if(gpsOnFlag)
-{
-u.tempFloat = gpsLatitude;
-for(int c=0; c<4; c++){
-  radioPacket[c+7] = u.tempArray[c];
-}
-radioPacket[4] = gpsLatDirect; //N or S
-u.tempFloat = gpsLongitude;
-for(int c=0; c<4; c++){
-  radioPacket[(c+11)] = u.tempArray[c];
-}
-radioPacket[9] = gpsLonDirect; //E or W
-u.tempFloat = gpsAltitude;
-for(int c=0; c<4; c++){
-  radioPacket[(c+16)] = u.tempArray[c];
-}
-radioPacket[20] = gpsFix;
-radioPacket[21] = gpsFixQuality; //Useful for determining valid/invalid GPS data; if fix or quality are 0 the data isn't reliable
-}
-
-else if(flightState = burnout) {
-
-  radioPacket[7] = endRollFlag; //If we're in burnout, send the "end roll flag." It determines whether we send the running tally (float) or the current rotation speed (int)
-
-if(endRollFlag) {
-union { //Since we're sending an integer, we need a different-sized memory union to work with
-  int tempInt;
-  byte tempArray[1];
-} uInt;
-
-uInt.tempInt = gyroData[2]; //Remember: THIS ASSUMES Z-AXIS IS VERTICAL!!!
-radioPacket[8] = uInt.tempArray[0];
-radioPacket[9] = uInt.tempArray[1];
-packetSize = 9;
-}
-
-else {
-  u.tempFloat = rotationCounter;
-for(int c=0; c<4; c++){
-  radioPacket[(c+8)] = u.tempArray[c];
-}
-packetSize = 11;
-}
-
-}
-
-else { //If we're not in the burnout phase and haven't turned on the GPS, then send current altitude
-u.tempFloat = baroData[2];
-for(int c=0; c<4; c++){
-  radioPacket[(c+7)] = u.tempArray[c];
-}
-packetSize = 10;
-}
-
-
-rf95.send((uint8_t *)radioPacket, packetSize); //Once packet has been constructed, transmit
-rf95.waitPacketSent(); //Short, necessary wait for packet transmission to complete
-}
-
- else { //Receive data mode
-
-    if (rf95.available())
-  {
-    sendFlag = true; //If data is received, return to data-send mode
-    uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
-    uint8_t len = sizeof(buf); //Variables to contain received message
-    if (rf95.recv(buf, &len)) //If message is intact; this call also fills buf and len with data
-   {
-
-    //Two very important flags from the ground station, sent in triplicate.
-    //masterEnableFlag enables the flight sensors to begin liftoff detection; finOverrideFlag acts as a master interrupt to halt in-flight fin rotation.
-
-    if(buf[0] || buf[1] || buf[2])
-        masterEnableFlag = true;
-      else
-        masterEnableFlag = false;
-
-     if(buf[3] || buf[4] || buf[5])
-        finOverrideFlag = true;
-     else
-        finOverrideFlag = false;
-   }
-  }
-  }
-}
-
-
-
-void BufferUpdate(sensors_event_t event) { //Function to keep a running buffer of select sensor values needed for data averaging (or numerical integration)
-
-accelAverage = 0;
-baroAverage = 0;
-
-for(int c = 0; c<4; c++) {
-  accelZBuffer[4-c] = accelZBuffer[3-c];
-  baroAltBuffer[4-c] = baroAltBuffer[3-c];
-}
-accelZBuffer[0] = event.acceleration.z;
-baroAltBuffer[0] = bmp.pressureToAltitude(seaLevelPressure, event.pressure);
-
-for(int c = 0; c<5; c++) {
-  accelAverage = accelAverage + accelZBuffer[c];
-  baroAverage = baroAverage + baroAltBuffer[c];
-}
-accelAverage = accelAverage / 5;
-baroAverage = baroAverage / 5;
-baroAverage = baroAverage - startAlt; //Have to compare the average to the ground, not sea level
-
-if(flightState == burnout && !endRollFlag){ //Keep track of rotations once we transition to the burnout stage
-/*
- * This section functions stepwise. Once the two buffers are full, the algorithm performs numerical
- * integration, increments rollCounter, and flushes the buffers before starting over.
-*/
-if(timeBuffer[6] < 1) { //If the buffers are not yet full; avoiding == 0 because it's an unsigned long
-
-for(int c = 0; c<6; c++) {
-  timeBuffer[6-c] = timeBuffer[5-c];
-  gyroZBuffer[6-c] = gyroZBuffer[5-c];
-}
-timeBuffer[0] = millis();
- gyroZBuffer[0] = event.gyro.z;
-
-}
-
-else { //Once the buffers are full, perform the integration!
-
-float deltaT = (timeBuffer[6] - timeBuffer[0]) / 18; //Note: the average is technically /6, but since Simpson's Rule adds a /3 anyways, it's just more efficient to combine them
-float simpsonSum = gyroZBuffer[0] + gyroZBuffer[6];
-simpsonSum = simpsonSum + 4*(gyroZBuffer[1] + gyroZBuffer[3] + gyroZBuffer[5]);
-simpsonSum = simpsonSum + 2*(gyroZBuffer[2] + gyroZBuffer[4]);
-simpsonSum = simpsonSum * deltaT; //Hooray for numerical integration! Should look into whether there's a more efficient way to perform Simpson's rule here.
-
-rotationCounter = rotationCounter + (simpsonSum / 6.28318531); //Convert from radians to revolutions and increment the counter!
-
-for(int c = 0; c<7; c++) {
-  timeBuffer[c] = 0;
-  gyroZBuffer[c] = 0; //Don't forget to clear the buffers for the next step!
-}
-
-}
-
-}
-
-}
-
-
+


set ambient condition upper limit

set ambient condition upper limit

--- QmoteRHTlogger_w_Daikin/QmoteRHTlogger_w_Daikin.ino
+++ QmoteRHTlogger_w_Daikin/QmoteRHTlogger_w_Daikin.ino
@@ -34,7 +34,9 @@
 #define TEMP_SETTING          24          // cooling setting to this temperature
 #define TEMP_HIGH             27.8        // restart cooling if temperature reaches this measurement
 #define TEMP_LOW              25          // stop cooling or switch to humidifier if temerature reaches this measurement
-#define TEMP_TOO_LOW          23          // if temperature reaches to this mesurement means humidifier goes too much, turn off everything
+#define TEMP_TOO_LOW          23          // if temperature reaches this value means humidifier goes too much, turn off everything
+#define TEMP_TOO_HIGH         30          // if temperature reaches this value, KEEP_OFF_TIMER will be ignored
+#define RH_TOO_HIGH           80          // if Rh reaches this value, KEEP_OFF_TIMER will be ignored
 #define RH_HIGH               68          // restart humidifier if Rh reaches to this measurement
 #define RH_LOW                60          // stop humidifier if Rh reaches to this measurement

@@ -414,6 +416,14 @@
           }
         }
       } // end if(!just_off || ...)
+      else
+      {
+        if(((float) currentTemp) >= ((float) TEMP_TOO_HIGH) || currentRh >= RH_TOO_HIGH)
+        {
+          // ambient condition exceeds the limit, ignore the KEEP_OFF_TIMER
+          just_off = false;
+        }
+      }
     } // end if(currentTemp > -100 ...)
   } // end if(!qmoteDisconnected)


Added missing free

Added missing free

--- http_test.ino
+++ http_test.ino
@@ -102,6 +102,7 @@
               else //there was an error
               {
                 Serial.println("Error allocating memory!");
+                free(temp);
                 break;
               }
             }


Add fourth servo motor

Add fourth servo motor

--- mearm_knob/mearm_knob.ino
+++ mearm_knob/mearm_knob.ino
@@ -6,16 +6,19 @@
 Servo servo1;
 Servo servo2;
 Servo servo3;
-
+Servo servo4;
+
 int controle1 = A0;
 int controle2 = A1;
 int controle3 = A2;
+int controle4 = A3;

 void setup()
 {
   servo1.attach(3);
   servo2.attach(5);
   servo3.attach(6);
+  servo4.attach(9);

 }

@@ -24,7 +27,8 @@
   lePotAcionaServo(servo1, controle1);
   lePotAcionaServo(servo2, controle2);
   lePotAcionaServo(servo3, controle3);
-  delay(15);
+  lePotAcionaServo(servo4, controle4);
+  delay(50);
 }

 int leComando(int controle) {


Remove stupid String dislay Logic

Remove stupid String dislay Logic

--- NTPclock/NTPclock.ino
+++ NTPclock/NTPclock.ino
@@ -27,7 +27,6 @@

 RtcDS3231 RTC;
 LedControl lc1 = LedControl(D5,D6,D7,1); // Initialize MAX7219
-char timeDigits[] = "----";              // String represntation of current time

 // Initial set up routines
 void setup() {
@@ -44,23 +43,27 @@

 // Main program loop
 void loop() {
-  String timeDisplay = NTP.getTimeStr();
-  timeDigits[0] = timeDisplay.charAt(0);
-  timeDigits[1] = timeDisplay.charAt(1);
-  timeDigits[2] = timeDisplay.charAt(3);
-  timeDigits[3] = timeDisplay.charAt(4);
-  for (int i=0; i<4; i++) {
-    Serial.print(i);
-    lc1.setChar(0, i, timeDigits[i], false);
+  updateDigits();
+  updateMisc();
+  delay(1000);         //TODO:   REMOVE DELAY FOR A COUNTER..............................PLEASE!!!!......../////////////////////////
+}
+
+//
+void updateDigits() {
+  if ((hour() / 10) == 0) {
+    lc1.setChar(0, 0, ' ', false);
+  } else {
+    lc1.setChar(0, 0, (hour() / 10), false);
   }
-
-  Serial.println(timeDisplay);
-
-  time_t nowTime = now();                  //store the current time in time variable t
-  int portion = (second(nowTime) / 6) + 1; //get the number of bars that should be lit
-  setBar(portion);                         //and then set them
-
-  delay(1000);         //TODO:   REMOVE DELAY FOR A COUNTER..............................PLEASE!!!!......../////////////////////////
+  lc1.setChar(0, 1, (hour() % 10), false);
+  lc1.setChar(0, 2, (minute() / 10), false);
+  lc1.setChar(0, 3, (minute() % 10), false);
+}
+
+//
+void updateMisc() {
+  int portion = (second() / 6) + 1; //get the number of bars that should be lit
+  setBar(portion);                  //and then set them
 }

 // Controlls a 10-segment LED bargraph


Code uploaded with no global variables

Code uploaded with no global variables

--- Code/ProgramSerieShuntController/ProgramSerieShuntController.ino
+++ Code/ProgramSerieShuntController/ProgramSerieShuntController.ino
@@ -43,16 +43,20 @@

 volatile int f_wdt=1;                                             // Sleep arduino

-long posit = 0;                                                   // This value will be the previous value of the position of the rotary encoder
+//long posit = 0;                                                   // This value will be the previous value of the position of the rotary encoder
+//long newPos;

 const int analogInPinV = A0;                 // Analog input pin that the potentiometer (Voltmeter) is attached to / Default = A0
 const int analogInPinA = A1;                 // Analog input pin that the potentiometer (Ammeter) is attached to / Default = A1
 const int buttonC = 4;                       // Digital input pin that the button of the rotary encoder is attached to / Default = 4

-char selection = 0;                          // Choose true for PWM, false for no PWM
 const int  overchargeIndicatorLed = 5;       // LedOutput  Default = 2

-float VinMax;                                // Maximum Input Voltage Default = 4
+const char serialDisplayVoltage[] PROGMEM  = {"Actual Voltage : "};
+bool testFirstSleep = HIGH;
+bool testCase5 = LOW;
+
+/*float VinMax;                                // Maximum Input Voltage Default = 4
 unsigned int R1;                             // Bottom resistance Kohm Default = 10
 unsigned int R2 ;                            // top resistance Kohm     Default = 100
 float maxControllerVoltage ;                 // the arduino Uno boardcard cant excess 5 volt   default = 5v
@@ -60,30 +64,19 @@
 float setpointHigh = (VinMax + hysteresis);  // Set setpointHigh Caution the battery may go beyond the overcharge
 float setpointLow = (VinMax - hysteresis) ;  // Set setpointLow
 unsigned int times;                          // Defines the time between two points when drawing the curve
-unsigned char cpt =0;
-
-int limitOverchargeInAnalog;                 // Limit of the overcharge in analog value
-int limitSetpointHighInAnalog;               // Limit of the setpointhigh in analog value
-int limitSetpointLowInAnalog;                // Limit of the setpointlow in analog value
-float limitOverchargeInVolt;                 // Limit of the overcharge in voltage
-float limitSetpointHighInVolt;               // Limit of the setpointhigh in voltage
-float limitSetpointLowInVolt;                // Limit of the setpointLow in voltage
-bool verification;                           // False = Overcharged / True = not overcharged
-float Vin;                                   // Actual Value of the voltage Input
-unsigned char intensity;                     // Used to set the intensity of the led with PWM control
-char pourcentageIntensity;
-int intensityInPercent;
-unsigned char curveCpt = 0;
-float curveTab[120] ;
-byte xCurve = 0;
-
-const char serialDisplayVoltage[] PROGMEM  = {"Actual Voltage : "};
-char state = 0;
-bool testFirstSleep = HIGH;
-bool testCase5 = LOW;
-
+char selection = 0;                          // Choose true for PWM, false for no PWM*/
+
+//float valuesArray[8]; // 0: Vinmax; 1: R1; 2: R2; 3: maxControllerVoltage; 4: hysteresis; 5: setPointHigh; 6: setPointLow; 7: times
+//int limitOverchargeInAnalog;                 // Limit of the overcharge in analog value
+//float limitOverchargeInVolt;                 // Limit of the overcharge in voltage
+//float limitSetpointHighInVolt;               // Limit of the setpointhigh in voltage
+//float limitSetpointLowInVolt;                // Limit of the setpointLow in voltage
+//bool verification;                           // False = Overcharged / True = not overcharged
+//float Vin;                                   // Actual Value of the voltage Input
+//int intensityInPercent;
+//char state = 0;
 /* Value read from the potentiometers */
-int sensorValue = 0;
+//int sensorValue = 0;
 //int ampvalue = 0;

 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -91,7 +84,7 @@
 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 void setup() {
-  char i = 0;
+
   // put your setup code here, to run once:
   // initialize serial:
   Serial.begin(9600);
@@ -105,44 +98,70 @@
   digitalWrite(13,HIGH);                    // Set the pin 13 to HIGH (that turns on the display's blue light so we can see something)
   pinMode(buttonC, INPUT_PULLUP);           // Initialize the encoder button

-  initEEPROMValue();                        // initialization of VinMax, maxControllerVoltage, R1, R2, hysteresis and times with the last values stored in the EEPROM
-  initOLED(500);                             // Setup the WDT
+  //initEEPROMValue(VinMax, maxControllerVoltage, R1, R2, hysteresis, times);                        // initialization of VinMax, maxControllerVoltage, R1, R2, hysteresis and times with the last values stored in the EEPROM
+  initOLED();                               // Setup the WDT

   MCUSR &= ~(1<<WDRF);                      // Clear the reset flag
   WDTCSR |= (1<<WDCE) | (1<<WDE);           // In order to change WDE or the prescaler, we need to set WDCE (This will allow updates for 4 clock cycles).
   WDTCSR = 1<<WDP0 | 1<<WDP1;               // Set new watchdog timeout prescaler value (0.125 seconds)
   WDTCSR |= _BV(WDIE);                      // Enable the WD interrupt (note no reset)
-  for (i = 0; i<120; i++)
+
+
+  delay(100);                               //Allow for serial print to complete.
+}
+
+
+
+
+////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+////////////LOOP////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+void loop() {
+  // put your main code here, to run repeatedly:
+  char i = 0;
+  static float setpointHigh;                          // Set setpointHigh Caution the battery may go beyond the overcharge
+  static float setpointLow;                           // Set setpointLow
+  static float VinMax;                                // Maximum Input Voltage Default = 4
+  static unsigned int R1;                             // Bottom resistance Kohm Default = 10
+  static unsigned int R2 ;                            // top resistance Kohm     Default = 100
+  static float maxControllerVoltage ;                 // the arduino Uno boardcard cant excess 5 volt   default = 5v
+  static float hysteresis ;                           // Value of the hysteresis
+  static unsigned int times;
+  static char first_time = 1;
+  static char selection = 0;
+  static float Vin;
+  static int sensorValue = 0;
+  static long posit = 0;
+  static long newPos = 0;
+  static int limitSetpointHighInAnalog;               // Limit of the setpointhigh in analog value
+  static int limitSetpointLowInAnalog;                // Limit of the setpointlow in analog value
+  static unsigned char cpt =0;
+  static unsigned char curveCpt = 0;
+  static float curveTab[120] ;
+
+  if (first_time == 1)
+  {
+    initEEPROMValue(VinMax, maxControllerVoltage, R1, R2, hysteresis, times);                        // initialization of VinMax, maxControllerVoltage, R1, R2, hysteresis and times with the last values stored in the EEPROM
+    updateValue(setpointHigh, setpointLow, VinMax, hysteresis);
+    for (i = 0; i<120; i++)
     {
       curveTab[i]= 0;
     }
-
-  delay(100);                               //Allow for serial print to complete.
-}
-
-
-
-
-////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-////////////LOOP////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-
-void loop() {
-  // put your main code here, to run repeatedly:
+    first_time = 0;
+  }
+
   if(f_wdt == 1)
   {
 //    ampvalue = analogRead(analogInPinA);
 //    Serial.println("current:");
 //    Serial.println(ampvalue);
-    configureSelection();           // Changes the value of "selection" depending on the position of the encoder
-    seriesRegulator();              // Write 0 in the parenthesis for no PWM or 1 for the PWM //default selection
-    displayOLED(selection);         // Default selection
-    displaySerialInformation();     // Read the global declaration in order to display information on the serial monitor
-
-    Serial.println("curveCpt");
-    Serial.println(curveCpt);
+    selection = configureSelection(sensorValue, setpointHigh, setpointLow, maxControllerVoltage, newPos, posit, limitSetpointHighInAnalog, limitSetpointLowInAnalog);           // Changes the value of "selection" depending on the position of the encoder
+    seriesRegulator(sensorValue, maxControllerVoltage, selection, setpointHigh, setpointLow, Vin, limitSetpointHighInAnalog, limitSetpointLowInAnalog);              // Write 0 in the parenthesis for no PWM or 1 for the PWM //default selection
+    displayOLED(selection, sensorValue, setpointHigh, setpointLow, Vin, VinMax, maxControllerVoltage, times, limitSetpointHighInAnalog, limitSetpointLowInAnalog, cpt, curveTab, curveCpt);         // Default selection
+    displaySerialInformation(Vin);     // Read the global declaration in order to display information on the serial monitor

-    enableMenu(testButtonC());      // Displays the menu if you press the rotary encoder // You can change Vlim, Vmax, R1, R2, hysteresis, times and decide if you the arduino to sleep depending on the position of the encoder
+    enableMenu(testButtonC(), VinMax, maxControllerVoltage, R1, R2, hysteresis, times, setpointHigh, setpointLow, newPos, posit);      // Displays the menu if you press the rotary encoder // You can change Vlim, Vmax, R1, R2, hysteresis, times and decide if you the arduino to sleep depending on the position of the encoder
     f_wdt = 0;

     enterSleepArduino();            // Re-enter sleep mode
@@ -159,7 +178,7 @@
 ///////FUNCTION/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

-void displaySerialInformation()                                                              // Read the global declaration in order to display information on the serial monitor // 0 for all value
+void displaySerialInformation(float Vin)                                                              // Read the global declaration in order to display information on the serial monitor // 0 for all value
 {
   int k;
   char myChar;
@@ -172,14 +191,17 @@
   Serial.println(Vin);
 }

-float getVin(int sensorValue)                                                                // Get Vin value and store it in the global declaration Vin
-{
+float getVin(int sensorValue, float maxControllerVoltage)                                                                // Get Vin value and store it in the global declaration Vin
+{
+  float Vin;
   Vin = ((sensorValue) * maxControllerVoltage / 1024);
   return (Vin);
 }

-bool verificationOvercharge(int sensorValue, int VinMax)                                     // Check for overcharge
-{
+bool verificationOvercharge(int sensorValue, int VinMax, float maxControllerVoltage)                                     // Check for overcharge
+{
+  int limitOverchargeInAnalog;
+  float limitOverchargeInVolt;
   limitOverchargeInVolt = VinMax;                                                            // * (((R1 + R2)*1000) / (R1*1000)); // PotentialDiviser R1 = bottom // R2 = top // VinMax= Maximum Input Voltage
   limitOverchargeInAnalog = 1024 * ( limitOverchargeInVolt / maxControllerVoltage) ;

@@ -194,8 +216,9 @@

 }

-bool verificationSetpointHigh(int sensorValue, float setpointHigh)                           // Check if sensorValue is higher than setpointHigh
-{
+bool verificationSetpointHigh(int sensorValue, float setpointHigh, float maxControllerVoltage, int & limitSetpointHighInAnalog)                           // Check if sensorValue is higher than setpointHigh
+{
+  float limitSetpointHighInVolt;
   limitSetpointHighInVolt = setpointHigh ;
   limitSetpointHighInAnalog = 1024 * ( limitSetpointHighInVolt / maxControllerVoltage) ;

@@ -209,9 +232,9 @@
   }
 }

-bool verificationSetpointLow(int sensorValue, float setpointLow)                             // Check if sensorValue is lower than setpointLow
-{
-
+bool verificationSetpointLow(int sensorValue, float setpointLow, float maxControllerVoltage, int & limitSetpointLowInAnalog)                             // Check if sensorValue is lower than setpointLow
+{
+  float limitSetpointLowInVolt;
   limitSetpointLowInVolt = setpointLow;
   limitSetpointLowInAnalog = 1024 * ( limitSetpointLowInVolt / maxControllerVoltage) ;

@@ -225,88 +248,88 @@
   }
 }

-void seriesRegulator()                            // The function that does the regulation
+void seriesRegulator(int & sensorValue, float maxControllerVoltage, char selection, float setpointHigh, float setpointLow, float & Vin, int limitSetpointHighInAnalog, int limitSetpointLowInAnalog)                            // The function that does the regulation
 {
   char i;
   for (i=0; i<11; i++)
   {
     delay(50);
     sensorValue = analogRead(analogInPinV);
-    getVin(sensorValue);
-    controlMosfet();
+    Vin = getVin(sensorValue, maxControllerVoltage);
+    controlMosfet(selection, maxControllerVoltage, sensorValue, setpointHigh, setpointLow, limitSetpointHighInAnalog, limitSetpointLowInAnalog);
     //CheckButtonA();
   }
 }

-void PWMwrite(int intensity, int outputPin)       // Generate the PWM square wave with the right duty cycle
+void PWMwrite(int intensity, int outputPin, int limitSetpointHighInAnalog, int limitSetpointLowInAnalog)       // Generate the PWM square wave with the right duty cycle
 {
   int mappedIntensity;
   mappedIntensity = map(intensity,limitSetpointLowInAnalog,limitSetpointHighInAnalog, 0, 255);
   analogWrite(outputPin, mappedIntensity);
 }

-void controlShuntPWM(void)
-{
-  if(verificationSetpointHigh(sensorValue,setpointHigh)==1)     //Voltage higher than setpointHigh
-  {
-    digitalWrite(overchargeIndicatorLed, HIGH);                 // Turn on the led // Overcharged
-  }
-  else if (verificationSetpointLow(sensorValue,setpointLow)==1) //Voltage lower than setpointLow
-  {
-    digitalWrite(overchargeIndicatorLed, LOW);                  // Turn off the led // Not overcharged
-  }
-  else
-  {
-    PWMwrite(sensorValue, overchargeIndicatorLed);              // Hysteresis
-  }
-}
-
-void controlShuntNoPWM(void)
-{
-  if(verificationSetpointHigh(sensorValue,setpointHigh)==1)     //Voltage higher than setpointHigh
-  {
-    digitalWrite(overchargeIndicatorLed, HIGH);                 // Turn on the led // Overcharged
-  }
-  else if (verificationSetpointLow(sensorValue,setpointLow)==1) //Voltage lower than setpointLow
-  {
-    digitalWrite(overchargeIndicatorLed, LOW);                  // Turn off the led // Not overcharged
-  }
-  else
-  {
-                                                                // Hysteresis
-  }
-}
-
-void controlMosfet()                                            // Selection of the control mode
+void controlShuntPWM(float maxControllerVoltage, int sensorValue, float setpointHigh, float setpointLow, int limitSetpointHighInAnalog, int limitSetpointLowInAnalog)
+{
+  if(verificationSetpointHigh(sensorValue,setpointHigh,maxControllerVoltage, limitSetpointHighInAnalog)==1)     //Voltage higher than setpointHigh
+  {
+    digitalWrite(overchargeIndicatorLed, HIGH);                                      // Turn on the led // Overcharged
+  }
+  else if (verificationSetpointLow(sensorValue,setpointLow,maxControllerVoltage, limitSetpointLowInAnalog)==1) //Voltage lower than setpointLow
+  {
+    digitalWrite(overchargeIndicatorLed, LOW);                                       // Turn off the led // Not overcharged
+  }
+  else
+  {
+    PWMwrite(sensorValue, overchargeIndicatorLed, limitSetpointHighInAnalog, limitSetpointLowInAnalog);                                   // Hysteresis
+  }
+}
+
+void controlShuntNoPWM(float maxControllerVoltage, int sensorValue, float setpointHigh, float setpointLow, int limitSetpointHighInAnalog, int limitSetpointLowInAnalog)
+{
+  if(verificationSetpointHigh(sensorValue,setpointHigh,maxControllerVoltage, limitSetpointHighInAnalog)==1)     //Voltage higher than setpointHigh
+  {
+    digitalWrite(overchargeIndicatorLed, HIGH);                                      // Turn on the led // Overcharged
+  }
+  else if (verificationSetpointLow(sensorValue,setpointLow,maxControllerVoltage, limitSetpointLowInAnalog)==1) //Voltage lower than setpointLow
+  {
+    digitalWrite(overchargeIndicatorLed, LOW);                                       // Turn off the led // Not overcharged
+  }
+  else
+  {
+                                                                                // Hysteresis
+  }
+}
+
+void controlMosfet(char selection, float maxControllerVoltage, int sensorValue, float setpointHigh, float setpointLow, int limitSetpointHighInAnalog, int limitSetpointLowInAnalog)                                            // Selection of the control mode
 {
   if (selection == 0)
   {
-    controlSerieNoPWM();
+    controlSerieNoPWM(maxControllerVoltage, sensorValue, setpointHigh, setpointLow, limitSetpointHighInAnalog, limitSetpointLowInAnalog);
   }
   else if (selection == 1)
   {
-    controlSeriePWM();
+    controlSeriePWM(maxControllerVoltage, sensorValue, setpointHigh, setpointLow, limitSetpointHighInAnalog, limitSetpointLowInAnalog);
   }
   else if (selection == 2)
   {
-    controlShuntNoPWM();
+    controlShuntNoPWM(maxControllerVoltage, sensorValue, setpointHigh, setpointLow, limitSetpointHighInAnalog, limitSetpointLowInAnalog);
   }
   else if (selection == 3)
   {
-    controlShuntPWM();
-  }
-}
-
-char getIntensityInPercent()                                    // Turn sensorValue into a percentage depending on the value of "selection"
-{
-
+    controlShuntPWM(maxControllerVoltage, sensorValue, setpointHigh, setpointLow, limitSetpointHighInAnalog, limitSetpointLowInAnalog);
+  }
+}
+
+char getIntensityInPercent(char selection, int sensorValue, float setpointHigh, float setpointLow, float maxControllerVoltage, int limitSetpointHighInAnalog, int limitSetpointLowInAnalog)                                    // Turn sensorValue into a percentage depending on the value of "selection"
+{
+  int intensityInPercent;
   if (selection == 2)
   {
-    if (verificationSetpointHigh(sensorValue,setpointHigh) == 1)
+    if (verificationSetpointHigh(sensorValue,setpointHigh,maxControllerVoltage, limitSetpointHighInAnalog) == 1)
     {
       intensityInPercent = 100;
     }
-    else if (verificationSetpointLow(sensorValue,setpointLow) == 1)
+    else if (verificationSetpointLow(sensorValue,setpointLow,maxControllerVoltage, limitSetpointLowInAnalog) == 1)
     {
       intensityInPercent = 0;
     }
@@ -325,11 +348,11 @@
   }
   else if (selection == 0)
   {
-    if (verificationSetpointHigh(sensorValue,setpointHigh)==1)
+    if (verificationSetpointHigh(sensorValue,setpointHigh,maxControllerVoltage, limitSetpointHighInAnalog)==1)
     {
       intensityInPercent = 0;
     }
-    else if (verificationSetpointLow(sensorValue,setpointLow)==1)
+    else if (verificationSetpointLow(sensorValue,setpointLow,maxControllerVoltage, limitSetpointLowInAnalog)==1)
     {
       intensityInPercent = 100;
     }
@@ -350,7 +373,7 @@
 }

-void initOLED( int tempo )                         // Initialize the OLED
+void initOLED()                         // Initialize the OLED
 {
   u8g.begin();
   if ( u8g.getMode() == U8G_MODE_R3G3B2 ) {
@@ -373,14 +396,13 @@
   u8g.drawStr(20 , 50,"(C)2016 by");
   u8g.drawStr(8 , 64,"Matthew Little");
 } while(u8g.nextPage());
-  delay(tempo);
-
-}
-
-void displayOLED(char selection)                   // Diplays the informations on the OLED
+  delay(500);
+
+}
+
+void displayOLED(char selection, int sensorValue, float setpointHigh, float setpointLow, float Vin, float VinMax, float maxControllerVoltage, unsigned int times, int limitSetpointHighInAnalog, int limitSetpointLowInAnalog, unsigned char & cpt, float curveTab[], unsigned char & curveCpt)                   // Diplays the informations on the OLED
 {
   char percent;
-
   float mappedval;

   u8g.firstPage();
@@ -421,7 +443,7 @@
   u8g.setPrintPos(35, 30);
   u8g.print('v');

-  percent = getIntensityInPercent();
+  percent = getIntensityInPercent(selection, sensorValue, setpointHigh, setpointLow, maxControllerVoltage, limitSetpointHighInAnalog, limitSetpointLowInAnalog);
   if ((float)percent == 100)
   {
     u8g.setPrintPos(92, 30);
@@ -443,8 +465,8 @@
   u8g.drawHLine(5, 60, 120);
   u8g.drawLine(5, 60, 5, 35);

-  drawBatteryLimit();
-  curveDisplay();
+  drawBatteryLimit(VinMax, maxControllerVoltage);
+  curveDisplay(Vin, maxControllerVoltage, times, cpt, curveTab, curveCpt);
   }while(u8g.nextPage());
   if (curveCpt < 120)
   {
@@ -472,12 +494,12 @@
   }
 }

-void enableMenu(bool enable) // Displays the menu if you press the rotary encoder // You can change Vlim, Vmax, R1, R2, hysteresis, times and decide if you the arduino to sleep depending on the position of the encoder
+void enableMenu(bool enable, float & VinMax, float & maxControllerVoltage, unsigned int & R1, unsigned int & R2, float & hysteresis, unsigned int & times, float setpointHigh, float setpointLow, long & newPos, long & posit) // Displays the menu if you press the rotary encoder // You can change Vlim, Vmax, R1, R2, hysteresis, times and decide if you the arduino to sleep depending on the position of the encoder
 {
   char y;
   char x;
-  long newPos;
   char choix = 0;
+  char state = 0;

   if(testCase5 == HIGH)
   {
@@ -653,8 +675,6 @@
         //posit = newPos;
         //posit = 0;
       }
-
-      Serial.println(newPos);

       if(( newPos >= 26) || (newPos < -26))
       {
@@ -1064,37 +1084,43 @@
   choix = 0;
   delay(1500);
 }
-updateValue();
-}
-}
-
-bool configureSelection()                             // Changes the value of "selection" depending on the position of the encoder
-{
-  long newPos;
+updateValue(setpointHigh, setpointLow, VinMax, hysteresis);
+}
+}
+
+char configureSelection(int sensorValue, float setpointHigh, float setpointLow, float maxControllerVoltage, long & newPos, long & posit, int limitSetpointHighInAnalog, int limitSetpointLowInAnalog)                             // Changes the value of "selection" depending on the position of the encoder
+{
+  char selection;
+  int intensityInPercent;
+
   newPos = rotEncoder.read() - posit;

   Serial.println(newPos);
   if(( newPos >= -2) & (newPos < 2))
   {
     selection = 1;
-
+    return(selection);
   }
   else if(((newPos >= 2) && (newPos < 6)) || ((newPos < -10) && (newPos >= -14)))
   {
     selection = 0;
+    intensityInPercent = getIntensityInPercent(selection,sensorValue,setpointHigh,setpointLow, maxControllerVoltage, limitSetpointHighInAnalog, limitSetpointLowInAnalog);
     if(intensityInPercent != 100)
     {
       digitalWrite(overchargeIndicatorLed, LOW);
       intensityInPercent =0;
     }
+    return(selection);
   }
   else if(((newPos >= 6) && (newPos < 10)) || ((newPos < -6) && (newPos >= -10)))
   {
     selection = 2;
+    return(selection);
   }
   else if(((newPos >= 10) && (newPos < 14)) || ((newPos < -2) && (newPos >= -6)))
   {
     selection = 3;
+    return(selection);
   }
   else
   {
@@ -1117,13 +1143,13 @@
 }

-void controlSerieNoPWM(void)
-{
-  if(verificationSetpointHigh(sensorValue,setpointHigh)==1)     //Voltage higher than setpointHigh
+void controlSerieNoPWM(float maxControllerVoltage, int sensorValue, float setpointHigh, float setpointLow, int limitSetpointHighInAnalog, int limitSetpointLowInAnalog)
+{
+  if(verificationSetpointHigh(sensorValue,setpointHigh,maxControllerVoltage, limitSetpointHighInAnalog)==1)     //Voltage higher than setpointHigh
   {
     digitalWrite(overchargeIndicatorLed, LOW);                  // Turn on the led // Overcharged
   }
-  else if (verificationSetpointLow(sensorValue,setpointLow)==1) // Voltage lower than setpointLow
+  else if (verificationSetpointLow(sensorValue,setpointLow,maxControllerVoltage, limitSetpointLowInAnalog)==1) // Voltage lower than setpointLow
   {
     digitalWrite(overchargeIndicatorLed, HIGH);                 // Turn off the led // Not overcharged
   }
@@ -1133,31 +1159,58 @@
   }
 }

-void controlSeriePWM(void)
-{
-  if(verificationSetpointHigh(sensorValue,setpointHigh)==1)     //Voltage higher than setpointHigh
+void controlSeriePWM(float maxControllerVoltage, int sensorValue, float setpointHigh, float setpointLow, int limitSetpointHighInAnalog, int limitSetpointLowInAnalog)
+{
+  if(verificationSetpointHigh(sensorValue,setpointHigh,maxControllerVoltage, limitSetpointHighInAnalog)==1)     //Voltage higher than setpointHigh
   {
     digitalWrite(overchargeIndicatorLed, LOW);                  // TURN on the led // Overcharged
   }
-  else if (verificationSetpointLow(sensorValue,setpointLow)==1) //Voltage lower than setpointHigh
+  else if (verificationSetpointLow(sensorValue,setpointLow,maxControllerVoltage, limitSetpointLowInAnalog)==1) //Voltage lower than setpointHigh
   {
     digitalWrite(overchargeIndicatorLed, HIGH);                 // Light off the led // Not overcharged
   }
   else
   {
-    PWMwriteShunt(sensorValue, overchargeIndicatorLed);         // Hysteresis
-  }
-}
-
-
-void drawCurve(byte numberArray)
+    PWMwriteShunt(sensorValue, overchargeIndicatorLed, limitSetpointHighInAnalog, limitSetpointLowInAnalog);         // Hysteresis
+  }
+}
+
+void PWMwriteShunt(int intensity, int outputPin, int limitSetpointHighInAnalog, int limitSetpointLowInAnalog) //Generate the PWM square wave with the right duty cycle
 {
-  u8g.setColorIndex(1);
-  u8g.drawPixel(5 + numberArray, 60 - curveTab[numberArray]);
-  u8g.setColorIndex(255);
-}
-
-void drawBatteryLimit(void)
+  int mappedIntensity;
+  mappedIntensity = map(intensity,limitSetpointHighInAnalog,limitSetpointLowInAnalog, 0, 255);
+  analogWrite(outputPin, mappedIntensity);
+}
+
+ISR(WDT_vect)                             //Watchdog Interrupt Service. This is executed when watchdog timed out
+{
+  if(f_wdt == 0)
+  {
+    f_wdt=1;
+  }
+  else
+  {
+             //Serial.println("WDT Overrun!!!");
+  }
+}
+
+void updateValue(float & setpointHigh, float & setpointLow, float VinMax, float hysteresis)                    // Update setpointHigh and setpointLow depending on VinMax and hysteresis
+{
+  setpointHigh = (VinMax + hysteresis);
+  setpointLow = (VinMax - hysteresis) ;
+}
+
+void initEEPROMValue (float & VinMax, float & maxControllerVoltage, unsigned int & R1, unsigned int & R2, float & hysteresis, unsigned int & times)               // initialization of VinMax, maxControllerVoltage, R1, R2, hysteresis and times with the last values stored in the EEPROM
+{
+  VinMax = EEPROM.readFloat(0);
+  maxControllerVoltage = EEPROM.readFloat(4);
+  R1 = EEPROM.read(8);
+  R2 = EEPROM.read(12);
+  hysteresis = EEPROM.readFloat(16);
+  times = EEPROM.readInt(20);
+}
+
+void drawBatteryLimit(float VinMax, float maxControllerVoltage)
 {
   char i;
   float mappedVinMax;
@@ -1171,42 +1224,7 @@
   u8g.setColorIndex(255);
 }

-void PWMwriteShunt(int intensity, int outputPin) //Generate the PWM square wave with the right duty cycle
-{
-  int mappedIntensity;
-  mappedIntensity = map(intensity,limitSetpointHighInAnalog,limitSetpointLowInAnalog, 0, 255);
-  analogWrite(outputPin, mappedIntensity);
-}
-
-ISR(WDT_vect)                             //Watchdog Interrupt Service. This is executed when watchdog timed out
-{
-  if(f_wdt == 0)
-  {
-    f_wdt=1;
-  }
-  else
-  {
-             //Serial.println("WDT Overrun!!!");
-  }
-}
-
-void updateValue(void)                    // Update setpointHigh and setpointLow depending on VinMax and hysteresis
-{
-  setpointHigh = (VinMax + hysteresis);
-  setpointLow = (VinMax - hysteresis) ;
-}
-
-void initEEPROMValue (void)               // initialization of VinMax, maxControllerVoltage, R1, R2, hysteresis and times with the last values stored in the EEPROM
-{
-  VinMax = EEPROM.readFloat(0);
-  maxControllerVoltage = EEPROM.readFloat(4);
-  R1 = EEPROM.read(8);
-  R2 = EEPROM.read(12);
-  hysteresis = EEPROM.readFloat(16);
-  times = EEPROM.readInt(20);
-}
-
-void curveDisplay(void)                   // Draw the curve
+void curveDisplay(float Vin, float maxControllerVoltage, unsigned int times, unsigned char & cpt, float curveTab[], unsigned char curveCpt)                   // Draw the curve
 {
   char i;
   float mappedValueVin;
@@ -1224,7 +1242,9 @@
   {
     for (i = 0; i<curveCpt; i++)
     {
-      drawCurve(i);
+      u8g.setColorIndex(1);
+      u8g.drawPixel(5 + i, 60 - curveTab[i]);
+      u8g.setColorIndex(255);
     }
   }
   else


Add preamp usage to the CPU profile

Add preamp usage to the CPU profile

--- roto.ino
+++ roto.ino
@@ -184,6 +184,12 @@
     Serial.print(vibrato.processorUsageMax());
     Serial.print("  ");

+    Serial.print("preamp=");
+    Serial.print(preamp.processorUsage());
+    Serial.print(",");
+    Serial.print(preamp.processorUsageMax());
+    Serial.print("  ");
+
     Serial.print("antialias=");
     Serial.print(antialias.processorUsage());
     Serial.print(",");


Port to the more modern world: Arduino 1.6.13 and MIDI lib 4.3.1

--- roto.ino
+++ roto.ino
@@ -6,6 +6,8 @@
 #undef ROTO_TEST_TONES

 #include "tonewheels.h"
+
+MIDI_CREATE_DEFAULT_INSTANCE();

 #define BUFFER_LEN 128


Improved

Improved

--- JamesBrown/JamesBrown.ino
+++ JamesBrown/JamesBrown.ino
@@ -1,9 +1,9 @@
 #include <SD.h>

-const int pin_card_select{10}; //Must be 10, the shield requires it
-const int pin_chip_select{4};
-const int pin_thermistor{A0};
-const int pin_humidity{A1};
+const int pin_card_select = 10; //Must be 10, the shield requires it
+const int pin_chip_select = 4;
+const int pin_thermistor = A0;
+const int pin_humidity = A1;

 void setup()
 {
@@ -37,8 +37,8 @@

 void loop()
 {
-  const int temperature{analogRead(pin_thermistor)};
-  const int humidity{analogRead(pin_humidity)};
+  const int temperature = analogRead(pin_thermistor);
+  const int humidity = analogRead(pin_humidity);

   const String s
     = String(millis() / 1000)
@@ -61,4 +61,3 @@
   }
   delay(1000);
 }
-


added missing ssl port

added missing ssl port

--- examples/ArduinoWiFi101_SSL/ArduinoWiFi101_SSL.ino
+++ examples/ArduinoWiFi101_SSL/ArduinoWiFi101_SSL.ino
@@ -27,7 +27,7 @@
 void setup() {
   Serial.begin(9600);
   WiFi.begin(ssid, pass);
-  client.begin("broker.shiftr.io", net);
+  client.begin("broker.shiftr.io", 8883, net);

   connect();
 }


Modifying WeatherStationDemo to work on ESP32

--- examples/WeatherStationDemo/WeatherStationDemo.ino
+++ examples/WeatherStationDemo/WeatherStationDemo.ino
@@ -23,8 +23,10 @@
 See more at http://blog.squix.ch
 */

-#include <ESP8266WiFi.h>
+#include <ESPWiFi.h>
+#if defined(ESP8266)
 #include <Ticker.h>
+#endif
 #include <JsonListener.h>
 #include "SSD1306Wire.h"
 #include "OLEDDisplayUi.h"
@@ -51,8 +53,13 @@

 // Display Settings
 const int I2C_DISPLAY_ADDRESS = 0x3c;
+#if defined(ESP8266)
 const int SDA_PIN = D3;
 const int SDC_PIN = D4;
+#else
+const int SDA_PIN = 5; //D3;
+const int SDC_PIN = 4; //D4;
+#endif

 // TimeClient settings
 const float UTC_OFFSET = 2;
@@ -89,7 +96,11 @@

 String lastUpdate = "--";

+#if defined(ESP8266)
 Ticker ticker;
+#else
+long timeSinceLastWUpdate = 0;
+#endif

 //declaring prototypes
 void drawProgress(OLEDDisplay *display, int percentage, String label);
@@ -169,12 +180,21 @@
   Serial.println("");

   updateData(&display);
-
+
+#if defined(ESP8266)
   ticker.attach(UPDATE_INTERVAL_SECS, setReadyForWeatherUpdate);
+#endif

 }

 void loop() {
+
+#if !defined(ESP8266)
+  if (millis() - timeSinceLastWUpdate > (1000L*UPDATE_INTERVAL_SECS)) {
+    setReadyForWeatherUpdate();
+    timeSinceLastWUpdate = millis();
+  }
+#endif

   if (readyForWeatherUpdate && ui.getUiState()->frameState == FIXED) {
     updateData(&display);


Version 2.9a - 22nd September 2019

Version 2.9a - 22nd September 2019

Make analogwrite work with DAC

--- ulisp.ino
+++ ulisp.ino
@@ -1,5 +1,5 @@
-/* uLisp AVR Version 2.9 - www.ulisp.com
-   David Johnson-Davies - www.technoblogy.com - 20th September 2019
+/* uLisp AVR Version 2.9a - www.ulisp.com
+   David Johnson-Davies - www.technoblogy.com - 22nd September 2019

    Licensed under the MIT license: https://opensource.org/licenses/MIT
 */
@@ -1211,7 +1211,7 @@
 #elif defined(__AVR_ATmega4809__)
   if (!(pin==3 || pin==5 || pin==6 || pin==9 || pin==10)) error(ANALOGWRITE, invalidpin, number(pin));
 #elif defined(__AVR_ATtiny3216__)
-  if (!(pin==0 || pin==1 || (pin>=7 && pin<=11) || pin==16)) error(ANALOGWRITE, invalidpin, number(pin));
+  if (!((pin>=0 && pin<=2) || (pin>=7 && pin<=11) || pin==16)) error(ANALOGWRITE, invalidpin, number(pin));
 #endif
 }


Ellie 4/15/2017: Move sensor readings to subroutines.

--- AzElSensor/AzElSensor.ino
+++ AzElSensor/AzElSensor.ino
@@ -9,6 +9,9 @@
  * http://www.lucidarme.me/?p=5057
  *
 */
+
+// 4/15 changes by Ellie:  starting line 129, I made subroutines to read/print accel and gyro data
+

 #include <Wire.h>
 #include <TimerOne.h>
@@ -66,7 +69,7 @@
 {
   // Arduino initializations
   Wire.begin();
-  Serial.begin(115200);
+  Serial.begin(9600);

   // Set accelerometers low pass filter at 5Hz
   I2CwriteByte(MPU9250_ADDRESS,29,0x06);
@@ -84,8 +87,8 @@
   // Request continuous magnetometer measurements in 16 bits
   I2CwriteByte(MAG_ADDRESS,0x0A,0x16);

-  pinMode(13, OUTPUT);
-  Timer1.initialize(10000);         // initialize timer1, and set a 1/2 second period
+   pinMode(13, OUTPUT);
+  Timer1.initialize(100000);         // initialize timer1, and set a 1/2 second period
   Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt

@@ -99,6 +102,13 @@

 // Counter
 long int cpt=0;
+
+uint8_t Buf[6];
+int16_t ax, ay, az;
+int16_t gx, gy, gz;
+int16_t mx, my, mz;
+uint8_t Mag[7];
+

 void callback()
 {
@@ -113,8 +123,7 @@
   intFlag=false;

   // Display time
-  //Serial.print (millis()-ti,DEC);
-  Serial.print (String("time: ")+String(millis()-ti));
+  Serial.print (millis()-ti,DEC);
   Serial.print ("\t");

@@ -125,54 +134,63 @@
 //  Serial.print (cpt++,DEC);
 //  Serial.print ("\t");

-
+  // End of line
+  Serial.println("");
+  delay(500);

   // ____________________________________
   // :::  accelerometer and gyroscope :::
-
-  // Read accelerometer and gyroscope
-  uint8_t Buf[14];
-  I2Cread(MPU9250_ADDRESS,0x3B,14,Buf);
+}
+
+
+  void accelerometer_subr()
+  {
+ // Read accelerometer data
+    I2Cread(MPU9250_ADDRESS,0x3B,6,Buf);

   // Create 16 bits values from 8 bits data
-
-  // Accelerometer
-  int16_t ax=-(Buf[0]<<8 | Buf[1]);
-  int16_t ay=-(Buf[2]<<8 | Buf[3]);
-  int16_t az=Buf[4]<<8 | Buf[5];
-
-  // Gyroscope
-  int16_t gx=-(Buf[8]<<8 | Buf[9]);
-  int16_t gy=-(Buf[10]<<8 | Buf[11]);
-  int16_t gz=Buf[12]<<8 | Buf[13];
-
-    // Display values
-
-  // Accelerometer
-  Serial.print("Accel: ");
-  Serial.print (ax,DEC);
-  Serial.print ("\t");
-  Serial.print (ay,DEC);
-  Serial.print ("\t");
-  Serial.print (az,DEC);
-  Serial.print ("\t");
-
-  // Gyroscope
-  Serial.print("Gyro: ");
-  Serial.print (gx,DEC);
-  Serial.print ("\t");
-  Serial.print (gy,DEC);
-  Serial.print ("\t");
-  Serial.print (gz,DEC);
-  Serial.print ("\t");
-
-
+    ax=-(Buf[0]<<8 | Buf[1]);
+    ay=-(Buf[2]<<8 | Buf[3]);
+    az=Buf[4]<<8 | Buf[5];
+
+  //print accelerometer data
+    Serial.print (ax,DEC);
+    Serial.print ("\t");
+    Serial.print (ay,DEC);
+    Serial.print ("\t");
+    Serial.print (az,DEC);
+    Serial.print ("\t");
+  }
+
+
+  void gyro_subr()
+  {
+  // Read gyroscope data
+    I2Cread(MPU9250_ADDRESS,0x43,6,Buf);
+
+  // Create 16 bits values from 8 bits data
+    int16_t gx=-(Buf[0]<<8 | Buf[1]);
+    int16_t gy=-(Buf[2]<<8 | Buf[3]);
+    int16_t gz=Buf[4]<<8 | Buf[5];
+
+  // print gyroscope data
+    Serial.print (gx,DEC);
+    Serial.print ("\t");
+    Serial.print (gy,DEC);
+    Serial.print ("\t");
+    Serial.print (gz,DEC);
+    Serial.print ("\t");
+
+  }
   // _____________________
   // :::  Magnetometer :::

   // Read register Status 1 and wait for the DRDY: Data Ready
-
+
+  void subr_magnetometer()
+  {
+
   uint8_t ST1;
   do
   {
@@ -180,32 +198,33 @@
   }
   while (!(ST1&0x01));

-  // Read magnetometer data
-  uint8_t Mag[7];
-  I2Cread(MAG_ADDRESS,0x03,7,Mag);
-
-
+  // Read magnetometer data
+    I2Cread(MAG_ADDRESS,0x03,7,Mag);
+
   // Create 16 bits values from 8 bits data
-
-  // Magnetometer
-  int16_t mx=-(Mag[3]<<8 | Mag[2]);
-  int16_t my=-(Mag[1]<<8 | Mag[0]);
-  int16_t mz=-(Mag[5]<<8 | Mag[4]);
-
-
-  // Magnetometer
-  Serial.print("Compass: ");
-  Serial.print (mx+200,DEC);
-  Serial.print ("\t");
-  Serial.print (my-70,DEC);
-  Serial.print ("\t");
-  Serial.print (mz-700,DEC);
-  Serial.print ("\t");
-
-
-
-  // End of line
-  Serial.println("");
-  Serial.flush();
-
-}
+    mx=-(Mag[3]<<8 | Mag[2]);
+    my=-(Mag[1]<<8 | Mag[0]);
+    mz=-(Mag[5]<<8 | Mag[4]);
+
+
+  // print magnetometer data
+    Serial.print (mx,DEC);//(mx+200,DEC);
+    Serial.print ("\t");
+    Serial.print (my,DEC);//(my-70,DEC);
+    Serial.print ("\t");
+    Serial.print (mz,DEC);//(mz-700,DEC);
+    Serial.print ("\t");
+
+  }
+
+
+
+
+
+
+
+
+
+
+
+


Added licence header

Added licence header

--- arduino/gps/simple_gps/simple_gps.ino
+++ arduino/gps/simple_gps/simple_gps.ino
@@ -1,3 +1,30 @@
+/*
+Copyright (c) 2014 - 2015, Intel Corporation
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+    * Redistributions of source code must retain the above copyright notice,
+      this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above copyright notice,
+      this list of conditions and the following disclaimer in the documentation
+      and/or other materials provided with the distribution.
+    * Neither the name of Intel Corporation nor the names of its contributors
+      may be used to endorse or promote products derived from this software
+      without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
 void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);


update with flashing and buzz alarm

update with flashing and buzz alarm

--- examples/ALARM/ALARM.ino
+++ examples/ALARM/ALARM.ino
@@ -9,8 +9,8 @@

 #define SENSOR_ID "ALARM1"

-#define ALARM_RELAY_PIN        D6
-
+#define ALARM_LED_RELAY_PIN        D5
+#define ALARM_BUZ_RELAY_PIN        D1

@@ -20,27 +20,38 @@
 #define MQTT_PORT 1883

 //Constants
-const char TV_STATE_OFF = 1;
-const char TV_STATE_ON  = 2;
-const char ALARM_ON  =  '2';
-const char ALARM_OFF =  '1';
-
+const char ALARM_LED_ON  =  '2';
+const char ALARM_LED_OFF =  '1';
+const char ALARM_BUZ_ON  =  '4';
+const char ALARM_BUZ_OFF =  '3';
 void processAlarmStateMsg(char* topic, byte* payload, unsigned int length)
 {

   Serial.print("Checking if state topic");
   if(String(topic) == "ALARM1/cmd"){
 	  Serial.println("Received Alarm change message");
-       if ((char)payload[0] == ALARM_ON){
-		    Serial.println("ALARM ON received");
+       if ((char)payload[0] == ALARM_LED_ON){
+		    Serial.println("ALARM LED ON received");

-			  switchAlarmOn();
+			  switchAlarmLedOn();

 	     }
-       else if ((char)payload[0] == ALARM_OFF){
-        Serial.println("ALARM OFF received");
+       else if ((char)payload[0] == ALARM_LED_OFF){
+        Serial.println("ALARM LED OFF received");

-        switchAlarmOff();
+        switchAlarmLedOff();
+
+       }
+       else if ((char)payload[0] == ALARM_BUZ_ON){
+        Serial.println("ALARM BUZ ON received");
+
+        switchAlarmBuzOn();
+
+       }
+       else if ((char)payload[0] == ALARM_BUZ_OFF){
+        Serial.println("ALARM BUZ OFF received");
+
+        switchAlarmBuzOff();

        }
 		 else {
@@ -53,9 +64,10 @@

 void setup() {
   Serial.begin(115200);
-  pinMode(ALARM_RELAY_PIN, OUTPUT);
-  digitalWrite(ALARM_RELAY_PIN, HIGH);
-
+  pinMode(ALARM_LED_RELAY_PIN, OUTPUT);
+  digitalWrite(ALARM_LED_RELAY_PIN, LOW);
+  pinMode(ALARM_BUZ_RELAY_PIN, OUTPUT);
+  digitalWrite(ALARM_BUZ_RELAY_PIN, LOW);

   delay(10);

@@ -66,16 +78,28 @@
 }

-void switchAlarmOn(){
+void switchAlarmLedOn(){

-  Serial.println("Switching Alarm ON");
-  digitalWrite(ALARM_RELAY_PIN, LOW);
+  Serial.println("Switching Alarm LED ON");
+  digitalWrite(ALARM_LED_RELAY_PIN, HIGH);

 }
-void switchAlarmOff(){
+void switchAlarmLedOff(){

-  Serial.println("Switching Alarm OFF");
-  digitalWrite(ALARM_RELAY_PIN, HIGH);
+  Serial.println("Switching Alarm LED OFF");
+  digitalWrite(ALARM_LED_RELAY_PIN, LOW);
+
+}
+void switchAlarmBuzOn(){
+
+  Serial.println("Switching Alarm BUZ ON");
+  digitalWrite(ALARM_BUZ_RELAY_PIN, HIGH);
+
+}
+void switchAlarmBuzOff(){
+
+  Serial.println("Switching Alarm BUZ OFF");
+  digitalWrite(ALARM_BUZ_RELAY_PIN, LOW);

 }
 void loop() {
@@ -91,4 +115,4 @@
   delay(10);

-}+}


add function of Push

add function of Push

--- tank/src/sketch.ino
+++ tank/src/sketch.ino
@@ -8,6 +8,10 @@
 #define MAX 250
 #define NOM 50

+//発射
+const int Push_A = 7;
+const int Push_B = 8;
+
 //上の回線部分
 const int Turn_A = 2;
 const int Turn_B = 3;
@@ -15,7 +19,7 @@
 //右モーター
 const int Right_A = 4;
 const int Right_B = 5;
-const int Right_PWM = 6; //速度調整用のアナログピン
+const int Right_PWM = 6;

 //左モーター
 const int Left_PWM = 11;
@@ -23,13 +27,13 @@
 const int Left_B = 13;

 int r,l;
+
 //砲台の上下
 Servo myservo;

 //シリアル通信で使う文字の宣言
 char ch = 'R';

-//設定について記述
 void setup(){
   //シリアルポートの設定
   Serial.begin(9600);
@@ -46,30 +50,32 @@
 /*   独自関数を記述します  */

 //砲台の回転に関する関数
-//砲台右回転
 void Turn_Right(void){
   digitalWrite(Turn_A,HIGH);
   digitalWrite(Turn_B,LOW);
 }
-
-//砲台左回転
 void Turn_Left(void){
   digitalWrite(Turn_A,LOW);
   digitalWrite(Turn_B,HIGH);
 }
-
-//砲台回転ストップ
-void Turn_Stop(void){
+void Turn_Stop(){
   digitalWrite(Turn_A,LOW);
   digitalWrite(Turn_B,LOW);
 }

+//砲台の上下
 void battery(char val){
   if(val != 'x'){
 	int vali = elect(val);
 	vali = vali * 10;
 	myservo.write(vali);
   }
+}
+
+//発射
+void Push(void){
+  digitalWrite(Push_A,LOW);
+  digitalWrite(Push_B,HIGH);
 }

 //右側モーターに関する関数
@@ -108,7 +114,6 @@
 	analogWrite(Left_PWM,NOM + (-vali  * 10));
   }
 }
-//砲台の上下に関する関数

 int elect(char x){
   switch(x){
@@ -144,11 +149,13 @@
 				 break;
 			   }
 			   //Car battery's servo moter
+
 	  case 'H':{
 				 ch = Serial.read();
-
+				 battery(ch);
 				 break;
 			   }
+
 			   //B1:Battery right moter B2:Battery left Moter B3:Firing
 	  case 'B':{
 				 ch = Serial.read();
@@ -170,7 +177,7 @@
 				 }
 				 ch = Serial.read();
 				 if(ch == '1'){
-
+				   Push();
 				 }
 				 break;
 			   }


Remove yet more dead code

Remove yet more dead code

--- moros/moros.ino
+++ moros/moros.ino
@@ -6,9 +6,7 @@
 #define cs_2   7
 #define dc_2   8
 #define rst_2  9
-#define btn_1 2
 #define btn_1_interrupt 0
-#define btn_2 3
 #define btn_2_interrupt 1

 #include <SPI.h>


Update mech.ino

Update mech.ino

--- mech/mech.ino
+++ mech/mech.ino
@@ -173,6 +173,7 @@
     }
     chanel->move(step);
     yeld();
+    dprintf("optimize() - [%d]: step=%d, P(n-1)=%d, P(n)=%d\n", stepCount, step, prevSetepPwr, rflPwrPercent);
     if (prevSetepPwr < (rflPwrPercent + hysteresis)) {
       step = -step;
       if (stepCount != 0) {
@@ -184,7 +185,7 @@
     prevSetepPwr = rflPwrPercent;
     stepCount++;
   }
-  dprintf("optimize() - finished in %d step(s), rflPwrPercent = %d\n", stepCount, rflPwrPercent);
+  dprintf("optimize() - finished in %d step(s), P(n)=%d\n", stepCount, rflPwrPercent);
 }

 void autoTune() {


Quick path fix so the example will compile in Build

Hey! You're going to get two of these file changes for the two examples. Added in the complete path so it'll work in Build, please accept the change and reimport the library!
Let me know if you have any problems,
Richard@Particle

--- firmware/examples/current_only/current_only.ino
+++ firmware/examples/current_only/current_only.ino
@@ -1,6 +1,6 @@
 // EmonLibrary examples openenergymonitor.org, Licence GNU GPL V3

-#include "EmonLib.h"                   // Include Emon Library
+#include "EmonLib/EmonLib.h"                   // Include Emon Library
 EnergyMonitor emon1;                   // Create an instance

 void setup()


Roll Control Updates

Roll Control Updates

roll control system works now

--- FlightCode/FlightCode.ino
+++ FlightCode/FlightCode.ino
@@ -61,7 +61,9 @@
 float baroAltBuffer[5] = {0, 0, 0, 0, 0};
 float gyroZBuffer[7] = {0, 0, 0, 0, 0, 0, 0}; //The other values are arbitrary; this one is used in Simpsons Rule, so it MUST BE ODD!
 float timeBuffer[7] = {0, 0, 0, 0, 0, 0, 0}; //Must equal the size of gyroZBuffer; used for the same calculations.
-
+float gyroZBuffer2[5] = {0, 0, 0, 0, 0};
+
+float gyroAverage;
 float accelAverage;
 float baroAverage; //Averages of the above buffer values

@@ -87,6 +89,8 @@
 const int CENTER = 1;
 const int LEFT = 2;
 int finPosition = CENTER; //Since the servo moves based on increments and not absolute positions, these constants and variable are needed to track the fins' position.
+long lastTime = 0; //Variable to keep track of the time between servo pulses
+

 bool servoPowerFlag = false;
 const int servoPowerPin = 5; //Flag and pin to power on/off the servo with a transistor
@@ -192,6 +196,16 @@
   digitalWrite(controlPin, HIGH);
   digitalWrite(servoPowerPin, HIGH);
   delay(100);
+
+  for(int c = 0; c < 5; c++) { //Initialize gyro average buffer beforehand because time is limited
+  sensors_event_t event;
+  gyro.getEvent(&event);
+  gyroData[0] = event.gyro.x;
+  gyroData[1] = event.gyro.y;
+  gyroData[2] = event.gyro.z;
+  gyroZBuffer2[c] = gyroData[2];
+  }
+
 }

@@ -307,7 +321,7 @@
 void Set_Servo(int current, int goal) { //Subroutine which takes current position and intended position and turns those into a servo output.
   //(I think this is more efficient/adaptive than writing the same thing out multiple times in Roll_Control()?

-  if (current != goal) { //Only run the fin-setting pulse and delay if motion is necessary
+  if (current != goal && millis() - lastTime > 500) { //Only run the fin-setting pulse and delay if motion is necessary
     if (abs(current - goal) == 2)
       digitalWrite(statePinB, HIGH); //If moving from right to left, or vice-versa, pin B needs to be high.
     else
@@ -318,11 +332,14 @@
     else//Otherwise, we are rotating from left to right: clockwise: negative, so A should be high
       digitalWrite(statePinA, HIGH);

+    delay(25);
+
     digitalWrite(controlPin, LOW); //Once the output pins have been set properly, pulse the control pin to update the servo.
     delay(7);
     digitalWrite(controlPin, HIGH);

     finPosition = goal; //Update the fin state tracking variable
+    lastTime = millis();
   }

 }
@@ -602,41 +619,53 @@
   baroAverage /= 5;
   baroAverage = baroAverage - startAlt; //Have to compare the average to the ground, not sea level

-  if (flightState == burnout && !endRollFlag) { //Keep track of rotations once we transition to the burnout stage
-    /*
-       This section functions stepwise. Once the two buffers are full, the algorithm performs numerical
-       integration, increments rollCounter, and flushes the buffers before starting over.
-    */
-    if (timeBuffer[6] < 1) { //If the buffers are not yet full; avoiding == 0 because it's a floating point
-
-      for (int c = 0; c < 6; c++) {
-        timeBuffer[6 - c] = timeBuffer[5 - c];
-        gyroZBuffer[6 - c] = gyroZBuffer[5 - c];
-      }
-      timeBuffer[0] = millis();
-      gyroZBuffer[0] = gyroData[2] - GYRO_DRIFT_FACTOR; //Again, this buffer should be up-to-date
-
-    }
-
-    else { //Once the buffers are full, perform the integration!
-
-      float deltaT = (timeBuffer[0] - timeBuffer[6]) / 18; //Note: the average is technically /6, but since Simpson's Rule adds a /3 anyways, it's just more efficient to combine them
-      float simpsonSum = gyroZBuffer[0] + gyroZBuffer[6];
-      simpsonSum = simpsonSum + 4 * (gyroZBuffer[1] + gyroZBuffer[3] + gyroZBuffer[5]);
-      simpsonSum = simpsonSum + 2 * (gyroZBuffer[2] + gyroZBuffer[4]);
-      simpsonSum = simpsonSum * deltaT / 1000; //Hooray for numerical integration! Should look into whether there's a more efficient way to perform Simpson's rule here.
-
-      rotationCounter = rotationCounter + (simpsonSum / 6.28318531) * SIMPSON_SCALE_FACTOR; //Convert from radians to revolutions and increment the counter!
-
-      for (int c = 0; c < 7; c++) {
-        timeBuffer[c] = 0;
-        gyroZBuffer[c] = 0; //Don't forget to clear the buffers for the next step!
-      }
-
-    }
-
-  }
-
+  if (flightState == burnout) { //Keep track of rotations once we transition to the burnout stage
+    if (!endRollFlag) {
+      /*
+         This section functions stepwise. Once the two buffers are full, the algorithm performs numerical
+         integration, increments rollCounter, and flushes the buffers before starting over.
+      */
+      if (timeBuffer[6] < 1) { //If the buffers are not yet full; avoiding == 0 because it's a floating point
+
+        for (int c = 0; c < 6; c++) {
+          timeBuffer[6 - c] = timeBuffer[5 - c];
+          gyroZBuffer[6 - c] = gyroZBuffer[5 - c];
+        }
+        timeBuffer[0] = millis();
+        gyroZBuffer[0] = gyroData[2] - GYRO_DRIFT_FACTOR; //Again, this buffer should be up-to-date
+
+      }
+
+      else { //Once the buffers are full, perform the integration!
+
+        float deltaT = (timeBuffer[0] - timeBuffer[6]) / 18; //Note: the average is technically /6, but since Simpson's Rule adds a /3 anyways, it's just more efficient to combine them
+        float simpsonSum = gyroZBuffer[0] + gyroZBuffer[6];
+        simpsonSum = simpsonSum + 4 * (gyroZBuffer[1] + gyroZBuffer[3] + gyroZBuffer[5]);
+        simpsonSum = simpsonSum + 2 * (gyroZBuffer[2] + gyroZBuffer[4]);
+        simpsonSum = simpsonSum * deltaT / 1000; //Hooray for numerical integration! Should look into whether there's a more efficient way to perform Simpson's rule here.
+
+        rotationCounter = rotationCounter + (simpsonSum / 6.28318531) * SIMPSON_SCALE_FACTOR; //Convert from radians to revolutions and increment the counter!
+
+        for (int c = 0; c < 7; c++) {
+          timeBuffer[c] = 0;
+          gyroZBuffer[c] = 0; //Don't forget to clear the buffers for the next step!
+        }
+
+      }
+    }
+    else {
+      gyroAverage = 0;
+
+      for (int c = 0; c < 4; c++) {
+        gyroZBuffer2[4 - c] = gyroZBuffer2[3 - c];
+      }
+      gyroZBuffer2[0] = gyroData[2];
+
+      for (int c = 0; c < 5; c++) {
+        gyroAverage = gyroAverage + gyroZBuffer2[c];
+      }
+      gyroAverage /= 5;
+    }
+  }
 }

-


Added new line, removed struct.

Added new line, removed struct.

--- arduino/Led_Strip/Steppers.ino
+++ arduino/Led_Strip/Steppers.ino
@@ -15,16 +15,6 @@
 };

 Stepper steppers[AMOUNTSTEPPERS];
-
-typedef struct Steps Steps;
-
-struct Steps {
-  int steps;
-  boolean down;
-  boolean finished;
-};
-
-Steps steps[AMOUNTSTEPPERS];

 void setupSteppers(){
   //set how the steppers are connected //TODO add other steppers
@@ -84,10 +74,6 @@
   }
 }

-void rotateMultiple(int []){
-
-}
-
 void calib(int stepper){ //Set the Steppermotor to bottom most position
   for(int i = 0; i < MAXHEIGHTINSTEPS * 1.2; i++){
     if(!bottom(stepper)){
@@ -128,6 +114,7 @@
   }
 }

+<<<<<<< HEAD
 void setHeigthMultiple(int numbers[6][3]){
   Steps steps[AMOUNTSTEPPERS];
   for(int i = 0; i < AMOUNTSTEPPERS; i++){ //calculate the amount of steps all steppers have to move
@@ -280,8 +267,10 @@

-
-
-
-
-
+=======
+>>>>>>> parent of c03b88a... added setting of height multiple continents
+
+
+
+
+


Cleaning code

Cleaning code

--- T0/src/main.ino
+++ T0/src/main.ino
@@ -25,9 +25,7 @@
 AFELED Led;
 AFESwitch Switch;
 AFESwitch ExternalSwitch;
-
 AFERelay Relay;
-
 MQTT MQTTConfiguration;

 void setup() {


select_turn() implementiert

select_turn() implementiert

--- MazeSolver/MazeSolver.ino
+++ MazeSolver/MazeSolver.ino
@@ -293,3 +293,18 @@
 //		turn(dir);
 //		//TODO End of the maze
 //	}
+
+char select_turn(unsigned char found_left, unsigned char found_straight, unsigned char found_right)
+{
+	// Make a decision about how to turn.  The following code
+	// implements a left-hand-on-the-wall strategy, where we always
+	// turn as far to the left as possible.
+	if (found_left)
+		return 'L';
+	else if (found_straight)
+		return 'S';
+	else if (found_right)
+		return 'R';
+	else
+		return 'B';
+} // end select_turn


pointer refactoring in progress

pointer refactoring in progress

--- lightbright/LightBrightMain/LightBrightMain.ino
+++ lightbright/LightBrightMain/LightBrightMain.ino
@@ -15,10 +15,10 @@
 #define LOGLEVEL LOG_LEVEL_DEBUG

 // Globals
-int a;
-
 Channel digitalChannels[LBPIN_DOUT_COUNT];
 DigitalOutPin digitalPins[LBPIN_DOUT_COUNT];
+
+DigitalOutPin *dpins;

 #ifdef LBC_KEYBOARD
 KeyboardHandler keyboardHandler;
@@ -34,8 +34,14 @@
   for (int x = 0; x < LBPIN_DOUT_COUNT; x++) {
     digitalPins[x].begin(LBPIN_DOUT_START + (x * LBPIN_DOUT_INTERVAL));
     digitalChannels[x].begin(&digitalPins[x], x+1);
-    Log.Info("Initialized digital channel %d to pin %d"CR, digitalChannels[x].getNumber(), (*digitalChannels[x].getPin()).getPinNumber());
+    Log.Info("Initialized digital channel %d to pin %d"CR, digitalChannels[x].getNumber(), digitalChannels[x].getPin()->getPinNumber());
   }
+
+  // example code to be removed
+  dpins = digitalPins;
+  int dpinm = digitalPins[3].getPinNumber();
+  int dpinn = dpins[3].getPinNumber();
+

 #ifdef LBC_KEYBOARD
   keyboardHandler.begin(digitalChannels);


Timer interface tested and working

Timer interface tested and working

--- Valokepakko.ino
+++ Valokepakko.ino
@@ -19,9 +19,9 @@
 /*                                                  */
 /* Uncomment only ONE line at a time.               */
 /****************************************************/
-/* #define TIMER; */
-#define TILT;
-/* #define WHEEL; */
+#define TIMER
+/* #define TILT */
+/* #define WHEEL */

 const int LED_PIN = 6;

@@ -32,6 +32,7 @@

 const int LEDS = 60;
 const int TIMEFRAME = 500;
+
 // Parameter 1 = number of pixels in strip
 // Parameter 2 = Arduino pin number (most are valid)
 // Parameter 3 = pixel type flags, add together as needed:
@@ -83,15 +84,14 @@
   }
   return strip.Color(rgb.r, rgb.g, rgb.b);
 }
-//Lookup the pixel's color for the timer based interface.
- uint32_t timerColorLookup(int led, int index) {
-    int x = mapfloat(led, 0.0, float(LEDS), index, float(IMAGE_WIDTH-1));
-    int y = led;
-    int pixelIndex = x + led * IMAGE_WIDTH;
-    }
-    return lookUpColor(pixelIndex)
+
+// Lookup the pixel's color for the timer based interface.
+uint32_t timerColorLookup(int led, int frame) {
+  int pixelIndex = frame % IMAGE_WIDTH + led * IMAGE_WIDTH;
+  return lookupColor(pixelIndex);
 }
-  // Lookup the pixel's color for the tilt based interface.
+
+// Lookup the pixel's color for the tilt based interface.
 uint32_t tiltColorLookup(int led, float angle) {
     const float originX = IMAGE_WIDTH / 2;
     const float originY = IMAGE_HEIGHT - 1;
@@ -122,35 +122,44 @@
     return lookupColor(pixelIndex);
 }

+// Last tick for the timer based interface.
+unsigned long lastTick = 0;
+
+// The frame (column) being shown for the timer based interface.
+int frame = 0;
+
 void loop() {
   /**********************/
   /* Accelerometer code */
   /**********************/

-  // variables to read the pulse widths:
-  int pulseX, pulseY;
-  float angle;
-
-  pulseX = pulseIn(ACCEL_X_PIN, HIGH);
-  pulseY = pulseIn(ACCEL_Y_PIN, HIGH);
-  angle = atan2(pulseX-NO_TILT, pulseY-NO_TILT);
+  int pulseX = pulseIn(ACCEL_X_PIN, HIGH);
+  int pulseY = pulseIn(ACCEL_Y_PIN, HIGH);
+  float angle = atan2(pulseX-NO_TILT, pulseY-NO_TILT);

   /******************/
   /* LED strip code */
   /******************/

+#ifdef TIMER
+  unsigned long time = millis();
+  if (time - lastTick > TIMEFRAME) {
+    frame++;
+    lastTick = time;
+  }
+#endif /* TIMER */
+
   for (int led = 0; led < LEDS; led++) {
     uint32_t c;

 #ifdef TIMER
-    int i = 0;
-    c = timer.setInterval(TIMEFRAME, timerColorLookup(led, i++));
-    noLoop();
+    c = timerColorLookup(led, frame);
+#endif /* TIMER */

-#endif /* TIMER */
 #ifdef TILT
     c = tiltColorLookup(led, angle);
 #endif /* TILT */
+
 #ifdef WHEEL
     c = wheelColorLookup(led, angle);
 #endif /* WHEEL */


example work

example work

--- examples/Advanced/Advanced.ino
+++ examples/Advanced/Advanced.ino
@@ -24,7 +24,8 @@
   wm.addParameter(&custom_field);

   // custom menu via array or vector
-  // menu tokens, "wifi","wifinoscan","info","param","close","sep","erase","restart","exit"
+  //
+  // menu tokens, "wifi","wifinoscan","info","param","close","sep","erase","restart","exit" (sep is seperator) (if param is in menu, params will not show up in wifi page!)
   // const char* menu[] = {"wifi","info","param","sep","restart","exit"};
   // wm.setMenu(menu,6);
   std::vector<const char *> menu = {"wifi","info","param","sep","restart","exit"};
@@ -41,14 +42,16 @@

   // wifi scan settings
   // wm.setRemoveDuplicateAPs(false); // do not remove duplicate ap names (true)
-  // wm.setMinimumSignalQuality(20);  // set min RSSI to show in scans, null = 8%
+  // wm.setMinimumSignalQuality(20);  // set min RSSI (percentage) to show in scans, null = 8%
   // wm.setShowInfoErase(false);      // do not show erase button on info page
   // wm.setScanDispPerc(true);       // show RSSI as percentage not graph icons
+
+  // wm.setBreakAfterConfig(true);   // always exit configportal even if wifi save fails

   bool res;
   // res = wm.autoConnect(); // auto generated AP name from chipid
   // res = wm.autoConnect("AutoConnectAP"); // anonymous ap
-  res = wm.autoConnect("AutoConnectAP"); // password protected ap
+  res = wm.autoConnect("AutoConnectAP","password"); // password protected ap

   if(!res) {
     Serial.println("Failed to connect or hit timeout");
@@ -59,7 +62,6 @@
   }
 }

-
 void loop() {
   // check for button press
   if ( digitalRead(TRIGGER_PIN) == LOW ) {
@@ -69,11 +71,13 @@

     delay(3000); // reset timer
     if( digitalRead(TRIGGER_PIN) == LOW ){
+      Serial.println("Erasing Config");
       // holding button 3000 ms, reset settings
       wm.resetSettings();
       ESP.restart();
     }

+    Serial.println("Starting config portal");
     wm.setConfigPortalTimeout(120);

     if (!wm.startConfigPortal("OnDemandAP")) {


Remove superfluous serial setup

Remove superfluous serial setup

--- Programmer/Programmer.ino
+++ Programmer/Programmer.ino
@@ -246,10 +246,6 @@
 }

 void read_infopage() {
-  // start serial port:
-  Serial.begin(57600);
-  Serial.setTimeout(3000);
-
   progSetup();

   Serial.println("READY");
@@ -285,10 +281,6 @@
 }

 void read_mainpage() {
-  // start serial port:
-  Serial.begin(57600);
-  Serial.setTimeout(3000);
-
   progSetup();

   Serial.println("READY");
@@ -345,10 +337,6 @@
 };

 void restore_infopage() {
-  // start serial port:
-  Serial.begin(57600);
-  Serial.setTimeout(3000);
-
   progSetup();

   Serial.println("READY");


add button debounce

add button debounce

--- arduino/standing-desk-timer/standing-desk-timer.ino
+++ arduino/standing-desk-timer/standing-desk-timer.ino
@@ -36,44 +36,73 @@
 unsigned long goalTime = 0;
 unsigned long startedSettingTimeGoalMillis = 0;

+int lastIncrState = HIGH;
+int lastDecrState = HIGH;
+
+unsigned long debounceDelay = 500;
+unsigned long lastDebounceTimeIncr = 0;
+unsigned long lastDebounceTimeDecr = 0;
+
 SoftwareSerial s7s(SOFTWARE_RX, SOFTWARE_TX);

 void setup() {
-  State state = COUNTING_DOWN;
+  s7s.begin(9600);
+  s7s.write(0x76); // clear display

-  s7s.begin(9600);
-  s7s.write(0x76);  // Clear display
   s7s.write(0x77);
-  s7s.write(1<<COLON);
+  s7s.write(1<<COLON); // enable colon

   q.setup();
   pinMode(INPUT_PIN_INCR, INPUT_PULLUP);
   pinMode(INPUT_PIN_DECR, INPUT_PULLUP);

   timeGoalMinutes = EEPROM.read(timerGoalAddr);
-  timeGoalMinutes = 1;
   goalTime = millis() + (timeGoalMinutes * 1000L * 60);
 }

 void readGoalAdjustment() {
   int incrVal = digitalRead(INPUT_PIN_INCR);
-  int decrVal = digitalRead(INPUT_PIN_DECR);
-  if (incrVal == HIGH || decrVal == HIGH) {
-    q.setRGB(PURPLE);
-  }
-  if (incrVal == LOW || decrVal == LOW) {
-    state = SETTING_TIME_GOAL;
-    startedSettingTimeGoalMillis = millis();
-    q.setRGB(YELLOW);
+
+  if (incrVal != lastIncrState) {
+    lastDebounceTimeIncr = millis();
   }

-  if (incrVal == LOW) {
-    timeGoalMinutes++;
+  if ((millis() - lastDebounceTimeIncr) > debounceDelay) {
+    lastIncrState = incrVal;
+
+    if (incrVal == LOW) {
+      q.setRGB(YELLOW);
+      timeGoalMinutes++;
+      state = SETTING_TIME_GOAL;
+      startedSettingTimeGoalMillis = millis();
+      lastDebounceTimeIncr = millis();
+    } else {
+      q.setRGB(PURPLE);
+    }
   }

-  if (decrVal == LOW) {
-    timeGoalMinutes--;
+  lastIncrState = incrVal;
+
+  int decrVal = digitalRead(INPUT_PIN_DECR);
+  if (decrVal != lastDecrState) {
+    lastDebounceTimeDecr = millis();
   }
+
+  if ((millis() - lastDebounceTimeDecr) > debounceDelay) {
+    lastDecrState = decrVal;
+
+    if (decrVal == LOW) {
+      q.setRGB(YELLOW);
+      timeGoalMinutes--;
+      state = SETTING_TIME_GOAL;
+      startedSettingTimeGoalMillis = millis();
+      lastDebounceTimeDecr = millis();
+    } else {
+      q.setRGB(PURPLE);
+    }
+  }
+
+  lastDecrState = decrVal;

   EEPROM.write(timerGoalAddr, timeGoalMinutes);
 }
@@ -82,8 +111,8 @@
   unsigned long timeLeftMillis = goalTime - millis();

   if (millis() > goalTime) {
-    goalTime = millis() + (timeGoalMinutes * 1000L * 60);
-    timeLeftMillis = goalTime;
+    state = AT_ZERO;
+    return;
   }

@@ -96,8 +125,17 @@

 }

+void resetTime() {
+  goalTime = millis() + (timeGoalMinutes * 1000L * 60);
+}
+
 void displayTimeGoal() {
   sprintf(tempString, "%4d", timeGoalMinutes);
+  s7s.print(tempString);
+}
+
+void displayDashes() {
+  sprintf(tempString, "----");
   s7s.print(tempString);
 }

@@ -120,6 +158,9 @@
       break;

     case AT_ZERO:
+      displayDashes();
+      resetTime();
+      state = COUNTING_DOWN;
       break;

     default:


Working amplifiers gain settings.

Working amplifiers gain settings.

--- arduino_sketches/PGA309/testPin_I2C/testPin_I2C.ino
+++ arduino_sketches/PGA309/testPin_I2C/testPin_I2C.ino
@@ -3,7 +3,7 @@

 #define PGA309ADDR 0x40
 #define REG3 0x0500
-#define REG4 0x8000
+#define REG4 0xE300
 #define REG6 0x0600

 PGA309 pga(PGA309ADDR);