Add external stops support. (#46)

Add external stops support. (#46)

* Add external stops and modify code to stop robot when engaged.

--- Arduino/victoria_teensy_ros_node/victoria_teensy_ros_node.ino
+++ Arduino/victoria_teensy_ros_node/victoria_teensy_ros_node.ino
@@ -39,6 +39,11 @@
 #include <victoria_sensor_msgs/IMURaw.h>

 // Teensy pin definitions
+const int FOB_STOP_1_PIN(2);       // Teensy digital pin 2
+const int FOB_STOP_2_PIN(3);       // Teensy digital pin 3
+const int FOB_STOP_3_PIN(4);       // Teensy digital pin 4
+const int FOB_STOP_4_PIN(5);       // Teensy digital pin 5
+const int E_STOP_PIN(6);           // Teensy digital pin 6
 const int BLINK_PIN(13);           // Teensy digital pin 13
 const int ENCODER_LEFT_PIN_1(29);  // Teensy digital pin 29
 const int ENCODER_LEFT_PIN_2(30);  // Teensy digital pin 30
@@ -68,6 +73,13 @@
 double motor_left_speed;
 double motor_right_speed;

+// External stop state, false if no intervention required.
+bool external_stop(false);
+
+// Fob mode, 0 indicates no fobs should be checked. 1-4
+// indicates which fob to check.
+byte fob_mode(0);
+
 // Victoria configuration
 double ticks_per_radian;
 double track_radius;  // in meters
@@ -106,7 +118,7 @@
 // to stop robot activity
 double cmd_vel_timeout_threshold;
 ros::Time last_cmd_vel_time;
-bool cmd_vel_timeout_stop = false; // Set to true if time out threshold has been exceeded
+bool cmd_vel_timeout_exceeded(false); // Will be set to true if time out threshold has been exceeded
 void cmdVelCallback(const geometry_msgs::Twist& twist_msg);
 ros::Subscriber<geometry_msgs::Twist> ros_cmd_vel_sub("cmd_vel", cmdVelCallback);

@@ -241,11 +253,14 @@
   ros_bumper_left_msg.header.frame_id = "/bumper_left";
   ros_bumper_right_msg.header.frame_id = "/bumper_right";
   last_cmd_vel_time = current_time;
+  cmd_vel_timeout_exceeded = false;
   last_encoder_read_time = current_time;
   encoder_left_pos = 0;
   encoder_right_pos = 0;
   motor_left_speed = 0.0;
   motor_right_speed = 0.0;
+  external_stop = false;
+  fob_mode = 0;
   reference_wl = 0.0;
   reference_wr = 0.0;
   pose.x = 0.0;
@@ -257,6 +272,9 @@

   ros::Time current_time = ros_nh.now();

+  // Check for external stop intervention.
+  external_stop = checkEStop() || checkFobStop(fob_mode);
+
   // Update any timer callbacks
   timer.update();

@@ -264,9 +282,40 @@
   ros_nh.spinOnce();

   // If no cmd_vel messages withing threshold time, something is wrong, stop the robot.
-  cmd_vel_timeout_stop = (current_time.toSec() - last_cmd_vel_time.toSec()) > cmd_vel_timeout_threshold;
-  if (cmd_vel_timeout_stop) {
-    setReferenceVelocity(0, 0);
+  cmd_vel_timeout_exceeded = (current_time.toSec() - last_cmd_vel_time.toSec()) > cmd_vel_timeout_threshold;
+}
+
+/**
+ * Checks the state input for the estop control.
+ */
+bool checkEStop(void) {
+  return (digitalRead(E_STOP_PIN) == LOW);
+}
+
+/**
+ * Checks the state of the input for the given
+ * fob stop.
+ */
+bool checkFobStop(byte fob_stop_to_check) {
+  if (fob_mode != fob_stop_to_check) {
+    return false;
+  }
+
+  switch(fob_stop_to_check) {
+    case 1:
+      return (digitalRead(FOB_STOP_1_PIN) == LOW);
+
+    case 2:
+      return (digitalRead(FOB_STOP_2_PIN) == LOW);
+
+    case 3:
+      return (digitalRead(FOB_STOP_3_PIN) == LOW);
+
+    case 4:
+      return (digitalRead(FOB_STOP_4_PIN) == LOW);
+
+    default:
+      return false;
   }
 }

@@ -291,6 +340,12 @@
 }

 void doMotorController(void) {
+
+  // If cmd vel timeout or external stop, stop the motors.
+  if (cmd_vel_timeout_exceeded || external_stop) {
+    setReferenceVelocity(0, 0);
+  }
+
   // Get the current wheel angular velocity
   double sensed_wl = getAngularVelocityFromSamples(samples_wl);
   double sensed_wr = getAngularVelocityFromSamples(samples_wr);
@@ -632,6 +687,7 @@
   teensy_debug_msg.motor_speed_left = motor_left_speed;
   teensy_debug_msg.motor_speed_right = motor_right_speed;
   teensy_debug_msg.last_cmd_vel_time = last_cmd_vel_time;
+  teensy_debug_msg.cmd_vel_timeout_exceeded = cmd_vel_timeout_exceeded;
   teensy_debug_msg.encoder_left = encoder_left_pos;
   teensy_debug_msg.encoder_right = encoder_right_pos;
   teensy_debug_msg.last_encoder_read_time = last_encoder_read_time;
@@ -639,6 +695,12 @@
   teensy_debug_msg.w_right = getAngularVelocityFromSamples(samples_wr);
   teensy_debug_msg.bumper_left = analogRead(BUMPER_LEFT_PIN);
   teensy_debug_msg.bumper_right = analogRead(BUMPER_RIGHT_PIN);
+  teensy_debug_msg.e_stop = checkEStop();
+  teensy_debug_msg.fob_mode = fob_mode;
+  teensy_debug_msg.fob_stop_1 = checkFobStop(1);
+  teensy_debug_msg.fob_stop_2 = checkFobStop(2);
+  teensy_debug_msg.fob_stop_3 = checkFobStop(3);
+  teensy_debug_msg.fob_stop_4 = checkFobStop(4);
   ros_teensy_debug_pub.publish(&teensy_debug_msg);
 }


Allow subsequent uploads without requiring Arduino to be reset.

--- Programmer/Programmer.ino
+++ Programmer/Programmer.ino
@@ -150,7 +150,6 @@
   SPI.setBitOrder(MSBFIRST);
   SPI.setDataMode(SPI_MODE0);
   SPI.setClockDivider(SPI_CLOCK_DIV4);
-  SPI.begin();

   // Initialise control pins
   pinMode(PROG, OUTPUT);
@@ -160,8 +159,15 @@
   pinMode(_FCSN_, OUTPUT);
   digitalWrite(_FCSN_, HIGH);

+}
+
+
+void loop() {
+
   Serial.println("READY");
   while (!Serial.find("GO\n"));
+
+  SPI.begin();

   // Put nRF24LE1 into programming mode
   digitalWrite(PROG, HIGH);
@@ -409,14 +415,10 @@
   delay(10);
   digitalWrite(_RESET_, HIGH);

+  SPI.end();
+
   Serial.println("DONE");
-}
-
-
-
-void loop() {
-  // Do nothing
-  delay(1000);
+
 }

 int ParseHexRecord(struct hexRecordStruct * record, char * inputRecord, int inputRecordLen){


+) arduino works!!!

+) arduino works!!!

--- arduino/binary_clock.ino
+++ arduino/binary_clock.ino
@@ -4,44 +4,71 @@
  * developed by Sergey Markelov (11/04/2013)
  */

-#include <clock.h>
 #include <clock_main.h>

-#define P1    2
-#define P2    3
-#define P3    4
-#define P4    5
-#define P5    6
-#define P6    7
-#define P7    8
-#define P8    9
-#define PA   10
-#define PB   11
-#define PC   12
-#define PD   13
-#define PE   A0
-#define PF   A1
-#define PG   A2
-#define PH   A3
+//
+// P1 -> 74HC595 [Q0]  \
+// P2 -> 74HC595 [Q1]   \
+// P3 -> 74HC595 [Q2]    \
+// P4 -> 74HC595 [Q3]     \
+// P5 -> 74HC595 [Q4]     /   1st Shift Register
+// P6 -> 74HC595 [Q5]    /      Columns
+// P7 -> 74HC595 [Q6]   /
+// P8 -> 74HC595 [Q7]  /
+//
+// PA -> 74HC595 [Q0]  \
+// PB -> 74HC595 [Q1]   \
+// PC -> 74HC595 [Q2]    \
+// PD -> 74HC595 [Q3]     \
+// PE -> 74HC595 [Q4]     /   2st Shift Register
+// PF -> 74HC595 [Q5]    /      Rows
+// PG -> 74HC595 [Q6]   /
+// PH -> 74HC595 [Q7]  /
+//

-#define BUTTON_1_PIN 1
-#define BUTTON_2_PIN 2
+#define DUTY_CYCLE_MILLIS 15
+
+#define BUTTON_1_PIN 5
+#define BUTTON_2_PIN 4
 #define BUTTON_3_PIN 3
-#define BUTTON_4_PIN 4
+#define BUTTON_4_PIN 2

-static const int cols[] = { P1, P2, P3, P4, P5, P6, P7, P8 };
-static const int rows[] = { PA, PB, PC, PD, PE, PF, PG, PH };
+// Pin connected to ST_CP of 74HC595
+#define LATCH_PIN 8
+// Pin connected to SH_CP of 74HC595
+#define CLOCK_PIN 12
+// Pin connected to DS of 74HC595
+#define DATA_PIN  11
+
+static byte ScreenColumns[CLOCK_PATTERN_SIZE] = { ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0 };
+
+// static const int cols[] = { P1, P2, P3, P4, P5, P6, P7, P8 };
+// static const int rows[] = { PA, PB, PC, PD, PE, PF, PG, PH };
 static const int buttons[] = { BUTTON_1_PIN, BUTTON_2_PIN, BUTTON_3_PIN, BUTTON_4_PIN };
 static ClockState clockState;
+
+static void display()
+{
+    for(size_t i = 0; i < countof(ScreenColumns); ++i) {
+        // Take the latchPin low so the LEDs don't change while you're sending in bits:
+        digitalWrite(LATCH_PIN, LOW);
+
+        // Shift out the bits
+        // First shift rows, then columns, because shift register for rows comes after columns
+        shiftOut(DATA_PIN, CLOCK_PIN, MSBFIRST, 1 << i);
+        shiftOut(DATA_PIN, CLOCK_PIN, MSBFIRST, ScreenColumns[i]);
+
+        // Take the latch pin high so the LEDs will light up:
+        digitalWrite(LATCH_PIN, HIGH);
+    }
+}

 static int arduino_setPixel(int x, int y, Bool turnOn)
 {
     if(turnOn) {
-        digitalWrite(cols[x % countof(cols)], LOW);
-        digitalWrite(rows[y / countof(rows)], HIGH);
+        ScreenColumns[y] &= ~(1 << x);
     } else {
-        digitalWrite(cols[x % countof(cols)], HIGH);
-        digitalWrite(rows[y / countof(rows)], LOW);
+        ScreenColumns[y] |= 1 << x;
     }

     return 0;
@@ -53,24 +80,44 @@
     return 0;
 }

+static int arduino_clearScreen()
+{
+    memset(&ScreenColumns, 0xFF, sizeof(ScreenColumns));
+
+    return 0;
+}
+
+static int arduino_initDateTime(DateTime *dt)
+{
+    memset(dt, 0, sizeof(DateTime));
+
+    dt->year   = 2013;
+    dt->month  = DECEMBER;
+    dt->day    = 10;
+    dt->hour   = 9;
+    dt->minute = 17;
+    dt->second = 41;
+
+    return 0;
+}
+
 void setup()
 {
     clock_extern_setPixel     = arduino_setPixel;
     clock_extern_uptimeMillis = arduino_uptimeMillis;
-//     clock_extern_initDateTime = emulator_initDateTime;
-//     clock_extern_clearScreen  = emulator_clearScreen;
+    clock_extern_initDateTime = arduino_initDateTime;
+    clock_extern_clearScreen  = arduino_clearScreen;
+
+    // Set pins to output so you can control the shift register
+    pinMode(LATCH_PIN, OUTPUT);
+    pinMode(CLOCK_PIN, OUTPUT);
+    pinMode(DATA_PIN,  OUTPUT);

     for(size_t i = 0; i < countof(buttons); ++i) {
         pinMode(buttons[i], INPUT);
     }
-    for(size_t i = 0; i < countof(cols); ++i) {
-        pinMode(cols[i], OUTPUT);
-    }
-    for(size_t i = 0; i < countof(rows); ++i) {
-        pinMode(rows[i], OUTPUT);
-    }
+
     clock_clearScreen();
-
     Call(clock_init(&clockState));
 }

@@ -80,4 +127,7 @@
         Call(clock_button_press( &(clockState.buttons), i, digitalRead(buttons[i]) == HIGH ? TRUE : FALSE));
     }
     Call(clock_update(&clockState));
+
+    display();
+    delay(DUTY_CYCLE_MILLIS);
 }


Forgot to save a file with the last commit.

--- src/solitaire/solitaire.ino
+++ src/solitaire/solitaire.ino
@@ -94,7 +94,7 @@
     // Tableau
     for (int i = 0; i < 7; i++) {
       for (int j = 0; j < tableau[i].getCardCount(); j++) {
-        drawCard(tableau[i].x, tableau[i].y + 2 * j, tableau[i].getCard(tableau[i].getCardCount() - i - 1));
+        drawCard(tableau[i].x, tableau[i].y + 2 * j, tableau[i].getCard(tableau[i].getCardCount() - j - 1));
       }
     }


Refactor drawEllipse() in terms of moveToPoint()

--- dee-oh-tee.ino
+++ dee-oh-tee.ino
@@ -86,26 +86,16 @@

   for (int targetDegrees = startX; targetDegrees <= endX; targetDegrees += xDegreesPerCycle) {
     const int targetPanServoDegrees = convertNormalizedAngleToServoAngle(targetDegrees);
-
-    panServo.write(targetPanServoDegrees);
+    const int targetTiltDegrees = centerY + directionSign * sqrt(pow(radiusY, 2) * (1.0 - pow(targetDegrees - centerX, 2) / pow(radiusX, 2)));

-    const int targetTiltDegrees = centerY + directionSign * sqrt(pow(radiusY, 2) * (1.0 - pow(targetDegrees - centerX, 2) / pow(radiusX, 2)));
-    const int targetTiltServoDegrees = convertNormalizedAngleToServoAngle(targetTiltDegrees);
-    tiltServo.write(targetTiltServoDegrees);
-
-    delay(SERVO_DELAY);
+    moveToPoint(targetDegrees, targetTiltDegrees, xDegreesPerCycle);
   }

   for (int targetDegrees = endX; targetDegrees > startX; targetDegrees -= xDegreesPerCycle) {
     const int targetPanServoDegrees = convertNormalizedAngleToServoAngle(targetDegrees);
-
-    panServo.write(targetPanServoDegrees);
+    const int targetTiltDegrees = centerY - directionSign * sqrt(pow(radiusY, 2) * (1.0 - pow(targetDegrees - centerX, 2) / pow(radiusX, 2)));

-    const int targetTiltDegrees = centerY - directionSign * sqrt(pow(radiusY, 2) * (1.0 - pow(targetDegrees - centerX, 2) / pow(radiusX, 2)));
-    const int targetTiltServoDegrees = convertNormalizedAngleToServoAngle(targetTiltDegrees);
-    tiltServo.write(targetTiltServoDegrees);
-
-    delay(SERVO_DELAY);
+    moveToPoint(targetDegrees, targetTiltDegrees, xDegreesPerCycle);
   }
 }


WIP dynamic payload length

WIP dynamic payload length

--- avoccado-adhoc-migration-wip/avoccado-adhoc-migration-wip.ino
+++ avoccado-adhoc-migration-wip/avoccado-adhoc-migration-wip.ino
@@ -36,7 +36,7 @@

 // sets the role of this unit in hardware.  Connect to GND to be the 'pong' receiver
 // Leave open to be the 'ping' transmitter
-const int role_pin = 1;
+const int role_pin = 0;

 //
 // Topology
@@ -88,7 +88,13 @@
   //
   // Print preamble
   //
-
+  pinMode(A1,OUTPUT);
+  digitalWrite(A1, LOW); // Vcc for MPU6050
+  pinMode(5,OUTPUT);
+  digitalWrite(5, HIGH); // Vcc for MPU6050
+  pinMode(7,OUTPUT);
+  digitalWrite(7, HIGH); // Vcc for MPU6050
+
   Serial.begin(115200);
   printf_begin();
   printf("\n\r  \n\r");
@@ -143,7 +149,7 @@
   if (role == sender)
   {
     // The payload will always be the same, what will change is how much of it we send.
-    static char send_payload[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ789012"; //32 byte max
+    static char send_payload[] = "LBCDEFGHIJKLMNOPQRSTUVWXYZ789012"; //32 byte max
     radio.stopListening(); // stop listening so we can talk.
     printf("Now sending length %i...",next_payload_size);
     radio.write( send_payload, next_payload_size ); // This will block until complete


Reimplmenting HTTP connection handling + result code check, removing neopixel support

--- arduino/arduino.ino
+++ arduino/arduino.ino
@@ -12,11 +12,7 @@
 #define WIFI_SSID "ssid"
 #define WIFI_KEY "wpakey"

-// Uncomment this line if you would like to use a NeoPixel for status indication
-//#define USE_NEOPIXEL
-#define NEOPIXEL_PIN 9
-
-//#define USE_XS1_SERVER
+#define USE_XS1_SERVER
 #define XS1_IP (10, 11, 10, 18)
 #define XS1_URL "/control?callback=cname&cmd=set_state_sensor&number=9&value="
 #define XS1_TIMEFRAME 2
@@ -41,9 +37,6 @@

 // Dynamic inclusion taking place

-#if defined(USE_NEOPIXEL)
-  #include <Adafruit_NeoPixel.h>
-#endif
 #if defined(ARDUINO) && ARDUINO > 18
   #include <SPI.h>
 #endif
@@ -64,15 +57,6 @@

 // Whyever??? Only prototype needed. TODO.
 void networkConnect();
-
-// Set up the NeoPixel usage
-#ifdef USE_NEOPIXEL
-  Adafruit_NeoPixel neopixel = Adafruit_NeoPixel(1, NEOPIXEL_PIN, NEO_GRB + NEO_KHZ800);
-  uint32_t
-    neopixelBlinkColor,
-    neopixelFadeColor,
-    neopixelFlashColor;
-#endif

 // Set up the corresponding network device
 #ifdef USE_ETHERNET_SHIELD
@@ -98,8 +82,7 @@
 #endif

 #ifdef USE_NETWORK
-  char requestBuffer[128];
-  boolean lastConnected = false;
+  char readBuffer[13];
 #endif

 #ifdef USE_STROMBEWUSST_SERVER
@@ -132,9 +115,6 @@

   pinMode(TRIGGER_PIN, INPUT);

-  #ifdef USE_NEOPIXEL
-    neopixelInit();
-  #endif
   #ifdef USE_NETWORK
     pinMode(4, OUTPUT);     // SD select pin
     digitalWrite(4, HIGH);  // Disable the SD port
@@ -142,12 +122,12 @@
     digitalWrite(10, LOW);  // Explicitly enable network
     networkConnect();
   #endif
+
+  Serial.println("[system] end of setup function");
 }

 void networkConnect()
 {
-   neopixelSet(64, 32, 0);
-
    #ifdef USE_WIFI_SHIELD
     wifiConnect();
   #endif
@@ -162,9 +142,7 @@
     // UDP Format: <32xkey><1xtimeframe><1xticks>
     udpBuffer[16] = (byte)TIMEFRAME;
     udp.begin(STROMBEWUSST_PORT);
-  #endif
-
-  neopixelSet(0, 64, 0);
+  #endif
 }

 void loop()
@@ -180,36 +158,29 @@
     serverCheck();
     networkCheck();
   #endif
-  #ifdef USE_NEOPIXEL
-    neopixelLoop();
+}
+
+#ifdef USE_NETWORK
+void networkCheck()
+{
+  // dump all pending data from network connections to the serial interface
+  if (client.available())
+  {
+    for (byte i=0; i<12; i++)
+    {
+      readBuffer[i] = client.read();
+    }
+    client.stop();

-    if (millis()-lastTrigger < 1000)
+    String response = readBuffer;
+    if (response.substring(9) == "200")
     {
-      neopixelSet(255 - (millis()-lastTrigger)*255/1000, 0, 0);
-    } else if (lastTrigger > 0)
+      Serial.println("[network] HTTP push successful");
+    } else
     {
-      neopixelSet(0, 64, 0);
-      lastTrigger = 0;
+      Serial.println("[network] HTTP push failed - response: "+response.substring(9));
     }
-  #endif
-}
-
-#ifdef USE_NETWORK
-void networkCheck()
-{
-  // dump all pending data from network connections to the serial interface
-  while (client.available())
-  {
-    char c = client.read();
-    Serial.print(c);
-  }
-
-  // stop the client if we lost the connection since the last loop
-  if (!client.connected() && lastConnected) {
-    Serial.println("[network] closing connection");
-    client.stop();
-  }
-  lastConnected = client.connected();
+  }
 }
 #endif

@@ -391,14 +362,13 @@
   IPAddress ip XS1_IP;
   String url = XS1_URL;
   url += (int)(storageSum(60*XS1_TIMEFRAME/TIMEFRAME)*1.25*60/XS1_TIMEFRAME);
-  Serial.println("[XS1] Update URL: "+url);

   if (networkRequestIP(ip, url))
   {
-    Serial.println("[XS1] updated");
+    Serial.println("[XS1] push!");
   } else
   {
-    Serial.println("[XS1] update failed");
+    Serial.println("[XS1] push failed");
   }
 }
 #endif
@@ -406,21 +376,16 @@
 #ifdef USE_NETWORK
 bool networkRequestIP(IPAddress ip, String url)
 {
-  if (client.connected())
-  {
-    client.stop();
-  }
+  Serial.print("[network] HTTP request ");
+  Serial.println(url);

   if (client.connect(ip, 80))
   {
-    Serial.println("[network] sending request");
-
     client.print("GET ");
     client.print(url);
     client.println(" HTTP/1.0");
     client.println("Connection: close");
     client.println();
-
     return true;
   } else
   {
@@ -467,26 +432,3 @@
   }
   return sum;
 }
-
-#ifdef USE_NEOPIXEL
-void neopixelInit()
-{
-  neopixel.begin();
-}
-#endif
-
-void neopixelSet(byte red, byte green, byte blue)
-{
-  #ifdef USE_NEOPIXEL
-    neopixel.setPixelColor(0, red, green, blue);
-    neopixel.show();
-  #endif
-}
-
-#ifdef USE_NEOPIXEL
-void neopixelLoop()
-{
-  long unsigned time = millis();
-}
-#endif
-


Minimizing in-memory string operations, adding 404 for invalid URLs

--- arduino/arduino.ino
+++ arduino/arduino.ino
@@ -12,7 +12,7 @@
 #define WIFI_SSID "ssid"
 #define WIFI_KEY "wpakey"

-#define USE_XS1_SERVER
+//#define USE_XS1_SERVER
 #define XS1_IP (10, 11, 10, 18)
 #define XS1_URL "/control?callback=cname&cmd=set_state_sensor&number=9&value="
 #define XS1_TIMEFRAME 2
@@ -83,6 +83,7 @@

 #ifdef USE_NETWORK
   char readBuffer[13];
+  char headerBuffer[10];
 #endif

 #ifdef USE_STROMBEWUSST_SERVER
@@ -178,7 +179,8 @@
       Serial.println("[network] HTTP push successful");
     } else
     {
-      Serial.println("[network] HTTP push failed - response: "+response.substring(9));
+      Serial.print("[network] HTTP push failed - response: ");
+      Serial.println(response.substring(9));
     }
   }
 }
@@ -189,51 +191,49 @@
 {
   connection = server.available();
   // Check for a new connection
-  char headerBuffer[10];
-
   if (connection)
   {
     Serial.println("[server] new client");
-    while (connection.connected()) {
-      if (connection.available()) {
-        // Get the first couple of bytes
-        for (int i=0; i<10; i++)
-        {
-          headerBuffer[i] = connection.read();
-        }
-        connection.flush();
-        Serial.println(headerBuffer);
-        String header = headerBuffer;
-        if (header.startsWith("GET / "))
-        {
-          connection.print(serverHeader("text/html"));
-          connection.println("Angelegte Last: ");
-          connection.print((int)(storageSum(60*XS1_TIMEFRAME/TIMEFRAME)*1.25*60/XS1_TIMEFRAME));
-          connection.println();
-        }
-
-        if(header.startsWith("GET /json "))
-        {
-          connection.print(serverHeader("text/json"));
-          connection.print(generateJSON());
-        }
-
-        delay(1);
-        connection.stop();
+    if (connection.available()) {
+      // Get the first couple of bytes
+      for (int i=0; i<9; i++)
+      {
+        headerBuffer[i] = connection.read();
       }
+      connection.flush();
+
+      Serial.print("[server] request: ");
+      Serial.println(headerBuffer);
+
+      String header = headerBuffer;
+      if (header.startsWith("GET / "))
+      {
+        connection.println("HTTP/1.1 200 OK");
+        connection.println("Content-Type: text/html");
+        connection.println("Connection: close");
+        connection.println();
+
+        connection.println("Angelegte Last: ");
+        connection.print(calculateWatt(1));
+
+      } else if (header.startsWith("GET /json"))
+      {
+        connection.println("HTTP/1.1 200 OK");
+        connection.println("Content-Type: text/json");
+        connection.println("Connection: close");
+        connection.println();
+        connection.println("{\"foo\":\"bar\"}");
+      } else
+      {
+        connection.println("HTTP/1.1 404 Not found");
+        connection.println("");
+      }
+
+      delay(10);
+      connection.stop();
     }
     Serial.println("[server] client disconnected");
   }
-}
-#endif
-
-#ifdef USE_NETWORK
-String serverHeader(String contentType)
-{
-  return
-    String("HTTP/1.1 200 OK\r\n")+
-    "Content-Type: "+contentType+"\r\n"+
-    "Connection: close\r\n\r\n";
 }
 #endif

@@ -338,11 +338,18 @@
   #endif

   Serial.println("[loop] *** Time frame changed ***");
-  Serial.println("[data] Last 30 seconds: "+String(storageSum(1)));
-  Serial.println("[data] Last 60 seconds: "+String(storageSum(2)));
-  Serial.println("[data] Last 5 minutes: "+String(storageSum(20)));
+
+  Serial.print("[data] Last 30 seconds: ");
+  Serial.println(storageSum(1));
+
+  Serial.print("[data] Last 60 seconds: ");
+  Serial.println(storageSum(2));
+
+  Serial.print("[data] Last 5 minutes: ");
+  Serial.println(storageSum(20));
+
   Serial.print("[data] Currently connected: ");
-  Serial.print((int)(storageSum(60*XS1_TIMEFRAME/TIMEFRAME)*1.25*60/XS1_TIMEFRAME));
+  Serial.print(calculateWatt(2));
   Serial.println(" Watt");
 }

@@ -361,7 +368,7 @@
 {
   IPAddress ip XS1_IP;
   String url = XS1_URL;
-  url += (int)(storageSum(60*XS1_TIMEFRAME/TIMEFRAME)*1.25*60/XS1_TIMEFRAME);
+  url += calculateWatt(XS1_TIMEFRAME);

   if (networkRequestIP(ip, url))
   {
@@ -407,17 +414,7 @@
 }
 #endif

-#ifdef USE_NETWORK
-String generateJSON()
-{
-  return "{\"history\":{\"30\":"+String(storageSum(1))
-          +",\"60\":"+String(storageSum(2))
-          +",\"300\":"+String(storageSum(20))
-          +"}}";
-}
-#endif
-
-int storageSum(int frames)
+int storageSum(unsigned int frames)
 {
   int sum = 0;
   int pos = storagePointer;
@@ -428,7 +425,12 @@
     {
       pos = storageSize-1;
     }
-    sum += (int)storage[pos];
+    sum += storage[pos];
   }
   return sum;
 }
+
+int calculateWatt(unsigned int minutes)
+{
+  return storageSum(60 / TIMEFRAME * minutes)*1.25*60/minutes;
+}


Working motor control after re-wiring

Working motor control after re-wiring

--- controller/controller.ino
+++ controller/controller.ino
@@ -1,8 +1,8 @@
-//#include <ZumoMotors.h>
+#include <ZumoMotors.h>

 #define LED_PIN 13

-//ZumoMotors motors;
+ZumoMotors motors;

 String inputString = "";         // a string to hold incoming data
 boolean stringComplete = false;  // whether the string is complete
@@ -15,6 +15,11 @@
   inputString.reserve(200);

   pinMode(LED_PIN, OUTPUT);
+
+  // Left motor power wiring is reversed.
+  motors.flipLeftMotor(true);
+
+  // Initial speed is zero
   motors.setLeftSpeed(0);
   motors.setRightSpeed(0);
 }
@@ -39,7 +44,7 @@
  response.  Multiple bytes of data may be available.
  */
 void serialEvent() {
-  int vel, vel2;
+  int vel, vel2, dt;
   while (Serial.available()) {
     // Get state character from buffer
     char c = (char)Serial.read();
@@ -64,16 +69,19 @@
       break;

       case 'c':
-      // Both
+      // c left_speed right_speed dt_millis
+      // All
       vel = Serial.parseInt();
       vel = constrain(vel, -400, 400);
       vel2 = Serial.parseInt();
       vel2 = constrain(vel2, -400, 400);
+      dt = Serial.parseInt();
+      dt = constrain(dt, 0, 10000); // 0-10 seconds
       Serial.print("Both ");
       Serial.print(vel);
       Serial.print(" ");
       Serial.println(vel2);
-      drive(vel,vel2,250);
+      drive(vel,vel2,dt);
       break;

       case 'd':


set analog ref to use external

set analog ref to use external

--- short-circuit-limiter/short-circuit-limiter.ino
+++ short-circuit-limiter/short-circuit-limiter.ino
@@ -83,6 +83,8 @@

   currentEnableThreshold = getEnableThresholdFromEEProm();

+  analogReference(EXTERNAL);
+
   pinMode(PIN_LED, OUTPUT);
   pinMode(PIN_BUZZER, OUTPUT);


Comentarios

Comentarios

--- arduino/Alarma/Alarma.ino
+++ arduino/Alarma/Alarma.ino
@@ -98,7 +98,9 @@
   }
 }

-
+//Prende o apaga la alarma
+//Similar al método de las luces.
+//Evita que la alarma se prenda si hay algun sensor activo.
 void switchAlarm(int light) {
   //Verificar que ningun sensor este activado para poder activar alarma

@@ -119,6 +121,8 @@
   }
 }

+//Chequea el estado de los sensores y dispara la alarma si se desactiva
+//uno de ellos mientras la alarma está activada.
 void checkSensors() {

   //Comienzo el chequeo de cada uno de los sensores


Changed light length, updated IP address

--- arduino/colour_controlled_with_decay/colour_controlled_with_decay.ino
+++ arduino/colour_controlled_with_decay/colour_controlled_with_decay.ino
@@ -18,7 +18,7 @@
 int CKI = 2;
 int SDI = 3;

-#define STRIP_LENGTH 20 // Number of RGBLED modules connected
+#define STRIP_LENGTH 19 // Number of RGBLED modules connected

 long ind_colours[STRIP_LENGTH]; // actual individual modules.


Adding other Accent Chars (degree symbol, bullet, etc.)


Activate the Arduino's built-in LED along with the Typeatron's laser, for development purposes while the device is in USB mode

--- typeatron/mark1/arduino/typeatron/typeatron.ino
+++ typeatron/mark1/arduino/typeatron/typeatron.ino
@@ -15,7 +15,7 @@
  * D10: RGB LED green
  * D11: RGB LED blue
  * D12: push button 5
- * D13: LED and Bluetooth power
+ * D13: LED
  * A0:  piezo motion sensor
  * A1:  (unused)
  * A2:  (unused)
@@ -76,7 +76,7 @@
 const int vibrationMotorPin = 3;
 const int transducerPin = 5;
 const int laserPin = 6;
-const int bluetoothPowerPin =  13;
+const int ledPin =  13;

 // note: blue and green pins were wired in reverse w.r.t. the BL-L515 datasheet
 const int redPin = 9;
@@ -148,6 +148,22 @@
         writeRGBColor(BLUE);
     }
     colorToggle = !colorToggle;
+}
+
+
+////////////////////////////////////////////////////////////////////////////////
+
+void laserOn() {
+    digitalWrite(laserPin, HIGH);
+
+    // also turn on the on-board LED, as a cue to the developer in USB mode (when the laser is powered off)
+    digitalWrite(ledPin, HIGH);
+}
+
+void laserOff() {
+    digitalWrite(laserPin, LOW);
+
+    digitalWrite(ledPin, LOW);
 }

@@ -208,7 +224,7 @@
     pinMode(vibrationMotorPin, OUTPUT);
     pinMode(transducerPin, OUTPUT);
     pinMode(laserPin, OUTPUT);
-    pinMode(bluetoothPowerPin, OUTPUT);
+    pinMode(ledPin, OUTPUT);
     pinMode(redPin, OUTPUT);
     pinMode(greenPin, OUTPUT);
     pinMode(bluePin, OUTPUT);
@@ -228,8 +244,6 @@
 #endif

     serialInputPtr = 0;
-
-    initializeBluetooth();

     startupSequence();
 }
@@ -280,24 +294,6 @@
     } else {
         Serial.println("");
     }*/
-}
-
-
-////////////////////////////////////////////////////////////////////////////////
-
-void initializeBluetooth() {
-#ifdef USE_BLUETOOTH
-    // to start the device with Bluetooth disabled, hold a key while powering up or resetting
-    readKeys();
-    if (keyState) {
-        digitalWrite(bluetoothPowerPin, LOW);
-    } else {
-        digitalWrite(bluetoothPowerPin, HIGH);
-    }
-    keyState = 0;
-#else
-    digitalWrite(bluetoothPowerPin, LOW);
-#endif
 }

@@ -535,7 +531,7 @@
         }
     }
 #endif
-
+
     readKeys();

     if (keyState != lastKeyState) {
@@ -545,9 +541,9 @@

         // bells and whistles
         if (keys[4] == HIGH) {
-            digitalWrite(laserPin, HIGH);
+            laserOn();
         } else {
-            digitalWrite(laserPin, LOW);
+            laserOff();
         }
         if (keys[3] == HIGH) {
             receiveLightLevelRequest(0, 0);


Added literal float to improve precision

according to #2922 I added missing float literals to improve the accuracy of the result.

If sensorValue = 1:

Before: voltage = 4

Now: voltage = 4.88

--- libraries/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino
+++ libraries/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino
@@ -98,9 +98,9 @@
       Serial.println(timeString);
       int sensorValue = analogRead(A1);
       // convert the reading to millivolts:
-      float voltage = sensorValue *  (5000 / 1024);
+      float voltage = sensorValue * (5000.0f / 1024.0f);
       // convert the millivolts to temperature celsius:
-      float temperature = (voltage - 500) / 10;
+      float temperature = (voltage - 500.0f) / 10.0f;
       // print the temperature:
       client.print("Current time on the Yún: ");
       client.println(timeString);


Reverted back MDNS hostname setting as multiple devices could run in AP mode which can cause conflicts.


Eliminate LED flicker when cycling through colours

  Closes #1 - whereby LEDs have a noticeable flicker when cycling
   through the random colours.

   - Move the call to random() so that it is called at most once
      per loop, and that the time take to calculate new values is
      spread out, reducing the time paused when creating a new
      set of pixel colours

--- driver_boards/firmware/DanceFloor.ino
+++ driver_boards/firmware/DanceFloor.ino
@@ -71,6 +71,10 @@
 unsigned char display_buffer_2[BUFFER_SIZE];
 static unsigned char *display_buffer = display_buffer_1;

+unsigned char random_colours_buffer[BUFFER_SIZE];
+unsigned int random_colours_buffer_pixel = 0;
+
+
 volatile byte display_buffer_live = 1;

 volatile byte new_row = 0;
@@ -84,7 +88,7 @@
 unsigned long tickcounter = 0;
 unsigned long lastdata_tickcounter = 0;
 // 40000 = 20 seconds
-unsigned long timeout = 40000;
+unsigned long timeout = 4000;

 volatile boolean cycling = false;
 // 1000 ~ 1/2 second
@@ -92,13 +96,14 @@
 unsigned long cycle_tickcounter = 0;

 unsigned long colours[] = {0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0x00FFFF, 0xFF00FF, 0xFFFFFF};
+int colours_length = 7;

 void set_initial_pattern(void) {
   set_random_colours();
 }

 void set_random_colours() {
-  int colours_length = 7;
+
   for (int pixel=0; pixel < RGB_LEDS; pixel++) {
     unsigned long colour = colours[random(colours_length)];
     display_buffer[pixel * 3 + 0] = colour & 0xFF;
@@ -189,12 +194,23 @@

     new_row = 0;
     tickcounter++;
-

     // If we are cycling, then see if we need to cycle again
     if (cycling == true) {
+      if (random_colours_buffer_pixel < RGB_LEDS) {
+        unsigned long colour = colours[random(colours_length)];
+        //colour = colours[0];
+        random_colours_buffer[random_colours_buffer_pixel * 3 + 0] = colour & 0xFF;
+        random_colours_buffer[random_colours_buffer_pixel * 3 + 1] = (colour >> 8 ) & 0xFF;
+        random_colours_buffer[random_colours_buffer_pixel * 3 + 2] = (colour >> 16) & 0xFF;
+        random_colours_buffer_pixel++;
+      }
       if (tickcounter - cycle_tickcounter > cycle_period) {
-        set_random_colours();
+        //set_random_colours();
+        for (int i=0; i<BUFFER_SIZE;i++){
+           display_buffer[i] = random_colours_buffer[i];
+        }
+        random_colours_buffer_pixel = 0;
         cycle_tickcounter = tickcounter;
       }
     } else {


Correct thruster controller firmware.

Correct thruster controller firmware.

--- riptide_hardware/firmware/thruster_controller/thruster_controller.ino
+++ riptide_hardware/firmware/thruster_controller/thruster_controller.ino
@@ -65,44 +65,54 @@
   // Write PWM data & request remote checksums
   //

-  Wire.beginTransmission(ESC_BOARD[1]);
+  Wire.beginTransmission(ESC_BOARD[0]);
+  Wire.write(valid(cmd.pwm.surge_port_hi >> 8));
   Wire.write(valid(cmd.pwm.surge_port_hi));
+  Wire.write(valid(cmd.pwm.surge_stbd_hi >> 8));
   Wire.write(valid(cmd.pwm.surge_stbd_hi));
   Wire.endTransmission();

-  Wire.requestFrom(ESC_BOARD[1], ONE_BYTE);
+  Wire.requestFrom(ESC_BOARD[0], ONE_BYTE);
   state.surge_hi ^= Wire.read();

-  Wire.beginTransmission(ESC_BOARD[2]);
+  Wire.beginTransmission(ESC_BOARD[1]);
+  Wire.write(valid(cmd.pwm.surge_port_lo >> 8));
   Wire.write(valid(cmd.pwm.surge_port_lo));
+  Wire.write(valid(cmd.pwm.surge_stbd_lo >> 8));
   Wire.write(valid(cmd.pwm.surge_stbd_lo));
   Wire.endTransmission();

-  Wire.requestFrom(ESC_BOARD[2], ONE_BYTE);
+  Wire.requestFrom(ESC_BOARD[1], ONE_BYTE);
   state.surge_lo ^= Wire.read();

-  Wire.beginTransmission(ESC_BOARD[3]);
+  Wire.beginTransmission(ESC_BOARD[2]);
+  Wire.write(valid(cmd.pwm.sway_fwd >> 8));
   Wire.write(valid(cmd.pwm.sway_fwd));
+  Wire.write(valid(cmd.pwm.sway_aft >> 8));
   Wire.write(valid(cmd.pwm.sway_aft));
   Wire.endTransmission();

-  Wire.requestFrom(ESC_BOARD[3], ONE_BYTE);
+  Wire.requestFrom(ESC_BOARD[2], ONE_BYTE);
   state.sway ^= Wire.read();

-  Wire.beginTransmission(ESC_BOARD[4]);
+  Wire.beginTransmission(ESC_BOARD[3]);
+  Wire.write(valid(cmd.pwm.heave_port_fwd >> 8));
   Wire.write(valid(cmd.pwm.heave_port_fwd));
+  Wire.write(valid(cmd.pwm.heave_stbd_fwd >> 8));
   Wire.write(valid(cmd.pwm.heave_stbd_fwd));
   Wire.endTransmission();

-  Wire.requestFrom(ESC_BOARD[4], ONE_BYTE);
+  Wire.requestFrom(ESC_BOARD[3], ONE_BYTE);
   state.heave_fwd ^= Wire.read();

-  Wire.beginTransmission(ESC_BOARD[5]);
+  Wire.beginTransmission(ESC_BOARD[4]);
+  Wire.write(valid(cmd.pwm.heave_port_aft >> 8));
   Wire.write(valid(cmd.pwm.heave_port_aft));
+  Wire.write(valid(cmd.pwm.heave_stbd_aft >> 8));
   Wire.write(valid(cmd.pwm.heave_stbd_aft));
   Wire.endTransmission();

-  Wire.requestFrom(ESC_BOARD[5], ONE_BYTE);
+  Wire.requestFrom(ESC_BOARD[4], ONE_BYTE);
   state.heave_aft ^= Wire.read();

   // Publish checksum results


tweak aestheticts of the heartbeat effect

--- examples/chibitronics/effects/effects.ino
+++ examples/chibitronics/effects/effects.ino
@@ -51,6 +51,8 @@
     current = current + ((target - current) > 0 ? rate : - rate);
     delay(pause);
   }
+  current = target; // handle cases where target and rate aren't multiples of 255
+  analogWrite(pin, current);
   return current;
 }

@@ -74,10 +76,11 @@
   current = fade_to(current, 0xc0, 2, cfg->pin, 1);
   current = fade_to(current, 0x4, 2, cfg->pin, 1);
   delay(80); // fastest rate
-  delay( (13 - cfg->tempo) * 15 );
+  delay( (13 - cfg->tempo) * 13 );
   //delay(180);
   current = fade_to(current, 0xff, 2, cfg->pin, 1);
   current = fade_to(current, 0x00, 2, cfg->pin, 1);
+  digitalWrite(cfg->pin, 0);
   delay(214); // fastest rate
   delay( (13 - cfg->tempo) * 37 );
   //delay(420);
@@ -119,7 +122,7 @@
     digitalWrite(port[i].pin, LOW);
     if (port[i].effect == NONE)
       continue;
-    light_threads[i] = createThreadFromHeap(64,
+    light_threads[i] = createThreadFromHeap(32,
                                            20,
                                            effects_thread,
                                            &port[i]);


reorganizado código, alterado cálculo de média

--- EMP-B-Due.ino
+++ EMP-B-Due.ino
@@ -5,7 +5,28 @@
  Controlador de Empacotadeira com Arduino Due.
 */

-// CONSTANTES
+// CONFIGURAÇÕES
+// GERAL
+#define BOTAO INPUT_PULLUP  // INPUT ou INPUT_PULLUP
+#define SENSOR INPUT        // INPUT ou INPUT_PULLUP
+#define SAIDA OUTPUT
+#define ALTO LOW    // Deve ser invertido para INPUT_PULLUP
+#define BAIXO HIGH  // Deve ser invertido para INPUT_PULLUP
+#define LIGA HIGH
+#define DESLIGA LOW
+#define VERDADEIRO true
+#define FALSO false
+// NOMES DE FUNÇÕES
+#define NomeGeral "Geral" // Acionamento da máquina
+#define NomeDosador "Dosador" // Acionamento do Dosador
+#define NomeDatador "Datador" // Liberação do Datador
+#define NomeMandibula "Mandibula" // Ciclo da Mandíbula
+#define NomeFaca "Faca" // Ciclo da Faca
+#define NomeRefrigeracao "Refrigeracao" // Ciclo da Refrigeração
+#define NomeSoldas "Soldas" // Ciclo das Soldas Vertical e Horizontal
+#define NomeSoldaVertical "Solda Vertical"
+#define NomeSoldaHorizontal "Solda Horizontal"
+#define NomeSoldaDatador "Solda Datador"
 // ENTRADAS
 const byte bt_geral = 22;        // Entrada do botão de Liga/Desliga Geral
 const byte bt_dosador = 24;      // Entrada do botão de Liga/Desliga do Dosador
@@ -17,11 +38,10 @@
 const byte pot_solda_vertical = A0;    // Potenciômetro da Solda Vertical
 const byte pot_solda_horizontal = A1;  // Potenciômetro da Solda Vertical
 const byte pot_solda_datador = A2;     // Potenciômetro da Solda Vertical
-
 // SAÍDAS
-const byte geral = 23;                 // Saída Geral
-const byte dosador = 25;               // Saída do Dosador
-const byte led_datador = 27;               // Saída do Datador
+const byte geral = 23; // Saída Geral
+const byte dosador = 25; // Saída do Dosador
+const byte led_datador = 27; // Saída do Datador
 const byte mandibula = 40;
 const byte faca = 42;
 const byte refrigeracao = 44;
@@ -31,80 +51,10 @@
 const byte solda_vertical_PWM = 33;        // Saída da Solda Vertical
 const byte solda_horizontal_PWM = 35;      // Saída da Solda Horizontal
 const byte solda_datador_PWM = 37;         // Saída da Solda do Datador
-
-
-// REMOVER
-const byte saida_teste = 2;
-const byte entrada_teste = 4;
-
-// VARIÁVEIS
-// CONFIGURAÇÕES
-#define BOTAO INPUT_PULLUP  // INPUT ou INPUT_PULLUP
-#define SENSOR INPUT        // INPUT ou INPUT_PULLUP
-#define SAIDA OUTPUT
-#define ALTO LOW    // Deve ser invertido para INPUT_PULLUP
-#define BAIXO HIGH  // Deve ser invertido para INPUT_PULLUP
-#define LIGA HIGH
-#define DESLIGA LOW
-#define VERDADEIRO true
-#define FALSO false
-
-// NOMES DE FUNÇÕES
-#define NomeGeral "Geral"
-#define NomeDosador "Dosador"
-#define NomeDatador "Datador"
-#define NomeMandibula "Mandibula"
-#define NomeFaca "Faca"
-#define NomeRefrigeracao "Refrigeracao"
-#define NomeSoldas "Soldas"
-#define NomeSoldaVertical "Solda Vertical"
-#define NomeSoldaHorizontal "Solda Horizontal"
-#define NomeSoldaDatador "Solda Datador"
-
-// BOTOÕES UM-CLIQUE
-unsigned long atraso = 50;
-int estbt_geral;                // Estado do Botão Geral
-int estbta_geral = BAIXO;       // Estado anterior do Botão Geral
-unsigned long atr_geral = 0;    // Atraso do Botão Geral
-int estbt_dosador;              // Estado do Botão Dosador
-int estbta_dosador = BAIXO;     // Estado anterior do Botão Dosador
-unsigned long atr_dosador = 0;  // Atraso do Botão Dosador
-int estbt_datador;              // Estado do Botão Datador
-int estbta_datador = BAIXO;     // Estado anterior do Botão Dosador
-unsigned long atr_datador = 0;  // Atraso do Botão Dosador
-
-// PWM DAS SOLDAS
-const unsigned long ciclo_PWM = 1000;
-unsigned long tempo_PWM_vertical = 0;    // Tempo do PWM da solda vertical
-unsigned long tempo_PWM_horizontal = 0;  // Tempo do PWM da solda horizontal
-unsigned long tempo_PWM_datador = 0;     // Tempo do PWM da solda do Datador
-
-// MODOS DE TRABALHO
-boolean stand_by = FALSO;
-boolean maquina_ligada = FALSO;
-boolean dosador_ligado = FALSO;
-boolean datador_ligado = FALSO;
-boolean alarme_ativo = FALSO;
-boolean fotocelula_liberada = FALSO;
-boolean fotocelula_cortou = FALSO;
-boolean produzindo = FALSO;
-boolean resetado = FALSO;
-
 // TEMPOS DE CICLO
-// CONTROLE DE CICLO
-unsigned long tempo_atual = millis();
 unsigned long ciclo_padrao = 2000;
-unsigned long ciclo_padrao_anterior = ciclo_padrao;
-unsigned long inicio_ciclo = 0;
-unsigned long ciclo_minimo = 900;
-unsigned long ciclo_maximo = 2000;
-unsigned long soma_ciclos = 0;
-unsigned long conta_ciclos = 0;
-unsigned long fim_ciclo = 0;
-unsigned long minimo = 0;
-unsigned long maximo = 0;
-unsigned long ultimo_ciclo = ciclo_padrao;
-
+const unsigned long ciclo_minimo = 900;
+const unsigned long ciclo_maximo = 2000;
 // MANDÍBULA
 const unsigned int inicio_mandibula = 550;
 const unsigned int fim_mandibula = 1500;
@@ -123,6 +73,54 @@
 // SOLDAS VERTICAL E HORIZONTAL
 const unsigned int inicio_soldas = 5;
 const unsigned int fim_soldas = 400;
+
+// REMOVER >>
+const byte saida_teste = 2;
+const byte entrada_teste = 4;
+// << REMOVER
+
+// VARIÁVEIS
+// BOTOÕES UM-CLIQUE
+unsigned long atraso = 50;
+int estbt_geral;                // Estado do Botão Geral
+int estbta_geral = BAIXO;       // Estado anterior do Botão Geral
+unsigned long atr_geral = 0;    // Atraso do Botão Geral
+int estbt_dosador;              // Estado do Botão Dosador
+int estbta_dosador = BAIXO;     // Estado anterior do Botão Dosador
+unsigned long atr_dosador = 0;  // Atraso do Botão Dosador
+int estbt_datador;              // Estado do Botão Datador
+int estbta_datador = BAIXO;     // Estado anterior do Botão Dosador
+unsigned long atr_datador = 0;  // Atraso do Botão Dosador
+
+// PWM DAS SOLDAS
+const unsigned long ciclo_PWM = 1000;
+unsigned long tempo_PWM_vertical = 0;    // Tempo do PWM da solda vertical
+unsigned long tempo_PWM_horizontal = 0;  // Tempo do PWM da solda horizontal
+unsigned long tempo_PWM_datador = 0;     // Tempo do PWM da solda do Datador
+
+// MODOS DE TRABALHO
+boolean stand_by = FALSO;
+boolean maquina_ligada = FALSO;
+boolean dosador_ligado = FALSO;
+boolean datador_ligado = FALSO;
+boolean alarme_ativo = FALSO;
+boolean fotocelula_liberada = FALSO;
+boolean fotocelula_cortou = FALSO;
+boolean produzindo = FALSO;
+boolean resetado = FALSO;
+
+// TEMPOS DE CICLO
+// CONTROLE DE CICLO
+unsigned long tempo_atual = millis();
+unsigned long ciclo_padrao_anterior = ciclo_padrao;
+unsigned long inicio_ciclo = 0;
+unsigned long soma_ciclos = 0;
+unsigned long conta_ciclos = 0;
+unsigned long fim_ciclo = 0;
+unsigned long minimo = 0;
+unsigned long maximo = 0;
+unsigned long ultimo_ciclo = ciclo_padrao;
+
 // TEMPOS MÉDIOS
 // MANDÍBULA
 unsigned long ti_mandibula = (unsigned long)inicio_mandibula; // NÃO ALTERE
@@ -223,7 +221,7 @@
     // funcaoSimples(mandibula, NomeMandibula, inicio_mandibula, fim_mandibula);
     // funcaoSimples(faca, NomeFaca, inicio_faca, fim_faca);
     // funcaoSimples(refrigeracao, NomeRefrigeracao, inicio_refrigeracao, fim_refrigeracao);
-    funcaoSimples(datador, NomeDatador, inicio_datador, fim_datador);
+    funcaoSimples(datador, NomeDatador, ti_datador, tf_datador);
     // funcaoSimples(soldas, NomeSoldas, inicio_soldas, fim_soldas);
     // funcaoSimples(saida_teste, "Teste", 1500, 1600);
   }
@@ -304,23 +302,23 @@
 void cicloMedio() {
   if (conta_ciclos > 0) {
     ciclo_padrao_anterior = ciclo_padrao;
-    ciclo_padrao = ultimo_ciclo; //soma_ciclos / conta_ciclos;
+    ciclo_padrao = ultimo_ciclo; // soma_ciclos / conta_ciclos;
     // AJUSTE DINÂMICO DOS TEMPOS DAS FUNÇÕES
-    ajustaCiclo(&inicio_mandibula);
-    ajustaCiclo(&fim_mandibula);
-    ajustaCiclo(&inicio_faca);
-    ajustaCiclo(&fim_faca);
-    ajustaCiclo(&inicio_refrigeracao);
-    ajustaCiclo(&fim_refrigeracao);
-    ajustaCiclo(&inicio_datador);
-    ajustaCiclo(&fim_datador);
-    ajustaCiclo(&inicio_soldas);
-    ajustaCiclo(&fim_soldas);
-  }
-}
-
-void ajustaCiclo(unsigned long *variavel){
-  unsigned long tempo = (*variavel * ciclo_padrao) / ciclo_padrao_anterior;
+    ajustaCiclo(&ti_mandibula, inicio_mandibula);
+    ajustaCiclo(&tf_mandibula, fim_mandibula);
+    ajustaCiclo(&ti_faca, inicio_faca);
+    ajustaCiclo(&tf_faca, fim_faca);
+    ajustaCiclo(&ti_refrigeracao, inicio_refrigeracao);
+    ajustaCiclo(&tf_refrigeracao, fim_refrigeracao);
+    ajustaCiclo(&ti_datador, inicio_datador);
+    ajustaCiclo(&tf_datador, fim_datador);
+    ajustaCiclo(&ti_soldas, inicio_soldas);
+    ajustaCiclo(&tf_soldas, fim_soldas);
+  }
+}
+
+void ajustaCiclo(unsigned long *variavel, unsigned int original){
+  unsigned long tempo = ((unsigned long)original * ciclo_padrao) / ciclo_padrao_anterior;
   if (tempo <= 0){
     *variavel = 1;
   } else {
@@ -369,7 +367,7 @@
   if (desligado(saida)) {
     liga(saida);
     if (ligado(saida)){
-      escreveSerial(">> " + nome + " Ligado." + (String)inicio_datador);
+      escreveSerial(">> " + nome + " Ligado." + (String)ti_datador);
     } else {
       escreveSerial("Ocorreu um erro ao ligar " + nome);
     }
@@ -381,7 +379,7 @@
 void desligaFuncao(byte saida, String nome) {
   if (ligado(saida)) {
     desliga(saida);
-    escreveSerial("<< " + nome + " Desligado." + (String) fim_datador);
+    escreveSerial("<< " + nome + " Desligado." + (String)tf_datador);
   }
 }


Update example01s_led.ino

Update example01s_led.ino


improve ardiuno serial connection guide

improve ardiuno serial connection guide

--- Arduino/ODriveArduino/examples/ODriveArduinoTest/ODriveArduinoTest.ino
+++ Arduino/ODriveArduino/examples/ODriveArduinoTest/ODriveArduinoTest.ino
@@ -1,14 +1,38 @@
-
+// includes
 #include <SoftwareSerial.h>
 #include <ODriveArduino.h>
-
-// Printing with stream operator
+// Printing with stream operator helper functions
 template<class T> inline Print& operator <<(Print &obj,     T arg) { obj.print(arg);    return obj; }
 template<>        inline Print& operator <<(Print &obj, float arg) { obj.print(arg, 4); return obj; }

-// Serial to the ODrive
-SoftwareSerial odrive_serial(8, 9); //RX (ODrive TX), TX (ODrive RX)
-// Note: you must also connect GND on ODrive to GND on Arduino!
+
+////////////////////////////////
+// Set up serial pins to the ODrive
+////////////////////////////////
+
+// Below are some sample configurations.
+// You can comment out the default Teensy one and uncomment the one you wish to use.
+// You can of course use something different if you like
+// Don't forget to also connect ODrive GND to Arduino GND.
+
+// Teensy 3 and 4 (all versions) - Serial1
+// pin 0: RX - connect to ODrive TX
+// pin 1: TX - connect to ODrive RX
+// See https://www.pjrc.com/teensy/td_uart.html for other options on Teensy
+Stream& odrive_serial = Serial1;
+
+// Arduino Mega or Due - Serial1
+// pin 19: RX - connect to ODrive TX
+// pin 18: TX - connect to ODrive RX
+// See https://www.arduino.cc/reference/en/language/functions/communication/serial/ for other options
+// Stream& odrive_serial = Serial1;
+
+// Arduino without spare serial ports (such as Arduino UNO) have to use software serial.
+// Note that this is implemented poorly and can lead to wrong data sent or read.
+// pin 8: RX - connect to ODrive TX
+// pin 9: TX - connect to ODrive RX
+// SoftwareSerial odrive_serial(8, 9);
+

 // ODrive object
 ODriveArduino odrive(odrive_serial);


The folder in which the .ino is enclosed, in this case /Github/dremelfuge, is considered the sketch folder, and must have the *same name* as the .ino; rename Dremelfuge.ino -> dremelfuge.ino

--- Dremelfuge.ino
+++ Dremelfuge.ino
@@ -10,13 +10,9 @@
     unsigned long lastTimePressed;
   public:
     // combination of Button(byte) and Button(byte, bool) and Button(byte, bool, int) constructors via default args
-    Button(const uint8_t pin, const bool isToggleButton=false, uint16_t debounceDelay=500)
-    : pin(pin), isToggleButton(isToggleButton) // const variables can only be assigned through initialization lists
+    Button(const uint8_t pin, const bool isToggleButton=false, uint16_t debounceDelay=500); // const variables can only be assigned through initialization lists
                                                // (since they're supposed to be read-only)
-    {
-      this->debounceDelay = debounceDelay;
-      lastTimePressed = 0;
-    }
+
     void setDebounceDelay(int debounceDelay)
     {
       this->debounceDelay = debounceDelay;
@@ -241,3 +237,15 @@
   //***
   lcd.print(seconds/60); lcd.print(F(":")); lcd.print((seconds%60 < 10 ? F("0") : F(""))); lcd.print(seconds%60);
 }
+
+
+
+
+
+    Button::Button(const uint8_t pin, const bool isToggleButton, uint16_t debounceDelay)
+    : pin(pin), isToggleButton(isToggleButton) // const variables can only be assigned through initialization lists
+                                               // (since they're supposed to be read-only)
+    {
+      this->debounceDelay = debounceDelay;
+      lastTimePressed = 0;
+    }


- quick hack: blink outer LEDs if someone approaches the door

--- GeheimTuer.ino
+++ GeheimTuer.ino
@@ -704,6 +704,17 @@
           }

           ledptr = &tmp_leds[0];
+
+          // quick hack: blink outer LEDs if someone approaches the door
+          // TODO: fix double period at fader counter limits
+          if (pirTrigger == HIGH) {
+            if ((ledState.fader / 20) % 2) {
+              tmp_leds[0] = tmp_leds[MAXPIX-1] = {g: 0xFF, r: 0xFF, b: 0x00};
+            } else {
+              tmp_leds[1] = tmp_leds[MAXPIX-2] = {g: 0xFF, r: 0xFF, b: 0x00};
+            }
+          }
+
           LED.sync();
         }
         break;


Updated and tested Water Sensor code.

Updated and tested Water Sensor code.

--- arduinoWorkspace/SubWaterSensorController/SubWaterSensorController.ino
+++ arduinoWorkspace/SubWaterSensorController/SubWaterSensorController.ino
@@ -8,12 +8,13 @@
 #define DELAY 200

 void setup(){
+  analogReference(DEFAULT);
   Serial.begin(BAUD);
 }

 void loop(){
-  int s1 = analogRead(S1)>0.2?1:0;
-  int s2 = analogRead(S2)>0.2?1:0;
+  int s1 = analogRead(S1)>600?1:0;
+  int s2 = analogRead(S2)>600?1:0;

   Serial.print("S");
   Serial.print(s1);


Added talking lights on Digital 12 pin

Added talking lights on Digital 12 pin

--- Skulleyes.ino
+++ Skulleyes.ino
@@ -30,8 +30,14 @@

 Adafruit_8x8matrix matrix = Adafruit_8x8matrix();

+// Pin 13 has an LED connected on most Arduino boards.
+// give it a name:
+int led = 12;
+
 void setup() {
   Serial.begin(9600);
+
+  pinMode(led, OUTPUT);

   randomSeed(analogRead(0));

@@ -192,6 +198,22 @@
   eyesDraw(eye_off);
 }

+/*
+void eyesTalk() {
+  eyesDraw(eye_off);
+  eyesDraw(eye_center);
+
+  int choice = random(20,40);
+  for (int i=0; i<choice; i++) {
+    digitalWrite(led, HIGH);
+    delay(random(100, 300));
+    digitalWrite(led, LOW);
+    delay(random(100, 300));
+  }
+
+  eyesDraw(eye_off);
+}
+*/

 void loop() {
   int choice = random(4);
@@ -208,6 +230,9 @@
     case 3:
       eyesClock();
       break;
+    //case 4:
+    //  eyesTalk();
+    //  break;
     default:
       ;
   }


improved ringps resolution.  CHECK MY WORK

--- TICC/TICC.ino
+++ TICC/TICC.ino
@@ -1,7 +1,7 @@
 // TICC.ino - master sketch file

 // TICC Time interval Counter based on TICC Shield using TDC7200
-// version 0.62 -- 6 August 2016
+// version 0.65 -- 6 August 2016

 // Copyright John Ackermann N8UR 2016
 // Portions Copyright George Byrkit K9TRV 2016


arrumando erro de compilação no sendcode (faltou um repeat como parametro)

--- codigo.ino
+++ codigo.ino
@@ -117,7 +117,7 @@
 {
     if (codeType == NEC)
     {
-        sendCodeNec();
+        sendCodeNec(repeat);
     }
     else if (codeType == SONY)
     {
@@ -133,7 +133,7 @@
         sendCodeUnknow();
     }
 }
-void sendCodeNec()
+void sendCodeNec(int repeat)
 {

     if (repeat)


Update simple publish example

Update simple publish example

--- examples/rapifire-mqtt-simple-publish/rapifire-mqtt-simple-publish.ino
+++ examples/rapifire-mqtt-simple-publish/rapifire-mqtt-simple-publish.ino
@@ -29,7 +29,7 @@
     }
   }

-  rapifire.addValue("test", "", counter++);
+  rapifire.addValue("test", counter++);
   rapifire.publish();

   Serial.print("counter: ");


Update door-sign.ino

Update door-sign.ino

--- firmware/door-sign.ino
+++ firmware/door-sign.ino
@@ -16,7 +16,7 @@

     // Placeholder text before we recieve first update
     lcd->setCursor(0,0);
-    lcd->print("Alex is at:");
+    lcd->print("Ryan is at:");

     // Register the Spark cloud functions
     Spark.function("update", update);


Added error when MAXSERIALCOMMANDS value has not been changed in the SerialCommand library. Modification in the serial command that returns the current version of the software.

--- SkyPointer.ino
+++ SkyPointer.ino
@@ -2,6 +2,11 @@
 #include <EEPROM.h>
 #include "sky_pointer.h"

+#define VERSION "2.1"
+
+#if MAXSERIALCOMMANDS < 11
+#error "Please increase MAXSERIALCOMMANDS to 11 in SerialCommand library"
+#endif

 SkyPointer sp = SkyPointer();
 SerialCommand sCmd;
@@ -51,7 +56,7 @@

 // Get ID
 void ProcessId() {
-  Serial.print("SkyPointer 1.0\r");
+    Serial.print("SkyPointer v"VERSION"\r");
 }

 // Release both motors and shut down the laser


Added comments to no_wait_for_conversion.ino

--- Sensor_Tests/one_wire_non_blocking/no_wait_for_conversion.ino
+++ Sensor_Tests/one_wire_non_blocking/no_wait_for_conversion.ino
@@ -1,7 +1,7 @@
 #include <OneWire.h>
 #include <DallasTemperature.h>

-
+// Digital pin that sensor is connected to
 #define ONE_WIRE_BUS 4

@@ -10,13 +10,15 @@
 // Pass our oneWire reference to Dallas Temperature.
 DallasTemperature sensors(&oneWire);

+//We will need to change this to code that checks how many sensors on the chain
 DeviceAddress tempDeviceAddress;

-int  resolution = 12;
-unsigned long lastTempRequest = 0;
-int  delayInMillis = 0;
-float temperature = 0.0;
-int  idle = 0;
+//Setting up variables
+int  resolution = 12;              //resolution from 9-12 bits
+unsigned long lastTempRequest = 0; //when the last read occured
+int  delayInMillis = 0;            //how long to wait for a read
+float temperature = 0.0;           //the temperature
+int  idle = 0;                     //how long we stay in the main loop

 void setup(void)
 {
@@ -26,7 +28,9 @@
   sensors.getAddress(tempDeviceAddress, 0);
   sensors.setResolution(tempDeviceAddress, resolution);

+  // This is the library function that disables needing to hold the pin state
   sensors.setWaitForConversion(false);
+
   sensors.requestTemperatures();
   delayInMillis = 750 / (1 << (12 - resolution));
   lastTempRequest = millis();


teste.ino

teste.ino

--- utils/ASInterface/teste.ino
+++ utils/ASInterface/teste.ino
@@ -1,11 +1,3 @@
-
-/**********************************************
- *        Writed by @AndressAndrade           *
- *                                            *
- *       A-Star Robot for Arduino 2017        *
- *   This code uses A* to make a robot able   *
- *        to get out of a labyrinth           *
- *********************************************/
 /*Libraries*/
 //#include <Ultrasonic.h>


Se añade proyecto luces ritmicas

Se añade proyecto luces ritmicas


Removed debugging stuff.

Removed debugging stuff.

--- PLDuinoAVR/libraries/PLDuino/examples/Demo-v2_ATMEGA/Demo-v2_ATMEGA.ino
+++ PLDuinoAVR/libraries/PLDuino/examples/Demo-v2_ATMEGA/Demo-v2_ATMEGA.ino
@@ -96,7 +96,7 @@
   bool testmode = false;
   for(int i=1; i<8; ++i)
     testmode |= !digitalRead(30+i);
-  switch(MODE_WIFI)//showModeSelectionScreen(testmode? MODE_TEST : MODE_DEMO, 10))
+  switch(showModeSelectionScreen(testmode? MODE_TEST : MODE_DEMO, 10))
   {
     case MODE_DEMO:
       demo();


sketch: add averaging, layout, comments

sketch: add averaging, layout, comments

--- src/src.ino
+++ src/src.ino
@@ -1,14 +1,23 @@
 #include <math.h>

+// A physical location
 typedef struct Location {
   double lat;
   double lng;
 } Location;

+// A name attached to a physical location
 typedef struct Destination {
   char name[16];
   Location loc;
 } Destination;
+
+// Waypoints to be used for navigation
+Destination dests[] = {
+  {"Test", {0.0, 10.0}},
+  {"Home", {45.022884, -93.244983}},
+  {"Work", {44.989136, -93.250454}},
+};

 // Updated by on_new_gps
 // Location
@@ -24,11 +33,10 @@
 // ETA in milliseconds. If negative, we're traveling away from current_dest
 double eta_time = 0;

-Destination dests[] = {
-  {"Test", {0.0, 10.0}},
-  {"Home", {45.022884, -93.244983}},
-  {"Work", {44.989136, -93.250454}},
-};
+// For averaging ETA
+const int avg_count = 10;
+double avg_buf[avg_count] = {0};
+int avg_buf_pos = 0;

 // Change current_dest to change the distance and eta
 Location current_dest = dests[0].loc;
@@ -38,6 +46,22 @@
   return sqrt(pow(from.lat - to.lat, 2) + pow(from.lng - to.lng, 2));
 }

+// Stores a value for the sliding window average
+void put_avg(double val) {
+  avg_buf[avg_buf_pos] = val;
+  avg_buf_pos = (avg_buf_pos + 1) % avg_count;
+}
+
+// Gets the average of all stored values
+double get_avg() {
+  double avg = 0;
+  for (int i = 0; i < avg_count; i++) {
+    avg += avg_buf[i] / avg_count;
+  }
+  return avg;
+}
+
+// Called when the GPS has a new location
 void on_new_gps(double lat, double lng) {
   current_loc.lat = lat;
   current_loc.lng = lng;
@@ -51,14 +75,18 @@
   delta_dist = current_dist - last_dist;

   eta_time = -delta_time * current_dist / delta_dist;
+  put_avg(eta_time / 1000);
 }

+// Used for simulating GPS data
+unsigned long update_at = 0;
+
+// Start serial
 void setup() {
   Serial.begin(9600);
 }

-unsigned long update_at = 0;
-
+// Fake GPS data and print calculated values
 void loop() {
   if (millis() >= update_at) {
     update_at = millis() + 250;
@@ -72,7 +100,7 @@
     Serial.println(current_loc.lng, 6);
     Serial.println(current_dist);
     Serial.println(delta_dist);
-    Serial.println(eta_time / 1000);
+    Serial.println(get_avg());
     Serial.println();
   }
 }


Moved switch state initialization

Moved switch state initialization

--- src/src.ino
+++ src/src.ino
@@ -6,7 +6,9 @@
 const int launchKey = 13;
 const int led = 8;
 const int launchButton = 7;
+const int rcsSwitch = 11;
 boolean doneLaunch;
+int rcsBit;

 void setup()
 {
@@ -18,17 +20,14 @@
   pinMode(launchButton, INPUT);
   //Setup state
   doneLaunch = false;
+  rcsBit = 0;
 }

 void loop()
 {
-  //Setup switch detection
-  int keyState;
-  keyState = digitalRead(launchKey);
-  int launchState;
-  launchState = digitalRead(launchButton);
+  initState();
   //Turn on the LED if the key is turned
   if(keyState == LOW)
   {
@@ -53,6 +52,17 @@

 }

+void initState(){
+  //Setup switch detection
+  int keyState;
+  keyState = digitalRead(launchKey);
+  int launchState;
+  launchState = digitalRead(launchButton);
+  int rcsState;
+  rcsState = digitalRead(rcsState);
+}
+
+
 //Keyboard Implimentation, see:http://mitchtech.net/arduino-usb-hid-keyboard/
   void sendKey(int keyNum){
     buf[2] = keyNum;


Very basic signal smoothing for deskheight sensor


Added check for AVR around avr only test

--- tests/ioAbstractionTests/ioAbstractionTests.ino
+++ tests/ioAbstractionTests/ioAbstractionTests.ino
@@ -10,7 +10,9 @@
 #include "taskManagerTests.h"

 // always run this last as it adjusts the millisecond counter, to test rolling.
+#ifdef __AVR__
 #include "avrTaskManagerClockRoll.h"
+#endif

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


Set IR sensor pins to input mode explicitly

--- examples/3-Projects/LeonardoBreadboard/LeonardoBreadboard.ino
+++ examples/3-Projects/LeonardoBreadboard/LeonardoBreadboard.ino
@@ -76,6 +76,9 @@
 	getRadio(radioPins[0]);
 	getRadio(radioPins[1]);

+	pinMode(IRPins[0], INPUT);
+	pinMode(IRPins[1], INPUT);
+
 	delay(1000);
 }

@@ -228,12 +231,10 @@
 		lcd.print("IR");
 	lcd.setCursor(0,1);
 		lcd.print("Left:  ");
-		if(digitalRead(IRPins[0])) lcd.print("On ");
-		else lcd.print("Off");
+		lcd.print( (digitalRead(IRPins[0])? "On " : "Off" ) );
 	lcd.setCursor(0,2);
 		lcd.print("Right: ");
-		if(digitalRead(IRPins[1])) lcd.print("On ");
-		else lcd.print("Off");
+		lcd.print( (digitalRead(IRPins[1])? "On " : "Off" ) );
 	lcd.setCursor(0,3);
 }


Refactored and better paramaterized lineFollowBot_Line example

--- examples/3-Projects/LineFollowBot_Line/LineFollowBot_Line.ino
+++ examples/3-Projects/LineFollowBot_Line/LineFollowBot_Line.ino
@@ -11,65 +11,66 @@
 / and three QTI sensors in pins A0, A1, and A2
 /***************************************************/

-Servo leftServo, rightServo;
-bool left, middle, right;
+Servo left, right;

 float Lout, Rout;
 float Lset, Rset;

-unsigned long time;
-double dT;
-double adj;
-
-const int center = 90;
+const double rxtime    = 0.25;
+const int neutral      = 90;
+const int leftCenter   = 4;
+const int rightCenter  = 5;
+const int outsideSpeed = 45;
+const int insideSpeed  = 12;
+const int forwardSpeed = 35;

 void setup() {
-  Serial.begin(115200);
+  Serial.begin(9600);

-  leftServo.attach(5);
-  rightServo.attach(4);
+  left.attach(5);
+  right.attach(4);

-  leftServo.write(center);
-  rightServo.write(center);
+  left.write(neutral);
+  right.write(neutral);

-  Rout = center;
-  Lout = center;
+  Rout = neutral;
+  Lout = neutral;
 }

 void loop() {
-  left   = QTI(A0) > 120;
-  middle = QTI(A1) > 120;
-  right  = QTI(A2) > 120;
+  bool left   = QTI(A0) > 120;
+  bool middle = QTI(A1) > 120;
+  bool right  = QTI(A2) > 120;

   if (left) {
-    Lset = center + 6;
-    Rset = center + 45;
+    Lset = neutral + insideSpeed;
+    Rset = neutral + outsideSpeed;
   }
   else if (right) {
-    Lset = center - 45;
-    Rset = center - 6;
+    Lset = neutral - outsideSpeed;
+    Rset = neutral - insideSpeed;
   }
   else if (middle) {
-    Lset = center - 45;
-    Rset = center + 45;
+    Lset = neutral - forwardSpeed;
+    Rset = neutral + forwardSpeed;
   }

   output();
 }

+//all this is because the QTI Blocks for a variable amount of time
 void output() {
-  //all this is because the QTI Blocks for a variable amount of time
-#define rxtime .25
+  static uint32_t time = millis();

-  dT = ( double(millis() - time) / 100) ;
+  double dT = ( double(millis() - time) / 100) ;
   time = millis();

-  adj = pow(rxtime, dT);
+  double adj = pow(rxtime, dT);

   Rout = ( Rout * adj ) + ( Rset * (1 - adj) );
   Lout = ( Lout * adj ) + ( Lset * (1 - adj) );

-  leftServo.write(Lout);
-  rightServo.write(Rout);
+  left.write(Lout + leftCenter);
+  right.write(Rout+ rightCenter);
 }


Re-order switch cases for consistency

Re-order switch cases for consistency

--- Arduino/LightPlayer/LightPlayer.ino
+++ Arduino/LightPlayer/LightPlayer.ino
@@ -389,6 +389,10 @@
           GlobalPendingOperations.next_video = 1;
         } break;

+        case Pressed::c: {
+          CurrentMode = Mode::MACRO;
+        } break;
+
         case Pressed::d: {
           GlobalPendingOperations.skip_forward = 1;
         } break;
@@ -397,24 +401,20 @@
           CurrentMode = Mode::COLOR_CEILING;
         } break;

+        case Pressed::ac: {
+          CurrentMode = Mode::CYCLE_BULBS;
+        } break;
+
+        case Pressed::ad: {
+          CurrentMode = Mode::VIDEO_PLAYBACK;
+        } break;
+
+        case Pressed::bc: {
+          CurrentMode = Mode::MISC;
+        } break;
+
         case Pressed::cd: {
           CurrentMode = Mode::COLOR_FLOOR;
-        } break;
-
-        case Pressed::ad: {
-          CurrentMode = Mode::VIDEO_PLAYBACK;
-        } break;
-
-        case Pressed::c: {
-          CurrentMode = Mode::MACRO;
-        } break;
-
-        case Pressed::ac: {
-          CurrentMode = Mode::CYCLE_BULBS;
-        } break;
-
-        case Pressed::bc: {
-          CurrentMode = Mode::MISC;
         } break;
       }
     } break;
@@ -478,16 +478,16 @@
           GlobalPendingOperations.toggle_pause = 1;
         } break;

+        case Pressed::d: {
+          GlobalPendingOperations.skip_forward = 1;
+        } break;
+
         case Pressed::ac: {
           GlobalPendingOperations.prev_video = 1;
         } break;

         case Pressed::bd: {
           GlobalPendingOperations.next_video = 1;
-        } break;
-
-        case Pressed::d: {
-          GlobalPendingOperations.skip_forward = 1;
         } break;
       }
     } break;


Box_joint_final isnt really final. Its actually the test branch.

--- Box_joint_final/Box_joint_final.ino
+++ Box_joint_final/Box_joint_final.ino
@@ -5,24 +5,34 @@
  This removes alot of the wire clutter inside the box and makes it simpler to visualize
  what is connected to what and what it is doing.
  */
-
-#include <SerialLCD.h>
-#include <SoftwareSerial.h> //this is a must
-
-
-SerialLCD slcd(11,12); //Initialize the lcd lib.
-
-const int inPin1 = 5; //right red button
-const int inPin2 = 4; //left red button
-const int inPin3 = 3; //green menu button
-const int inPin4 = 8; //yellow enter button, I/O 2
-const int inPin5 = 7; //left limit switch. Green/White twisted pair.
-const int inPin6 = 6; //right limit switch. Blue/White twisted pair.
-
-//const int Hallpin = 2;               // wired to Hall Effect sensor output
-//const int CWpin  = 10;                // wired to MD01B pin INa
-//const int CCWpin = 9;                // wired to MD01B pin INb
-
+//*********************LIBRARY IMPORTS*********************************
+#include <Wire.h>
+#include <LiquidTWI.h>
+#include <Tap.h>
+
+LiquidTWI lcd(0); //Initialize the lcd lib.
+
+//**********************INPUT PINS**************************************
+
+const int rightRed = 5; //right red button
+const int leftRed = 4; //left red button
+const int greenMenu = 3; //green menu button
+const int yellowEnter = 8; //yellow enter button, I/O 2
+const int leftLimit = 7; //left limit switch. Green/White twisted pair.
+const int rightLimit = 6; //right limit switch. Blue/White twisted pair.
+
+//***********************OUTPUT PINS************************************
+
+const int pwmPin = 9;
+const int Hallpin = 2;               // wired to Hall Effect sensor output
+const int CWpin  = A1;                // wired to MD01B pin INa
+const int CCWpin = A0;                // wired to MD01B pin INb
+
+//*************************TAP lib constructors*************************
+Tap green(greenMenu);
+Tap right_Rb(rightRed);
+Tap left_Rb(leftRed);
+Tap yellow(yellowEnter);

 int loopCounter = 0; //Loop counter to refresh screen.
 unsigned long lcdUpdate;
@@ -40,16 +50,19 @@

 void setup() { //int yer inpins

-  pinMode(inPin1, INPUT);
-  pinMode(inPin2, INPUT);
-  pinMode(inPin3, INPUT);
-  pinMode(inPin4, INPUT);
-  pinMode(inPin5, INPUT);
-  pinMode(inPin6, INPUT);
-
-  Serial.begin(9600);
-  slcd.begin();
-  slcd.backlight();
+  pinMode(rightRed, INPUT);
+  pinMode(leftRed, INPUT);
+  pinMode(greenMenu, INPUT);
+  pinMode(yellowEnter, INPUT);
+  pinMode(leftLimit, INPUT);
+  pinMode(rightLimit, INPUT);
+
+  pinMode(pwmPin, OUTPUT);
+  pinMode(CWpin, OUTPUT);
+  pinMode(CCWpin, OUTPUT);
+
+  lcd.begin(20,4);
+  lcd.setBacklight(HIGH);
 }

 void loop() { //high speed code goes here
@@ -57,12 +70,8 @@
 }

 void mainMenu() { //this is the overall menu controller
-  int inputLeft = digitalRead(inPin2);
-  int inputRight = digitalRead(inPin1);
-  int menuButton = digitalRead(inPin3);
-  int enterButton = digitalRead(inPin4);
-
-  if (menuButton == HIGH){
+
+  if (green.isHit()){
     noClear();
     menuMode++;
     delay(50);
@@ -87,14 +96,13 @@
 }

 void setupDefault() { //this is the default setup menu
-  int inputRight = digitalRead(inPin1);
-  int inputLeft = digitalRead(inPin2);
-  int menuButton = digitalRead(inPin3);
-  int enterButton = digitalRead(inPin4);
+
   double targetInches = targetSteps * .00390625;

-  if (enterButton == HIGH) {
+  if (yellow.isHit()) {
     stepIncrements++;
+    lcd.setCursor(16,0);
+    lcd.print("    ");
     //noClear();
   }
   if (stepIncrements == 3) {
@@ -112,81 +120,65 @@
     break;
   }

-  if (inputRight == HIGH) {
+  if (right_Rb.isHit()) {
     targetSteps = targetSteps + stepMultiplier;
     refreshScreen =1;
   }
-  else if (inputLeft == HIGH) {
+  else if (left_Rb.isHit()) {
     targetSteps = targetSteps - stepMultiplier;
     refreshScreen = 1;
   }

-  if (refreshScreen == 1 && !inputLeft && !inputRight) {
+  if (refreshScreen == 1 && !left_Rb.isHit() && !right_Rb.isHit()) {
     noClearBottom();
     refreshScreen = 0;
   }
-  slcd.setCursor(0, 0);
-  slcd.print(" steps ");
-  slcd.setCursor(7,0);
-  slcd.print(stepIncrements, DEC);
-  slcd.setCursor(8, 0);
-  slcd.print(" inches ");
-  slcd.setCursor(1, 1);
-  slcd.print(targetSteps, DEC);
-  lcdPrintDouble(targetInches, 5, 9, 1);
+  lcd.setCursor(0,0);
+  lcd.print("Setup");
+
+    if (stepIncrements == 0){
+    lcd.setCursor(7,0);
+    lcd.print("Incr. x 1");
+    }
+      if (stepIncrements == 1){
+      lcd.setCursor(7,0);
+      lcd.print("Incr. x 10");
+      }
+        if (stepIncrements == 2){
+        lcd.setCursor(7,0);
+        lcd.print("Incr. x 100");
+        }
+
+  lcd.setCursor(0, 2);
+  lcd.print("Steps ");
+
+  lcd.setCursor(8, 2);
+  lcd.print("Inches ");
+  lcd.setCursor(1, 3);
+  lcd.print(targetSteps, DEC);
+  lcd.setCursor(9,3);
+  lcd.print(targetInches,4);
 }

 void jogMenuMode() { //This is the controller for jog mode
-  slcd.setCursor(0, 0);
-  slcd.print("Jog mode | steps");
+  lcd.setCursor(0, 0);
+  lcd.print("Jog mode | steps");
   jogMenuControl();
-}
-
-void jogMenuControl() { //This is the action code for jog mode
-  int inputRight = digitalRead(inPin1);
-  int inputLeft = digitalRead(inPin2);
-
-  if (inputLeft == HIGH) {
-    testVar++;
-    slcd.setCursor(8, 1);
-    slcd.print("<--");
-    refreshScreen = 1;
-  }
-  else if (inputRight == HIGH) {
-    testVar++;
-    slcd.setCursor(8, 1);
-    slcd.print("-->");
-    refreshScreen = 1;
-  }
-  else {
-    testVar = 0;
-  }
-  if (refreshScreen == 1 && !inputLeft && !inputRight) {
-    noClearBottom();
-    refreshScreen = 0;
-  }
-
-  slcd.setCursor(12, 1);
-  slcd.print(testVar, DEC);
-  slcd.setCursor(0, 1);
-  slcd.print(refreshScreen, DEC);
 }

 void slewMenuMode() { //this is the slewing controller
   if (lcdRefreshOK()) {
     noClear;
   }
-  slcd.setCursor(0, 0);
-  slcd.print("Slew Mode        ");
-  slcd.setCursor(12, 1);
-  slcd.print(menuMode, DEC);
-  slcd.setCursor(1, 1);
-  slcd.print(targetSteps, DEC);
-}
-
-void slewMenuControl() { //this is the sction code for slew mode.
-
-}
+  lcd.setCursor(0, 2);
+  lcd.print("Slew Mode        ");
+  lcd.setCursor(12, 1);
+  lcd.print(menuMode, DEC);
+  lcd.setCursor(1, 1);
+  lcd.print(targetSteps, DEC);
+}
+
+//*************************************** LCD HANDLERS **********************************

 boolean lcdRefreshOK() { //Refresh the lcd screen, this is a better way, calls noClear()
   boolean OK = false;
@@ -198,32 +190,32 @@
   return OK;
 }

-void noClear() { //prints blanks to the screen, looks way better that using slcd.clear().
-  slcd.setCursor(0,0);
-  slcd.print("                ");
-  slcd.setCursor(0,1);
-  slcd.print("                ");
+void noClear() { //prints blanks to the screen, looks way better that using lcd.clear().
+  lcd.setCursor(0,0);
+  lcd.print("                ");
+  lcd.setCursor(0,1);
+  lcd.print("                ");
 }

 void noClearBottom() { //does the same as noClear but only clears the bottom row.
-  slcd.setCursor(0,1);
-  slcd.print("                ");
+  lcd.setCursor(0,1);
+  lcd.print("                ");
 }

 void lcdPrintDouble( double val, byte precision, int row, int col){ // example: printDouble( 3.1415, 2, 0, 1); // prints 3.14 (two decimal places)
   // prints val on a ver 0012 text lcd with number of decimal places determine by precision
   // precision is a number from 0 to 6 indicating the desired decimial places
   // example: printDouble( 3.1415, 2); // prints 3.14 (two decimal places)
-  slcd.setCursor(row,col);
+  lcd.setCursor(row,col);

   if(val < 0.0){
-    slcd.print('-');
+    lcd.print('-');
     val = -val;
   }

-  slcd.print (val,DEC);  //prints the int part
+  lcd.print (val,DEC);  //prints the int part
   if( precision > 0) {
-    slcd.print("."); // print the decimal point
+    lcd.print("."); // print the decimal point
     unsigned long frac;
     unsigned long mult = 1;
     byte padding = precision -1;
@@ -238,15 +230,60 @@
     while( frac1 /= 10 )
       padding--;
     while(  padding--)
-      slcd.print("0");
-    slcd.print(frac,DEC) ;
-  }
-}
-
-void rightLimitHandler() {
+      lcd.print("0");
+    lcd.print(frac,DEC) ;
+  }
+}
+
+
+//***************** MOTOR HANDLING *************************
+
+void rightLimitHandler() { //this controld the behavior of the system when the RIGHT limit switch is HIGH.
   // placeholder
 }

-void leftlimit() {
+void leftlimit() { //this controld the behavior of the system when the LEFT limit switch is HIGH.
   //placeholder
+}
+
+/*
+void stopMotor(){ //This is to stop the motor
+  digitalWrite(CWpin, LOW);
+  digitalWrite(CCWpin, LOW);
+}
+*/
+
+void slewMenuControl() { //this is the action code for slew mode.
+
+}
+
+void jogMenuControl() { //This is the action code for jog mode
+
+  boolean rightRed_b = digitalRead(rightRed);
+  boolean leftRed_b = digitalRead(leftRed);
+
+  if (left_Rb.isHit()) {
+    testVar++;
+    lcd.setCursor(8, 1);
+    lcd.print("<--");
+    refreshScreen = 1;
+  }
+  else if (right_Rb.isHit()) {
+    testVar++;
+    lcd.setCursor(8, 1);
+    lcd.print("-->");
+    refreshScreen = 1;
+  }
+  else {
+    testVar = 0;
+  }
+  if (refreshScreen == 1 && !rightRed_b && !leftRed_b) {
+    noClearBottom();
+    refreshScreen = 0;
+  }
+
+  lcd.setCursor(12, 1);
+  lcd.print(testVar, DEC);
+  lcd.setCursor(0, 1);
+  lcd.print(refreshScreen, DEC);
 }


новый формат посылки

новый формат посылки

--- serialracoon.ino
+++ serialracoon.ino
@@ -1,28 +1,16 @@

-/* YourDuino.com Example: BlueTooth HC-05 Setup
- - WHAT IT DOES:
-   - Sets "Key" pin on HC-05 HIGH to enable command mode
-   - THEN applies Vcc from 2 Arduino pins to start command mode
-   - SHOULD see the HC-05 LED Blink SLOWLY: 2 seconds ON/OFF
-
- Sends, Receives AT commands
-   For Setup of HC-05 type BlueTooth Module
-   NOTE: Set Serial Monitor to 'Both NL & CR' and '9600 Baud' at bottom right
- - SEE the comments after "//" on each line below
- - CONNECTIONS:
+/*
+   CONNECTIONS:
    - GND
    - Pin 2 to HC-05 TXD
    - Pin 3 to HC-05 RXD
    - Pin 4 to HC-05 KEY
    - Pin 5+6 to HC-05 VCC for power control
- - V1.02 05/02/2015
-   Questions: terry@yourduino.com */
-
-/*-----( Import needed libraries )-----*/
+ */
+
 #include <SoftwareSerial.h>
 #include <SFE_BMP180.h>

-/*-----( Declare Constants and Pin Numbers )-----*/
 #define HC_05_TXD_ARDUINO_RXD 2
 #define HC_05_RXD_ARDUINO_TXD 3
 #define HC_05_SETUPKEY        4
@@ -32,10 +20,9 @@

 #define msg(x) Serial.println(x)

-/*-----( Declare objects )-----*/
+const int board = 0; // 0 -- for outdoor, 1 -- indor module
+
 SoftwareSerial BTSerial(HC_05_TXD_ARDUINO_RXD, HC_05_RXD_ARDUINO_TXD); // RX | TX
-/*-----( Declare Variables )-----*/
-//NONE

 enum BTDeviceState {
   error = -2,
@@ -153,7 +140,6 @@
 }

 int cnt = 0;
-int board = 0;

 const int aInPin = A0;
 int analogPin = 3;
@@ -167,6 +153,8 @@
 double T = -10.0;
 double P = -10.0;

+#define bt_echo_send(x) Serial.print(x); BTSerial.write(x);
+#define fbt_echo_send(x) bt_echo_send(x); bt_echo_send(" ");

 void loop()
 {
@@ -208,32 +196,39 @@
   char status;

   // abirvalg!!!
-
-  status = pressure.startTemperature();
-  if (status != 0)  {
-    delay(status);
-    status = pressure.getTemperature(T);
-    Serial.println(T);
-    if (status != 0) {
-      status = pressure.startPressure(3);
+  if (board == 0) {
+    status = pressure.startTemperature();
+    if (status != 0)  {
+      delay(status);
+      status = pressure.getTemperature(T);
+      //Serial.println(T);
       if (status != 0) {
-        delay(status);
-
-        status = pressure.getPressure(P,T);
+        status = pressure.startPressure(3);
         if (status != 0) {
-
+          delay(status);
+
+          status = pressure.getPressure(P,T);
+          if (status != 0) {
+
+          } else { T = -1.0; P = -1.0; }
         } else { T = -1.0; P = -1.0; }
       } else { T = -1.0; P = -1.0; }
     } else { T = -1.0; P = -1.0; }
-  } else { T = -1.0; P = -1.0; }
-
-
-  if (board == 0) {
-    char out[80];
-    //sprintf(out, "seqid %d;%d;;;\r\n", cnt++, val); // 0.7501
-    sprintf(out, "seqid=%d;A0=%d;A1=%d;D8=%d;D10=%d;T=%d;P=%d\r\n", cnt, v0, v1, d8, d10, (int)T, (int)(P*0.7501));
-    Serial.print(out);
-    BTSerial.write(out);
+
+    bt_echo_send("(")
+    fbt_echo_send(cnt);
+    fbt_echo_send(v0);
+    fbt_echo_send(-1);
+    fbt_echo_send(-1);
+    fbt_echo_send(v1);
+    fbt_echo_send(d8);
+    fbt_echo_send(d10);
+    fbt_echo_send(T);
+    fbt_echo_send(P);
+    bt_echo_send(")")
+
+    bt_echo_send("\r\n")
+
     delay(100);
   }
   cnt++;


Fixed example and added note

Fixed example and added note

--- examples/AnalogKeysExample/AnalogKeysExample.ino
+++ examples/AnalogKeysExample/AnalogKeysExample.ino
@@ -2,6 +2,8 @@
 	AnalogKeys example file - Library for analog key managment for lcds (designed for LCD Keypad Shield V2.0)
 	Created by Filip Smets, 22/05/2014.
 	Released into the public domain.
+
+        Note: Before you start using this library, make sure you understand how the lcd works!
 */

 #include <LiquidCrystal.h>
@@ -32,6 +34,9 @@
 boolean needsCalibration = true;

 void setup () {
+  lcd.begin(16, 2);
+  lcd.clear();
+  lcd.print("Calibrating keys...");
   needsCalibration = true;
 }


Update Pegasus_vehicle.ino

Update Pegasus_vehicle.ino

-reduced main loop to 2.5ms from 5ms
-removed call to esc_calibrate() in setup for safety( in the event of temporary power loss to the board but not ESC's)
-reduced gyro sensitivity, set g-force sensor range to 16 from 4
-added PID integral reset when motors off
-changed DEBUG to check value instead of #ifdef

--- Pegasus_vehicle/Pegasus_vehicle.ino
+++ Pegasus_vehicle/Pegasus_vehicle.ino
@@ -17,8 +17,8 @@
 #include "pPID.h"
 #include "CurveRemap.h"

-//#define DEBUG
-#ifdef DEBUG
+#define DEBUG false
+#if DEBUG
 #define Serial_begin(x) Serial.begin(x);
 #define print(x) Serial.print(x);
 #else
@@ -67,22 +67,23 @@
 // motor power output
 long power_FL, power_FR, power_BR, power_BL;

-// throttle-thrust correction
+// linear throttle-thrust correction
 CurveRemap tt;
-
+/* // unchanged set
 #define FLTTLENGTH 2
 unsigned short FL_tt_x[FLTTLENGTH] = {0,65535};
-unsigned short FL_tt_y[FLTTLENGTH] = {3195,65535};
+unsigned short FL_tt_y[FLTTLENGTH] = {0,65535};
 #define FRTTLENGTH 2
 unsigned short FR_tt_x[FRTTLENGTH] = {0,65535};
-unsigned short FR_tt_y[FRTTLENGTH] = {3195,65535};
+unsigned short FR_tt_y[FRTTLENGTH] = {0,65535};
 #define BRTTLENGTH 2
 unsigned short BR_tt_x[BRTTLENGTH] = {0,65535};
-unsigned short BR_tt_y[BRTTLENGTH] = {3195,65535};
+unsigned short BR_tt_y[BRTTLENGTH] = {0,65535};
 #define BLTTLENGTH 2
 unsigned short BL_tt_x[BLTTLENGTH] = {0,65535};
-unsigned short BL_tt_y[BLTTLENGTH] = {3195,65535};
-/*
+unsigned short BL_tt_y[BLTTLENGTH] = {0,65535};
+*/
+/* // mapped set
 #define FLTTLENGTH 14
 unsigned short FL_tt_x[FLTTLENGTH] = {0,1843,25384,25465,26711,32691,37411,44993,45244,47404,53389,60687,62966,65535};
 unsigned short FL_tt_y[FLTTLENGTH] = {3359,4022,29892,30626,31276,37814,41815,47131,47705,48586,52278,56283,58021,59281};
@@ -96,20 +97,17 @@
 unsigned short BL_tt_x[BLTTLENGTH] = {0,2558,25426,26377,26494,28842,41066,47144,47512,49400,65535};
 unsigned short BL_tt_y[BLTTLENGTH] = {3195,3894,24949,26229,26919,28269,40086,44674,45374,46146,55350};
 */
+
 // timers
 unsigned long elapsed_ms;
-
 unsigned short longPeriod = 500;
 unsigned long lastLongTime = millis();
-
 byte loggerPeriod = 40;
 unsigned long lastloggerTime = millis();
-
 byte midPeriod = 21;
 unsigned long lastMidTime = millis();
-
 unsigned long elapsed_si;
-unsigned short shortPeriod = 5000; //microseconds(si) 2500=400Hz, 5000=200Hz, 10000=100Hz
+unsigned short shortPeriod = 2500; //microseconds(si) 2500=400Hz, 5000=200Hz, 10000=100Hz
 unsigned long lastShortTime = micros();
 unsigned long lastShortTimeMS = millis();

@@ -146,7 +144,8 @@
     esc.init(motorPin_FR);
     esc.init(motorPin_BR);
     esc.init(motorPin_BL);
-    esc_calibrate();
+    //esc_calibrate();
+    motor_off();
     print("ESC Setup Complete\n");

     // RX initialize
@@ -166,10 +165,10 @@
     pid_config();

     //GyroAngle.config( ushort FullScaleRangeDPS,
-    //                  ulong deltaTime_UnitsPerSecond,
+    //                  ulong deltaTime,
     //                  float correction_weight
     //                  bool invX, invY, invZ)
-    gyro.config(2000, 1000000, 0.005, false, true, true);
+    gyro.config(2000, 1000000, 0.0025, false, true, true); // wtf is deltaTime 1,000,000 here
     accel.config(false, true, false);//args are for inverting axis
     compass.config(152.0, 197.5, -172.5, 1.076132, 1.039761, 1.0); // see compass_calibrate()

@@ -177,7 +176,7 @@
     print("IMU Setup...");
     imu.initialize();
     imu.setFullScaleGyroRange(MPU9255_GYRO_FS_2000);//250, 500, 1000, 2000dps
-    imu.setFullScaleAccelRange(MPU9255_ACCEL_FS_4);//2, 4, 8, 16g
+    imu.setFullScaleAccelRange(MPU9255_ACCEL_FS_16);//2, 4, 8, 16g
     imu.magInitialize();
     if (!imu.testConnection()) {
         print("Connection_Failed\n");
@@ -246,12 +245,14 @@
     }
     gyro.correctZ(compass.yaw);

+    pid_update();
     if (ctrl.live) {
-        pid_update();
         motor_update();
     }else{
         motor_off();
-        // zero out yaw
+        PID_yaw.restIntegral();
+        PID_pitch.restIntegral();
+        PID_roll.restIntegral();
         gyro.zeroZ();
         compass.zero();
     }
@@ -263,17 +264,19 @@
     /*if(ctrl.live){
         logger.append_IMU(lastloggerTime, gyro.posX, gyro.posY, gyro.posZ);
         logger.append_PID(lastloggerTime, op_roll, op_pitch, op_yaw);
-        logger.append_MP(lastloggerTime, power_FL, power_FR, power_BR, power_BL);
+        //logger.append_MP(lastloggerTime, power_FL, power_FR, power_BR, power_BL);
         logger.append_RX(lastloggerTime, ctrl.rollf, ctrl.pitchf, ctrl.yawf, ctrl.throttle);
         logger.writeOnFull();
     }*/
-    print("IMU "); print(lastShortTimeMS); print(" "); print(gyro.posX); print(" "); print(gyro.posY); print(" "); print(gyro.posZ); print("\n");
-    //print("GRATE "); print(lastShortTimeMS); print(" "); print(gyro.rateX); print(" "); print(gyro.rateY); print(" "); print(gyro.rateZ); print("\n");
-    print("GRSUM "); print(lastShortTimeMS); print(" "); print(gyro.rsumX); print(" "); print(gyro.rsumY); print(" "); print(gyro.rsumZ); print("\n");
-    print("ACC "); print(lastShortTimeMS); print(" "); print(accel.x); print(" "); print(accel.y); print(" "); print(compass.yaw); print("\n");
-    //print("MAG "); print(lastShortTimeMS); print(" ");print(compass.mx); print(" "); print(compass.my); print(" "); print(compass.mz); print("\n");
-    print("PID "); print(lastShortTimeMS); print(" "); print(op_roll); print(" "); print(op_pitch); print(" "); print(op_yaw); print("\n");
-    print("MP "); print(lastShortTimeMS); print(" "); print(power_FL); print(" "); print(power_FR); print(" "); print(power_BR); print(" "); print(power_BL); print("\n");
+    #if DEBUG
+        print("IMU "); print(lastShortTimeMS); print(" "); print(gyro.posX); print(" "); print(gyro.posY); print(" "); print(gyro.posZ); print("\n");
+        //print("GRATE "); print(lastShortTimeMS); print(" "); print(gyro.rateX); print(" "); print(gyro.rateY); print(" "); print(gyro.rateZ); print("\n");
+        //print("GRSUM "); print(lastShortTimeMS); print(" "); print(gyro.rsumX); print(" "); print(gyro.rsumY); print(" "); print(gyro.rsumZ); print("\n");
+        //print("ACC "); print(lastShortTimeMS); print(" "); print(accel.x); print(" "); print(accel.y); print(" "); print(compass.yaw); print("\n");
+        //print("MAG "); print(lastShortTimeMS); print(" ");print(compass.mx); print(" "); print(compass.my); print(" "); print(compass.mz); print("\n");
+        print("PID "); print(lastShortTimeMS); print(" "); print(op_roll); print(" "); print(op_pitch); print(" "); print(op_yaw); print("\n");
+        print("MP "); print(lastShortTimeMS); print(" "); print(power_FL); print(" "); print(power_FR); print(" "); print(power_BR); print(" "); print(power_BL); print("\n");
+    #endif
   }
 }

@@ -377,26 +380,28 @@
   PID_roll.config(shortPeriod, ctrl.Kp_roll, ctrl.Ki_roll, ctrl.Kd_roll, 0.0-float(throttleMax), float(throttleMax));
 }

-void motor_update() {
+void motor_update() {
   //    roll
   // fl-----fr
   // |  yaw  | pitch
   // bl-----br

   op_throttle = int(ctrl.throttlef);
+
   power_FL = op_throttle + op_pitch + op_roll - op_yaw;
   power_FR = op_throttle + op_pitch - op_roll + op_yaw;
   power_BR = op_throttle - op_pitch - op_roll - op_yaw;
   power_BL = op_throttle - op_pitch + op_roll + op_yaw;
   /*
+  power_FL = constrain(power_FL, 0, throttleMax);
+  power_FR = constrain(power_FR, 0, throttleMax);
+  power_BR = constrain(power_BR, 0, throttleMax);
+  power_BL = constrain(power_BL, 0, throttleMax);
   power_FL = tt.interp(power_FL, FL_tt_x, FL_tt_y, FLTTLENGTH);
   power_FR = tt.interp(power_FR, FR_tt_x, FR_tt_y, FRTTLENGTH);
   power_BR = tt.interp(power_BR, BR_tt_x, BR_tt_y, BRTTLENGTH);
   power_BL = tt.interp(power_BL, BL_tt_x, BL_tt_y, BLTTLENGTH);
   */
-
-  //print("MP "); print(lastShortTimeMS); print(" "); print(power_FL); print(" "); print(power_FR); print(" "); print(power_BR); print(" "); print(power_BL); print("\n");
-
   esc.update(motorPin_FL, power_FL);
   esc.update(motorPin_FR, power_FR);
   esc.update(motorPin_BR, power_BR);
@@ -404,6 +409,10 @@
 }

 void motor_off() {
+    power_FL = 0;
+    power_FR = 0;
+    power_BR = 0;
+    power_BL = 0;
     esc.update(motorPin_FL, 0);
     esc.update(motorPin_FR, 0);
     esc.update(motorPin_BR, 0);
@@ -468,11 +477,11 @@
   //accel.setRestingPosition(int(ax_avg), int(ay_avg), int(az_avg)); // only use if craft is perfectly level
   accel.update(int(ax_avg), int(ay_avg), int(az_avg));
   gyro.init(gx_avg, gy_avg, gz_avg, accel.x, accel.y, 0.0); // gyro offset xyz, accel starting rotation xyz
-  #ifdef DEBUG
-    Serial.printf("accel resting vector %0.3f %0.3f %0.3f\n", ax_avg, ay_avg, az_avg);
-    Serial.printf("accel current angle %0.3f %0.3f %0.3f\n", accel.x, accel.y, accel.z);
-    Serial.printf("gyro rate offset %0.3f %0.3f %0.3f\n", gx_avg, gy_avg, gz_avg);
-    Serial.printf("compass resting heading %0.3f\n", compass.yaw);
+  #if DEBUG
+    //Serial.printf("accel resting vector %0.3f %0.3f %0.3f\n", ax_avg, ay_avg, az_avg);
+    //Serial.printf("accel current angle %0.3f %0.3f %0.3f\n", accel.x, accel.y, accel.z);
+    //Serial.printf("gyro rate offset %0.3f %0.3f %0.3f\n", gx_avg, gy_avg, gz_avg);
+    //Serial.printf("compass resting heading %0.3f\n", compass.yaw);
   #endif
   print("IMU Calibration Complete\n");
 }
@@ -510,10 +519,10 @@
     Yscale = longCord/(Ymax - Ymin);
     Zscale = longCord/(Zmax - Zmin);

-    #ifdef DEBUG
-        Serial.printf("X min %i max %i = offset %0.6f scale %0.6f\n", Xmin, Xmax, Xoffset, Xscale);
-        Serial.printf("Y min %i max %i = offset %0.6f scale %0.6f\n", Ymin, Ymax, Yoffset, Yscale);
-        Serial.printf("Z min %i max %i = offset %0.6f scale %0.6f\n", Zmin, Zmax, Zoffset, Zscale);
+    #if DEBUG
+        //Serial.printf("X min %i max %i = offset %0.6f scale %0.6f\n", Xmin, Xmax, Xoffset, Xscale);
+        //Serial.printf("Y min %i max %i = offset %0.6f scale %0.6f\n", Ymin, Ymax, Yoffset, Yscale);
+        //Serial.printf("Z min %i max %i = offset %0.6f scale %0.6f\n", Zmin, Zmax, Zoffset, Zscale);
     #endif
   }
   compass.config(Xoffset,Yoffset,Zoffset,Xscale,Yscale,Zscale);
@@ -533,8 +542,5 @@
     esc.update(motorPin_BR, throttleMax);
     esc.update(motorPin_BL, throttleMax);
     delay(3000);
-    esc.update(motorPin_FL, 0);
-    esc.update(motorPin_FR, 0);
-    esc.update(motorPin_BR, 0);
-    esc.update(motorPin_BL, 0);
-}
+    motor_off();
+}


Increments the buffer to read the whole message

--- example/GPRS_LoopHandle/GPRS_LoopHandle.ino
+++ example/GPRS_LoopHandle/GPRS_LoopHandle.ino
@@ -13,12 +13,15 @@
 *********************************************************************************
 created on 2013/12/5, version: 0.1
 by lawliet.zou(lawliet.zou@gmail.com)
+
+2017/05/31
+Reads the full message, not only the first 20 characters (jzorrilla@x-red.com)
 */
 #include <gprs.h>
 #include <SoftwareSerial.h>
 #include <stdio.h>

-char gprsBuffer[64];
+char gprsBuffer[140];
 int i = 0;
 char *s = NULL;
 int inComing = 0;
@@ -45,18 +48,18 @@
    }

    if(inComing){
-      gprs.readBuffer(gprsBuffer,32,DEFAULT_TIMEOUT);
-      Serial.print(gprsBuffer);
+      gprs.readBuffer(gprsBuffer, 140, DEFAULT_TIMEOUT);
+      Serial.println(gprsBuffer);

       if(NULL != strstr(gprsBuffer,"RING")) {
           gprs.answer();
       }else if(NULL != (s = strstr(gprsBuffer,"+CMTI: \"SM\""))) { //SMS: $$+CMTI: "SM",24$$
           char message[MESSAGE_LENGTH];
           int messageIndex = atoi(s+12);
-          gprs.readSMS(messageIndex, message,MESSAGE_LENGTH);
+          gprs.readSMS(messageIndex, message, MESSAGE_LENGTH);
           Serial.print(message);
      }
-     gprs.cleanBuffer(gprsBuffer,32);
+     gprs.cleanBuffer(gprsBuffer,140);
      inComing = 0;
    }
 }


Delete R_ANA3PT.ino

Delete R_ANA3PT.ino

--- Examples/R_ANA3PT-Arduino/R_ANA3PT.ino
+++ Examples/R_ANA3PT-Arduino/R_ANA3PT.ino
@@ -1,61 +0,0 @@
-/*-------------------------------------------------------------------------------------------------------------------------------------------*
- * SE2R : R_ANA3PT - Fonction de transformation d'un pourcentage en commande 3-Points                                             25/06/2015 *
- * ------------------------------------------------------------------------------------------------------------------------------------------*
- *        R_ANA3PT(float VPC[], float VTC[], int VNO, int VNF, int CFG)                                                           25/06/2015 *
- *                VPC : [00] : Signal de commande de régulation à convertir                                                                  *
- *                      [01] : Signal de commande retranscrit sur l'actionneur 3-points en fin du cycle courant                              *
- *                VTC : [00] : Durée du cycle de l'action 3-Points (s)                                                                       *
- *                      [01] : Durée totale de la pleine course de l'actionneur (s)                                                          *
- *                      [02] : Calcul du temps de cycle automate (s)                                                                         *
- *                      [03] : Compteur de durée depuis la dernière exécution de la fonction (s)                                             *
- *                      [04] : Mémoire des millis() de la dernière exécution de la fonction                                                  *
- *                      [05] : Durée de l'action sur les sorties pour le cycle d'exécution en cours                                          *
- *                VNO : Numéro de la voie de la sortie de commande d'ouverture  de l'actionneur 3-points                                     *
- *                VNF : Numéro de la voie de la sortie de commande de fermeture de l'actionneur 3-points                                     *
- *                CFG : Commande de forçage.                                                                                *
- *                      <0 : VPC[0] maintenu à 0                                                                                *
- *                      0  : VPC[0] figé dans sa dernière valeur connue                                                                      *
- *                      1  : VPC[0] est fixé par le calcul de régulation PID                                                                 *
- *                      2  : VPC[0] maintenue à VPC[3]                                                                                *
- *                      3  : VPC[0] maintenue à 100                                                                                *
- *                      >3 : VPC[0] maintenu à 0                                                                                *
- *       Interne  NUM : [00] : Mémoire dans l'exécution de l'écart du cycle précédent                                                        *
- *                      [01] : Mémoire dans l'exécution de la variation d'écart du cycle précédent                                           *
- *                      [02] : Mémoire dans l'exécution de la variation d'écart du cycle précédent                                           *
- *-------------------------------------------------------------------------------------------------------------------------------------------*
- * Copyright SE2R under the APACHE Licence                                                                                *
- *-------------------------------------------------------------------------------------------------------------------------------------------*
- * Plate-formes testées : Arduino Leonardo, Arduino Uno, Industruino                                                                         *
- * ------------------------------------------------------------------------------------------------------------------------------------------*
- * 25/06/2015 : DD, SE2R : Testée et validée sur banc                                                                                *
- * ------------------------------------------------------------------------------------------------------------------------------------------*/
-
-// Déclaration des bibliothèques nécessaires à l'exécution du programme ---------------------------------------------------------------------*
-#include <BMS.h>                         // Biblio   - SE2R - Fonctions BMS
-BMS BMS;
-
-// Déclaration des variables nécessaires à l'exécution du programme -------------------------------------------------------------------------*
-float VPC_XXXX[2];                       // R_ANA3PT - Table des commandes
-float VTC_XXXX[6];                       // R_ANA3PT - Table des coefficients de régulation
-int VNO_OUVR;                            // R_ANA3PT - Numéro de voie de la sortie de commande d'ouverture
-int VNF_FERM;                            // R_ANA3PT - Numéro de voie de la sortie de commande de fermeture
-int VCO_XXXX;                            // R_ANA3PT - Commande de forçage, ici en position auto
-void setup() {                           // Initialisation ----------------------------------------------------------------------------------*
-  VTC_XXXX[0] = 30;                      // R_ANA3PT - Durée du cycle de rafraîchissement de l'action sur la vanne
-  VTC_XXXX[1] = 180;                     // R_ANA3PT - Durée de la course complète de la vanne
-  VCO_XXXX = 1;                          // R_ANA3PT - Commande de forçage
-  pinMode(7, OUTPUT);                    // Système  - Affectation de la voie 07 en tant que sortie de commande d'ouverture
-  pinMode(8, OUTPUT);                    // Système  - Affectation de la voie 08 en tant que sortie de commande de fermeture
-  Serial.begin(9600);                    // Port COM - Paramétrage du port série
-}
-void loop() {                            // Exécution ---------------------------------------------------------------------------------------*
-  VPC_XXXX[0] = analogRead(0) / 10.23;                                              // Lecture 0-100% de l'entrée analogique 0
-  BMS.R_ANA3PT(VPC_XXXX, VTC_XXXX, 7, 8, VCO_XXXX);
-  Serial.print(VTC_XXXX[3]);
-  Serial.print("\t");
-  Serial.print(VTC_XXXX[5]);
-  Serial.print("\t");
-  Serial.print(VPC_XXXX[0]);
-  Serial.print("\t");
-  Serial.println(VPC_XXXX[1]);
-}


Fixed a typo of a comment in arduino_irrec.ino

--- arduino_irrec.ino
+++ arduino_irrec.ino
@@ -202,7 +202,7 @@
  * the pattern.  It aborts whenever IR state (on/off) does not change for
  * TIMEOUT_IR (microseconds).
  *
- * Note: It assumes IR detecting state is 'on' when the functions is called
+ * Note: It assumes IR detecting state is 'on' when the function is called
  */
 static int
 record_ir(int *tab, int maxlen)


Added working example with 2 LEDs. Got rid of pestering '/favicon.ico' requests

--- arduinofences.ino
+++ arduinofences.ino
@@ -4,7 +4,7 @@

 int RECV_PIN = 4;
 int BUTTON_PIN = 5;
-int STATUS_PIN = 13;
+int STATUS_PIN = 6;

 IRrecv irrecv(RECV_PIN);
 IRsend irsend;
@@ -14,9 +14,8 @@
 #define WIRELESS_MODE_INFRA	1
 #define WIRELESS_MODE_ADHOC	2

-#define ledPin1 13
-#define ledPin2 13
-#define ledPin3 13
+#define ledPin1 6
+#define ledPin2 7

 // Wireless configuration parameters ----------------------------------------
 unsigned char local_ip[] = {10,0,0,50};	// IP address of WiShield
@@ -64,20 +63,18 @@
     // Initialize WiServer and have it use the sendMyPage function to serve pages
     pinMode(ledPin1, OUTPUT);
     pinMode(ledPin2, OUTPUT);
-    pinMode(ledPin3, OUTPUT);

     //WiFi.init();
     WiServer.init(sendPage);
     WiServer.enableVerboseMode(true);
     states[0] = false;
     states[1] = false;
-    states[2] = false;
     Serial.println("Started webserver ...");
 }

 void printStates()
 {
-        for (stateCounter = 0 ; stateCounter < 3; stateCounter++)
+        for (stateCounter = 0 ; stateCounter < 2; stateCounter++)
         {
             boolToString(states[stateCounter], stateBuff);

@@ -93,7 +90,6 @@
         //set led states
         digitalWrite(ledPin1, states[0]);
         digitalWrite(ledPin2, states[1]);
-        digitalWrite(ledPin3, states[2]);
 }

 void boolToString (boolean test, char returnBuffer[4])
@@ -142,7 +138,7 @@
       WiServer.print("<title>Led switch</title>");

       WiServer.print("Please select the led state:\n");
-      for (stateCounter = 0; stateCounter < 3; stateCounter++) //for each led
+      for (stateCounter = 0; stateCounter < 2; stateCounter++) //for each led
       {
         numAsCharBuff[0] = (char)(stateCounter + 49); //as this is displayed use 1 - 3 rather than 0 - 2
         numAsCharBuff[1] = '\0'; //strcat expects a string (array of chars) rather than a single character.
@@ -167,10 +163,11 @@
         WiServer.print(" ");
         return true;
    }
-}
-
-// This is the webpage that is served up by the webserver
-const prog_char webpage[] PROGMEM = {"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n
Hello World!! I am WiShield
<form method=\"get\" action=\"0\">Toggle LED:<input type=\"submit\" name=\"0\" value=\"LED1\"></input></form>"};
+   else {
+     WiServer.print(" ");
+     return true;
+   }
+}

 // Storage for the recorded code
 int codeType = -1; // The type of code
@@ -293,7 +290,7 @@
     digitalWrite(STATUS_PIN, HIGH);
     sendCode(lastButtonState == buttonState);
     digitalWrite(STATUS_PIN, LOW);
-    delay(1000); // Wait a bit between retransmissions
+    delay(10); // Wait a bit between retransmissions
   }
   else if (irrecv.decode(&results)) {
     digitalWrite(STATUS_PIN, HIGH);
@@ -306,7 +303,7 @@

 void loop()
 {
-  ir_loop();
+  //ir_loop();
   WiServer.server_task();

   delay(10);


Remove incorrect fix.

Remove incorrect fix.

--- src/homie-sonoff-touch.ino
+++ src/homie-sonoff-touch.ino
@@ -32,9 +32,7 @@
 ClickButton button1(PIN_BUTTON, LOW, CLICKBTN_PULLUP);

 // Register our two HomieNode instances
-// nodeName(property, value, retained);
 HomieNode relayNode("relay", "relay");
-//HomieNode buttonNode("button", "button", false);
 HomieNode buttonNode("button", "button");

 bool RelayHandler(const HomieRange& range, const String& value) {