Start of 'Animation' class concept

Start of 'Animation' class concept

Add an 'Animation' pure abstract class that defines the contract of an animation
implementation. Add a sample 'Pulse' concrete implementation. Demonstrate usage
of this framework when owner is 'Enlightened'.

--- MagnusCoreNeoPixel_v1.ino
+++ MagnusCoreNeoPixel_v1.ino
@@ -4,6 +4,11 @@

 // first communication pin for neo pixel string
 #define BASE_PIN 2
+
+#define NUM_STRINGS 1 // one for each resonator
+//#define NUM_STRINGS 8 // one for each resonator
+
+const uint16_t LEDS_PER_STRAND = 50;

 enum Direction { NORTH = 0, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST };
 enum Ownership {  neutral = 0, enlightened, resistance };
@@ -13,9 +18,62 @@
   uint32_t timing;
 };

-#define NUM_STRINGS 1 // one for each resonator
-//#define NUM_STRINGS 8 // one for each resonator
-
+// Animation State
+
+struct PulseState {
+    unsigned long startTime;
+};
+
+union AnimationState {
+    PulseState pulse;
+};
+
+// Contract of animation implemnations
+class Animation {
+    public:
+        virtual void init(AnimationState& state) = 0;
+        virtual void doFrame(AnimationState& state, Adafruit_NeoPixel& strip) =0;
+};
+
+// Animation implemntations
+
+class Pulse : public Animation {
+    public:
+        // Initialize state to animation start point
+        virtual void init(AnimationState& state) override {
+            state.pulse.startTime = millis();
+        }
+
+        // Draw a new frame of the animation
+        virtual void doFrame(AnimationState& state, Adafruit_NeoPixel& strip) override {
+            unsigned long phase = (millis() - state.pulse.startTime) % AnimationDuration; // In ms
+            uint16_t startPixel = phase * PixelsPerMs;
+            Serial.print("Start pixel: "); Serial.println(startPixel, DEC);
+            for (uint16_t i = 0; i < LEDS_PER_STRAND; i++) {
+                if (i >= startPixel && i < startPixel + PulseLength) {
+                    strip.setPixelColor(i, 0, 0xff, 0);
+                } else {
+                    strip.setPixelColor(i, 0, 0, 0);
+                }
+            }
+            strip.show();
+        }
+
+    private:
+        const unsigned long AnimationDuration = 4000l; // ms
+        const uint16_t PulseLength = LEDS_PER_STRAND / 8;
+        const float PixelsPerMs = (float) LEDS_PER_STRAND / AnimationDuration;
+};
+
+// Collection of all supported animations
+struct Animations {
+    Pulse pulse;
+};
+
+// Static animation implementations singleton
+Animations animations;
+
+AnimationState states[NUM_STRINGS];

 pixel_string strings[NUM_STRINGS];

@@ -28,7 +86,7 @@
 //   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
 //   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
 //Adafruit_NeoPixel strip = Adafruit_NeoPixel(120, BASE_PIN, NEO_RGBW + NEO_KHZ800);
-Adafruit_NeoPixel strip = Adafruit_NeoPixel(50, BASE_PIN, NEO_GRB + NEO_KHZ800);
+Adafruit_NeoPixel strip = Adafruit_NeoPixel(50, BASE_PIN, NEO_RGB + NEO_KHZ800);

 // Serial I/O
@@ -113,6 +171,7 @@
     {
       owner = enlightened;
       percent = getPercent(&command[1]);
+      animations.pulse.init(states[0]);
     }
     else if( command[0] == 'r' || command[0] == 'R' )
     {
@@ -136,6 +195,7 @@

     uint8_t red, green, blue, white;
     red = 0x20; green = 0; blue = 0x20; white = 0x20;
+    bool useAnimations = false;
     if( owner == neutral )
     {
       red = 0x40; green = 0x40; blue = 0x40; white = 0x40;
@@ -148,19 +208,26 @@
     else if( owner == enlightened )
     {
       red = 0x1f; green = 0xff; blue = 0; white = 0;
+      useAnimations = true;
     }

-    for(i=0; i < strip.numPixels(); i++)
-    {
-        //strip.setPixelColor(i, green,blue,red); // for RGB order is funny?
-//        strip.setPixelColor(i, green, red, blue,white);
-        strip.setPixelColor(i, green, red, blue);
-        float scale = ((millis()/100)%100)/200.0 + 0.5;
-        float pct = percent * scale;
-//        Serial.print("Percent: "); Serial.println(pct, 4);
-        strip.setBrightness((uint8_t)((uint16_t)(255*(pct/100.0))));
-    }
-    strip.show();
+    if (useAnimations) {
+        strip.setBrightness(255);
+        animations.pulse.doFrame(states[0], strip);
+    } else {
+        for(i=0; i < strip.numPixels(); i++)
+        {
+            //strip.setPixelColor(i, green,blue,red); // for RGB order is funny?
+            //        strip.setPixelColor(i, green, red, blue,white);
+            strip.setPixelColor(i, red, green, blue);
+            //        float scale = ((millis()/100)%100)/200.0 + 0.5;
+            float scale = 1.0f;
+            float pct = percent * scale;
+            //        Serial.print("Percent: "); Serial.println(pct, 4);
+            strip.setBrightness((uint8_t)((uint16_t)(255*(pct/100.0))));
+        }
+        strip.show();
+    }

     dir++;
     if( dir >= NUM_STRINGS )


COH-80: WIP

COH-80: WIP

--- Arduino/COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
+++ Arduino/COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
@@ -561,6 +561,8 @@
 #if !defined(ENABLE_OTSECUREFRAME_ENCODING_SUPPORT)
    // For non-secure, check that there enough bytes for expected (fixed) frame size.
    if(msglen < 8) { return; } // Too short to be useful, so ignore.
+   const uint8_t *cleartextBody = msg;
+   const uint8_t cleartextBodyLen = msglen;
 #else
   // For length-first OpenTRV secureable-frame format, validate structure of header/frame first.
   // This is quick and checks for insane/dangerous values throughout.
@@ -584,9 +586,8 @@
   // Buffer for receiving secure frame body.
   // (Non-secure frame bodies should be read directly from the frame buffer.)
   uint8_t secBodyBuf[OTRadioLink::ENC_BODY_SMALL_FIXED_PTEXT_MAX_SIZE];
+  // Body length after any decryption, etc.
   uint8_t decryptedBodyOutSize = 0;
-  // Body length after any decryption, etc.
-  uint8_t receivedBodyLength;
   // Check that there is an association/key for the inbound message.
   uint8_t senderNodeID[OTV0P2BASE::OpenTRV_Node_ID_Bytes];
   // Look up full ID in associations table,
@@ -611,6 +612,8 @@
 #endif
     return; // FAIL
     }
+   const uint8_t *cleartextBody = secBodyBuf;
+   const uint8_t cleartextBodyLen = decryptedBodyOutSize;
 #endif // ENABLE_OTSECUREFRAME_ENCODING_SUPPORT

   const uint8_t firstByte = msg[0];
@@ -652,10 +655,14 @@
 #ifdef ALLOW_CC1_SUPPORT_HUB
     // Handle poll-response message (at hub).
     // Dump onto serial to be seen by the attached host.
-    case OTRadioLink::FTp2_CC1PollResponse:
+#if !defined(ENABLE_OTSECUREFRAME_ENCODING_SUPPORT)
+    case OTRadioLink::FTp2_CC1PollResponse: // Non-secure.
+#else
+    case 0x80 | OTRadioLink::FTp2_CC1PollResponse: // Secure.
+#endif // !defined(ENABLE_OTSECUREFRAME_ENCODING_SUPPORT)
       {
       OTProtocolCC::CC1PollResponse a;
-      a.OTProtocolCC::CC1PollResponse::decodeSimple(msg, msglen);
+      a.OTProtocolCC::CC1PollResponse::decodeSimple(cleartextBody, cleartextBodyLen);
       // After decode instance should be valid and with correct (source) house code.
       if(a.isValid())
         {
@@ -693,10 +700,14 @@
     // Handle poll/cmd message (at relay).
     // IFF this message is addressed to this (target) unit's house code
     // then action the commands and respond (quickly) with a poll response.
-    case OTRadioLink::FTp2_CC1PollAndCmd:
+#if !defined(ENABLE_OTSECUREFRAME_ENCODING_SUPPORT)
+    case OTRadioLink::FTp2_CC1PollAndCmd: // Non-secure.
+#else
+    case 0x80 | OTRadioLink::FTp2_CC1PollAndCmd: // Secure.
+#endif // !defined(ENABLE_OTSECUREFRAME_ENCODING_SUPPORT)
       {
       OTProtocolCC::CC1PollAndCommand c;
-      c.OTProtocolCC::CC1PollAndCommand::decodeSimple(msg, msglen);
+      c.OTProtocolCC::CC1PollAndCommand::decodeSimple(cleartextBody, cleartextBodyLen);
       // After decode instance should be valid and with correct house code.
       if(c.isValid())
         {
@@ -746,18 +757,12 @@
             { OTV0P2BASE::serialPrintlnAndFlush(F("!TX key")); return; } // FAIL
           const OTRadioLink::SimpleSecureFrame32or0BodyTXBase::fixed32BTextSize12BNonce16BTagSimpleEnc_ptr_t e = OTAESGCM::fixed32BTextSize12BNonce16BTagSimpleEnc_DEFAULT_STATELESS;
           uint8_t buf[OTRadioLink::SecurableFrameHeader::maxSmallFrameSize];
-
-
-
-
-// FIXME FIXME FIXME
-
-
-
-
-
-
-          OTV0P2BASE::serialPrintlnAndFlush(F("!TX not impl")); // FAIL
+          const uint8_t sbodylen = secureTXState.generateSecureOStyleFrameForTX(buf, sizeof(buf), OTRadioLink::FTS_RESERVED_A, lenTXID, txbuf, bodylen, e, NULL, key);
+          const bool success = (0 != sbodylen) && PrimaryRadio.sendRaw(buf+1, bodylen-1);
+#if 1 && defined(DEBUG)
+          if(!success) { OTV0P2BASE::serialPrintlnAndFlush(F("!TX A")); }
+          else { OTV0P2BASE::serialPrintlnAndFlush(F("TX A")); }
+#endif
 #endif // !defined(ENABLE_OTSECUREFRAME_ENCODING_SUPPORT)
           }
         }
@@ -852,7 +857,7 @@
       oldDropped = dropped;
       }
 #endif
-#if 1 && defined(DEBUG) && !defined(ENABLE_TRIMMED_MEMORY)
+#if 0 && defined(DEBUG) && !defined(ENABLE_TRIMMED_MEMORY)
     // Filtered out messages are not an error.
     const uint8_t filtered = PrimaryRadio.getRXMsgsFilteredRecent();
     static uint8_t oldFiltered;
@@ -1144,19 +1149,13 @@
             { OTV0P2BASE::serialPrintlnAndFlush(F("!TX key")); return(false); } // FAIL
           const OTRadioLink::SimpleSecureFrame32or0BodyTXBase::fixed32BTextSize12BNonce16BTagSimpleEnc_ptr_t e = OTAESGCM::fixed32BTextSize12BNonce16BTagSimpleEnc_DEFAULT_STATELESS;
           uint8_t buf[OTRadioLink::SecurableFrameHeader::maxSmallFrameSize];
-
-
-
-
-
-// FIXME FIXME FIXME
-
-
-
-
-
-
-//          OTV0P2BASE::serialPrintlnAndFlush(F("!TX not impl")); // FAIL
+          const uint8_t sbodylen = secureTXState.generateSecureOStyleFrameForTX(buf, sizeof(buf), OTRadioLink::FTS_RESERVED_Q, lenTXID, txbuf, bodylen, e, NULL, key);
+          const bool success = (0 != sbodylen) && PrimaryRadio.sendRaw(buf+1, bodylen-1);
+#if 1 && defined(DEBUG)
+          if(!success) { OTV0P2BASE::serialPrintlnAndFlush(F("!TX Q")); }
+          else { OTV0P2BASE::serialPrintlnAndFlush(F("TX Q")); }
+#endif
+          if(success) { return(true); }
 #endif // !defined(ENABLE_OTSECUREFRAME_ENCODING_SUPPORT)
           // Fall-through is failure...
           OTV0P2BASE::serialPrintlnAndFlush(F("!TX fail"));


add timing.h.

add timing.h.

--- pomodoro/pomodoro.ino
+++ pomodoro/pomodoro.ino
@@ -1,5 +1,6 @@
 #include  <timestamp.h>
 #include  <debouncing.h>
+#include  <timing.h>

 #include  "logic.h"


Read incoming data as byte

Read incoming data as byte

Signed-off-by: Mark Knoop <f1b5a91d4d6ad523f2610114591c007e75d15084@markknoop.com>

--- src/sketch.ino
+++ src/sketch.ino
@@ -33,25 +33,26 @@
 #define rRecentre      10
 #define rNoRecentre    11
 #define rSetDuration   12
+#define rReset         13
 #define rDurlength      5
 #define rLength        12
 /*
  * ranges:
-    13-20  tests
     21-39  set halfturns
     40-112 set startpitch
    120-192 set endpitch
+   203-209 tests
  */

 char serialIncoming[rLength];
 char newDuration[rDurlength];
-int halfTurns         = 1;
-unsigned int duration = 500;
-float startPitch      = 72;
-float endPitch        = 36;
-boolean dir           = true;
-boolean recentre      = true;
-boolean newData       = false;
+int halfTurns;
+unsigned int duration;
+float startPitch;
+float endPitch;
+boolean dir;
+boolean recentre;
+boolean newData = false;

 void setup() {
     pinMode(LED_BUILTIN, OUTPUT);
@@ -61,8 +62,17 @@
     digitalWrite(dirPin, HIGH);
     Serial.begin(9600);
     findsensor(maxPulse);
-    //Serial.write(sReady);
-    Serial.println("arduino ready");
+    defaults();
+    Serial.write(sReady);
+}
+
+void defaults() {
+    halfTurns = 1;
+    duration = 500;
+    startPitch = 72;
+    endPitch = 36;
+    dir = true;
+    recentre = true;
 }

 int pitchToPulse(float pitch) {
@@ -316,60 +326,67 @@
         Serial.println(recentre, BIN);
     } else {
         // show test styles
-        Serial.println("13: 0x0d: turn");
-        Serial.println("14: 0x0e: gliss");
-        Serial.println("15: 0x0f: timedturn");
-        Serial.println("16: 0x10: durationturn");
-        Serial.println("17: 0x11: durationgliss");
-        Serial.println("18: 0x12: scale");
-        Serial.println("19: 0x13: show settings");
+        Serial.println("203: 0xcb: turn");
+        Serial.println("204: 0xcc: gliss");
+        Serial.println("205: 0xcd: timedturn");
+        Serial.println("206: 0xce: durationturn");
+        Serial.println("207: 0xcf: durationgliss");
+        Serial.println("208: 0xd0: scale");
+        Serial.println("209: 0xd1: show settings");
     }
     delay(333);
 }

 void processdata() {
     for (byte i=0; i<rLength; i++) {
-        if (serialIncoming[i] == rEOM) {
+        byte data = serialIncoming[i];
+        if (data == rEOM) {
             newData = false;
             return;
-        } else if (serialIncoming[i] == rQuery) {
+        } else if (data == rQuery) {
             findsensor(maxPulse);
-            //Serial.write(sReady);
-            Serial.println("arduino ready");
+            Serial.write(sReady);
             flashled();
-        } else if (serialIncoming[i] == rTurn) {
+        } else if (data == rTurn) {
             turn(halfTurns, startPitch, dir);
-        } else if (serialIncoming[i] == rGliss) {
+        } else if (data == rGliss) {
             gliss(halfTurns, startPitch, endPitch, dir);
-        } else if (serialIncoming[i] == rTimedTurn) {
+        } else if (data == rTimedTurn) {
             timedturn(halfTurns, duration, dir);
-        } else if (serialIncoming[i] == rDurationTurn) {
+        } else if (data == rDurationTurn) {
             durationturn(duration, startPitch, dir, recentre);
-        } else if (serialIncoming[i] == rDurationGliss) {
+        } else if (data == rDurationGliss) {
             durationgliss(duration, startPitch, endPitch, dir, recentre);
-        } else if (serialIncoming[i] == rForwards) {
+        } else if (data == rForwards) {
             dir = true;
-        } else if (serialIncoming[i] == rBackwards) {
+        } else if (data == rBackwards) {
             dir = false;
-        } else if (serialIncoming[i] == rRecentre) {
+        } else if (data == rRecentre) {
             recentre = true;
-        } else if (serialIncoming[i] == rNoRecentre) {
+        } else if (data == rNoRecentre) {
             recentre = false;
-        } else if (serialIncoming[i] == rSetDuration) {
+        } else if (data == rSetDuration) {
             for (byte d=0; d<rDurlength; d++) {
                 newDuration[d] = serialIncoming[++i];
             }
             duration = atoi(newDuration);
-        } else if (serialIncoming[i] < 21) {
-            test(serialIncoming[i] - 13);
-        } else if (serialIncoming[i] < 40) {
-            halfTurns = serialIncoming[i] - 20;
-        } else if (serialIncoming[i] < 112) {
-            startPitch = pitchbyteToMidi(serialIncoming[i] - 40);
-        } else if (serialIncoming[i] < 120) {
+        } else if (data == rReset) {
+            defaults();
+        } else if (data < 21) {
             true;
-        } else if (serialIncoming[i] < 192) {
-            endPitch = pitchbyteToMidi(serialIncoming[i] - 120);
+        } else if (data < 40) {
+            halfTurns = data - 20;
+        } else if (data < 113) {
+            startPitch = pitchbyteToMidi(data - 40);
+        } else if (data < 120) {
+            true;
+        } else if (data < 193) {
+            endPitch = pitchbyteToMidi(data - 120);
+        } else if (data < 203) {
+            true;
+        } else if (data < 210) {
+            test(data - 203);
+            flashled();
         }
     }
 }


Add control of second motor

Add control of second motor

--- Arduino/AK60-6/AK60-6.ino
+++ Arduino/AK60-6/AK60-6.ino
@@ -44,6 +44,8 @@
   }
   setZero(0x01);
   setMotormode(0x01);
+  setZero(0x02);
+  setMotormode(0x02);

   //exitMotormode(0x01);

@@ -56,8 +58,9 @@

 void loop() {
   float angle = servo.getAngle();  // get angle of servo (0 - 180)
-  readCAN();
-  bool positionControl = false;
+  readCAN(0x01);
+  readCAN(0x02);
+  bool positionControl = true;
   float torque_extinction_ratio = 1;
   if (positionControl)
   {
@@ -66,6 +69,7 @@
     setpoint = setpoint + constrain(order-setpoint, -slew_rate * dt_ms/1000., slew_rate * dt_ms/1000.);

     setCommand(0x01, setpoint, 0.0, 25, 5, 0*setpoint);
+    setCommand(0x02, setpoint, 0.0, 25, 5, 0*setpoint);
   }
   else // torque control
   {
@@ -203,8 +207,9 @@
   return (int) ((x-x_min)*((float)((1<<bits)-1)/span));
 }

-void readCAN()
-{
+void readCAN(int id)
+{
+  //CAN.filter(id);
   int packetSize = CAN.parsePacket();

   if (packetSize)
@@ -230,15 +235,15 @@
   float p = uint_to_float(p_int, P_MIN, P_MAX, 16);
   float v = uint_to_float(v_int, V_MIN, V_MAX, 12);
   float i = uint_to_float(i_int, -T_MAX, T_MAX, 12);
-  if (id==1)
+//if (id==1)
   {
    position = p;

    float speed = v;
    torque = i;
-   Serial.print("position:"); Serial.print(position); Serial.print(", ");
-   Serial.print("speed:"); Serial.print(speed); Serial.print(", ");
-   Serial.print("intensity:"); Serial.print(torque); Serial.print(", ");
+   Serial.print("position");Serial.print(id);Serial.print(":"); Serial.print(position); Serial.print(", ");
+   Serial.print("speed");Serial.print(id);Serial.print(":"); Serial.print(speed); Serial.print(", ");
+   Serial.print("intensity");Serial.print(id);Serial.print(":"); Serial.print(torque); Serial.print(", ");
    }
  }


Integrate mic animation with triangle animation

--- Cymatic-Triangles/Mic.ino
+++ Cymatic-Triangles/Mic.ino
@@ -30,6 +30,11 @@
 Wisp wisp1(WISP_1_START_POS, BASE_TRAIL, BASE_BRIGHTNESS, WISP_1_HUE);
 Wisp wisp2(WISP_2_START_POS, BASE_TRAIL, BASE_BRIGHTNESS, WISP_2_HUE);

+/* Variables to be changed in the loop */
+int speed = BASE_SPEED; /* Speed of Wisps (as of now they share the speed globally) */
+int brightness_step = BASE_BRIGHTNESS_STEP; /* How much brightness is lost from one trail pixel to the next */
+int new_brightness; /* Temp variable for the new calculated brightness */
+
 void setupMic() {
   /* Instantiate FastLED */
   FastLED.addLeds<NEOPIXEL, MIC_DATA_PIN>(mic_leds, NUM_MIC_LEDS);
@@ -45,9 +50,6 @@

 void animateMic() {
   float peak = normalize((float)amp_sum_L);
-  int speed; /* Speed of Wisps (as of now they share the speed globally) */
-  int new_brightness; /* Temp variable for the new calculated brightness */
-  int brightness_step; /* How much brightness is lost from one trail pixel to the next */

   /* Calculate the new speed based on the peak value (it's between 0.0 and 1.0) */
   speed = BASE_SPEED - (int)(peak * (BASE_SPEED * 0.9));
@@ -66,7 +68,7 @@
     wisp2.set_brightness(new_brightness);
   }

-  /* Change the brightness step so that brightness of trail pixels doesn't go below 0 */
+  /* Change the brightness step so taht brightness of trail pixels doens't go below 0 */
   brightness_step = new_brightness / (NUM_MIC_LEDS / 1.5);

   /* If Wisps reach the end of the strip, start over at the beginning */


Update 3_System.ino

Update 3_System.ino

修正send_to_sigfox(), _bale2Hex()


Added Button Mode Functionality

Added Button Mode Functionality

--- GroundStationCode/GroundStationCode.ino
+++ GroundStationCode/GroundStationCode.ino
@@ -1,10 +1,11 @@
 /*
-   Notre Dame Rocket Team Roll Control Payload Ground Station Code V. 0.6.2
+   Notre Dame Rocket Team Roll Control Payload Ground Station Code V. 1.1.1
    Aidan McDonald, 2/8/17
    Kyle Miller, 2/2/17

    Most recent changes:
-   Changed the packet-processing code to match the flight code (v. 1.1.0)
+   Added Basic Display Mode Shifting for LCD, 0 keeps defaults based on flgiht
+   status, other modes force different LCD outputs (v. 1.1.1)

    To-dones:
    Basic radio transmit-receive architecture in place
@@ -74,6 +75,7 @@
 const int masterEnablePin = 0;
 const int finOverridePin = 1;
 const int servoPowerPin = 2; //Digital inputs for important flags- CHANGE THESE TO FIT REAL WORLD!!
+const int buttonPin = 3;

@@ -82,6 +84,7 @@
   pinMode(masterEnablePin, INPUT);
   pinMode(finOverridePin, INPUT);
   pinMode(servoPowerPin, INPUT);
+  pinMode(buttonPin, INPUT);
   pinMode(RFM95_RST, OUTPUT);
   digitalWrite(RFM95_RST, HIGH);

@@ -111,6 +114,19 @@

 void loop()
 {
+  int buttonState = 0;
+  if (digitalRead(buttonPin) == HIGH) {
+    if (buttonState == 4) {
+      buttonState = 0;
+    }
+    else {
+      buttonState++;
+    }
+  }
+  lcd.clear(); //Clear LCD to print new data
+  lcd.setCursor(0,15);
+  lcd.print(buttonState);
+

   if (sendFlag) { //Transmit select commands to the payload

@@ -164,6 +180,8 @@
     {
       sendFlag = true;
       lcd.clear(); //Clear the LCD since new data is incoming
+      lcd.setCursor(15,1);
+      lcd.print(buttonState);
       lcd.setCursor(0, 0); //Return cursor to the origin

       // Should be a message for us now
@@ -184,7 +202,7 @@
           lcd.print("ERR: Bad Header"); //42 in slot 4 is the header's backup validity check
         }

-        else if (buf[1] == 0) { //buf[1] is the sensor "sleep mode" flag
+        else if ((buf[1] == 0 && buttonState == 0) || (buttonState == 1)) { //buf[1] is the sensor "sleep mode" flag
           float batteryLevel;
           for (int c = 0; c < 4; c++) {
             u.tempBuff[c] = buf[c + 8];
@@ -198,7 +216,7 @@
           lcd.print("%");
         }

-        else if (buf[5] == true) { //buf[5] is the GPS enabled flag
+        else if ((buf[5] == true && buttonState == 0) || (buttonState == 2 && buf[5] == true)) { //buf[5] is the GPS enabled flag
           float latitude;
           float longitude;
           float altitude;
@@ -238,7 +256,7 @@
           }
         }

-        else if (flightState == burnout) { //This indicates we are in the roll-controll phase
+        else if ((flightState == burnout && buttonState == 0) || buttonState == 3) { //This indicates we are in the roll-controll phase or that we want flight status

           if (buf[8] == 0) { //This flag being false indicates the payload is still trying to complete its two revolutions, so completed revolutions are tracked
             float completedRevs;
@@ -250,7 +268,7 @@
             lcd.setCursor(0, 1);
             lcd.print(completedRevs, 7);
           }
-          else { //If the flag is true, rotational velocity is tracked
+          else if(buf[8] == 1) { //If the flag is true, rotational velocity is tracked
             int rotationVel;
             union { //Since we're receiving an integer, we need a different-sized memory union to work with
               int tempInt;
@@ -265,9 +283,25 @@
             lcd.setCursor(6, 1);
             lcd.print("rad/s");
           }
-        }
-
-        else { //If none of the other conditions are met, altitude data is transmitted
+          else {
+            switch (flightState) {
+              case 0:
+                lcd.print("Waiting");
+                break;
+              case 1:
+                lcd.print("Launched");
+                break;
+              case 3:
+                lcd.print("Falling");
+                break;
+              case 4:
+                lcd.print("Landed");
+                break;
+            }
+          }
+        }
+
+        else if (buttonState == 0 || buttonState == 4){ //If none of the other conditions are met, altitude data is transmitted
           float altitude;
           for (int c = 0; c < 4; c++) {
             u.tempBuff[c] = buf[c + 8];


Added simple button function

Added simple button function

--- ArduinoCode/FinalIntegration/FinalIntegration.ino
+++ ArduinoCode/FinalIntegration/FinalIntegration.ino
@@ -2,13 +2,13 @@

 /*
 * Read a card using a mfrc522 reader on your SPI interface
-* Pin layout should be as follows (on Arduino Uno):
-* MOSI: Pin 11 / ICSP-4
-* MISO: Pin 12 / ICSP-1
-* SCK: Pin 13 / ISCP-3
-* SS/SDA: Pin 10
-* RST: Pin 9
-*/
+ * Pin layout should be as follows (on Arduino Uno):
+ * MOSI: Pin 11 / ICSP-4
+ * MISO: Pin 12 / ICSP-1
+ * SCK: Pin 13 / ISCP-3
+ * SS/SDA: Pin 10
+ * RST: Pin 9
+ */

 #include <SPI.h>
 #include <RFID.h>
@@ -48,7 +48,7 @@
 unsigned long animation_time = millis();

 //LEDs setup
-Adafruit_NeoPixel strip = Adafruit_NeoPixel(30, LEDStrip, NEO_GRB + NEO_KHZ800);
+Adafruit_NeoPixel strip = Adafruit_NeoPixel(19, LEDStrip, NEO_GRB + NEO_KHZ800);

 //RFID variables
@@ -56,7 +56,8 @@

 int serNum[5];
 int test[][5] = {
-  {131,222,128,0,221}
+  {
+    131,222,128,0,221      }
 };

 bool access = false;
@@ -70,245 +71,156 @@

 void setup(){

-    Serial.begin(9600);               // starts serial monitor at 9600bps
-    SPI.begin();                      // starts SPI
-    rfid.init();                      // initialises RFID library
-    bluetooth.begin(115200);          // starts bluetooth at 115200
-    delay(100);                       // wait for bluetooth module to sed back command
-    bluetooth.println("U,9600,N");    // temporarily change the bps to 9600, no parity
-    bluetooth.begin(9600);            // starts bluetooth at 9600bps
-    tft.begin();                      // starts TFT screen
-    tft.setRotation(3);               // sets screen orientation to landscape with pins on left
-    tft.setTextSize(2);
+  Serial.begin(9600);               // starts serial monitor at 9600bps
+  SPI.begin();                      // starts SPI
+  rfid.init();                      // initialises RFID library
+  bluetooth.begin(115200);          // starts bluetooth at 115200
+  delay(100);                       // wait for bluetooth module to sed back command
+  bluetooth.println("U,9600,N");    // temporarily change the bps to 9600, no parity
+  bluetooth.begin(9600);            // starts bluetooth at 9600bps
+  tft.begin();                      // starts TFT screen
+  tft.setRotation(3);               // sets screen orientation to landscape with pins on left
+  tft.setTextSize(2);
+  loginDisplay();
+
+  //LED strip initialise
+  strip.begin();
+  strip.show();
+
+  colorWipe(strip.Color(0, 0, 0), 10); //off init
+
+
+  pinMode(speaker, OUTPUT);
+  tone(speaker,1000);
+  delay(100);
+  noTone(speaker);
+
+}
+
+void loop(){
+
+  //Display switch
+  switch(display_state) {
+  case 0: //Login/Idle animated screen
+
     loginDisplay();
+
+    if(digitalRead(BTN0) && digitalRead(BTN3)) { //Shorcut to main menu for debugging purposes
+      scanned_card = false;
+      display_state = 1;
+      screen_drawn = 0;
+    }
+
+    if(scanned_card) {
+      if(available_bt) {
+
+        if (read_bt() == "access1") { //Card is good
+          scanned_card = false;
+          display_state = 1;
+          screen_drawn = 0;
+        }
+        else {
+          tft.println("Sorry, no access");
+          scanned_card = false;
+          delay(1000);
+          screen_drawn = 0;
+        }
+
+      }
+    }
+    break;
+
+  case 1: //Main Display
+    homeDisplay();
+
+    //If buttons pressed move to corresponding screen
+    // Read buttons and send to bluetooth
+    if (digitalRead(BTN0)) { //Bill
+      display_state = 2;
+      screen_drawn = 0;
+    }
+    if (digitalRead(BTN1)) { //Bill
+      display_state = 3;
+      screen_drawn = 0;
+    }
+
+
+
+    break;
+
+  case 2: //Bill called
+    billDisplay();
+    break;

-    //LED strip initialise
-    strip.begin();
-    strip.show();
-
-    colorWipe(strip.Color(0, 0, 100), 10); //Blue init
-
-
-    pinMode(speaker, OUTPUT);
-    tone(speaker,1000);
-    delay(100);
-    noTone(speaker);
-
-}
-
-void loop(){
-
-    //Display switch
-    switch(display_state) {
-      case 0:
-
-      loginDisplay();
-
-
-        if(scanned_card) {
-          if(available_bt) {
-
-            //screen_drawn = 2; //Icky, will keep printing please wait until card is recieved from server
-            //We can fix this later
-
-            scanned_card = false;
-            if (read_bt() == "access1") { //Card is good
-              display_state = 1;
-              screen_drawn = 0;
-            }
-            else {
-              tft.println("Sorry, no access");
-              delay(1000);
-              screen_drawn = 0;
-            }
-          }
-        }
-        break;
-
-      case 1: //Main Display
-          homeDisplay();
-
-          //If buttons pressed move to corresponding screen
-        break;
-
-      default:
-        break;
-    }
-
-
-    // Read bluetooth text and print it to screen
-
-    if(bluetooth.available())  // If the bluetooth sent any characters
-    {
-      char char_in = (char)bluetooth.read();
-      if(char_in != '\0'){ // Before end char
-
-        bt_buffer = bt_buffer + char_in;
-      } else { // Print to screen at end char
-        last_bt = bt_buffer;
-        available_bt = true;
-        bt_buffer = "";
+  case 3: //Leave Table
+    leaveDisplay();
+    break;
+
+  default:
+    break;
+  }
+
+
+  // Scan bt and listen for new data
+  listen_bt();
+
+
+  // RFID reading
+  if(rfid.isCard() && !scanned_card){
+    if(rfid.readCardSerial()){
+      String serNumStr = "";
+      for(int i=0; i<5; i++){
+        serNumStr = serNumStr + String(rfid.serNum[i]) + " ";
       }
-
-    }
-
-
-    // Read buttons and send to bluetooth
-//    if(digitalRead(BTN0)==HIGH){
-//      bluetooth.print("BTN0");
-//    } else if(digitalRead(BTN1)==HIGH) {//      bluetooth.print("BTN1");
-//    } else if(digitalRead(BTN2)==HIGH) {
-//      bluetooth.print("BTN2");
-//    } else if(digitalRead(BTN3)==HIGH) {
-//      bluetooth.print("BTN3");
-//    }
-
-    // RFID reading
-    if(rfid.isCard() && !scanned_card){
-        if(rfid.readCardSerial()){
-            String serNumStr = "";
-            for(int i=0; i<5; i++){
-              serNumStr = serNumStr + String(rfid.serNum[i]) + " ";
-            }
-            bluetooth.print(serNumStr);
-
-            scanned_card = true;
-
-            screen_drawn = 2;
-
-            tone(speaker, 800);
-            delay(120);
-            tone(speaker, 1000);
-            delay(40);
-            noTone(speaker);
-
-        }
-
-//       if(access){
-//          tft.setCursor(0, 75);
-//          tft.setTextColor(ILI9341_WHITE);
-//          tft.setTextSize(4);
-//          Serial.println("Welcome TEST!");
-//          tft.println("Hey TEST!");
-//          colorWipe(strip.Color(0, 100, 0), 10);
-//          access = false;
-//          homeDisplay();
-//        } else {
-//           Serial.println("Not allowed!");
-//           tft.println("ACCESS DENIED.");
-//           colorWipe(strip.Color(255, 0, 0), 10);
-//           tone(speaker, 400);
-//           delay(150);
-//           noTone(speaker);
-//           delay(100);
-//           tone(speaker, 400);
-//           delay(150);
-//           noTone(speaker);
-//           delay(100);
-//           tone(speaker, 400);
-//           delay(150);
-//           noTone(speaker);
-//           delay(100);
-//           colorWipe(strip.Color(0, 0, 100), 10);
-//           loginDisplay();
-//       }
-    }
-
-
-
-    rfid.halt();
-
-}
-
-void loginDisplay(){
-
-  switch(screen_drawn) {
-    case 0: // Initialise
-      tft.fillScreen(ILI9341_BLACK);
-      tft.setTextSize(2);
-      tft.setCursor(126,113); // centred text
-      tft.println("bleepr");
-      tft.drawCircle(160,120,60,ILI9341_RED);
-
-      screen_drawn = 1;
-      animation_time = millis();
-      break;
-     case 1: //Animate (Currently janky and NEEDS to be fixed)
-//      if(millis() - animation_time >= 20) {
-//        tft.drawCircle(160,120,60,ILI9341_RED);
-//      }
-//      if(millis() - animation_time >= 200){
-//        tft.drawCircle(160,120,60,ILI9341_BLACK);
-//      }
-//      if(millis() - animation_time >= 240){
-//        tft.drawCircle(160,120,80,ILI9341_YELLOW);
-//      }
-//      if(millis() - animation_time >= 440){
-//        tft.drawCircle(160,120,80,ILI9341_BLACK);
-//      }
-//      if(millis() - animation_time >= 460){
-//        tft.drawCircle(160,120,100,ILI9341_GREEN);
-//      }
-//      if(millis() - animation_time >= 660){
-//        tft.drawCircle(160,120,100,ILI9341_GREEN);
-//      }
-//      if(millis() - animation_time >= 700){
-//        tft.drawCircle(160,120,100,ILI9341_BLACK);
-//      }
-//      if(millis() - animation_time >= 740){
-//        animation_time = millis();
-//      }
-
-       break;
-     case 2: //Please wait
-       tft.setCursor(126,200); // centred text
-       tft.println("Please wait");
-       screen_drawn = 1;
-  }
-}
-
-
-//Needs to be converted for new steup
-void homeDisplay(){
-  switch(screen_drawn) {
-    case 0: //Setup
-      tft.fillRect(0,0,160,120,ILI9341_LIGHTGREY);
-      tft.fillRect(160,0,160,120,ILI9341_DARKGREY);
-      tft.fillRect(0,120,160,120,ILI9341_DARKGREY);
-      tft.fillRect(160,120,160,120,ILI9341_LIGHTGREY);
-      tft.setTextSize(2);
-      tft.setCursor(5,60);
-      tft.println("Call waiter");
-      tft.setCursor(165,60);
-      tft.println("Ask for bill");
-      tft.setCursor(5,180);
-      tft.println("Food status");
-      tft.setCursor(165,180);
-      tft.println("Leave table");
-
-      screen_drawn = 1;
-      break;
-
-     case 1: //Loop
-       break;
-
-     default:
-       break;
-
-  }
-
-
-
-}
+      bluetooth.print("CARD_ID," + serNumStr);
+
+      scanned_card = true;
+
+      screen_drawn = 8;
+
+      tone(speaker, 800);
+      delay(120);
+      tone(speaker, 1000);
+      delay(40);
+      noTone(speaker);
+
+    }
+  }
+
+  rfid.halt();
+
+}
+
+
+
+

 //BT Functions
+void listen_bt() {
+  if(bluetooth.available())  // If the bluetooth sent any characters
+  {
+    char char_in = (char)bluetooth.read();
+    if(char_in != '\0'){ // Before end char
+
+      bt_buffer = bt_buffer + char_in;
+    }
+    else { // Print to screen at end char
+      last_bt = bt_buffer;
+      available_bt = true;
+      bt_buffer = "";
+    }
+
+  }
+}
+
 String read_bt() {
- if(available_bt) {
-   available_bt = false;
-   return last_bt;
- } else {
-   return "";
- }
+  if(available_bt) {
+    available_bt = false;
+    return last_bt;
+  }
+  else {
+    return "";
+  }
 }

@@ -324,3 +236,299 @@
   }
 }

+//ScreenDisplays
+void loginDisplay(){
+
+  switch(screen_drawn) {
+  case 0: // Initialise
+    tft.fillScreen(ILI9341_BLACK);
+    tft.setTextSize(2);
+    tft.setCursor(126,113); // centred text
+    tft.println("bleepr");
+
+    screen_drawn = 1;
+    animation_time = millis();
+    break;
+  case 1: //Animate Red circle
+    if(millis() - animation_time >= 0) {
+      //colorWipe(strip.Color(255, 0, 0), 1);
+      tft.drawCircle(160,120,60,ILI9341_RED);
+      screen_drawn = 2;
+    }
+    break;
+
+  case 2: //Animate black circle clear
+    if(millis() - animation_time >= 200){
+      tft.drawCircle(160,120,60,ILI9341_BLACK);
+      screen_drawn = 3;
+    }
+    break;
+
+  case 3: //Animate yellow circle
+    if(millis() - animation_time >= 240){
+      //  colorWipe(strip.Color(255, 255, 0), 1);
+      tft.drawCircle(160,120,80,ILI9341_YELLOW);
+      screen_drawn = 4;
+    }
+    break;
+
+  case 4: //Animate black circle clear
+    if(millis() - animation_time >= 440){
+      tft.drawCircle(160,120,80,ILI9341_BLACK);
+      screen_drawn = 5;
+    }
+    break;
+
+  case 5: //Animate green circle
+    if(millis() - animation_time >= 480){
+      // colorWipe(strip.Color(0, 255, 0), 1);
+      tft.drawCircle(160,120,100,ILI9341_GREEN);
+      screen_drawn = 6;
+    }
+    break;
+  case 6: //Animate (Currently janky and NEEDS to be fixed)
+    if(millis() - animation_time >= 680){
+      tft.drawCircle(160,120,100,ILI9341_BLACK);
+      screen_drawn = 7;
+    }
+    break;
+
+  case 7: //Resets
+    if(millis() - animation_time >= 740){
+      animation_time = millis();
+      screen_drawn = 1;
+    }
+    break;
+
+
+
+  case 8: //Please wait
+    tft.setCursor(126,200); // centred text
+    tft.println("Please wait");
+    screen_drawn = 1;
+    break;
+  }
+}
+
+void homeDisplay(){
+  switch(screen_drawn) {
+  case 0: //Setup
+
+    //LEDs blue
+    colorWipe(strip.Color(0, 0, 255), 10);
+
+
+    tft.fillRect(0,0,160,120,ILI9341_LIGHTGREY);
+    tft.fillRect(160,0,160,120,ILI9341_DARKGREY);
+    tft.fillRect(0,120,160,120,ILI9341_DARKGREY);
+    tft.fillRect(160,120,160,120,ILI9341_LIGHTGREY);
+    tft.setTextSize(2);
+    tft.setCursor(5,60);
+    tft.println("Call waiter");
+    tft.setCursor(165,60);
+    tft.println("Ask for bill");
+    tft.setCursor(5,180);
+    tft.println("Food status");
+    tft.setCursor(165,180);
+    tft.println("Leave table");
+
+    screen_drawn = 1;
+    break;
+
+  case 1: //Loop
+    break;
+
+  default:
+    break;
+
+  }
+}
+
+
+void billDisplay(){
+  switch(screen_drawn) {
+  case 0: //Setup
+
+    //LEDs yellow
+    colorWipe(strip.Color(255, 255, 0), 10);
+
+    tft.fillRect(160,0,160,120,ILI9341_RED);
+
+    tft.setTextSize(2);
+    tft.setCursor(165,60);
+    tft.println("Calling bill");
+
+    bluetooth.print("request_bill");
+
+    screen_drawn = 1;
+    break;
+
+  case 1: //Loop
+    if(available_bt) {
+      if( read_bt() == "ok") {
+        screen_drawn = 2;
+      }
+    }
+    break;
+
+  case 2: //Exit state
+    colorWipe(strip.Color(0, 255, 0), 10);
+
+    tft.fillRect(160,0,160,120,ILI9341_GREEN);
+
+    tft.setTextSize(2);
+    tft.setCursor(165,60);
+    tft.println("Bill on way");
+
+    delay(2000);
+    screen_drawn = 0;
+    display_state = 1; //Main menu
+    break;
+
+  default:
+    break;
+
+  }
+}
+
+void waiterDisplay(){
+  switch(screen_drawn) {
+  case 0: //Setup
+
+    //LEDs yellow
+    colorWipe(strip.Color(255, 255, 0), 10);
+
+    tft.fillRect(160,0,160,120,ILI9341_RED);
+
+    tft.setTextSize(2);
+    tft.setCursor(165,60);
+    tft.println("Calling bill");
+
+    bluetooth.print("request_bill");
+
+    screen_drawn = 1;
+    break;
+
+  case 1: //Loop
+    if(available_bt) {
+      if( read_bt() == "ok") {
+        screen_drawn = 2;
+      }
+    }
+    break;
+
+  case 2: //Exit state
+    colorWipe(strip.Color(0, 255, 0), 10);
+
+    tft.fillRect(160,0,160,120,ILI9341_GREEN);
+
+    tft.setTextSize(2);
+    tft.setCursor(165,60);
+    tft.println("Bill on way");
+
+    delay(2000);
+    screen_drawn = 0;
+    display_state = 1; //Main menu
+    break;
+
+  default:
+    break;
+
+  }
+}
+
+void leaveDisplay(){
+  switch(screen_drawn) {
+  case 0: //Setup
+
+    //LEDs yellow
+    colorWipe(strip.Color(255, 255, 0), 10);
+
+    tft.fillRect(160,120,160,120,ILI9341_RED);
+
+    tft.setTextSize(2);
+    tft.setCursor(165,60);
+    tft.println("Hang on!");
+
+    bluetooth.print("leave_table");
+
+    screen_drawn = 1;
+    break;
+
+  case 1: //Loop
+    if(available_bt) {
+      if( read_bt() == "ok") {
+        screen_drawn = 2;
+      }
+    }
+    break;
+
+  case 2: //Exit state
+    colorWipe(strip.Color(0, 255, 0), 10);
+
+    tft.fillRect(160,0,160,120,ILI9341_GREEN);
+
+    tft.setTextSize(2);
+    tft.setCursor(165,60);
+    tft.println("Bill on way");
+
+    delay(2000);
+    screen_drawn = 0;
+    display_state = 1; //Main menu
+    break;
+
+  default:
+    break;
+
+  }
+}
+
+void foodDisplay(){
+  switch(screen_drawn) {
+  case 0: //Setup
+
+    //LEDs yellow
+    colorWipe(strip.Color(255, 255, 0), 10);
+
+    tft.fillRect(160,0,160,120,ILI9341_RED);
+
+    tft.setTextSize(2);
+    tft.setCursor(165,60);
+    tft.println("Calling bill");
+
+    bluetooth.print("request_bill");
+
+    screen_drawn = 1;
+    break;
+
+  case 1: //Loop
+    if(available_bt) {
+      if( read_bt() == "ok") {
+        screen_drawn = 2;
+      }
+    }
+    break;
+
+  case 2: //Exit state
+    colorWipe(strip.Color(0, 255, 0), 10);
+
+    tft.fillRect(160,0,160,120,ILI9341_GREEN);
+
+    tft.setTextSize(2);
+    tft.setCursor(165,60);
+    tft.println("Bill on way");
+
+    delay(2000);
+    screen_drawn = 0;
+    display_state = 1; //Main menu
+    break;
+
+  default:
+    break;
+
+  }
+
+}
+
+
+


Pump it grid, pump it.

Pump it grid, pump it.

--- Buddy/Iris_buddy_workFile/Iris_buddy_workFile.ino
+++ Buddy/Iris_buddy_workFile/Iris_buddy_workFile.ino
@@ -61,16 +61,16 @@

 void valueToLedScale(int value) {
-
   int calc = map(value, 0, 1023, 0, 8 * 256 - 1);

   for (int i = 0; i < 7; i++) strip.setPixelColor(ledPositions[i][0], strip.Color(0, 255, 0));
   for (int i = 0; i < 7; i++) strip.setPixelColor(ledPositions[i][9], strip.Color(0, 0, 255));

-  for (int j = 0; j < 8; j++) {
-    for (int i = 0; i < 7; i++) strip.setPixelColor(ledPositions[i][1 + j], strip.Color(0, constrain(calc - 256 * j, 0, 255), 255 - constrain(calc - 256 * j, 0, 255)));
-  }
+  for (int j = 0; j < 8; j++) for (int i = 0; i < 7; i++) strip.setPixelColor(ledPositions[i][1 + j], strip.Color(0, constrain(calc - 256 * j, 0, 255), 255 - constrain(calc - 256 * j, 0, 255)));
+

   strip.show();
 }

+
+


Brackets and whitespace.

Brackets and whitespace.

--- oledtask.ino
+++ oledtask.ino
@@ -1,12 +1,10 @@
-void IRAM_ATTR oledTask( void * pvParameters )
-{
+void IRAM_ATTR oledTask( void * pvParameters ) {
   const TickType_t oledTaskdelayTime = 1000 / UPDATE_FREQ_OLED / portTICK_PERIOD_MS;

   OLED.init();
   ESP_LOGI( TAG, "OLED initialized." );

-  if ( preferences.getString( "oledorientation", "normal" ) == "upsidedown" )
-  {
+  if ( preferences.getString( "oledorientation", "normal" ) == "upsidedown" ) {
     oledOrientation = OLED_ORIENTATION_UPSIDEDOWN;
     OLED.flipScreenVertically();
   }
@@ -18,23 +16,19 @@
   OLED.display();

   while ( !xDimmerTaskHandle )
-  {
     vTaskDelay( 10 / portTICK_PERIOD_MS );
-  }

   oledContrast = preferences.getUInt( "oledcontrast", 15 );
   OLED.setContrast( oledContrast << 0x04 );

   OLED.setFont( ArialMT_Plain_10 );

-  while (1)
-  {
+  while (1) {
     static char content[64];

     OLED.clear();

-    if ( OLED_SHOW_SYSTEMDATA )
-    {
+    if ( OLED_SHOW_SYSTEMDATA ) {
       //https://github.com/espressif/esp-idf/blob/master/examples/protocols/sntp/main/sntp_example_main.c
       struct tm timeinfo;
       if ( getLocalTime( &timeinfo, 0 ) )
@@ -51,8 +45,7 @@
       snprintf( content, sizeof( content ), "%s", sketchVersion );
       OLED.drawString( 64, 45, content );
     }
-    else
-    {
+    else {
       const uint8_t BARS_BOTTOM      = OLED.getHeight() - 11;
       const uint8_t BARS_HEIGHT      = BARS_BOTTOM;
       const uint8_t BARS_BORDER      = 4;
@@ -60,30 +53,23 @@

       OLED.drawString( 64, 0, WiFi.localIP().toString() );

-      for ( uint8_t thisChannel = 0; thisChannel < NUMBER_OF_CHANNELS; thisChannel++ )
-      {
+      for ( uint8_t thisChannel = 0; thisChannel < NUMBER_OF_CHANNELS; thisChannel++ ) {
         uint8_t x1 = BARS_WIDTH * thisChannel + BARS_BORDER;
         uint8_t y1 = ( BARS_BOTTOM ) - ( BARS_BOTTOM * ( channel[thisChannel].currentPercentage / 100 ) ) * 0.6;
         uint8_t x2 = BARS_WIDTH - BARS_BORDER;
         uint8_t y2 = BARS_BOTTOM - y1;
         OLED.fillRect( x1, y1, x2, y2 );
-
-        //threeDigitPercentage( content, sizeof( content ), channel[thisChannel].currentPercentage, NO_PERCENTSIGN );
-
         OLED.drawString( x1 + ( BARS_WIDTH / 2 ) - 1, y1 - 11,
                          threeDigitPercentage( content, sizeof( content ), channel[thisChannel].currentPercentage, NO_PERCENTSIGN ) );
       }

-      if ( logger.sensorCount() )
-      {
+      if ( logger.sensorCount() ) {
         uint8_t charCount = 0;
         for ( uint8_t sensorNumber = 0; sensorNumber < logger.sensorCount(); sensorNumber++ )
           charCount += snprintf( content + charCount, sizeof( content ) - charCount, "%.1f°C  " , logger.sensorTemp( sensorNumber ) );
       }
       else
-      {
         snprintf( content, sizeof( content ), "%.2f kB RAM", esp_get_free_heap_size() / 1024.0 );
-      }
       OLED.drawString( 64, BARS_BOTTOM, content );
     }


Updated CAN receive example

Updated CAN receive example

Added CS constant for easy adaption to different boards...

--- libraries/MCP_CAN_lib_15/examples/CAN_receive/CAN_receive.ino
+++ libraries/MCP_CAN_lib_15/examples/CAN_receive/CAN_receive.ino
@@ -1,5 +1,5 @@
-// CAN Receive Example
-//
+// CAN Receive Example by Cory Fowler
+// modified with CS constant, 2016 MyLab-odyssey

 #include <mcp_can.h>
 #include <SPI.h>
@@ -8,15 +8,15 @@
 unsigned char len = 0;
 unsigned char rxBuf[8];

-MCP_CAN CAN0(9);                               // Set CS to pin 10
-
+#define CS 10                //!< chip select pin of MCP2515 CAN-Controller
+MCP_CAN CAN0(CS);

 void setup()
 {
   Serial.begin(115200);

-  pinMode(9, OUTPUT);
-  pinMode(8, OUTPUT);
+  pinMode(CS, OUTPUT);
+  pinMode(8, OUTPUT);       //!< disable chip select of SD card reader (commonly pin 8)
   digitalWrite(8, HIGH);

   // Initialize MCP2515 running at 16MHz with a baudrate of 500kb/s and the masks and filters disabled.
@@ -34,7 +34,7 @@
 {
     if(!digitalRead(2))                         // If pin 2 is low, read receive buffer
     {
-      CAN0.readMsgBuf(&rxId, &len, rxBuf);              // Read data: len = data length, buf = data byte(s)
+      CAN0.readMsgBuf(&rxId, &len, rxBuf);      // Read data: len = data length, buf = data byte(s)

       Serial.print("ID: ");                     // Print the message ID.
       Serial.print(rxId, HEX);
@@ -56,4 +56,4 @@

 /*********************************************************************************************************
   END FILE
-*********************************************************************************************************/
+*********************************************************************************************************/


added comments

added comments

--- v2/Motor_control/Distance_Test/Distance_Test.ino
+++ v2/Motor_control/Distance_Test/Distance_Test.ino
@@ -33,35 +33,35 @@
 #include <SharpDistSensor.h>

 // Analog pin to which the sensor is connected
-const byte sensorPin = A0;
-const byte sensorPin2 = A1;
-const byte backleft = A6;
-const byte backright = A7;
-const byte frontright = A2;
-const byte frontleft = A3;
+const byte sensorPin = A0; //right motor
+const byte sensorPin2 = A1; //left motor
+const byte backleft = A6; //back-left line sensor
+const byte backright = A7; //back-right line sensor
+const byte frontright = A2; //front-left line sensor
+const byte frontleft = A3; //front-right line sensor

 // Window size of the median filter (odd number, 1 = no filtering)
 const byte mediumFilterWindowSize = 5;
-unsigned int distance;
-unsigned int distance2;
+unsigned int distance; //distance from right sensor
+unsigned int distance2; //distance from left sensor

 // Create an object instance of the SharpDistSensor class
-SharpDistSensor sensor(sensorPin, mediumFilterWindowSize);
-SharpDistSensor sensor2(sensorPin2, mediumFilterWindowSize);
+SharpDistSensor sensor(sensorPin, mediumFilterWindowSize); //right sensor
+SharpDistSensor sensor2(sensorPin2, mediumFilterWindowSize); //left sensor
 int STBY = 10; //standby

-//Motor A
+//Right Motor (? I'm not too sure about this)
 int PWMA = 3; //Speed control
 int AIN1 = 9; //Direction
 int AIN2 = 8; //Direction

-//Motor B
+//Left Motor (? also not too sure about this)
 int PWMB = 5; //Speed control
 int BIN1 = 11; //Direction
 int BIN2 = 12; //Direction
-char past;
-int count;
-int threshold;
+char past; //what direction the robot was moving previously
+int count; //counter for how long before the rebot gives up searching in one direction
+int threshold; //threshold for line sensors
 short iter;
 void setup() {
   Serial.begin(9600);
@@ -74,7 +74,9 @@
   pinMode(PWMB, OUTPUT);
   pinMode(BIN1, OUTPUT);
   pinMode(BIN2, OUTPUT);
-  past = 'f';
+
+  //initialising values
+  past = 'f'; //set default move to forward
   count = 0;
   iter = 0;
   threshold = analogRead(backleft) - 200;
@@ -84,8 +86,9 @@

 void loop() {
   // Get distance from sensor
-  iter ++;
+  iter++;
   if (iter == 1) {
+    //print out values from sensors and motors to the console
     distance = sensor.getDist();
     distance2 = sensor2.getDist();
     Serial.print(past);
@@ -104,55 +107,66 @@
   } else if (iter == 5) {
     iter = 0;
   }
-  if (analogRead(backleft) < threshold) {
+  if (analogRead(backleft) < threshold) { //first read from line sensors before doing anything else
+    //if line detected by back-left line sensor, turn left a bit
+    move(1, 40, 1); //motor 1, full speed, left
+    move(2, 120, 0); //motor 2, full speed, left
+    past = 'f'; //set default move to forward
+    delay(50); //wait 50ms for the IR sensors to take new reading
+  } else if (analogRead(backright) < threshold) {
+    //if line detected by back-right line sensor, turn right a bit
     move(1, 120, 1); //motor 1, full speed, left
     move(2, 40, 0); //motor 2, full speed, left
     past = 'f';
     delay(50);
-  } else if (analogRead(backright) < threshold) {
-    move(1, 40, 1); //motor 1, full speed, left
-    move(2, 120, 0); //motor 2, full speed, left
-    past = 'f';
-    delay(50);
   } else if (analogRead(frontleft) < threshold) {
+    //if line dectected by front-left sensor, go back and to the left a bit
     move(1, 40, 0); //motor 1, full speed, left
     move(2, 120, 1); //motor 2, full speed, left
     past = 'f';
     delay(50);
   } else if (analogRead(frontright) < threshold) {
+    //if line detected by front-right sensor, go back and to the right a bit
     move(1, 120, 0); //motor 1, full speed, left
     move(2, 40, 1); //motor 2, full speed, left
     past = 'f';
     delay(50);
   } else if (iter == 1){
     if (((past == 'f' || count >= 100) && (distance > 600 && distance2 > 600)) || (distance <= 300 && distance2 <= 300) || (abs(distance - distance2) <= 150)) {
+      //if (robot moved forward in the past OR it's been searching for 100 iterations) AND (there isn't an object within 600mm of either IR sensor))
+      //OR there is an object within 300mm of both sensors
+      //OR the difference between the two distances measured by the IR sensors is within 150mm of each other
+      //move forward
       move(1, 128, 1); //motor 1, full speed, left
       move(2, 128, 0); //motor 2, full speed, left
-      past = 'f';
-      count = 0;
+      past = 'f'; //set past movement to forward
+      count = 0; //reset abandon search count
     } else if (past == 'l') {
+      //if robot has been moving left in the past, move left more
       move(1, 20, 1); //motor 1, full speed, left
       move(2, 128, 0); //motor 2, full speed, left
-      past = 'l';
-      count++;
+      past = 'l'; //set past movement to left
+      count++; //increment abandon search count
     } else if (past == 'r') {
+      //if robot has been moving right in the past, move right
       move(1, 128, 1); //motor 1, full speed, left
       move(2, 20, 0); //motor 2, full speed, left
-      past = 'r';
-      count++;
+      past = 'r'; //set past movement to right
+      count++; //increment abandon search count
     } else if (distance > 600) {
+      //if there is an object beyond 600mm of the right sensor (i.e. there is something closer in the left sensor), move left
       move(1, 20, 1); //motor 1, full speed, left
       move(2, 128, 0); //motor 2, full speed, left
-      past = 'l';
-      count = 0;
-    } else{
+      past = 'l'; //set past movement to left
+      count = 0; //reset abandon search count because the robot has found an object
+    } else {
+      //else (i.e. there is an object closer in the right sensor), move right
       move(1, 128, 1); //motor 1, full speed, left
       move(2, 20, 0); //motor 2, full speed, left
-      past = 'r';
-      count = 0;
+      past = 'r'; //set past movement to right
+      count = 0; //reset abandon search count
     }
   }
-

   // Print distance to Serial
   // Wait some time
@@ -160,33 +174,33 @@
 }

 void move(int motor, int speed, int direction){
-//Move specific motor at speed and direction
-//motor: 0 for B 1 for A
-//speed: 0 is off, and 255 is full speed
-//direction: 0 clockwise, 1 counter-clockwise
-
-digitalWrite(STBY, HIGH); //disable standby
-
-boolean inPin1 = LOW;
-boolean inPin2 = HIGH;
-
-if(direction == 1){
-inPin1 = HIGH;
-inPin2 = LOW;
-}
-
-if(motor == 1){
-digitalWrite(AIN1, inPin1);
-digitalWrite(AIN2, inPin2);
-analogWrite(PWMA, speed);
-}else{
-digitalWrite(BIN1, inPin1);
-digitalWrite(BIN2, inPin2);
-analogWrite(PWMB, speed);
-}
+  //Move specific motor at speed and direction
+  //motor: 1 for right, 2 for left
+  //speed: 0 is off, and 255 is full speed
+  //direction: 0 clockwise, 1 counter-clockwise
+
+  digitalWrite(STBY, HIGH); //disable standby
+
+  boolean inPin1 = LOW;
+  boolean inPin2 = HIGH;
+
+  if(direction == 1){
+    inPin1 = HIGH;
+    inPin2 = LOW;
+  }
+
+  if(motor == 1){
+    digitalWrite(AIN1, inPin1);
+    digitalWrite(AIN2, inPin2);
+    analogWrite(PWMA, speed);
+  } else {
+    digitalWrite(BIN1, inPin1);
+    digitalWrite(BIN2, inPin2);
+    analogWrite(PWMB, speed);
+  }
 }

 void stop(){
-//enable standby
-digitalWrite(STBY, LOW);
-}
+  //enable standby
+  digitalWrite(STBY, LOW);
+}


avoid printing nullptr string (#7144)

avoid printing nullptr string (#7144)

--- libraries/esp8266/examples/NTP-TZ-DST/NTP-TZ-DST.ino
+++ libraries/esp8266/examples/NTP-TZ-DST/NTP-TZ-DST.ino
@@ -134,7 +134,7 @@
   Serial.println((uint32_t)now);

   // timezone and demo in the future
-  Serial.printf("timezone:  %s\n", getenv("TZ"));
+  Serial.printf("timezone:  %s\n", getenv("TZ") ? : "(none)");

   // human readable
   Serial.print("ctime:     ");


display sensor details on start

display sensor details on start

--- src/esp_8266_sensor.ino
+++ src/esp_8266_sensor.ino
@@ -1,4 +1,4 @@
-// BMP180
+// I2C sensors
 #include <Wire.h>
 #include <Adafruit_BMP085_U.h>
 // Display
@@ -119,6 +119,7 @@
       while (1) {}
     }
     Serial.println("Sensor ready");
+    displaySensorDetails();

     // première mesure
     Serial.println("Lancement de la première mesure");
@@ -324,6 +325,26 @@
       light = myLight;
     }
 }
+/**************************************************************************/
+/*
+    Displays some basic information on this sensor from the unified
+    sensor API sensor_t type (see Adafruit_Sensor for more information)
+*/
+/**************************************************************************/
+void displaySensorDetails(void) {
+  sensor_t sensor;
+  bmp.getSensor(&sensor);
+  Serial.println("------------------------------------");
+  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
+  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
+  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
+  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" hPa");
+  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" hPa");
+  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" hPa");
+  Serial.println("------------------------------------");
+  Serial.println("");
+  delay(500);
+}

 int BH1750_Read(int address) //
 {


set default brightness to max

set default brightness to max

--- fireplace.ino
+++ fireplace.ino
@@ -31,7 +31,7 @@
 // used to 'turn off' the LEDs
 bool runLoop = true;

-int defaultBrightness = 50;
+int defaultBrightness = 255;

 uint32_t leds[PIXEL_COUNT];


Massive Update to v1 Code

Massive Update to v1 Code

Added Menu options in mode cycle
Storing data and pins in arrays
Allowing varying engagement computation methods
Persisting variables in EEPROM


Added blinking LED to check if the ISR routine causes the arduino to block.

--- skypointer.ino
+++ skypointer.ino
@@ -32,12 +32,18 @@
 #define LASER_PIN 13

+#define DEBUG 1
+// Pin for debug
+#ifdef DEBUG
+  int blinkLed = 12;
+#endif
+
 // Definition of the SerialCommand object, with delimiter ":"
 SerialCommand sCmd;
 // Definition of the motor shield
 SkyPointer_MotorShield MS = SkyPointer_MotorShield();
 // Motor 1 on port 1, 200 steps/rev
-SkyPointer_MicroStepper *motor1 = MS.getMicroStepper(STEPS, 1);
+SkyPointer_MicroStepper *motor1 =MS.getMicroStepper(STEPS, 1);
 // Motor 2 on port 2, 200 steps/rev
 SkyPointer_MicroStepper *motor2 = MS.getMicroStepper(STEPS, 2);

@@ -46,7 +52,18 @@
 void ISR_rotate() {
   uint16_t pos, sim_pos, tg;
   uint8_t dir;
-
+
+  #ifdef DEBUG
+      bool status;
+      status = digitalRead(blinkLed);
+      if (status == HIGH) {
+        digitalWrite(blinkLed, LOW);
+      }
+      else {
+        digitalWrite(blinkLed, HIGH);
+      }
+  #endif
+
   sei();  // Enable interrupts --> Serial, I2C (MotorShield)

   // MOTOR 1
@@ -168,7 +185,10 @@

 void setup() {
   pinMode(LASER_PIN, OUTPUT);
-
+  #ifdef DEBUG
+    pinMode (blinkLed, OUTPUT);
+  #endif
+
   // Start the serial port
   Serial.begin(115200);


example is for esp6266 not arduino

example is for esp6266 not arduino

--- examples/simple/simple.ino
+++ examples/simple/simple.ino
@@ -11,7 +11,7 @@
     * Reads analog inputs as input registers.

     The circuit: ( see: ./extras/ModbusSetch.pdf )
-    * An Arduino.
+    * An ESP8266 unit with connectors to digital out pins.
     * 2 x LEDs, with 220 ohm resistors in series.
     * A switch connected to a digital input pin.
     * A potentiometer connected to an analog input pin.


Delete oas-0-2.ino

Delete oas-0-2.ino


alwaysUseCamelCase

alwaysUseCamelCase

--- src/main.ino
+++ src/main.ino
@@ -37,14 +37,14 @@
       middleFinger();
       break;
     default:
-      allfingers(0);
+      allFingers(0);
       break;
   }
 }

 // FUNCTIONS //
-void allfingers(int pos) {
+void allFingers(int pos) {
   // get all fingers in same position.
   // 0 for open hand, 180 for fully closed hand
   m1.write(pos);


added ui check and mdns begin

added ui check and mdns begin

--- wifi-lib-interface-SPI/wifi-lib-interface-SPI.ino
+++ wifi-lib-interface-SPI/wifi-lib-interface-SPI.ino
@@ -1,3 +1,4 @@
+
 #include "CommLgc.h"
 //#include "utility/wifi_utils.h"

@@ -10,25 +11,43 @@
 #include <Hash.h>
 #include <ESP8266WebServer.h>

-#define WIFI_LED 2
-#define HOSTNAME "Arduino-PrimoSPI"
+#define HOSTNAME "Arduino-Primo"

 ESP8266WebServer server(80);    //server UI
-
+bool SERVER_STOP = false;       //check stop server
+// MCU McuType = NRF52;
 void setup() {

   ArduinoOTA.begin();
   CommunicationLogic.begin();
-  WiFi.hostname(HOSTNAME);      //set hostname
-  MDNS.begin(HOSTNAME);         //set mdns
   initWBServer();               //UI begin
+  initMDNS();                   //set MDNS
+  //Serial1.println("end setup");

 }

 void loop() {
-
+
   ArduinoOTA.handle();
   CommunicationLogic.handle();
-  handleWBServer();
+  if(CommunicationLogic.UI_alert){			//stop UI SERVER){}
+    if(!SERVER_STOP){
+      server.stop();
+      SERVER_STOP = true;
+    }
+  }
+  else
+    handleWBServer();
+  // unsigned long currentMillis = millis();
+  // if (currentMillis - previousMillis >= interval) {
+  //   // save the last time you blinked the LED
+  //   previousMillis = currentMillis;
+  //   if (ledState == LOW) {
+  //     ledState = HIGH;
+  //   } else {
+  //     ledState = LOW;
+  //   }
+  //   digitalWrite(WIFI_LED, ledState);
+  // }

 }


Delete some codes

Delete some codes

--- arduino/sketch_switch/sketch_switch.ino
+++ arduino/sketch_switch/sketch_switch.ino
@@ -7,7 +7,7 @@
       json data from yunba service
 */
 #include <ArduinoJson.h>
-#include <PWM.h>
+//#include <PWM.h>

 #define MSG_TYPE_UP 0x01
 #define MSG_TYPE_DOWN 0x02
@@ -18,17 +18,16 @@

 #define FIRST_PIN_CTRL 3
 #define FIRST_PIN_LED 6
-#define FIRST_PIN_PWM 9
 #define FIRST_PIN_TOUCH A1

 /* 检测到 MAX_LOW_CNT 次小于 MAX_LOW_ANNALOG 的电压后, 认为是面板发出了关的信号 */
 #define MAX_LOW_CNT 16
 #define MAX_LOW_ANNALOG 192

-#define CHILD_NUM 1
-
-
-class Child;
+#define CHILD_NUM 3
+
+
+class ChildSwitch;

 const char *g_devid = "switch_0";

@@ -38,29 +37,28 @@
 uint16_t g_body_len = 0;
 uint16_t g_recv_len = 0;

-Child *g_child[CHILD_NUM];
+ChildSwitch *g_child[CHILD_NUM];

 char g_need_report = 1;
 unsigned long g_check_ms = 0;

-class Child {
+class ChildSwitch {
 private:
   int pin_ctrl; /* 控制继电器 */
   int pin_led; /* 控制开关的指示LED */
-  int pin_pwm; /* 输出PWM给触摸面板 */
   int pin_touch; /* 接受来自触摸面板的开关信号  */

   int ctrl_value; /* 当前继电器状态 */

   int touch_value; /* 当前触摸面板认为的开关状态 */
-  int low_cnt; /* 触摸面板开关信号为0的计数, 当超过阈值, 认为是关信号(因为面板输出不稳定的脉冲) */
+  int low_cnt; /* 触摸面板开关信号为低的计数, 当超过 MAX_LOW_CNT, 认为是关信号(因为面板输出不稳定的脉冲) */

 public:
-  Child(int pin_ctrl, int pin_led, int pin_pwm, int pin_touch) {
+  ChildSwitch(int pin_ctrl, int pin_led, int pin_touch) {
     this->pin_ctrl = pin_ctrl;
     this->pin_led = pin_led;
-    this->pin_pwm = pin_pwm;
+//    this->pin_pwm = pin_pwm;
     this->pin_touch = pin_touch;

     pinMode(this->pin_ctrl, OUTPUT);
@@ -68,8 +66,8 @@

     pinMode(this->pin_led, INPUT);

-    SetPinFrequencySafe(this->pin_pwm, 50);
-    pwmWrite(this->pin_pwm, 127);
+//    SetPinFrequencySafe(this->pin_pwm, 50);
+//    pwmWrite(this->pin_pwm, 127);

     pinMode(this->pin_touch, INPUT);

@@ -89,10 +87,9 @@
   }

   int check_touch() {
-    int i = 0;
-    i = analogRead(this->pin_touch);
-
-    if (i < MAX_LOW_ANNALOG) {
+    int v = analogRead(this->pin_touch);
+
+    if (v < MAX_LOW_ANNALOG) {
       ++this->low_cnt;
       if (this->low_cnt >= MAX_LOW_CNT) {
         this->low_cnt = 0;
@@ -121,10 +118,12 @@
     this->ctrl_value = value;
     if (value) {
       digitalWrite(this->pin_ctrl, HIGH);
-      pinMode(this->pin_led, INPUT);
-      digitalWrite(this->pin_led, LOW);
+
+      pinMode(this->pin_led, OUTPUT);
+      analogWrite(this->pin_led, 128); /* 拉低 LED 的负极, 使它更亮(LED 的正极接的是电源正极) */
     } else {
       digitalWrite(this->pin_ctrl, LOW);
+
       pinMode(this->pin_led, INPUT);
     }
   }
@@ -252,10 +251,10 @@
 }

 void init_child() {
-  InitTimersSafe();
+//  InitTimersSafe();

   for (int i = 0; i < CHILD_NUM; i++) {
-    g_child[i] = new Child(FIRST_PIN_CTRL + i, FIRST_PIN_LED + i, FIRST_PIN_PWM + i, FIRST_PIN_TOUCH + i);
+    g_child[i] = new ChildSwitch(FIRST_PIN_CTRL + i, FIRST_PIN_LED + i, FIRST_PIN_TOUCH + i);
   }
 }


Adding packet definition to terminaly

Adding packet definition to terminaly

Merge branch 'master' of github.com:Ertinfagor/SensorBoard

--- SensorBoard.ino
+++ SensorBoard.ino
@@ -7,12 +7,13 @@
 const uint64_t pipes[2] = { 0xF0F0F0F001LL, 0xF0F0F0F002LL };
 const byte shortAddr = 0x02;
 int led = 13;
+char switchStatus = 0;
+char lampStatus = 0;
 void setup(void)
 {
   Serial.begin(57600);

   radio.begin();
-  //radio.setChannel(0x4b);
   radio.setAutoAck(false);
   radio.setRetries(15,15);
   radio.setPALevel(RF24_PA_MAX);
@@ -30,8 +31,8 @@

 void loop(void)
 {
-  byte command[32] ;
-  byte *ptr;
+  char command[32] ;
+  char *ptr;
   ptr = &command[0];
   if ( radio.available() )
     {
@@ -39,54 +40,78 @@
       bool done = false;
       while (!done)
       {
-        done = radio.read( ptr, sizeof(byte[32]) );
-        Serial.println(ptr[1]);
-	// Delay just a little bit to let the other unit
-	// make the transition to receiver
-	delay(20);
+        done = radio.read( ptr, sizeof(char[32]) );
+        delay(20);
       }
       runCommand(ptr);
-      Serial.println(ptr[3]);
+      Serial.println(ptr[12]);
+
       radio.stopListening();
       radio.write(ptr, sizeof(byte[32]));
       radio.startListening();
     }

 }
-bool runCommand(byte *ptr)
+void runCommand(char *ptr)
 {
-  Serial.println(ptr[1]);
-  Serial.println(ptr[2]);
-  Serial.println(ptr[3]);
-  switch (ptr[1])
+  Serial.println(ptr[10]);
+  switch (ptr[10])
   {
     case 0:
       break;
     case 1:
-      if (ptr[3]== 0x00)
-      {
-        switchOnLight(ptr);
+    {
+      if (ptr[12]== 0x00){
+        switchLight(ptr);
       }
       break;
-    case 2:
-      if (ptr[3]== 0x00)
-      {
-        switchOffLight(ptr);
-      }
-      break;
+    }
   }

 }
+void readAllSensors(char* ptr){
+  readTemp(ptr);
+  readHum(ptr);
+  readLum(ptr);
+  readSwitch(ptr);
+  readLamp(ptr);
+
+}
+void readTemp(char* ptr){
+  ptr[12] = 0xFF;
+  ptr[13] = 0x02;
+}
+void readHum(char* ptr){
+  ptr[12] = 0xFF;
+  ptr[14] = 0x03;
+}
+void readLum(char* ptr){
+  ptr[12] = 0xFF;
+  ptr[15] = 0xFF;

-byte readTemp(void){}
-byte readHum(void){}
-byte readLight(void){}
-bool switchOnLight(byte* ptr)
+}
+
+void readSwitch(char* ptr){
+  ptr[12] = 0xFF;
+  ptr[15] = switchStatus;
+
+}
+
+void readLamp(char* ptr){
+  ptr[12] = 0xFF;
+  ptr[15] = lampStatus;
+
+}
+
+void switchLight(char* ptr)
 {
-  digitalWrite(led, HIGH);
-  ptr[3] = 0xFF;
+  lampStatus = ptr[16];
+  if(lampStatus == 0xFF){
+    digitalWrite(led, HIGH);
+  }
+  else{
+    digitalWrite(led, LOW);
+  }
+  ptr[12] = 0xFF;
 }
-bool switchOffLight(byte* ptr){
-  digitalWrite(led, LOW);
-  ptr[3] = 0xFF;
-}
+


Added Second Motor and now trying to streamline the code through using functions and variables

--- MotorControlling/BasicStepping2/BasicStepping2.ino
+++ MotorControlling/BasicStepping2/BasicStepping2.ino
@@ -23,7 +23,7 @@
 const uint8_t amisDirPin1 = 2;      //Dir
 const uint8_t amisDirPin2 = 6;      //Dir
 const uint8_t amisStepPin1 = 3;     //Step
-const uint8_t amisSlaveSelect1 = 4; //CS
+const uint8_t amisSlaveSelect = 4;  //CS
 const uint8_t amisStepPin2 = 5;

 AMIS30543 stepper;
@@ -31,9 +31,10 @@
 void setup()
 {
   SPI.begin();
-  stepper.init(amisSlaveSelect1);
-  //stepper.init(amisSlaveSelect2);
-
+  //stepper.init(amisSlaveSelect);
+
+  char myChar = 'A';
+
   // Drive the NXT/STEP and DIR pins low initially.
   digitalWrite(amisStepPin1, LOW);
   pinMode(amisStepPin1, OUTPUT);
@@ -116,5 +117,6 @@
   // microseconds before and after changing the DIR pin.
   delayMicroseconds(1);
   digitalWrite(amisDirPin1, dir);
+  digitalWrite(amisDirPin2, dir);
   delayMicroseconds(1);
 }


Turn calculations added as comment in Arduino step :)

--- Arduino/MotorTest/MotorTest.ino
+++ Arduino/MotorTest/MotorTest.ino
@@ -6,6 +6,11 @@

 //Include the pololu encoder library
 #include <PololuWheelEncoders.h>
+//Encoder measures 24 steps per revolution so
+//each step is (pi*48)/24 mm in length
+//which is 6.28mm in rotation of the wheel
+//which means that the robot turns roughly 0.084 radians
+//per step which is 4.8 degrees!

 //Pin definitions
 int MTR_STDBY=6;


updates

updates

--- BitController/BitController.ino
+++ BitController/BitController.ino
@@ -323,21 +323,48 @@

 void drive(double nx, double sx, double ex, double wx)
 {
+  int val_ns = 0;
+  int val_ew = 0;
   int val1 = 0;
   int val2 = 0;
   int val3 = 0;

-  //val1 = map(nx/wx, ,-255, 255);
-  //val2 = map(nx/ex, ,-255, 255);
-
-
-
+  val_ns = map(log10(nx/sx), -log10(600), log10(600), -127, 127); //S at -127, N at 127
+  val_ew = map(log10(ex/sx), -log10(600), log10(600), -127, 127); //W at -127, E at 127
+  //The summed/subtracted range of val_ns with val_ew is +/-254
+
+  if (val_ns - val_ew > 0) //Left motors
+  {
+    analogWrite(l1_motor, val_ns - val_ew); //(l1 high & l2 low, motors go forward)
+    analogWrite(l2_motor, 0);
+  }
+  else
+  {
+    analogWrite(l1_motor, 0);
+    analogWrite(l2_motor, abs(val_ns - val_ew));
+  }
+
+  if (val_ns + val_ew > 0) //Right motors
+  {
+    analogWrite(r1_motor, val_ns + val_ew);
+    analogWrite(r2_motor, 0);
+  }
+  else
+  {
+    analogWrite(r1_motor, 0);
+    analogWrite(r2_motor, abs(val_ns + val_ew));
+  }
+
+  //val1 = map(nx/ex, , , -255, 255)
+  //val2 = map(nx/wx, , , -255, 255)
+
   //north
-  if (nx <= 50) nx = 0;
-  nx = map(nx, 0, 600, 0, 255);
-  analogWrite(l1_motor, nx);
-  analogWrite(l2_motor, 0);
-  analogWrite(r1_motor, nx);
-  analogWrite(r2_motor, 0);
-}
-
+  //if (nx <= 50) nx = 0;
+  //sx = map(nx, 0, 600, 0, 255);
+  //analogWrite(l1_motor, nx);
+  //analogWrite(l2_motor, 0);
+  //analogWrite(r1_motor, nx);
+  //analogWrite(r2_motor, 0);
+
+}
+


Update wled06_usermod.ino

Update wled06_usermod.ino

--- usermods/Wemos_D1_mini+Wemos32_mini_shield/wled06_usermod.ino
+++ usermods/Wemos_D1_mini+Wemos32_mini_shield/wled06_usermod.ino
@@ -3,11 +3,11 @@
 #ifdef ARDUINO_ARCH_ESP32 //ESP32 boards
 uint8_t SCL_PIN = 22;
 uint8_t SDA_PIN = 21;
-// uint8_t RST_PIN = 16; // Uncoment for Heltec WiFi-Kit-8
 OneWire oneWire(23);
 #else //ESP8266 boards
 uint8_t SCL_PIN = 5;
 uint8_t SDA_PIN = 4;
+// uint8_t RST_PIN = 16; // Uncoment for Heltec WiFi-Kit-8
 OneWire oneWire(13);
 #endif
 //The SCL and SDA pins are defined here.


add red(), green() and blue() to blinkm example

--- examples/blinkm/blinkm.ino
+++ examples/blinkm/blinkm.ino
@@ -31,17 +31,39 @@
 #include "bitlash.h"

 byte blinkm_addr = 0;
+byte red, green, blue;

 numvar func_setaddr(void) {
 	blinkm_addr = getarg(1);
 }

 numvar func_setrgb(void) {
-	BlinkM_setRGB(blinkm_addr, getarg(1), getarg(2), getarg(3));
+	red = getarg(1);
+	green = getarg(2);
+	blue = getarg(3);
+	BlinkM_setRGB(blinkm_addr, red, green, blue);
+}
+
+numvar func_red(void) {
+	red = getarg(1);
+	BlinkM_fadeToRGB(blinkm_addr, red, green, blue);
+}
+
+numvar func_blue(void) {
+	blue = getarg(1);
+	BlinkM_fadeToRGB(blinkm_addr, red, green, blue);
+}
+
+numvar func_green(void) {
+	green = getarg(1);
+	BlinkM_fadeToRGB(blinkm_addr, red, green, blue);
 }

 numvar func_fadetorgb(void) {
-	BlinkM_fadeToRGB(blinkm_addr, getarg(1), getarg(2), getarg(3));
+	red = getarg(1);
+	green = getarg(2);
+	blue = getarg(3);
+	BlinkM_fadeToRGB(blinkm_addr, red, green, blue);
 }

 numvar func_fadetohsb(void) {
@@ -61,6 +83,9 @@
 	addBitlashFunction("fadergb", (bitlash_function) func_fadetorgb);
 	addBitlashFunction("fadehsb", (bitlash_function) func_fadetohsb);
 	addBitlashFunction("setrgb", (bitlash_function) func_setrgb);
+	addBitlashFunction("red", (bitlash_function) func_red);
+	addBitlashFunction("green", (bitlash_function) func_green);
+	addBitlashFunction("blue", (bitlash_function) func_blue);
 	addBitlashFunction("setfade", (bitlash_function) func_setfade);
 	addBitlashFunction("setaddr", (bitlash_function) func_setaddr);
 }


fix mqtt message text

fix mqtt message text

--- brew-buddy-firmware/src/brew-buddy-firmware.ino
+++ brew-buddy-firmware/src/brew-buddy-firmware.ino
@@ -163,11 +163,9 @@
   if (client.isConnected())
   {
     Particle.publish("mqtt/status", "connected");
-    bool methodSubResult = client.subscribe("$iothub/methods/#", MQTT::QOS0);
     bool msgSubResult = client.subscribe("devices/" + deviceID + "/messages/devicebound/#", MQTT::QOS0);

-    Particle.publish("matt/method-sub-result", methodSubResult ? "subscribed to hub methods" : "subscription failed");
-    Particle.publish("matt/method-sub-result", msgSubResult ? "subscribed to hub messages" : "subscription failed");
+    Particle.publish("mqtt/message-sub-result", msgSubResult ? "subscribed to hub messages" : "subscription failed");
   }
   else
   {


Update the MarqueeText example docs

Update the MarqueeText example docs

--- examples/MarqueeText/MarqueeText.ino
+++ examples/MarqueeText/MarqueeText.ino
@@ -4,7 +4,7 @@
 // Example written 16.06.2017 by Marko Oette, www.oette.info

 // Define the ChipSelect pin for the led matrix (Dont use the SS or MISO pin of your Arduino!)
-// Other pins are arduino specific SPI pins (MOSI=DIN of the LEDMatrix and CLK) see https://www.arduino.cc/en/Reference/SPI
+// Other pins are Arduino specific SPI pins (MOSI=DIN, SCK=CLK of the LEDMatrix) see https://www.arduino.cc/en/Reference/SPI
 const uint8_t LEDMATRIX_CS_PIN = 9;

 // Define LED Matrix dimensions: 32x8, 16x8, or 8x8


Calculates offsets and counter-rotates servo.

--- software/Arduino/ServoController/ServoController.ino
+++ software/Arduino/ServoController/ServoController.ino
@@ -18,6 +18,7 @@
 int j = 0;
 float runningSum = 0;
 float oldAverage;
+int servoVal = 90;
 bool int_flag = false;

 void setup() {
@@ -34,7 +35,7 @@
   oldAverage = getAverage();

   xy.attach(3); // pro mini pwm pin
-  xy.write(0); // Start at a well-defined value
+  xy.write(servoVal); // Start at a well-defined value

   MsTimer2::set(100, a);
   MsTimer2::start();
@@ -43,11 +44,14 @@

 void loop() {
   if (int_flag) {
-    runningSum -= entries[j % 10];
-    entries[j % 10] = readGyro();
-    runningSum += entries[j % 10];
+    j %= 10;
+    runningSum -= entries[j];
+    entries[j] = readGyro();
+    runningSum += entries[j];
     float newAverage = getAverage();
-    Serial.println(newAverage - oldAverage, 2); // Print drift in 100 ms
+    //Serial.println(newAverage - oldAverage, 2); // Print drift in 100 ms
+    servoVal += newAverage - oldAverage;
+    rotate(servoVal);
     oldAverage = newAverage;
     j++;
     int_flag = false;


Modifying firmware speed map.

Modifying firmware speed map.

--- firmware/communication.ino
+++ firmware/communication.ino
@@ -4,7 +4,7 @@
 UnBallSoftwareSerial serial1(15, 14);

 // Conversion from message speed to RPM
-float speedMap[8] = {-150, -100, -50, 0, 37.5, 75, 112.5, 150};
+float speedMap[8] = {-150, -125, -100, 0, 75, 100, 125, 150};

 // Flag to print communication data for debug purposes
 bool debugCommunicationFlag = false;


Update secondOrderFilter.ino

Update secondOrderFilter.ino

--- code/secondOrderFilter.ino
+++ code/secondOrderFilter.ino
@@ -13,13 +13,13 @@
 class filter
 {
   public:
-  static float coeff[5];
   float filterInput(float input);
   private:
   float output[3]={0,0,0};
   float input[3]={0,0,0};
 };
-float filter::coeff[5];
+
+static double coeff[5];

 float filter::filterInput(float Input)
 {
@@ -44,10 +44,10 @@
     double QcWarp = tan(QcRaw);
     double gain = 1 / ( 1 + sqrt2 / QcWarp + 2 / ( QcWarp * QcWarp ) );

-    filter::coeff[4] = ( 1 - sqrt2 / QcWarp + 2 / ( QcWarp * QcWarp ) ) * gain;
-    filter::coeff[3] = ( 2 - 2 * 2 / ( QcWarp * QcWarp ) ) * gain;
+    coeff[4] = ( 1 - sqrt2 / QcWarp + 2 / ( QcWarp * QcWarp ) ) * gain;
+    coeff[3] = ( 2 - 2 * 2 / ( QcWarp * QcWarp ) ) * gain;

-    filter::coeff[0] = 1 * gain;
-    filter::coeff[1] = 2 * gain;
-    filter::coeff[2] = 1 * gain;
+    coeff[0] = 1 * gain;
+    coeff[1] = 2 * gain;
+    coeff[2] = 1 * gain;
  }


Update HMClientTest.ino

Update HMClientTest.ino

--- examples/HMClientTest.ino
+++ examples/HMClientTest.ino
@@ -22,7 +22,7 @@
   hmstring_t RoofWeather;

   Homematic.setHMSystemVariable(&RoofWeather);
-  Serial.printf("Set Homematic Variable to Value : %d\n", RoofWeather.Value);
+  Serial.printf("Set Homematic Variable to Value : %s\n", RoofWeather.Value);

 }//end setup


Trying to get more stability after ST updates which break the timing. Argh.

--- water-sensor/water-sensor.ino
+++ water-sensor/water-sensor.ino
@@ -5,7 +5,8 @@
 #include "SmartThings.h"

 #define DEBUG_ENABLED      1
-#define DEBUG_RAW_ENABLED  0
+#define DEBUG_RAW_SHORT    1
+#define DEBUG_RAW_HISTORY  0
 #define SUBMIT_TO_ST       1

 #define PIN_THING_RX       3
@@ -119,6 +120,7 @@

 Queue<40> measurements;
 float lastDistance = 0;
+bool firstUpdate = true;

 int lastLedState = 0;
 unsigned long lastCheck = 0;
@@ -164,11 +166,16 @@
     if (measurements.valid())
     {
       float cm = (float)measurements.average() / US_ROUNDTRIP_CM;
+
+      if (lastDistance == 0)
+      {
+        lastDistance = cm;
+      }

-#if DEBUG_RAW_ENABLED
+#if DEBUG_RAW_SHORT
       Serial.print("Raw: ");
       Serial.print(cm);
-
+
       float diff = lastDistance - cm;

       if (diff >= 0)
@@ -181,7 +188,8 @@
       }

       Serial.print(diff);
-
+
+#if DEBUG_RAW_HISTORY
       Serial.print("  :: Last 10 :: ");

       for (int i = max(0, measurements.size() - 10); i < measurements.size(); ++i)
@@ -189,12 +197,13 @@
         Serial.print((float)measurements.values()[i] / US_ROUNDTRIP_CM);
         Serial.print(" ");
       }
-
+#endif
       Serial.println("");
 #endif

-      if (abs(lastDistance - cm) > 0) {
+      if (fabs(lastDistance - cm) > 1.5f || firstUpdate) {
         lastDistance = cm;
+        firstUpdate = false;

 #if DEBUG_ENABLED
         Serial.print("Ping: ");
@@ -223,8 +232,10 @@

         snprintf(message, sizeof(message), "level:%d", (int)cm);
         smartthing.send(message);
+
+        lastDistance = 0;
 #endif
-      }
+      }
     }

     lastCheck = time;


Remove one space

Remove one space

--- src/Weather-Station.ino
+++ src/Weather-Station.ino
@@ -187,7 +187,7 @@

     snprintf_P(datestring,
             countof(datestring),
-            PSTR("%02u/%02u/%04u_%02u:%02u:%02u "),
+            PSTR("%02u/%02u/%04u_%02u:%02u:%02u"),
             dt.Day(),
             dt.Month(),
             dt.Year(),


Updating serial read functionality

Updating serial read functionality

Changed serial data stuff to work better hopefully

--- Arduino/Mimic_LED_Controller/Mimic_LED_Controller.ino
+++ Arduino/Mimic_LED_Controller/Mimic_LED_Controller.ino
@@ -5,10 +5,8 @@
 Adafruit_NeoPixel stbdIEA = Adafruit_NeoPixel(24, 5, NEO_GRB + NEO_KHZ800);
 Adafruit_NeoPixel portIEA = Adafruit_NeoPixel(24, 6, NEO_GRB + NEO_KHZ800);
 Adafruit_NeoPixel moduleLED = Adafruit_NeoPixel(16, 7, NEO_GRB + NEO_KHZ800);
-const int ledRedPin = 13;
-const int ledBluePin = 52;
-const int ledGreenPin = 53;
-String test;
+
+String readData;

 double V1A = 0.00;
 double V1B = 0.00;
@@ -18,16 +16,13 @@
 double V2B = 0.00;
 double V4A = 0.00;
 double V4B = 0.00;
+
 String module = "unset module";
 boolean Disco = false;
 int NULLIFY = 0;

 void setup()
 {
-  pinMode(ledRedPin, OUTPUT);
-  pinMode(ledBluePin, OUTPUT);
-  pinMode(ledGreenPin, OUTPUT);
-//  Serial1.begin(9600);
   Serial.begin(9600);
   Serial.setTimeout(50);
   portIEA.begin();
@@ -43,75 +38,121 @@

 void loop()
 {
-  digitalWrite(ledRedPin, LOW);
-  digitalWrite(ledGreenPin, LOW);
-  digitalWrite(ledBluePin, LOW);
-  //wSerial1.println("-------");
-  if(Serial.available())
-  {
-    checkSerial();
-  }
-  allSet_module(moduleLED.Color(0,0,0),0);
-  //Serial1.println(module);
+  //Process any incoming serial data
+  readData = "";
+  if(Serial.available() > 0)
+  {
+    readData = Serial.readString();
+  }
+  delay(100);
+  Serial.flush();
+
+  char sz[readData.length() + 1];
+  char copy[readData.length() + 1];
+  strcpy(sz, readData.c_str());
+  char *p = sz;
+  char *str;
+  int delimeter = 0;
+  String readData2 = "";
+  Serial2.println(readData);
+
+  //Split up string into substrings separated by spaces
+  //Go through each substring and extract data
+  while((str = strtok_r(p," ",&p))!=NULL)
+  {
+    readData2 = String(str);
+    //Serial.println(readData2);
+    delimeter = readData2.indexOf('=');
+    if(readData2.substring(0,delimeter)=="Disco")
+    {
+      Disco = true;
+    }
+    else if (readData2.substring(0, delimeter) == "NULLIFY")
+    {
+      NULLIFY = int((readData2.substring(delimeter + 1)).toFloat());
+    }
+    if(readData2.substring(0,delimeter)=="V2A")
+    {
+      V2A = (readData2.substring(delimeter+1)).toFloat();
+    }
+    else if(readData2.substring(0,delimeter)=="V2B")
+    {
+      V2B = (readData2.substring(delimeter+1)).toFloat();
+    }
+    else if(readData2.substring(0,delimeter)=="V4A")
+    {
+      V4A = (readData2.substring(delimeter+1)).toFloat();
+    }
+    else if(readData2.substring(0,delimeter)=="V4B")
+    {
+      V4B = (readData2.substring(delimeter+1)).toFloat();
+    }
+    else if(readData2.substring(0,delimeter)=="V1A")
+    {
+      V1A = (readData2.substring(delimeter+1)).toFloat();
+    }
+    else if(readData2.substring(0,delimeter)=="V1B")
+    {
+      V1B = (readData2.substring(delimeter+1)).toFloat();
+    }
+    else if(readData2.substring(0,delimeter)=="V3A")
+    {
+      V3A = (readData2.substring(delimeter+1)).toFloat();
+    }
+    else if(readData2.substring(0,delimeter)=="V3B")
+    {
+      V3B = (readData2.substring(delimeter+1)).toFloat();
+    }
+    //module Selection
+    else if(readData2.substring(0,delimeter)=="ISS")
+    {
+      module = String((readData2.substring(delimeter+1)));
+    }
+  }
+
+  module.trim(); //trim whitespace off serial data
+
   if(module == "SM")
   {
     moduleLED.setPixelColor(0, moduleLED.Color(255,255,255));
-    moduleLED.show();
-    //Serial1.println("SM");
   }
   else if(module == "FGB")
   {
     moduleLED.setPixelColor(1, moduleLED.Color(255,255,255));
-    moduleLED.show();
-    //Serial1.println("FGB");
   }
   else if(module == "Node1")
   {
     moduleLED.setPixelColor(2, moduleLED.Color(255,255,255));
-    moduleLED.show();
-    //Serial1.println("Node1");
   }
   else if(module == "Node2")
   {
     moduleLED.setPixelColor(6, moduleLED.Color(255,255,255));
-    moduleLED.show();
-    //Serial1.println("Node2");
   }
   else if(module == "Node3")
   {
     moduleLED.setPixelColor(4, moduleLED.Color(255,255,255));
-    moduleLED.show();
-    //Serial1.println("Node3");
   }
   else if(module == "AL")
   {
     moduleLED.setPixelColor(3, moduleLED.Color(255,255,255));
-    moduleLED.show();
-    //Serial1.println("AL");
   }
   else if(module == "USL")
   {
     moduleLED.setPixelColor(5, moduleLED.Color(255,255,255));
-    moduleLED.show();
-    //Serial1.println("USL");
   }
   else if(module == "Col")
   {
     moduleLED.setPixelColor(7, moduleLED.Color(255,255,255));
-    moduleLED.show();
-    //Serial1.println("Col");
   }
   else if(module == "JEM")
   {
     moduleLED.setPixelColor(8, moduleLED.Color(255,255,255));
-    moduleLED.show();
-    //Serial1.println("JEM");
   }
   else
   {
     allSet_module(moduleLED.Color(0,0,0),0);
-    moduleLED.show();
-  }
+  }
+  moduleLED.show();

   if(V2A < 151.5)
   {
@@ -365,80 +406,6 @@
     theaterChaseRainbow_stbdIEA(50);
   }
   Disco = false;
-}
-void checkSerial()
-{
-  digitalWrite(ledBluePin, HIGH);
-  test = "";
-
-  while(Serial.available() > 0)
-  {
-    test = Serial.readStringUntil('\n');
-    //test = Serial.readString();
-  }
-  //Serial.println(test);
-
-  char sz[test.length() + 1];
-  char copy[test.length() + 1];
-  strcpy(sz, test.c_str());
-  char *p = sz;
-  char *str;
-  int delimeter = 0;
-  String test2 = "";
-
-  while((str = strtok_r(p," ",&p))!=NULL)
-  {
-    test2 = String(str);
-    delimeter = test2.indexOf('=');
-    if(test2.substring(0,delimeter)=="Disco")
-    {
-      Disco = true;
-    }
-    else if (test2.substring(0, delimeter) == "NULLIFY")
-    {
-      NULLIFY = int((test2.substring(delimeter + 1)).toFloat());
-      //Serial.println(" Got the NULL cmd over Serial...");
-    }
-    if(test2.substring(0,delimeter)=="V2A")
-    {
-      V2A = (test2.substring(delimeter+1)).toFloat();
-    }
-    else if(test2.substring(0,delimeter)=="V2B")
-    {
-      V2B = (test2.substring(delimeter+1)).toFloat();
-    }
-    else if(test2.substring(0,delimeter)=="V4A")
-    {
-      V4A = (test2.substring(delimeter+1)).toFloat();
-    }
-    else if(test2.substring(0,delimeter)=="V4B")
-    {
-      V4B = (test2.substring(delimeter+1)).toFloat();
-    }
-    else if(test2.substring(0,delimeter)=="V1A")
-    {
-      V1A = (test2.substring(delimeter+1)).toFloat();
-    }
-    else if(test2.substring(0,delimeter)=="V1B")
-    {
-      V1B = (test2.substring(delimeter+1)).toFloat();
-    }
-    else if(test2.substring(0,delimeter)=="V3A")
-    {
-      V3A = (test2.substring(delimeter+1)).toFloat();
-    }
-    else if(test2.substring(0,delimeter)=="V3B")
-    {
-      V3B = (test2.substring(delimeter+1)).toFloat();
-    }
-    //module Selection
-    else if(test2.substring(0,delimeter)=="ISS")
-    {
-      //Serial1.println("----Module!------");
-      module = (test2.substring(delimeter+1));
-    }
-  }
-//  Serial1.println();
 }

 //module led functions


COH-77: simple serial status for REV9/relay

--- COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
+++ COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
@@ -1,6 +1,6 @@
 // Uncomment exactly one of the following CONFIG_... lines to select which board is being built for.
-#define CONFIG_Trial2013Winter_Round2_CC1HUB // REV2 cut4 as CC1 hub.
-//#define CONFIG_REV9 // REV9 as CC1 relay, cut 2 of the board.
+//#define CONFIG_Trial2013Winter_Round2_CC1HUB // REV2 cut4 as CC1 hub.
+#define CONFIG_REV9 // REV9 as CC1 relay, cut 2 of the board.

 #include <Arduino.h>
 #include <Wire.h>
@@ -51,7 +51,7 @@
 bool pollIO(bool force = false);

 // Sends a short 1-line CRLF-terminated status report on the serial connection (at 'standard' baud).
-void serialStatusReport() { OTV0P2BASE::serialPrintlnAndFlush(F("=")); }
+void serialStatusReport();

 // Reset CLI active timer to the full whack before it goes inactive again (ie makes CLI active for a while).
 // Thread-safe.
@@ -906,11 +906,47 @@
   OTRadioLink::OTRadioChannelConfig(OTRFM23BLink::StandardRegSettingsOOK5000, true, false, true, false, false, true),
   };

+// Sends a short 1-line CRLF-terminated status report on the serial connection (at 'standard' baud).
+void serialStatusReport()
+  {
+#if !defined(ENABLE_FHT8VSIMPLE)
+  OTV0P2BASE::serialPrintlnAndFlush(F("="));
+#else
+  TemperatureC16.read(); // Force read as not polled in main loop for COHEAT...
+  const bool neededWaking = OTV0P2BASE::powerUpSerialIfDisabled<V0P2_UART_BAUD>(); // FIXME
+  // Stats line starts with distinguished marker character '='.
+  Serial.print((char) OTV0P2BASE::SERLINE_START_CHAR_STATS);
+  Serial.print(NominalRadValve.get()); Serial.print('%'); // Target valve position.
+  const int temp = TemperatureC16.get();
+  Serial.print('@'); Serial.print(temp >> 4); Serial.print('C'); // Unrounded whole degrees C.
+      Serial.print(temp & 0xf, HEX); // Show 16ths in hex.
+  // Print optional house code section if codes set.
+  const uint8_t hc1 = FHT8V.nvGetHC1();
+  if(hc1 != 255)
+    {
+    Serial.print(F(";HC"));
+    Serial.print(hc1);
+    Serial.print(' ');
+    Serial.print(FHT8V.nvGetHC2());
+    if(!FHT8V.isInNormalRunState())
+      {
+      Serial.print(' ');
+      Serial.print('s'); // Indicate syncing with trailing lower-case 's' in field...
+      }
+    }
+  // Terminate line.
+  Serial.println();
+  // Ensure that all text is sent before this routine returns, in case any sleep/powerdown follows that kills the UART.
+  OTV0P2BASE::flushSerialSCTSensitive();
+  if(neededWaking) { OTV0P2BASE::powerDownSerial(); }
+#endif
+  }
+
 // Handle CLI extension commands.
 // Commands of form:
 //   +EXT .....
 // where EXT is the name of the extension, usually 3 letters.
-
+//
 // It is acceptable for extCLIHandler() to alter the buffer passed,
 // eg with strtok_t().
 static bool extCLIHandler(Print *const p, char *const buf, const uint8_t n)


COH-78: WIP

COH-78: WIP

--- COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
+++ COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
@@ -878,7 +878,7 @@
   // TODO: filter for only this unit address/housecode as FHT8V.getHC{1,2}() are thread-safe.
 #else
   // Expect secure frame with 2-byte ID and empty body.
-  if((buflen < 29) || ((0x80|OTRadioLink::FTp2_CC1PollAndCmd) != buf[0])) { return(false); }
+  if((buflen < 28) || ((0x80|OTRadioLink::FTp2_CC1PollAndCmd) != buf[0])) { return(false); }
   // TODO: filter for only this unit address/housecode as FHT8V.getHC{1,2}() are thread-safe.
 #endif // ENABLE_OTSECUREFRAME_ENCODING_SUPPORT
   return(true); // Accept message.
@@ -894,7 +894,7 @@
   // TODO: filter for only associated relay address/housecodes.
 #else
   // Expect secure frame with 2-byte ID and 32-byte encrypted body.
-  if(buflen < 63) { return(false); }
+  if(buflen < 60) { return(false); }
   const uint8_t t = buf[0];
   if(((0x80|OTRadioLink::FTp2_CC1Alert) != t) && ((0x80|OTRadioLink::FTp2_CC1PollResponse) != t)) { return(false); }
   // TODO: filter for only associated relay address/housecodes.


Fix negative values, such as temperature.

--- examples/T3_ILI9341_display/T3_ILI9341_display.ino
+++ examples/T3_ILI9341_display/T3_ILI9341_display.ino
@@ -70,7 +70,7 @@
 } obd_unit;

 typedef struct{
-  uint32_t old_value;
+  int32_t old_value;
   elapsedMillis timesince;
 } obd_unit_state;


Print button pressed time, if button released

--- examples/Test_InputDebounce/Test_InputDebounce.ino
+++ examples/Test_InputDebounce/Test_InputDebounce.ino
@@ -31,6 +31,7 @@
 void loop()
 {
   static unsigned int buttonTest_StateOnCount = 0;
+  static unsigned int buttonTest_OnTimeLast = 0;

   unsigned long now = millis();

@@ -38,6 +39,7 @@
   unsigned int buttonTest_OnTime = buttonTest.process(now);

   if(buttonTest_OnTime) {
+    buttonTest_OnTimeLast = buttonTest_OnTime;
     unsigned int count = buttonTest.getStateOnCount();
     if(buttonTest_StateOnCount != count) {
       buttonTest_StateOnCount = count;
@@ -53,5 +55,13 @@
   }
   else {
     digitalWrite(pinLED, LOW); // turn the LED off
+    if(buttonTest_OnTimeLast) {
+      Serial.print("LOW (");
+      Serial.print(buttonTest_OnTimeLast);
+      Serial.println("ms)");
+      buttonTest_OnTimeLast = 0;
+    }
   }
+
+  delay(1); // [ms]
 }


small fixes and fine tunings

small fixes and fine tunings

also to reduse memory foot print, if too much memory used
serial communication with esp will fail!

--- greenhouse/greenhouse.ino
+++ greenhouse/greenhouse.ino
@@ -13,6 +13,7 @@
 uint8_t buttonState = LOW;
 uint8_t alertLevel  = 30;
 uint8_t humLevel = 80;
+uint8_t wifiCheckCntr = 0;
 boolean hatchOpen = false;

 //state handling
@@ -22,7 +23,6 @@
 byte state = STATE_INITIAL;

 //analog pin assignments
-const byte tempSensorPin = 0;
 const byte tempPotPin    = 0;
 const byte humPotPin     = 1;

@@ -54,7 +54,6 @@
 String homePageArray[HOME_PAGE_STATIC_ARR_SZ]={
   "HTTP/1.1 200 OK\r\n",
   "Connection: close\r\n",
-//  "Refresh: 120\r\n",
 //  "Content-Length:",
   "Content-Type: text/html; charset=UTF-8\r\n\r\n",
   "<!DOCTYPE html PUBLIC>\r\n",
@@ -62,10 +61,10 @@
 //  "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\r\n",
   "\r\n",
 //  "\r\n",
-//  "<title>Vilikkaankujan Kasvihuone</title>\r\n",
+//  "<title>The Greenhouse</title>\r\n",
 //  "\r\n",
   "\r\n",
-  "
Kasvihuone
\r\n",
+  "
Greenhouse
\r\n",
   "\r\n",
   "\r\n\r\n",
 };
@@ -136,7 +135,7 @@

   servo1.attach(servo1Pin); // Attaches the servo on pin 14 to the servo1 object
   servo1.write(180);  // Put servo1 at home position
-  delay(1000);
+  delay(2000);
   servo1.detach();

   // Open serial communications and wait for port to open:
@@ -146,22 +145,21 @@
   Serial.println("\nStarting up...");
   Serial.print("Dht11 Lib version ");
   Serial.println(Dht11::VERSION);
-  lcd.begin(16, 2); // Set the display to 16 columns and 2 rows
   analogReference(INTERNAL);
   pinMode(buttonPin, INPUT);
   pinMode(wifiResetPin, OUTPUT);
   digitalWrite (wifiResetPin, HIGH);
-
+
+  lcd.begin(16, 2); // Set the display to 16 columns and 2 rows
   lcd.clear();
   lcd.setCursor(0,0);

-
   lcd.print("Setting up Wifi.");
   setupWifi();

   lcd.setCursor(0,0);
   lcd.print("Wifi is set up.");
-  delay(1000);
+  delay(5000);
   lcd.clear();

   state = STATE_INITIAL;
@@ -189,9 +187,9 @@
         while (*pb != ':') pb++;
         pb++;
         if (strncmp(pb, "GET / ", 6) == 0) {
-          Serial.println(buffer);
-          Serial.print( "get Status from ch:" );
-          Serial.println(ch_id);
+          //Serial.println(buffer);
+          //Serial.print( "get Status from ch:" );
+          //Serial.println(ch_id);
           delay(100);
           clearSerialBuffer();
           homepage(ch_id);
@@ -200,6 +198,15 @@
     }
   }
   clearBuffer();
+  if (!(++wifiCheckCntr)){
+    espSerial.println("AT+GMR\r");
+    if(espSerial.find("OK")){
+      Serial.println("Wifi OK");
+    }else{
+      Serial.println("Wifi NOK, restart WIfi");
+      setupWifi();
+    }
+  }
   delay(500);
 }

@@ -219,26 +226,43 @@
         }
     }
     else{
-      Serial.println("sending data failed...");
+      Serial.println("send data failed!");
     }
   }else{
-    Serial.println("D'OH! Connection failure!");
+    Serial.println("D'OH! Conn. fail!");
     setupWifi();
   }
   //esp seems wery slow at times, so just in case...
   delay(500);
 }

+char *get_temp_warn()
+{
+  if (tempSensorValue <=5) return "WARN!";
+  if (tempSensorValue < 15 && tempSensorValue >5) return "cold";
+  if (tempSensorValue < 20 && tempSensorValue >14) return "chilly";
+  if (tempSensorValue < 31 && tempSensorValue >19) return "OK";
+  if (tempSensorValue > 30) return "HOT!";
+  return "";
+}
+
 void homepage(uint8_t ch_id) {
   //create dynamic content first, so that we get the length.
-  String tempstr = "
Lämpötila:";
+  String tempstr = "
Temperature:";
   tempstr += tempSensorValue;
-  tempstr += "°C
\r\n";
-  String humstr = "
Kosteus:";
+  tempstr += "°C ";
+  tempstr += get_temp_warn();
+  tempstr += "
min:";
+  tempstr += minC;
+  tempstr += " max:";
+  tempstr += maxC;
+  tempstr += " ";
+  tempstr += "
\r\n";
+  String humstr = "
Hum:";
   humstr += humSensorValue;
   humstr += "%
\r\n";
-  String windowstr = "
Ikkuna on ";
-  windowstr += ((hatchOpen)?"Auki
\r\n":"Kiinni
\r\n");
+  String windowstr = "
Window is ";
+  windowstr += ((hatchOpen)?"Open
\r\n":"Closed
\r\n");
   //count dynamic lengts together and Set Content Len in header
   String hdrContLen = "Content-Length: ";
   hdrContLen += String((tempstr.length() +
@@ -247,7 +271,7 @@
                         staticContLen), DEC);
   hdrContLen += "\r\n";

-  Serial.println("Create HomePage");
+  Serial.println("Show page");
   Serial.println(hdrContLen);
   sendToClient(&homePageArray[0], ch_id);
   sendToClient(&homePageArray[1], ch_id);
@@ -257,23 +281,14 @@
   sendToClient(&homePageArray[4], ch_id);
   sendToClient(&homePageArray[5], ch_id);
   sendToClient(&homePageArray[6], ch_id);
-  /*
-  sendToClient(&homePageArray[7], ch_id);
-  sendToClient(&homePageArray[8], ch_id);
-  sendToClient(&homePageArray[9], ch_id);
-  sendToClient(&homePageArray[10], ch_id);
-  sendToClient(&homePageArray[11], ch_id);
-  sendToClient(&homePageArray[12], ch_id);
-  sendToClient(&homePageArray[13], ch_id);*/
   //dynamic part
   sendToClient(&tempstr, ch_id);
   sendToClient(&humstr, ch_id);
   sendToClient(&windowstr, ch_id);
   //end of html page
   sendToClient(&homePageArray[7], ch_id);
-  sendToClient(&homePageArray[8], ch_id);
-
-  Serial.println("HomePage End.");
+  sendToClient(&homePageArray[8], ch_id);
+  Serial.println("Show done");
 }

 void clearSerialBuffer(void) {
@@ -323,11 +338,11 @@
     case Dht11::OK:
       humSensorValue = sensor.getHumidity();
       tempSensorValue = sensor.getTemperature();
-      Serial.print("\nTemperature (C): ");
-      Serial.print(tempSensorValue);
-      Serial.print("\nHumidity (%): ");
-      Serial.print(humSensorValue);
-      Serial.println();
+      //Serial.print("\nTemperature (C): ");
+      //Serial.print(tempSensorValue);
+      //Serial.print("\nHumidity (%): ");
+      //Serial.print(humSensorValue);
+      //Serial.println();
       break;
     case Dht11::ERROR_CHECKSUM:
       Serial.println("Checksum error");
@@ -345,16 +360,16 @@
   delay(10);
   tempLimitPotValue = analogRead(tempPotPin); // Read the pot value
   tempLimitPotValue = map(tempLimitPotValue, 0, 1023, 20, 40); // Map the values from 20 to 40 degrees
-  Serial.print("tp:");
-  Serial.println(tempLimitPotValue);
+  //Serial.print("tp:");
+  //Serial.println(tempLimitPotValue);

   delay(10);
   humLimitPotValue = analogRead(humPotPin); // Read the pot value
   delay(10);
   humLimitPotValue = analogRead(humPotPin); // Read the pot value
   humLimitPotValue = map(humLimitPotValue, 0, 1023, 20, 100); // Map the values from 20 to 100%
-  Serial.print("hp:");
-  Serial.println(humLimitPotValue);
+  //Serial.print("hp:");
+  //Serial.println(humLimitPotValue);

   buttonState = digitalRead(buttonPin); // Check for button press
 }
@@ -369,29 +384,30 @@

 void stateWorking()
 {
-  celsius(tempSensorValue);
+
+  writeTempAndHumToLcd();

   if (!hatchOpen && (tempSensorValue >= alertLevel ||( humSensorValue >= humLevel && tempSensorValue >= 20))){
-    Serial.print("Alert! over ");
-    Serial.print(alertLevel);
-    Serial.print("degrees, open hatch\n");
+    //Serial.print("Alert! over ");
+    //Serial.print(alertLevel);
+    //Serial.print("degrees, open hatch\n");
     turnServo(90);
     hatchOpen=true;
   }
-  if (hatchOpen && tempSensorValue <= alertLevel-2 && (humSensorValue <= humLevel) || tempSensorValue <= 20){
-    Serial.print("Alert! less than ");
-    Serial.print(alertLevel);
-    Serial.print("(");
-    Serial.print(tempSensorValue);
-    Serial.print(") degrees, close hatch\n");
+  if (hatchOpen && ((tempSensorValue <= alertLevel-2 && humSensorValue <= humLevel) || tempSensorValue <= 20)){
+    //Serial.print("Alert! less than ");
+    //Serial.print(alertLevel);
+    //Serial.print("(");
+    //Serial.print(tempSensorValue);
+    //Serial.print(") degrees, close hatch\n");
     turnServo(180);
     hatchOpen=false;
   }
 }

-void celsius(float deg_cels) {
+void writeTempAndHumToLcd() {
   lcd.setCursor(0,0);
-  int temp = (int)deg_cels; // Convert to C
+  int temp = (int)tempSensorValue;
   lcd.print(temp);
   lcd.write(B11011111); // Degree symbol
   lcd.print("C ");
@@ -416,6 +432,7 @@
 }

 void displaySetup() {
+  lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("T:");
   lcd.print(tempLimitPotValue);


added status leds to arduino sketch

added status leds to arduino sketch

--- device/include/arduino_i2c_dmx/arduino_i2c_dmx.ino
+++ device/include/arduino_i2c_dmx/arduino_i2c_dmx.ino
@@ -9,6 +9,9 @@
 #define RGB_IDLE 0xF1
 #define RGB_TEST 0xF2
 #define RGB_TRAN 0xF3
+
+#define LED_1 5
+#define LED_2 3

 byte state = RGB_IDLE;

@@ -24,6 +27,9 @@
   Wire.begin( RGB_ADDR );                // join i2c bus with address #4
   Wire.onReceive(receiveEvent);
   Wire.onRequest(requestEvent);
+
+  pinMode(LED_1, OUTPUT);
+  pinMode(LED_2, OUTPUT);

   Serial.begin(9600);
 }
@@ -42,6 +48,8 @@
 // this function is registered as an event, see setup()
 void receiveEvent(int num_bytes)
 {
+  digitalWrite(LED_1, HIGH);
+
   Serial.print("data received, #bytes: ");
   Serial.print(num_bytes);
   Serial.println("");
@@ -59,6 +67,7 @@
       default: state = RGB_IDLE; break;
     }

+    digitalWrite(LED_1, LOW);
     return;
   }

@@ -82,10 +91,14 @@

     writeDmxValues();
   }
+
+  digitalWrite(LED_1, LOW);
 }

 void requestEvent()
 {
+  digitalWrite(LED_2, HIGH);
+
   if( state == RGB_TRAN )
   {
     //return the current rgb values
@@ -99,6 +112,8 @@
     mode_test();
     Wire.write( state );
   }
+
+  digitalWrite(LED_2, LOW);
 }

 void writeDmxValues()