LoaderTest: Disable USB/serial for ATtiny85

--- Utils/LoaderTest/LoaderTest.ino
+++ Utils/LoaderTest/LoaderTest.ino
@@ -35,6 +35,7 @@
 // XXX Keyboard: Map Enter to both newline AND buttonA
 // XXX Keyboard: Delete = buttonA (same code 0x7f). Change delete code?
 // XXX Keyboard: Is it possible to mimic key hold-down properly???
+// XXX Timeouts/reset in case of hanging (dead man switch function?)
 // XXX Embed a Gigatron Terminal program. Or better: GigaMon

 /*----------------------------------------------------------------------+
@@ -49,6 +50,8 @@
 // Pin 11  PORTB3 6 hSync  SER_PULSE 10 CLOCK   11 SRCLK 12 RCLK 4

 #if ArduinoUno
+ #define version "ArduinoUno"
+
  // Pins for Gigatron
  #define SER_DATA  PB5
  #define SER_LATCH PB4
@@ -88,6 +91,7 @@
 // --------------------+

 #if ArduinoMicro
+ #define version "ArduinoMicro"

  // Pins for Gigatron
  #define SER_DATA  PB1
@@ -115,6 +119,7 @@
 //                   ATtiny85

 #if ATtiny85
+ #define version "ATtiny85"

  // Pins for Gigatron
  #define SER_DATA  PB2
@@ -174,8 +179,9 @@
   DDRB = 1<<SER_DATA;

   // Open upstream communication
-  Serial.begin(115200);
-
+  #if hasSerial
+    Serial.begin(115200);
+  #endif
   doVersion();

   // In case we power on together with the Gigatron, this is a
@@ -193,19 +199,21 @@
  */
 void loop()
 {
-  static char line[20];
-  static byte lineIndex = 0;
-
-  if (Serial.available()) {
-    byte next = Serial.read();
-    if (lineIndex < sizeof line)
-      line[lineIndex++] = next;
-    if (next == '\n') {
-      line[lineIndex-1] = '\0';
-      doCommand(line);
-      lineIndex = 0;
+  #if hasSerial
+    static char line[20];
+    static byte lineIndex = 0;
+
+    if (Serial.available()) {
+      byte next = Serial.read();
+      if (lineIndex < sizeof line)
+        line[lineIndex++] = next;
+      if (next == '\n') {
+        line[lineIndex-1] = '\0';
+        doCommand(line);
+        lineIndex = 0;
+      }
     }
-  }
+  #endif

   if (keyboard.available()) {
     char c = keyboard.read();
@@ -228,8 +236,10 @@

 void prompt()
 {
-  Serial.println(detectGigatron() ? ":Gigatron OK" : "!Gigatron offline");
-  Serial.println("\nCmd?");
+  #if hasSerial
+    Serial.println(detectGigatron() ? ":Gigatron OK" : "!Gigatron offline");
+    Serial.println("\nCmd?");
+  #endif
 }

 bool detectGigatron()
@@ -269,37 +279,45 @@
   case 'Q': sendController(~buttonSelect, 2); break;
   case 'E': sendController(~buttonStart,  2); break;
   case 0: /* Empty line */                    break;
-  default:  Serial.println("!Unknown command (type 'H' for help)");
+  #if hasSerial
+    default:
+      Serial.println("!Unknown command (type 'H' for help)");
+  #endif
   }
   prompt();
 }

 void doVersion()
 {
-  Serial.println(":Gigatron Interface Adapter [Arduino]\n"
-                 ":Type 'H' for help");
+  #if hasSerial
+    Serial.println(":Gigatron Interface Adapter [" version "]\n"
+                   ":Type 'H' for help");
+  #endif
 }

 void doHelp()
 {
-  Serial.println(":Commands are");
-  Serial.println(": V        Show version");
-  Serial.println(": H        Show this help");
-  Serial.println(": R        Reset Gigatron");
-  Serial.println(": L        Start Loader");
-  Serial.println(": P        Transfer object file from PROGMEM");
-  Serial.println(": U        Transfer object file from USB");
-  Serial.println(": W/A/S/D  Up/left/down/right arrow");
-  Serial.println(": Z/X      A/B button ");
-  Serial.println(": Q/E      Select/start button");
+  #if hasSerial
+    Serial.println(":Commands are");
+    Serial.println(": V        Show version");
+    Serial.println(": H        Show this help");
+    Serial.println(": R        Reset Gigatron");
+    Serial.println(": L        Start Loader");
+    Serial.println(": P        Transfer object file from PROGMEM");
+    Serial.println(": U        Transfer object file from USB");
+    Serial.println(": W/A/S/D  Up/left/down/right arrow");
+    Serial.println(": Z/X      A/B button ");
+    Serial.println(": Q/E      Select/start button");
+  #endif
 }

 void doReset()
 {
   // Soft reset: hold start for >128 frames (>2.1 seconds)
-  Serial.println(":Resetting Gigatron");
-  Serial.flush();
-
+  #if hasSerial
+    Serial.println(":Resetting Gigatron");
+    Serial.flush();
+  #endif
   sendController(~buttonStart, 128+32);

   // Wait for main menu to be ready
@@ -309,8 +327,11 @@
 void doLoader()
 {
   // Navigate menu. 'Loader' is at the bottom
-  Serial.println(":Starting Loader from menu");
-  Serial.flush();
+  #if hasSerial
+    Serial.println(":Starting Loader from menu");
+    Serial.flush();
+  #endif
+
   for (int i=0; i<10; i++) {
     sendController(~buttonDown, 2);
     delay(50);
@@ -333,16 +354,23 @@
 {
   int nextByte;

-  #define readNext() {\
-    nextByte = gt1 ? pgm_read_byte(gt1++) : nextSerial();\
-    if (nextByte < 0) return;\
-  }
-
-  #define ask(n)\
-    if (!gt1) {\
-      Serial.print(n);\
-      Serial.println("?");\
+  #if hasSerial
+    #define readNext() {\
+      nextByte = gt1 ? pgm_read_byte(gt1++) : nextSerial();\
+      if (nextByte < 0) return;\
     }
+    #define ask(n)\
+      if (!gt1) {\
+        Serial.print(n);\
+        Serial.println("?");\
+      }
+  #else
+    #define readNext() {\
+      nextByte = pgm_read_byte(gt1++);\
+      if (nextByte < 0) return;\
+    }
+    #define ask(n)
+  #endif

   byte segment[300] = {0}; // Multiple of N for padding

@@ -368,17 +396,20 @@

     // Check that segment doesn't cross the page boundary
     if ((address & 255) + len > 256) {
-      Serial.println("!Data error (page overflow)");
+      #if hasSerial
+        Serial.println("!Data error (page overflow)");
+      #endif
       return;
     }

     // Send downstream
-    Serial.print(":Loading ");
-    Serial.print(len);
-    Serial.print(" bytes at $");
-    Serial.println(address, HEX);
-    Serial.flush();
-
+    #if hasSerial
+      Serial.print(":Loading ");
+      Serial.print(len);
+      Serial.print(" bytes at $");
+      Serial.println(address, HEX);
+      Serial.flush();
+    #endif
     sendGt1Segment(address, len, segment);

     // Signal that we're ready to receive more
@@ -394,25 +425,29 @@
   readNext();
   address = (address << 8) + nextByte;
   if (address != 0) {
-    Serial.print(":Executing from $");
-    Serial.println(address, HEX);
-    Serial.flush();
+    #if hasSerial
+      Serial.print(":Executing from $");
+      Serial.println(address, HEX);
+      Serial.flush();
+    #endif
     sendGt1Execute(address, segment+240);
   }
 }

 int nextSerial()
 {
-  unsigned long timeout = millis() + 5000;
-
-  while (!Serial.available() && millis() < timeout)
-    ;
-
-  int nextByte = Serial.read();
-  if (nextByte < 0)
-    Serial.println("!Timeout error (no data)");
-
-  return nextByte;
+  #if hasSerial
+    unsigned long timeout = millis() + 5000;
+
+    while (!Serial.available() && millis() < timeout)
+      ;
+
+    int nextByte = Serial.read();
+    if (nextByte < 0)
+      Serial.println("!Timeout error (no data)");
+
+    return nextByte;
+  #endif
 }

 // Send a 1..256 byte code or data segment into the Gigatron by
@@ -492,7 +527,7 @@
   byte lastByte = -checksum;   // Checksum must come out as 0
   sendBits(lastByte, 8);
   checksum = lastByte;         // Concatenate checksums
-  PORTB |= 1<<SER_DATA;          // Send 1 when idle
+  PORTB |= 1<<SER_DATA;        // Send 1 when idle
 }

 void sendFirst(byte value, byte n)


Save 14 bytes by avoiding a for loop.

Save 14 bytes by avoiding a for loop.

The code is slightly less clear, but every byte counts.

--- printer.ino
+++ printer.ino
@@ -258,7 +258,7 @@

 void flashErrorLEDs(unsigned int times, unsigned int pause) {
   delay(pause);
-  for(int i = 1; i <= times; i++) {
+  while (times--) {
     digitalWrite(errorLED, HIGH); delay(pause);
     digitalWrite(errorLED, LOW); delay(pause);
   }


updating aquario main file

updating aquario main file

--- aquario.ino
+++ aquario.ino
@@ -2,15 +2,35 @@
 // DS3231 Library Copyright (C)2015 Rinky-Dink Electronics, Henning Karlsen. All right reserved
 // web: http://www.RinkyDinkElectronics.com/

+// Init libraries
 #include <DallasTemperature.h>
 #include <OneWire.h>
 #include <DS3231.h>

+// Define OneWire pin
+#define ONE_WIRE_BUS 8
+
+// Define Relay Digital I/O pin number and names
+#define RELAY_ON 1
+#define RELAY_OFF 0
+#define relay_1  2  // SSR
+#define relay_1_name = "Heater"
+#define relay_2  3  // SSR
+#define relay_2_name = "Lighting"
+#define relay_3  4  // SSR
+#define relay_3_name = "CO2"
+#define relay_4  5  //
+#define relay_4_name = "Pump1"
+#define relay_5  6  //
+#define relay_5_name = "Pump2"
+#define relay_6  7  //
+#define relay_6_name = "Pump3"
+#define relay_7  8  //
+#define relay_7_name = "Pump4"
+
+
 // Init the DS3231 using the hardware interface
 DS3231  rtc(SDA, SCL);
-
-// Define OneWire pin
-#define ONE_WIRE_BUS 8

 // Init OneWire
 OneWire oneWire(ONE_WIRE_BUS);
@@ -24,25 +44,14 @@
 // Init a Time-data structure
 Time  t;

-// Define Relay Digital I/O pin number
-#define RELAY_ON 1
-#define RELAY_OFF 0
-
-#define Relay_1  2  // purple
-#define Relay_2  3  // white
-#define Relay_3  4  // orange
-#define Relay_4  5  // yellow
-
-// set temp
+// set water temp
 float temp = 30;

-// set upper temp variance
+// set upper water temp variance
 float upperTempVariance = 2;

-// set lower temp variance
+// set lower water temp variance
 float lowerTempVariance = 5;
-
-int waittime; // Delay between changes

 void tempSensorsSetup() {
   // Start up the DallasTemp library
@@ -56,25 +65,25 @@
   return temp;
 }

-void setSetTemp(float temp) {
-  temp = temp;
-}
+//void setSetTemp(float temp) {
+//  temp = temp;
+//}

 float getUpperTempVariance() {
   return upperTempVariance;
 }

-void setUpperTempVariance(float upperTempVariance) {
-  upperTempVariance = upperTempVariance;
-}
+//void setUpperTempVariance(float upperTempVariance) {
+//  upperTempVariance = upperTempVariance;
+//}

 float getLowerTempVariance() {
   return lowerTempVariance;
 }

-void setLowerTempVariance(float lowerTempVariance) {
-  lowerTempVariance = lowerTempVariance;
-}
+//void setLowerTempVariance(float lowerTempVariance) {
+//  lowerTempVariance = lowerTempVariance;
+//}

 // declare upperTempLimit and lowerTempLimit
 float upperTempLimit = getSetTemp() + getUpperTempVariance();
@@ -86,114 +95,71 @@

   // Initialize the rtc object
   rtc.begin();
+  setCurrentTime(10, 0, 0);     // Set the time to 12:00:00 (24hr format)
+
+  //set digital pins as outputs
+  pinMode(relay_1, OUTPUT);
+  pinMode(relay_2, OUTPUT);
+  pinMode(relay_3, OUTPUT);
+  pinMode(relay_4, OUTPUT);

-  // The following lines can be uncommented to set the date and time
-  //rtc.setDOW(WEDNESDAY);     // Set Day-of-Week to SUNDAY
-  rtc.setTime(10, 0, 0);     // Set the time to 12:00:00 (24hr format)
-  //rtc.setDate(1, 1, 2014);   // Set the date to January 1st, 2014
-
-  waittime = 100;
-//-------( Initialize Pins so relays are inactive at reset)----
-  digitalWrite(Relay_1, RELAY_OFF);
-  digitalWrite(Relay_2, RELAY_OFF);
-  digitalWrite(Relay_3, RELAY_OFF);
-  digitalWrite(Relay_4, RELAY_OFF);
-
-
-//set digital pins as outputs
-  pinMode(Relay_1, OUTPUT);
-  pinMode(Relay_2, OUTPUT);
-  pinMode(Relay_3, OUTPUT);
-  pinMode(Relay_4, OUTPUT);
+  //-------( Initialize Pins so relays are inactive at reset)----
+  digitalWrite(relay_1, RELAY_OFF);
+  digitalWrite(relay_2, RELAY_OFF);
+  digitalWrite(relay_3, RELAY_OFF);
+  digitalWrite(relay_4, RELAY_OFF);
+
   delay(4000); //Check that all relays are inactive at

   // temp setup
-  tempSensorsSetup();
+  tempSensorsSetup();
 }

 void loop() {
-  // Get data from the DS3231
-  t = rtc.getTime();
-
- /* // Send date over serial connection
-  Serial.print("Today is the ");
-  Serial.print(t.date, DEC);
-  Serial.print(". day of ");
-  Serial.print(rtc.getMonthStr());
-  Serial.print(" in the year ");
-  Serial.print(t.year, DEC);
-  Serial.println(".");
-
-  // Send Day-of-Week and time
-  Serial.print("It is the ");
-  Serial.print(t.dow, DEC);
-  Serial.print(". day of the week (counting monday as the 1th), and it has passed ");
-  Serial.print(t.hour, DEC);
-  Serial.print(" hour(s), ");
-  Serial.print(t.min, DEC);
-  Serial.print(" minute(s) and ");
-  Serial.print(t.sec, DEC);
-  Serial.println(" second(s) since midnight.");

-  // Send a divider for readability
-  Serial.println("  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -");*/
-
-//  // Send Day-of-Week
-//  Serial.print(rtc.getDOWStr());
-//  Serial.print(" ");
-//
-//  // Send date
-//  Serial.print(rtc.getDateStr());
-//  Serial.print(" -- ");
-//
-//  // Send time
-//  Serial.println(rtc.getTimeStr());
-//
-//if(t.hour == 10 && t.min == 00 && t.sec == 15) {
-//  turnRelayOnAndOff(Relay_1);
-//}
-//
-//if(t.hour == 10 && t.min == 00 && t.sec == 30) {
-//  turnRelayOnAndOff(Relay_2);
-//}
-//
-//if(t.hour == 10 && t.min == 00 && t.sec == 45) {
-//  turnRelayOnAndOff(Relay_3);
-//}
-//
-//if(t.hour == 10 && t.min == 01 && t.sec == 00) {
-//  turnRelayOnAndOff(Relay_4);
-//}
-
+  delay (2000);
+  turnRelayOn(2, "relay");
   // Wait one second before repeating :)
   delay (1000);
+  turnRelayOff(2, "relay");
+  delay (2000);

-  // Method 1:
-  // check each address individually for an alarm condition
-  checkTemp(insideThermometer);
-
+//  t = rtc.getTimeStr();
+
+  Serial.println(rtc.getTimeStr());
+
+//  checkTemp(insideThermometer);
 }

 void checkTemp(DeviceAddress deviceAddress) {
   sensors.requestTemperatures(); // Send the command to get temperatures
   Serial.println(sensors.getTempCByIndex(0));
   if (sensors.getTempCByIndex(0) >= upperTempLimit) {
-    Serial.print("ALARM!! turning relay off: ");
-    turnRelayOff(Relay_1, "Heater relay");
+    Serial.print("ALARM!! turning heater off.");
+    turnRelayOff(relay_1, relay_1_name);
   } else if (sensors.getTempCByIndex(0) <= lowerTempLimit) {
-    Serial.print("ALARM!! turning relay on: ");
-    turnRelayOn(Relay_1, "Heater relay");
+    Serial.print("ALARM!! turning heater on.");
+    turnRelayOn(relay_1, relay_1_name);
   }
 }

 void turnRelayOn(int relay_num, String relay_name) {
   Serial.print(relay_name + " ON");
   Serial.println("");
-  digitalWrite(relay_num, RELAY_ON);// set the Relay ON
+  digitalWrite(relay_num, HIGH);// set the Relay ON
 }

 void turnRelayOff(int relay_num, String relay_name) {
-  digitalWrite(relay_num, RELAY_OFF);// set the Relay OFF
+  digitalWrite(relay_num, LOW);// set the Relay OFF
   Serial.print(relay_name + " OFF");
   Serial.println("");
 }
+
+Time getCurrentTime() {
+  // Need the internet connection for this - from the Raspberry Pi?
+}
+
+void setCurrentTime(int hours, int minutes, int seconds) {
+  rtc.setTime(hours, minutes, seconds);
+}
+


Move sensor reading to seperate function

--- arduinoApp/gardenSketch/gardenSketch.ino
+++ arduinoApp/gardenSketch/gardenSketch.ino
@@ -57,13 +57,15 @@
     prevMillis = curMillis;

     // Read sensor values
-    LDRValue = analogRead(lightSensorPin); // read light level from LDR
-    airHumidity = airSensor.readHumidity(); // read humidity from DHT
-    airTemperature = airSensor.readTemperature(); // read temperature from DHT
-    soilSensor.measure(&soilTemperature, &soilMoisture, &dewpoint);
+    sensorReadings();
   }

 }

-
+void sensorReadings() {
+  LDRValue = analogRead(lightSensorPin); // read light level from LDR
+  airHumidity = airSensor.readHumidity(); // read humidity from DHT sensor
+  airTemperature = airSensor.readTemperature(); // read temperature from DHT sensor
+  soilSensor.measure(&soilTemperature, &soilMoisture, &dewpoint); // read temperature and moisture from SHT10 sensor
+}


exchange X/Y axes on joysticks

exchange X/Y axes on joysticks

--- ksp-gegi-microusb/ksp-gegi-microusb.ino
+++ ksp-gegi-microusb/ksp-gegi-microusb.ino
@@ -80,10 +80,10 @@
 analogInPin analogInPins[] = {
   analogInPin(0,A6,2),  // throttle
   analogInPin(1,A8,5),	// timewarp
-  analogInPin(2,A0,2),	// joy1x
-  analogInPin(3,A1,2),	// joy1y
-  analogInPin(4,A2,2),	// joy2x
-  analogInPin(5,A3,2),	// joy2y
+  analogInPin(2,A1,2),	// joy1x
+  analogInPin(3,A0,2),	// joy1y
+  analogInPin(4,A3,2),	// joy2x
+  analogInPin(5,A2,2),	// joy2y
 };

 analogInPin::analogInPin(const uint8_t id, const uint8_t pin, const int threshold) :


performance fix, wall collision detection

--- ray-gfx.ino
+++ ray-gfx.ino
@@ -91,6 +91,7 @@
 void rotatePlayer(Player *player, uint8_t right);
 void movePlayer(Player *player);
 void drawDottedLine(int16_t x, int16_t y0, int16_t y1);
+void drawLine(int16_t x, int16_t y0, int16_t y1);

 void setup()  {
   D(Serial.begin(9600));
@@ -137,13 +138,13 @@
     double nextStepX = player->dirX * STEP_SIZE;
     double nextStepY = player->dirY * STEP_SIZE;

-   // if (pgm_read_byte(&level_map[int(player->y)][int(player->x + nextStepX)])) {
+  if (pgm_read_byte(&level_map[int(player->y)][int(player->x + nextStepX)]) == 0) {
       player->x += nextStepX;
-   // }
-
-   // if (pgm_read_byte(&level_map[int(player->y + nextStepY)][int(player->x)])) {
+   }
+
+  if (pgm_read_byte(&level_map[int(player->y + nextStepY)][int(player->x)]) == 0) {
       player->y += nextStepY;
-   // }
+   }
     // D(Serial.print("palyer x,y"));
     // D(Serial.print(player->x));
     // D(Serial.print(","));
@@ -168,6 +169,12 @@
   }
 }

+void drawLine(int16_t x, int16_t y0, int16_t y1) {
+  while (y0>=y1) {
+    display.drawPixel(x, y0, WHITE);
+    y0--;
+  }
+}

 void drawDottedLine(int16_t x, int16_t y0, int16_t y1) {
   uint16_t color = BLACK;
@@ -177,7 +184,6 @@
     i ? color=WHITE:color=BLACK;
     display.drawPixel(x, y0, color);
   }
-
 }

 void drawWallLine(uint8_t x, uint8_t h, uint8_t side) {


added timestamp. couldnt find dynamic filename function. removed some legacy code. converted main loop to only write once.

--- Calibration/liveCode/overclockAccel/overclockAccel.ino
+++ Calibration/liveCode/overclockAccel/overclockAccel.ino
@@ -18,7 +18,6 @@
 sensors_event_t accel_event;
 sensors_vec_t   orientation;
 //data buffer for the accel and orientation readings
-//char dataArray[80];
 String dataString;

 void initAccel()


Get ready for mesh

Get ready for mesh

--- arduino/rfglow_esp32/rfglow_esp32.ino
+++ arduino/rfglow_esp32/rfglow_esp32.ino
@@ -4,6 +4,9 @@
 #include "ble.h"

 #include <driver/i2c.h>
+
+// #include <painlessMesh.h>
+// painlessMesh  mesh;

 void setup() {
   setCpuFrequencyMhz(80);


Can now exit settings screen without immediately starting game.

--- arduboy-game/arduboy-game.ino
+++ arduboy-game/arduboy-game.ino
@@ -51,7 +51,7 @@
 byte titleScreen() {
   byte selectedItem = TITLE_PLAY_GAME;
   unsigned short totalDelay = 0;
-  long lastDebounceTime = 0;  // the last time the button was pressed
+  long lastDebounceTime = millis();  // the last time the button was pressed

   arduboy.clear();
   printText("TITLE", 25, 20, 2);
@@ -64,7 +64,11 @@

   while (totalDelay < ATTRACT_MODE_TIMEOUT) {
     if (arduboy.pressed(A_BUTTON) || arduboy.pressed(B_BUTTON)) {
-      break;
+      if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY) {
+        break;
+      } else {
+        lastDebounceTime = millis();
+      }
     }

     if (arduboy.pressed(LEFT_BUTTON)) {
@@ -292,7 +296,7 @@
   score = 0;
   spaceShip.reset();
   // Random test to set score
-  unsigned int randomScore = 5000;//random(65000, 99999);
+  unsigned int randomScore = 1000;//random(65000, 99999);

   // Loop to simulate a game that ends with score being
   // close to value of randomScore


`Sketch uses 28,670 bytes (99%) of program storage space. Maximum is 28,672 bytes.`

--- arduboy-game/arduboy-game.ino
+++ arduboy-game/arduboy-game.ino
@@ -80,7 +80,7 @@
 char textBuf[23];

 void playMusic(byte song) {
-  return; // SIMON
+//  return; // SIMON
     if (! soundOn) {
       return;
     }
@@ -145,6 +145,10 @@
   delay(2750);
 }

+void drawRectAroundPlayMenuOption(byte color) {
+  arduboy.drawRect(2, 48, 28, 12, color);
+}
+
 byte titleScreen() {
   byte selectedItem = TITLE_PLAY_GAME;
   unsigned long totalDelay = 0;
@@ -154,7 +158,7 @@
   arduboy.clear();
 //  arduboy.drawRect(0,0,128,64,1);
   //drawBitmap(4, 14, title, 0);
-  drawBitmap(4, 16, title_letter_e, 0);
+  drawBitmap(4,  16, title_letter_e, 0);
   drawBitmap(20, 16, title_letter_v, 0);
   drawBitmap(39, 16, title_letter_a, 0);
   drawBitmap(59, 16, title_letter_d, 0);
@@ -166,7 +170,8 @@
   drawChrs(4, 51, titleScreenText1, 30);
   drawChrs(34, 51, titleScreenText2, 30);
   drawChrs(79, 51, titleScreenText3, 30);
-  arduboy.drawRect(2, 48, 28, 12, 1);
+//  arduboy.drawRect(2, 48, 28, 12, 1);
+  drawRectAroundPlayMenuOption(1);
   arduboy.display();

 //  playMusic(5);
@@ -203,17 +208,20 @@
         selectedItem = titleMenuRightButton(selectedItem);
         lastDebounceTime = currentMilliseconds; //set the current time
         delay(250);
-
       }
     }

     totalDelay ++;
-
-  }
-  arduboy.tunes.stopScore();
+  }
+  playMusic(99);

   return (totalDelay >= ATTRACT_MODE_TIMEOUT ? TITLE_TIMEOUT : selectedItem);
+}
+
+
+void drawRectAroundSettingsMenuOption(byte color) {
+  arduboy.drawRect(32, 48, 42, 12, color);
 }

 byte titleMenuLeftButton(byte selectedItem) {
@@ -225,14 +233,18 @@
   switch (selectedItem) {
     case TITLE_SETTINGS:
       arduboy.drawRect(77, 48, 50, 12, 0);
-      arduboy.drawRect(32, 48, 42, 12, 1);
+//      arduboy.drawRect(32, 48, 42, 12, 1);
+      drawRectAroundSettingsMenuOption(1);
       arduboy.display();
       return TITLE_CREDITS;
       break;

     case TITLE_CREDITS:
-      arduboy.drawRect(32, 48, 42, 12, 0);
-      arduboy.drawRect(2, 48, 28, 12, 1);
+      drawRectAroundSettingsMenuOption(0);
+//      arduboy.drawRect(32, 48, 42, 12, 0);
+//      arduboy.drawRect(2, 48, 28, 12, 1);
+      drawRectAroundPlayMenuOption(1);
+
       arduboy.display();
       return  TITLE_PLAY_GAME;
       break;
@@ -247,10 +259,14 @@
      to navigate through main menu
      items.
   */
+
   switch (selectedItem) {
     case TITLE_PLAY_GAME:
-      arduboy.drawRect(2, 48, 28, 12, 0);
-      arduboy.drawRect(32, 48, 42, 12, 1);
+//      arduboy.drawRect(2, 48, 28, 12, 0);
+      drawRectAroundPlayMenuOption(0);
+
+//      arduboy.drawRect(32, 48, 42, 12, 1);
+      drawRectAroundSettingsMenuOption(1);
       arduboy.display();
       return TITLE_CREDITS;
       break;
@@ -529,32 +545,32 @@
     // This logic seems way too nested and can probably be simplified a little. :) -- JG
     if (!isBossAlive) {
       if ((score >= 5000ul + (currentIteration * 20000ul)) && (spawnedBoss < 1)) {
-        if (!enemiesAlive) {
+        if (isBossAlive = stopSpawningEnemies = !enemiesAlive) {
           boss.set(129, 28, 128);
           spawnedBoss = 1;
-          isBossAlive = true;
+//          isBossAlive = true;
         }
-        else {
-          stopSpawningEnemies = true;
-        }
+//        else {
+//          stopSpawningEnemies = true;
+//        }
       } else if ((score >= (12000ul + (currentIteration * 20000ul))) && (spawnedBoss < 2)) {
-        if (!enemiesAlive) {
+        if (isBossAlive = stopSpawningEnemies = !enemiesAlive) {
           boss.set(129, 24, 129);
           spawnedBoss = 2;
-          isBossAlive = true;
+//          isBossAlive = true;
         }
-        else {
-          stopSpawningEnemies = true;
-        }
+//        else {
+//          stopSpawningEnemies = true;
+//        }
       } else if ((score >= (20000ul + (currentIteration * 20000ul))) && (spawnedBoss < 3)) {
-        if (!enemiesAlive) {
+        if (isBossAlive = stopSpawningEnemies =!enemiesAlive) {
           boss.set(129, 10, 130);
           spawnedBoss = 3;
-          isBossAlive = true;
+//          isBossAlive = true;
         }
-        else {
-          stopSpawningEnemies = true;
-        }
+//        else {
+//          stopSpawningEnemies = true;
+//        }
       }
     }

@@ -613,7 +629,7 @@

 void drawGunTemp() {
   arduboy.drawRect(40, 1, 40, 5, 1);
-  arduboy.fillRect(40, 1, (playerGunCharge >= MAX_GUN_CHARGE ? MAX_GUN_CHARGE : playerGunCharge), 5, 1);
+  arduboy.fillRect(40, 1, (playerGunCharge), 5, 1);
 }

 void drawScore() {
@@ -832,7 +848,7 @@
 }

 void playerWinsScreen() {
-  arduboy.tunes.stopScore();
+  playMusic(99);
   arduboy.clear();

   // Temp
@@ -851,8 +867,8 @@
   arduboy.tunes.stopScore();
   arduboy.clear();

-  drawBitmap(0, 23, gameOver, 0);
-  arduboy.drawFastHLine(0, 63, 128, 1);
+//  drawBitmap(0, 23, gameOver, 0);
+//  arduboy.drawFastHLine(0, 63, 128, 1);

   printText("GAME", 50, 5, 3);
   printText("OVER", 50, 33, 3);


memory efficency

memory efficency

--- led_subsystem.ino
+++ led_subsystem.ino
@@ -11,11 +11,13 @@
 ThreadHandler led_thread_handler = ThreadHandler();

 void led_man_queue() {
-	 led_thread_handler.queue(new Animation_Seasonal_Winter_Snow());
-	//led_thread_handler.queue();
+	led_thread_handler.queue(new Animation_Static_DeskDimAmbient());
+	led_thread_handler.queue(new Animation_Seasonal_Winter_Snow_Win1());
+	led_thread_handler.queue(new Animation_Seasonal_Winter_Snow_Win2());
+	led_thread_handler.queue(new Animation_Seasonal_Winter_Snow_Win3());

-	Serial.println("----------------------");
-	Serial.println("Manual Queue:");
+	Serial.println(F("----------------------"));
+	Serial.println(F("Manual Queue:"));

 	std::vector<Thread*> t = led_thread_handler.listThreads();
 	for (unsigned int a = 0; a < t.size(); a++) {
@@ -24,7 +26,7 @@
 		Serial.println(name);
 	}

-	Serial.println("----------------------");
+	Serial.println(F("----------------------"));
 }

 void led_main_loop() {


switch to IRQ controlled LED

switch to IRQ controlled LED

--- btnLed/src/sketch.ino
+++ btnLed/src/sketch.ino
@@ -9,29 +9,43 @@
 */

 #define pushbuttonPIN 2
-#define onoffLED 3
+#define onoffPIN 3

-boolean flag = LOW;
+volatile int flag = LOW;

 void setup()
 {
   pinMode(onoffLED, OUTPUT);       // An LED to signal on or off state
-  pinMode(pushbuttonPIN, INPUT);  // A button to switch the LED
+  attachInterrupt(0, ISRbutton, RISING); // Interrupt when button is pressed
+  //pinMode(pushbuttonPIN, INPUT);  // A button to switch the LED
 }

 void loop()
 {
+  digitalWrite(onoffPIN, flag);
   // wait for a button press
+/*
   if ((digitalRead(pushbuttonPIN) == HIGH) && (flag == LOW))
   {
+    flag = HIGH;
     digitalWrite(onoffLED, HIGH);
-    delay(20);
+    delay(500);
     //digitalWrite(onoffLED,LOW);
   }
   if ((digitalRead(pushbuttonPIN) == HIGH) && (flag == HIGH))
   {
+    flag = LOW;
     digitalWrite(onoffLED, LOW);
-    delay(20);
+    delay(500);
     //digitalWrite(onoffLED,LOW);
   }
+*/
 }
+
+
+// toggles LED when interrupt pin changes state
+
+void ISRbutton()
+{
+  flag = !flag;
+}


methode mesure temps achevé pret pour le MERGE!!!

--- calibrateur.ino
+++ calibrateur.ino
@@ -45,20 +45,20 @@
 #include "potar.h"

 //------------------------------------------------------------------------------
-#define DELTA 150
+#define DELTA 150 // en servo unit (en microseconde de servo)
 #define TEMPOSLEEP 1000
 //en ms le temps d'etre sur que le servo ait bougé
 //d'un increment quand on fait les mesure à la roue codeuse
 #define PINVOIEB 3 //la pin surlaquelle est branché la voie B
 #define ERREURCOMPTAGE 6 //la tolérance de comptage avant que l'on estime que le servo est arrivé au bout
 #define NBRCYCLE_AR 10 //nbre de cycle d'aller et retour pour la fin des mesure de caractérisation et nbr de cycle pour la mesure des PWMIN et PWMMAX
-#define TEMPO_STAT 100 // tempo pour laisser le servo avancer lors des mesures
+#define TEMPO_STAT 50 // tempo pour laisser le servo avancer lors des mesures
                        // statistique à la fin de la calibration ATTENTION 100ms semble etre trop court!!!!
 #define DEP_MINI_STAT 5  //correspond au déplacement minimum en nombre d'impulsion que doit faire le servo pour
 						//considérer qu'il n' pas encore atteint sa fin de course et que l'on peut laisser le chronometre en
 						//route (pour mesure de vitesse réeel du servo en °/s)
 #define ADRESSE_EEPROM 42//position de leeprom ou la valeur de reglage de vitesse est stocké
-#define VITESSEMAXSERVO 2000 // vitesse max d'un servo en microsecond de PWM par seconde
+#define VITESSEMAXSERVO 4000 // vitesse max d'un servo en microsecond de PWM par seconde
 //cette vitesse doit imperativement etre superieure à la vitesse que
 //peut physiquement atteindre le servo afin que les mesrues de vitesse physique en fin de calibration USB soient justes.
 //Par conttre dans la sequense sweep to min sweep to max cette valeur conduit a
@@ -387,27 +387,13 @@
                     leServo.setObjectif(leServo.getMin());

                     //----------------------------------------------------------
-                    //séquence pour mesurer une vitesse et amplitude moyenne
+                    //séquence pour mesurer une vitesse
                     //(10 cycles d'aller et retour de min à max
                     //et enregistrement systématique des mesures)
+					//chaque cycle s'arrete quand le servo atteint amplitude moyenne à DEP_MIN_STAT près
                     for (i=0;i<NBRCYCLE_AR;i=i+1)
                         {
                             compteur=0;
-                            compteurRef=0;
-                            //compteur ref utilisé différement dans la suite
-                            //par rapport à ce qui était fait jusque là. Compteur
-                            //ref est utilisé pour voir si le servo continue
-                            //de bouger
-
-							//séquence suivante permet d'éviter que l'ensemble des mesures s'envoient en l'air
-							// si trop d'inertie dans le servo et qu'il a à peine le temps de bouger et que l'on à arreté la mesure précédente
-							sleep(3*TEMPO_STAT);
-							while (compteur!=0)
-							{
-								compteur=0;
-								sleep(3*TEMPO_STAT);
-							}
-
                             tempsMesureVitesse=millis();
                             Serial.print("tempsMesureVitesse=");
                             Serial.println(tempsMesureVitesse);
@@ -415,34 +401,22 @@
                             leServo.setObjectif(leServo.getMax());
                             sleep(TEMPO_STAT);
                             Serial.print("cmpt="); Serial.println(compteur);
-                            while (abs(compteur)>abs(compteurRef)+DEP_MINI_STAT)
+                            while (abs(compteur)<abs(amplitude)-DEP_MINI_STAT)
                                 {
-                                    compteurRef=compteur;
                                     Serial.print("yop");
                                     Serial.print(" cmpt=");
                                     Serial.println(compteur);
                                     sleep(TEMPO_STAT);
                                 }
-                            resultatImpulsionMax[i]=compteur;
+
                             resultatTempsMax[i]=millis()-tempsMesureVitesse-\
                                                     TEMPO_STAT;
                             Serial.print(F("Cycle ")); Serial.print(i);
-                            Serial.print(F(" imp= ")); Serial.print(resultatImpulsionMax[i]);
+
                             Serial.print(F(" temps= ")); Serial.println(resultatTempsMax[i]);

                             compteur=0;
-                            compteurRef=0;
-							//séquence suivante permet d'éviter que l'ensemble des mesures s'envoient en l'air
-							// si trop d'inertie dans le servo et qu'il a à peine le temps de bouger et que l'on à arreté la mesure précédente
-							sleep(3*TEMPO_STAT);
-							while (compteur!=0)
-							{
-								compteur=0;
-								sleep(3*TEMPO_STAT);
-							}
-
-
-
+
                             tempsMesureVitesse=millis();
                             // Mesure de max vers min
                              Serial.print("tempsMesureVitesse=");
@@ -450,7 +424,7 @@
                             leServo.setObjectif(leServo.getMin());
                             sleep(TEMPO_STAT);
                             Serial.print("cmpt="); Serial.println(compteur);
-                            while (compteur<amplitude-DEP_MINI_STAT)
+                            while (abs(compteur)<abs(amplitude)-DEP_MINI_STAT)
                                 {
                                     compteurRef=compteur;
                                     Serial.print("yup ");
@@ -458,12 +432,11 @@
                                     Serial.println(compteur);
                                     sleep(TEMPO_STAT);
                                 }
-                            resultatImpulsionMin[i]=compteur;
+
                             resultatTempsMin[i]=millis()-tempsMesureVitesse-TEMPO_STAT;
                             Serial.print(F("Cycle "));
                             Serial.print(i);
-                            Serial.print(F(" imp= "));
-                            Serial.print(resultatImpulsionMin[i]);
+
                             Serial.print(F(" temps= "));
                             Serial.println(resultatTempsMin[i]);
 							Serial.println();


[refactored] main arduino file

[refactored] main arduino file

--- arduino_sketches/PGA309/testPin_I2C/testPin_I2C.ino
+++ arduino_sketches/PGA309/testPin_I2C/testPin_I2C.ino
@@ -8,31 +8,56 @@
 #define REG4 0xE300
 #define REG6 0x0600

+void WriteToMultiRegisters(int pregData[], int pregToWriteTo[], int size);
+void ReadFromMultRegisters(int pregToReadFrom[], int size);
+
 PGA309 pga(PGA309ADDR);
+
+int regData[] = {REG3, REG4, REG6};
+int regToWriteTo[] = {0x03, 0x04, 0x06};
+int regToReadFrom[] = {0x03, 0x04, 0x06, 0x08};

 void setup() {
 	Serial.begin(9600);
 	Wire.begin();
-	byte data[2];
+

 	//Setting the test pin high enables direct writing of internal registers and stops transactions with External EEPROM
 	pga.enableTestPin();
-	Serial.print("Status of writing to the PGA309 internal register 3: ");
-	Serial.println(pga.writePGA309Register(0x03, REG3));
-	delay(10);
-	Serial.print("Status of writing to the PGA309 internal register 4: ");
-	Serial.println(pga.writePGA309Register(0x04, REG4));
-	delay(10);
-	Serial.print("Status of writing to the PGA309 internal register 6: ");
-	Serial.println(pga.writePGA309Register(0x06, REG6));
-	delay(10);
+
+	WriteToMultiRegisters(regData, regToWriteTo, (sizeof(regData)/sizeof(int)));
+	ReadFromMultRegisters(regToReadFrom, (sizeof(regToReadFrom)/sizeof(int)));
+}
+
+void loop() {
+}
+
+//======================================================
+// Helper functions
+void WriteToMultiRegisters(int pregData[], int pregToWriteTo[], int size){
+	for (int i = 0; i < size; i++){
+		Serial.print("Status of writing to the PGA309 internal register ");
+		Serial.print(pregToWriteTo[i]);
+		Serial.print(": ");
+		Serial.println(pga.writePGA309Register(pregToWriteTo[i], pregData[i]));
+		delay(5);
+	}
+}
+
+void ReadFromMultRegisters(int pregToReadFrom[], int size){
 	int testdata;
-	testdata = pga.readPGA309Register(0x03);
+	byte data[2];
+	for (int i = 0; i < size; i++){
+	testdata = pga.readPGA309Register(pregToReadFrom[i]);
 	if (testdata != 0){
-		Serial.print("There was error while reading: ");
+		Serial.print("There was error while reading data from register ");
+		Serial.print(pregToReadFrom[i]);
+		Serial.print(": ");
 		Serial.println(testdata);
 	} else {
-		Serial.print("Successfully read data from the register. Data: ");
+		Serial.print("Successfully read data from the register ");
+		Serial.print(pregToReadFrom[i]);
+		Serial.print(". Data: ");
 		pga.getRecData(data);
 		for (int i = 1; i >= 0 ; i--){
 			Serial.print(pga.binaryFormat(data[i],8));
@@ -40,47 +65,6 @@
 		}
 		Serial.println();
 	}
-	testdata = pga.readPGA309Register(0x04);
-	if (testdata != 0){
-		Serial.print("There was error while reading: ");
-		Serial.println(testdata);
-	} else {
-		Serial.print("Successfully read data from the register. Data: ");
-		pga.getRecData(data);
-		for (int i = 1; i >= 0 ; i--){
-			Serial.print(pga.binaryFormat(data[i],8));
-			Serial.print(" ");
-		}
-		Serial.println();
+		delay(5);
 	}
-	testdata = pga.readPGA309Register(0x06);
-	if (testdata != 0){
-		Serial.print("There was error while reading: ");
-		Serial.println(testdata);
-	} else {
-		Serial.print("Successfully read data from the register. Data: ");
-		pga.getRecData(data);
-		for (int i = 1; i >= 0 ; i--){
-			Serial.print(pga.binaryFormat(data[i],8));
-			Serial.print(" ");
-		}
-		Serial.println();
-	}
-	testdata = pga.readPGA309Register(0x08);
-	if (testdata != 0){
-		Serial.print("There was error while reading: ");
-		Serial.println(testdata);
-	} else {
-		Serial.print("Successfully read data from the register. Data: ");
-		pga.getRecData(data);
-		for (int i = 1; i >= 0 ; i--){
-			Serial.print(pga.binaryFormat(data[i],8));
-			Serial.print(" ");
-		}
-		Serial.println();
-	}
-
-}
-
-void loop() {
-}
+}


Added reset feature.

Added reset feature.

--- simon_says/simon_says.ino
+++ simon_says/simon_says.ino
@@ -5,7 +5,7 @@
  * License: MIT
  */

-// TODO Reset game in the middle of a game.
+// TODO Expand function comments.

 // Turn debug mode on or off.
 const boolean DEBUG = true;
@@ -74,7 +74,8 @@
     // Begin the game.
     playGame(pattern);

-    // The game is over, so turn off all lights and reset the game.
+    // The game is over; turn off all lights and reset.
+    delay(LIGHT_DELAY);
     for (int i = 0; i < QTY; i++) {
         digitalWrite(LEDS[i], LOW);
         gameStart = false;
@@ -111,7 +112,7 @@
     // Set game parameters then begin.
     int lives = TOTAL_LIVES;
     int currentLevel = 1;
-    while (lives > 0 && currentLevel < TOTAL_LEVELS) {
+    while (gameStart && lives > 0 && currentLevel < TOTAL_LEVELS) {

         // Display the pattern.
         for (int lvl = 0; lvl < currentLevel; lvl++) {
@@ -128,6 +129,13 @@
         // Check player input.
         if (verifyPlayerInput(pattern, currentLevel)) {

+            // Check for game reset.
+            if (digitalRead(TILT)) {
+                gameStart = false;
+                signalGameChange(1);
+                return;
+            }
+
             // The player was correct; move to the next level.
             currentLevel++;
             delay(GAME_SPEED);
@@ -135,14 +143,14 @@
         // The player was incorrect; subtract a life.
         } else {

-            // Turn on the next red LED.
-            if (lives == TOTAL_LIVES) digitalWrite(RED_1, HIGH);
-            else if (lives == TOTAL_LIVES - 1) digitalWrite(RED_2, HIGH);
-            else if (lives == TOTAL_LIVES - 2) digitalWrite(RED_3, HIGH);
-            delay(LIGHT_DELAY);
-
             // Remove a life from the current total.
             lives--;
+
+            // Turn on the next red LED.
+            if (lives == TOTAL_LIVES - 1) digitalWrite(RED_1, HIGH);
+            else if (lives == TOTAL_LIVES - 2) digitalWrite(RED_2, HIGH);
+            else if (lives == TOTAL_LIVES - 3) digitalWrite(RED_3, HIGH);
+            delay(LIGHT_DELAY);
         }
     }
 }
@@ -169,8 +177,12 @@
         digitalWrite(LEDS[i], HIGH);
         digitalWrite(LEDS[last], HIGH);

-        // Check the switches for a new game.
-        if (signalGameStart()) return;
+        // Check the tilt switch and buttons for a new game.
+        if (digitalRead(TILT) || analogRead(BUTTONS) > 3) {
+            gameStart = true;
+            signalGameChange(2);
+            return;
+        }

         // Wait before cycling the next set of lights.
         delay(LIGHT_DELAY);
@@ -183,36 +195,21 @@

 /**
- * Checks the switches and determines if the game should start.
- */
-boolean signalGameStart() {
-
-    // Check the tilt switch and buttons for a new game.
-    if (digitalRead(TILT) || (!gameStart && analogRead(BUTTONS) > 3)) {
-        gameStart = true;
-    }
-
-    // Flash all LEDs to signal game start if appropriate.
-    if (gameStart) {
-
-        // Blink all lights twice.
-        for (int j = 0; j < 2; j++) {
-            for (int k = 0; k < QTY; k++) {
-                digitalWrite(LEDS[k], HIGH);
-            }
-            delay(LIGHT_DELAY);
-            for (int k = 0; k < QTY; k++) {
-                digitalWrite(LEDS[k], LOW);
-            }
-            delay(LIGHT_DELAY * 2);
-        }
-
-        // Signal game start.
-        return true;
-    }
-
-    // The game has not begun.
-    return false;
+ * Blinks all LEDs to signal a change in game state.
+ */
+void signalGameChange(int blinks) {
+
+    // Blink all LEDs to signal a change in game state.
+    for (int j = 0; j < blinks; j++) {
+        for (int k = 0; k < QTY; k++) {
+            digitalWrite(LEDS[k], HIGH);
+        }
+        delay(LIGHT_DELAY);
+        for (int k = 0; k < QTY; k++) {
+            digitalWrite(LEDS[k], LOW);
+        }
+        delay(LIGHT_DELAY * 2);
+    }
 }

@@ -228,6 +225,11 @@
         // Wait for a button press.
         int simonLed = -1;
         while (simonLed == -1) {
+
+            // Check for game reset.
+            if (digitalRead(TILT)) return true;
+
+            // Check for a button press.
             simonLed = getSimonLed(analogRead(BUTTONS));
         }

@@ -241,6 +243,6 @@
         else return false;
     }

-    // The player successfully matched the pattern.
+    // The player successfully matched the entire pattern.
     return true;
 }


Remove wrong comment

Remove wrong comment

--- cirkit_unit03_driver/arduino/steer_ctrl/steer_ctrl.ino
+++ cirkit_unit03_driver/arduino/steer_ctrl/steer_ctrl.ino
@@ -34,7 +34,6 @@
 /* Define pulse width time of the stepping motor. */
 #define PULSE_WIDTH_MICRO_SECOND 500

-/* Define direction of angular z. */
 enum {
   LEFT,
   RIGHT,
@@ -85,7 +84,6 @@
   if (msg.angular.z < 0 && time > 50) gen_pluse(LEFT, time); // Minus mean CCW or right.
   else if (msg.angular.z > 0 && time > 50) gen_pluse(RIGHT, time); // Plus mean CW or left.
   else gen_pluse(KEEP, 0); // Zero mean keep steer.
-  /* move task */
 }

 /**


bugfix

bugfix

--- tokens-firmware/Prototype#2/pawn/pawn.ino
+++ tokens-firmware/Prototype#2/pawn/pawn.ino
@@ -74,17 +74,18 @@
 int face1 = 0;

 // BOARD CONSTANTS
-#define ACC_INT1_PIN 4 // Pin where the acceleromter interrupt1 is connected
+#define ACC_INT1_PIN        4 // Pin where the acceleromter interrupt1 is connected
 #define VIBRATING_M_PIN     3 // Pin where the vibrating motor is connected

 // Initiation of the objects
 TokenFeedback tokenFeedback = TokenFeedback(VIBRATING_M_PIN); // Connected on pin 2
 TokenConstraintEvent tokenConstraint = TokenConstraintEvent();
 TokenSoloEvent tokenSolo = TokenSoloEvent(ACC_INT1_PIN); // Connected on pin 4
-TokenTokenEvent tokenToken = TokenTokenEvent();
+//TokenTokenEvent tokenToken = TokenTokenEvent();

 void setup(void)
 {
+  //
   Serial.begin(9600);

   // Enable interrupts :
@@ -97,13 +98,13 @@
   tokenSolo.accelConfig();

   // Config of the capacitive sensor
-  tokenToken.capConfig();
+  //tokenToken.capConfig();

   // Config of the LED matrix
   tokenFeedback.matrixConfig();

   // Configure the RFduino BLE properties
-  RFduinoBLE.deviceName = "RFduino";
+  RFduinoBLE.deviceName = "Any_PAWN";
   RFduinoBLE.txPowerLevel = -20;

   // Start the BLE stack
@@ -152,12 +153,12 @@
     }

 /************************************************************/
- /*   // Sector detection if the token is on the board
-    if (inactivity)
+    // Sector detection if the token is on the board
+    if (inactivity) //change true with inactivity when accelerometer is connected
     {
       tokenConstraint.rgb_sensor.getData();
     }
-    //Serial.println(tokenConstraint.rgb_sensor.ct);
+    Serial.println(tokenConstraint.rgb_sensor.ct);

     // Location of the pawn in function of the color temperature (ct)
     current_sector_ID = tokenConstraint.locate(current_sector_ID, tokenConstraint.rgb_sensor.ct);
@@ -169,13 +170,16 @@
         sendData[1] = current_sector_ID;
         sendData[2] = last_sector_ID;
         RFduinoBLE.send((char*) sendData, 3);
+
+        if(current_sector_ID==8)
+          tokenFeedback.displaySmile();

         // Update sector_ID variables
         last_sector_ID = current_sector_ID;
     }

 /************************************************************/
-    // Detection of the token token event
+/*    // Detection of the token token event
     tokenToken.capTestProximity(&face1);
     if(face1==1)
     {


Removed some empty lines

Removed some empty lines

--- gcn_controller_v5/gcn_controller_v5.ino
+++ gcn_controller_v5/gcn_controller_v5.ino
@@ -444,14 +444,12 @@
               for (uint8_t innerLoopMetadataIndex = 0; innerLoopMetadataIndex < sizeof(inner_loop_metadata[macroMetadataIndex]); innerLoopMetadataIndex++) {
                 Serial.write(inner_loop_metadata[macroMetadataIndex][innerLoopMetadataIndex]);
               }
-
               if (inner_loop_metadata[macroMetadataIndex][2] < inner_loop_metadata[macroMetadataIndex][6]) {
                 // Current input index is lower than starting index, fix this
                 // Current input index for current inner loop is below what it is supposed to be, fix that!
                 inner_loop_metadata[macroMetadataIndex][2] = inner_loop_metadata[macroMetadataIndex][6];
                 currentMacroIndexRunning = inner_loop_metadata[macroMetadataIndex][6];
               }
-
               if (inner_loop_metadata[macroMetadataIndex][2] >= inner_loop_metadata[macroMetadataIndex][6] && inner_loop_metadata[macroMetadataIndex][2] <= inner_loop_metadata[macroMetadataIndex][7]) {
                 // Current input index is valid
                 // Current input index for current inner loop is in the valid range!


initial acs714 current sensor support

initial acs714 current sensor support

--- src/analog_sensors_board.ino
+++ src/analog_sensors_board.ino
@@ -39,19 +39,20 @@
 //	measured using AREF when the shield is in place and
 //	the Arduino is powered by external power with vehicle

-#define ADC_INTERNAL_V 	0.002483f	// was 0.002502f
-#define ADC_INTERNAL_MV 2.483f		// was 2.502f
-#define ADC_DEFAULT_V 0.004887f
-#define ADC_DEFAULT_MV 4.887f
-
-#define BAT_R1 24000.0f
-#define BAT_R2 2200.0f
-
-#define LM35_MVC 10.0f
+#define ADC_INTERNAL_V 	0.002483f	// manual calibration (was 0.002502f)
+#define ADC_INTERNAL_MV 2.483f		// manual calibration (was 2.502f)
+#define ADC_DEFAULT_V 0.004887f		// uncalibrated
+#define ADC_DEFAULT_MV 4.887f		// uncalibrated
+
+#define BAT_R1 24000.0f 		// R1 (ohm)
+#define BAT_R2 2200.0f 			// R2 (ohm)
+
+#define LM35_MVC 10.0f			// mV/C
+#define ACS714_MVA 185.0f 		// mv/A

 #define BMP085_ADDRESS 0x77		// I2C address
 #define BMP085_OSS 0 			// Oversampling Setting
-#define BMP_MAX 1000 			// endless loop protection
+#define BMP_MAX 1000 			// Loop protection (number of loops)

 // ** LM35 Analog Temperature Sensor
 // 	[1]: http://learn.adafruit.com/tmp36-temperature-sensor
@@ -69,6 +70,8 @@
 //  [8]: http://forum.arduino.cc/index.php?topic=128717.0
 //  [9]: http://www.nongnu.org/avr-libc/user-manual/group__avr__watchdog.html

+const int ACS_ZERO = (int) 2500 / ADC_INTERNAL_MV;	// ADC reading for 2.5V (~ 1007)
+const float ACS_CONV = ADC_INTERNAL_MV / ACS714_MVA	// Amps per ADC level
 const float BAT_RK = (BAT_R1 + BAT_R2) / BAT_R2;

 unsigned long time_iq;
@@ -107,6 +110,13 @@
 long b5;

+// ACS714 current sensor
+//	working in reverse current flow to keep output signal within 0-2.5V range
+//	2.5V output is the steady 0A initial reading
+float acs0;
+int raw_acs0;
+
+
 // the setup routine runs once when you press reset:
 void setup() {
 	// disable watchdog, because of [8]
@@ -146,6 +156,17 @@
 	// start acquisition (with double readings to avoid interferences [1])
 	digitalWrite(LED_PIN, HIGH);

+	// current sensor
+	raw_acs0 = analogRead(A11);		// J5 (pin 2)
+	raw_acs0 = analogRead(A11);		// J5 (pin 2)
+
+	// calculate output is Amps
+	acs0 = (float) (ACS_ZERO - raw_acs0) * ACS714_CONV;
+
+	// send current report
+	report_current();
+
+
 	// acquisition loop delta
 	delta = millis() - time_iq;

@@ -185,14 +206,14 @@
 		raw_tm2 = analogRead(A8);		// J6 (pin 2)
 		raw_tm2 = analogRead(A8);		// J6 (pin 2)

-		raw_tm3 = analogRead(A11);		// J5 (pin 2)
-		raw_tm3 = analogRead(A11);		// J5 (pin 2)
+		//raw_tm3 = analogRead(A11);		// J5 (pin 2)
+		//raw_tm3 = analogRead(A11);		// J5 (pin 2)

 		// lm35 temperature conversion
 		tm0 = (float(raw_tm0) * ADC_INTERNAL_MV) / LM35_MVC;
 		tm1 = (float(raw_tm1) * ADC_INTERNAL_MV) / LM35_MVC;
 		tm2 = (float(raw_tm2) * ADC_INTERNAL_MV) / LM35_MVC;
-		tm3 = (float(raw_tm3) * ADC_INTERNAL_MV) / LM35_MVC;
+		//tm3 = (float(raw_tm3) * ADC_INTERNAL_MV) / LM35_MVC;

 		// send temperature report
 		report_temperature();
@@ -221,7 +242,6 @@
 		// send humidity report
 		report_humidity();

-
 		// send timestamp
 		Serial.print("$TIME,");
 		Serial.println(time_iq, DEC);
@@ -241,6 +261,13 @@

 	// reset watchdog
 	wdt_reset();
+}
+
+void report_current() {
+	Serial.print("$ACS,");
+	Serial.print(acs0, 4);
+	Serial.print(',');
+	Serial.println(raw_acs0, DEC);
 }

 void report_battery() {


corr. error in SxInterface

corr. error in SxInterface

--- examples/SxInterface/SxInterface.ino
+++ examples/SxInterface/SxInterface.ino
@@ -34,6 +34,8 @@
 #include <SX22Command.h>   // this is the Selectrix Command library

 #define LED_PIN  13   // on most Arduinos there is an LED at pin 13
+#define MAX_SX_CHANNEL   109   // do not read values above 110
+              // because FCC does some "strange" multiplexing

 SX22b sx;                // library
 SX22Command sxcmd;       // holds command data
@@ -127,7 +129,8 @@
 					|| (inputString[0] == 'R')) { // READ command
 				sxcmd.decodeChannel(inputString);
 				if (sxcmd.err == COMMAND_OK) {
-					printSXValue(sxcmd.channel, sxcmd.data);   // send value to serial port
+          int d = sx.get(sxcmd.channel);
+					printSXValue(sxcmd.channel, d);   // send value to serial port
 					toggleLed();  //
 				} else {
 					Serial.println("ERR");
@@ -146,7 +149,7 @@
 void loop() {

 	// check selectrix channels for changes
-	for (int i = 0; i < 112; i++) {
+	for (int i = 0; i <= MAX_SX_CHANNEL; i++) {
 		byte d = sx.get(i);
 		if (oldSx[i] != d) {   // data have changed on SX bus
 			oldSx[i] = d;


modified and added comments to the ConsoleRead.ino example

--- hardware/arduino/avr/libraries/Bridge/examples/ConsoleRead/ConsoleRead.ino
+++ hardware/arduino/avr/libraries/Bridge/examples/ConsoleRead/ConsoleRead.ino
@@ -1,11 +1,12 @@
 /*
- Console.read() example:
- read data coming from bridge using the Console.read() function
+  Console Read example
+
+ Read data coming from bridge using the Console.read() function
  and store it in a string.

- To see the Console, pick your Yun's name and IP address in the Port menu
+ To see the Console, pick your Yún's name and IP address in the Port menu
  then open the Port Monitor. You can also see it by opening a terminal window
- and typing
+ and typing:
  ssh root@ yourYunsName.local 'telnet localhost 6571'
  then pressing enter. When prompted for the password, enter it.

@@ -22,32 +23,32 @@
 String name;

 void setup() {
-  //Initialize Console and wait for port to open:
+  // Initialize Console and wait for port to open:
   Bridge.begin();
   Console.begin();

-  while (!Console){
-    ; // wait for Console port to connect.
-  }
+  // Wait for Console port to connect
+  while (!Console);
+
   Console.println("Hi, what's your name?");
 }

 void loop() {
   if (Console.available() > 0) {
-    char thisChar = Console.read(); //read the next char received
-    //look for the newline character, this is the last character in the string
-    if (thisChar == '\n') {
+    char c = Console.read(); // read the next char received
+    // look for the newline character, this is the last character in the string
+    if (c == '\n') {
       //print text with the name received
       Console.print("Hi ");
       Console.print(name);
       Console.println("! Nice to meet you!");
       Console.println();
-      //Ask again for name and clear the old name
+      // Ask again for name and clear the old name
       Console.println("Hi, what's your name?");
-      name = "";
+      name = "";  // clear the name string
     }
-    else {   //if the buffer is empty Cosole.read returns -1
-      name += thisChar; //thisChar is int, treat him as char and add it to the name string
+    else {  	 // if the buffer is empty Cosole.read() returns -1
+      name += c; // append the read char from Console to the name string
     }
   }
 }


correct enable/disable of NFC chip

correct enable/disable of NFC chip

--- src/src.ino
+++ src/src.ino
@@ -52,7 +52,7 @@
 #define TRELLIS_INT_PIN    1

 // Feather/Wing pin setup
-#define MUSIC_RESET_PIN   12     // VS1053 reset pin (not used!)
+#define MUSIC_RESET_PIN   12     // VS1053 reset pin
 #define CARD_CS_PIN        5     // Card chip select pin
 #define MUSIC_CS_PIN       6     // VS1053 chip select pin (output)
 #define MUSIC_DCS_PIN     10     // VS1053 Data/command select pin (output)
@@ -120,6 +120,9 @@
  ****************************************************/
 void setup() {
   initializeAmplifier();
+  trellis.begin(0x70);
+  trellis.clear();
+  trellis.writeDisplay();

   Serial.begin(14400);
   while (!Serial && millis() < nextIdleTick + 2000);
@@ -202,20 +205,24 @@
 }

 void initializeNfc() {
-  pinMode(MUSIC_RESET_PIN, OUTPUT);
-  digitalWrite(MUSIC_RESET_PIN, HIGH);
+  pinMode(NFC_RESET_PIN, OUTPUT);
+  digitalWrite(NFC_RESET_PIN, HIGH);
   nfc.begin();
   uint32_t versiondata = nfc.getFirmwareVersion();
   if (!versiondata) {
     Serial.println(F("PN532 failed"));
     return;
   }
-
-  // Set the max number of retry attempts to read from a card.
-  // This prevents us from waiting forever for a card, which is the default behaviour of the PN532.
+
+  configNfc();
+  Serial.println(F("PN532 initialized"));
+}
+
+// Set the max number of retry attempts to read from a card.
+// This prevents us from waiting forever for a card, which is the default behaviour of the PN532.
+void configNfc() {
   nfc.setPassiveActivationRetries(1);
-
-  Serial.println(F("PN532 initialized"));
+  nfc.SAMConfig();
 }

 void initializeTimer() {
@@ -465,9 +472,6 @@
     hexId.toUpperCase();
     Serial.print(F("NFC UID: 0x")); Serial.println(hexId);
     onNfcId(hexId);
-
-    enableNfc(false);
-    nextNfcTick = 0; // no nfc reading during playing
   } else {
     // No NFC card found, try again
     nextNfcTick = now + NFC_DELAY;
@@ -492,6 +496,7 @@
     if (state == PLAY_SELECTED) stopPlaying();
     nextTimeoutTick = 0; // no timeout during playing
     nextNfcTick = 0; // no nfc reading during playing
+    enableNfc(false);
     enablePlayer(true);
     onStartFirstTrack(index);
     enableAmplifier(!headphone);
@@ -511,6 +516,8 @@
     playingAlbum = 0;
     blinkSelected(playingAlbum);
     nextTimeoutTick = 0; // no timeout during playing
+    nextNfcTick = 0; // no nfc reading during playing
+    enableNfc(false);
     enablePlayer(true);
     player.startPlayingFile(trackName.c_str());
     enableAmplifier(!headphone);
@@ -630,6 +637,7 @@
 }

 void enablePlayer(boolean enable) {
+  pinMode(MUSIC_RESET_PIN, OUTPUT);
   if (enable) {
     digitalWrite(MUSIC_RESET_PIN, HIGH);
     player.reset();
@@ -641,14 +649,20 @@
 }

 void enableAmplifier(boolean enable) {
+  pinMode(AMPLIFIER_ENABLE_PIN, OUTPUT);
   digitalWrite(AMPLIFIER_ENABLE_PIN, enable);
 }

 void enableNfc(boolean enable) {
-  digitalWrite(NFC_RESET_PIN, enable);
+  pinMode(NFC_RESET_PIN, OUTPUT);
   if (enable) {
-    nfc.SAMConfig();
-  }
-}
-
-
+    Serial.println("Enable NFC");
+    digitalWrite(NFC_RESET_PIN, HIGH);
+    configNfc();
+  } else {
+    Serial.println("Disable NFC");
+    digitalWrite(NFC_RESET_PIN, LOW);
+  }
+}
+
+


Bugfix: wasn't interrupt safe

Bugfix: wasn't interrupt safe

--- zamek.ino
+++ zamek.ino
@@ -99,9 +99,10 @@
 void loop() {
 	//poor man's state machine!
 	if(servoDo){
-		servoDo = false;
 		//disable interrupts during rotation
 		detachInterrupts();
+
+		servoDo = false;

 		servo.attach(9);
 		if(isOpened){


Version 1.05. Sound functions added.

Version 1.05. Sound functions added.

--- module/module.ino
+++ module/module.ino
@@ -19,6 +19,7 @@

 const int ledPin = 13;
 const int signalPin = 4;
+const int speakerPin = 8;
 const int debounce = 25;
 const int quota = 3600;

@@ -27,6 +28,7 @@
 	RDM880.begin(9600);
 	pinMode(ledPin, OUTPUT);
 	pinMode(signalPin, INPUT);
+	pinMode(speakerPin, OUTPUT);
 }

 void loop() {
@@ -53,20 +55,25 @@

 	// Analyze response packet and data
 	if(responseFlag == false) {
+		soundFeedback(true);
 		Serial.println("Read unsuccessful, please try again.");
 		Serial.println();
+		delay(500);
 	}
 	else {
 		existingTime = getTime(readData);
 		if(readData[8] != 0xDD) {
+			soundFeedback(true);
 			Serial.println("You are not authorized to use this machine.");
 			Serial.println();
 		}
 		else if(existingTime >= quota) {
+			soundFeedback(true);
 			Serial.println("You have reached your quota for this month.");
 			Serial.println();
 		}
 		else {
+			soundFeedback(false);
 			Serial.println("User authenticated. Machine is ready to fire.");
 			elapsedTime = accumulator();
 			Serial.print("Total time used: ");
@@ -83,6 +90,18 @@
 	if(responseFlag == false) Serial.println("Unexpected result");
 	*/

+}
+
+void soundFeedback(bool reject) {
+	if(reject) {
+		tone(8, 123, 250);
+		delay(300);
+		tone(8, 123, 250);
+		delay(300);
+		tone(8, 123, 250);
+	}
+	else
+		tone(8, 440, 500);
 }

 bool getResponse(unsigned char response[]) {


LoaderTest: Make Snake playable from keyboard by sending arrow keys twice

--- Utils/LoaderTest/LoaderTest.ino
+++ Utils/LoaderTest/LoaderTest.ino
@@ -160,7 +160,6 @@
  ISR(PCINT0_vect) {
    if (~PINB & (1<<keyboardClockPin)) // FALLING edge of PS/2 clock
      ps2interrupt();
-
  }
 #endif

@@ -265,10 +264,10 @@
       #else
         case PS2_ESC:      doTransfer(terminalGt1);         break; // XXX HACK Find some proper short-cut. Ctrl-T?
       #endif
-      case PS2_LEFTARROW:  sendController(~buttonLeft,  1); break;
-      case PS2_RIGHTARROW: sendController(~buttonRight, 1); break;
-      case PS2_UPARROW:    sendController(~buttonUp,    1); break;
-      case PS2_DOWNARROW:  sendController(~buttonDown,  1); break;
+      case PS2_LEFTARROW:  sendController(~buttonLeft,  2); break;
+      case PS2_RIGHTARROW: sendController(~buttonRight, 2); break;
+      case PS2_UPARROW:    sendController(~buttonUp,    2); break;
+      case PS2_DOWNARROW:  sendController(~buttonDown,  2); break;
       case PS2_ENTER:      sendController('\n', 1);         break;
       case PS2_DELETE:     sendController(127, 1);          break;
       default:             sendController(c, 1);            break;


Correct typo in comment in firmware source

--- firmware/removinator/removinator.ino
+++ firmware/removinator/removinator.ino
@@ -328,7 +328,7 @@
 // Remove the inserted card.  If a card is not inserted,
 // this is just a no-op.
 //
-// We "remove" a card be disabling the multiplexor ICs by setting
+// We "remove" a card by disabling the multiplexor ICs by setting
 // their enable pin to low.  This disconnects the card contacts from
 // the card reader adapter.  We also set the reader switch pin to HIGH
 // so the reader thinks that the card was physically removed.


read & display time from ds1307

read & display time from ds1307

--- research/DCF-RTC/DCF-RTC.ino
+++ research/DCF-RTC/DCF-RTC.ino
@@ -82,32 +82,36 @@

 void setup() {
   Serial.begin(9600);
+  Wire.begin();
+
+  tmElements_t tm;
+  if (RTC.read(tm)) {
+    Serial.println("Time: ");
+  }

   Serial.println("Setting system clock from RTC module");
   setSyncProvider(RTC.get);
-  DCF.Start();
-  setSyncInterval(30);
-  setSyncProvider(getDCFTime);
+  //DCF.Start();
+  //setSyncInterval(30);
+  //setSyncProvider(getDCFTime);
   // It is also possible to directly use DCF.getTime, but this function gives a bit of feedback
   //setSyncProvider(DCF.getTime);

-  Serial.println("Waiting for DCF77 time ... ");
-  Serial.println("It will take at least 2 minutes until a first update can be processed.");
-  while(timeStatus()== timeNotSet) {
-    // wait until the time is set by the sync provider
-    Serial.print("RTC: ");
-    digitalClockDisplay();
-    delay(2000);
-  }
+//  Serial.println("Waiting for DCF77 time ... ");
+//  Serial.println("It will take at least 2 minutes until a first update can be processed.");
+//  while(timeStatus()== timeNotSet) {
+//    // wait until the time is set by the sync provider
+//    Serial.print("RTC: ");
+//    digitalClockDisplay();
+//    delay(2000);
+//  }
 }

 void loop()
 {
-  if( now() != prevDisplay) //update the display only if the time has changed
-  {
-
-  }
+  digitalClockDisplay();
+  delay(1000);
 }

 int words(int minutesOfDay, word_t* buffer)


Update all5V0Sensors.ino

Update all5V0Sensors.ino

--- examples/all5V0Sensors/all5V0Sensors.ino
+++ examples/all5V0Sensors/all5V0Sensors.ino
@@ -1,51 +1,50 @@
-/*
- * All 5.0 V sensors example
- *
- * This sketch shows you how to use all 5.0 V ROHM sensors simultaneously.
- *
- * Before powering up your Arduino, make sure to select 5V on jumper J15 on the shield!
- *
- * NOTE: When using BD7411G Hall sensor with Arduino UNO, be sure to disconnect the sensor from the shield before uploading the sketch!
- *       Since BD7411G's OUT pin is directly connected to Arduino D0 (serial RX), any attempt to upload with the sensor connected will lead to out_of_sync() error.
- */
-
-// define all the sensors we will use
-#define INCLUDE_BD7411G
-#define INCLUDE_BD1020HFV
-
-// include the library
-#include <RohmMultiSensor.h>
-
-//instantiate all the sensors' classes
-BD7411G hall;
-BD1020HFV temp;
-
-void setup() {
-  // begin serial communication
-  Serial.begin(9600);
-
-  // begin the TWI (I2C) interface.
-  // this function has to be called before any calls to .init()!
-  Wire.begin();
-
-  // initialize all the sensor with default values.
-  hall.init();
-  // temperature sensor (BD1020HFV) is connected to ANALOG_1 header on the shield
-  temp.init(ANALOG_1);
-
-  Serial.println("MF[-]\tt[deg C]");
-}
-
-void loop() {
-  // measure all the sensor values
-  bool magFieldDetected = hall.measure();
-  float tempValue = temp.measure();
-
-  // print the values to the serial port
-  Serial.print(magFieldDetected);
-  Serial.print('\t');
-  Serial.println(tempValue);
-
-  // wait 100 ms before the next measurement
-  delay(100);
+/*
+ * All 5.0 V sensors example
+ *
+ * This sketch shows you how to use all 5.0 V ROHM sensors simultaneously.
+ *
+ * Before powering up your Arduino, make sure to select 5V on jumper J15 on the shield!
+ *
+ * NOTE: When using BD7411G Hall sensor with Arduino UNO, be sure to disconnect the sensor from the shield before uploading the sketch!
+ *       Since BD7411G's OUT pin is directly connected to Arduino D0 (serial RX), any attempt to upload with the sensor connected will lead to out_of_sync() error.
+ */
+
+// define all the sensors we will use
+#define INCLUDE_ALL_5V0_SENSORS
+
+// include the library
+#include <RohmMultiSensor.h>
+
+//instantiate all the sensors' classes
+BD7411G hall;
+BD1020HFV temp;
+
+void setup() {
+  // begin serial communication
+  Serial.begin(9600);
+
+  // begin the TWI (I2C) interface.
+  // this function has to be called before any calls to .init()!
+  Wire.begin();
+
+  // initialize all the sensor with default values.
+  hall.init();
+  // temperature sensor (BD1020HFV) is connected to ANALOG_1 header on the shield
+  temp.init(ANALOG_1);
+
+  Serial.println("MF[-]\tt[deg C]");
 }
+
+void loop() {
+  // measure all the sensor values
+  bool magFieldDetected = hall.measure();
+  float tempValue = temp.measure();
+
+  // print the values to the serial port
+  Serial.print(magFieldDetected);
+  Serial.print('\t');
+  Serial.println(tempValue);
+
+  // wait 100 ms before the next measurement
+  delay(100);
+}


Update arduino code

Update arduino code

--- Arduino/coopController/coopController.ino
+++ Arduino/coopController/coopController.ino
@@ -13,7 +13,7 @@
 #include "RTClib.h"

 // print debug messages or not to serial
-const int Debugging = 1;
+const int Debugging = 0;

 // Digital & analog pins for various components
 const int tempSense     =  6; // DS18S20 Temperature Sensor
@@ -22,13 +22,13 @@
 const int heaterRelay   =  9; // Water Heater Relay
 const int doorOpen      = 35; // MotorA left
 const int doorClose     = 36; // MotorA right
-const int doorSpeed     = 37; // MotorA speed
+const int doorEnable    = 37; // MotorA enable
 const int doorTop       = 51; // Reed Switch
 const int doorBottom    = 53; // Reed Switch
 const int doorOpenLED   = 11; // Indicator light (blinks during open/close steady on when open)
 const int doorClosedLED = 12; // Indicator Light (blinks during open/close steady on when closed)
 const int fan           = 38; // MotorB left
-const int fanSpeed      = 39; // MotorB speed
+const int fanEnable     = 39; // MotorB enable
 const int rtcSDA        = 20; // Real Time Clock SDA (i2c arduino mega)
 const int rtcSCL        = 21; // Real Time Clock SCL (i2c arduino mega)

@@ -369,7 +369,7 @@
 void toggleFan() {
   if (fanState) {
     digitalWrite(fan, LOW);
-    digitalWrite(fanSpeed, LOW);
+    digitalWrite(fanEnable, HIGH);
     if (Debugging) {
       debugger.println("Fan off.");
     }
@@ -379,7 +379,7 @@
   }
   else {
     digitalWrite(fan, HIGH);
-    digitalWrite(fanSpeed, HIGH);
+    digitalWrite(fanEnable, HIGH);
     if (Debugging) {
       debugger.println("Fan on.");
     }
@@ -606,13 +606,13 @@
       // Door isn't closed, run motor until it is.
       digitalWrite(doorClose, HIGH);
       digitalWrite(doorOpen, LOW);
-      digitalWrite(doorSpeed, HIGH);
+      digitalWrite(doorEnable, HIGH);
     }
     else {
       // Door is closed, stop motor
       digitalWrite(doorClose, LOW);
       digitalWrite(doorOpen, LOW);
-      digitalWrite(doorSpeed, LOW);
+      digitalWrite(doorEnable, HIGH);
       doorState = "closed";
       if (doorStatePrev != doorState && wifiConnected) {
         mqtt.publish("coop/status", "door|closed", 2, 0);
@@ -624,13 +624,13 @@
       // Door isn't open, run motor until it is.
       digitalWrite(doorClose, LOW);
       digitalWrite(doorOpen, HIGH);
-      digitalWrite(doorSpeed, HIGH);
+      digitalWrite(doorEnable, HIGH);
     }
     else {
       // Door is open, stop motor.
       digitalWrite(doorClose, LOW);
       digitalWrite(doorOpen, LOW);
-      digitalWrite(doorSpeed, LOW);
+      digitalWrite(doorEnable, HIGH);
       doorState = "open";
       if (doorStatePrev != doorState && wifiConnected) {
         mqtt.publish("coop/status", "door|open", 2, 0);
@@ -931,26 +931,26 @@
   pinMode(heaterRelay, OUTPUT);
   pinMode(doorOpen, OUTPUT);
   pinMode(doorClose, OUTPUT);
-  pinMode(doorSpeed, OUTPUT);
+  pinMode(doorEnable, OUTPUT);
   pinMode(doorOpenLED, OUTPUT);
   pinMode(doorClosedLED, OUTPUT);
   pinMode(doorTop, INPUT);
   pinMode(doorBottom, INPUT);
   pinMode(fan, OUTPUT);
-  pinMode(fanSpeed, OUTPUT);
+  pinMode(fanEnable, OUTPUT);

   // Pin defaults
   digitalWrite(lampRelay, LOW);
   digitalWrite(heaterRelay, LOW);
   digitalWrite(doorOpen, LOW);
   digitalWrite(doorClose, LOW);
-  digitalWrite(doorSpeed, LOW);
+  digitalWrite(doorEnable, HIGH);
   digitalWrite(doorOpenLED, LOW);
   digitalWrite(doorClosedLED, HIGH);
   digitalWrite(doorTop, HIGH);    // Enable resistor
   digitalWrite(doorBottom, HIGH); // Enable resistor
   digitalWrite(fan, LOW);
-  digitalWrite(fanSpeed, LOW);
+  digitalWrite(fanEnable, HIGH);

   lcdWrite("System Ready");
 }


Update example08_sw.ino

Update example08_sw.ino

--- 2_example/example08_sw/example08_sw.ino
+++ 2_example/example08_sw/example08_sw.ino
@@ -56,7 +56,7 @@
 }

 void sleep(){
-    digitalWrite(PIN_LED,LOW);              // LED(EN信号)の消灯
+    digitalWrite(PIN_LED,LOW);              // LEDの消灯
     delay(200);                             // 送信待ち時間
     ESP.deepSleep(SLEEP_P,WAKE_RF_DEFAULT); // スリープモードへ移行する
     while(1){                               // 繰り返し処理


touch: refactor

touch: refactor

--- DigiSpark/TouchKeyboardDigiSpark/TouchKeyboardDigiSpark.ino
+++ DigiSpark/TouchKeyboardDigiSpark/TouchKeyboardDigiSpark.ino
@@ -4,6 +4,8 @@
 #ifdef ARDUINO_AVR_DIGISPARK
 #include "DigiKeyboard.h"
 #endif
+
+int g_pushed = 0;

 void mydelay(int ms)
 {
@@ -48,7 +50,7 @@
     pinMode(PIN_KEY3, INPUT);

 }
-int g_pushed = 0;
+
 void loop()
 {
     int b1 = digitalRead(PIN_KEY1);


Update isTouch.ino

Update isTouch.ino

 added Wire.begin();

--- Seeed_QTouch/examples/isTouch/isTouch.ino
+++ Seeed_QTouch/examples/isTouch/isTouch.ino
@@ -11,6 +11,7 @@

 void setup()
 {
+    Wire.begin();
     Serial.begin(9600);
 }

@@ -25,4 +26,4 @@
         Serial.println(" ms");
     }
     delay(10);
-}+}


added logic for sas on/off and sas state update

+ added new comments
+ minor refactoring
+ changes to the ramping function for helm states

--- KSPboard.ino
+++ KSPboard.ino
@@ -61,11 +61,13 @@
 // rotary pins
 #define PIN_ROT_CTRL_CLK 2
 #define PIN_ROT_CTRL_DATA A2
-#define PIN_ROT_CTRL_SW A3 // no pin yet
+#define PIN_ROT_CTRL_SW A3 // when you push the rotary switch in
+#define PIN_ROT_CTRL_EN A6 // sas on / off

 // i2c addresses / stuff
 #define I2C_SUCCESS 0
 #define IO_ADDR_BASE 0x20
+// also note the wire library uses pins A4, A5

 #define IO_OPS_ADDR 0
 #define IO_OPS_LENGTH 2
@@ -80,10 +82,10 @@
 // misc
 #define OPS 16 // Action 1-10, stage, gear, light, rcs, brake, abort

-// helm
-#define RAMP_MAX 65
+// helm, with velocity ramping
+#define RAMP_MAX 100
 #define RAMP_MIN -RAMP_MAX
-#define DIR_MAX 2000
+#define DIR_MAX 6000
 #define DIR_MIN -DIR_MAX

@@ -101,7 +103,8 @@
 // sas control variable
 volatile uint8_t _vol_rotaryControl = 0; // 0-255 for conversion to sas states
 uint8_t controlState = 0, controlLocked = 0; // 0-7 for all sas states
-uint8_t controlDebounce = 0;
+uint8_t controlDebounce = 0; // debounce for the jittery rotary control switch
+boolean controlEnable = false; // for the sas on / off switch

 // op control variables
 // state == 0 to DELAY_OP-1 -> off / debounce, state == DELAY_OP -> on
@@ -147,7 +150,9 @@
   return (Wire.requestFrom(IO_ADDR_BASE | address, len) == len); // returns success fail
 }

-uint16_t i2cReadData() // get the data bytes and stuff them into a 16-bit unsigned value
+// get the data bytes and stuff them into a 16-bit unsigned value
+// call more than once if you have more than 2 bytes
+uint16_t i2cReadData()
 {
   return (~(Wire.read() | (Wire.read() << 8)));
 }
@@ -165,7 +170,7 @@

     for (col = PIN_HELM_MAT_COL; col < PIN_HELM_MAT_COLS; col++)
     {
-      // get inverted result and shift it onto the matrix
+      // get inverted result (matrix is active low) and shift it onto the matrix
       matrix = (matrix << 1) | !digitalRead(col); // wish there was <<=
     }

@@ -175,7 +180,7 @@
   return (matrix);
 }

-// get control input
+// get control input and set the new adjust value
 int16_t helmGetAdjustment(boolean high, boolean low, int8_t adj)
 {
   switch (high ? HIGH : (low ? LOW : NEUTRAL)) // high trumps low
@@ -302,40 +307,54 @@

 void updateControl()
 {
-  uint8_t roter = 0; // setup space
-
-  noInterrupts(); // shutdown interrupts for this volatile operation
-  roter = _vol_rotaryControl; // copy the volatile control variable
-  interrupts(); // reenable interrupts immediately
-
-  uint8_t newState = rotaryControl2State(roter);
-
-  if (newState != controlState)
-  {
-    controlState = newState; // update the hilighted state
-
-    // do hiligting stuff //
-
-    Serial.print(F("new state => ")); Serial.println(newState);
-  }
-
-  if (controlDebounce > 0) //
-  {
-    controlDebounce--; // do dat sweet digi debounce
-  }
-  else
-  {
-    if (!digitalRead(PIN_ROT_CTRL_SW)) // if you press dis switch lock the sas control state
-    {
-      controlLocked = controlState; // update locked variable
-
-#ifdef DEBUG
-      Serial.println(F("this is the krpc call to change sas state"));
-#endif
-
-      controlDebounce = DELAY_CTRL; // reset delay
-    }
-  }
+  boolean newControlEnable = digitalRead(PIN_ROT_CTRL_EN);
+
+  // if it was on and now its off
+  if (controlEnable && !newControlEnable)
+  {
+    Serial.println(DISABLE); // send disable sequence
+  }
+  else if (controlEnable || newControlEnable)
+  {
+    uint8_t roter = 0; // setup space
+
+    noInterrupts(); // shutdown interrupts for this volatile operation
+    roter = _vol_rotaryControl; // copy the volatile control variable
+    interrupts(); // reenable interrupts immediately
+
+    uint8_t newState = rotaryControl2State(roter); // convert to sas number
+
+    if (newState != controlState)
+    {
+      controlState = newState; // update the hilighted state
+
+      // do hiligting stuff //
+      // here the currently hovered state will be a blinking
+      // led, there should be a timer started now that if not
+      // dealt with by pressing the dial button resets the
+      // controlState variable back to what is actually selected
+    }
+
+    if (controlDebounce > 0)
+    {
+      controlDebounce--; // do dat sweet digi debounce
+    }
+    else
+    {
+      // if you press dis switch lock the sas control state (active low)
+      if (!digitalRead(PIN_ROT_CTRL_SW))
+      {
+        controlLocked = controlState; // update locked variable
+
+        Serial.println(ENABLE); // send enable
+        Serial.println(controlLocked); // send new sas state
+
+        controlDebounce = DELAY_CTRL; // reset delay
+      }
+    }
+  }
+
+  controlEnable = newControlEnable; // finally save the new state for next time around

   Serial.println(DISABLE); // skip or end transmission
 }


Now it makes the *right* noises.

Now it makes the *right* noises.

--- switchbox.ino
+++ switchbox.ino
@@ -247,11 +247,11 @@
   pinMode(BLUBTN_OUT,   OUTPUT);
   pinMode(BLUBTN_IN,     INPUT);
   digitalWrite(BLUBTN_IN, HIGH); // turn on internal pullup resistor
-  btn_tones[BLUBTN_IN] = NOTE_F3;
+  btn_tones[BLUBTN_IN] = NOTE_E3;

   pinMode(BIGBTN_IN,     INPUT);
   digitalWrite(BIGBTN_IN, HIGH); // turn on internal pullup resistor
-  btn_tones[BIGBTN_IN] = NOTE_G3;
+  btn_tones[BIGBTN_IN] = NOTE_F3;

   pinMode(SPKR_PIN,     OUTPUT);


Calculating throughput

Calculating throughput

--- sensing/SBRC2017_Throughput_arduino.ino
+++ sensing/SBRC2017_Throughput_arduino.ino
@@ -15,9 +15,6 @@
 #include <SoftwareSerial.h>
 #include <SD.h>

-#include "TinyGPS++.h"
-#include "DHT.h"
-
 #define NODE_ID 1 //The network id of the present device

 #define DEBUG false // Set true if
@@ -31,26 +28,17 @@
 #define WIFI_RX 5
 #define WIFI_BAUD_RATE 38400

-#define DHT11_PIN 7
-#define DHTPIN 7
-#define DHTTYPE DHT11
-
-
-
 #define request "?"
 #define clear_to_send ":"
 #define end_of_file "#"
 #define wifi_freq 10
 #define wifi_timeout 20

-#define SEPARATOR ","
+#define BATCH_SIZE 30

 #define DELAY_TIME 150

-#define PIN_LIGHT A3
 #define SD_CHIP_SELECT 10
-#define PIN_RAIN A1
-

 const char string_0[] PROGMEM = "log.txt";
 const char string_1[] PROGMEM = "node_id=";
@@ -64,57 +52,25 @@
                                             string_3, string_4, string_5
                                            };

-#if DEBUG
-const char debug_0[] PROGMEM = "Searching for GPS";
-const char debug_1[] PROGMEM = "GPS Found!";
-const char debug_2[] PROGMEM = "Asking for wifi";
-const char debug_3[] PROGMEM = "Waiting WiFi";
-const char debug_4[] PROGMEM = "Sending Data";
-const char debug_5[] PROGMEM = "WiFi available";
-const char debug_6[] PROGMEM = "File Restarted!";
-const char debug_7[] PROGMEM = "DHT failure";
-const char debug_8[] PROGMEM = "WiFi not available";
-const char debug_9[] PROGMEM = "Data sent";
-
-const char* const debug_table[] PROGMEM = {debug_0, debug_1, debug_2,
-                                           debug_3, debug_4, debug_5,
-                                           debug_6, debug_7, debug_8,
-                                           debug_9
-                                          };
-#endif
-
 char buffer[40];
-
-//DateTime is in DDMMYYHHMMSSCC format
-TinyGPSPlus gps;
-DHT dht(DHTPIN, DHTTYPE);
-
-int iteration = 0;
-
-SoftwareSerial gpsSerial(GPS_RX, GPS_TX);
 SoftwareSerial wifiSerial(WIFI_RX, WIFI_TX);
 String filename("log.txt");
+unsigned long filesize;

 void start_file() {
-  //strcpy_P(buffer, (char*)pgm_read_word(&(string_table[0])));
   if (SD.begin(SD_CHIP_SELECT)) {
     SD.remove(filename);
-    //strcpy_P(buffer, (char*)pgm_read_word(&(string_table[0])));
     File data_file = SD.open(filename, FILE_WRITE);
+
     for (int i = 0; i < 200; i ++) {
       data_file.print(String(i) + ",aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n");
     }
     data_file.close();
+    data_file = SD.open(filename, FILE_WRITE);
+    filesize = data_file.size();
+    Serial.println("File size = " + String(filesize) + "bytes");
   }
 }
-
-#if DEBUG
-void print_debug(int i) {
-  strcpy_P(buffer, (char*)pgm_read_word(&(debug_table[i])));
-  Serial.println(buffer);
-}
-#endif
-

 void start_message() {
@@ -135,10 +91,7 @@
   wifiSerial.print(buffer);
 }

-void send_data() {
-#if DEBUG
-  print_debug(4);
-#endif
+bool send_data() {
   wifiSerial.listen();
   while (!wifiSerial.isListening()) {}
   //Send the whole file
@@ -147,13 +100,12 @@

   while (data_file.available()) {
     if(!start_connection()){
-      Serial.println(__LINE__);
       break;
     }
     String a;
     int i = 0;
     start_message();
-    while (data_file.available() and i < 30) {
+    while (data_file.available() and i < BATCH_SIZE) {
       i++;
       a = data_file.readStringUntil('\n');
       wifiSerial.print(a + "\n");
@@ -162,24 +114,14 @@
     }
     wifiSerial.write(end_of_file);
     delay(500);
-    Serial.println(__LINE__);
   }
   data_file.close();
-
-  //Remove the file and create a new
-  //start_file();
-
-#if DEBUG
-  print_debug(9);
-#endif
 }

 bool start_connection() {
   // Check for connection
   wifiSerial.listen();
-  while (!wifiSerial.isListening()) {
-    Serial.println(__LINE__);
-  }
+  while (!wifiSerial.isListening()) {}
   wifiSerial.print(request);
   int index = 0;
   while (!wifiSerial.available()) {
@@ -202,19 +144,21 @@
 void setup() {
   Serial.begin(SERIAL_BAUD_RATE);
   wifiSerial.begin(WIFI_BAUD_RATE);
-  gpsSerial.begin(GPS_BAUD_RATE);  // gps begins after wifi because it is used first

   pinMode(10, OUTPUT);
   Serial.println("Start");
   start_file();
   Serial.println("File started");
   delay(DELAY_TIME);
+
 }

 void loop() {
-#if DEBUG
-  print_debug(2); //Asking for WiFi
-#endif
-  Serial.println(__LINE__);
+  unsigned long t_start = millis();
   send_data();
-}
+  unsigned long t_end = millis();
+  float elapsed = (t_end - t_start)/1000.0;
+  Serial.println("Elapsed seconds = " + String(elapsed));
+  float throughput = float(filesize)/elapsed;
+  Serial.println("Throughput = " + String(throughput));
+}


Update Timer_Interrupt_Notes.ino

Update Timer_Interrupt_Notes.ino

added notes to Gemma and Trinket examples

--- PulseSensorAmped_Arduino_1.5.0/Timer_Interrupt_Notes.ino
+++ PulseSensorAmped_Arduino_1.5.0/Timer_Interrupt_Notes.ino
@@ -150,6 +150,18 @@
   ADAFRUIT Gemma, ADAFRUIT Trinket (or any other board with ATtiny85 running at 8MHz)

     NOTE: Gemma does not do serial communication! Comment out or remove the Serial code in the Arduino sketch!
+
+    NOTE: You must use Software Serial with the Trinket!
+          A the top of the main code page put these lines
+
+            #define rxPin 3
+            #define txPin 4
+            SoftwareSerial uart(rxPin, txPin);
+
+          Then, whenever the word 'Serial' is used, replace it with 'uart'
+            example:
+              change Serial.begin(115200); to uart.begin(57600);
+
     NOTE: Use pin 2 to connect the Pulse Sensor Purple Pin on Trinket and Gemma!

   Timer1
@@ -172,6 +184,17 @@
   ADAFRUIT Trinket with 16MHz software setting (or any other board with ATtiny85 running at 16MHz)

     NOTE: Use analog pin 2 for the Pulse Sensor purple wire.
+
+    NOTE: You must use Software Serial with the Trinket!
+          A the top of the main code page put these lines
+
+            #define rxPin 3
+            #define txPin 4
+            SoftwareSerial uart(rxPin, txPin);
+
+          Then, whenever the word 'Serial' is used, replace it with 'uart'
+            example:
+              change Serial.begin(115200); to uart.begin(57600);

   Timer1


Update Base FW

Update Base FW

--- Base/Base.ino
+++ Base/Base.ino
@@ -44,7 +44,7 @@
 void setup() {

-//  ps2.begin(DataPin, IRQpin);
+  //  ps2.begin(DataPin, IRQpin);

   Serial.begin(9600);

@@ -62,13 +62,13 @@
   radio.printDetails();

-//  pinMode(18, OUTPUT);
-//  pinMode(19, OUTPUT);
-//  digitalWrite(18, LOW);
-
-
-//  lcd.begin(20, 4);
-//  lcd.cursor();
+  //  pinMode(18, OUTPUT);
+  //  pinMode(19, OUTPUT);
+  //  digitalWrite(18, LOW);
+
+
+  //  lcd.begin(20, 4);
+  //  lcd.cursor();

 }

@@ -82,11 +82,10 @@
     Command msg(Serial.readString());
     String identifier = msg.getIdentifier();

+    // Example: #NRFA1D&#SLPL2T1D1P\&ff00000000ff\&;&;
     if (identifier == "NRF") {
       int ID = msg.getParam('A').toInt(); // jakoze Adress
       String data = msg.getParam('D'); // jakoze Data
-
-      Serial.println(data);

       char a[data.length() + 1];
       data.toCharArray(a, data.length() + 1);


Updating circuit description and Arduino pins.

--- examples/Wireless/CosaWirelessButton/CosaWirelessButton.ino
+++ examples/Wireless/CosaWirelessButton/CosaWirelessButton.ino
@@ -22,7 +22,8 @@
  *
  * @section Description
  * Demonstration of the Wireless interface and ExternalInterruptPin
- * for wakeup after power down.
+ * for wakeup after power down. An ATtiny85-20PU running this example
+ * sketch will require 5 uA in power down mode (VWI transmitter).
  *
  * This file is part of the Arduino Che Cosa project.
  */
@@ -33,7 +34,7 @@
 #include "Cosa/Watchdog.hh"
 #include "Cosa/RTC.hh"

-// Select Wireless device driver
+// Select Wireless device driver (network = 0xC05A, device = 0x02)
 // #include "Cosa/Wireless/Driver/CC1101.hh"
 // CC1101 rf(0xC05A, 0x02);

@@ -46,24 +47,22 @@
 #if defined(__ARDUINO_TINYX5__)
 VWI rf(0xC05A, 0x03, 4000, Board::D1, Board::D0, &codec);
 #else
-VWI rf(0xC05A, 0x03, 4000, Board::D7, Board::D8, &codec);
+VWI rf(0xC05A, 0x02, 4000, Board::D7, Board::D8, &codec);
 #endif

-// Connect button with pullup to Arduino Mega EXT2/D19, others to
-// Arduino EXT0; Mighty/D10, TinyX4/D10, Standard/D2 and TinyX5/D2.
+// Connect button between ground and pin TinyX4 EXT0/D10, TinyX5
+// EXT0/D2, Mega EXT2/D29 and others to Arduino EXT1 which is
+// Standard/D3 and Mighty/D11.
 class Button : public ExternalInterrupt {
 public:
   Button() :
-    ExternalInterrupt(
 #if defined(__ARDUINO_MEGA__)
-		      Board::EXT2,
+    ExternalInterrupt(Board::EXT2, ExternalInterrupt::ON_LOW_LEVEL_MODE, true)
 #elif defined(__ARDUINO_TINY__)
-		      Board::EXT0,
+    ExternalInterrupt(Board::EXT0, ExternalInterrupt::ON_LOW_LEVEL_MODE, true)
 #else
-		      Board::EXT1,
+    ExternalInterrupt(Board::EXT1, ExternalInterrupt::ON_LOW_LEVEL_MODE, true)
 #endif
-		      ExternalInterrupt::ON_LOW_LEVEL_MODE,
-		      true)
   {}

   virtual void on_interrupt(uint16_t arg = 0)
@@ -125,7 +124,7 @@
   Power::all_disable();

   // Debounce the button before allowing further interrupts. This also
-  // give a periodic message send when the button is kept low
+  // gives periodic (1 second) message send when the button is kept low.
   Watchdog::delay(1024);
   wakeup.enable();
 }


aweewa

aweewa

--- linefollower_working/linefollower.ino
+++ linefollower_working/linefollower.ino
@@ -1,155 +0,0 @@
-// TODO:
-//
-//    0.x*speedVal when steering?
-//
-//    If there are problems, add a value to turnDelay
-
-// Include libraries:
-#include <Adafruit_MotorShield.h>
-#include <lenlib.h>
-#include <Wire.h>
-#include <Servo.h>
-
-// Delay value called after motors been running:
-int delVal = 0;
-
-// Initialize variables for storing the sensor values
-int leftSensor = 0;
-int middleSensor = 0;
-int rightSensor = 0;
-
-//int turnSpeed = 60;
-int turnDelay = 0;
-// int containing last action: 0 starting value, 1 fwd, 2 steerLeft, 3 steerRight
-int lastAction = 0;
-
-// // Variable that works as a factor regulating the turn speed. i.e 1.8*spedVal = turnspeed
-// float turnMulti = 1.8;
-// float turnDivi = 0.2;
-// This is the speed value, (0-255)
-int speedVal = 90; // 100 seem to be a good value
-
-// // Variable that works as a factor regulating the turn speed. i.e 1.8*spedVal = turnspeed
-// float turnMulti = 1.8;
-// // This is the speed value, (0-255)
-// int speedVal = 100; // 100 seem to be a good value
-
-int loopDelay = 0;
-
-myMotors Motors;   // Create Motors object
-mySensors Sensors; // Create Sensors object
-
-void setup() {
-  Serial.begin(9600); // set up Serial connection at 9600 bps
-
-  Motors.beginMotors();   // Start motors
-  Sensors.beginSensors(); // Start sensors
-
-  delay(2000);
-}
-
-void loop() {
-
-  readSensors();
-
-  // if the right sensor is the only sensor that have the value 1, the bot need to compensate by turning right
-  if((leftSensor == 0 && middleSensor == 0 && rightSensor == 1) || (leftSensor == 0 && middleSensor == 1 && rightSensor == 1))
-  {
-    steerRight();
-    Serial.print("SteerLeft");
-    lastAction = 2;
-  }
-  // if the left sensor is the only sensor that have the value 1, the bot need to compensate by turning left
-  else if((leftSensor == 1 && middleSensor == 0 && rightSensor == 0) || (leftSensor == 1 && middleSensor == 1 && rightSensor == 0))
-  {
-    steerLeft();
-    Serial.print("SteerRight");
-    lastAction = 3;
-  }
-  // if sensor value = 1, then the sensor is on track
-  if((leftSensor == 0 && middleSensor == 1 && rightSensor == 0) || (leftSensor == 1 && middleSensor == 1 && rightSensor == 1))
-  {
-    fwd();
-    Serial.print("Forward");
-    lastAction = 1;
-  }
-  else
-  {
-    // if(lastAction == 1){fwd();Serial.print("Forward**");}
-    // else if(lastAction == 2){steerLeft();Serial.print("SteerLeft**");}
-    // else if(lastAction == 3){steerRight();Serial.print("SteerRight**");}
-    // else {stop();Serial.println("Stop");}
-  }
-  delay(loopDelay);
-  Serial.println();
-}
-
-void readSensors(){
-  // Read the sensor values:
-  leftSensor = Sensors.readReflect0();
-  delay(20);
-  middleSensor = Sensors.readReflect1();
-  delay(20);
-  rightSensor = Sensors.readReflect2();
-  delay(20);
-  // Print status of sensors:
-  Serial.print("Reflect 0: ");Serial.print(leftSensor);
-  Serial.print("\tReflect 1: ");Serial.print(middleSensor);
-  Serial.print("\tReflect 2: ");Serial.print(rightSensor);
-  Serial.print("\tMotor speed: ");Serial.print(speedVal);
-  Serial.print("\tAction: ");
-}
-
-//
-// Motor functions
-//
-void fwd(){
-  Motors.runMotor(1,FORWARD,speedVal);
-  Motors.runMotor(2,FORWARD,speedVal);
-  delay(delVal);
-}
-void rev(){
-  Motors.runMotor(1,BACKWARD,speedVal);
-  Motors.runMotor(2,BACKWARD,speedVal);
-  delay(delVal);
-}
-void stop(){
-  Motors.runMotor(1,FORWARD,0);
-  Motors.runMotor(2,FORWARD,0);
-  delay(delVal);
-}
-// void steerRight(){
-//   Motors.runMotor(1,FORWARD,speedVal*turnMulti);
-//   Motors.runMotor(2,FORWARD,speedVal*turnDivi);
-//   delay(delVal);
-// }
-// void steerLeft(){
-//   Motors.runMotor(1,FORWARD,speedVal*turnDivi);
-//   Motors.runMotor(2,FORWARD,speedVal*turnMulti);
-//   delay(delVal);
-// }
-void steerRight(){
-  Motors.runMotor(1,FORWARD,speedVal);
-  Motors.runMotor(2,FORWARD,0);
-  delay(delVal);
-}
-void steerLeft(){
-  Motors.runMotor(1,FORWARD,0);
-  Motors.runMotor(2,FORWARD,speedVal);
-  delay(delVal);
-}
-
-void turnLeft(){  // Turn 90 degree LEFT
-  Motors.runMotor(1,BACKWARD,speedVal);
-  Motors.runMotor(2,FORWARD,speedVal);
-  delay(turnDelay);
-  Motors.runMotor(1,FORWARD,0);
-  Motors.runMotor(2,FORWARD,0);
-}
-void turnRight(){   // Turn 90 degrees RIGHT
-  Motors.runMotor(1,FORWARD,speedVal);
-  Motors.runMotor(2,BACKWARD,speedVal);
-  delay(turnDelay);
-  Motors.runMotor(1,FORWARD,0);
-  Motors.runMotor(2,FORWARD,0);
-}


moyenne sur mesure ref fait...meme si c'est pas ce qu'il fallait faire2

--- calibrateur.ino
+++ calibrateur.ino
@@ -16,6 +16,8 @@
 	https://github.com/gilles293/calibrateurServo.git
 	nettoyage du code, j'ai craqué
 */
+
+//pour la suite faire moyenne pour mesure PWMIN et PWMMAX et virer le calcul de la moyenne mesureimpulsion pour le remplacer par la méthode

 #include <EEPROM.h>


idea for no color detection

idea for no color detection

--- src/colorpicker_v0/colorpicker_v0.ino
+++ src/colorpicker_v0/colorpicker_v0.ino
@@ -1,3 +1,28 @@
+/*
+
+TODO:
+
+Make a calibration mode.  When the system first boots (if color is still unset)
+allow some button press sequence to initialize a scanning mode which takes
+average rgb readings until released.  Then, give those values a little padding
+and use them in isColor() like this:
+
+!(abs(175 - this->color.r) < 20
+  && abs(71 - this->color.g) < 20
+  && abs(55 - this->color.b) < 20
+)
+
+*/
+
+
+
+
+
+
+
+
+
+
 /*

     ------->  ready  <----------   confirm <------------------------------------
@@ -102,6 +127,11 @@
   // TODO return if this->color != black or white (or anything returned when not actually touching a color)
   if (this->enabled
   //  && this->color > 0
+    && !( // rgb 175, 71, 55 was the average color I got for "white", or "no color", when testing this around my apartment.
+      abs(175 - this->color.r) < 20
+      && abs(71 - this->color.g) < 20
+      && abs(55 - this->color.b) < 20
+    )
   ) {
     return true;
   }
@@ -119,7 +149,7 @@

 #define SENSOR_UPDATE_MILIS 50
 #define RESET_TIMEOUT_MILIS 2000 // duration of reset timeout, in miliseconds
-#define CONFRIM_COUNTDOWN_MILIS 300 // duration of confirmation countdown timer, in miliseconds
+#define CONFRIM_COUNTDOWN_MILIS 200 // duration of confirmation countdown timer, in miliseconds
 #define CONFIRMATION_PRESSES 2 // number of button presses to confirm a color
 Metro resetTimer;
 Metro confirmDebounceTimer; // A debouncer for confirmation clicks.
@@ -299,3 +329,7 @@
     }
   }
 }
+
+
+
+


Changed sleep duration

Changed sleep duration

--- lpwan/SigFoxMkr1200.ino
+++ lpwan/SigFoxMkr1200.ino
@@ -13,36 +13,47 @@
   // Start the module
   SigFox.begin();
   // Wait at least 30mS after first configuration (100mS before)
-  delay(100);
+  delay(1000);
   // Clears all pending interrupts

   SigFox.status();
-  delay(1);
+  delay(1000);
   SigFox.beginPacket();
   uint8_t v= SigFox.internalTemperature();
   SigFox.write(v);

-  int ret = SigFox.endPacket(true);  // send buffer to SIGFOX network
+  int ret = SigFox.endPacket();  // send buffer to SIGFOX network
   SigFox.end();
 }

 void setup() {
+
   // Uncomment this line and comment begin() if you are working with a custom board
+  //if (!SigFox.begin(SPI1, 30, 31, 33, 28, LED_BUILTIN)) {
   if (!SigFox.begin()) {
     return;
   }
   // Enable debug led and disable automatic deep sleep
   // Comment this line when shipping your project :)
-  SigFox.debug();
+SigFox.debug();
+
   delay(100);
+
   // Send the module to the deepest sleep
   SigFox.end();
+
 }

 void loop() {
   // Every 15 minutes, read all the sensors and send them
-  sendTemperature();
+  // Let's try to optimize the data format
+  // Only use floats as intermediate representaion, don't send them directly
+sendTemperature();
+
+
+
   //Sleep for 15 minutes
-  LowPower.sleep(15 * 60 * 1000);
+  LowPower.sleep(20 * 60 * 1000);
 }
+


lower min values for light cutoff, reduce delay time

--- super_freq/super_freq.ino
+++ super_freq/super_freq.ino
@@ -4,8 +4,8 @@
 #define MAX_FFT_BIN 32767
 #define LIN_OUT 1          // use the linear output function
 #define FFT_N 128          // set number of FFT points
-#define MIN_FFT_SUM 2000    // Used to turn off the lights for low volumes
-#define MIN_PEAK_VALUE 200  // Used to turn off the lights for low volumes
+#define MIN_FFT_SUM 900    // Used to turn off the lights for low volumes
+#define MIN_PEAK_VALUE 400  // Used to turn off the lights for low volumes

 #include <math.h>
 #include <FFT.h>
@@ -189,7 +189,7 @@
     }

     setColor(peak_index, brightness);
-    delay(65);
+    delay(20);

     if (DEBUG) {
         frequency = peak_index * ((1.0 * SAMPLE_RATE / (SKIP_MULT / 2)) / (FFT_N / 2));


add thermistor logic

add thermistor logic

this is temporary. The thermistor calibration is somewhat of a pain.
will replace with TI temp sensor.

--- basement_control/src/sketch.ino
+++ basement_control/src/sketch.ino
@@ -1,9 +1,16 @@
 #include <stdio.h>
 #include <softwareserial.h>
+#include <math.h>

 const int ping_sensor_pin = 7;
+const int thermistor_pin = 5;
 const int serial_speed = 9600;
 const int poll_interval = 10000;
+const float vcc = 4.14; // only used for display purposes, if used
+                        // set to the measured Vcc.
+const float pad = 9850; // balance/pad resistor value, set this to
+                        // the measured resistance of your pad resistor
+const float thermr = 10000;     // thermistor nominal resistance
 SoftwareSerial impSerial(8, 9); // RX on 8, TX on 9 for imp

 float current_temperature = 22.2222; // in C
@@ -20,6 +27,11 @@
   // establish variables for duration of the ping,
   // and the distance result in inches and centimeters:
   float duration, inches, cm;
+
+  current_temperature = read_thermistor(analogRead(thermistor_pin));
+  Serial.print("Current Temp: ");
+  Serial.print(current_temperature);
+  Serial.println("C");

   // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
   // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
@@ -75,3 +87,32 @@
   // 331.3 m/s plus .606 * current temp in C
   return 331.3 + (0.606 * current_temperature);
 }
+
+float read_thermistor(int RawADC) {
+  long Resistance;
+  float Temp;  // Dual-Purpose variable to save space.
+
+  Resistance=((1024 * pad / RawADC) - pad);
+  Temp = log(Resistance); // Saving the Log(resistance) so not to calculate  it 4 times later
+  Temp = 1 / (0.001129148 + (0.000234125 * Temp) + (0.0000000876741 * Temp * Temp * Temp));
+  Temp = Temp - 273.15;  // Convert Kelvin to Celsius
+
+  // BEGIN- Remove these lines for the function not to display anything
+  Serial.print("ADC: ");
+  Serial.print(RawADC);
+  Serial.print("/1024");                           // Print out RAW ADC Number
+  Serial.print(", vcc: ");
+  Serial.print(vcc,2);
+  Serial.print(", pad: ");
+  Serial.print(pad/1000,3);
+  Serial.print(" Kohms, Volts: ");
+  Serial.print(((RawADC*vcc)/1024.0),3);
+  Serial.print(", Resistance: ");
+  Serial.print(Resistance);
+  Serial.println(" ohms");
+  // END- Remove these lines for the function not to display anything
+
+  // Uncomment this line for the function to return Fahrenheit instead.
+  //temp = (Temp * 9.0)/ 5.0 + 32.0;                  // Convert to Fahrenheit
+  return Temp;
+}


implemented basic number display

implemented basic number display

--- src/rboy/src/main.ino
+++ src/rboy/src/main.ino
@@ -8,24 +8,27 @@

 #include <math.h>

-#define OLED_RESET (-1)
+#define OLED_RESET  (-1)
+#define BUTTON_PIN  2
+#define MAX_DISP_NUM     100
+#define LCDW        SSD1306_LCDWIDTH
+#define LCDH        SSD1306_LCDHEIGHT
+#define FONTW       6
+#define FONTH       8
+
+#define LIMIT       3000L
+
+const long MAX_NUM = MAX_DISP_NUM * LIMIT;
+
 Adafruit_SSD1306 display(OLED_RESET);
 MPU6050 mpu;
-
-int16_t raw[6];
+bool mpu_test;

 unsigned long prev = 0;

-// ================================================================
-// ===               INTERRUPT DETECTION ROUTINE                ===
-// ================================================================
+volatile long number = 0;

-volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
-void dmpDataReady() {
-  mpuInterrupt = true;
-}
-
-void displayLog(const char* message, bool complete=true, uint8_t size=1) {
+void display_log(const char* message, bool complete=true, uint8_t size=1) {
   display.clearDisplay();
   display.setTextSize(size);
   display.setTextColor(WHITE);
@@ -36,18 +39,48 @@
   }
 }

-void setup() {
+void show_number(int n, uint8_t size=5) {
+  display.clearDisplay();
+  display.setTextSize(size);
+  display.setTextColor(WHITE);
+  uint16_t fw = FONTW * size;
+  uint16_t fh = FONTH * size;
+  uint16_t x = (LCDW >> 1) - fw;
+  uint16_t y = (LCDH - fh) >> 1;
+  uint16_t mx = 4;
+  uint16_t my = 2;
+  for (int i = 0; i < 2; i++) {
+    int offset = i << 1;
+    display.drawRect(x - mx - 1 - offset, y - my - 1 - offset, (fw << 1) + (mx << 1) + (offset << 1), fh + (my << 1) + (offset << 1), WHITE);
+  }
+  if (n < 10) {
+    x += fw;
+  }
+  display.setCursor(x, y);
+  display.print(n);
+}
+
+void button_pressed() {
+  number = LIMIT >> 1;
+}
+
+void setup_button() {
+  pinMode(BUTTON_PIN, INPUT_PULLUP);
+  attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), button_pressed, RISING);
+}
+
+void setup_i2c_devices() {
   // by default, we'll generate the high voltage from the 3.3v line internally! (neat!)
   display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // initialize with the I2C addr 0x3D (for the 128x64)
-  // Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
-  displayLog("inited display");
+  Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
+  show_number(number);
+  mpu.initialize();
+  if (!(mpu_test = mpu.testConnection())) {
+    display_log("MPU6050 connection failed");
+  }
+}

-  displayLog("initing MPU...");
-  mpu.initialize();
-
-  displayLog("Testing device connections...");
-  displayLog(mpu.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");
-
+void setup_mpu_offset() {
   // supply your own gyro offsets here, scaled for min sensitivity
   // mpu.setXGyroOffset(220);
   // mpu.setYGyroOffset(76);
@@ -55,23 +88,34 @@
   // mpu.setZAccelOffset(1788); // 1688 factory default for my test chip
 }

+void setup() {
+  setup_button();
+  setup_i2c_devices();
+  setup_mpu_offset();
+}
+
 void loop() {
+  if (!mpu_test) { return; }
+  int16_t raw[6];
   mpu.getMotion6(raw, raw + 1, raw + 2, raw + 3, raw + 4, raw + 5);
-  displayLog("ax\nay\naz\ngx\ngy\ngz\n", false);
+  double ayz = sqrt(sq((unsigned long)raw[1]) + sq((unsigned long)raw[2]));
+  double sinv = max(-1.0, min(1.0, ayz / ((double) 0x3fff)));
+  double value = (M_PI_4 - abs(asin(sinv))) * 10;
+
+  long delta = (long) value;
   unsigned long time = millis();
-  unsigned long fps = 1000 / (time - prev);
+  long dt = time - prev;
   prev = time;
-  display.print("fps: ");
-  display.println(fps);
-  int rate = 32768 / 56;
-  for (int i = 0; i < 6; i++) {
-    int x0 = 16 + 56;
-    int y0 = i * 8 + 1;
-    display.drawRect(16, y0, 112, 6, WHITE);
-    int len = raw[i] / rate;
-    int x1 = x0 + len;
-    display.fillRect(min(x0, x1), y0 + 1, abs(len), 4, WHITE);
+  number += delta * dt;
+  if (number <= 0) {
+    number = MAX_NUM - 1;
   }
+  number = number % MAX_NUM;
+  display.invertDisplay(delta < 0);
+  show_number(number / LIMIT);
+
+  // display.setCursor(0, 0);
+  // display.setTextSize(1);

   display.display();
 }