Rewrite for photoresistors

Rewrite for photoresistors

Also did some reorganization.  I haven't actually filled in the logic to
decide which gears are where at the end of calibration yet.

--- crypt-gears/gear_arduino/gear_arduino.ino
+++ crypt-gears/gear_arduino/gear_arduino.ino
@@ -1,12 +1,7 @@
-// hard-coded pin numbers for input/output
-// TODO(benkraft): I am assuming for the sake of argument that these start at
-// the top and go clockwise; fix once we know the correct positions.
-int gear_connections[3][12] = {{ 2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13},
-                               {14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25},
-                               {26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37}};
-
+// PIN NUMBERS
 int output_lights[7] = {38, 39, 40, 41, 42, 43, 44};

+// TODO(benkraft): Do we still need these?
 int gear_lodged[3] = {45, 46, 47};

 int pot = A0;
@@ -16,14 +11,44 @@
 // TODO(bhomberg): calculate these numbers for real once mechanism is built; this is approx
 int pot_locs[8] = {100, 200, 300, 400, 500, 600, 700, 800};

+
+// STATE OF THE WORLD
+
+// 0: we have not started to calibrate.
+// 1: we are calibrating.
+// 2: we are unlocking.
+// 3: we have won.
+int state = 0;
+
+// The last known state of the selector.
+// NOTE: selector_pos starts at 0 when we begin to calibrate, goes up to 6 when
+// we finish calibration and start checking positions, and then back to 0 when
+// we perhaps win.
+// TODO(benkraft): Confirm this is correct.
+int last_selector_pos = 0;
+
+// photoresistor_history[i][j] is the state of the photoresistor i when we were
+// at selector position j.  Only meaningful in state 1, and then only for
+// 0 <= j < the current selector gear position.  When we transition to state 2
+// we use this to populate gear_types and gear_orientations.
+boolean photoresistor_history[3][7];
+
+// The state of the ith gear, if we know it.  Only meaningful in state 2; set
+// from photoresistor_history when we transition there.
+// Type is 0, 1, 2, in order of the correct solution.
+// Orientation is 0 in the correct solution, 1 if we are one step clockwise
+// from it, and so on.
+int gear_types[3];
+int gear_orientations[3];
+
 // State of the output lights (should match output_lights).
-// Reset when you move any gears.  This is the only state we need;
-// everything about the positions of gears we determine at need.
-// When each of these are set to 1, you win!
-boolean correct_positions[7] = {
-  false, false, false, false, false, false, false};
-
-int have_won = false;
+// Only meaningful if we are in state 2.  If while in state 2,
+// these are all true, we move to state 3 and win.
+// Note they get filled in in reverse order (see note by selector pos).
+boolean correct_positions[7];
+
+
+// CONSTANTS DEFINING THE PUZZLE

 // Structure of the gears, represented as pairs that are connected.
 // Orientation is as described in getOrientationAndTypeForGear.
@@ -41,6 +66,9 @@
   {1, 5}, {1, 9}, {5, 9},
   {2, 6}, {2, 10}, {6, 10}};

+
+// MAIN TOPLEVEL STUFF
+
 // this runs once when the program starts
 void setup()
 {
@@ -73,68 +101,127 @@
 // this is run continuously after setup has completed
 void loop()
 {
+  int selector_pos = getSelectorGearPosition();
+  if (selector_pos == -1)
+  {
+    sendCastleErrorMessage();
+    return;
+  }
+
+  // LE GRAND STATE MACHINE
+  // NOTE: with some exceptions the state machine falls through: if we advance
+  // position we immediately do what we would have done there.
+  if (state == 0)
+  {
+    // TODO(benkraft): Should we only be starting here when the red button is
+    // pressed?
+    if (selector_pos == 0)
+    {
+      // We have started calibrating!
+      state = 1;
+    }
+  }
+
+  if (state == 1)
+  {
+    if (selector_pos < last_selector_pos
+        || selector_pos > last_selector_pos + 1)
+    {
+      // They have gone backwards or too fast.
+      // TODO(benkraft): We may wish to debounce here, or say it's ok for them
+      // to go back and forth as long as they get there eventually (and we only
+      // consider the position they last got to in order).
+      state = 0;
+      resetLights();
+    }
+    else if (selector_pos == last_selector_pos + 1)
+    {
+      // Fill in new photoresistor states.
+      // TODO(benkraft): We almost certainly want to wait until we're closer to
+      // the middle of this state to check; probably this will be solved at the
+      // same time as debouncing.
+      for (int i=0; i<3; i++)
+      {
+        photoresistor_history[i][selector_pos] = getPhotoresistor(i);
+      }
+
+      // If we are at the end, move on to state 2.
+      if (selector_pos == 6)
+      {
+        state = 2;
+        // This fills in gear_types and gear_orientations.
+        if (!computeGearPositions())
+        {
+          // Or should we say you failed calibration?
+          sendCastleErrorMessage();
+          state = 0;
+          resetLights();
+        }
+
+        for (int i=0; i<7; i++)
+        {
+          correct_positions[i] = false;
+        }
+      }
+    }
+  }
+
+  if (state == 2)
+  {
+    if (selector_pos > last_selector_pos
+        || selector_pos < last_selector_pos - 1)
+    {
+      // They have gone backwards or too fast.
+      // TODO(benkraft): As above, we may wish to debounce.
+      state = 0;
+      resetLights();
+    }
+    else if (selector_pos == last_selector_pos - 1)
+    {
+      // Fill in new connection states.
+      correct_positions[selector_pos] = haveConnection(selector_pos);
+      if (correct_positions[selector_pos])
+      {
+        showCorrect(selector_pos);
+      }
+
+      if (selector_pos == 0)
+      {
+        // If we are back to the beginning, and have won, yay!
+        boolean winning = true;
+        for (int i=0; i<7; i++)
+        {
+          if (!correct_positions[i])
+          {
+            winning = false;
+            break;
+          }
+        }
+
+        if (winning)
+        {
+          state = 3;
+          sendCastleSuccessMessage();
+        }
+      }
+    }
+  }
+
+  // TODO(benkraft): How do we exit state 3?  When the button is pressed?
+
+  last_selector_pos = selector_pos;
   delay(50);
-  // print out position of the pot
-  Serial.print(getSelectorGearPosition());
-  Serial.print("  ");
-  Serial.println(getConnection(gear_connections[0][0], gear_connections[0][1]));
-
-  // First, get the state of the world.
-  int gear_types[3];
-  int gear_orientations[3];
-  boolean should_reset = false;
-  for (int i=0; i<3; i++)
-  {
-    getOrientationAndTypeForGear(i, &gear_types[i], &gear_orientations[i]);
-    showLodged(i, should_reset);
-    if (gear_types[i] = -1)
-    {
-      should_reset = true;
-    }
-  }
-
-  // If not all gears are lodged, reset -- which may be a no-op -- and exit.
-  if (should_reset)
-  {
-    reset();
-    return;
-  } else if (have_won) {
-    // If we are not resetting, and we have already won, no need to do more
-    // work; just wait for the reset.
-    return;
-  }
-
-  int selector_pos = getSelectorGearPosition();
-  correct_positions[selector_pos] = haveConnection(
-    selector_pos, gear_types, gear_orientations);
-
-  // check if we won
-  int winning = true;
-  for (int i=0; i<7; i++)
-  {
-    if (!correct_positions[i])
-    {
-      winning = false;
-    }
-  }
-
-  if (winning)
-  {
-    have_won = true;
-    sendCastleSuccessMessage();
-  }
-}
-
-// True if white gear is in front of photo resistor.  False if black paper.
-boolean getPhotoresistor(int i)
-{
-  // sees white gear
-  if(analogRead(photoresistors[i]) > 850)
-  {
-    return true;
-  }
-  // sees black paper
-  return false;
+}
+
+
+// LOGIC FOR GEAR STUFF
+
+// Takes in photoresistor_history, which must be filled in entirely, and sets
+// gear_orientations and gear_types.
+// Returns true for success, false if there was an issue.
+boolean computeGearPositions()
+{
+  // TODO(benkraft)
 }

 // True if positions pos1 and pos2 are connected on gear_num.
@@ -187,8 +274,7 @@
 // Check if we have a connection.  rotation is the amount we have rotated,
 // relative to 0 being the start position.  (That is, the position of the
 // selector gear.)  Call only if all gears are lodged.
-boolean haveConnection(int rotation, int gear_types[],
-                       int gear_orientations[])
+boolean haveConnection(int rotation)
 {
   // TODO(benkraft): Make sure these match the actual directions of rotation in
   // the final mechanism.
@@ -234,6 +320,40 @@
   return false;
 }

+
+// COMMUNICATION
+
+// turn on light / open solenoid for selector connection #n
+void showCorrect(int n)
+{
+  // turn on light
+  digitalWrite(output_lights[n], HIGH);
+
+  // TODO(bhomberg): open solenoid??
+}
+
+// turn on light for gear #n lodged, or not
+void showLodged(int n, boolean isLodged)
+{
+  digitalWrite(gear_lodged[n], isLodged ? HIGH : LOW);
+}
+
+// Reset all the lights.  (Caller should reset internal state.)
+void resetLights()
+{
+  // turn off all lights
+  for(int i=0; i<7; i++)
+  {
+    digitalWrite(output_lights[i], LOW);
+  }
+  for(int i=0; i<3; i++)
+  {
+    digitalWrite(gear_lodged[i], LOW);
+  }
+
+  // TODO(bhomberg): close all solenoids (??)
+}
+
 void sendCastleSuccessMessage()
 {
   // 20's -- 2nd puzzle message
@@ -244,67 +364,37 @@
 void sendCastleErrorMessage()
 {
   // TODO(benkraft): May or may not need to wait a tick to be sure here.
+  // TODO(benkraft): May want to log debugging info here.
   Serial.println(21);
 }

-// Return the type and orientation of the gear in the nth position, or -1 for
-// both if no gear is lodged.
-// Type is 0, 1, 2, in order of the correct solution.
-// Orientation is 0 in the correct solution, 1 if we are one step clockwise
-// from it, and so on.
-void getOrientationAndTypeForGear(int gear_num, int* type, int* orientation)
-{
-  *type = -1;
-  *orientation = -1;
-  for (int i=0; i<12; i++) {
-    if (getGearConnection(gear_num, i, (i + 3) % 12))
-    {
-      *type = 0;
-      *orientation = (4 + i) % 12;  // actually equivalent mod 3
-      return;
-    }
-    else if (getGearConnection(gear_num, i, (i + 6) % 12))
-    {
-      *type = 1;
-      *orientation = i % 6;  // actually equivalent mod 3
-      return;
-    }
-    else if (getGearConnection(gear_num, i, (i + 2) % 12))
-    {
-      *type = 2;
-      *orientation = (4 + i) % 12;  // actually equivalent mod 4
-      return;
-    }
-  }
-}
-
-boolean getGearConnection(int gear_num, int slot1, int slot2)
-{
-  return getConnection(gear_connections[gear_num][slot1],
-                       gear_connections[gear_num][slot2]);
-}
-
-// all pins are tied to ground with a 12kOhm resistor
-// we drive one of the pins high (changing its impedance mode) and read the other pin
-// if high, we're connected, if low, not connected
-// pins on separate gears will never be connected
-// returns true if the pins are connected
-// side effects: briefly turns pin1 high, but returns it to input mode after
-boolean getConnection(int pin1, int pin2)
-{
-  pinMode(pin1, OUTPUT);
-  digitalWrite(pin1, HIGH);
-
-  boolean rtrn = false;
-  if (digitalRead(pin2)) {
-    rtrn = true;
-  }
-  delay(2000);
-
-  digitalWrite(pin1, LOW);
-  pinMode(pin1, INPUT);
-
-  return rtrn;
+void printState()
+{
+  // TODO(benkraft): internal state too?
+  // print out position of the pot
+  Serial.print(getSelectorGearPosition());
+  // print out the three photoresistors.
+  for (int i=0; i<3; i++)
+  {
+    Serial.print(" ");
+    Serial.print(getPhotoresistor(i));
+  }
+  Serial.println("");
+}
+
+
+// INPUT READING
+
+// True if white gear is in front of photo resistor.  False if black paper.
+boolean getPhotoresistor(int i)
+{
+  // sees white gear
+  if(analogRead(photoresistors[i]) > 850)
+  {
+    return true;
+  }
+  // sees black paper
+  return false;
 }

 // based on the pot value, we know which of the 7 positions the selector gear is in
@@ -325,44 +415,5 @@

   // else: val is below pot_locs[0] or greater than pot_locs[7]
   // puzzle is borken
-  sendCastleErrorMessage();
   return -1;
 }
-
-// turn on light / open solenoid for selector connection #n
-void showCorrect(int n)
-{
-  // turn on light
-  digitalWrite(output_lights[n], HIGH);
-
-  // TODO(bhomberg): open solenoid??
-}
-
-// turn on light for gear #n lodged, or not
-void showLodged(int n, boolean isLodged)
-{
-  digitalWrite(gear_lodged[n], isLodged ? HIGH : LOW);
-}
-
-// gears have been taken out / selector gear goes back to beginning, reset everything
-void reset()
-{
-  // turn off all lights
-  for(int i=0; i<7; i++)
-  {
-    digitalWrite(output_lights[i], LOW);
-  }
-  for(int i=0; i<3; i++)
-  {
-    digitalWrite(gear_lodged[i], LOW);
-  }
-
-  // reset internal state: you have to start over.
-  have_won = false;
-  for(int i=0; i<7; i++)
-  {
-    correct_positions[i] = 0;
-  }
-
-  // TODO(bhomberg): close all solenoids (??)
-}


Updated LED example

Updated LED example

--- examples/Widgets/LED/LED.ino
+++ examples/Widgets/LED/LED.ino
@@ -16,7 +16,8 @@
  * Blynk using a LED widget on your phone!
  *
  * App dashboard setup:
- *   LED widget on V5
+ *   LED widget on V1
+ *   LED widget on V2
  *
  **************************************************************/

@@ -30,7 +31,8 @@
 // Go to the Project Settings (nut icon).
 char auth[] = "YourAuthToken";

-WidgetLED led(5);
+WidgetLED led1(1);
+WidgetLED led2(2);

 SimpleTimer timer;

@@ -40,16 +42,30 @@
   Blynk.begin(auth);

   timer.setInterval(1000, blinkLedWidget);
+  timer.setInterval(200, fadeLedWidget);
 }

 void blinkLedWidget()
 {
-  if (led.getValue()) {
-    led.off();
-    BLYNK_LOG("LED off");
+  if (led1.getValue()) {
+    led1.off();
+    BLYNK_LOG("LED1: off");
   } else {
-    led.on();
-    BLYNK_LOG("LED on");
+    led1.on();
+    BLYNK_LOG("LED1: on");
+  }
+}
+
+void fadeLedWidget()
+{
+  static int value = 0;
+  static int delta = 20;
+  value += delta;
+  if (value > 255 || value < 0) {
+    delta = -delta;
+  } else {
+    BLYNK_LOG("LED2: %d", value);
+    led2.setValue(value);
   }
 }


Removed: LightControl example

Removed: LightControl example

--- examples/ESP8266/LightControl/LightControl.ino
+++ examples/ESP8266/LightControl/LightControl.ino
@@ -1,67 +0,0 @@
-#include <Meeo.h>
-
-#define CONTROLLABLE_COMPONENT D8
-
-String nameSpace = "my_namespace";
-String accessKey = "my_access_key";
-String ssid = "MyWiFi";
-String pass = "qwerty123";
-String channel = "my-channel";
-
-void setup() {
-  Serial.begin(115200);
-
-  Meeo.setEventHandler(meeoEventHandler);
-  Meeo.setDataReceivedHandler(meeoDataHandler);
-  Meeo.begin(nameSpace, accessKey, ssid, pass);
-
-  pinMode(CONTROLLABLE_COMPONENT, OUTPUT);
-  digitalWrite(CONTROLLABLE_COMPONENT, LOW);
-}
-
-void loop() {
-  Meeo.run();
-}
-
-void meeoDataHandler(String topic, String payload) {
-  Serial.print(topic);
-  Serial.print(": ");
-  Serial.println(payload);
-
-  if (Meeo.isChannelMatched(topic, channel)) {
-    if (payload.toInt() == 1) {
-      digitalWrite(CONTROLLABLE_COMPONENT, HIGH);
-    } else {
-      digitalWrite(CONTROLLABLE_COMPONENT, LOW);
-    }
-  }
-}
-
-void meeoEventHandler(MeeoEventType event) {
-  switch (event) {
-    case WIFI_DISCONNECTED:
-      Serial.println("Not Connected to WiFi");
-      break;
-    case WIFI_CONNECTING:
-      Serial.println("Connecting to WiFi");
-      break;
-    case WIFI_CONNECTED:
-      Serial.println("Connected to WiFi");
-      break;
-    case MQ_DISCONNECTED:
-      Serial.println("Not Connected to MQTT Server");
-      break;
-    case MQ_CONNECTED:
-      Serial.println("Connected to MQTT Server");
-      Meeo.subscribe(channel);
-      break;
-    case MQ_BAD_CREDENTIALS:
-      Serial.println("Bad Credentials");
-      break;
-    case AP_MODE:
-      Serial.println("AP Mode");
-      break;
-    default:
-      break;
-  }
-}


first commit of aJson test. Not yet working.

--- firmware/PCB_V02/PCB_V02.ino
+++ firmware/PCB_V02/PCB_V02.ino
@@ -1,3 +1,5 @@
+#include <aJSON.h>
+
  /*
 -------------------------------------------------
 | Zachary Nelson
@@ -66,6 +68,8 @@
 int motorPulse = 1;
 volatile int motorState = LOW;
 boolean motorCommand = false;
+
+aJsonStream serial_stream(&Serial);

 void setup() {
   //set pins to output so you can control the shift register
@@ -171,6 +175,16 @@
     inputString = "";
     stringComplete = false;
   }
+
+  if (serial_stream.available()) {
+    serial_stream.skip();
+  }
+
+  if (serial_stream.available()) {
+    aJsonObject *msg = aJson.parse(&serial_stream);
+
+    aJson.deleteItem(msg);
+  }
 }

 void sendDigit(int i){


updated data-record.ino

updated data-record.ino

added the spi configuration variable back in

--- v2/data-record/firmware/data-record.ino
+++ v2/data-record/firmware/data-record.ino
@@ -3,6 +3,8 @@

 #include "math.h"
 #include "SdFat.h"
+
+#define SPI_CONFIGURATION 0

 // uncomment for offline use:
 SYSTEM_MODE(SEMI_AUTOMATIC);


Delete comm.ino

Delete comm.ino

--- app/inTheDuck/comm.ino
+++ app/inTheDuck/comm.ino
@@ -1,20 +0,0 @@
-void comBegin(int speed){
-  if(isBT){
-    //passkey is 1234
-    BT.begin(speed);
-  }
-  else{
-    Serial.begin(speed);
-  }
-}
-
-void mySend(String s){
-  //add device ID
-  s=idString+s;
-  if(isBT){
-    BT.println(s);
-  }
-  else{
-    Serial.println(s);
-  }
-}


Update rx5808-pro-diversityGc9n.ino

Update rx5808-pro-diversityGc9n.ino

--- rx5808-pro-diversityGc9n/rx5808-pro-diversityGc9n.ino
+++ rx5808-pro-diversityGc9n/rx5808-pro-diversityGc9n.ino
@@ -715,7 +715,7 @@
                 {
                   //NoFav
                       if (EEPROM.read(EEPROM_ADR_TUNE_FAV[i])!=255)
-                      {  FirstFav=i;
+                      {  FirstFav=i+1;
                         HaveFav=true;
                         }
                 }


Added 'flash' to all actions

Added 'flash' to all actions

--- DigitalVFO.ino
+++ DigitalVFO.ino
@@ -785,17 +785,20 @@
 // Define the menus to be used, plus handler code
 //-----

-const char *menu_items[2] = {"Save", "Restore"};
+const char *menu_items[] = {"Save slot", "Restore slot", "Delete slot"};
 #define NumMainMenuItems (sizeof(menu_items)/sizeof(const char *))

 Menu main_menu = {"Menu", menu_display, menu_select,
                   NumMainMenuItems, menu_items};

-Menu save_menu = {"Save", save_restore_display, save_select,
+Menu save_menu = {menu_items[0], savresdel_display, save_select,
                   NumSaveSlots, NULL};

-Menu restore_menu = {"Restore", save_restore_display, restore_select,
+Menu restore_menu = {menu_items[1], savresdel_display, restore_select,
                      NumSaveSlots, NULL};
+
+Menu delete_menu = {menu_items[2], savresdel_display, delete_select,
+                    NumSaveSlots, NULL};

 void menu_display(Menu *menu, int slot_num)
@@ -837,21 +840,35 @@
   Serial.print("menu_select: slot_num="); Serial.println(slot_num);
   const char *action_text = menu->items[slot_num];

-  if (strcmp(action_text, "Save") == 0)
+  Serial.print("action_text="); Serial.println(action_text);
+
+  if (strcmp(action_text, menu->items[0]) == 0)
   {
       show_menu(&save_menu);
   }
-  else if (strcmp(action_text, "Restore") == 0)
+  else if (strcmp(action_text, menu->items[1]) == 0)
   {
       show_menu(&restore_menu);
   }
+  else if (strcmp(action_text, menu->items[2]) == 0)
+  {
+      show_menu(&delete_menu);
+  }
+  else
+  {
+    char msg[32+1];
+
+    strcpy(msg, "Unknown: ");
+    strcpy(msg+strlen("Unknown: "), action_text);
+    abort(msg);
+  }
 }

 // draw the Save or Restore screen
-void save_restore_display(Menu *menu, int slot_num)
-{
-  Serial.print("save_restore_display: menu="); Serial.println(menu->title);
-  Serial.print("save_restore_display: slot_num="); Serial.println(slot_num);
+void savresdel_display(Menu *menu, int slot_num)
+{
+  Serial.print("savresdel_display: menu="); Serial.println(menu->title);
+  Serial.print("savresdel_display: slot_num="); Serial.println(slot_num);

   // max length of item strings is "0: xxxxxxxxHz"
   const int max_len = 13;
@@ -865,8 +882,8 @@

   ltochbuff(buf, MAX_FREQ_CHARS, freq);
   buf[MAX_FREQ_CHARS] = 0;
-  Serial.print("save_restore_display: freq="); Serial.println(freq);
-  Serial.print("save_restore_display: buf="); Serial.write(buf, MAX_FREQ_CHARS);
+  Serial.print("savresdel_display: freq="); Serial.println(freq);
+  Serial.print("savresdel_display: buf="); Serial.write(buf, MAX_FREQ_CHARS);
   Serial.println("");

   // write menu title on first row
@@ -890,29 +907,48 @@
   lcd.write("Hz");
 }

-// clear display and delay a little
+// show that *something* happened
 void action_flash(void)
 {
-  lcd.clear();
-  delay(200);
+  lcd.noDisplay();
+  delay(100);
+  lcd.display();
+  delay(100);
+  lcd.noDisplay();
+  delay(100);
+  lcd.display();
 }

 void save_select(Menu *menu, int slot_num)
 {
   put_slot(slot_num, VfoFrequency, VfoSelectDigit);

-  // display an 'action flash'
+  // display an 'action flash' and then do it
   action_flash();
-  save_restore_display(menu, slot_num);
+  savresdel_display(menu, slot_num);
 }

 void restore_select(Menu *menu, int slot_num)
 {
   Serial.print("restore_select: slot_num="); Serial.println(slot_num);

+  // display an 'action flash' and then do it
+  action_flash();
   get_slot(slot_num, VfoFrequency, VfoSelectDigit);

   Serial.print("restore_select: restoring frequency "); Serial.print(VfoFrequency);
+  Serial.print(" and offset "); Serial.print(VfoSelectDigit);
+  Serial.print(" from slot "); Serial.println(slot_num);
+}
+void delete_select(Menu *menu, int slot_num)
+{
+  Serial.print("delete_select: slot_num="); Serial.println(slot_num);
+
+  // display an 'action flash' and then do it
+  action_flash();
+  put_slot(slot_num, 0L, 0);
+
+  Serial.print("delete_select: deleting frequency "); Serial.print(VfoFrequency);
   Serial.print(" and offset "); Serial.print(VfoSelectDigit);
   Serial.print(" from slot "); Serial.println(slot_num);
 }


Auto baud rate detection 1200-19200, removed baud config menu, setup() and loop() instead of main, removed ATDL redial.

--- MicroView/WiFiModem-Menu/WiFiModem-Menu.ino
+++ MicroView/WiFiModem-Menu/WiFiModem-Menu.ino
@@ -89,17 +89,60 @@
 // ----------------------------------------------------------
 // Arduino Setup Function

-int main(void) {
-    init();
-    {
+void setup()
+{
         uView.begin(); // begin of MicroView
         uView.setFontType(0);
         uView.clear(ALL); // erase hardware memory inside the OLED controller

+    BAUD_RATE = (EEPROM.read(ADDR_BAUD_LO) * 256 + EEPROM.read(ADDR_BAUD_HI));
+    if (BAUD_RATE != 1200 && BAUD_RATE != 2400 && BAUD_RATE != 4800 && BAUD_RATE != 9600 && BAUD_RATE != 19200)
+        BAUD_RATE = 2400;
+
+    //
+    // Baud rate detection
+    //
+    pinMode (C64_RxD, INPUT);
+    digitalWrite (C64_RxD, HIGH);
+
+    Display("Baud\ndetection");
+
+    long detectedBaudRate = detRate(C64_RxD);  // Function finds a standard baudrate of either
+    // 1200,2400,4800,9600,14400,19200,28800,38400,57600,115200
+    // by having sending circuit send "U" characters.
+    // Returns 0 if none or under 1200 baud
+
+    char temp[20];
+    sprintf(temp, "Baud\ndetected:\n%ld", detectedBaudRate);
+    Display(temp);
+
+    delay(3000);
+
+    if (detectedBaudRate == 1200 || detectedBaudRate == 2400 || detectedBaudRate == 4800 || detectedBaudRate == 9600 || detectedBaudRate == 19200) {
+        BAUD_RATE = detectedBaudRate;
+
+        byte a = BAUD_RATE / 256;
+        byte b = BAUD_RATE % 256;
+
+        // Let's not waste writes..
+        if (EEPROM.read(ADDR_BAUD_LO) != a)
+            EEPROM.write(ADDR_BAUD_LO, a);
+        if (EEPROM.read(ADDR_BAUD_HI) != b)
+            EEPROM.write(ADDR_BAUD_HI, b);
+    }
+
+    //setBaud(BAUD_RATE, false, true);
+
+    //
+    // Baud rate detection end
+    //
+
         C64Serial.begin(BAUD_RATE);
         WifiSerial.begin(WiFly_BAUD_RATE);

         C64Serial.setTimeout(1000);
+
+        baudMismatch = (BAUD_RATE != WiFly_BAUD_RATE ? 1 : 0);

         // Always setup pins for flow control
         pinModeFast(C64_RTS, INPUT);
@@ -112,15 +155,17 @@
         digitalWriteFast(WIFI_CTS, LOW);
         digitalWriteFast(C64_CTS, HIGH);  // C64 is inverted

-        WifiSerial.begin(WiFly_BAUD_RATE);
-
+        //WifiSerial.begin(WiFly_BAUD_RATE);
+
+  /*
         BAUD_RATE = (EEPROM.read(ADDR_BAUD_LO) * 256 + EEPROM.read(ADDR_BAUD_HI));
         if (BAUD_RATE != 1200 && BAUD_RATE != 2400 && BAUD_RATE != 9600 && BAUD_RATE != 38400)
             BAUD_RATE = 2400;
-
-        C64Serial.begin(BAUD_RATE);
-
-        delay(1000);
+  */
+
+        //C64Serial.begin(BAUD_RATE);
+
+        //delay(1000);
         DisplayBoth(F("Wi-Fi Init..."));

         boolean ok = wifly.begin(&WifiSerial, &C64Serial);
@@ -161,7 +206,11 @@
         C64Println(F("Commodore Wi-Fi Modem"));
 #endif // HAYES
         ShowInfo(true);
-    }
+
+}
+
+void loop()
+{
     while (1)
     {
         Display(F("READY."));
@@ -237,9 +286,9 @@
         C64Println(F("1. Display Current Configuration"));
         C64Println(F("2. Change SSID"));
         C64Println(F("3. Autostart Options"));
-        C64Println(F("4. Change baud rate"));
-        C64Println(F("5. Direct Terminal Mode (Debug)"));
-        C64Println(F("6. Return to Main Menu"));
+        //C64Println(F("4. Change baud rate"));
+        C64Println(F("4. Direct Terminal Mode (Debug)"));
+        C64Println(F("5. Return to Main Menu"));
         C64Println();
         C64Print(F("Select: "));

@@ -257,13 +306,13 @@
         case '3': ConfigureAutoStart();
             break;

-        case '4': ConfigureBaud();
-            break;
-
-        case '5': RawTerminalMode();
+/*      case '4': ConfigureBaud();
+            break;*/
+
+        case '4': RawTerminalMode();
             return;

-        case '6': return;
+        case '5': return;

         case 8:
             SetPETSCIIMode(false);
@@ -482,7 +531,8 @@
 void SetPETSCIIMode(boolean mode)
 {
     petscii_mode = mode;
-    EEPROM.write(ADDR_PETSCII, petscii_mode);
+    if (EEPROM.read(ADDR_PETSCII) != petscii_mode)
+        EEPROM.write(ADDR_PETSCII, petscii_mode);
 }

 // ----------------------------------------------------------
@@ -765,13 +815,12 @@
             for(int i=0; i<buffer_index; i++) {
                 // Always do flow control if baudMismatch
                 // Check that C64 is ready to receive
-                while (digitalReadFast(C64_RTS) == LOW);   // If not...  C64 RTS and CTS are inverted.
+            //while (digitalReadFast(C64_RTS) == LOW);   // If not...  C64 RTS and CTS are inverted.
                 C64Serial.write(buffer[i]);

-                while (wifly.available() > 0)
+            while (C64Serial.available() > 0)
                 {
-                    DoFlowControl();
-                    C64Serial.write(wifly.read());
+            wifly.write(C64Serial.read());
                 }
             }

@@ -1065,7 +1114,8 @@
             continue;
         }

-        EEPROM.write(ADDR_AUTOSTART, autostart_mode);  // Save
+        if (EEPROM.read(ADDR_AUTOSTART) != autostart_mode)
+            EEPROM.write(ADDR_AUTOSTART, autostart_mode);  // Save
         C64Println(F("Saved"));
     }
 }
@@ -1094,7 +1144,8 @@
 //            break;

         default: // Invalid - on first startup or if corrupted.  Clear silently and continue to menu.
-            EEPROM.write(ADDR_AUTOSTART, AUTO_NONE);
+        if (EEPROM.read(ADDR_AUTOSTART) != AUTO_NONE)
+            EEPROM.write(ADDR_AUTOSTART, AUTO_NONE);  // Save
             autostart_mode = AUTO_NONE;
             return;
     }
@@ -1327,16 +1378,9 @@
     }
     else if (strcmp(Modem_CommandBuffer, ("AT&F")) == 0)
     {
-        if (strcmp(Modem_LastCommandBuffer, ("AT&F")) == 0)
-        {
             Modem_LoadDefaults();
             Modem_PrintOK();
         }
-        else
-        {
-            C64Println(F("Send command again to verify"));
-        }
-    }
     else if (strcmp(Modem_CommandBuffer, ("ATA")) == 0)
     {
         Modem_Answer();
@@ -1420,12 +1464,6 @@
             Modem_flowControl = true;
         }

-        if (strstr(Modem_CommandBuffer, ("DL")) != NULL)
-        {
-            Modem_Dialout("",1);
-            Modem_ResetCommandBuffer();  // This avoids port# string fragments on subsequent calls
-        }
-
         char *currentS;
         char temp[100];

@@ -1552,8 +1590,8 @@
             if (Modem_EchoOn)
             {
                 if (!Modem_flowControl)
-                    delay(100/(BAUD_RATE/2400));         // Slow down command mode to prevent garbage if flow control
-                                                         // is disabled.  Doesn't work at 9600.  TODO:  Fix
+                delay(100 / (BAUD_RATE / 2400));     // Slow down command mode to prevent garbage if flow control
+                // is disabled.  Doesn't work at 9600 but flow control should be on at 9600 baud anyways.  TODO:  Fix
                 C64Serial.write(inbound);
             }

@@ -1646,18 +1684,6 @@
     uint16_t port = 23;
     String hostname;

-    if (redial) {
-        if (lastHost.length() > 0)
-        {
-            hostname = lastHost;
-            port = lastPort;
-        }
-        else {
-            Modem_PrintERROR();
-            return;
-        }
-    }
-    else {
         if (strlen(host) == 0)
         {
             Modem_PrintERROR();
@@ -1670,7 +1696,6 @@
             hostname = String(host);
             port = atoi(index + 1);
         }
-    }
     /*if (hostname == F("5551212"))
     {
         QuantumLinkReloaded();
@@ -1786,6 +1811,7 @@
   }
 }*/

+/*
 void ConfigureBaud()
 {
     while (true)
@@ -1828,39 +1854,41 @@
         EEPROM.write(ADDR_AUTOSTART, autostart_mode);  // Save
         C64Println(F("Saved"));
     }
-}
-
-void setBaud(int newBaudRate, boolean pause) {
-  char temp[20];
-  BAUD_RATE = newBaudRate;
-  sprintf(temp,"New baud: %d",BAUD_RATE);
-  C64Println(temp);
-  C64Serial.flush();
-  delay(2);
-  C64Serial.end();
-  C64Serial.begin(BAUD_RATE);
-  C64Serial.setTimeout(1000);
-
-  if(BAUD_RATE == 1200)
-    setBaudWiFi(2400);
-  else
-    setBaudWiFi(BAUD_RATE);
-
-  if (pause)
-    delay(5000);  // Delay 5 seconds so user has time to switch to help prevent junk...
-
-  byte a = newBaudRate/256;
-  byte b = newBaudRate % 256;
-
-  // Let's not waste writes..
-  if (EEPROM.read(ADDR_BAUD_LO) != a)
-      EEPROM.write(ADDR_BAUD_LO, a);
-  if (EEPROM.read(ADDR_BAUD_HI) != b)
-      EEPROM.write(ADDR_BAUD_HI, b);
-}
+}*/
+
+/*
+void setBaud(int newBaudRate, boolean pause, boolean setup) {
+    char temp[20];
+    BAUD_RATE = newBaudRate;
+    if (!setup) {
+        sprintf(temp, "New baud: %d", BAUD_RATE);
+    C64Println(temp);
+    C64Serial.flush();
+    delay(2);
+    C64Serial.end();
+    }
+    C64Serial.begin(BAUD_RATE);
+    C64Serial.setTimeout(1000);
+
+    if(BAUD_RATE == 1200)
+        setBaudWiFi(2400);
+    else
+        setBaudWiFi(BAUD_RATE);
+
+    if (pause)
+        delay(5000);  // Delay 5 seconds so user has time to switch to help prevent junk...
+
+    byte a = newBaudRate/256;
+    byte b = newBaudRate % 256;
+
+    // Let's not waste writes..
+    if (EEPROM.read(ADDR_BAUD_LO) != a)
+        EEPROM.write(ADDR_BAUD_LO, a);
+    if (EEPROM.read(ADDR_BAUD_HI) != b)
+        EEPROM.write(ADDR_BAUD_HI, b);
+}*/

 void setBaudWiFi(int newBaudRate) {
-  baudMismatch = (BAUD_RATE != WiFly_BAUD_RATE ? 1 : 0);
   WiFly_BAUD_RATE = newBaudRate;
   WifiSerial.flush();
   delay(2);
@@ -1878,4 +1906,47 @@
 }

 // EOF!
-
+long detRate(int recpin)  // function to return valid received baud rate
+// Note that the serial monitor has no 600 baud option and 300 baud
+// doesn't seem to work with version 22 hardware serial library
+{
+    unsigned long timer;
+    timer = millis();
+
+    while (1)
+    {
+      if (millis() - 3000 < timer)
+          return (0);
+      if (digitalRead(recpin) == 0)
+          break;
+    }
+    //while(digitalRead(recpin) == 1 && millis()-3000 < timer){} // wait for low bit to start
+    long baud;
+    long rate = pulseIn(recpin, LOW); // measure zero bit width from character 'U'
+
+    if (rate < 12)
+        baud = 115200;
+    else if (rate < 20)
+        baud = 57600;
+    else if (rate < 29)
+        baud = 38400;
+    else if (rate < 40)
+        baud = 28800;
+    else if (rate < 60)
+        baud = 19200;
+    else if (rate < 80)
+        baud = 14400;
+    else if (rate < 150)
+        baud = 9600;
+    else if (rate < 300)
+        baud = 4800;
+    else if (rate < 600)
+        baud = 2400;
+    else if (rate < 1200)
+        baud = 1200;
+    else
+        baud = 0;
+    return baud;
+}
+
+


added rotarty encoder functions & outline milestone 1 requirements

--- SDPArduinoCode/SDPArduinoCode.ino
+++ SDPArduinoCode/SDPArduinoCode.ino
@@ -24,6 +24,15 @@
 int  lastSeqNo;
 bool done;

+// Encoder Board Variables
+#define ROTARY_SLAVE_ADDRESS 5
+#define ROTARY_COUNT 6
+#define PRINT_DELAY 200
+
+// Initial motor position is 0.
+int positions[ROTARY_COUNT] = {0};
+
+
 void setup(){

   SDPsetup();
@@ -33,7 +42,7 @@
 //  Serial.write("+++");
 //  Serial.write("ATCN20");
 //  Serial.write("ATAC");
-//  Serial.write("ATDN");
+//  Serial.write(	"ATDN");

   // 1. inital test to see if message is recieved to computer stating "hello world"
    helloWorld();
@@ -185,10 +194,62 @@
 }

-
+void robotForwardDistance(int distance){
+  // will eventually use this function, and parameter ARG from input will represent how far to move forward
+  // rather than the power to move forward.
+
+  // need encoders working first!
+}
+
+//////////////////////////////////////////////////////////////////////////////////////////////////////////
+//                              TESTING ENCODER BOARD READS                                             //
+//////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+void updateMotorPositions() {
+  // Request motor position deltas from rotary slave board
+  Wire.requestFrom(ROTARY_SLAVE_ADDRESS, ROTARY_COUNT);
+
+  // Update the recorded motor positions
+  for (int i = 0; i < ROTARY_COUNT; i++) {
+    positions[i] += (int8_t) Wire.read();  // Must cast to signed 8-bit type
+  }
+}
+
+void printMotorPositions() {
+  Serial.print("Motor positions: ");
+  for (int i = 0; i < ROTARY_COUNT; i++) {
+    Serial.print(positions[i]);
+    Serial.print(' ');
+  }
+  Serial.println();
+  delay(PRINT_DELAY);  // Delay to avoid flooding serial out
+}
+
+////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////////////////////////////////////////////////////
+//                                Milestone 1 communication functions                                     //
+////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+int getFrequency(String c){
+  int f = 100;
+
+  return f;
+}
+
+void storeFileInRegister(int freq){
+  int register_address = 69;
+
+
+}
+
+///////////////////////////////////////////////////////////////////////////////////////////////////////////

 void loop(){
+
+  updateMotorPositions();
+  printMotorPositions();

   // if message is available on our frequency accept it.
   if(Serial.available() > 0){
@@ -201,10 +262,6 @@
       return;
     }

-    // inital test to see if message is recieved (delete afterwards)
-    // Serial.println(c);
-
-
       // need to check if signuture is our teams first!
       // avoids unessacary computation on the arduino if it is not a message for out team.
       int sig = getSig(c);
@@ -213,6 +270,18 @@
       // Quits if sig belongs to other teams
       // OR if command is redundant (i.e. already executed)
       if(sig != 0 || ignore(seqNo)){ return; }
+
+      // for accepting file
+      if(sig == 3){
+
+        // get frequency from file.
+        //int frequency = getFrequency(c);
+
+        // storeStringInRegister(int frequency)
+
+
+
+      }

       int opcode = getOpcode(c);
       int arg = getArg(c);


reading data into byte array and sout it

--- reciever/reciever.ino
+++ reciever/reciever.ino
@@ -48,16 +48,17 @@
       boolean matchZero = matchZeroBit(pwm_low_length);

       setState(newState, matchOne || matchZero);
+
       if (state == newState) {
           int bitNumber = (state - 1) / 2 - 1;
-          //fillDataArray(bitNumber, matchOne);
-
-          if (bitNumber == DATA_BIT_SIZE) {
-            //for (byte i = 0; i < DATA_ARRAY_SIZE; i++) {
-            //    Serial.print(data[i]);
-            //    Serial.print(" ");
-            //}
-            Serial.println(matchOne);
+          fillDataArray(bitNumber, matchOne);
+
+          if (bitNumber == DATA_BIT_SIZE - 1) {
+            for (byte i = 0; i < DATA_ARRAY_SIZE; i++) {
+                Serial.print(data[i]);
+                Serial.print(" ");
+            }
+            Serial.println();

             setState(state, false);
           }
@@ -80,9 +81,7 @@

 void fillDataArray(byte bitNumber, boolean isOne) {
    byte dataArrayIndex = bitNumber / BITS_PER_PACKET;
-   byte value = bitNumber ? 1 : 0;
-
-   data[dataArrayIndex] = (data[dataArrayIndex] << 1) & value;
+   data[dataArrayIndex] = (data[dataArrayIndex] << 1) | isOne;
 }

 void clearDataArray(byte upTo) {
@@ -116,9 +115,16 @@
         state = st;
     } else {
         state = 0;
-        //if (st > 3) {
-        //  clearDataArray(((st - 2) / 2 - 1) / BITS_PER_PACKET);
-        //}
+        if (st > 3) {
+          clearDataArray(((st - 2) / 2 - 1) / BITS_PER_PACKET);
+        }
     }
 }

+
+
+
+
+
+
+


Added 32-bit parity calculations, cleaned up last TRN code (thanks Tjerk).

--- firmware/arduino_nano/swdtest/swdtest.ino
+++ firmware/arduino_nano/swdtest/swdtest.ino
@@ -11,7 +11,18 @@
 #define SWDDAT_PIN 2
 #define SWDCLK_PIN 3

-#define SWDDELAY_us 300
+#define SWDDELAY_us 100
+
+bool calcParity32(uint32_t x)
+{
+   unsigned y;
+   y = x ^ (x >> 1);
+   y = y ^ (y >> 2);
+   y = y ^ (y >> 4);
+   y = y ^ (y >> 8);
+   y = y ^ (y >>16);
+   return (y & 1) != 0;
+}

 // *********************************************************
 //   Perform SWD transaction
@@ -86,6 +97,8 @@
     SWDWriteBit(false);
   }
 }
+
+

 uint32_t SWDTransaction(bool APnDP, bool RnW, uint8_t A23, uint32_t data)
 {
@@ -139,20 +152,21 @@

     // turn around time
     SWDReadBit();         // trn
-
+
+    bool parity = calcParity32(data);
     for(uint8_t i=0; i<32; i++)
     {
-      if (data >= 0x80000000)
+      if ((data & 1) != 0)
         SWDWriteBit(true);
       else
         SWDWriteBit(false);
-      data <<= 1;
+      data >>= 1;
     }

-    // TODO: generate correct parity
-    SWDWriteBit(false);
-
-    SWDIdle();
+    SWDWriteBit(parity);
+
+    // turn-around
+    SWDReadBit();
   }
   else
   {
@@ -160,14 +174,15 @@
     result = 0;
     for(uint8_t i=0; i<32; i++)
     {
-      result <<= 1;
+      result >>= 1;
       if (SWDReadBit())
-        result |= 1;
+        result |= 0x80000000;
     }

     bool parity = SWDReadBit();

-    SWDIdle();
+    // turn-around
+    SWDReadBit();

     //TODO: get SWD code
     //      and check parity..
@@ -191,13 +206,14 @@
   {
     SWDWriteBit(true);
   }
-
+
+  /*
   SWDWord(0x6DB7);

   for(uint32_t i=0; i<64; i++)
   {
     SWDWriteBit(true);
-  }
+  }*/

   SWDIdle();


Opzet claw voorwaarden

Opzet claw voorwaarden

--- Claw/Claw_controller/Claw_controller.ino
+++ Claw/Claw_controller/Claw_controller.ino
@@ -1,19 +1,25 @@
-int buttonState = 1 //
-                  int servoPosition
+int buttonState = 1 ;//
+int servoPosition;
+int grabCount;
+int teller;
+int vorigeStatus;

-                  //this is nothing yet, working on it. ;)
-                  /*
-                    Een grijper die open of dicht gaat naar aanleiding van de waarde die middels een draaiknop wordt gegeven (en middels MAP functie omgevormd tot een bruikbare waarde)
-                    Als een object gegrepen is,
-                    dan luidt er een buzzer.
-                    En
-                    Het ledje gaat knipperen
-                    Als hoe kleiner de hoek is van de grijper, hoe feller het ledje gaat branden
+bool grabdingStaatStil = false;
+bool claw = false;

-                    Op de LCD wordt weergeven:
-                    de hoek van de motor(dus de grijper) = Vraagt de waarde op van de huidige grijperwaarde
-                    Hoe vaak een object is gepakt = Telt
-                    En geeft weer indien een object wordt vastgehouden.*/
+//this is nothing yet, working on it. ;)
+/*
+  Een grijper die open of dicht gaat naar aanleiding van de waarde die middels een draaiknop wordt gegeven (en middels MAP functie omgevormd tot een bruikbare waarde)
+  Als een object gegrepen is,
+  dan luidt er een buzzer.
+  En
+  Het ledje gaat knipperen
+  Als hoe kleiner de hoek is van de grijper, hoe feller het ledje gaat branden
+
+  Op de LCD wordt weergeven:
+  de hoek van de motor(dus de grijper) = Vraagt de waarde op van de huidige grijperwaarde
+  Hoe vaak een object is gepakt = Telt
+  En geeft weer indien een object wordt vastgehouden.*/

 void setup() {
   // put your setup code here, to run once:
@@ -23,6 +29,36 @@
 void loop() {
   // put your main code here, to run repeatedly:

-  analogRead (buttonState)
-  servoposition = map(buttonState, 0, 1023, 0, 180) //" map(value, fromLow, fromHigh, toLow, toHigh)
+  analogRead (buttonState);
+  servoposition = map(buttonState, 0, 1023, 0, 180); //" map(value, fromLow, fromHigh, toLow, toHigh)
+
+  if (graden = < 30 && grabdingStaatStil)
+  {
+    if (claw == false)
+    {
+      claw = true;
+      grabCount ++;
+    }
+  }
+  else
+  {
+    claw = false;
+  }
+
+
+
+
+  if (buttonState = vorigeStatus )
+  {
+    teller ++;
+  }
+
+  if (teller >= 30)
+  {
+    grabdingStaatStil = true;
+
+  }
+  vorigeStatus = buttonState;
+
+
 }


Removed MODULE_OLED definition

Removed MODULE_OLED definition

--- _36_Bricks.ino
+++ _36_Bricks.ino
@@ -5,7 +5,6 @@
 //-----------------------------------------------------------
 #define MODULE_OUTPUTS
 //#define MODULE_TELEINFO_EDF
-#define MODULE_OLED
 //#define MODULE_PHOTO
 //#define MODULE_DHT22
 //#define MODULE_NEOPIXELS


ピンモードの条件分岐を良い感じのテーブルで持つようにした.

ピンモードの条件分岐を良い感じのテーブルで持つようにした.

--- arduino/GeneralIoSerial/GeneralIoSerial.ino
+++ arduino/GeneralIoSerial/GeneralIoSerial.ino
@@ -22,6 +22,19 @@
 struct TASK_FUNC {
   String prefix;
   TASK_FUNC_PTR func;
+};
+
+// Stringとuint8_tを保持する構造体.
+struct STR_UINT8_PEAR {
+  String key;
+  uint8_t value;
+};
+
+// pinModeの名前と値を保持するテーブル.
+const struct STR_UINT8_PEAR PIN_MODE_TBL[] = {
+  {"INPUT", INPUT},
+  {"OUTPUT", OUTPUT},
+  {"INPUT_PULLUP", INPUT_PULLUP}
 };

 // prefixとタスク関数のテーブルを使ってキメる.
@@ -140,17 +153,13 @@
     return NgReturnJson("type is not specified.", valQuery);
   }

-  if(valQuery == "INPUT"){
-    pinMode(port, INPUT);
-  }else if(valQuery == "OUTPUT"){
-    pinMode(port, OUTPUT);
-  }else if(valQuery == "INPUT_PULLUP"){
-    pinMode(port, INPUT_PULLUP);
-  }else{
-    return NgReturnJson("Illegal type", valQuery);
-  }
-  return switchTypeReturnJson("OK", valQuery);
-
+  for(int i = 0; i < ARRAYSIZE(PIN_MODE_TBL); i++){
+    if(valQuery == PIN_MODE_TBL[i].key){
+      pinMode(port, PIN_MODE_TBL[i].value);
+      return switchTypeReturnJson("OK", valQuery);
+    }
+  }
+  return NgReturnJson("Illegal type", valQuery);
 }

 String checkPortWithQuery(String portWithQuery, int *port, String *query){


deleted test file

deleted test file

--- projectFiles/test.ino
+++ projectFiles/test.ino
@@ -1,108 +0,0 @@
-#include "LaserDriver.h"
-#include "math.h"
-
-void setup(){}
-
-
-void loop()
-{
-
-
-
-	LaserDriver LD;
-
-	int x = 255/2;
-	int y = 255/2;
-	int r = 50;
-
-
-	delayMicroseconds(500);
-	static float temp =0;
-	int leftPot=analogRead(A4)/8;
-	int rightPot=(analogRead(A5)/32)+2;
-	//fine = random(1, 255);
-	for (int i = 0; i<=255; i++ ) {
-		//temp = (random(0, 1024)/163.1);
-
-		//delayMicroseconds(200);
-		//static int temp=0;
-		//if (i%=5) temp = random(50,150);
-		//LD.lSet(i, temp);
-		LD.lSet( (char)(tan(temp)*(leftPot)+128)*(char)(sin(temp)*(leftPot)+128), (char)(cos(temp)*(leftPot)+128)*(char)(sin(temp)*(leftPot)+128));
-		//LD.lSet(i, (char)(tan(temp)*64.0f)+128);
-		temp+=6.28f/(rightPot);
-		//delayMicroseconds(5);
-		}
-
-	/*
-	LD.lSet(x, y-r);
-	delayMicroseconds(200);
-	LD.lSet(x-r, y-r);
-	//delayMicroseconds(100);
-	LD.lSet(x-r, y);
-	delayMicroseconds(200);
-	LD.lSet(x-r, y+r);
-	//delayMicroseconds(100);
-	LD.lSet(x, y+r);
-	delayMicroseconds(200);
-	LD.lSet(x+r, y+r);
-	//delayMicroseconds(100);
-	LD.lSet(x+r, y);
-	delayMicroseconds(200);
-	LD.lSet(x+r, y-r);
-	//delayMicroseconds(100);
-	*/
-
-
-	/*float angle = 0;
-
-	LaserDriver LD;
-
-	for(int i=255; i>0; i--){
-
-		LD.lSet( i*i*i, (pow(-1, i)));
-		delayMicroseconds(500);
-	}
-	for(int i=255; i>0; i--){
-
-		LD.lSet( i/2, (pow(-1, i)));
-		delayMicroseconds(500);
-	}
-	for(int i=0; i<255; i++){
-
-		LD.lSet( i*i*i, (i));
-		delayMicroseconds(500);
-	}
-
-	for(int i=0; i<255; i++){
-
-		LD.lSet((i),i*i*i);
-		delayMicroseconds(500);
-	}
-
-	for(int i=255; i>0; i--){
-
-		LD.lSet( i*i*i, (pow(-1, i)));
-		delayMicroseconds(500);
-	}
-	for(int i=0; i<255; i++){
-			LD.lSet( i, pow(i,2) + pow(i,2));
-			delayMicroseconds(250);
-	}
-
-	for(int i=0; i<255; i++){
-
-		LD.lSet( pow(i,2) + pow(i,2), pow(i,2) + pow(i,2));
-		delayMicroseconds(250);
-	}
-
-
-	for(int i=0; i<255; i++){
-
-		LD.lSet( i,pow(i,2));
-		delayMicroseconds(250);
-	}
-
-	*/
-
-}


FaceUphill: Go back to using the slightly different acceleration conversion factor we used in the Zumo32U4 example.

--- examples/FaceUphill/FaceUphill.ino
+++ examples/FaceUphill/FaceUphill.ino
@@ -46,7 +46,7 @@
 void loop()
 {
   // Read the acceleration from the LSM303.
-  // A value of 16393 corresponds to approximately 1 g.
+  // A value of 16384 corresponds to approximately 1 g.
   lsm6.read();
   int16_t x = lsm6.a.x;
   int16_t y = lsm6.a.y;
@@ -74,9 +74,9 @@
   forwardSpeed = constrain(forwardSpeed, -maxSpeed, maxSpeed);

   // See if we are actually on an incline.
-  // 16393 * sin(5 deg) = 1428
+  // 16384 * sin(5 deg) = 1427
   int16_t turnSpeed;
-  if (magnitudeSquared > (int32_t)1428 * 1428)
+  if (magnitudeSquared > (int32_t)1427 * 1427)
   {
     // We are on an incline of more than 5 degrees, so
     // try to face uphill using a feedback algorithm.


use byte instead of unsigned char

use byte instead of unsigned char

--- examples/QuickStart/QuickStart.ino
+++ examples/QuickStart/QuickStart.ino
@@ -43,7 +43,7 @@
   debugPrintLn("Uptime (ms): " + String(uptime));

   // Encode uptime into 4 bytes
-  unsigned char bytes[4];
+  byte bytes[4];
   longToBytes(uptime, bytes);
   debugPrintLn("Uptime (bytes in hex): " + bytesToHexString(bytes, 4));


refactoring

refactoring

--- autotop986.ino
+++ autotop986.ino
@@ -13,27 +13,35 @@
   14.4sec to close
 */

+
+// pin definitions
 #define openBtnOut     2
 #define closeBtnOut    3
 #define pBrakeOut      4
 #define openBtnIn      8
 #define closeBtnIn     9

+// cutoff point, after which a press is considered a long press
 #define shortPressInterval 250
+// loop delay
 #define loopInterval 50

+// time taken to open top
 #define openTime 15600
+// time taken to close top
 #define closeTime 16400

+// operation modes
 #define modeNull 0
 #define modeAutoOpen 1
 #define modeAutoClose 2
 #define modeManualOpen 3
 #define modeManualClose 4

+int closeBtnCount = 0;
+int openBtnCount = 0;
 int movementCount = 0;
-int openBtnCount = 0;
-int closeBtnCount = 0;
+
 int openMode = modeNull;
 bool btnReleased = false;
 bool ignoreBtn = false;
@@ -62,31 +70,43 @@
 }

 void checkButtons() {
-
-  //check buttons
   if(digitalRead(openBtnIn) == HIGH) {
-    if(btnReleased){
-      allStop();
-      ignoreBtn = true;
-    } else if(ignoreBtn == false) {
-      if(openBtnCount < 32000) {
-        openBtnCount += loopInterval;
-      }
-      closeBtnCount = 0;
-      digitalWrite(closeBtnOut, LOW);
+    handleOpenButtonPressed();
+  } else if(digitalRead(closeBtnIn) == HIGH) {
+    handleCloseButtonPressed();
+  } else {
+    handleNoButtonPressed();
+  }
+}
+
+void handleOpenButtonPressed() {
+  if(btnReleased){
+    allStop();
+    ignoreBtn = true;
+  } else if(ignoreBtn == false) {
+    if(openBtnCount < 32000) {
+      openBtnCount += loopInterval;
     }
-  } else if(digitalRead(closeBtnIn) == HIGH) {
-    if(btnReleased){
-      allStop();
-      ignoreBtn = true;
-    } else if(ignoreBtn == false) {
-      if(closeBtnCount < 32000) {
-        closeBtnCount += loopInterval;
-      }
-      openBtnCount = 0;
-      digitalWrite(openBtnOut, LOW);
+    closeBtnCount = 0;
+    digitalWrite(closeBtnOut, LOW);
+  }
+}
+
+void handleCloseButtonPressed() {
+  if(btnReleased){
+    allStop();
+    ignoreBtn = true;
+  } else if(ignoreBtn == false) {
+    if(closeBtnCount < 32000) {
+      closeBtnCount += loopInterval;
     }
-  } else if (openMode != modeAutoOpen && openMode != modeAutoClose) {
+    openBtnCount = 0;
+    digitalWrite(openBtnOut, LOW);
+  }
+}
+
+void handleNoButtonPressed() {
+  if (openMode != modeAutoOpen && openMode != modeAutoClose) {
     allStop();
     ignoreBtn = false;
   } else {
@@ -143,22 +163,30 @@

     default: //no movement currently
       if(openBtnCount > 0) {
-        openMode = modeManualOpen;
-        movementCount = openTime;
-        digitalWrite(pBrakeOut, HIGH);
-        digitalWrite(closeBtnOut, LOW);
-        digitalWrite(openBtnOut, HIGH);
+        startAutoOpen();
       } else if(closeBtnCount > 0) {
-        openMode = modeManualClose;
-        movementCount = closeTime;
-        digitalWrite(pBrakeOut, HIGH);
-        digitalWrite(openBtnOut, LOW);
-        digitalWrite(closeBtnOut, HIGH);
+        startAutoClose();
       } else {
         allStop();
       }
       break;
   }
+}
+
+void startAutoOpen() {
+  openMode = modeManualOpen;
+  movementCount = openTime;
+  digitalWrite(pBrakeOut, HIGH);
+  digitalWrite(closeBtnOut, LOW);
+  digitalWrite(openBtnOut, HIGH);
+}
+
+void startAutoClose() {
+  openMode = modeManualClose;
+  movementCount = closeTime;
+  digitalWrite(pBrakeOut, HIGH);
+  digitalWrite(openBtnOut, LOW);
+  digitalWrite(closeBtnOut, HIGH);
 }

 void allStop() {


Updated comments

Updated comments

--- avr/examples/CANBusTriple_Mazda/CANBusTriple_Mazda.ino
+++ avr/examples/CANBusTriple_Mazda/CANBusTriple_Mazda.ino
@@ -1,8 +1,8 @@
 /*
 *  CANBus Triple
 *  The Car Hacking Platform
-*  http://canb.us
-*  https://github.com/etx/CANBus-Triple
+*  https://canb.us
+*  https://github.com/CANBus-Triple
 */

 #include <avr/wdt.h>
@@ -179,7 +179,7 @@

 /*
-*  TODO, Comment on this method
+*  Main Loop
 */
 void loop() {

@@ -225,7 +225,7 @@

 /*
-*  TODO, Comment on this method
+*  Load CAN Controller buffer and set send flag
 */
 boolean sendMessage( Message msg, CANBus bus ){

@@ -263,7 +263,7 @@

 /*
-*  TODO, Comment on this method
+*  Read Can Controller Buffer
 */
 void readBus( CANBus bus ){

@@ -297,7 +297,7 @@

 /*
-*  TODO, Comment on this method
+*  Process recieved CAN message through middleware
 */
 void processMessage( Message msg ){


Remove debug spew

Remove debug spew

--- contrib/gd3load.ino
+++ contrib/gd3load.ino
@@ -221,5 +221,5 @@

 void loop()
 {
-  Serial.println(GD.rd16(REG_TOUCH_RAW_XY));
-}
+  // Serial.println(GD.rd16(REG_TOUCH_RAW_XY));
+}


better calibration functionality + some cleanup

--- firmware/src/PoolBuddy.ino
+++ firmware/src/PoolBuddy.ino
@@ -2,10 +2,11 @@
 #include "SparkFunMAX17043.h"

 PRODUCT_ID(4513);
-PRODUCT_VERSION(1);
+PRODUCT_VERSION(2);

 #define POWER D6
 #define TEMP_SENSOR D5
+#define CALIBRATION_LED D7
 #define PH_ADDRESS 99
 #define ORP_ADDRESS 98
 #define SAMPLE_INTERVAL 2500
@@ -18,7 +19,7 @@
 ApplicationWatchdog wd(180000, System.reset);

 DS18B20 ds18b20(TEMP_SENSOR);
-int nextSampleTime, nextSleepTime, sleepInterval;
+unsigned int nextSampleTime, nextSleepTime, sleepInterval;

 double temp = 0;
 double ph = 0;
@@ -26,18 +27,17 @@
 double soc = 0;
 int wifi;
 bool calibrationmode = false;
+bool temponly = false;

 void setup() {
-  //Serial.begin(9600);
-  temp = 0;
-  ph = 0;
-  orp = 0;
-  soc = 0;
   if (!Wire.isEnabled())
     Wire.begin();
+
   pinMode(POWER,OUTPUT);
   pinMode(TEMP_SENSOR, INPUT);
+  pinMode(CALIBRATION_LED, OUTPUT);
   digitalWrite(POWER, HIGH);
+  digitalWrite(CALIBRATION_LED, LOW);

   lipo.begin();
   lipo.quickStart();
@@ -46,31 +46,39 @@
   Particle.variable("pH", ph);
   Particle.variable("ORP", orp);
   Particle.variable("soc", soc);
-  Particle.variable("calibrating",calibrationmode);
-  Particle.function("switchmode",switchcalibrationmode);
-  Particle.function("calibratePh",calibrate_ph);
-  Particle.function("calibrateORP",calibrate_orp);
-  Particle.function("check",check_calibrated);
-  Particle.function("measure",measure);
-  Particle.function("slope",check_slope);
-  Particle.variable("wifi",wifi);
+  Particle.variable("calibrating", calibrationmode);
+  Particle.variable("temponly", temponly);
+  Particle.function("switchcalmode", switchcalibrationmode);
+  Particle.function("switchtemponly", switchtemponly);
+  Particle.function("calibratePH", calibrate_ph);
+  Particle.function("calibrateORP", calibrate_orp);
+  Particle.function("check", check_calibrated);
+  Particle.function("slope", check_slope);
+  Particle.variable("wifi", wifi);

   nextSleepTime = millis() + WAKE_INTERVAL;
+  //Serial.begin(9600);
 }

 void loop() {
-  if (!calibrationmode) {
-    if (millis() > nextSampleTime) {
+  // Always measure every sample time interval
+  if (millis() > nextSampleTime) {
       measure_temp();
-      compensate_temp_ph();
-      measure_ph();
-      measure_orp();
+      if(temponly == 0) {
+        compensate_temp_ph();
+        measure_ph();
+        measure_orp();
+      }
       measure_wifi();
       nextSampleTime = millis() + SAMPLE_INTERVAL;
       soc = lipo.getSOC();
-    }
-    if(millis() > nextSleepTime) {
-      Particle.publish("pooldata", water_data(), PRIVATE);
+  }
+
+  // Publish results before going to sleep
+  if(millis() > nextSleepTime) {
+    Particle.publish("pooldata", water_data(), PRIVATE);
+    // Only go to sleep when not in calibration mode
+    if (!calibrationmode) {
       if(soc <= 10)
         sleepInterval = 60 * 60;
       else if(soc <= 20)
@@ -78,26 +86,22 @@
       else
         sleepInterval = 60 * 15;
       nextSleepTime = millis() + (sleepInterval * 1000) + WAKE_INTERVAL;
-      executeRequest(PH_ADDRESS,"Sleep");
+      executeRequest(PH_ADDRESS,"Sleep");
       executeRequest(ORP_ADDRESS,"Sleep");
       digitalWrite(POWER, LOW);
-      System.sleep(SLEEP_MODE_DEEP,sleepInterval);
+      System.sleep(SLEEP_MODE_DEEP, sleepInterval);
+    } else {
+      nextSleepTime = millis() + SAMPLE_INTERVAL;
+      orp = ph = 0;
     }
   }
 }

 String water_data() {
-  return String::format("{\"temperature\":%f,\"ph\":%f,\"orp\":%f,\"soc\":%f,\"wifi\":%d}",temp,ph,orp,soc,wifi);
-}
-
-int measure(String arg) {
-  ph = 0;
-  orp = 0;
-  temp = 0;
-  measure_temp();
-  measure_ph();
-  measure_orp();
-  measure_wifi();
+  if(temponly)
+    return String::format("{\"temperature\":%f,\"soc\":%f,\"wifi\":%d}",temp,soc,wifi);
+  else
+    return String::format("{\"temperature\":%f,\"ph\":%f,\"orp\":%f,\"soc\":%f,\"wifi\":%d}",temp,ph,orp,soc,wifi);
 }

 void measure_ph() {
@@ -105,9 +109,9 @@
   //Serial.print("Ph:");
   //Particle.publish("ph_reading", pH_data, PRIVATE);
   //Serial.println(pH_data);
-  if (isdigit(pH_data[0])) {
+  if (isdigit(pH_data.charAt(0))) {
     float current = String(pH_data).toFloat();
-    if(ph == 0)
+    if((ph == 0) | calibrationmode)
       ph = current;
     else
       ph = (ph + current) / 2;
@@ -118,9 +122,9 @@
   String orp_data = executeRequest(ORP_ADDRESS,"R");
   //Serial.print("ORP:");
   //Serial.println(orp_data);
-  if (isdigit(orp_data[0])) {
+  if (isdigit(orp_data.charAt(0))) {
     float current = String(orp_data).toFloat();
-    if(orp == 0)
+    if((orp == 0) | calibrationmode)
       orp = current;
     else
       orp = (orp + current) / 2;
@@ -160,6 +164,19 @@

 int switchcalibrationmode(String arg) {
   calibrationmode = !calibrationmode;
+  if(calibrationmode) {
+    digitalWrite(CALIBRATION_LED, HIGH);
+    nextSleepTime = millis() + SAMPLE_INTERVAL;
+  } else {
+    digitalWrite(CALIBRATION_LED, LOW);
+    nextSleepTime = millis() + WAKE_INTERVAL;
+  }
+  return 0;
+}
+
+int switchtemponly(String arg) {
+  temponly = !temponly;
+  return 0;
 }

 int calibrate_ph(String arg) {
@@ -173,14 +190,14 @@
     commandString.concat("4.00");
   if(arg=="high")
     commandString.concat("10.00");
-  Serial.println(executeRequest(PH_ADDRESS,commandString));
+  Particle.publish("calibrate", executeRequest(PH_ADDRESS,commandString), PRIVATE);
   return 0;
 }

 int calibrate_orp(String arg) {
   String commandString = String("Cal,");
   commandString.concat(arg);
-  executeRequest(ORP_ADDRESS,commandString);
+  Particle.publish("calibrate", executeRequest(ORP_ADDRESS,commandString), PRIVATE);
   return 0;
 }

@@ -191,17 +208,13 @@
 }

 int check_calibrated(String args) {
-  Serial.println("Ph:");
-  Serial.println(executeRequest(PH_ADDRESS,"Cal,?"));
-  Serial.println(executeRequest(PH_ADDRESS,"Status"));
-  Serial.println("ORP:");
-  Serial.println(executeRequest(ORP_ADDRESS,"Cal,?"));
-  Serial.println(executeRequest(ORP_ADDRESS,"Status"));
+  Particle.publish("check",String::format("Ph:%s %s", executeRequest(PH_ADDRESS,"Cal,?").c_str(), executeRequest(PH_ADDRESS,"Status").c_str()), PRIVATE);
+  Particle.publish("check",String::format("ORP:%s %s", executeRequest(ORP_ADDRESS,"Cal,?").c_str(), executeRequest(ORP_ADDRESS,"Status").c_str()), PRIVATE);
   return 0;
 }

 int check_slope(String args) {
-  executeRequest(PH_ADDRESS,"Slope,?");
+  Particle.publish("check", executeRequest(PH_ADDRESS,"Slope,?"), PRIVATE);
   return 0;
 }

@@ -212,7 +225,7 @@
   Wire.beginTransmission(address);
   Wire.write(cmd);
   Wire.endTransmission();
-  if(cmd=="R" | cmd.startsWith("Cal"))
+  if((cmd == "R") | cmd.startsWith("Cal"))
     delay(900);
   else
     delay(300);
@@ -220,20 +233,20 @@
   int val=Wire.read();
   switch (val) {
     case 1:
-      Serial.println("Success");
+      //Serial.println("Success");
       break;
     case 2:
-      Serial.println("Failed");
+      //Serial.println("Failed");
       return String("Failed");
       break;
     case 254:
-      Serial.println("Pending");
+      //Serial.println("Pending");
       break;
     case 255:
-      Serial.println("No Data");
+      //Serial.println("No Data");
       break;
     default:
-      Serial.printlnf("Invalid response %d",val);
+      //Serial.printlnf("Invalid response %d",val);
       return String("Failed");
   }


corrected a wrong comment inside the KeyboardAndMouseControl example

--- build/shared/examples/09.USB/KeyboardAndMouseControl/KeyboardAndMouseControl.ino
+++ build/shared/examples/09.USB/KeyboardAndMouseControl/KeyboardAndMouseControl.ino
@@ -67,7 +67,7 @@
       Mouse.move(40, 0);
       break;
     case 'm':
-      // perform the right click
+      // perform mouse left click
       Mouse.click(MOUSE_LEFT);
       break;
     }


Update connect4.ino

Update connect4.ino

(Very) minor speed improvements

--- connect4.ino
+++ connect4.ino
@@ -47,7 +47,9 @@

     Serial.println();
     Serial.print("My go:");
+    unsigned long t = millis();
     currentScore = bestMove(board, 'X', 'O', best, 4);
+    Serial.println(millis() - t);
     Serial.println(best);
     Serial.println();
     dropCounter(board, 'X', best);
@@ -77,7 +79,7 @@
   }
 }

-void dropCounter(char board[], char token, byte col) {
+byte dropCounter(char board[], char token, byte col) {

   byte i = col;

@@ -88,6 +90,7 @@
   }
   // Place the token here
   board[i] = token;
+  return i;
 }

 int score(char board[], char token, char oppToken) {
@@ -99,9 +102,10 @@

     byte i = lineStart[line];
     byte lineStep = lineSteps[line];
+    byte reps = lineReps[line];

     // Scan each group of 4 positions on the "win" line
-    for (byte rep = 0; rep < lineReps[line]; rep++) {
+    for (byte rep = 0; rep < reps; rep++) {

       byte j = i;
       int addScore = 0;
@@ -124,8 +128,7 @@
             goto gameWon;
           }
         }
-
-        if (board[j] == oppToken) {
+        else if (board[j] == oppToken) {
           if (addScore > 0) {
             // A mix of "O" and "X" - no-one can win here
             addScore = 0;
@@ -156,21 +159,19 @@

   int bestScore = -9999;

+  // Make a copy of the board
+  char boardCopy[43];
+  for (byte i = 0; i < 43; i++) boardCopy[i] = board[i];
+
   // Evaluate each choice of column
   for (byte col = 0; col < 7; col++) {
     if (board[col] == '.') {

-      int thisScore;
+      // Drop token onto the copy of the board
+      byte counterPosition = dropCounter(boardCopy, token, col);
+      int thisScore = score(boardCopy, token, oppToken);

-      // Make a copy of the board
-      char boardCopy[43];
-      for (byte i = 0; i < 43; i++) boardCopy[i] = board[i];
-
-      // Drop token onto the copy of the board
-      dropCounter(boardCopy, token, col);
-      thisScore = score(boardCopy, token, oppToken);
-
-      if (abs(thisScore) < 1000 && lookAhead > 0) {
+      if (thisScore > -1000 && thisScore < 1000 && lookAhead > 0) {
         // Look more moves ahead, but swap places with opponent since it will be their turn next
         byte oppBestCol;
         thisScore = -bestMove(boardCopy, oppToken, token, oppBestCol, lookAhead - 1);
@@ -182,7 +183,14 @@
         bestScore = thisScore;
         bestCol = col;
       }
+      // remove the counter again
+      boardCopy[counterPosition] = '.';
     }
   }
   return bestScore;
 }
+
+
+
+
+


Updated example 19 for STM32F boards

Updated example 19 for STM32F boards

--- examples/Scheduler_example19_Dynamic_Tasks/Scheduler_example19_Dynamic_Tasks.ino
+++ examples/Scheduler_example19_Dynamic_Tasks/Scheduler_example19_Dynamic_Tasks.ino
@@ -4,23 +4,38 @@
       Main task runs every 100 milliseconds 100 times and in 50% cases generates a task object
       which runs 1 to 10 times with 100 ms to 5 s interval, and then destroyed.

-      This sketch uses a FreeMemory library: https://github.com/McNeight/MemoryFree
+      This sketch uses the following libraries:
+       - FreeMemory library: https://github.com/McNeight/MemoryFree
+       - QueueArray library: https://playground.arduino.cc/Code/QueueArray/
 */

 #define _TASK_WDT_IDS // To enable task unique IDs
 #define _TASK_SLEEP_ON_IDLE_RUN  // Compile with support for entering IDLE SLEEP state for 1 ms if not tasks are scheduled to run
 #define _TASK_LTS_POINTER       // Compile with support for Local Task Storage pointer
 #include <TaskScheduler.h>
-
+#include <QueueArray.h>
+
+#if defined (ARDUINO_ARCH_AVR)
 #include <MemoryFree.h>
+#elif defined(__arm__)
+extern "C" char* sbrk(int incr);
+static int freeMemory() {
+  char top = 't';
+  return &top - reinterpret_cast<char*>(sbrk(0));
+}
+#else
+int freeMemory(); // supply your own
+#endif

 Scheduler ts;

 // Callback methods prototypes
 void MainLoop();
+void GC();

 // Statis task
-Task tMain(100*TASK_MILLISECOND, 100, MainLoop, &ts, true);
+Task tMain(100*TASK_MILLISECOND, 100, &MainLoop, &ts, true);
+Task tGarbageCollection(TASK_IMMEDIATE, TASK_FOREVER, &GC, &ts, false);

 void Iteration();
@@ -28,6 +43,7 @@
 void OnDisable();

 int noOfTasks = 0;
+QueueArray <(Task*)> toDelete;

 void MainLoop() {
   Serial.print(millis()); Serial.print("\t");
@@ -42,8 +58,9 @@
     Task *t = new Task(p, j, Iteration, &ts, false, OnEnable, OnDisable);

     Serial.print(F("Generated a new task:\t")); Serial.print(t->getId()); Serial.print(F("\tInt, Iter = \t"));
-    Serial.print(p); Serial.print(", "); Serial.print(j); Serial.print(F("\tFree mem="));
-    Serial.print(freeMemory()); Serial.print(F("\tNo of tasks=")); Serial.println(++noOfTasks);
+    Serial.print(p); Serial.print(", "); Serial.print(j);
+	Serial.print(F("\tFree mem=")); Serial.print(freeMemory());
+	Serial.print(F("\tNo of tasks=")); Serial.println(++noOfTasks);
     t->enable();
   }
   else {
@@ -69,10 +86,12 @@
 void OnDisable() {
   Task *t = &ts.currentTask();
   unsigned int tid = t->getId();
-
-  delete t;
+  toDelete.push(t);
+  tGarbageCollection.enableIfNot();
+
   Serial.print(millis()); Serial.print("\t");
-  Serial.print("Task N"); Serial.print(tid); Serial.print(F("\tfinished and destroyed.\tFree mem="));
+  Serial.print("Task N"); Serial.print(tid); Serial.println(F("\tfinished");
+  Serial.ptint("and destroyed.\tFree mem="));
   Serial.print(freeMemory());Serial.print(F("\tNo of tasks=")); Serial.println(--noOfTasks);
 }

@@ -87,14 +106,29 @@

   Serial.println(F("Dynamic Task Creation/Destruction Example"));
   Serial.println();
-  Serial.print(F("Free mem="));
-  Serial.print(freeMemory()); Serial.print(F("\tNo of tasks=")); Serial.println(noOfTasks);
+
+  Serial.print(F("Free mem=")); Serial.print(freeMemory());
+  Serial.print(F("\tNo of tasks=")); Serial.println(noOfTasks);
   Serial.println();
+}
+
+void GC() {
+	if ( toDelete.isEmpty() ) {
+		tGarbageCollection.disable();
+		return;
+	}
+	Task *t = toDelete.pop();
+    Serial.print(millis()); Serial.print("\t");
+    Serial.print("Task N"); Serial.print(t->getId()); Serial.println(F("\tdestroyed");
+    Serial.ptint("Free mem=")); Serial.print(freeMemory());
+	Serial.print(F("\tNo of tasks=")); Serial.println(--noOfTasks);
+	delete t;
 }

 void loop() {
   ts.execute();
 }
+

 /* Output on Arduino Uno:


Fixed casting bug on RX side that was causing failsafe to engage without specific reason

--- crossbow.ino
+++ crossbow.ino
@@ -134,14 +134,7 @@
     LoRa.setSpreadingFactor(8);
     LoRa.setCodingRate4(6);
     LoRa.enableCrc();
-
-    /*
-     * Use interrupt driven approach only on RX side
-     * TX interrupts breaks PPM readout
-     */
-// #ifdef DEVICE_MODE_RX
     LoRa.onReceive(onReceive);
-// #endif
     LoRa.receive();

 #ifdef DEVICE_MODE_RX
@@ -393,7 +386,7 @@
         sbusTime = currentMillis + SBUS_UPDATE_RATE;
     }

-    if (abs(currentMillis - qsp.lastFrameReceivedAt[QSP_FRAME_RC_DATA]) > RX_FAILSAFE_DELAY) {
+    if (qsp.lastFrameReceivedAt[QSP_FRAME_RC_DATA] + RX_FAILSAFE_DELAY < currentMillis) {
         qsp.deviceState = DEVICE_STATE_FAILSAFE;
     } else {
         qsp.deviceState = DEVICE_STATE_OK;


Testing

Testing

--- TimerShot/TimerShot.ino
+++ TimerShot/TimerShot.ino
@@ -108,21 +108,27 @@

   for (pos = 168; pos < 192; pos++) {

+    //long beginning = micros();
     OSP_SET_AND_FIRE(pos);

     //while (OSP_INPROGRESS());         // This just shows how you would wait if nessisary - not nessisary in this application.

-    _delay_ms(20);      // Wait a sec to let the audience clap
+    //long now = micros();
+    //Serial.println(now-beginning);
+    delay(20);//_delay_ms(20);      // Wait a sec to let the audience clap

   }

   for (pos = 192; pos > 168; pos--) {
-
+    //long beginning = micros();
     OSP_SET_AND_FIRE(pos);

     //while (OSP_INPROGRESS());         // This just shows how you would wait if nessisary - not nessisary in this application.

-    _delay_ms(20);      // Wait a sec to let the audience clap
+    //long now = micros();
+    //Serial.println(now-beginning);
+
+    delay(20);//_delay_ms(20);      // Wait a sec to let the audience clap

   }


a change that I dont grok

a change that I dont grok

--- Arduino/ResetAtlasProbe/ResetAtlasProbe.ino
+++ Arduino/ResetAtlasProbe/ResetAtlasProbe.ino
@@ -6,7 +6,7 @@
   Serial.println(F("Resetting pH probe"));
   char reset_p[] = {'X', '\0'};
   Wire.beginTransmission(probe_address); //call the circuit by its ID number.
- // Wire.write(reset_p);        //transmit the command that was sent through the serial port.
+  Wire.write(reset_p);        //transmit the command that was sent through the serial port.
   Wire.endTransmission();
   Serial.println("Complete");
 }


Update Launchpad_Data_Processor.ino

Update Launchpad_Data_Processor.ino

Added SD write routine on Matt's behalf, but it is now within another boolean condition so that we can still test without the SD connected.

Also cut a bunch of code that was commented out and updated the start/stop/reset string indicators. Starts in idle mode by default, so if using serial monitor type !!! to begin transmission.

--- Launchpad_Data_Processor/Launchpad_Data_Processor.ino
+++ Launchpad_Data_Processor/Launchpad_Data_Processor.ino
@@ -37,38 +37,37 @@

 //===================================Library Includes====================================
 #include <EEPROM.h>
-
+#include <SD.h>
+#include <SPI.h>
 //=====================================Definitions=======================================
 #define dataSetLength 6
 #define EEPROM_TIMEBASE_ADDR 0

 //===================================Program Settings====================================
-boolean mockMode = false;                    //  Defines which mode of operation to use.
-                                            //    - True denotes Mock Data Mode
-                                            //    - False denotes Data Acquistion Mode
+boolean mockMode = false;                  //  Defines which mode of operation to use.
+                                           //    - True denotes Mock Data Mode
+                                           //    - False denotes Data Acquistion Mode

 boolean sendConfigInfo = true;             //  This is an option to send an initial
-                                            //  set of configuration settings, giving
-                                            //  the plotting program more information
-                                            //  on what data it is handling.
+                                           //  set of configuration settings, giving
+                                           //  the plotting program more information
+                                           //  on what data it is handling.

 int configUpdateLimit = 10;                //  If config info strings are enabled,
                                            //  sets the maximum time elapsed before
                                            //  program should send an config update.
-
-boolean retainTimeReference = false;        //  This option reads and writes each time
-                                           //  base value to EEPROM on each loop to
-                                           //  determine whether a reset has occured.
-                                           //  If reset occurs, then the stored value
-                                           //  is added to the newly generated execution
-                                           //  time.

-boolean xbeeMode = true;                  //  This condition determines whether Xbees
+boolean xbeeMode = false;                  //  This condition determines whether Xbees
                                            //  are being used. Usually this would be
                                            //  true, except for testing without the
                                            //  Xbee.
-
-int sigNum = 6;                           //  This allows quick changes to be made to
+
+boolean SDMode = false;                    //  Condition to execute optional SD
+                                           //  functionality. This is provided for
+                                           //  testing purposes where the SD might
+                                           //  not be used.
+
+int sigNum = 6;                            //  This allows quick changes to be made to
                                            //  the number of signals when in mock mode,
                                            //  which helps with testing transmission
                                            //  capacity.
@@ -180,54 +179,36 @@
     Serial.println("OK received. Configuration complete");

   }
-  //~~~~~~~~~~~~~~~~~~~~~~~~~Wait for Information from Plotter~~~~~~~~~~~~~~~~~~~~~~~~~~~
-  /*int buff_length = 6;
-  char xbee_buf[10];
-  Serial2.print("+++");
-  delay(1000);

-  while(1)
-  {
-    if(Serial2.available() > buff_length)
-    {
-      Serial2.readBytesUntil('\n', xbee_buf, Serial2.available());
-      Serial.println(xbee_buf);
-      delay(1000);
+  //~~~~~~~~~~~~~~~~~~~~~~~Send Initial Configuration Information~~~~~~~~~~~~~~~~~~~~~~~~
+  sendConfigString();
+}
+
+//=================================Main Program Loop=====================================
+void loop() {
+  float timeElapsed = 0;
+  float addedTime = 0;
+  int n = 0;
+  File myFile;
+
+  //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~SD Card Implementation~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+  if(SDMode)                              //  SD only needs to be initialized if SD is being
+  {                                       //  used. Otherwise, initialization will fail.
+    pinMode(10, OUTPUT);
+
+    if (!SD.begin(4)) {
+      Serial.println("initialization failed!");
+      return;
     }
-    else if(Serial2.available())
-    {
-      Serial2.readBytesUntil('S', xbee_buf, Serial2.available());
-      Serial.print("Else: ");
-      Serial.println(xbee_buf);
-
+
+    if(SD.exists("data.txt")){
+      SD.remove("data.txt");
     }
+
+    myFile = SD.open("data.txt", FILE_WRITE);
   }

-
-  //while(Serial2.available()) Serial.write(Serial2.read());
-  Serial.println("Waiting on start message...");
-  while((!Serial2.available()) || (!Serial2.find("Start")));
-  Serial.println("Start message received. Beginning transmission");
-  */
-  //~~~~~~~~~~~~~~~~~~~~~~~Send Initial Configuration Information~~~~~~~~~~~~~~~~~~~~~~~~
-  sendConfigString();
-
-  //~~~~~~~~~~~~~~~~~~~~~~~~Clear time reference if applicable~~~~~~~~~~~~~~~~~~~~~~~~~~~
-  if(!retainTimeReference)
-  {
-    EEPROM.write(EEPROM_TIMEBASE_ADDR, 0);  //  Set recorded time value to 0
-    EEPROM.write(EEPROM_TIMEBASE_ADDR+1, 0);
-    EEPROM.write(EEPROM_TIMEBASE_ADDR+2, 0);
-  }
-}
-
-
-
-//=================================Main Program Loop=====================================
-void loop() {
-
-  float timeElapsed = 0;
-  float addedTime = 0;
+  //~~~~~~~~~~~~~~~~~~~~~~~~~~~Generate and Transmit Mock Data~~~~~~~~~~~~~~~~~~~~~~~~~~~
   if(mockMode)                              //  Enters mock data transmission mode
   {
     int ramp = 0;
@@ -281,6 +262,8 @@
     int n=0;                                // Count loops around print routine
     int i=0;
     boolean transBegin = false;
+    boolean downloadBegin = false;
+
     for(;;)
     {
       //~~~~~~~~~~~~~~~~~~~~~~~Create simulation data for now~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -294,45 +277,56 @@
          addedTime = execTime;
       }

-      //~~~~~~~~~~~~~~~~Check for transmission start signal from plotter~~~~~~~~~~~~~~~~
-      /*if(Serial2.available() > 2)
-      {
-        char start_buf[10] = "";
-        Serial2.readBytes(start_buf, Serial2.available());
-        if(String(start_buf) == "!!!")
-        {
-          transBegin = true;
-        }
-        if(String(start_buf) == "~~~")  transBegin = false;
-        if(String(start_buf) == "---")
-        {
-          EEPROM.write(EEPROM_TIMEBASE_ADDR+2, 0);
-          EEPROM.write(EEPROM_TIMEBASE_ADDR+1, 0);
-          EEPROM.write(EEPROM_TIMEBASE_ADDR, 0);
-          n=0;
-          initRead = 0;
-          resetTime = execTime;
-        }
-      }
-      if(!transBegin) continue;
-      */
+      //~~~~~~~~~~~~~~~~~~~~~~~~~Check for signals from plotter~~~~~~~~~~~~~~~~~~~~~~~~~
+     if(xbeeMode)
+      {
+        if(Serial2.available() > 2)
+        {
+          char start_buf[10] = "";
+          Serial2.readBytes(start_buf, Serial2.available());
+          Serial.print("Plotter string received was: ");
+          Serial.println(String(start_buf));
+          if(String(start_buf) == "!!!")
+          {
+            transBegin = true;
+          }
+          if(String(start_buf) == "~~~")  transBegin = false;
+          if(String(start_buf) == "---")
+          {
+            n=0;
+            initRead = 0;
+            resetTime = execTime;
+          }
+        }
+        if(!transBegin) continue;
+      }
+      else
+      {
+        if(Serial.available() > 2)
+        {
+          char start_buf[10] = "";
+          Serial.readBytes(start_buf, Serial.available());
+
+
+          Serial.print("Plotter string received was: ");
+          Serial.println(String(start_buf));
+          if(String(start_buf) == "!!!")
+          {
+            transBegin = true;
+          }
+          if(String(start_buf) == "~~~")  transBegin = false;
+          if(String(start_buf) == "---")
+          {
+            n=0;
+            initRead = 0;
+            resetTime = execTime;
+          }
+        }
+        if(!transBegin) continue;
+      }
+
+      //~~~~~~~~~~~~~~~~~~~~~~~~~Generate Data for transmission~~~~~~~~~~~~~~~~~~~~~~~~~~
       execTime = execTime - resetTime;
-      //~~~~~~~~~~~~~~~~~~~~~Refer to stored timebase in EEPROM~~~~~~~~~~~~~~~~~~~~~~~~~
-      if(retainTimeReference)
-      {
-        float timeRead = 0;
-        timeRead = float(EEPROM.read(EEPROM_TIMEBASE_ADDR+2)<<8) + float(EEPROM.read(EEPROM_TIMEBASE_ADDR+1)) + float(EEPROM.read(EEPROM_TIMEBASE_ADDR))/100.0;
-        if((execTime - 0.1) < timeRead)
-        {
-          if(n == 0)  initRead = timeRead;
-          execTime = execTime + initRead;
-        }
-
-        EEPROM.write(EEPROM_TIMEBASE_ADDR+2, int(execTime)>>8);
-        EEPROM.write(EEPROM_TIMEBASE_ADDR+1, execTime);
-        EEPROM.write(EEPROM_TIMEBASE_ADDR, int(execTime*100)-int(execTime));
-
-      }

       i++;
       if((i>=10) || (n==0))
@@ -359,19 +353,52 @@
       {
         if(xbeeMode)
         {
-          Serial.println("Sending data...");
-          Serial2.print(currentDataSet[i]);
-          Serial2.print(" ");
-          if(i == (sizeof(currentDataSet)/sizeof(float) - 1)) Serial2.print("\r");
+          if(SDMode)
+          {
+            //SD with Xbee yet to be added, but should be much the same as below
+            Serial.println("SD with Xbee yet to be added, but should be much the same");
+          }
+          else
+          {
+            Serial.println("Sending data...");
+            Serial2.print(currentDataSet[i]);
+            Serial2.print(" ");
+            if(i == (sizeof(currentDataSet)/sizeof(float) - 1)) Serial2.print("\r");
+          }
         }
         else                                  //  If Xbees aren't being used UART1
         {                                     //  is used instead.
-          Serial.print(currentDataSet[i]);
-          Serial.print(" ");
-          if(i == (sizeof(currentDataSet)/sizeof(float) - 1)) Serial.print("\r");
-        }
-      }
-      delay(25);
+          if(SDMode)
+          {                                   //  If SD selected run SD routines
+            // SD Card Implementation
+            if(myFile) {
+              Serial.println("---- WRITING TO SD ---- "); // Testing if SD Card Works
+              myFile.print(currentDataSet[i]);           // Print dataset to SD Card
+              myFile.print(" ");                         // Formatting
+              if(i == (sizeof(currentDataSet)/sizeof(float) - 1)) myFile.print("\r");
+            }
+
+            if (n==100)                                 // SD Card Close Loop
+            {                                           // Close to be Impl. by Plotter
+              Serial.println("---- CLOSE SD ----");     // Testing if SD Card Works
+              myFile.close();
+            }
+
+            //Serial.print(currentDataSet[i]);           // Print dataset to Serial
+            //Serial.print(" ");
+
+            if(i == (sizeof(currentDataSet)/sizeof(float) - 1)) Serial.print("\r");
+          }
+          else                                //  If SD is not selected, simply print
+          {                                   //  data to UART1.
+            Serial.print(currentDataSet[i]);           // Print dataset to Serial
+            Serial.print(" ");
+
+            if(i == (sizeof(currentDataSet)/sizeof(float) - 1)) Serial.print("\r");
+          }
+        }
+      }
+      delay(100);
       n++;                                   //  Increment loop counter
     }
   }
@@ -412,4 +439,3 @@
     }
     return;
 }
-


Trying out arduinoServoWrapper, doesn't work yet

--- current-test-program/servo_via_timer.ino
+++ current-test-program/servo_via_timer.ino
@@ -1,19 +1,21 @@
 #include <Servo.h>
+#include <inttypes.h>
+#include <signal.h>

-Servo main_signal;
+Signal main_signal=Signal(1300, 1750, 2200, 11);
 Servo secondary_signal;

-int MAIN_SIGNAL_MIN = 1300;
-int MAIN_SIGNAL_MAX = 1750;
-int MAIN_SIGNAL_DURATION_MS = 2200;
-int main_signal_timestep_ms;
-boolean main_signal_done=false;
-unsigned int main_signal_next_time_ms;
-int main_signal_value;
+// int MAIN_SIGNAL_MIN = 1300;
+// int MAIN_SIGNAL_MAX = 1750;
+// int MAIN_SIGNAL_DURATION_MS = 2200;
+// int main_signal_timestep_ms;
+// boolean main_signal_done=false;
+// unsigned int main_signal_next_time_ms;
+// int main_signal_value;

 int SECONDARY_SIGNAL_MIN = 1150;
 int SECONDARY_SIGNAL_MAX = 1750;
-int SECONDARY_SIGNAL_DURATION_MS = 2200;
+int SECONDARY_SIGNAL_DURATION_MS = 1200;
 int secondary_signal_timestep_ms;
 boolean secondary_signal_done=false;
 unsigned int secondary_signal_next_time_ms;
@@ -25,12 +27,13 @@
 void setup() {
   pinMode(13, OUTPUT);

-  main_signal.attach(11);
-  main_signal_timestep_ms = (MAIN_SIGNAL_DURATION_MS) / (MAIN_SIGNAL_MAX - MAIN_SIGNAL_MIN);
-  main_signal_value = MAIN_SIGNAL_MIN;
-  main_signal.writeMicroseconds(main_signal_value);
-  main_signal_next_time_ms = millis() + INITIAL_DELAY_MS;
-  main_signal.writeMicroseconds(main_signal_value);
+  main_signal.toMaxPos();
+  // main_signal.attach(11);
+  // main_signal_timestep_ms = (MAIN_SIGNAL_DURATION_MS) / (MAIN_SIGNAL_MAX - MAIN_SIGNAL_MIN);
+  // main_signal_value = MAIN_SIGNAL_MIN;
+  // main_signal.writeMicroseconds(main_signal_value);
+  // main_signal_next_time_ms = millis() + INITIAL_DELAY_MS;
+  // main_signal.writeMicroseconds(main_signal_value);

   secondary_signal.attach(12);
   secondary_signal_timestep_ms = (SECONDARY_SIGNAL_DURATION_MS) / (SECONDARY_SIGNAL_MAX - SECONDARY_SIGNAL_MIN);
@@ -42,18 +45,18 @@
 }

-void perhaps_update_main_signal() {
-  if (millis() > main_signal_next_time_ms && !main_signal_done) {
-    main_signal_value++;
-    if (main_signal_value > MAIN_SIGNAL_MAX) {
-      main_signal_done = true;
-      main_signal.detach();
-      return;
-    }
-    main_signal_next_time_ms += main_signal_timestep_ms;
-    main_signal.writeMicroseconds(main_signal_value);
-  }
-}
+// void perhaps_update_main_signal() {
+//   if (millis() > main_signal_next_time_ms && !main_signal_done) {
+//     main_signal_value++;
+//     if (main_signal_value > MAIN_SIGNAL_MAX) {
+//       main_signal_done = true;
+//       main_signal.detach();
+//       return;
+//     }
+//     main_signal_next_time_ms += main_signal_timestep_ms;
+//     main_signal.writeMicroseconds(main_signal_value);
+//   }
+// }

 void perhaps_update_secondary_signal() {
@@ -71,6 +74,8 @@

 void loop() {
-  perhaps_update_main_signal();
+  uint64_t now=millis();
+  main_signal.update(now);
+  // perhaps_update_main_signal();
   perhaps_update_secondary_signal();
 }


Update capSenseTest.ino

Update capSenseTest.ino

--- Arduino/Sensors/Capacitance/capSenseTest/capSenseTest.ino
+++ Arduino/Sensors/Capacitance/capSenseTest/capSenseTest.ino
@@ -10,8 +10,7 @@
 }

 void loop() {
-  long start = millis();                    // time performance - not necessary
-  long total = sensor.capacitiveSensor(30); // read 30 bytes
+  long total = sensor.capacitiveSensor(30); // take 30 samples

   Serial.println(total);                    // print sensor output
   delay(1);                                 // small delay to spare serial port from too much data


Use coolStep and report CS actual

Use coolStep and report CS actual

--- examples/StallGuard/StallGuard.ino
+++ examples/StallGuard/StallGuard.ino
@@ -28,25 +28,36 @@

 #include <SPI.h>
 #include <TMC2130Stepper.h>
-TMC2130Stepper TMC2130 = TMC2130Stepper(EN_PIN, DIR_PIN, STEP_PIN, CS_PIN);
+#include <TMC2130Stepper_REGDEFS.h>
+TMC2130Stepper driver = TMC2130Stepper(EN_PIN, DIR_PIN, STEP_PIN, CS_PIN);
+
+bool vsense;
+
+uint16_t rms_current(uint8_t CS, float Rsense = 0.11) {
+  return (float)(CS+1)/32.0 * (vsense?0.180:0.325)/(Rsense+0.02) / 1.41421 * 1000;
+}

 void setup() {
   //init serial port
   {
-	  Serial.begin(250000); //init serial port and set baudrate
-	  while(!Serial); //wait for serial port to connect (needed for Leonardo only)
-	  Serial.println("\nStart...");
-    TMC2130.begin();
-	}
+    Serial.begin(250000); //init serial port and set baudrate
+    while(!Serial); //wait for serial port to connect (needed for Leonardo only)
+    Serial.println("\nStart...");
+    driver.begin();
+  }

   //set TMC2130 config
   {
-		TMC2130.rms_current(600); // mA
-		TMC2130.microsteps(16);
-		TMC2130.diag1_stall(1);
-		TMC2130.diag1_active_high(1);
-		TMC2130.coolstep_min_speed(0xFFFFF); // 20bit max
-		TMC2130.sg_stall_value(STALL_VALUE);
+    driver.rms_current(600); // mA
+    driver.microsteps(16);
+    driver.diag1_stall(1);
+    driver.diag1_active_high(1);
+    driver.coolstep_min_speed(0xFFFFF); // 20bit max
+    driver.THIGH(0);
+    driver.semin(5);
+    driver.semax(2);
+    driver.sedn(0b01);
+    driver.sg_stall_value(STALL_VALUE);
   }

   // Set stepper interrupt
@@ -67,6 +78,8 @@

   //TMC2130 outputs on (LOW active)
   digitalWrite(EN_PIN, LOW);
+
+  vsense = driver.vsense();
 }

 ISR(TIMER1_COMPA_vect){
@@ -80,18 +93,21 @@
   uint32_t ms = millis();

   while(Serial.available() > 0) {
-  	int8_t read_byte = Serial.read();
-  	if (read_byte == '0') 		 { TIMSK1 &= ~(1 << OCIE1A); digitalWrite( EN_PIN, HIGH ); }
-  	else if (read_byte == '1') { TIMSK1 |=  (1 << OCIE1A); digitalWrite( EN_PIN,  LOW ); }
+    int8_t read_byte = Serial.read();
+    if (read_byte == '0')      { TIMSK1 &= ~(1 << OCIE1A); digitalWrite( EN_PIN, HIGH ); }
+    else if (read_byte == '1') { TIMSK1 |=  (1 << OCIE1A); digitalWrite( EN_PIN,  LOW ); }
     else if (read_byte == '+') if (OCR1A > MAX_SPEED) OCR1A -= 20;
     else if (read_byte == '-') if (OCR1A < MIN_SPEED) OCR1A += 20;
   }

   if((ms-last_time) > 100) //run every 0.1s
   {
-    last_time = ms;
+    last_time = ms;
+    uint32_t drv_status = driver.DRV_STATUS();
     Serial.print("0 ");
-    Serial.println(TMC2130.sg_result(), DEC);
+    Serial.print((drv_status & SG_RESULT_bm)>>SG_RESULT_bp , DEC);
+    Serial.print(" ");
+    Serial.println(rms_current((drv_status & CS_ACTUAL_bm)>>CS_ACTUAL_bp), DEC);
   }
 }


Use V pin notation

Use V pin notation

--- examples/Widgets/SDcard/SDcard.ino
+++ examples/Widgets/SDcard/SDcard.ino
@@ -33,7 +33,7 @@

 WidgetSD sd;

-BLYNK_ATTACH_WIDGET(sd, 1)
+BLYNK_ATTACH_WIDGET(sd, V1)

 void setup()
 {


added potentiometer test

added potentiometer test

--- proj/ledvo_lounge_final/ledvo_lounge_final.ino
+++ proj/ledvo_lounge_final/ledvo_lounge_final.ino
@@ -193,17 +193,17 @@
     }

     // Update the chaser options if we are one of those animations
-    /*EVERY_N_SECONDS(20) {
-      if (gAnimCounter == 0) {
+    EVERY_N_SECONDS(20) {
+//      if (gAnimCounter == 0) {
         chaser_opt = (chaser_opt + 1) % 9;
-      }
-      else if (gAnimCounter == 4 || gAnimCounter == 5) {
-        chaser_opt = (chaser_opt + 1) % 6;
-      }
-      else if (gAnimCounter == 8) {
-        chaser_opt = (chaser_opt + 1) % 3;
-      }
-    }*/
+//      }
+//      else if (gAnimCounter == 4 || gAnimCounter == 5) {
+//        chaser_opt = (chaser_opt + 1) % 6;
+//      }
+//      else if (gAnimCounter == 8) {
+//        chaser_opt = (chaser_opt + 1) % 3;
+//      }
+    }

     // For flashing black over current animation. We want it to work
     // with the animation so we want it separate from the DJ controls


changed drawChar to printChar

changed drawChar to printChar

--- examples/ScrollingText/ScrollingText.ino
+++ examples/ScrollingText/ScrollingText.ino
@@ -107,8 +107,8 @@
       for (int i = 0; i < sizeof(text)-1; i++) {   // Now draw each character in the string

          /*
-          drawChar() takes 3 parameters:
-           - Character to draw
+          printChar() takes 3 parameters:
+           - Character to print
            - X position (left)
            - Y position (top)
           The y position will always stay the same (unless you want to try something funky)
@@ -116,7 +116,7 @@
           position from the outer for loop plus the font width multiplied
           by its location in the text array.
          */
-         lm.drawChar(text[i], x + (FONT8x8 * i), 0);
+         lm.printChar(text[i], x + (FONT8x8 * i), 0);
       }
       lm.update();      // update() must be called to redraw the display
       delay(2);         // This sets the scroll speed
@@ -132,7 +132,7 @@
    for (int x = NUM_COLS * 8; x >= -sizeof(text)*(FONT5x7 + 1); x--) {
       lm.clear();
       for (int i = 0; i < sizeof(text)-1; i++) {
-         lm.drawChar(text[i], x + ((FONT5x7 + 1) * i), 8);
+         lm.printChar(text[i], x + ((FONT5x7 + 1) * i), 8);
       }
       lm.update();
       delay(2);


Formatting changes.  Added header guards. Removed clutter.

--- pulse_ox/pulse_ox.ino
+++ pulse_ox/pulse_ox.ino
@@ -1,9 +1,12 @@
+#ifndef __PULSE_OX__
+#define __PULSE_OX__ 1
+
+
+
 float InputPin = A0; // Analog input pin from output of op amp
 float sensorVoltage = 0;
 float sensorCurrent = 0;
-float LEDCurrentRed = 0;
 float AbsorbanceRed = 0;
-float LEDCurrentIR = 0;
 float AbsorbanceIR = 0;
 float CalculatedRatio;
 float bloodOx = 0;
@@ -11,7 +14,6 @@
 int LEDIR=D1;
 bool red_state;
 bool ir_state;
-bool state_diag;

 #include<math.h>

@@ -21,7 +23,7 @@

 //SYSTEM_MODE(MANUAL);

-Timer change_led_timer(3000, change_led_type);
+Timer change_led_timer(1500, change_led_type);
 //Timer change_ir_timer(6000, change_ir_type);
 //Timer ir_timer(6000, read_ir_and_calc);
 //Timer call_connect_timer(20000, call_connect);
@@ -34,44 +36,41 @@
 red_state = false;
 ir_state  = true;
 state_diag  = true; // Init state
-//ir_timer.start();
 change_led_timer.start();
-//change_ir_timer.start();
-//call_connect_timer.start();
 }

 void loop() {
     // red_led_on and start red_timer
     if(red_state)
     {
-       read_red_and_calc();
+       read_red();
        red_state  =  false;
        ir_state   =  false;
     }

     if(ir_state)
     {
-      read_ir_and_calc();
+      read_ir();
       red_state = false;
       ir_state  = false;
     }
-    //else
-    //{
-      // do nothing
-    //}
+
 } // loop

+// Turns on Red LED
 void red_led_on()
 {
   digitalWrite(LEDIR, LOW); digitalWrite(LEDRed, HIGH);
 }

+// Turns on IR LED
 void ir_led_on()
 {
   digitalWrite(LEDRed, LOW); digitalWrite(LEDIR, HIGH);
 }

-void read_red_and_calc()
+// Reads analog data of Red LED values
+void read_red()
 {
   ir_led_on();
   sensorVoltage = analogRead(InputPin);
@@ -85,7 +84,8 @@
 #endif
 }

-void read_ir_and_calc()
+// Reads analog data of IR LED values
+void read_ir()
 {
   red_led_on();
   sensorVoltage = analogRead(InputPin);
@@ -103,6 +103,7 @@
   Serial.println(bloodOx);
 }

+// Changes which LED to shine
 void change_led_type()
 {
     if(state_diag)
@@ -118,7 +119,4 @@
     state_diag  = !state_diag;
 }

-void call_connect()
-{
-  Particle.connect();
-}
+#endif


Using the Sparkfun MIDI shield.

Using the Sparkfun MIDI shield.

--- src/midi_IO_Serial/midi_IO_Serial.ino
+++ src/midi_IO_Serial/midi_IO_Serial.ino
@@ -20,12 +20,25 @@
  * SOFTWARE.
  */

+#include <sparkfun_MidiShield.h>
+
+struct State
+{
+    sparkfun::MidiShield::ButtonsState  mButtons;
+    sparkfun::MidiShield::PotsState     mPots;
+};
+
+State sState;
+
+// -----------------------------------------------------------------------------
+
 void setup()
 {
-
+    sparkfun::MidiShield::setup();
 }

 void loop()
 {
-
+    sparkfun::MidiShield::readPots(sState.mPots);
+    sparkfun::MidiShield::readButtons(sState.mButtons);
 }


Get rid of dead code Define port for clearer plugging

--- Communication/RF/ask_receiver/ask_receiver.ino
+++ Communication/RF/ask_receiver/ask_receiver.ino
@@ -7,11 +7,9 @@
 #include <RH_ASK.h>
 #include <SPI.h> // Not actualy used but needed to compile

-RH_ASK driver(4800, 11, 12);
+#define RF_DATA_PIN 11
+RH_ASK driver(4800, RF_DATA_PIN, 12);
 // RECEPTEUR : DATA D11
-// Sensors
-unsigned int SensorData1;
-char SensorMsg1[10];

 void setup()
 {
@@ -27,8 +25,6 @@

     if (driver.recv(buf, &buflen)) // Non-blocking
     {
-	int i;
-
 	// Message with a good checksum received, dump it.
 	//driver.printBuffer("Got:", buf, buflen);
         for (byte i = 0; i < buflen; i++) // Si il n'est pas corrompu on l'affiche via Serial


Replacing serial print by OLED print

Replacing serial print by OLED print

--- test/Arduino/MicroView/MicroView_ino/MicroView_ino.ino
+++ test/Arduino/MicroView/MicroView_ino/MicroView_ino.ino
@@ -7,6 +7,7 @@
 // MicroView OLED
 #include <MicroView.h>

+const int fontHeight = 10;

 /* This driver uses the Adafruit unified sensor library (Adafruit_Sensor),
  which provides a common 'type' for sensor data and some helper functions.
@@ -48,24 +49,40 @@
 {
   sensor_t sensor;
   bno.getSensor(&sensor);
-  Serial.println("------------------------------------");
-  Serial.print  ("Sensor:       ");
-  Serial.println(sensor.name);
-  Serial.print  ("Driver Ver:   ");
-  Serial.println(sensor.version);
-  Serial.print  ("Unique ID:    ");
-  Serial.println(sensor.sensor_id);
-  Serial.print  ("Max Value:    ");
+  char buffer[7];         //the ASCII of the integer will be stored in this char array
+
+  uView.clear(PAGE);
+
+  //Serial.print  ("Sensor:       ");
+  uView.setCursor(0, 0*fontHeight);
+  uView.print(sensor.name);
+
+  //Serial.print  ("Driver Ver:   ");
+  uView.setCursor(0, 1*fontHeight);
+  uView.print("Version: ");
+  itoa(sensor.version, buffer, 10);
+  uView.print(buffer);
+
+  //Serial.print  ("Unique ID:    ");
+  uView.setCursor(0, 2*fontHeight);
+  uView.print("ID: ");
+  itoa(sensor.sensor_id, buffer, 10);
+  uView.print(buffer);
+
+  //Serial.print  ("Max Value:    ");
   Serial.print(sensor.max_value);
-  Serial.println(" xxx");
+  //Serial.println(" xxx");
   Serial.print  ("Min Value:    ");
   Serial.print(sensor.min_value);
-  Serial.println(" xxx");
+  //Serial.println(" xxx");
   Serial.print  ("Resolution:   ");
   Serial.print(sensor.resolution);
-  Serial.println(" xxx");
-  Serial.println("------------------------------------");
-  Serial.println("");
+  //Serial.println(" xxx");
+  //Serial.println("------------------------------------");
+  //Serial.println("");
+
+  uView.display();
+
   delay(500);
 }

@@ -138,8 +155,8 @@
   // set font and cursor
   uView.setFontType(0);
   uView.setCursor(0,0);
-
-  // 10x5 lines availabe
+
+  // 10x6 lines availabe
   //           1234567890
   uView.print(" Robotik- ");
   uView.print(" labor :) ");
@@ -157,9 +174,11 @@
   if(!bno.begin())
   {
     uView.clear(PAGE);
+    uView.setCursor(0,0);
     /* There was a problem detecting the BNO055 ... check your connections */
     //Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!");
-    uView.print("Ooops, no BNO055 detected!");
+    uView.println("Ooops, no    BNO055 detected!");
+    uView.print("Please reset HW.");
     uView.display();

     while(1);
@@ -179,34 +198,34 @@

 void loop(void)
 {
-/*
+  /*
   // MicroView
-  // TEXT Font 0
-  uView.clear(PAGE);
-  uView.setCursor(0,40);
-  uView.print("  Font 0  ");
-  uView.display();
-
-  uView.setFontType(0);
-  uView.setCursor(0,0);
-  uView.print("01234567890ABCDabcd01234567890ABCDabcd");
-  uView.display();
-  delay(1500);
-
-
-  // TEXT Font 1
-  uView.clear(PAGE);
-  uView.setCursor(0,40);
-  uView.print("  Font 1  ");
-  uView.display();
-
-  uView.setFontType(1);
-  uView.setCursor(0,0);
-  uView.print("0123ABCDabcd");
-  uView.display();
-  delay(1500);
-  uView.clear(PAGE);
-*/
+   // TEXT Font 0
+   uView.clear(PAGE);
+   uView.setCursor(0,40);
+   uView.print("  Font 0  ");
+   uView.display();
+
+   uView.setFontType(0);
+   uView.setCursor(0,0);
+   uView.print("01234567890ABCDabcd01234567890ABCDabcd");
+   uView.display();
+   delay(1500);
+
+
+   // TEXT Font 1
+   uView.clear(PAGE);
+   uView.setCursor(0,40);
+   uView.print("  Font 1  ");
+   uView.display();
+
+   uView.setFontType(1);
+   uView.setCursor(0,0);
+   uView.print("0123ABCDabcd");
+   uView.display();
+   delay(1500);
+   uView.clear(PAGE);
+   */

   /* Get a new sensor event */
   sensors_event_t event;
@@ -234,3 +253,4 @@
 }

+


latest arduino software for pushing notifications via buttons

--- arduino/pusher/pusher.ino
+++ arduino/pusher/pusher.ino
@@ -26,10 +26,9 @@
   ethernetConnecting();
   Ethernet.begin(mac,ip);
   delay(1000); //Give time to initialize before connecting
-  if(pushMessage("arduino_test_channel", "arduino_event_register", "success"))
-    ethernetSucceeded();
-  else
+  while(!pushMessage("arduino_test_channel", "arduino_event_register", "success"))
     ethernetFailed();
+  ethernetSucceeded();

   for(int i = 0; i < 7; i++)
     pinMode(buttonPin[i], INPUT);
@@ -51,11 +50,17 @@

+
+
+
+
+
+
 void readButtons()
 {
   for(int i = 0; i < 7; i++)
   {
-    if(digitalRead(buttonPin[i]) == HIGH)
+    if(digitalRead(buttonPin[i]) == LOW)
     {
       if(buttonCountDown[i] == 0)
       {