invert PWM output

invert PWM output

--- light-dress/light-dress.ino
+++ light-dress/light-dress.ino
@@ -17,9 +17,9 @@
 //Rx16Response rx16 = Rx16Response();

 /* High Power LED BUCKPUCK Control pins */
-#define LED1  13
-#define LED2  11
-#define LED3  10
+#define LED1  3
+#define LED2  5
+#define LED3  6

 #define CONSOLE   Serial
 //#define XBEEUART  Serial2
@@ -32,7 +32,7 @@

 /* MAXBOTIX Analog pin */
 // #define MAXBOTIX  A12 //A12 for teensy
-#define MAXBOTIX  A0 // A0...7 for Arduino
+#define MAXBOTIX A3 // A0...7 for Arduino

 /* Zones:
@@ -109,8 +109,8 @@

   CONSOLE.print(".");

-  analogWrite(LED1, frame->led1);
-  analogWrite(LED2, frame->led2);
+  analogWrite(LED1, (255-(frame->led1))); // inverting the output by subtracting the frame values from 255 because the BuckPucks are active on LOW
+  analogWrite(LED2, (255-(frame->led2)));
   //TODO: implement third LED

   anim->frame_delay = frame->delay;
@@ -118,9 +118,9 @@

   if (++anim->frame >= anim->num_frames) {
     if (--anim->repeat <= 0) {
-      analogWrite(LED1, 0);
-      analogWrite(LED2, 0);
-      analogWrite(LED3, 0);
+      analogWrite(LED1, 255); // 255 -> LED off
+      analogWrite(LED2, 255);
+      analogWrite(LED3, 255);
       set_next_state(STATE_ANIMATION_DONE);
     } else {
       CONSOLE.print("REPEAT: ");
@@ -257,7 +257,7 @@

     case STATE_XBEE_OVERRIDE_START:
       /* change animation.frames and animation.num_frames to the wanted animation frames structure */
-      animation.frames = (frameStc*)anim_xbee_override_frames;
+      animation.frames = (frameStc*) anim_xbee_override_frames;
       animation.num_frames = sizeof(anim_xbee_override_frames) / sizeof(frameStc);
       /***/
       animation.frame = 0;


Tested working simple, single key proof-of-concept!

--- sketches/test_key/test_key.ino
+++ sketches/test_key/test_key.ino
@@ -3,9 +3,6 @@

  Turns on and off a light emitting diode(LED) connected to digital
  pin 13, when pressing a key attached to pin 2.
-
- This is
-

  The circuit:
  * LED built in to pin 13, connected to ground
@@ -18,12 +15,12 @@
  by Tom Igoe
  modified 03 May 2016
  by @JDWarner
- */
+*/

 // constants won't change. They're used here to
 // set pin numbers:
-const int keyPin = 2;          // pin connected to organ key
-const int ledPin =  LED_BUILTIN;  // the number of the LED pin
+const int keyPin = 2;          // pin from organ key
+const int ledPin = LED_BUILTIN;  // LED pin
 bool keyState = false;    // the key state, starts off
 bool keyRead = false;     // input from digital pin

@@ -36,8 +33,8 @@
   // Compare them - state records inverse of switch read
   if (value == state) { // Equal means a change
     // Update values as needed, if needed
-    value = not state;
-    digitalWrite(ledPin, value);
+    state = not value;
+    digitalWrite(ledPin, state);
   }
 }


Update main.ino

Update main.ino

--- main/main.ino
+++ main/main.ino
@@ -21,9 +21,9 @@
 void setup(){

 Serial.begin(115200);
-inputs.begin(); // set inputs
-outputs.begin(); // set outputs
-interruptsfunctions.begin(); // set interrupts
+inputsinit(); // set inputs
+outputsinit(); // set outputs
+interruptsfunctionsinit(); // set interrupts

 }


add note

add note

--- main/main.ino
+++ main/main.ino
@@ -163,6 +163,7 @@

         engine_rpm.previousValue = engine_rpm.currentValue;
         engine_rpm.currentValue = buf[2] * 256 + buf[3];
+        engine_rpm.currentValue = 4938;

         engine_clt.previousValue = engine_clt.currentValue;
         engine_clt.currentValue = (buf[4] * 256 + buf[5]) / 10.0;
@@ -239,6 +240,7 @@
   }
 }

+//note: using log10 would work but this is faster
 bool is_current_value_shorter(EngineVariable engine) {
   int currentLength;
   if(engine.currentValue >= 10000) {


20150217.1236

--- cmdMULTIsens/src/sketch.ino
+++ cmdMULTIsens/src/sketch.ino
@@ -62,6 +62,7 @@
         Serial.println(" ");
         Serial.println("cmdMULTIsens help is underway!");
         Serial.println(" ");
+        Serial.println("A | a : All sensor and calculated values (T,S,H,D,E)")
         Serial.println("D | d : DHT22 calculated Dewpoint");
         Serial.println("E | e : DHT22 calculated Dewpoint2");
         Serial.println("H | h : DHT22 humidity");
@@ -87,8 +88,17 @@
         Value = dht.readHumidity();
         Serial.print(Value);
         break;
+      case 'A':
+      case 'a':
       case 'R':
       case 'r':
+        if ((ActionRequest == 'A') || (ActionRequest == 'a'))
+        {
+          // TMP36 temperature
+          Value = tmp36.readTemperature();
+          Serial.print(Value);
+          Serial.print(", ");
+        }
         // All DHT22 data: Temperature, Humidity, DewPoint, DewPoint2
         t = dht.readTemperature();
         Serial.print(t);


Indicate when autoprobing commences, in case it fails

If no devices are present autoprobe could cause a watchdog reset.
Indicate what is happening beforehand for easier debugging.

--- examples/RTCx_example/RTCx_example.ino
+++ examples/RTCx_example/RTCx_example.ino
@@ -39,8 +39,8 @@
 	else
 		Serial.begin(9600);
 	Wire.begin();
-
-	// Autoprobe to find a real-time clock.
+	Serial.println();
+	Serial.println("Autoprobing for a RTC...");
 	if (rtc.autoprobe()) {
 		// Found something, hopefully a clock.
 		Serial.print("Autoprobe found ");


Fixed calibrate

Fixed calibrate

--- mech/mech.ino
+++ mech/mech.ino
@@ -30,7 +30,7 @@
 			calibrate2(true);
 			break;
 		case channelC2:
-			calibrate2(true);
+			calibrate3(true);
 			break;
 		case channelL:
 			calibrate1(true);


Improve instructions for Arduino serial monitor.


switch IR broadcast off when connected

switch IR broadcast off when connected

--- glass/glass.ino
+++ glass/glass.ino
@@ -44,7 +44,7 @@
 boolean isWaitingReply;
 char XBeeReturnIDs[20];
 int XBeeReturnCount;
-boolean ir_cue_mode = true;
+boolean ir_bcast_mode = true;
 unsigned long ir_time;
 unsigned int ir_cycle = 300;
 unsigned int ir_response_threshold = 1000;
@@ -95,7 +95,7 @@
     }
   }

-  if(ir_cue_mode){
+  if(ir_bcast_mode){
     //constantly sending out ir broadcast as visual cue
     if(millis() - ir_time > ir_cycle) {
       // -1 indicates for broacast which is different than normal session id
@@ -127,6 +127,17 @@
       DEBUG_PRINT("[XBee]: send message: ");
       DEBUG_PRINTLN(message);
       XBee.print(message);
+      //check if led broadcast related msg
+      //turn of broadcast when a client is connected
+      //e.g. "IDCSEL ON" or "IDCSELAON"
+      //turn on when IDCSELOFF
+      if(message[8] == 'O' && message[9] == 'N') {
+        ir_bcast_mode = false;
+        DEBUG_PRINTLN("turning off IR bcast");
+      } else if(message[7] == 'O' && message[8] == 'F') {
+        ir_bcast_mode = true;
+        DEBUG_PRINTLN("turning on IR bcast");
+      }
     }
   }


Added soft serial for Trio board C6

Added soft serial for Trio board C6

--- Lab4_Drive/MotionPilot/MotionPilot.ino
+++ Lab4_Drive/MotionPilot/MotionPilot.ino
@@ -38,12 +38,22 @@
   which sends the resulting speed out on its SerialODoOut line, which is wired to its SerialDrive
   receive line.
 */
-//#define SINGLE_BOARD
+#define SOFT_SERIAL
+#define SINGLE_BOARD
 #define SerialMonitor Serial
+
+#ifdef SINGLE_BOARD   // Mega
+#ifdef SOFT_SERIAL
+#include <SoftwareSerial.h>
+SoftwareSerial SerialDrive(28, 26);
+#define SerialOdoOut SerialDrive
+#else
 #define SerialOdoOut  Serial1
-#ifdef SINGLE_BOARD   // Mega
 #define SerialDrive   Serial2
+#endif // SOFT_SERIAL
+
 #else  // OK for Micro or Leonardo
+#define SerialOdoOut  Serial1
 #define SerialDrive   Serial1
 // TO DO: Are we using speed in mm/sec or revolutions/sec?
 #define SpeedCyclometer_revPs  sensor_speed_mmPs
@@ -445,6 +455,7 @@

 void setup()
 {
+
     sensor_speed_mmPs = 0;
     SerialMonitor.begin(115200);
     SerialMonitor.print("\n\n\n");


adding termination character

adding termination character

--- sensing/wifi_interface.ino
+++ sensing/wifi_interface.ino
@@ -5,22 +5,24 @@
 const char* host = "146.164.69.186";
 const int httpPort = 50000;
 const char* skpln = "\r\n";
-const char* request = "?";
+const String request = "?";
 const char* clear_to_send = ":";
 const char* wait_to_send = "!";
+const String end_of_file = "#";
 String url = "/";

 void setup() {
   Serial.begin(9600);
   delay(100);
-
+  Serial.println("Started");
   // We start by connecting to a WiFi network
   WiFi.begin(ssid, password);

   while (WiFi.status() != WL_CONNECTED) {
     delay(500);
-    //Serial.println("Searching WiFi");
+    Serial.println("Searching WiFi");
   }
+  Serial.println("WiFi connected");
 }

 void loop() {
@@ -28,40 +30,45 @@
   bool connected = false;
   // Use WiFiClient class to create TCP connections
   WiFiClient client;
-
+  Serial.println("loop");
   if (!client.connect(host, httpPort)) {
     connected=false;
   } else {
     connected = true;
   }
-
+  Serial.println("Connection started");
   char a;
   while(Serial.available()){
     a = Serial.read();
-    if (String(a) == String(request)){
+    if (String(a) == request){
       if(connected){
         Serial.write(clear_to_send);

         while(!Serial.available()){}
          // Receive data from serial
-        char index = 0;
-        char temp = 0;
+        String temp = "";
         String dataString = "";
-        while(Serial.available()){
-          delay(100);
-          temp = Serial.read();
-          dataString += String(temp);
-          index++;
+        while(true){
+          if (Serial.available()){
+            temp = String(char(Serial.read()));
+            if(temp != end_of_file){
+              dataString += temp;
+            }else{
+              break;
+            }
+          }
+          delay(10);
         }
         if (dataString.length() > 0){
         // This will send the request to the server
-        client.print(String("POST ") + url + " HTTP/1.1" + skpln +
+          client.print(String("POST ") + url + " HTTP/1.1" + skpln +
                      "Host: " + host + skpln +
                      "Connection: close" + skpln +
                      "Content-Type: application/x-www-form-urlencoded" + skpln +
                      "Content-Length:" + dataString.length() + skpln + skpln +
                      dataString);
-        }
+          Serial.println(dataString);
+        }
       }else{
         Serial.write(wait_to_send);
       }
@@ -76,4 +83,4 @@

   Serial.println();
   Serial.println("closing connection");*/
-}+}


license

license

--- examples/LightMeter_LCD/LightMeter_LCD.ino
+++ examples/LightMeter_LCD/LightMeter_LCD.ino
@@ -3,9 +3,8 @@
 #include <LiquidCrystal.h>

 /*
- * Clock_LCD
+ * LightMeter_LCD
  *
- * Author: Alexander Schulz
  * Version 1.2
  * Datum: 05.08.2013
  *
@@ -29,6 +28,22 @@
  *     LCD D5 pin an digital pin 5
  *     LCD D6 pin an digital pin 6
  *     LCD D7 pin an digital pin 7
+ *
+ *
+ *   Copyright (c) 2013 Alexander Schulz.  All right reserved.
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation, either version 3 of the License, or
+ *   (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */

 AS_BH1750 lightMeter;
@@ -62,7 +77,6 @@
 }

 void loop() {
-  // Textvariablen
   char clux[9];

   // Werte auslesen und aufbereiten


Changed default distance multiplier to 55 cm, also added keywords.

git-svn-id: 59b6b80b3f28683e9a006dffc41d8db225db1926@48 ed0607b5-9f2d-40cd-ad1e-287a16c2e87a

--- examples/UltrasonicTemp/UltrasonicTemp.ino
+++ examples/UltrasonicTemp/UltrasonicTemp.ino
@@ -3,9 +3,9 @@
  *
  * SVN Keywords
  * ----------------------------------
- * $Author: $
- * $Date: $
- * $Revision: $
+ * $Author$
+ * $Date$
+ * $Revision$
  * ----------------------------------
  */

@@ -85,7 +85,7 @@
 // The max distance to read.
 #define MAX_CM_DISTANCE	400
 // Set multiplier, used to correct the non-linear result from the sensor.
-#define MULTIPLIER      1.0905
+#define MULTIPLIER      1.1017    // Default to 55 CM

 /*
  * The constructors needs to be passed arguments for the trigger pin and


now it actually includes correctly

now it actually includes correctly

--- examples/pseudopod-wifi/pseudopod-wifi.ino
+++ examples/pseudopod-wifi/pseudopod-wifi.ino
@@ -39,7 +39,11 @@
 void loop() {
   Serial.println("writing");
   Serial.flush();
-  int written = pseudopod->writeStateMessage(tentacle.getValue());
+  std::vector<Pin> pins;
+  for(int i = 0; i < 300; i++) {
+    pins.push_back(Pin(i,NULL, i));
+  }
+  int written = pseudopod->writeStateMessage(pins);
   Serial.print(written);
   Serial.println("bytes written.");
   Serial.flush();


Added the changes so that only one light turns on at a time

--- signal_lamp.ino
+++ signal_lamp.ino
@@ -64,20 +64,20 @@
     case 0:
       digitalWrite(light_red, LOW);
       digitalWrite(light_green, HIGH);
-      digitalWrite(light_yellow, HIGH);
+      digitalWrite(light_yellow, LOW);
       break;
       //GREEN
     case 1:
       digitalWrite(light_red, HIGH);
       digitalWrite(light_green, LOW);
-      digitalWrite(light_yellow, HIGH);
+      digitalWrite(light_yellow, LOW);

       break;
      //YELLOW
     case 2:
-      digitalWrite(light_red, HIGH);
-      digitalWrite(light_green, HIGH);
-      digitalWrite(light_yellow, LOW);
+      digitalWrite(light_red, LOW);
+      digitalWrite(light_green, LOW);
+      digitalWrite(light_yellow, HIGH);

       break;
   }


Nice patterns here. Going to rewrite each into its own function now

--- all/all.ino
+++ all/all.ino
@@ -1,3 +1,4 @@
+uint8_t wavebright = 255;                                     // You can change the brightness of the waves/bars rolling across the screen.
 #define qsubd(x, b)  ((x>b)?wavebright:0)                     // Digital unsigned subtraction macro. if result <0, then => 0. Otherwise, take on fixed value.
 #define qsuba(x, b)  ((x>b)?x-b:0)                            // Analog Unsigned subtraction macro. if result <0, then => 0

@@ -11,44 +12,28 @@
 uint8_t max_bright = 255;                                      // Overall brightness definition. It can be changed on the fly.
 unsigned long previousMillis;                                 // Store last time the strip was updated.

-uint8_t   thisfade = 200;                                      // How quickly does it fade? Lower = slower fade rate.
-int        thishue = 50;                                       // Starting hue.
-uint8_t    thisinc = 1;                                        // Incremental value for rotating hues
-uint8_t    thissat = 240;                                      // The saturation, where 255 = brilliant colours.
-uint8_t    thisbri = 255;                                      // Brightness of a sequence. Remember, max_bright is the overall limiter.
-int        huediff = 256;                                      // Range of random #'s to use for hue
-uint8_t  thisdelay = 0;                                        // We don't need much delay (if any)
+int hue = 50;                                       // Starting hue.

-uint8_t    numdots = 4;                                     // Number of dots in use.
-uint8_t   faderate = 128;                                     // How long should the trails be. Very low value = longer trails.
-uint8_t     hueinc = 16;                                     // Incremental change in hue between each dot.
-uint8_t     curhue = 0;                                     // The current hue
-uint8_t thisbright = 255;                                     // How bright should the LED/display be.
-uint8_t   basebeat = 48;                                     // Higher = faster movement.
+// This variable is set the first run-through of every pattern. Use it for setup!
+bool firstRun = false;

-uint8_t wavebright = 255;                                     // You can change the brightness of the waves/bars rolling across the screen.
-uint8_t    thisrot = 1;                                          // You can change how quickly the hue rotates for this wave. Currently 0.
-uint8_t     allsat = 240;                                         // I like 'em fully saturated with colour.
-int8_t   thisspeed = 48;                                         // You can change the speed of the wave, and use negative values.
-uint8_t    allfreq = 3;                                         // You can change the frequency, thus distance between bars.
-int      thisphase = 0;                                            // Phase change value gets calculated.
-uint8_t thiscutoff = 120;                                     // You can change the cutoff value to display this wave. Lower value = longer wave.
-uint8_t      bgclr = 0;                                            // A rotating background colour.
-uint8_t      bgbri = 0;
+// Patterns
+#define RAINBOW 1
+#define RAINBOW_2 2
+#define RAINBOW_3 3
+#define DISCO_BARBER_1 4
+#define DISCO_BARBER_2 5
+#define JUGGLE 6
+#define NEW 7
+
+int maxPatternId = 6;
+int rotationInMillseconds = 20000; // 20 seconds for production

-#define RAINBOW 1
-#define RAINBOW_2 2
-#define RAINBOW_3 2
-#define DISCO_BARBER_1 3
-#define DISCO_BARBER_2 4
-#define JUGGLE 5
-#define NEW 6
-
-int maxPatternId = 5;
-int patternId = random(maxPatternId - 1);
-bool holdPattern = false;
-int rotationInMillseconds = 20000;
+//int patternId = 3;
+//bool holdPattern = false;
+bool holdPattern = true;
+int patternId = RAINBOW;

 const int ledPin = 13;
 const int led = 13;
@@ -59,14 +44,21 @@
   LEDS.addLeds<LED_TYPE, LED_DT, COLOR_ORDER>(leds, NUM_LEDS);
   FastLED.setBrightness(max_bright);
   set_max_power_in_volts_and_milliamps(5, 10000);
+  randomSeed(analogRead(0));
 }

 int numberOfSparkles = 1;
 int increasing = true;

 void confetti() {
-  fadeToBlackBy(leds, NUM_LEDS, thisfade);
-  if (numberOfSparkles < 40 && increasing) {
+
+  if (patternId == RAINBOW) {
+    fadeToBlackBy(leds, NUM_LEDS, 180);
+  } else {
+    fadeToBlackBy(leds, NUM_LEDS, 200);
+  }
+
+  if (numberOfSparkles < 80 && increasing) {
     numberOfSparkles += 1;
   } else if (numberOfSparkles > 5) {
     numberOfSparkles -= 1;
@@ -79,66 +71,95 @@
   int pos;

   if (patternId == RAINBOW) {
-    for (int i = 0; i < 2; i++) {
+    for (int i = 0; i < 20; i++) {
       pos = random16(NUM_LEDS);
-      leds[pos] += CHSV(thishue, 255, 255);
+      leds[pos] = CHSV(hue, 180, 255);
     }
   }

-  for (int i = 0; i < numberOfSparkles * 8; i++) {
+  for (int i = 0; i < numberOfSparkles * 4; i++) {
     pos = random16(NUM_LEDS);
     if (patternId == RAINBOW) {
-      leds[pos] += CHSV(thishue, 255, 20);
+      leds[pos] += CHSV(hue, 200, 20);
     } else if (patternId == RAINBOW_2) {
-      leds[pos] = CHSV(thishue + (pos / 10), thissat, thisbri);
+      leds[pos] = CHSV(hue + (pos / 10), 240, 255);
     } else if (patternId == RAINBOW_3) {
-      leds[pos] = CHSV(thishue, thissat, thisbri);
+      leds[pos] = CHSV(hue, 240, 255);
     }
   }

   if (patternId == RAINBOW_2) {
-    thishue += thisinc * 10;
+    hue += 10;
+  } else {
+    hue = hue + 1;
   }
-
-  thishue = thishue + thisinc;
 }

+uint8_t    numdots = 3;    // Number of dots in use.
+uint8_t   faderate = 64;  // How long should the trails be. Very low value = longer trails.
+uint8_t     hueinc = 1;   // Incremental change in hue between each dot.
+uint8_t     curhue = 0;    // The current hue
+uint8_t   basebeat = 2;   // Higher = faster movement.
+
 void juggle() {
+  hueinc = 1;
+  faderate = 64;
+  if (faderate == 100 || faderate == 200) {
+    numdots += 1;
+  }
+
   fadeToBlackBy(leds, NUM_LEDS, faderate);
-  numdots = 3; basebeat = 2; hueinc = 1; faderate = 48; thishue = 128;
+
   for ( int i = 0; i < numdots; i++) {
     for ( int j = 0; j < 20; j++) {
-      leds[beatsin16(basebeat + i + numdots, 0, NUM_LEDS - 20) + j] += CHSV(curhue, thissat, thisbright); //beat16 is a FastLED 3.1 function
+      leds[beatsin16(basebeat + i + numdots, 0, NUM_LEDS - 20) + j] += CHSV(curhue, 240, 255); //beat16 is a FastLED 3.1 function
     }
-//    leds[beatsin16(basebeat + i + numdots, 0, NUM_LEDS)] += CHSV(curhue, thissat, thisbright); //beat16 is a FastLED 3.1 function
+    // leds[beatsin16(basebeat + i + numdots, 0, NUM_LEDS)] += CHSV(curhue, 240, 255); //beat16 is a FastLED 3.1 function
     curhue += hueinc;
   }
 }

+uint8_t allfreq = 3;
+int     thisphase = 0;
+uint8_t thiscutoff = 120;
+uint8_t thisrot = 1;
+int8_t  thisspeed = 48;
+uint8_t allsat = 240;
+
 void discoBarber() {
-  thisphase += thisspeed;                                                     // You can change direction and speed individually.
-  thishue = thishue + thisrot;                                                // Hue rotation is fun for thiswave.
+  if (patternId == DISCO_BARBER_1) {
+    allfreq = 5;
+    thisphase += 24;
+  } else {
+    allfreq = 3;
+    thisphase += 48;
+  }
+
+  hue = hue + 1;                                                // Hue rotation is fun for thiswave.
+
   for (int k = 0; k < NUM_LEDS - 1; k++) {                                    // For each of the LED's in the strand, set a brightness based on a wave as follows:
-    int thisbright = qsubd(cubicwave8((k * allfreq) + thisphase), thiscutoff); // qsub sets a minimum value called thiscutoff. If < thiscutoff, then bright = 0. Otherwise, bright = 128 (as defined in qsub)..
-    leds[k] = CHSV(bgclr, 255, bgbri);                                        // First set a background colour, but fully saturated.
+    int _brightness = qsubd(cubicwave8((k * allfreq) + thisphase), thiscutoff); // qsub sets a minimum value called thiscutoff. If < thiscutoff, then bright = 0. Otherwise, bright = 128 (as defined in qsub)..
+    leds[k] = CHSV(0, 0, 0);                                        // First set a background colour, but fully saturated.

     // Sparkles!
-    if (random(1000) > 997) {
+    if (random(1000) > 996) {
       leds[k] = CHSV(255, 0, 255);
     }

     if (patternId == DISCO_BARBER_1) {
-      leds[k] += CHSV(thishue+k/5, allsat, thisbright);                             // Then assign a hue to any that are bright enough.
+      // original disco barber 1
+      // leds[k] += CHSV(hue+k/5, allsat, _brightness);                             // Then assign a hue to any that are bright enough.
+      leds[k] += CHSV(hue * 10 + k / 2, allsat, _brightness);                             // Then assign a hue to any that are bright enough.
     } else {
-      leds[k] += CHSV(- (thishue * 20) + k / 4, allsat, thisbright);                       // Then assign a hue to any that are bright enough.
+      leds[k] += CHSV(hue * -20 + k / 4, allsat, _brightness);                       // Then assign a hue to any that are bright enough.
     }
   }
-  bgclr++;
-}
+ }

 void loop () {
   if (!holdPattern) {
     EVERY_N_MILLISECONDS(rotationInMillseconds) {
+      firstRun = true;
       patternId += 1;
       if (patternId > maxPatternId) {
         patternId = 1;
@@ -153,5 +174,8 @@
   } else if (patternId == JUGGLE) {
     juggle();
   }
+
+  firstRun = false;
+
   show_at_max_brightness_for_power();
 }


Pins of the final PCB

Pins of the final PCB

--- avr/avr.ino
+++ avr/avr.ino
@@ -60,11 +60,11 @@
 volatile uint8_t driving_readiness = 1;

 // Hardware configuration
-#define PIN_COL_BIT0 A2
-#define PIN_COL_BIT1 A1
-#define PIN_COL_BIT2 A0
-#define PIN_ROW_LATCH 7
-#define PIN_COL_LATCH 8
+#define PIN_COL_BIT0 A1
+#define PIN_COL_BIT1 A2
+#define PIN_COL_BIT2 A3
+#define PIN_ROW_LATCH 10
+#define PIN_COL_LATCH A0

 // Serial access
 unsigned int byte_i;


Modifico algo

Modifico algo

--- wifisense_GWY/wifisense_GWY.ino
+++ wifisense_GWY/wifisense_GWY.ino
@@ -7,10 +7,12 @@
 // This #include statement was automatically added by the Particle IDE.
 #include <MQTT.h>

+//
+
 // xbee object
 XBee xbee = XBee();

-// payload array for xbee transmission
+// payload array for xbee transmission
 byte payload[6] ;

 // TX objects:
@@ -33,20 +35,20 @@

 void setup() {
-
+
     Serial.begin(9600);
     Serial1.begin(9600);
     xbee.setSerial(Serial1);
-
+
     Serial.println ("Todo ok hasta aqui");

 }

 void loop() {
-
-
+
+
    xbee.readPacket();
-
+
     if (xbee.getResponse().isAvailable()) {
       // got something
       if (xbee.getResponse().getApiId() == ZB_RX_RESPONSE) {
@@ -54,7 +56,7 @@
         Serial.println("got a new report");
         // now fill our zb rx class
         xbee.getResponse().getZBRxResponse(rx);
-
+
         if (rx.getOption() == ZB_PACKET_ACKNOWLEDGED) {
             // the sender got an ACK
             Serial.println ("Sender is informed about it");
@@ -75,7 +77,7 @@
       } else if (xbee.getResponse().getApiId() == MODEM_STATUS_RESPONSE) {
         xbee.getResponse().getModemStatusResponse(msr);
         // the local XBee sends this response on certain events, like association/dissociation
-
+
         if (msr.getStatus() == ASSOCIATED) {
           // yay this is great.  flash led
           Serial.print ("local Xbee got associated");
@@ -88,14 +90,14 @@
         }
       } else {
       	// not something we were expecting
-        Serial.print ("I got something not expected...moving on");
+        Serial.print ("I got something not expected...moving on");
       }
     } else if (xbee.getResponse().isError()) {
-      Serial.print("Error reading packet.  Error code: ");
+      Serial.print("Error reading packet.  Error code: ");
       Serial.println(xbee.getResponse().getErrorCode());
     }
-
-
+
+
     delay(1000);

 }
@@ -112,6 +114,3 @@
     }
   }
 }
-
-
-


Change sonar's output to just a number (of cm)

--- sonar/sonar.ino
+++ sonar/sonar.ino
@@ -13,7 +13,5 @@
 void loop() {
   delay(50);
   int uS = sonar.ping();
-  Serial.print("Ping: ");
   Serial.print(uS / US_ROUNDTRIP_CM);
-  Serial.println("cm");
 }


Delete R_ANA3PL.ino

Delete R_ANA3PL.ino

--- BMS_Francais/Examples/R_ANA3PL-Arduino/R_ANA3PL.ino
+++ BMS_Francais/Examples/R_ANA3PL-Arduino/R_ANA3PL.ino
@@ -1,58 +0,0 @@
-/*-------------------------------------------------------------------------------------------------------------------------------------------*
- * SE2R : R_ANA3PL - Fonction de transformation d'un pourcentage en commande 3-Points sur deux points binaires                    30/06/2015 *
- * ------------------------------------------------------------------------------------------------------------------------------------------*
- *        R_ANA3PL(float VPC[], float VTC[], boolean FCC[], int CFG)                                                              30/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                                          *
- *                FCC : [00] : Commande bolléenne d'ouverture  de l'actionneur 3-points                                                      *
- *                      [01] : Commande bolléenne 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                                                                         *
- * ------------------------------------------------------------------------------------------------------------------------------------------*
- * 30/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_ANA3PL - Table des commandes en sortie du régulateur
-float VTC_XXXX[6];                       // R_ANA3PL - Table des temporisations de commande de la vanne 3 points
-boolean FCC_XXXX[2];                     // R_ANA3PL - Table des commandes de sorties de la vanne 3 points
-int VCO_XXXX;                            // R_ANA3PL - Commande de forçage, ici en position auto
-void setup() {                           // Initialisation ----------------------------------------------------------------------------------*
-  VTC_XXXX[0] = 30;                      // R_ANA3PL - Durée du cycle de rafraîchissement de l'action sur la vanne
-  VTC_XXXX[1] = 180;                     // R_ANA3PL - Durée de la course complète de la vanne
-  VCO_XXXX = 1;                          // R_ANA3PL - Commande de forçage
-  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_ANA3PL(VPC_XXXX, VTC_XXXX, FCC_XXXX, 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]);
-}


Fairly extensive change to work with new TI CC3000 on an AdaFruit shield as a Wifi option. Seems quite stable after a fairly few days of tweaking and experimenting.

--- device.ino
+++ device.ino
@@ -5,17 +5,23 @@
  (begun June 6, 2011)

+  April 4, 2014
+
+  Change wireless to use Adafruit CC3000 shield as the "official" Arduino
+  wifi shield is simply not reliable. Remove hardware reset.
+
+
   March 6, 2014

   Make changes to use a hardware line tied to the reset pin via a 1K Ohm
   resistor.  This can be triggered after repeated failed attempts to
-  communicate, thus making the wifishield acceptably reliable (in tends to
-  come back up ok after a hardware reset).
+  communicate, in an attempt to make the Arduino wifi shield acceptably
+  reliable (in tends to come back up ok after a hardware reset).

   Feb 21, 2014

-  But Wifi version on hold as Arduion Wifi Shield is simply not reliable
+  Put Wifi version on hold as Arduion Wifi Shield is simply not reliable
   with current library and firmware versions.

   Feb 20, 2014
@@ -48,7 +54,7 @@
   April, 2013

   Brought in encrypted/$FHS code that was working back in July and made it
-  trunk It encrypts content using aes-128-cbc encryption
+  trunk. It encrypts content using aes-128-cbc encryption

   May 2013

@@ -58,6 +64,7 @@

 */

+#include <Adafruit_CC3000.h>
 #include <Wire.h>
 #include <Adafruit_BMP085.h>
 #include <EEPROM.h>
@@ -67,7 +74,6 @@
 #include <Base64.h>
 #include <avr/wdt.h>
 #include <util/crc16.h>
-#include <WiFi.h>
 #include <SPI.h>

 #include "sometypes.h"
@@ -76,18 +82,17 @@
   Compile time option/debug flags
 */

-//#define   WIFI_NOT_CELL
-//#define WIFI_DEBUG_ON
+#define   WIFI_NOT_CELL
+#define WIFI_DEBUG_ON
 //#define GPRS_DEBUG_ON
-#define GPS_DEBUG_ON
+//#define GPS_DEBUG_ON
 //#define PUMP_DEBUG_ON
 //#define EXECUTION_PATH_DEBUG_ON
 //#define NMEA_DEBUG_ON
-//#define DEBUG_MEMORY_ON
+#define DEBUG_MEMORY_ON
+//#define STRESS_MEMORY_ON
 //#define BYPASS_AES_ON
 //#define BARO_DEBUG_ON
-#define GPS_SERIAL_SPEED 9600	//4800 for older GPS devices
-

 /*
   Anything which changes what the Floathub Data Receiver (fdr) needs to do
@@ -104,12 +109,23 @@
 #endif

+/*
+  Adafruit CC3000 wireless library settings
+*/
+
+#ifdef WIFI_NOT_CELL
+#define ADAFRUIT_CC3000_IRQ   3
+#define ADAFRUIT_CC3000_VBAT  5
+#define ADAFRUIT_CC3000_CS    10
+#endif

 /*
   Some AES variables
 */

-#define MAX_AES_CIPHER_LENGTH 1536
+#define MAX_AES_CIPHER_LENGTH 1024
+//#define MAX_AES_CIPHER_LENGTH 1536
+//#define MAX_AES_CIPHER_LENGTH 2048
 AES aes;
 byte iv[16];
 byte volatile_iv[16];
@@ -160,7 +176,10 @@
 /*
    Some global Strings, character arrays
 */
-
+
+
+#define MAX_LATEST_MESSAGE_SIZE 512
+#define MAX_NEW_MESSAGE_SIZE 256
 String latest_message_to_send = "";
 String new_message = "";
 char   temp_string[20];
@@ -201,7 +220,7 @@
 unsigned long led_update_interval = 200;          	//  Update the LED's every 200 miliseconds
 unsigned long nmea_update_interval = 100;         	//  Update NMEA in serial line every 1/10 of a second
 boolean green_led_state = false;         	  	//  For cycling on and off
-unsigned long hardware_watchdog_interval = 60000; 	//  Do a hardware reset if we don't pat the dog every 60 seconds
+unsigned long hardware_watchdog_interval = 120000; 	//  Do a hardware reset if we don't pat the dog every 2 minutes

 unsigned long sensor_previous_timestamp = 0;
 unsigned long gps_previous_timestamp = 0;
@@ -236,7 +255,9 @@
 #define	MAX_GPRS_READ_BUFFER	64

 #ifdef WIFI_NOT_CELL
-WiFiClient wifi_client;
+Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIVIDER);
+Adafruit_CC3000_Client cc3000_client;
+
 bool wifi_on_home_network;

 enum wireless_communication_state
@@ -378,12 +399,12 @@
   {
     free_memory = ((int)&free_memory) - ((int)__brkval);
   }
-  debug_info("Mem Free:", free_memory);
+  debug_info(F("Mem Free:"), free_memory);
 }
 #endif

 /*
-    Setup SPI for barometric and temperature
+    Setup for barometric and temperature
 */

@@ -403,7 +424,7 @@
   //  Setup gps on serial device 3, and make it send only GGA and RMC NMEA sentences
   //

-  Serial3.begin(GPS_SERIAL_SPEED);
+  Serial3.begin(9600);
   delay(1000);

   //
@@ -411,6 +432,7 @@
   //

   /*
+  Serial3.begin(4800);
   Serial3.println("$PSTMNMEACONFIG,0,4800,66,1");
   Serial3.println(F("$PSRF103,00,00,02,01*26"));  //  GGA ON every 2 seconds
   Serial3.println(F("$PSRF103,01,00,00,01*25"));  //  GLL OFF
@@ -424,10 +446,31 @@
   //	MTK3339 / Ultimate GPS breakout from Adafruit
   //

-  Serial3.println("$PMTK314,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28");
-}
-
-
+  //Serial3.println("$PMTK314,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28");	// Every 2 seconds
+  Serial3.println("$PMTK314,0,3,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*2A");		// GGA every 1 second, RMC every 3
+}
+
+
+
+#ifdef WIFI_NOT_CELL
+void wifi_setup()
+{
+  #ifdef WIFI_DEBUG_ON
+  debug_info(F("Wifi init"));
+  #endif
+  if (!cc3000.begin())
+  {
+    #ifdef WIFI_DEBUG_ON
+    debug_info(F("No wifi init"));
+    #endif
+  }
+  else
+  {
+    cc3000.reboot(NULL);
+    cc3000.setPrinter(NULL);
+  }
+}
+#endif

 #ifndef WIFI_NOT_CELL
 void gprs_setup()
@@ -471,10 +514,10 @@
   else
   {
     #ifdef GPRS_DEBUG_ON
-    debug_info("No dog pat");
+    debug_info(F("No dog pat"));
     #endif
     #ifdef WIFI_DEBUG_ON
-    debug_info("No dog pat");
+    debug_info(F("No dog pat"));
     #endif
   }
 }
@@ -867,6 +910,8 @@
   console_read_buffer.reserve(MAX_CONSOLE_BUFFER);
   gps_read_buffer.reserve(MAX_GPS_BUFFER);
   nmea_read_buffer.reserve(MAX_NMEA_BUFFER);
+  new_message.reserve(MAX_NEW_MESSAGE_SIZE);
+  latest_message_to_send.reserve(MAX_LATEST_MESSAGE_SIZE);

   bmp_setup();
   gps_setup();
@@ -921,14 +966,6 @@

   //
-  //   HACK HACK HACK
-  //
-
-  pinMode(4, OUTPUT);
-  digitalWrite(4, HIGH);
-
-
-  //
   //  Handle EEPROM logic for persistant settings (if the first 6 bytes of
   //  EEPROM memory are not all set to 42, then this is a completely
   //  unitialized device)
@@ -962,6 +999,14 @@

   watchdog_setup();

+
+  //
+  //	Possibly init wifi
+  //
+
+  #ifdef WIFI_NOT_CELL
+  wifi_setup();
+  #endif

   //
   //  Announce we are up
@@ -1170,7 +1215,7 @@
       var_start < 0     ||    var_start >= (int) gps_read_buffer.length()     )
   {
       #ifdef GPS_DEBUG_ON
-      debug_info("Bad RMC string");
+      debug_info(F("Bad RMC string"));
       debug_info(gps_read_buffer);
       #endif
       return;
@@ -1224,7 +1269,7 @@
     if(!gps_valid)
     {
       #ifdef GPS_DEBUG_ON
-      debug_info("Gps fix");
+      debug_info(F("Gps fix"));
       #endif
     }
     gps_valid = true;
@@ -1234,7 +1279,7 @@
     if(gps_valid)
     {
       #ifdef GPS_DEBUG_ON
-      debug_info("Gps no fix");
+      debug_info(F("Gps no fix"));
       #endif
     }
     gps_valid = false;
@@ -1349,7 +1394,7 @@
   {
       gps_valid = false;
       #ifdef GPS_DEBUG_ON
-      debug_info("Bad GGA string");
+      debug_info(F("Bad GGA string"));
       debug_info(gps_read_buffer);
       #endif
       return;
@@ -1414,7 +1459,7 @@
        if(gps_read_buffer.indexOf("$GPRMC,") == 0)
        {
          #ifdef GPS_DEBUG_ON
-         debug_info("--GPS BUF RMC--");
+         debug_info(F("--GPS BUF RMC--"));
          debug_info(gps_read_buffer);
          #endif
          push_out_nmea_sentence(false);
@@ -1423,7 +1468,7 @@
        else if(gps_read_buffer.indexOf("$GPGGA,") == 0)
        {
          #ifdef GPS_DEBUG_ON
-         debug_info("--GPS BUF GGA--");
+         debug_info(F("--GPS BUF GGA--"));
          debug_info(gps_read_buffer);
          #endif
          push_out_nmea_sentence(false);
@@ -1496,7 +1541,7 @@
      else if(state == off)
      {
        #ifdef PUMP_DEBUG_ON
-       debug_info("Pump turned on!");
+       debug_info(F("Pump turned on!"));
        #endif
        new_message = "$FHB:";
        new_message += float_hub_id;
@@ -1525,7 +1570,7 @@
      else if(state == on)
      {
        #ifdef PUMP_DEBUG_ON
-       debug_info("Pump turned off!");
+       debug_info(F("Pump turned off!"));
        #endif
        new_message = "$FHB:";
        new_message += float_hub_id;
@@ -2467,7 +2512,7 @@
     latest_message_to_send = new_message;
     encode_latest_message_to_send();
   }
-  else
+  else if(timeStatus() != timeNotSet)
   {
     //
     //  Need to store pump state in EEPROM
@@ -2503,91 +2548,157 @@

 #ifdef WIFI_NOT_CELL

+void nuke_wireless(void)
+{
+  unsigned long current_timestamp = millis();
+  #ifdef WIFI_DEBUG_ON
+  debug_info(F("*** Resetting Wifi ***"));
+  #endif
+  cc3000.disconnect();
+  cc3000.reboot(NULL);
+  wifi_on_home_network = false;
+  wifi_communication_state = idle;
+  gprs_or_wifi_watchdog_timestamp = current_timestamp;
+  return;
+}
+
+bool open_fdr()
+{
+
+  // Open a connection to the floathub server (usually fdr.floathub.net)
+
+  float_hub_server.toCharArray(temp_string_a, 40);
+  uint32_t ip = 0;
+  if(cc3000.getHostByName(temp_string_a, &ip) && ip > 0)
+  {
+    cc3000_client = cc3000.connectTCP(ip, float_hub_server_port);
+    if(cc3000_client.connected())
+    {
+      return true;
+    }
+    #ifdef WIFI_DEBUG_ON
+    debug_info(F("Wifi No comm"));
+    #endif
+    cc3000_client.close();
+    return false;
+  }
+  if(ip < 1)
+  {
+    #ifdef WIFI_DEBUG_ON
+    debug_info(F("Wifi DNS failure"));
+    #endif
+  }
+  else
+  {
+    #ifdef WIFI_DEBUG_ON
+    debug_info(F("Wifi DNS lookup failure"));
+    #endif
+  }
+  return false;
+}
+
+
+bool push_latest_message_out_socket(void)
+{
+  //
+  //	Send message in chunks of about 32 bytes. Too big, and we die due to
+  //	running out of memory.  Too small, and it takes forever to send the
+  //	message
+  //
+
+  for(i = 0; i < latest_message_to_send.length(); i = i + 32)
+  {
+    for(handy = 0; handy + i < latest_message_to_send.length() && handy < 32; handy++)
+    {
+      plain[handy] = (char) latest_message_to_send.charAt(i + handy);
+    }
+    if(cc3000_client.write(plain, handy) != handy)
+    {
+      return false;
+    }
+  }
+  plain[0] = '\r';
+  plain[1] = '\n';
+  if(cc3000_client.write(plain, 2) != 2)
+  {
+    return false;
+  }
+  return true;
+}
+
+
+
 void wifi_read()
 {
-  #ifdef WIFI_DEBUG_ON
-  debug_info("E wr()");
-  #endif
   if(gprs_or_wifi_communications_on == false)
   {
+    return;
+  }
+  unsigned long current_timestamp = millis();
+  if(current_timestamp - gprs_or_wifi_watchdog_timestamp > gprs_or_wifi_watchdog_interval)
+  {
+    gprs_or_wifi_watchdog_counter++;
+    nuke_wireless();
+  }
+
+  if(cc3000.getStatus() != STATUS_CONNECTED)
+  {
+    wifi_communication_state = idle;
     #ifdef WIFI_DEBUG_ON
-    debug_info("QA wr()");
+    debug_info(F("Wifi no conn yet"));
     #endif
     return;
   }
-  unsigned long current_timestamp = millis();
-  if(current_timestamp - gprs_or_wifi_watchdog_timestamp > gprs_or_wifi_watchdog_interval)
-  {
-    gprs_or_wifi_watchdog_counter++;
+
+  if(!cc3000.checkDHCP())
+  {
     #ifdef WIFI_DEBUG_ON
-    debug_info("*** Reseting Wifi (Watchdog)  ***");
-    #endif
-    if(wifi_client.connected())
-    {
-      wifi_client.stop();
-      wifi_client.flush();
-      wifi_client.stop();
-    }
-    wifi_on_home_network = false;
-    WiFi.disconnect();
-    wifi_communication_state = idle;
-    gprs_or_wifi_watchdog_timestamp = current_timestamp;
-    wifi_scan();
-    #ifdef WIFI_DEBUG_ON
-    debug_info("QB wr()");
+    debug_info(F("Wifi no IP yet"));
     #endif
     return;
   }
-  if(WiFi.status() != WL_CONNECTED)
-  {
-    wifi_communication_state = idle;
-    #ifdef WIFI_DEBUG_ON
-    debug_info("QC wr()");
-    #endif
-    return;
-  }
-
+
+
   if(wifi_communication_state == idle)
   {
     if(latest_message_to_send.length() > 0)
     {
-      float_hub_server.toCharArray(temp_string_a, 40);
-      if (wifi_client.connect(temp_string_a, float_hub_server_port))
-//      byte addthing[4] = {54, 213, 47, 184};
-//      if (wifi_client.connect(addthing, 50003))
+      if(open_fdr())
       {
-        for(i = 0; i < latest_message_to_send.length() ; i++)
+        if(push_latest_message_out_socket())
         {
-            wifi_client.write(latest_message_to_send.charAt(i));
+          #ifdef WIFI_DEBUG_ON
+          debug_info(F("Wifi Sent FHx"));
+          #endif
+          gprs_or_wifi_watchdog_timestamp = current_timestamp;
+          wifi_communication_state = waiting_for_response;
+          wifi_read_buffer = "";
         }
-        wifi_client.write('\r');
-        wifi_client.write('\n');
         #ifdef WIFI_DEBUG_ON
-        debug_info("Sent: " + latest_message_to_send);
+        else
+        {
+          debug_info(F("Wifi sock prob"));
+        }
         #endif
+      }
+    }
+    else
+    {
         gprs_or_wifi_watchdog_timestamp = current_timestamp;
-        wifi_communication_state = waiting_for_response;
-        wifi_read_buffer = "";
-      }
-      else
-      {
-        #ifdef WIFI_DEBUG_ON
-        debug_info("Wifi no comm");
-        #endif
-        wifi_client.stop();
-      }
-    }
-    else
-    {
-        gprs_or_wifi_watchdog_timestamp = current_timestamp;
     }
   }
   else if(wifi_communication_state == waiting_for_response)
   {
-    while (wifi_client.available() && wifi_read_buffer.length() < MAX_WIFI_BUFFER)
-    {
-      wifi_read_buffer += (char) wifi_client.read();
-    }
+    unsigned long lastRead = millis();
+    while (cc3000_client.connected() && (millis() - lastRead < 3000))
+    {
+        while (cc3000_client.available())
+        {
+          wifi_read_buffer += (char) cc3000_client.read();
+          lastRead = millis();
+        }
+    }
+
     if(wifi_read_buffer.indexOf("$FHR$ OK") > -1)
     {
       gprs_or_wifi_watchdog_counter = 0;
@@ -2595,162 +2706,183 @@
       pop_off_message_queue();
       if(latest_message_to_send.length() > 0)
       {
-        for(i = 0; i < latest_message_to_send.length() ; i++)
+        if(push_latest_message_out_socket())
         {
-            wifi_client.write(latest_message_to_send.charAt(i));
+          #ifdef WIFI_DEBUG_ON
+          debug_info(F("Wifi more FHx"));
+          #endif
+          wifi_communication_state = waiting_for_response;
+          wifi_read_buffer = "";
         }
-        wifi_client.write('\r');
-        wifi_client.write('\n');
-        #ifdef WIFI_DEBUG_ON
-        debug_info("Sent via wifi: " + latest_message_to_send);
-        #endif
-        wifi_communication_state = waiting_for_response;
-        wifi_read_buffer = "";
+        else
+        {
+          #ifdef WIFI_DEBUG_ON
+          debug_info(F("Wifi Hangup"));
+          #endif
+        }
       }
       else
       {
         wifi_read_buffer = "";
-        wifi_client.stop();
-        wifi_client.flush();
-        wifi_client.stop();
-        wifi_client.stop();
+        cc3000_client.close();
         wifi_communication_state = idle;
       }
     }
   }
-  #ifdef WIFI_DEBUG_ON
-  debug_info("QD wr()");
-  #endif
-}
-
-void hop_on_home_network(int encryption_type)
-{
+}
+
+void hop_on_home_network(uint8_t encryption_type)
+{
+
   wifi_on_home_network = false;
   gprs_apn.toCharArray(temp_string_a, 40);
   gprs_password.toCharArray(temp_string_b, 40);
-  if(encryption_type == 5)
-  {
-    if(WiFi.begin(temp_string_a, 1, temp_string_b) == WL_CONNECTED)
-    {
-      #ifdef WIFI_DEBUG_ON
-      debug_info("WiFi home net wep");
-      #endif
-      wifi_on_home_network = true;
-    }
-    else
-    {
-      #ifdef WIFI_DEBUG_ON
-      debug_info("WiFi home net wep error");
-      #endif
-    }
+
+
+  if (cc3000.deleteProfiles())
+  {
+    #ifdef WIFI_DEBUG_ON
+    debug_info(F("wifi pro out"));
+    #endif
   }
   else
-  {
-    if(WiFi.begin(temp_string_a, temp_string_b) == WL_CONNECTED)
-    {
-      #ifdef WIFI_DEBUG_ON
-      debug_info("WiFi home net");
-      #endif
-      wifi_on_home_network = true;
-    }
-    else
-    {
-      #ifdef WIFI_DEBUG_ON
-      debug_info("WiFi home net error");
-      #endif
-    }
-  }
-}
+  {
+    #ifdef WIFI_DEBUG_ON
+    debug_info(F("wifi pro fail"));
+    #endif
+  }
+
+
+  if(cc3000.connectSecure(temp_string_a, temp_string_b, encryption_type))
+  //if(cc3000.connectToAP(temp_string_a, temp_string_b, encryption_type))
+  {
+    #ifdef WIFI_DEBUG_ON
+    debug_info(F("WiFi home net "), encryption_type);
+    #endif
+    wifi_on_home_network = true;
+  }
+  else
+  {
+    #ifdef WIFI_DEBUG_ON
+    debug_info(F("Failed WiFi home"));
+    #endif
+  }
+}
+

 void wifi_scan()
 {

+  if(cc3000.getStatus() == STATUS_CONNECTED && wifi_on_home_network)
+  {
+    return;
+  }
   //
   //  We always scan for networks unless we are already attached to our
   //  preferred network, favouring our set network but using any open one we
   //  can find as well
   //
-
-  if(WiFi.status() == WL_CONNECTED && wifi_on_home_network)
-  {
-    return;
-  }
+
+  #ifdef WIFI_DEBUG_ON
+  debug_info(F("=== Wifi scan start ==="));
+  #endif

   wifi_on_home_network = false;
   boolean see_home_network = false;
   boolean see_open_network = false;

-  byte home_encryption_type = 0;
+  uint8_t home_encryption_type = 0;
   String open_network_name;

-  byte numb_networks = WiFi.scanNetworks();
-  for (int i = 0; i < numb_networks; i++)
-  {
-    if(gprs_apn.equals(WiFi.SSID(i)))
-    {
-        home_encryption_type = WiFi.encryptionType(i);
+
+  uint8_t valid, rssi, sec, index;
+  char ssidname[33];
+
+  index = cc3000.startSSIDscan();
+
+  while (index)
+  {
+    index--;
+
+    if(cc3000.getNextSSID(&rssi, &sec, ssidname))
+    {
+
+      if(gprs_apn.equals(ssidname))
+      {
+        home_encryption_type = sec;
         see_home_network = true;
         #ifdef WIFI_DEBUG_ON
-        debug_info("Saw home net: " + String(WiFi.SSID(i)));
-        #endif
-    }
-    else if(WiFi.encryptionType(i) == 7)
-    {
-      see_open_network = true;
-      open_network_name = WiFi.SSID(i);
-        #ifdef WIFI_DEBUG_ON
-        debug_info("Saw open net: " + String(WiFi.SSID(i)));
-        #endif
-    }
-    #ifdef WIFI_DEBUG_ON
-    else
-    {
-        debug_info("Saw other net: " + String(WiFi.SSID(i)));
-    }
-    #endif
-  }
-
-  if(WiFi.status() != WL_CONNECTED)
-  {
-    #ifdef WIFI_DEBUG_ON
-    debug_info("No wifi connection");
-    #endif
-    if(see_home_network)
-    {
-      hop_on_home_network(home_encryption_type);
-    }
-    else if(see_open_network)
-    {
-      open_network_name.toCharArray(temp_string_a, 40);
-      if(WiFi.begin(temp_string_a) == WL_CONNECTED)
-      {
-        #ifdef WIFI_DEBUG_ON
-        debug_info("wifi open net: " + open_network_name);
+        debug_info("Home wifi: " + gprs_apn);
         #endif
       }
+      else if(sec == WLAN_SEC_UNSEC)
+      {
+        see_open_network = true;
+        if(open_network_name.length() < 1)
+        {
+          open_network_name = String(ssidname);
+        }
+        else if(random(0,100) < 25)
+        {
+          open_network_name = String(ssidname);
+        }
+        #ifdef WIFI_DEBUG_ON
+        debug_info("Open wifi: " + String(ssidname));
+        #endif
+        break;
+      }
+      #ifdef WIFI_DEBUG_ON
       else
       {
-        #ifdef WIFI_DEBUG_ON
-        debug_info("wifi open net error");
-        #endif
+        debug_info("     wifi: " + String(ssidname));
       }
-    }
-  }
-  else
-  {
-    //
-    //  We are connected, but if not to home and we can see home, we want to connect to that
-    //
-
-    if(!String(WiFi.SSID()).startsWith(gprs_apn) && see_home_network)
-    {
-      WiFi.disconnect();
-      hop_on_home_network(home_encryption_type);
-    }
-  }
-}
-
-
+      #endif
+    }
+  }
+
+  cc3000.stopSSIDscan();
+
+  #ifdef WIFI_DEBUG_ON
+  debug_info(F("=== Wifi scan end ==="));
+  #endif
+
+
+  if(see_home_network)
+  {
+    hop_on_home_network(home_encryption_type);
+  }
+  else if(see_open_network && cc3000.getStatus() != STATUS_CONNECTED)
+  {
+    open_network_name.toCharArray(temp_string_a, 40);
+
+    if (cc3000.deleteProfiles())
+    {
+      #ifdef WIFI_DEBUG_ON
+      debug_info(F("wifi pro out"));
+      #endif
+    }
+    else
+    {
+      #ifdef WIFI_DEBUG_ON
+      debug_info(F("wifi pro fail"));
+      #endif
+    }
+
+    if(cc3000.connectSecure(temp_string_a, temp_string_a, WLAN_SEC_UNSEC))
+    //if(cc3000.connectToAP(temp_string_a, temp_string_a, WLAN_SEC_UNSEC))
+    {
+      #ifdef WIFI_DEBUG_ON
+      debug_info("Wifi open connect: " + open_network_name);
+      #endif
+    }
+    else
+    {
+      #ifdef WIFI_DEBUG_ON
+      debug_info("Failed wifi connect: " + open_network_name);
+      #endif
+    }
+  }
+}

 #else

@@ -2771,14 +2903,14 @@
   {

     #ifdef GPRS_DEBUG_ON
-    debug_info("\\/ GPRS-DEBUG  \\/");
+    debug_info(F("\\/ GPRS-DEBUG  \\/"));
     debug_info(gprs_read_buffer);
     #endif

     if(gprs_read_buffer.indexOf("CME ERROR") > 0)
     {
       #ifdef GPRS_DEBUG_ON
-      debug_info("*** Reboot GPRS   ***");
+      debug_info(F("*** Reboot GPRS   ***"));
       #endif
       Serial1.println(F("AT+CFUN=0,1"));
       gprs_connection_state = waiting_for_sind;
@@ -2825,7 +2957,7 @@
       gprs_or_wifi_watchdog_timestamp = current_timestamp;
       Serial1.println(F("AT+CGACT=1,1"));
       #ifdef GPRS_DEBUG_ON
-      debug_info("Waiting on ACT=1,1...");
+      debug_info(F("Waiting on ACT=1,1..."));
       #endif
     }
     else if(gprs_connection_state == waiting_for_pdp_context_active && gprs_read_buffer.indexOf("OK") > 0)
@@ -2852,7 +2984,7 @@
       gprs_connection_state = we_be_connected;
       gprs_or_wifi_watchdog_timestamp = current_timestamp;
       #ifdef GPRS_DEBUG_ON
-      debug_info("We got internets!");
+      debug_info(F("We got internets!"));
       #endif
     }
   }
@@ -2946,7 +3078,7 @@
   {
     gprs_or_wifi_watchdog_counter++;
     #ifdef GPRS_DEBUG_ON
-    debug_info("*** Rebooting GPRS (Watchdog)  ***");
+    debug_info(F("*** Rebooting GPRS (Watchdog)  ***"));
     #endif
     Serial1.println(F("AT+CFUN=0,1"));
     gprs_connection_state = waiting_for_sind;
@@ -3028,7 +3160,7 @@
       gprs_or_wifi_communications_on = true;
       #ifndef WIFI_NOT_CELL
       #ifdef GPRS_DEBUG_ON
-      debug_info("*** Rebooting GPRS (Watchdog)  ***");
+      debug_info(F("*** Rebooting GPRS (Watchdog)  ***"));
       #endif
       Serial1.println(F("AT+CFUN=0,1"));
       gprs_connection_state = waiting_for_sind;
@@ -3099,6 +3231,9 @@
           display_string = "a=";
           display_string += gprs_apn;
           help_info(display_string);
+          #ifdef WIFI_NOT_CELL
+          nuke_wireless();
+          #endif
         }
       }
       else if(console_read_buffer.startsWith("u=") && console_read_buffer.length() > 1)
@@ -3145,6 +3280,9 @@
           display_string = "w=";
           display_string += gprs_password;
           help_info(display_string);
+          #ifdef WIFI_NOT_CELL
+          nuke_wireless();
+          #endif
         }
       }
       else if(console_read_buffer.startsWith("p=") && console_read_buffer.length() > 2)
@@ -3344,6 +3482,7 @@
   }

   #ifdef WIFI_NOT_CELL
+/*
   if(WiFi.status() == WL_CONNECTED)
   {
     if(wifi_communication_state == idle)
@@ -3368,6 +3507,7 @@
   {
     digitalWrite(GREEN_LED, LOW);
   }
+*/
   #else

   //
@@ -3540,10 +3680,10 @@
   #endif

-  #ifdef DEBUG_MEMORY_ON
+  #ifdef STRESS_MEMORY_ON
   for(i=0; i < 10; i++)
   {
-    latest_message_to_send += " MEMORY STRESS TEST";
+    latest_message_to_send += F(" MEMORY STRESS TEST");
   }
   #endif


Starting v009

Starting v009


Fixed the Part 2 code for the gnd antenna: also re-added the escape char checks

--- Arduino/sketchbook/XbeeServerGnd/XbeeServerGnd.ino
+++ Arduino/sketchbook/XbeeServerGnd/XbeeServerGnd.ino
@@ -12,7 +12,7 @@
 //#define SERVER_ADDR 0x66

 Tx64Packet tx_packet;
-
+int rec_index;
 //uVector myvector;
 uint8_t * tx_buffer1;
 uint8_t rec_buf[64];
@@ -151,7 +151,7 @@
       //if(enable == 4) //For gnd nodes
       {
         int k = 0;
-        static int rec_index;
+
         char cv;
         if(Uart.available())
         {
@@ -163,7 +163,7 @@
               rec_index = 0;
               rec_buf[rec_index++] = cv;

-              if(rec_buf[3] = 0x80)
+              if(rec_buf[3] == 0x80)
               {
                 tx_packet.push_back(rec_buf[11]);
                 tx_packet.push_back(rec_buf[12]);


updated marsduino with watchdog timer and reference additions

--- marsduino/marsduino.ino
+++ marsduino/marsduino.ino
@@ -20,14 +20,14 @@
 #include "MemoryFree.h"
 #include "DaqTelemetry.h"

-//Defined as a global for memory
+//Telemetry
 DaqTelemetry *daqTelemetry;

 //Motor
 int enablePin = 13; //enable/disable motor
 int revPin = 11; //seting fwd/rev
 int brakePin = 12; //brake pin
-int speedPin = 6; //speedPin
+int speedPin = 5; //speedPin
 int voltagePin = A0; //ammeter voltage pin
 int currentPin = A1; //ammeter current pin
 int encoderPin = A5; //pin for motor controller
@@ -35,20 +35,36 @@
 boolean directionOfTravel;

 //LEDS
-int ledPin = 10;
+int ledPin = 9;

 //IRdistance sensors
 int frontIrPin = A3;
 int backIrPin = A4;
 int numSamples = 10;
-

 //Conversions
 double rpmMultiplier = 666.6;
 double voltageMultiplier = 0.076982;
 double currentMultiplier = 0.135135;
 double scaleOffset = 2.5;
+
+//Voltage Reference
+bool useRef = true;
 int realReference = 512;
+
+//Watchdog
+bool watchdogEnabled = false;
+unsigned long watchdogTimer;
+unsigned long timeoutTime = 30000;
+String recallCode = "M1005";
+
+//Timing
+unsigned long lastTime = 0;
+
+//Logging
+String logs = "marsduino initated";
+
+

 void setup() {
@@ -71,6 +87,7 @@
   pinMode(ledPin, OUTPUT);
   digitalWrite(ledPin, LOW);

+
   //enabling the serial connection
   Serial.begin(9600);
 }
@@ -80,9 +97,7 @@

    @param c: character to be encoded
 */
-int charToInt(char c) {
-  return c - '0';
-}
+

 /**
    Computes the distance from "WALL-E" (a distance sensor)
@@ -122,9 +137,20 @@
    Reads a string from serial input and parses based off of our format
    specified in our documentation, then executes given command.
 */
-void control_input()
-{
+
+
+
+int charToInt(char c) {
+  return int(c - '0');
+}
+
+String retrieve_code(){
   String input = Serial.readString();
+  return input;
+}
+
+void process_code(String input){
+
   char codeArray[8]; //input string turned into an array
   input.toCharArray(codeArray, 6);

@@ -136,7 +162,7 @@
     case 'M': {
         char enable = codeArray[1] == '0' ? LOW : HIGH;
         char reverse = codeArray[2] == '0' ? LOW : HIGH;
-        char brake = codeArray[3] == '1' ? LOW : HIGH;
+        char brake = codeArray[3] == '0' ? LOW : HIGH;
         char speedValue = codeArray[4];

         digitalWrite(enablePin, enable); //ENABLE PIN(13)
@@ -149,6 +175,7 @@

         //Changing the global direction for reference in the DAQ
         directionOfTravel = codeArray[2] == '0' ? 0 : 1; // one is forwards, zero is backwards
+        logs = "motor code set to level to " + input.substring(1);
         break;
       }
     //LED code
@@ -156,8 +183,30 @@
         char ledValue = codeArray[1];
         int ledDutyCycle = int(charToInt(ledValue) * 25.5);
         analogWrite(ledPin, ledDutyCycle); //sets up PWM on the speedPin
+        logs = "LEDs set to level to " + ledValue;
         break;
       }
+
+    case 'R': {
+      useRef = true;
+      realReference = input.substring(1).toInt();
+      logs = "Voltage Reference set to " + input.substring(1);
+      break;
+    }
+    case 'E': {
+      useRef = false;
+      logs = "Voltage Reference disabled";
+    }
+    case 'W': {
+      watchdogEnabled = true;
+      watchdogTimer = 0;
+      logs = "Watchdog Timer Reset";
+      break;
+    }
+    case 'Q': {
+      watchdogEnabled = false;
+      logs = "Watchdog Timer Disabled";
+    }
   }
 }

@@ -167,13 +216,18 @@
 DaqTelemetry* daq()
 {
   daqTelemetry = new DaqTelemetry();
-
-  //generating an offset based off of the reference voltage sent from motor controller
-  double referenceVoltage = analogRead(referencePin);
-  int voltageOffset = 0; //realReference - referenceVoltage;      //currently depreciated until we can get an accurate voltmeter
-
+  int voltageOffset;
+  if(useRef == true){
+    //generating an offset based off of the reference voltage sent from motor controller
+    double referenceVoltage = analogRead(referencePin);
+    voltageOffset = int(realReference - referenceVoltage);
+  }
+  else{
+    voltageOffset = 0;
+  }
+
   //Motor Calculations
-  double encoderVoltage = (analogRead(encoderPin)+voltageOffset)*.0049; //.0049 convert to real voltage values
+  double encoderVoltage = ( analogRead(encoderPin) + voltageOffset ) * 0.0049; //.0049 convert to real voltage values
   double scaledVoltage = encoderVoltage - scaleOffset;
   double finalRpm = scaledVoltage * rpmMultiplier;

@@ -229,24 +283,35 @@
   String daqString = String(daqTelemetry->systemRpm) + "," +
                      String(daqTelemetry->systemVoltage) + "," +
                      String(daqTelemetry->systemCurrent) + "," +
-                     outputDistance;
+                     String(outputDistance) + "," +
+                     logs + "," +
+                     (millis() / 1000.0 );
   Serial.println(daqString);
 }

-/**
-   TBD
-*/
-
+int update_watchdog_timer(){
+  watchdogTimer = watchdogTimer + ( millis() - lastTime );
+  lastTime = millis();
+  return watchdogTimer;
+}

 void loop() {
+  Serial.println(watchdogTimer);
   if (Serial.available() > 0) {
-    control_input();
-  }
-  //Solve serial buffer problem
+    process_code( retrieve_code() );
+  }
   daqTelemetry = daq();
   save_and_send(daqTelemetry);
+
+ update_watchdog_timer();
+  if(watchdogEnabled == true){
+    if(watchdogTimer > timeoutTime){
+      process_code( recallCode );
+    }
+  }
+  Serial.print("freeMemory()=");
+  Serial.println(freeMemory());
+  logs = "Null";
   delete daqTelemetry;
-  //Serial.print("freeMemory()=");
-  //Serial.println(freeMemory());
-}
-
+}
+


Adicionado PID para o YAW.

Adicionado PID para o YAW.

--- quad/quad.ino
+++ quad/quad.ino
@@ -25,7 +25,7 @@
  * DEBUG *
  *********/

-// #define DEBUG // Habilita a telemetria
+#define DEBUG // Habilita a telemetria
 #ifdef DEBUG
   #define D(X) X
 #else
@@ -151,9 +151,9 @@

 /* PIDs para a taxa de estabilização. Entrada: posição do quadricóptero através do MPU. Objetivo: Posição indicada através do controle. Saída: Taxa de giro proporcional ao erro. */
 /*                        ENTRADA                 SAÍDA          OBJETIVO  P  I  D  DIREÇÃO */
-PID PIDPitchStab (&ypr_degree[DMP_PITCH], &pitch_stab_output,    &rcPitch, 5, 1, 0, DIRECT);
-PID PIDRollStab  (&ypr_degree[DMP_ROLL],  &roll_stab_output,     &rcRoll,  5, 1, 0, DIRECT);
-PID PIDYawStab   (       &yawRate,        &yaw_stab_output,      &rcYaw,   5, 1, 0, DIRECT); // No yaw, utilizará a taxa de rotação, não a posição como referência.
+PID PIDPitchStab (&ypr_degree[DMP_PITCH], &pitch_stab_output,    &rcPitch, 10, 8, 0, REVERSE);
+PID PIDRollStab  (&ypr_degree[DMP_ROLL],  &roll_stab_output,     &rcRoll,  10, 8, 0, DIRECT);
+PID PIDYawStab   (       &yawRate,        &yaw_stab_output,      &rcYaw,   5, 0, 0, DIRECT); // No yaw, utilizará a taxa de rotação, não a posição como referência.

 /* Configuração dos endereços da EEPROM para armazenar os PIDs */
 const int EEPROM_PITCH_P = 0;
@@ -176,10 +176,10 @@
  *************************/

 /* Canais de cada motor */
-const int MOTOR_PIN_FL = 9; /* To-do test this pin */
+const int MOTOR_PIN_FL = 9;
 const int MOTOR_PIN_FR = 10;
-const int MOTOR_PIN_BL = 11; /* To-do test this pin */
-const int MOTOR_PIN_BR = 12; /* To-do test this pin */
+const int MOTOR_PIN_BL = 11;
+const int MOTOR_PIN_BR = 12;

 /* Entidades que representam os motores.
  * Responsáveis por acionar os ESCs realizando um PPM entre 1ms e 2ms. */
@@ -221,6 +221,8 @@

 /* Loop infinito do Arduino. */
 void loop() {
+  unsigned long start = millis();
+
   static float yaw_target = 0;

   /* Se a programação do DMP falhou, não faz nada */
@@ -246,8 +248,11 @@
       yaw_target = ypr_degree[DMP_YAW];   // remember this yaw for when pilot stops
     }

-    yaw_stab_output = 0;
+    /* Debug */
+    pitch_stab_output = 0;
+    // yaw_stab_output = 0;
     roll_stab_output = 0;
+
     motors[MOTOR_FL] = rcThrottle + roll_stab_output + pitch_stab_output - yaw_stab_output;
     motors[MOTOR_BL] = rcThrottle + roll_stab_output - pitch_stab_output + yaw_stab_output;
     motors[MOTOR_FR] = rcThrottle - roll_stab_output + pitch_stab_output + yaw_stab_output;
@@ -268,16 +273,29 @@
   /* Pisca a led para indicar atividade */
   blinkState = !blinkState;
   digitalWrite(LED_PIN, blinkState);
+
+  unsigned long now = millis();
+  if (now - start < 60) {
+    delay(60 - (now - start));
+  }
 }

 /* Efetua a leitura dos canais dos controles. */
 void readRC() {
-  channels[0] = pulseIn(CH1, HIGH, 20000); /* Roll (horizontal da direita) */
-  channels[1] = pulseIn(CH2, HIGH, 20000); /* Pitch (vertical da direita) */
+  //channels[0] = pulseIn(CH1, HIGH, 20000); /* Roll (horizontal da direita) */
+  //channels[1] = pulseIn(CH2, HIGH, 20000); /* Pitch (vertical da direita) */
+  //channels[2] = pulseIn(CH3, HIGH, 20000); /* Throttle (vertical da esquerda) */
+  //channels[3] = pulseIn(CH4, HIGH, 20000); /* Yaw (horizontal da esquerda */
+  //channels[4] = pulseIn(CH5, HIGH, 20000); /* ON/OFF */
+  //channels[5] = pulseIn(CH6, HIGH, 20000); /* Dimmer */
+
+  channels[0] = 1500;
+  channels[1] = 1500;
   channels[2] = pulseIn(CH3, HIGH, 20000); /* Throttle (vertical da esquerda) */
-  channels[3] = pulseIn(CH4, HIGH, 20000); /* Yaw (horizontal da esquerda */
-  channels[4] = pulseIn(CH5, HIGH, 20000); /* ON/OFF */
-  channels[5] = pulseIn(CH6, HIGH, 20000); /* Dimmer */
+  channels[2] = 1500;
+  channels[3] = 1500;
+  channels[4] = 1000;
+  channels[5] = 1000;

   normalizeRC();
 }
@@ -355,7 +373,9 @@
 /* Efetua o setup do PID */
 void setupPID() {
   /* Inicializa o PID */
-  getPIDParametersAndSetTunnings();
+  /* TODO: REMOVER COMENTÁRIO */
+  /* getPIDParametersAndSetTunnings(); */
+  /* END TODO */

   PIDPitchStab.SetMode(AUTOMATIC);
   PIDRollStab.SetMode(AUTOMATIC);
@@ -481,6 +501,11 @@
   rcThrottle = channels[2];
   rcOnOff    = map(channels[4], MIN_RC_ON_OFF, MAX_RC_ON_OFF, 0, 100);
   rcDimmer   = map(channels[5], MIN_RC_DIMMER, MAX_RC_DIMMER, 0, 255);
+
+  /* TODO: REMOVER */
+  rcRoll = rcPitch = rcYaw = 0;
+  rcThrottle = 1300;
+  /* END TODO */
 }

 /* Define os valores referentes ao zero do controle para Roll, Yaw e Pitch com base em 10 leituras do controle. */
@@ -503,11 +528,13 @@
     rcYawZero += pulseIn(CH4, HIGH, 20000);
   }
   rcYawZero /= 10;
+
+  /* TODO: REMOVER */
+  rcRollZero = rcPitchZero = rcYawZero = 1500;
 }

 /* Efetua a escrita da potência dos motores entre 1ms e 2ms */
 void writeMotor() {
-  // int val = map(rcThrottle, MIN_RC_THROTTLE, MAX_RC_THROTTLE, 1000, 2000); /* To-do: trocar por constrain */
   motorFL.writeMicroseconds(constrain(motors[MOTOR_FL], 1000, 2000));
   motorFR.writeMicroseconds(constrain(motors[MOTOR_FR], 1000, 2000));
   motorBL.writeMicroseconds(constrain(motors[MOTOR_BL], 1000, 2000));
@@ -526,16 +553,13 @@

     /* Obtém o byte INT_STATUS do MPU */
     mpuIntStatus = mpu.getIntStatus();
-    // D(Serial.println("getIntStatus: " + String(mpuIntStatus)));

     /* Obtém a contagem da FIFO */
     fifoCount = mpu.getFIFOCount();
-    // D(Serial.println("getFIFOCount: " + String(fifoCount)));

     /* Verifica se houve overflow da FIFO. Quanto mais ineficiente o código, mais irá ocorrer. */
     if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
       // Reseta a FIFO
-      // D(Serial.println("resetFIFO: " + String(fifoCount)));
       mpu.resetFIFO();
       fifoOverflow = true;
       return;
@@ -554,17 +578,13 @@
       fifoCount = mpu.getFIFOCount();

       /* Aguarda encher a FIFO caso não esteja com os todos dados completos (pacote completo) */
-      // Serial.println("Agu pac");
       int DMPwatchdog = 0;
       while (fifoCount < packetSize && DMPwatchdog < 5) {
         fifoCount = mpu.getFIFOCount();
-        // D(Serial.println("Count: " + String(fifoCount)));
         DMPwatchdog++;
       }

       if (DMPwatchdog < 5) {
-        // D(Serial.println("Pac rec...."));
-
         /* Dado está pronto para ser lido do MPU */
         mpu.getFIFOBytes(fifoBuffer, packetSize);

@@ -572,8 +592,7 @@
         mpu.dmpGetQuaternion(&q, fifoBuffer);
         mpu.dmpGetGravity(&gravity, &q);
         mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
-        yawRate = mpu.getRotationZ();
-        // D(Serial.println("Fim lei"));
+        yawRate = mpu.getRotationZ()/16.4; // Precision FS_SEL = 3 -> 16.4/LSB/deg/s

         /* Converte para graus/segundo */
         for (int i = 0; i < 3; i++) {
@@ -586,22 +605,26 @@

 /*
  * Efetua a telemetria dos dados do quadricoptero na seguinte ordem, separados por ';':
- * - rcThrottle (em us - entre ~1000 a ~2000)
- * - rcYaw    (entre -150 e 150)
- * - rcPitch  (entre -45 e 45)
- * - rcRoll   (entre -45 e 45)
- * - rcOnOff  (entre 0 e 100)
- * - rcDimmer (entre 0 e 1000)
- * - Posição: pitch (em graus)
- * - Posição: roll (em graus)
- * - Posição: yaw (em graus)
- * - Saída pitch do PID stab: pitch_stab_output (entre -500 a 500)
- * - Saída roll do PID stab: roll_stab_output (entre -500 a 500)
- * - Saída yaw do PID stab: yaw_stab_output (entre -500 a 500)
- * - Motor FL (em us - entre 1000 a 2000)
- * - Motor FR (em us - entre 1000 a 2000)
- * - Motor BL (em us - entre 1000 a 2000)
- * - Motor BR (em us - entre 1000 a 2000)
+ * - RCT - rcThrottle (em us - entre ~1000 a ~2000)
+ * - RCY - rcYaw    (entre -150 e 150)
+ * - RCP - rcPitch  (entre -45 e 45)
+ * - RCR - rcRoll   (entre -45 e 45)
+ * - RCO - rcOnOff  (entre 0 e 100)
+ * - RCD - rcDimmer (entre 0 e 1000)
+ * - ZRP - Posição 0 do Pitch no controle
+ * - ZRR - Posição 0 do Roll no controle
+ * - ZRY - Posição 0 do Pitch no controle
+ * - DMP - Posição: pitch (em graus)
+ * - DMR - Posição: roll (em graus)
+ * - DMY - Posição: yaw (em graus)
+ * - YRT - Taxa: yaw (em graus/seg)
+ * - PIP - Saída pitch do PID stab: pitch_stab_output (entre -500 a 500)
+ * - PIR - Saída roll do PID stab: roll_stab_output (entre -500 a 500)
+ * - PIY - Saída yaw do PID stab: yaw_stab_output (entre -500 a 500)
+ * - MFL - Motor FL (em us - entre 1000 a 2000)
+ * - MFR - Motor FR (em us - entre 1000 a 2000)
+ * - MBL - Motor BL (em us - entre 1000 a 2000)
+ * - MBR - Motor BR (em us - entre 1000 a 2000)
  * - Canal 1 (em us - entre ~1000 a ~2000)
  * - Canal 2 (em us - entre ~1000 a ~2000)
  * - Canal 3 (em us - entre ~1000 a ~2000)
@@ -627,7 +650,8 @@
   // tmValues += padding("ZRY=" + String(int(rcYawZero)), 9) + ";";
   tmValues += padding("DMP=" + String(int(ypr_degree[DMP_PITCH])), 9) + ";";
   tmValues += padding("DMR=" + String(int(ypr_degree[DMP_ROLL])), 9) + ";";
-  tmValues += padding("DMY=" + String(int(ypr_degree[DMP_YAW])), 9) + ";";
+  // tmValues += padding("DMY=" + String(int(ypr_degree[DMP_YAW])), 9) + ";";
+  tmValues += padding("YRT=" + String(int(yawRate)), 9) + ";";
   tmValues += padding("PIP=" + String(int(pitch_stab_output)), 8) + ";";
   tmValues += padding("PIR=" + String(int(roll_stab_output)), 8) + ";";
   tmValues += padding("PIY=" + String(int(yaw_stab_output)), 8) + ";";
@@ -635,10 +659,10 @@
   tmValues += padding("MFR=" + String(int(motors[MOTOR_FR])), 9) + ";";
   tmValues += padding("MBL=" + String(int(motors[MOTOR_BL])), 9) + ";";
   tmValues += padding("MBR=" + String(int(motors[MOTOR_BR])), 9) + ";";
-  tmValues += padding("INT=" + String(tmInterval), 11) + ";";
   // for (int i=0; i < 6; i++) {
   //  tmValues += padding(String(channels[i]), 8) + ";";
   // }
+  tmValues += padding("INT=" + String(tmInterval), 11) + ";";

   countToSend++;
   if (countToSend > 4) {


Updated perch trigger values

Updated perch trigger values

--- feeder.ino
+++ feeder.ino
@@ -24,8 +24,8 @@

 const int MEAT_SENSED_THRESHOLD = 200;
 const int MEAT_CLEARED_THRESHOLD = 100;
-const int PERCH_TRIGGERED_THRESHOLD = 500;
-const int PERCH_CLEAR_THRESHOLD = 200;
+const int PERCH_TRIGGERED_THRESHOLD = 2500;
+const int PERCH_CLEAR_THRESHOLD = 2000;

 PololuStepper stepper;
 Plunger plunger;


Fixes #24. (#28)

Fixes #24. (#28)

--- wifitask.ino
+++ wifitask.ino
@@ -1,5 +1,4 @@
-void IRAM_ATTR wifiTask( void * pvParameters )
-{
+void wifiTask( void * pvParameters ) {
   /* trying last accesspoint */
   WiFi.mode( WIFI_STA );
   WiFi.begin();
@@ -7,18 +6,15 @@

   ESP_LOGI( TAG, "Connecting WiFi" );

-  if ( xTftTaskHandle )
-  {
+  if ( xTftTaskHandle ) {
     tft.setTextColor( TFT_TEXT_COLOR , TFT_BACK_COLOR );
     tft.println( "Connecting WiFi");
   }

-  waitForWifi();
+  WiFi.waitForConnectResult();

-  if ( WiFi.status() != WL_CONNECTED )
-  {
-    if ( xTftTaskHandle )
-    {
+  if ( WiFi.status() != WL_CONNECTED ) {
+    if ( xTftTaskHandle ) {
       tft.println( "\nNo WiFi connection.\nWaiting for SmartConfig." );
       tft.invertDisplay( true );
     }
@@ -32,12 +28,9 @@

     ESP_LOGI( TAG, "Waiting %i seconds for SmartConfig.", rebootDelayMs / 1000 );

-
-    while ( !WiFi.smartConfigDone() && ( (unsigned long)millis() - smartConfigStartMs ) < rebootDelayMs )
-    {
+    while ( !WiFi.smartConfigDone() && ( (unsigned long)millis() - smartConfigStartMs ) < rebootDelayMs ) {
       char remainingSCTime[12];
-      if ( xOledTaskHandle )
-      {
+      if ( xOledTaskHandle ) {
         OLED.clear();
         OLED.setFont( ArialMT_Plain_10 );
         OLED.drawString( 64, 10, "Waiting for SmartConfig." );
@@ -47,52 +40,38 @@
         OLED.display();
       }

-      if ( xTftTaskHandle )
-      {
+      if ( xTftTaskHandle ) {
         tft.setCursor( 70, 100 );
         tft.print( remainingSCTime );
       }
       else
-      {
-        digitalWrite( TFT_BACKLIGHT_PIN, !gpio_get_level( gpio_num_t( TFT_BACKLIGHT_PIN ) ) );
-      }
+        digitalWrite( BUILTIN_LED, !gpio_get_level( gpio_num_t( BUILTIN_LED ) ) );
       vTaskDelay( 500 / portTICK_PERIOD_MS );
     }

     if ( !WiFi.smartConfigDone() )
-    {
       ESP.restart();
-    }

     if ( !xTftTaskHandle )
-    {
-      digitalWrite( TFT_BACKLIGHT_PIN, LOW );
-    }
+      digitalWrite( BUILTIN_LED, LOW );
   }

   waitForWifi();

   /* We have succesfully connected */
-  ESP_LOGI( TAG, "WiFi connected to %s", WiFi.SSID().c_str() );
-  tcpip_adapter_ip_info_t ip_info;
-  ESP_ERROR_CHECK( tcpip_adapter_get_ip_info( TCPIP_ADAPTER_IF_STA, &ip_info ) );
-  ESP_LOGI( TAG, "Local IP: %s", ip4addr_ntoa( &ip_info.ip ) );
   uint8_t mac[6];
   esp_efuse_mac_get_default(mac);
-  ESP_LOGI( TAG, "MAC: %02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
-  if ( xTftTaskHandle )
-  {
+  ESP_LOGI( TAG, "WiFi '%s' %s %02x:%02x:%02x:%02x:%02x:%02x",
+            WiFi.SSID().c_str(), WiFi.localIP().toString().c_str(), mac[0], mac[1], mac[2], mac[3], mac[4], mac[5] );
+  if ( xTftTaskHandle ) {
     tft.invertDisplay( false );
-    tft.printf( "WiFi connected.\nLocal IP: %s\n", ip4addr_ntoa( &ip_info.ip ) );
+    tft.printf( "WiFi connected.\nLocal IP: %s\n", WiFi.localIP().toString() );
   }
   if ( xOledTaskHandle )
-  {
     OLED.normalDisplay();
-  }
   strncpy( hostName, preferences.getString( "hostname", "" ).c_str(), sizeof( hostName ) );

-  if ( hostName[0] ==  0 )
-  {
+  if ( hostName[0] ==  0 ) {
     snprintf( hostName, sizeof( hostName ), "%s%c%c%c%c%c%c", DEFAULT_HOSTNAME_PREFIX,
               WiFi.macAddress()[9], WiFi.macAddress()[10],
               WiFi.macAddress()[12], WiFi.macAddress()[13],
@@ -100,14 +79,8 @@
             );
   }

-  if ( !MDNS.begin( "" ) )
-  {
-    ESP_LOGE( TAG, "Error setting up mDNS." );
-  }
-  else if ( !setupMDNS( hostName ) )
-  {
+  if ( !MDNS.begin( "" ) && !setupMDNS( hostName ) )
     ESP_LOGE( TAG, "Error setting up %s as hostname. ", hostName );
-  }

   /* start network dependent tasks */
   xTaskCreatePinnedToCore(
@@ -128,10 +101,8 @@
     NULL,                           /* Task handle. */
     1);                             /* Core where the task should run */

-  while (1)
-  {
-    if ( !WiFi.isConnected() )
-    {
+  while (1) {
+    if ( !WiFi.isConnected() ) {
       ESP_LOGI( TAG, "No Wifi. Reconnecting.." );
       WiFi.reconnect();
       vTaskDelay( 9000 / portTICK_PERIOD_MS );
@@ -141,23 +112,14 @@
 }

 /* https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFi/src/WiFiType.h */
-void waitForWifi()
-{
+void waitForWifi() {
   unsigned long timeOut = millis() + 10000;
   while ( !WiFi.isConnected() && millis() < timeOut )
-  {
-    if ( xTftTaskHandle )
-    {
-      tft.print( "." );
-    }
-    vTaskDelay( 500 / portTICK_PERIOD_MS );
-  }
+    vTaskDelay( 20 / portTICK_PERIOD_MS );
 }
-/*
-  void WiFiEvent( WiFiEvent_t event )
-  {
-  switch ( event )
-  {
+
+void WiFiEvent( WiFiEvent_t event ) {
+  switch ( event ) {
     case SYSTEM_EVENT_AP_START:
       ESP_LOGI( TAG, "AP Started");
       //WiFi.softAPsetHostname(AP_SSID);
@@ -190,5 +152,4 @@
     default:
       break;
   }
-  }
-*/
+}


Support $implementation/reset -> true

Support $implementation/reset -> true

--- homie-dht.ino
+++ homie-dht.ino
@@ -27,6 +27,7 @@

 static void loopHandler() {
   static unsigned long lastPublish = 0;
+
   unsigned long now = millis();
   bool deepSleep = deepSleepSetting.get();
   unsigned long publishInterval = publishIntervalSetting.get() * 1000UL;


reinstate temp sensor; more led blinking


large test

large test


simple pinball

simple pinball


'Rysk' ver 0.04

'Rysk' ver 0.04

:bulb: Tune LED color
:tv: Improve the judgment of screen boundary
:black_nib: Draw outline around letters

--- rysk/rysk.ino
+++ rysk/rysk.ino
@@ -10,7 +10,7 @@
 #define FPS             60
 #define APP_TITLE       "RYSK"
 #define APP_CODE        "OBN-Y00"
-#define APP_VERSION     "0.03"
+#define APP_VERSION     "0.04"
 #define APP_RELEASED    "NOVEMBER 2019"

 #define COOKIES         8
@@ -74,6 +74,7 @@
 static void drawObject(int16_t x, int16_t y, uint8_t size, const uint8_t *bitmap);
 static void drawStatus(void);
 static int  drawFigure(int16_t x, int16_t y, int value, uint8_t align);
+static void drawBorderedLetter(int16_t x, int16_t y, uint8_t w, uint8_t h, const uint8_t *bitmap);
 static void drawClock(int16_t x, int16_t y, uint8_t r, uint8_t sec);

 /*  Variables  */
@@ -179,8 +180,8 @@
 };

 PROGMEM static const uint8_t ledValues[] = {
-    LED_VALUE(2, 2, 2), LED_VALUE(4, 0, 0), LED_VALUE(0, 0, 4), LED_VALUE(3, 3, 0), LED_VALUE(0, 4, 0),
-    LED_VALUE(3, 1, 1), LED_VALUE(2, 1, 0), LED_VALUE(2, 0, 3), LED_VALUE(1, 3, 0), LED_VALUE(0, 2, 2)
+    LED_VALUE(2, 2, 2), LED_VALUE(4, 0, 0), LED_VALUE(0, 0, 4), LED_VALUE(3, 3, 0), LED_VALUE(0, 3, 0),
+    LED_VALUE(4, 1, 2), LED_VALUE(2, 1, 0), LED_VALUE(2, 0, 3), LED_VALUE(2, 4, 0), LED_VALUE(0, 3, 3)
 };

 MyArduboy   arduboy;
@@ -261,6 +262,7 @@
     arduboy.setCursor(40, 58);
     arduboy.print(F("RYSK " APP_VERSION));
     isPlaying = false;
+    arduboy.setRGBled(0, 0, 0);
 }

 static void update(void)
@@ -327,10 +329,12 @@
     if (arduboy.buttonPressed(UP_BUTTON))    vy--;
     if (arduboy.buttonPressed(DOWN_BUTTON))  vy++;
     int8_t vs = (vx != 0 && vy != 0) ? (SCALE * 3 / 8) : (SCALE / 2);
-    int16_t dx = playerX + vx * vs;
-    int16_t dy = playerY + vy * vs;
-    if (dx >= PL_SIZE_S && dx < WIDTH_S - PL_SIZE_S) playerX = dx;
-    if (dy >= PL_SIZE_S && dy < HEIGHT_S - PL_SIZE_S) playerY = dy;
+    playerX += vx * vs;
+    playerY += vy * vs;
+    if (playerX < PL_SIZE_S)            playerX = PL_SIZE_S;
+    if (playerX > WIDTH_S - PL_SIZE_S)  playerX = WIDTH_S - PL_SIZE_S;
+    if (playerY < PL_SIZE_S)            playerY = PL_SIZE_S;
+    if (playerY > HEIGHT_S - PL_SIZE_S) playerY = HEIGHT_S - PL_SIZE_S;

     /*  Animation  */
     playerChr = (vy + 1) * 3 + (vx + 1);
@@ -348,8 +352,8 @@
 {
     int16_t dx = pCookie->x + pCookie->vx;
     int16_t dy = pCookie->y + pCookie->vy;
-    if (dx < CK_SIZE_S || dx >= WIDTH_S - CK_SIZE_S) pCookie->vx = -pCookie->vx;
-    if (dy < CK_SIZE_S || dy >= HEIGHT_S - CK_SIZE_S) pCookie->vy = -pCookie->vy;
+    if (dx < CK_SIZE_S || dx > WIDTH_S - CK_SIZE_S) pCookie->vx = -pCookie->vx;
+    if (dy < CK_SIZE_S || dy > HEIGHT_S - CK_SIZE_S) pCookie->vy = -pCookie->vy;
     pCookie->x += pCookie->vx;
     pCookie->y += pCookie->vy;
 }
@@ -394,15 +398,15 @@
 static void drawStatus(void)
 {
     if (gameTime > GAME_DURATION + FPS) {
-        arduboy.drawBitmap((WIDTH - IMG_START1_W) / 2, 8, imgStart1, IMG_START1_W, IMG_START1_H, WHITE);
+        drawBorderedLetter((WIDTH - IMG_START1_W) / 2, 8, IMG_START1_W, IMG_START1_H, imgStart1);
     } else if (gameTime > GAME_DURATION) {
-        arduboy.drawBitmap((WIDTH - IMG_START2_W) / 2, 8, imgStart2, IMG_START2_W, IMG_START2_H, WHITE);
+        drawBorderedLetter((WIDTH - IMG_START2_W) / 2, 8, IMG_START2_W, IMG_START2_H, imgStart2);
     } else {
         int dx = drawFigure(0, 0, score, ALIGN_LEFT);
-        arduboy.drawBitmap(dx, 0, imgTen, IMG_TEN_W, IMG_TEN_H, WHITE);
+        drawBorderedLetter(dx, 0, IMG_TEN_W, IMG_TEN_H, imgTen);
         drawClock(CLOCK_X, CLOCK_Y, CLOCK_R, (gameTime > 0) ? (GAME_DURATION - gameTime) / FPS : 0);
         if (gameTime <= 0) {
-            arduboy.drawBitmap((WIDTH - IMG_OVER_W) / 2, 48, imgOver, IMG_OVER_W, IMG_OVER_H, WHITE);
+            drawBorderedLetter((WIDTH - IMG_OVER_W) / 2, 48, IMG_OVER_W, IMG_OVER_H, imgOver);
         }
     }
 }
@@ -410,8 +414,17 @@
 static int drawFigure(int16_t x, int16_t y, int value, uint8_t align)
 {
     int k = (value > 9) ? drawFigure(x - align * 4, y, value / 10, align) : 0;
-    arduboy.drawBitmap(x + k, y, imgFigures[value % 10], IMG_FIGURE_W, IMG_FIGURE_H, WHITE);
+    drawBorderedLetter(x + k, y, IMG_FIGURE_W, IMG_FIGURE_H, imgFigures[value % 10]);
     return k + 8 - align * 4;
+}
+
+static void drawBorderedLetter(int16_t x, int16_t y, uint8_t w, uint8_t h, const uint8_t *bitmap)
+{
+    arduboy.drawBitmap(x, y - 1, bitmap, w, h, BLACK);
+    arduboy.drawBitmap(x - 1, y, bitmap, w, h, BLACK);
+    arduboy.drawBitmap(x + 1, y, bitmap, w, h, BLACK);
+    arduboy.drawBitmap(x, y + 1, bitmap, w, h, BLACK);
+    arduboy.drawBitmap(x, y, bitmap, w, h, WHITE);
 }

 static void drawClock(int16_t x, int16_t y, uint8_t r, uint8_t sec)
@@ -419,6 +432,7 @@
     float d = sec * PI / 30.0;
     int16_t vx = sin(d) * r;
     int16_t vy = -cos(d) * r;
+    arduboy.fillCircle(x, y, r, BLACK);
+    arduboy.drawCircle(x, y, r, WHITE);
     arduboy.drawLine(x, y, x + vx, y + vy, WHITE);
-    arduboy.drawCircle(x, y, r, WHITE);
-}
+}


test1

test1

issue encoder reading

--- send/send.ino
+++ send/send.ino
@@ -1,108 +1,68 @@
-// demo: CAN-BUS Shield, send data
-#include <mcp_can.h>
+// demo: CAN-BUS Shield, receive data with check mode
+// send data coming to fast, such as less than 10ms, you can use this way
+// loovee, 2014-6-13
+
+
 #include <SPI.h>
+#include "mcp_can.h"
+

 // the cs pin of the version after v1.1 is default to D9
 // v0.9b and v1.0 is default D10
 const int SPI_CS_PIN = 9;
+uint32_t data = 0;

 MCP_CAN CAN(SPI_CS_PIN);                                    // Set CS pin
-
-int sensorValue = 0;        // value read from the pot
-unsigned char setpoint_position[8] = {0, 1, 2, 3, 4, 5, 6, 7};
-
-String inputString = "";         // a string to hold incoming data
-boolean stringComplete = false;  // whether the string is complete
-
-uint32_t angulo = 0;

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

-  // TIMER SETUP- the timer interrupt allows precise timed measurements of the reed switch
-  //for mor info about configuration of arduino timers see http://arduino.cc/playground/Code/Timer1
-
-  cli();//stop interrupts
-
-  //set timer1 interrupt at 1kHz
-  TCCR1A = 0;// set entire TCCR1A register to 0
-  TCCR1B = 0;// same for TCCR1B\
-  TCNT1  = 0;//initialize counter value to 0
-  // set timer count for 1khz increments
-  OCR1A = 19990/2;// = (16*10^6) / (1000*8) - 1
-  //had to use 16 bit timer1 for this bc 1999>255, but could switch to timers 0 or 2 with larger prescaler
-  // turn on CTC mode
-  TCCR1B |= (1 << WGM12);
-  // Set CS11 bit for 8 prescaler
-  TCCR1B |= (1 << CS11);
-  // enable timer compare interrupt
-  TIMSK1 |= (1 << OCIE1A);
-  Serial.println("Timer Setup OK!");
-  delay(100);
-
-  //END TIMER SETUP
-
     while (CAN_OK != CAN.begin(CAN_1000KBPS))              // init can bus : baudrate = 500k
     {
         Serial.println("CAN BUS Shield init fail");
-        delay(100);
         Serial.println(" Init CAN BUS Shield again");
         delay(100);
     }
     Serial.println("CAN BUS Shield init ok!");
-
-    delay(100);
 }

-unsigned char stmp[8] = {0, 1, 2, 3, 4, 5, 6, 7};
-
-void serialEvent() {
-  while (Serial.available()) {
-    // get the new byte:
-    char inChar = (char)Serial.read();
-    // add it to the inputString:
-    inputString += inChar;
-    // if the incoming character is a newline, set a flag
-    // so the main loop can do something about it:
-    if (inChar == '\n') {
-      stringComplete = true;
-    }
-  }
-}
-
-void PotRead(void) {
-
-  // read the analog in value:
-  sensorValue = analogRead(A0);
-  delay(10);
-
-  // map it to the range of the analog out:
-  angulo = map(sensorValue, 0, 960, 0, 3600);
-//angulo = angulo + 1;
-
-  //setpoint_position_position[6]+=10;
-  setpoint_position[4] = angulo & 0xFF;
-  setpoint_position[5] = (angulo >> 8) & 0xFF;
-  setpoint_position[6] = (angulo >> 16) & 0xFF;
-  setpoint_position[7] = (angulo >> 24) & 0xFF;
-}
-
-ISR(TIMER1_COMPA_vect) { //timer1 interrupt 1kHz toggles pin 13 (LED)
-
-      PotRead();
-      Serial.println(angulo);
-}

 void loop()
 {
-    Serial.println("Entrou no Loop");
-    sei();//allow interrupts
-    // send data:  id = 0x00, standrad frame, data len = 8, stmp: data buf
-    CAN.sendMsgBuf(0x00, 0, 8, setpoint_position);
-    delay(100);                       // send data per 100ms
+    unsigned char len = 0;
+    unsigned char buf[8];
+
+    if(CAN_MSGAVAIL == CAN.checkReceive())            // check if data coming
+    {
+        CAN.readMsgBuf(&len, buf);    // read data,  len: data length, buf: data buf
+
+        unsigned int canId = CAN.getCanId();
+
+        Serial.println("-----------------------------");
+        Serial.print("Get data from ID: ");
+        Serial.println(canId, HEX);
+
+        for(int i = 0; i<len; i++)    // print the data
+        {
+            Serial.print(buf[i], HEX);
+            Serial.print("\t");
+        }
+        Serial.println();
+    }
+
+        // data = buf[1]*256*256 + buf[2]*256 + buf[3];
+    data = (buf[5]*256 + buf[6])*(360/4096);
+
+
+    // if (buf[1] >= 128) {
+        data = data - 16777216;
+    // }
+
+    Serial.print("Data: ");
+    Serial.println(data);
 }

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


update proc_get() > to take 2000 msec wait to show the sender on LCD before the message

--- esp8266_160220_BYOP.ino
+++ esp8266_160220_BYOP.ino
@@ -6,6 +6,8 @@

 /*
+ * v0.31 2016 Mar. 5
+ *  - proc_get() takes 2000 msec wait to show the sender on LCD before the message
  * v0.30 2016 Mar. 4
  *  - return [SenderName] in proc_get()
  *    + update proc_get()
@@ -229,6 +231,12 @@

   bool isScrt = MsgServer_GetIsSecretOf1stMessage(rcver);

+  // show sender of the message
+  String fromMsg = "from:" + sndr;
+  AQM0802_Clear();
+  AQM0802_PutMessage(fromMsg, /* x_st1=*/1, /* y_st1=*/1);
+  delay(2000/*msec*/);
+
   // ---
   // When the user reads the message, the message is removed.
   MsgServer_Remove1stMessage(rcver);


Added nicer buttons for simple server

Added nicer buttons for simple server


Added a alternating light display method.

--- Robot_Lights_Display/Robot_Lights_Display.ino
+++ Robot_Lights_Display/Robot_Lights_Display.ino
@@ -23,11 +23,11 @@
   for (int c = 2; c > 0; c--) {
     cylon(YELLOW, BLUE);
   }
-  for (int i=0 ; i < NUM_LEDS; i++) {
-        leds[i] = CRGB::Red;
+  displayRed();
+  for (int c = 20; c > 0; c--) {
+    alternate(YELLOW, BLUE);
   }
-  FastLED.show();
-  delay(2000);
+  displayRed();
 }

@@ -55,3 +55,41 @@
 		delay(30);
 	}
 }
+
+void alternate(CRGB colorOne, CRGB colorTwo) {
+  for(int i = 0; i < NUM_LEDS; i++) {
+
+    if ((i & 1) == 0) { // For even numbered LEDs...
+      leds[i] = colorOne;
+    }
+    else {
+      leds[i] = colorTwo;
+    }
+
+  }
+
+  FastLED.show();
+  delay(200);
+
+  for(int i = 0; i < NUM_LEDS; i++) {
+
+    if ((i & 1) == 1) { // For odd numbered LEDs...
+      leds[i] = colorOne;
+    }
+    else {
+      leds[i] = colorTwo;
+    }
+
+  }
+
+  FastLED.show();
+  delay(200);
+}
+
+void displayRed() {
+  for (int i=0 ; i < NUM_LEDS; i++) {
+        leds[i] = CRGB::Red;
+  }
+  FastLED.show();
+  delay(2000);
+}


Fixed button map and added new JSON format

--- Sensors/iot-demo-sensors/iot-demo-sensors.ino
+++ Sensors/iot-demo-sensors/iot-demo-sensors.ino
@@ -1,13 +1,13 @@
 #define DEBOUNCE 10  // button debouncer, how many ms to debounce, 5+ ms is usually plenty

 // here is where we define the buttons that we'll use. button "1" is the first, button "6" is the 6th, etc
-byte buttons[] = {3, 5}; // 12
-String buttonNames[] = {"pb1", "pb2"};
+byte buttons[] = {3, 4, 5}; // 12
+String buttonNames[] = {"pb1", "pb2", "pb3"};

 // This handy macro lets us determine how big the array up above is, by checking the size
 #define NUMBUTTONS sizeof(buttons)

-byte potmeters[] = {14}; // A0-14, A5-19 6
+byte potmeters[] = {18}; // A0-14, A5-19 6

 String potmeterNames[] = {"pot1"};
 // This handy macro lets us determine how big the array up above is, by checking the size
@@ -63,7 +63,7 @@
 }

 String getSensorValueJSON(int value){
-  return String("{\"value\" : " + String(value, DEC) + "}");
+  return String("[\"messageName\" : {\"value\" : " + String(value, DEC) + "}]");
 }

 void reportButtons(){


Forgot to remove the negation of an if, whoops

--- temp/temp.ino
+++ temp/temp.ino
@@ -4,7 +4,7 @@
 #include <LiquidCrystal.h>
 #include <DHT.h>

-#define DEBUG 0                         // if DEBUG is 1, the arduino will print data on Serial
+#define DEBUG 1                         // if DEBUG is 1, the arduino will print data on Serial

 #define PHOTOpin A0                     // analog photoresistor
 #define GASpin A7                       // analog gas
@@ -158,7 +158,7 @@
   for( loadTime = 7 ; loadTime < 10; ++loadTime)
     loadScreen(loadTime);

-  if(!(bufferr[0]!=ESP8266_SSID[0] || bufferr[1]!=ESP8266_SSID[1] || bufferr[2]!=ESP8266_SSID[2])){          // test if the ESP is already connected to previous WiFi
+  if(bufferr[0]!=ESP8266_SSID[0] || bufferr[1]!=ESP8266_SSID[1] || bufferr[2]!=ESP8266_SSID[2]){          // test if the ESP is already connected to previous WiFi
   wifiSEND.sendCommand(F("AT+RST"), bufferr, sizeof(bufferr));                 // reset WiFi module
   delay(2000);
   wifiSEND.setupAsWifiStation(ESP8266_SSID, ESP8266_PASS, &Serial);            // connect to the WiFi with the set ssid and password


Update ArduCAM_Mini_2MP_OV2640_functions.ino

--- ArduCAM/examples/mini/ArduCAM_Mini_2MP_OV2640_functions/ArduCAM_Mini_2MP_OV2640_functions.ino
+++ ArduCAM/examples/mini/ArduCAM_Mini_2MP_OV2640_functions/ArduCAM_Mini_2MP_OV2640_functions.ino
@@ -49,8 +49,14 @@
 Serial.println(F("ACK CMD ArduCAM Start! END"));
 // set the CS as an output:
 pinMode(CS, OUTPUT);
+digitalWrite(CS,HIGH);
 // initialize SPI:
 SPI.begin();
+  //Reset the CPLD
+myCAM.write_reg(0x07, 0x80);
+delay(100);
+myCAM.write_reg(0x07, 0x00);
+delay(100);
 while(1){
   //Check if the ArduCAM SPI bus is OK
   myCAM.write_reg(ARDUCHIP_TEST1, 0x55);


morse gap delay substitution to doPowerDown()

--- first_one/first_one.ino
+++ first_one/first_one.ino
@@ -355,7 +355,7 @@
         break;

       case ' ': //gap
-        delay( MORSE_UNIT_TIME );
+        doPowerDown(MORSE_UNIT_TIME, TIME_MULTIPLIER);
     }
   }


Update ffdgjghk.ino

Update ffdgjghk.ino

--- temp/ffdgjghk.ino
+++ temp/ffdgjghk.ino
@@ -1,20 +1,131 @@
-#include <SoftwareSerial.h>
-SoftwareSerial mySerial(10, 11);
-int c=0;
-uint8_t CK_A = 0, CK_B = 0;
-void setup() {
-Serial.begin(57600);
-mySerial.begin(9600);
-Serial.read();
-}
-void ubx_checksum(byte ubx_data)
-{
-  CK_A+=ubx_data;
-  CK_B+=CK_A;
-}
-void loop()
-{
-  mySerial.write(Serial);
-}
-
+#include <SoftwareSerial.h>
+SoftwareSerial mySerial(10, 11);
+int c=0;
+uint8_t message[60];
+uint8_t CK_A = 0, CK_B = 0;
+uint8_t CK_AU = 0, CK_BU = 0;
+int gpsStep = 0;
+uint8_t UBX_id = 0;
+uint8_t UBX_class = 0;
+uint8_t meslenL = 0;
+uint8_t meslenH = 0;
+int16_t meslen = 0;
+int count = 0;
+boolean gotUBX = false;
+void setup() {
+Serial.begin(57600);
+mySerial.begin(9600);
+}
+void ubx_checksum(byte ubx_data)
+{
+  CK_A+=ubx_data;
+  CK_B+=CK_A;
+}
+void getUBX(void)
+{
+  if (Serial.available())
+  {
+    uint8_t c = Serial.read();
+    switch (gpsStep)
+    {
+      case 0:
+      {
+        if (c == 0xB5)
+          gpsStep++;
+        break;
+      }
+      case 1:
+      {
+        if (c == 0x62)
+          gpsStep++;
+        else
+          gpsStep = 0;
+        break;
+      }
+      case 2:
+      {
+        UBX_class = c;
+        ubx_checksum(c);
+        gpsStep++;
+        break;
+      }
+      case 3:
+      {
+        UBX_id = c;
+        ubx_checksum(c);
+        gpsStep++;
+        break;
+      }
+      case 4:
+      {
+        meslenL = c;
+        ubx_checksum(c);
+        gpsStep++;
+        break;
+      }
+      case 5:
+      {
+        meslenH = c;
+        ubx_checksum(c);
+        gpsStep++;
+        meslen = 0xFF & meslenL;
+        meslen |= meslenH << 8;
+        count = 0;
+        break;
+      }
+      case 6:
+      {
+        message[count] = c;
+        ubx_checksum(c);
+        count++;
+        if (count == meslen)
+        {
+          gpsStep++;
+          count = 0;
+        }
+        break;
+      }
+      case 7:
+      {
+        CK_AU = c;
+        gpsStep++;
+        break;
+      }
+   case 8:
+      {
+         CK_BU = c;
+        if (CK_A == CK_AU && CK_B == CK_BU)
+        {
+           mySerial.print("Ypa!");
+          gotUBX = true;
+          }
+        clearVars();
+        break;
+      }
+      }
+    }
+  }

+void clearVars(void)
+{
+  gpsStep = 0;
+  UBX_id = 0;
+  UBX_class = 0;
+  meslen = 0;
+  count = 0;
+  CK_AU = 0;
+  CK_BU = 0;
+  CK_A = 0;
+  CK_B = 0;
+  memset(message, 0, 60);
+}
+
+void loop()
+{
+   getUBX();
+  if (gotUBX == true)
+  {
+ mySerial.print("Ypa!");
+    gotUBX = false;
+  }
+}