Robot searches for and approaches cylinder

--- Tests/Ping_test/Ping_test.ino
+++ Tests/Ping_test/Ping_test.ino
@@ -12,6 +12,10 @@
 const int nMeasurements = 20;
 int       measurements[nMeasurements];
 int       measureIndex = 0;
+const int STATE_SEARCH    = 0;
+const int STATE_APPROACH  = 1;
+const int STATE_FOUND     = 2;
+int       currentState = STATE_SEARCH;

 const bool clockwise = true;
 const bool counterClockwise = false;
@@ -25,16 +29,51 @@
 }

 void loop() {
-  rotateStep(counterClockwise);
+
   pingDist = measurePingDist();
-
   measurements[measureIndex] = pingDist;
   Serial.println(arrayToString(measurements,nMeasurements));
-
+
+  switch (currentState) {
+    case STATE_SEARCH:
+      rotateStep(counterClockwise);
+      if((measurements[measureIndex]<100) &&
+         (measurements[measureIndex] < getMeanMeasurement(4)*0.66)
+        ){
+        stopMovement();
+        tone(4, 5000, 500);
+        delay(1000);
+        tone(4, 4000, 500);
+        currentState = STATE_APPROACH;
+      }
+      delay(100);
+      break;
+    case STATE_APPROACH:
+      if(measurements[measureIndex]<10){
+        currentState = STATE_FOUND;
+        stopMovement();
+      } else {
+        moveForward();
+      }
+      break;
+    case STATE_FOUND:
+      stopMovement();
+      if(measurements[measureIndex]>10){
+        currentState = STATE_SEARCH;
+      }
+      break;
+  }
   //Loop around to 0 before out of bounds:
   ++measureIndex %= nMeasurements;
+}

-  delay(100);
+long getMeanMeasurement(int n){
+  long sum = 0;
+  for(int i=1; i<=n; i++){
+    int arrayIndex = (measureIndex - i + nMeasurements) % nMeasurements;
+    sum += measurements[arrayIndex];
+  }
+  return (sum/n)+0.5;
 }

 String arrayToString(int array[], int arrayLength)
@@ -74,9 +113,18 @@
     servoLeft.writeMicroseconds(1300);
     servoRight.writeMicroseconds(1300);
   }
-  delay(100);
+  delay(50);
+  stopMovement();
+}
+
+void stopMovement(){
   servoLeft.writeMicroseconds(1500);
   servoRight.writeMicroseconds(1500);
+}
+
+void moveForward(){
+  servoLeft.writeMicroseconds(1700);
+  servoRight.writeMicroseconds(1300);
 }

 long microsecondsToCentimeters(long microseconds) {


working WiFi

working WiFi

--- iot/device/device.ino
+++ iot/device/device.ino
@@ -1,26 +1,37 @@
+#define CONFIG_SSID "icu"
+#define BACKUP_SSID "Sojasaus 5Ghz"
+#define BACKUP_PASSWORD "treb3f@EsTx"
+
+#include <OpenWiFi.h>
+#include <ESP8266HTTPClient.h>
 #include <ESP8266WiFi.h>
+#include <WiFiManager.h>

-const char ssid = "HvA Open Wi-Fi";
-const char password = "";
-
+OpenWiFi hotspot;

 const int pot = A0;
 int read_out = 0;
+String chipID;

 void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);

-  WiFi.mode(WIFI_STA);
-  WiFi.begin(ssid, password);
+  WiFiManager wifiManager;

   while (WiFi.status() != WL_CONNECTED) {
   	delay(500);
   	Serial.print(".");
   }

+  hotspot.begin(BACKUP_SSID, BACKUP_PASSWORD);
+
+  chipID = generateChipID();
+  String configSSID = String(CONFIG_SSID) + "_" + chipID;
+  wifiManager.autoConnect(configSSID.c_str());
+
   Serial.println("");
-  Serial.println("WiFi connected");
+  Serial.println("WiFi connected");
   Serial.print("IP address: ");
   Serial.println(WiFi.localIP());
 }
@@ -30,3 +41,14 @@
 	read_out = analogRead(pot);
 	Serial.println(read_out);
 }
+
+String generateChipID()
+{
+  String chipIDString = String(ESP.getChipId() & 0xffff, HEX);
+
+  chipIDString.toUpperCase();
+  while (chipIDString.length() < 4)
+    chipIDString = String("0") + chipIDString;
+
+  return chipIDString;
+}


Trying DHCP support

Trying DHCP support

--- src/sketch.ino
+++ src/sketch.ino
@@ -22,6 +22,7 @@
 #include <SPI.h>
 #include <Ethernet.h>
 #include <EthernetUdp.h>
+#include <Dns.h>
 #include <Time.h>
 #include <IPAddress.h>
 #include <EEPROM.h>
@@ -108,11 +109,10 @@
   Lcd.infoMessage("  Starting up.");

   // start Ethernet
-  Ethernet.begin(mac, ip, gateway, dns_server);
+  if(!Ethernet.begin(mac)) {
+      Ethernet.begin(mac, ip, gateway, dns_server);
+  }
   delay(1000);
-  // while(!client) {
-  //     // Wait until ready
-  // }

   // Upload saved session if present
   if (savePresent()) {


Remove debug

Remove debug

--- contrib/bargraph.ino
+++ contrib/bargraph.ino
@@ -6,7 +6,6 @@
 {
   Serial.begin(1000000);
   GD.begin(~GD_STORAGE);
-  printf("ok\n");

   GD.BitmapHandle(0);
   GD.cmd_setbitmap(0, BARGRAPH, 1280, 256);


reset game

reset game

made game properly reset

--- MorraGame/MorraGame.ino
+++ MorraGame/MorraGame.ino
@@ -52,35 +52,35 @@

   if (btnStatePlay != oldBtnStatePlay && displayState == 7) {
     // game is over, so reset
-	resetScore();
+    resetGame();
     showRoundsToPlay();
     displayState = 0;
   }
   else if (btnStatePlay != oldBtnStatePlay && displayState == 6) {
     // wait for next play button press after showing game winner
-	displayState = 7;
+    displayState = 7;
   }
   else if (btnStatePlay != oldBtnStatePlay && displayState == 5) {
     // show game winner and wait for next play button press
-	showHeaderNoScore();
+    showHeaderNoScore();
     mySerial.print(strWinner);
     displayState = 6;
   }
   else if (btnStatePlay != oldBtnStatePlay && displayState == 4) {
     // determine if the game is over and wait for next play button press
-	displayState = getGameWinner();
+    displayState = getGameWinner();
   }
   else if (btnStatePlay != oldBtnStatePlay && displayState == 3) {
     // show round results and wait for next play button press
-	displayResultOfRound();
+    displayResultOfRound();
     displayState = 4;
   }
   else if (btnStatePlay != oldBtnStatePlay && displayState == 2) {
-	// wait for next play button press after showing round stats
+    // wait for next play button press after showing round stats
     displayState = 3;
   }
   else if (displayState == 1) {
-	// handle hand, guess, and play buttons during a round
+    // handle hand, guess, and play buttons during a round
     if (btnStateHand == HIGH && btnStateHand != oldBtnStateHand) {
       nextHand();
       updateLCD();
@@ -94,7 +94,7 @@
     }
   }
   else if (displayState == 0) {
-	// determine rounds to play
+    // determine rounds to play
     if (btnStateHand == HIGH && btnStateHand != oldBtnStateHand && roundsToPlay > 1) {
       roundsToPlay -= 2;
       showRoundsToPlay();
@@ -276,9 +276,12 @@
   mySerial.write(148);   // new line
 }

-// reset the score
-void resetScore()
+// reset the game
+void resetGame()
 {
   playerScore = 0;
-  compScore = 0;
-}
+  compScore = 0;
+  roundsToPlay = 1;
+  roundsPlayed = 0;
+  winsNeeded = 1;
+}


comments

comments

--- MorraGame/MorraGame.ino
+++ MorraGame/MorraGame.ino
@@ -1,12 +1,12 @@
 #include <SoftwareSerial.h>

 //--- SETTINGS ---
-const String strTitle = "MORRA";         // title - all phrases have 16 character limit
 const int lcdPin = 2;                    // pin for LCD
 const int btnHand = 8;                   // pin for hand button
 const int btnGuess = 9;                  // pin for guess button
 const int btnPlay = 10;                  // pin for play button

+const String strTitle = "MORRA";         // title - all phrases have 16 character limit
 const String strNoWinner = "No winner";
 const String strTie = "It's a tie!";
 const String strPlayerWins = "You win round!";
@@ -26,17 +26,17 @@

 // keep track of button changes
 int oldBtnStateHand, oldBtnStateGuess, oldBtnStatePlay;
-int showResult = 0;                     // result to show (1, 2, 3, 4, or 0 for none)
+int showResult = 0;                      // result to show (1, 2, 3, 4, or 0 for none)

 SoftwareSerial mySerial = SoftwareSerial(255, lcdPin);

 void setup() {
-  pinMode(btnHand, INPUT);     // set hand button pin as input
-  pinMode(btnGuess, INPUT);    // set guess button pin as input
-  pinMode(btnPlay, INPUT);     // set play button pin as input
-  mySerial.begin(9600);        // start serial
-  mySerial.write(22);          // no cursor
-  mySerial.write(12);          // clear
+  pinMode(btnHand, INPUT);               // set hand button pin as input
+  pinMode(btnGuess, INPUT);              // set guess button pin as input
+  pinMode(btnPlay, INPUT);               // set play button pin as input
+  mySerial.begin(9600);                  // start serial
+  mySerial.write(22);                    // no cursor
+  mySerial.write(12);                    // clear
   updateLCD();
   delay(100);
 }
@@ -194,7 +194,7 @@
 // display result of round
 void displayResultOfRound() {
   showHeader();
-  mySerial.print(strRoundResult);    // display result of round
+  mySerial.print(strRoundResult);      // display result of round
 }

 // display header with score


Use explicit conditions in Arduino example

--- Examples/ArduinoSerial/ArduinoSerial.ino
+++ Examples/ArduinoSerial/ArduinoSerial.ino
@@ -9,7 +9,7 @@
  * Arduino libraries folder.  See: https://www.arduino.cc/en/guide/libraries
  *
  * 2) The Arduino Uno only has a very small amount of RAM (2 kB).  The value of
- * MAX_TRANSPORT_SIZE must be reduce to 200 in OscCommon.h.
+ * MAX_TRANSPORT_SIZE must be reduced to 200 in OscCommon.h.
  */

 #include "Osc99.h"
@@ -27,9 +27,9 @@
   // Send analogue inputs every 100 ms (10 Hz)
   static unsigned long previousMillis; // static means that the value will be remembered each loop
   unsigned long currentMillis = millis();
-  if(currentMillis - previousMillis > 100) {
+  if((currentMillis - previousMillis) > 100) {
     sendAnalogueInputsMessage();
-	previousMillis = currentMillis;
+    previousMillis = currentMillis;
   }

   // Process each received byte through the SLIP decoder
@@ -48,7 +48,7 @@
 void ProcessMessage(const OscTimeTag* const oscTimeTag, OscMessage* const oscMessage) {

   // If message address is "/hello" then send our hello message
-  if (OscAddressMatch(oscMessage->oscAddressPattern, "/hello")) {
+  if (OscAddressMatch(oscMessage->oscAddressPattern, "/hello") == true) {
     sendHelloMessage();
     return;
   }
@@ -56,10 +56,10 @@
   // If message address is "/digital/write" then get use the message arguments to set a digital pin
   if (OscAddressMatch(oscMessage->oscAddressPattern, "/digital/write")) {
     int32_t pinNumber, pinState;
-    if(OscMessageGetInt32(oscMessage, &pinNumber)) {
+    if(OscMessageGetArgumentAsInt32(oscMessage, &pinNumber) != OscErrorNone) {
       return; // error: unable to get first int32 argument
     }
-    if(OscMessageGetInt32(oscMessage, &pinState)) {
+    if(OscMessageGetArgumentAsInt32(oscMessage, &pinState) != OscErrorNone) {
       return; // error: unable to get second int32 argument
     }
     if(pinNumber < 2) {
@@ -77,14 +77,14 @@
 void sendHelloMessage() {
   OscMessage oscMessage;
   OscMessageInitialise(&oscMessage, "/hello");
-  OscMessageAddString(&oscMessage, "Hello! How are you?");
+  OscMessageAddString(&oscMessage, "Hi!");
   sendOscContents(&oscMessage);
 }

 void sendErrorMessage() {
   OscMessage oscMessage;
   OscMessageInitialise(&oscMessage, "/error");
-  OscMessageAddString(&oscMessage, "Sorry, I don't know what that means.");
+  OscMessageAddString(&oscMessage, "OSC address not recognised.");
   sendOscContents(&oscMessage);
 }

@@ -102,14 +102,14 @@

   // Create OSC packet from OSC message or bundle
   OscPacket oscPacket;
-  if(OscPacketInitialiseFromContents(&oscPacket, oscContents)) {
+  if(OscPacketInitialiseFromContents(&oscPacket, oscContents) != OscErrorNone) {
     return; // error: unable to create an OSC packet from the OSC contents
   }

   // Encode SLIP packet
   char slipPacket[MAX_OSC_PACKET_SIZE];
   size_t slipPacketSize;
-  if(OscSlipEncodePacket(&oscPacket, &slipPacketSize, slipPacket, sizeof (slipPacket))) {
+  if(OscSlipEncodePacket(&oscPacket, &slipPacketSize, slipPacket, sizeof (slipPacket)) != OscErrorNone) {
     return; // error: the encoded SLIP packet is too long for the size of slipPacket
   }


Implemented serial communications

Implemented serial communications

--- ledshifter.ino
+++ ledshifter.ino
@@ -4,6 +4,12 @@
  This sketch reads commands from a serial line that define patterns which in turn are shifted
  out to an 74HC595 shift register connected to the Arduino. Think of it as one of those
  terribly annoying christmas flickerfucks, but you can control this one with bluetooth. :)
+
+ The commands that come from serial are pretty simple: a row of hex encoded bytes. Those
+ bytes are parsed and shifted out to the LEDs with 150ms delay between the different values.
+
+ Try this one, it's quite pretty:
+ 010204081020408040201008040201008142241800ff00ff

  Program code by Gregor Ottmann, https://github.com/Zappes.
  Inspiration from the tutorial at http://arduino.cc/en/tutorial/ShiftOut
@@ -18,37 +24,52 @@
 // Pin connected to DS of 74HC595
 #define DATA_PIN 11

+// the serial port from which we read patterns
+#define COMPORT Serial
+
+// the speed of the serial port
+#define COMSPEED 9600
+
 // delay between patterns
 #define DELAY 150

-byte patterns[] = {
-  0x81,
-  0x42,
-  0x24,
-  0x18,
-  0x24,
-  0x42,
-  0xff,
-  0x00,
-  0xff,
-  0x00,
-  0xff,
-  0x00
-};
+// the patterns parsed from the serial port will be stored here
+// the pattern buffer size defines the maximum number of patterns
+// that may be sent in a serial command.
+#define PATTERN_BUFFER_SIZE 32
+byte patternBuffer[PATTERN_BUFFER_SIZE];
+byte patternCount;
+
+// the commands coming from the serial port will be stored here
+#define CMD_BUFFER_SIZE (PATTERN_BUFFER_SIZE*2)+1
+char  commandBuffer[CMD_BUFFER_SIZE+1];
+int   commandCursor = 0;

 void setup() {
   //set pins to output so you can control the shift register
   pinMode(LATCH_PIN, OUTPUT);
   pinMode(CLOCK_PIN, OUTPUT);
   pinMode(DATA_PIN, OUTPUT);
+
+  // switch off the LEDs
+  writeToLeds(0);
+
+  // start listening on the com port
+  COMPORT.begin(COMSPEED);
+
 }

 void loop() {
+  // we always look for a new pattern before each iteration. this means that
+  // every pattern block will always be played to its end before a new one is
+  // read and displayed.
+  readPatternsFromSerial();
+
   // count from 0 to 255 and display the number
   // on the LEDs
-  for (int i = 0; i < sizeof(patterns); i++) {
-    // take the latchPin low so
-    writeToLeds(patterns[i]);
+  for (int i = 0; i < patternCount; i++) {
+
+    writeToLeds(patternBuffer[i]);
     // pause before next value:
     delay(DELAY);
   }
@@ -68,3 +89,46 @@
     //take the latch pin high so the LEDs will light up:
     digitalWrite(LATCH_PIN, HIGH);
 }
+
+/*
+  Parses a pattern string, i.e. a string of hex encoded bytes, and puts the bytes into the
+  pattern buffer.
+*/
+void parsePatternsToBuffer(const char *input) {
+  char currentByte[3];
+
+  patternCount = 0;
+
+  for(int i = 0; i < (strlen(input) / 2); i++)
+  {
+    currentByte[0] = *(input+(2*i));
+    currentByte[1] = *(input+(2*i)+1);
+    currentByte[2] = 0;
+
+    patternBuffer[patternCount++] = strtol(currentByte, NULL, 16);
+  }
+}
+
+/*
+  Reads the pattern string from the serial port.
+*/
+void readPatternsFromSerial() {
+  while(COMPORT.available())
+  {
+    char current = (char)COMPORT.read();
+
+    // if the maximum command length is reached or if the command is terminated with a new line
+    // character, the command buffer is terminated with a 0 chat and the command processing
+    // routine is called.
+    if(commandCursor >= CMD_BUFFER_SIZE || current == 10 || current == 13) {
+      commandBuffer[commandCursor] = 0;
+      commandCursor = 0;
+
+      parsePatternsToBuffer(commandBuffer);
+    }
+    else
+    {
+      commandBuffer[commandCursor++] = current;
+    }
+  }
+}


avoid 12 bit overflow errors

avoid 12 bit overflow errors

use 13 bit of raw values to avoid overflow errors (jumps from HIGH to LOW and back)

--- LBridge_Arduino_V09/LBridge_Arduino_V09.ino
+++ LBridge_Arduino_V09/LBridge_Arduino_V09.ino
@@ -970,7 +970,7 @@
 }

 float Glucose_Reading(unsigned int val) {
-  int bitmask = 0x0FFF;
+  int bitmask = 0x1FFF;		/* use 13 bit to avoid overflow errors */
   return ((val & bitmask) / 8.5);
 }


Welcome screen

Welcome screen

--- retroduino.ino
+++ retroduino.ino
@@ -12,6 +12,16 @@
    Serial.begin(9600);
    g.begin();
    c.begin();
+   g.text("RETRODUINO",1,10);
+   while (true){
+    if (c.is_key_down(K_LEFT)||c.is_key_down(K_RIGHT) ){
+
+      break;
+
+      }
+
+    }
+   g.clear();

    // init all entities
    ball.on_init();


Fix for C64 to modem flow control

Fix for C64 to modem flow control

--- MicroView/WiFiModem-Menu/WiFiModem-Menu.ino
+++ MicroView/WiFiModem-Menu/WiFiModem-Menu.ino
@@ -1190,11 +1190,11 @@
     if (Modem_flowControl || BAUD_RATE >= MIN_FLOW_CONTROL_RATE)
     {
         // Check that C64 is ready to receive
-        while (digitalReadFast(WIFI_CTS) == HIGH)   // If not...
-        {
-            digitalWriteFast(C64_RTS, LOW);     // ..stop data from Wi-Fi and wait
-        }
-        digitalWriteFast(C64_RTS, HIGH);
+        while (digitalReadFast(WIFI_RTS) == HIGH)   // If not...
+        {
+            digitalWriteFast(C64_CTS, LOW);     // ..stop data from Wi-Fi and wait
+        }
+        digitalWriteFast(C64_CTS, HIGH);
     }
 }


Added initial packet to announce presence.

--- things/examples/arduino/PressureMat/PressureMat/PressureMat.ino
+++ things/examples/arduino/PressureMat/PressureMat/PressureMat.ino
@@ -14,6 +14,8 @@
 byte mac[] = { 0x0, 0xA2, 0xDA, 0x0D, 0x90, 0xE2 };  // Arduino Ethernet

 char packetBuffer[512];
+
+PROGMEM prog_char *initialPacket = "{\"path\":\"/api/v1/thing/reporting\",\"requestID\":\"1\",\"things\":{\"/device/sensor/arduino/mat\":{\"prototype\":{\"device\":{\"name\":\"60# pressure mat (902PR)\",\"maker\":\"United Security Products\"},\"name\":\"true\",\"status\":[\"present\",\"absent\",\"recent\"],\"properties\":{\"pressure\":[\"on\",\"off\"]}},\"instances\":[]}}}";

 PROGMEM prog_char *loopPacket1 = "{\"path\":\"/api/v1/thing/reporting\",\"requestID\":\"";
 PROGMEM prog_char *loopPacket2 = "\",\"things\":{\"/device/sensor/arduino/mat\":{\"prototype\":{\"device\":{\"name\":\"60# pressure mat (902PR)\",\"maker\":\"United Security Products\"},\"name\":\"true\",\"status\":[\"present\",\"absent\",\"recent\"],\"properties\":{\"pressure\":[\"on\",\"off\"]}},\"instances\":[{\"name\":\"Pressure Mat\",\"status\":\"present\",\"unit\":{\"serial\":\"";
@@ -63,6 +65,12 @@
   Serial.println();

   udp.beginMulti(ip,port);
+
+  // Send intital packet to announce that we're here.
+  Serial.println((char*)pgm_read_word(&initialPacket));
+  udp.beginPacket(udp.remoteIP(), udp.remotePort());
+  udp.write((char*)pgm_read_word(&initialPacket));
+  udp.endPacket();

 }


Added more complex sync thread example

Added more complex sync thread example

--- examples/Threads/SynchronisedThreads/SynchronisedThreads.ino
+++ examples/Threads/SynchronisedThreads/SynchronisedThreads.ino
@@ -3,15 +3,20 @@
 IO::PIC32 Core;
 IO::Pin LED(Core, 13, IO::OUTPUT, IO::LOW);

+UART1 Serial;
 const char states[] = {'Z', 'R', 'S', 'H', 'M', 'W'};

 thread blnk;
 thread topscreen;

+extern uint32_t isr_count;
+
 semaphore sem;

 void setup() {
-	printf("\e[2J");
+	Serial.begin(115200);
+	Serial.print("\e[2J");
+//	printf("\e[2J");
 	blnk = Thread::Create("blink",blinker, 0, 512);
 	topscreen = Thread::Create("top",top, 0, 512);
 }
@@ -22,9 +27,9 @@
 	while(1) {
 		Thread::Signal(sem);
 		LED.write(IO::HIGH);
+		Thread::Sleep(10);
+		LED.write(IO::LOW);
 		Thread::Sleep(100);
-		LED.write(IO::LOW);
-		Thread::Sleep(500);
 	}
 }

@@ -32,20 +37,41 @@
 extern thread currentThread;

 void top(uint32_t x) {
+	int lastCharacter = -1;
 	while(1) {
+		uint32_t ms = 0;
 		Thread::Wait(sem);
-	    printf("\e[0;0H");
-	    printf("Uptime: %lums\n", Thread::Milliseconds());
-	    printf("Entry    Thread     Stack %%CPU S A\n");
+		if (Serial.available()) {
+			lastCharacter = Serial.read();
+		}
+	    Serial.print("\e[0;0H");
+
+	    Serial.print("Uptime: ");
+	    Serial.println(Thread::Milliseconds());
+	    Serial.println("Entry    Thread         Stack CPU% S A");
 	    for (thread scan = ThreadList; scan; scan = scan->next) {
-	        printf("%08X %-10s %-4d %4d%% %c %c\n",
+	        Serial.printf("%08X %-14s %-4d %4u%% %c %c\n",
 	            scan->entry,
 	            scan->name, (scan->stack_head - scan->sp) * 4,
-	            Thread::Runtime(scan) * 100 / Thread::Milliseconds(),
+	            Math::DivU(Math::MulU(Thread::Runtime(scan), 100), Thread::Milliseconds()),
 	            states[scan->state],
 	            scan == currentThread? '*' : ' '
 	        );
+	        ms += Thread::Runtime(scan);
 	    }
-		Thread::Sleep(100);
+	    Serial.printf("Calculated ms: %u\n", ms);
+	    Serial.println();
+	    Serial.printf("Last character pressed: %3d (%c)\n", lastCharacter, lastCharacter >= ' ' && lastCharacter <= 'z' ? lastCharacter : '.');
+	    Serial.println();
+	    Serial.println("Serial RX Circular Buffer Contents:");
+	    for (uint8_t x = 0; x < 64; x++) {
+	    	Serial.printf("%02X ", Serial.rxBuffer->getEntry(x));
+	    	if (Math::ModU(x, 16) == 15) {
+	    		Serial.println();
+	    	}
+	    }
+    	Serial.println();
+    	Serial.printf("Head: %3d Tail: %3d\n", Serial.rxBuffer->getHead(), Serial.rxBuffer->getTail());
+    	Serial.printf("ISR Hits: %d\n", isr_count);
 	}
 }


Make input have seqNo bit which determines whether command is redundant

--- SDPArduinoCode/SDPArduinoCode.ino
+++ SDPArduinoCode/SDPArduinoCode.ino
@@ -15,6 +15,8 @@
 #define KICK 5
 #define GRAB 6

+int  lastSeqNo;
+
 void setup(){

   SDPsetup();
@@ -30,6 +32,19 @@
    helloWorld();
 }

+// Returns true if the command should be ignored (duplicate command)
+// Origin of idea:
+// https://bitbucket.org/angel-ignatov/sdp14-15-group-15/src/150da3baeb2045b83add95c70cfca494873c4180/arduino/arduino.ino?at=master&fileviewer=file-view-default
+bool ignore(int seqNo)
+{
+  if (seqNo == lastSeqNo) {
+    return true;
+  } else {
+    lastSeqNo = seqNo;
+    return false;
+  }
+}
+

 int getNumFromChar(char c){
   int r = (int)c - (int)'0';
@@ -38,6 +53,11 @@

 int getSig(String c){
   int r = getNumFromChar(c[0]);
+  return r;
+}
+
+int getSeqNo(String c){
+  int r = getNumFromChar(c[6]);
   return r;
 }

@@ -170,7 +190,11 @@
       // need to check if signuture is our teams first!
       // avoids unessacary computation on the arduino if it is not a message for out team.
       int sig = getSig(c);
-      if(sig != 0){ return; }
+      int seqNo = getSeqNo(c);
+
+      // Quits if sig belongs to other teams
+      // OR if command is redundant (i.e. already executed)
+      if(sig != 0 || ignore(seqNo)){ return; }

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


upd: change wifi connect

upd: change wifi connect

--- ArduinoFirmwareEsp/WebServer.ino
+++ ArduinoFirmwareEsp/WebServer.ino
@@ -9,13 +9,12 @@

 // extern "C" void system_set_os_print(uint8 onoff);    //TODO to test without
 // extern "C" void ets_install_putc1(void* routine);
-
-int tot;        //need to save the number of the networks scanned
+int tot = 0;
 String staticIP_param ;
 String netmask_param;
 String gateway_param;
 String dhcp = "on";
-bool connect = false;
+bool connect_wifi = false;
 //String HOSTNAME = "arduino";

@@ -38,29 +37,11 @@

 bool handleFileRead(String path){
   if(path.endsWith("/")) path += "index.html";
-  //Serial.println("13");
   String contentType = getContentType(path);
-  //Serial.println("14");
-  //String pathWithGz = path + ".gz";
-  //Serial.println("15");
-  //ETS_SPI_INTR_DISABLE();
-  //if(SPIFFS.exists(pathWithGz) || SPIFFS.exists(path)){
-    //Serial.println("16");
-    // if(SPIFFS.exists(pathWithGz))
-    //   path += ".gz";
-    //Serial.println("17");
-    File file = SPIFFS.open(path, "r");
-    //Serial.println("18");
-    ETS_SPI_INTR_DISABLE();
-    size_t sent = server.streamFile(file, contentType);
-    ETS_SPI_INTR_ENABLE();
-    //Serial.println("19");
-    file.close();
-    //Serial.println("20");
-    return true;
-  //}
-  //return false;
-  //ETS_SPI_INTR_ENABLE();
+  File file = SPIFFS.open(path, "r");
+  size_t sent = server.streamFile(file, contentType);
+  file.close();
+  return true;
 }

 String toStringIp(IPAddress ip) {
@@ -174,6 +155,12 @@
 }

 void handleWebServer(){
+  if(connect_wifi){
+    ETS_SPI_INTR_DISABLE();
+    WiFi.begin(newSSID_param.c_str(),newPASSWORD_param.c_str());
+    connect_wifi = false;
+    ETS_SPI_INTR_ENABLE();
+  }
   if(CommunicationLogic.UI_alert){			//stop UI SERVER
     if(!SERVER_STOP){
       server.stop();
@@ -191,8 +178,6 @@

   //"wifi/info" information
   server.on("/wifi/info", []() {
-
-    //ETS_SPI_INTR_DISABLE();
     String ipadd = (WiFi.getMode() == 1 || WiFi.getMode() == 3) ? toStringIp(WiFi.localIP()) : toStringIp(WiFi.softAPIP());
     String staticadd = dhcp.equals("on") ? "0.0.0.0" : staticIP_param;
     int change = WiFi.getMode() == 1 ? 3 : 1;
@@ -204,49 +189,33 @@
                                             + WiFi.RSSI() + "\",\"mac\":\"" + WiFi.macAddress() + "\",\"phy\":\"" + WiFi.getPhyMode() + "\", \"dhcp\": \"" + dhcp + "\", \"staticip\":\"" + staticadd +
                                             + "\", \"warn\": \"" + "Switch to " + toStringWifiMode(change) + " mode\""
                                             + "}" ));
-      //ETS_SPI_INTR_ENABLE();
-
     });

     //"system/info" information
     server.on("/system/info", []() {
-
-            //ETS_SPI_INTR_DISABLE();
-            server.send(200, "text/plain", String("{\"heap\":\""+ String(ESP.getFreeHeap()/1024)+" KB\",\"id\":\"" + String(ESP.getFlashChipId()) + "\",\"size\":\"" + (ESP.getFlashChipSize() / 1024 / 1024) + " MB\",\"baud\":\"9600\"}"));
-            //ETS_SPI_INTR_ENABLE();
-
-    });
+      server.send(200, "text/plain", String("{\"heap\":\""+ String(ESP.getFreeHeap()/1024)+" KB\",\"id\":\"" + String(ESP.getFlashChipId()) + "\",\"size\":\"" + (ESP.getFlashChipSize() / 1024 / 1024) + " MB\",\"baud\":\"9600\"}"));
+    });
+
     server.on("/heap", []() {
-
       server.send(200, "text/plain", String(ESP.getFreeHeap()));
-
     });

     server.on("/system/update", []() {
-
       String newhostname = server.arg("name");
       WiFi.hostname(newhostname);
       MDNS.begin(newhostname.c_str());
       MDNS.setInstanceName(newhostname);
-      // Config.getParam("hostname");  //TODO remove
-      // Config.getParam("ssid");
-      // Config.getParam("password");
       server.send(200, "text/plain", newhostname);
       Config.setParam("hostname", newhostname);
-
     });

     server.on("/wifi/netNumber", []() {
-
         tot = WiFi.scanNetworks();
         server.send(200, "text/plain", String(tot));
-
     });

     server.on("/wifi/scan", []() {
-
       String scanResp = "";
-
       if (tot == 0) {
         server.send(200, "text/plain", "No networks found");
       }
@@ -272,32 +241,25 @@
       scanResp += "]}}";
       //ETS_SPI_INTR_ENABLE();
       server.send(200, "text/plain", scanResp);
-
     });

     server.on("/connect", []() {
-
       newSSID_param = server.arg("essid");
       newPASSWORD_param = server.arg("passwd");
       server.send(200, "text/plain", "1");
-      WiFi.begin(newSSID_param.c_str(),newPASSWORD_param.c_str());
-      //WiFi.softAPConfig(default_IP, default_IP, IPAddress(255, 255, 255, 0));   //set default ip for AP mode
-      //WiFi.hostname(WiFi.hostname());
+      //WiFi.begin(newSSID_param.c_str(),newPASSWORD_param.c_str());
       Config.setParam("ssid", newSSID_param);
       Config.setParam("password", newPASSWORD_param);
-
+      connect_wifi = true;
     });

     server.on("/connstatus", []() {
-
         String ipadd = (WiFi.getMode() == 1 || WiFi.getMode() == 3) ? toStringIp(WiFi.localIP()) : toStringIp(WiFi.softAPIP());
         server.send(200, "text/plain", String("{\"url\":\"got IP address\", \"ip\":\""+ipadd+"\", \"modechange\":\"no\", \"ssid\":\""+WiFi.SSID()+"\", \"reason\":\"-\", \"status\":\""+ toStringWifiStatus(WiFi.status()) +"\"}"));
-
     });

     server.on("/setmode", []() {
-
       int newMode = server.arg("mode").toInt();

       switch (newMode){
@@ -315,7 +277,6 @@
     });

     server.on("/special", []() {
-
        dhcp = server.arg("dhcp");
        staticIP_param = server.arg("staticip");
        netmask_param = server.arg("netmask");
@@ -333,11 +294,9 @@
            delay ( 5000 );
          }
        }
-
      });

      server.on("/boardInfo", []() {
-
         StaticJsonBuffer<200> jsonBuffer;
         JsonObject& boardInfo = jsonBuffer.createObject();
         String output = "";
@@ -361,16 +320,13 @@
         }
         boardInfo.printTo(output);
         server.send(200, "text/json", output);
-
       });

     //called when the url is not defined here
     //use it to load content from SPIFFS
     server.onNotFound([](){
-
       if(!handleFileRead(server.uri()))
         server.send(404, "text/plain", "FileNotFound");
-
     });

     server.begin();


adjust battery indicator levels

adjust battery indicator levels

--- rcxr01_demo1/src/rcxr01_demo1.ino
+++ rcxr01_demo1/src/rcxr01_demo1.ino
@@ -25,7 +25,7 @@
 #define USB_DETECT_PIN  2   // PB2
 uint8_t on_battery;
 #define BATT_LEVEL_HIGH 2500
-#define BATT_LEVEL_MED  2100
+#define BATT_LEVEL_MED  2200
 #define BATT_LEVEL_LOW  1900

 uint8_t i;


494 bytes saved so far

494 bytes saved so far

--- arduboy-game/arduboy-game.ino
+++ arduboy-game/arduboy-game.ino
@@ -766,60 +766,56 @@

   while(! allDone) {
     unsigned long currentMilliseconds = millis();
-    if (arduboy.pressed(A_BUTTON)) {
-      if ((currentMilliseconds - lastDebounceTime) > DEBOUNCE_DELAY) {
-        // Advance right or finish entering initials
-        if (currPos < 2) {
-          currPos++;
-          drawHighScoreEntryCursor(currPos);
-          arduboy.display();
-        } else {
-          allDone = true;
-        }
-        lastDebounceTime = currentMilliseconds;
-      }
-    }
-
-    if (arduboy.pressed(LEFT_BUTTON)) {
-      if ((currentMilliseconds - lastDebounceTime) > DEBOUNCE_DELAY) {
+    const bool isGreater = (currentMilliseconds - lastDebounceTime) > DEBOUNCE_DELAY;
+
+    if (isGreater) {
+      if (arduboy.pressed(A_BUTTON)) {
+          // Advance right or finish entering initials
+          if (currPos < 2) {
+            currPos++;
+            drawHighScoreEntryCursor(currPos);
+//            arduboy.display();
+          }
+          else {
+            allDone = true;
+          }
+          lastDebounceTime = currentMilliseconds;
+      }
+
+      if (arduboy.pressed(LEFT_BUTTON)) {
         // Only do something if we are not already on leftmost one
         if (currPos > 0) {
           currPos--;
           drawHighScoreEntryCursor(currPos);
-          arduboy.display();
+//          arduboy.display();
         }
         lastDebounceTime = currentMilliseconds;
       }
-    }
-
-    if (arduboy.pressed(RIGHT_BUTTON)) {
-      if ((currentMilliseconds - lastDebounceTime) > DEBOUNCE_DELAY) {
+
+      if (arduboy.pressed(RIGHT_BUTTON)) {
         // Only do something if we are not already on rightmost one
         if (currPos < 2) {
           currPos++;
           drawHighScoreEntryCursor(currPos);
-          arduboy.display();
+//          arduboy.display();
         }
         lastDebounceTime = currentMilliseconds;
       }
-    }
-
-    if (arduboy.pressed(UP_BUTTON)) {
-       if ((currentMilliseconds - lastDebounceTime) > DEBOUNCE_DELAY) {
+
+      if (arduboy.pressed(UP_BUTTON)) {
           if (currInitials[currPos] == 96) {
             currInitials[currPos] = 32;
           } else {
             currInitials[currPos]++;
           }
+
           sprintf(textBuf, "%c%c%c", currInitials[0], currInitials[1], currInitials[2]);
           printText(textBuf, 44, 45, 2);
-          arduboy.display();
+//          arduboy.display();
           lastDebounceTime = currentMilliseconds;
        }
-    }
-
-    if (arduboy.pressed(DOWN_BUTTON)) {
-       if ((currentMilliseconds - lastDebounceTime) > DEBOUNCE_DELAY) {
+
+       if (arduboy.pressed(DOWN_BUTTON)) {
           if (currInitials[currPos] == 32) {
             currInitials[currPos] = 96;
           } else {
@@ -827,9 +823,11 @@
           }
           sprintf(textBuf, "%c%c%c", currInitials[0], currInitials[1], currInitials[2]);
           printText(textBuf, 44, 45, 2);
-          arduboy.display();
+//          arduboy.display();
           lastDebounceTime = currentMilliseconds;
-       }
+       }
+       arduboy.display();
+
     }
   }

@@ -859,6 +857,7 @@
   starX[i] = random(250);
   starY[i] = random(75);
   starWidth[i] = random(1, 4);
+

   if (starWidth[i] >= 3) {
 //    starSpeed[i] = random(75, 95) * 0.01f;


Improved frequency precision

Improved frequency precision

--- arduino/fasnacht/fasnacht.ino
+++ arduino/fasnacht/fasnacht.ino
@@ -94,8 +94,8 @@
     time = finish - start;

     //calculate freq
-    ValueFrq = ValueCount * 100 / time / 2 * 10;
-    ChannelFrq = ChannelCount * 100 / time / 2 * 10;
+    ValueFrq = ValueCount * 100 / (time / 10) / 2;
+    ChannelFrq = ChannelCount * 100 / (time / 10) / 2;

     //get channel data and write output LEFT AUIO CHANNEL
     Serial.print(ValueCount);


update period_target for fly mode

update period_target for fly mode

--- Device_LinkItOne/LASS/LASS.ino
+++ Device_LinkItOne/LASS/LASS.ino
@@ -103,8 +103,9 @@

 int period_target[2][3]= // First index is POLICY_POLICY[Sensing period],[Upload period],[Wifi check period], unit is second
-//  {10,0,60, // don't care power
-  {60,10,60, // don't care power
+  {
+   60,60,60, // don't care power, normal mode
+   // 5,5,300, // don't care power, fly mode
    60,600,300  // power saving
   };


Update comments for Spark

Update comments for Spark

--- firmware/examples/interrupt/interrupt.ino
+++ firmware/examples/interrupt/interrupt.ino
@@ -8,6 +8,18 @@
 #include <Wire.h>
 #include "Adafruit_MCP23017.h"
 #endif
+
+// Basic pin reading and pullup test for the MCP23017 I/O expander
+// public domain!
+
+// Connect pin #12 of the expander to Analog 5 for Arduino and D1 for Spark Core (i2c clock)
+// Connect pin #13 of the expander to Analog 4 for Arduino and D0 for Spark Core (i2c data)
+// Connect pins #15, 16 and 17 of the expander to ground (address selection)
+// Connect pin #9 of the expander to 5V (power)
+// Connect pin #10 of the expander to ground (common ground)
+// Connect pin #18 through a ~10kohm resistor to 5V (reset pin, active low)
+
+// Output #0 is on pin 21 so connect an LED or whatever from that to ground

 Adafruit_MCP23017 mcp;


sketch: set up for homebridge as board LED, remove led matrix scrolling

--- src/sketch.ino
+++ src/sketch.ino
@@ -1,6 +1,5 @@
 #include "leds.h"
 #include "wifi.h"
-#include "led_matrix.h"
 #include "http.h"

 void setup() {
@@ -8,14 +7,13 @@
   Serial.println();  // Clear the garbage from ESP8266's ROM

   start_leds();
-  start_led_matrix();
   start_wifi();
   http_set_request_cb(router);
+
+  digitalWrite(PIN_LED_BOARD, HIGH);
 }

 void loop() {
-  handle_leds();
-  handle_led_matrix();
   handle_wifi();
 }

@@ -27,10 +25,25 @@
       http_respond(client, RC_405);
     }

-  } else if (strcmp(path, "/matrix") == 0) {
+  } else if (strcmp(path, "/light") == 0) {
     if (strcmp(method, "POST") == 0) {
-      http_respond(client, RC_204);
-      scroll_once(body);
+      if (strcmp(body, "0") == 0) {
+        digitalWrite(PIN_LED_BOARD, HIGH);
+        http_respond(client, RC_204);
+      } else if (strcmp(body, "1") == 0) {
+        digitalWrite(PIN_LED_BOARD, LOW);
+        http_respond(client, RC_204);
+      } else {
+        Serial.println("Unknown POST to /light:");
+        Serial.write(body);
+        http_respond(client, RC_500);
+      }
+    } else if (strcmp(method, "GET") == 0) {
+      if (digitalRead(PIN_LED_BOARD)) {
+        http_respond(client, RC_200, "0");
+      } else {
+        http_respond(client, RC_200, "1");
+      }
     } else {
       http_respond(client, RC_405);
     }


Added countdown logic which performs a countdown timer once the users has scanned in. Added ability for a user to scan out of the equipment which turns that machine off when the user is done.

--- MakerspaceOSRFIDAuthentication/MakerspaceOSRFIDAuthentication.ino
+++ MakerspaceOSRFIDAuthentication/MakerspaceOSRFIDAuthentication.ino
@@ -101,7 +101,13 @@
   Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, rows, cols );
 #endif

-
+unsigned long Watch, _micro, time = micros();
+unsigned int Clock = 0, R_clock;
+boolean Reset = false, Stop = false, Paused = false;
+volatile boolean timeFlag = false;
+String storedSerial;
+
+
 #ifdef USELCD
   // Attach the serial display's RX line to digital pin 2
   SoftwareSerial lcdSerial(3,2);
@@ -203,20 +209,49 @@
     pinMode(GREEN_LED, OUTPUT);
     pinMode(YELLOW_LED, OUTPUT);
     digitalWrite(YELLOW_LED, HIGH);
-   digitalWrite(GREEN_LED, HIGH);
-  digitalWrite(RED_LED, HIGH);
-  delay(2000);
-
+    digitalWrite(GREEN_LED, HIGH);
+    digitalWrite(RED_LED, HIGH);
+    delay(2000);
   #endif
   #ifdef USELCD
     ClearScreen();
     lcdSerial.write("Please scan card");
   #endif
+  Stop = true;
 }

 void loop()
 {
+  CountDownTimer(); // run the timer
+  if (TimeHasChanged())
+  {
+    #ifdef DEBUG
+      Serial.print(ShowHours());
+      Serial.print(":");
+      Serial.print(ShowMinutes());
+      Serial.print(":");
+      Serial.print(ShowSeconds());
+      Serial.print(":");
+      Serial.print(ShowMilliSeconds());
+      Serial.print(":");
+      Serial.println(ShowMicroSeconds());
+    #endif
+
+    // This DOES NOT format the time to 0:0x when seconds is less than 10.
+    // if you need to format the time to standard format, use the sprintf() function.
+    if(Stop == true)
+    {
+      #ifdef DEBUG
+        Serial.println("Stop reached");
+      #endif
+      #ifdef USELED
+
+      #endif
+       digitalWrite(RELAY1,HIGH);
+    }
+  }
+
       int gotCard = 0;
       String serial;
       String pin ="";
@@ -274,6 +309,21 @@

                 // Stop and disable RFID
           mfrc522.PICC_HaltA();
+          #ifdef DEBUG
+                 Serial.println("Read Serial:" + serial);
+                 Serial.println("Stored Serial:" + storedSerial);
+          #endif
+
+          if(serial == storedSerial)
+          {
+              digitalWrite(RELAY1,HIGH);
+              StopTimer();
+              SetTimer(0);
+              storedSerial = "";
+
+          }
+          else
+          {
           AccessResponse accessResponse;

           #ifdef USEWEBAUTHENTICATE
@@ -285,8 +335,14 @@
           #endif
           if(strcmp(accessResponse.AccessAllowed,"true")==0)
           {
+               storedSerial = serial;
+
+               #ifdef DEBUG
+                 Serial.println("Stored" + storedSerial);
+               #endif
+
                #ifdef USELED
-                 digitalWrite(GREEN_LED, HIGH);
+                 TurnOnLED(GREEN_LED);
                #endif
                #ifdef USETONE
                   tone(TONEPIN,300,1000);
@@ -306,18 +362,21 @@

                if(accessResponse.TimeLimit != 0)
                {
+
                  #ifdef DEBUG
                    Serial.println(accessResponse.TimeLimit);
                  #endif
                  //Need to add a countdown timer here so that time counts down the time remaining and outputs to the LCD
-                 delay(accessResponse.TimeLimit * 60000);
-                 digitalWrite(RELAY1,HIGH); //Turn off time limit expires.  Need to add the current check and other logic here.  Very basic rightnow.  Delay is not
+                 //delay(accessResponse.TimeLimit * 60000);
+                 CountDownTimer(); // run the timer
+                 SetTimer(0,0,accessResponse.TimeLimit * 60); // 10 seconds
+                 StartTimer();
                }

            }
            else{
                #ifdef USELED
-                  digitalWrite(RED_LED, HIGH);
+                  TurnOnLED(RED_LED);
                #endif
                #ifdef USETONE
                   tone(TONEPIN,100,1000);
@@ -329,17 +388,29 @@
                #endif
            }
            delay(2000);
+          }
         }
       }
       #ifdef USELED
-          digitalWrite(RED_LED, LOW);
-          digitalWrite(GREEN_LED, LOW);
-          digitalWrite(YELLOW_LED, HIGH);
+          TurnOnLED(YELLOW_LED);
       #endif
       #ifdef USELCD
            ClearScreen();
            lcdSerial.write("Please scan card");
       #endif
+}
+
+void TurnOnLED(int LED)
+{
+  TurnOffAllLED();
+  digitalWrite(LED,HIGH);
+
+}
+void TurnOffAllLED()
+{
+    digitalWrite(RED_LED, LOW);
+    digitalWrite(GREEN_LED, LOW);
+    digitalWrite(YELLOW_LED, LOW);
 }

 void ClearScreen()
@@ -377,16 +448,16 @@
           {
 	    char c = client.read();
 	    response = response + c;
-            Serial.println(c);
+            //Serial.println(c);
           }
 	}
-	#ifdef DEBUG
-		Serial.println(response);
-	#endif
+//	#ifdef DEBUG
+//		Serial.println(response);
+//	#endif

 	StaticJsonBuffer<200> jsonBuffer;
 	char charBuf[response.length() + 1];
-#ifdef DEBUG
+        #ifdef DEBUG
 		Serial.println(response);
 	#endif
 	response.toCharArray(charBuf, response.length() + 1);
@@ -418,3 +489,97 @@
 	return accessResponse;
   #endif
 }
+
+
+
+boolean CountDownTimer()
+{
+  static unsigned long duration = 1000000; // 1 second
+  timeFlag = false;
+
+  if (!Stop && !Paused) // if not Stopped or Paused, run timer
+  {
+    // check the time difference and see if 1 second has elapsed
+    if ((_micro = micros()) - time > duration )
+    {
+      Clock--;
+      timeFlag = true;
+
+      if (Clock == 0) // check to see if the clock is 0
+        Stop = true; // If so, stop the timer
+
+     // check to see if micros() has rolled over, if not,
+     // then increment "time" by duration
+      _micro < time ? time = _micro : time += duration;
+    }
+  }
+  return !Stop; // return the state of the timer
+}
+void StartTimer()
+{
+  Watch = micros(); // get the initial microseconds at the start of the timer
+  Stop = false;
+  Paused = false;
+}
+
+void StopTimer()
+{
+  Stop = true;
+}
+
+void SetTimer(unsigned int hours, unsigned int minutes, unsigned int seconds)
+{
+  // This handles invalid time overflow ie 1(H), 0(M), 120(S) -> 1, 2, 0
+  unsigned int _S = (seconds / 60), _M = (minutes / 60);
+  if(_S) minutes += _S;
+  if(_M) hours += _M;
+
+  Clock = (hours * 3600) + (minutes * 60) + (seconds % 60);
+  R_clock = Clock;
+  Stop = false;
+}
+
+void SetTimer(unsigned int seconds)
+{
+ // StartTimer(seconds / 3600, (seconds / 3600) / 60, seconds % 60);
+ Clock = seconds;
+ R_clock = Clock;
+ Stop = false;
+}
+int ShowHours()
+{
+  return Clock / 3600;
+}
+
+int ShowMinutes()
+{
+  return (Clock / 60) % 60;
+}
+
+int ShowSeconds()
+{
+  return Clock % 60;
+}
+
+unsigned long ShowMilliSeconds()
+{
+  return (_micro - Watch)/ 1000.0;
+}
+
+unsigned long ShowMicroSeconds()
+{
+  return _micro - Watch;
+}
+
+boolean TimeHasChanged()
+{
+  return timeFlag;
+}
+
+// output true if timer equals requested time
+boolean TimeCheck(unsigned int hours, unsigned int minutes, unsigned int seconds)
+{
+  return (hours == ShowHours() && minutes == ShowMinutes() && seconds == ShowSeconds());
+}
+
+


url change

url change

--- PulseSensorAmped_Arduino_1dot2/PulseSensorAmped_Arduino_1dot2.ino
+++ PulseSensorAmped_Arduino_1dot2/PulseSensorAmped_Arduino_1dot2.ino
@@ -20,7 +20,7 @@
 If you want to use pin 13 for something else, adjust the interrupt handler
 It will also fade an LED on pin fadePin with every beat. Put an LED and series resistor from fadePin to GND.
 Check here for detailed code walkthrough:
-http://pulsesensor.myshopify.com/pages/pulse-sensor-amped-arduino-v1dot1
+http://www.pulsesensor.com

 Code Version 1.2 by Joel Murphy & Yury Gitman  Spring 2013
 This update fixes the firstBeat and secondBeat flag usage so that realistic BPM is reported.


cruise is being moved to MINDSi

cruise is being moved to MINDSi

--- examples/cruiseControl/cruiseControl.ino
+++ examples/cruiseControl/cruiseControl.ino
@@ -1,13 +0,0 @@
-#include "Wire.h"
-#include "SPI.h"
-#include "Servo.h"
-#include "DroneLibs.h"
-/*
-Encoder, Simple cruise control, perhaps one with radiodrive and one without.
-*/
-void setup(){
-
-}
-void loop(){
-
-}


updated control app

updated control app

--- beanWheelwriterControl/beanWheelwriterControl.ino
+++ beanWheelwriterControl/beanWheelwriterControl.ino
@@ -127,7 +127,8 @@
       }
       byte digital1 = digitalRead(d1);
       if (digital1 == 0) {
-        fastText("this is really fast");
+        forwardSpaces(5);
+        //fastText("this is really fast");
         //send_letter(0b000000001); // 'a'
         //send_letter(0b001011001); // 'b'
         //send_letter(0b000000100); // 'm'
@@ -468,6 +469,29 @@
     sendByteOnPin(0b000001011);
 }

+void forwardSpaces(int num_spaces) {
+    sendByte(0b100100001);
+    sendByte(0b000001110);
+    sendByte(0b010010110);
+    sendByte(0b100100001);
+    sendByte(0b000001011);
+    sendByte(0b100100001);
+    sendByte(0b000001101);
+    sendByte(0b000000110);
+    sendByte(0b100100001);
+    sendByte(0b000000110);
+
+    //sendByte(0b010000001);
+    sendByte(0b010000000);
+
+    sendByte(0b001111100);
+    sendByte(0b100100001);
+    sendByte(0b000000111);
+    sendByte(0b100100001);
+    sendByte(0b000001001);
+    sendByte(0b010000000);
+}
+
 void sendByte(int b) {
         //Serial.println("sending byte!");
         sendByteOnPin(b);


Delay with the remaining budget after measuring pulse instead

Also: comment these lines out because apparently a delay is a problem.

--- code/oakpowerboard/oakpowerboard.ino
+++ code/oakpowerboard/oakpowerboard.ino
@@ -106,7 +106,8 @@
       digitalWrite(1, curr_btn_state ? HIGH : LOW);
       btn_state = curr_btn_state;
     }
-    delay(remainingTimeBudget);
+    //if(millis() < deadline)
+    //  Particle.delay(millis() - deadline);
   }
 }


Added Can_bus_shield library

Added Can_bus_shield library

--- Firmware/Firmware.ino
+++ Firmware/Firmware.ino
@@ -1,9 +1,50 @@
-void setup() {
-  // put your setup code here, to run once:
+// demo: CAN-BUS Shield, receive data
+#include <mcp_can.h>
+#include <SPI.h>

+unsigned char Flag_Recv = 0;
+unsigned char len = 0;
+unsigned char buf[8];
+char str[20];
+
+void setup()
+{
+  attachInterrupt(0, MCP2515_ISR, FALLING);     // start interrupt
+  Serial.begin(115200);
+
+  if(CAN.begin(CAN_500KBPS) ==CAN_OK) Serial.print("can init ok!!\r\n");
+  else Serial.print("Can init fail!!\r\n");
 }

-void loop() {
-  // put your main code here, to run repeatedly:
+void MCP2515_ISR()
+{
+    Flag_Recv = 1;
+}
+
+void loop()
+{
+    if(Flag_Recv)                           // check if get data
+    {
+      Flag_Recv = 0;                        // clear flag
+      CAN.readMsgBuf(&len, buf);            // read data,  len: data length, buf: data buf
+      Serial.println("CAN_BUS GET DATA!");
+      Serial.print("data len = ");
+      Serial.println(len);
+
+      for(int i = 0; i<len; i++)            // print the data
+      {
+        Serial.print(buf[i]);Serial.print("\t");
+      }
+      Serial.println();
+    }
+
+  // send data:  id = 0x00, standrad flame, data len = 8, stmp: data buf

+  unsigned char test[2] = "$";
+  CAN.sendMsgBuf(0x00, 0, 2, test);
+  delay(100);                       // send data per 100ms
 }
+
+/*********************************************************************************************************
+  END FILE
+*********************************************************************************************************/


better wake up time

better wake up time

--- main.ino
+++ main.ino
@@ -141,7 +141,7 @@
   t = rtc.getTime();
   Serial.println(t.min);
   Serial.println(t.hour);
-  if (!((t.min == 30) && (t.hour == 18)))
+  if (!((t.min == 40) && (t.hour == 7)))
   {
     delay(500);
     return;


Test commit

Test commit

--- src/cyclop_plus/cyclop_plus.ino
+++ src/cyclop_plus/cyclop_plus.ino
@@ -37,7 +37,7 @@

 // Library includes
 #include <avr/pgmspace.h>
-#include <string.h>
+#include <string.h>
 #include <EEPROM.h>
 #ifdef SSD1306_OLED_DRIVER
 #include <Adafruit_SSD1306.h>


Partial refactor of LowLevel. Compute conversion for motor feedback to kph.

--- Elcano_C2_LowLevel/Elcano_C2_LowLevel.ino
+++ Elcano_C2_LowLevel/Elcano_C2_LowLevel.ino
@@ -12,16 +12,14 @@
 #define ERROR_HISTORY 20

 // Orange Trike
-#define VEHICLE_NUMBER 1
+//#define VEHICLE_NUMBER 1
+
+// Yellow Trike
+#define VEHICLE_NUMBER 2
+
+#if (VEHICLE_NUMBER == 1)
 #define RC_SPEKTRUM
 #undef  RC_HITEC
-
-// Yellow Trike
-//#define VEHICLE_NUMBER 2
-//#undef RC_SPEKTRUM
-//#define  RC_HITEC
-
-#if (VEHICLE_NUMBER == 1)
 //OUTPUT values -  0 to 255
 #define MIN_ACC_OUT 40
 #define MAX_ACC_OUT 227
@@ -38,11 +36,13 @@
 #define DAC_CHANNEL 0    // output to motor actuator
 #define STEER_OUT_PIN 7 // Output to steer actuator
 #define BRAKE_OUT_PIN 6  // output to brake actuator
-
+#define WHEEL_DIAMETER_MM 397
+#define MOTOR_POLE_PAIRS 23
 #endif

 #if (VEHICLE_NUMBER == 2)
-
+#undef RC_SPEKTRUM
+#define  RC_HITEC
 //OUTPUT values -  0 to 255
 #define MIN_ACC_OUT 50
 #define MAX_ACC_OUT 227
@@ -59,8 +59,27 @@
 #define DAC_CHANNEL 3
 #define STEER_OUT_PIN 7 // Output to steer actuator
 #define BRAKE_OUT_PIN 9  // output to brake actuator
-
+#define WHEEL_DIAMETER_MM 500
+#define MOTOR_POLE_PAIRS 23
 #endif
+
+// Distance the wheel outer circumference moves during one phase cycle.
+const float WHEEL_PHASE_DISTANCE_MM = WHEEL_DIAMETER_MM * PI / MOTOR_POLE_PAIRS;
+// Conversion factor from 1 / (motor phase cycle time in microseconds) to speed
+// in km/h:
+// There are MOTOR_POLE_PAIRS phase cycles per wheel rotation, so the time for
+// one wheel rotation (based on a single phase cycle) is the duration of that
+// phase cycle times the number of pole pairs.  Also, we want km / h rather
+// than mm / usec.  Units conversion:
+// speed measured in km / hr
+// = (speed measured in mm / usec) * (km / 10^6 mm) * (3600 * 10^6 usec / hr)
+// = (speed in mm / usec) * 3600
+// = (wheel phase distance in mm / motor feedback cycle time in usec) * 3600
+// = (wheel phase distance in mm * 3600) / (motor feedback cycle time in usec)
+// The first part is a constant for a given motor and wheel diameter:
+const float HUB_PHASE_TO_KMPH = WHEEL_PHASE_DISTANCE_MM * 3600;
+// For a motor with 23 pole pairs and a 500 mm diameter drive wheel, this is
+// about 245863.8.

 /*================ReadTurnAngle ================*/
 // Value measured at analog input A2 from right steering column when wheels pointed straight ahead.
@@ -136,8 +155,9 @@
 const int IRPT_RVS = 0;   // D2  = Int 0
 const int IRPT_TURN = 2;  // D21 = Int 2
 const int IRPT_GO = 3;   //  D20 = Int 3
+// RDR (rudder) is not used. Instead, use this interrupt for the motor phase
+// feedback, which gives speed.
 const int IRPT_RDR = 5;   // D18 = Int 5
-// RDR (rudder) is not used. Instead, use this interrupt for the motor phase feedback, which gives speed.
 const int IRPT_ESTOP = 4; // D19 = Int 4
 //RC input values - pulse widths in microseconds
 const int DEAD_ZONE = 75;
@@ -147,6 +167,16 @@
 const int MAX_RC = 1800;
 #endif
 //  D3 = Int 1  Wheel Click
+
+// Currently different interrupts are used for the motor phase feedback.
+#if (VEHICLE_NUMBER == 1)
+#define RC_MOTOR_FEEDBACK RC_RVS
+const int IRPT_MOTOR_FEEDBACK = IRPT_RVS;
+#endif
+#if (VEHICLE_NUMBER == 2)
+#define RC_MOTOR_FEEDBACK RC_RDR
+const int IRPT_MOTOR_FEEDBACK = IRPT_RDR;
+#endif

 long speed_errors[ERROR_HISTORY];
 long old_turn_degx1000;
@@ -168,18 +198,12 @@
   interrupts();
 }

+// RDR (rudder) is currently not used.
 void ISR_RDR_rise() {
-// RDR (rudder) is not used. Instead, use this interrupt for the motor phase feedback, which gives speed.
   noInterrupts();
   unsigned long old_phase_rise = RC_rise[RC_RDR];
   ProcessRiseOfINT(RC_RDR);
   RC_elapsed[RC_RDR] = RC_rise[RC_RDR] - old_phase_rise;
-  // The phase frequency is proportional to wheel rotation.
-  // An e-bike hub is powered by giving it 3 phased 36 V lines
-  // The e-bike controller needs feeback from the hub.
-  // The hub supplies 3 Hall Phase sensors; each is a 5V square wave and tells how fast the wheel rotates.
-  // The square wave feedback has sone noise, which is cleaned up by an RC low pass filter
-  //  with R = 1K, C = 100 nF
   interrupts();
 }

@@ -236,6 +260,34 @@
   attachInterrupt(IRPT_RVS, ISR_RVS_rise, RISING);
   interrupts();
 }
+
+// An e-bike hub motor is powered by giving it 3 phase power. This is supplied
+// by the motor controller. The controller needs feeback from the hub.  It
+// receives three feedback signals from the motor, one for each phase.  These
+// are the *actual* phase rotation of the motor, not the phases supplied by the
+// controller, which differ from what the motor is currently doing whenever the
+// controller is attempting to speed up or slow down or change direction of the
+// motor. The motor phase feedback pulse rate is an integer multiple of wheel
+// rotation rate. The factor is the number of pole pairs in the motor. Note
+// that the controller has no idea how many pole pairs the motor has, so it
+// only controls the phase rate, not the actual rotation rate.  It is "someone
+// else's problem" to limit the actual rotation rate or speed. The feedback
+// signals are 5V square waves.  They have some noise -- spikes of several
+// volts, which exceeds the maximum voltage allowed for Arduino inputs, which
+// is 5.5V.  The signal is cleaned up by an RC low pass filter with R = 1K,
+// C = 100 nF.
+void ISR_MOTOR_FEEDBACK_rise() {
+  noInterrupts();
+  // This differs from the other interrupt routines since we need the *cycle*
+  // duration, not the width of the high pulse.  So here, we get the time from
+  // the previous rising edge to the current rising edge.  Q: Are we properly
+  // ignoring the first value from all of these interval computations?
+  unsigned long old_phase_rise = RC_rise[RC_MOTOR_FEEDBACK];
+  ProcessRiseOfINT(RC_MOTOR_FEEDBACK);
+  RC_elapsed[RC_MOTOR_FEEDBACK] = RC_rise[RC_MOTOR_FEEDBACK] - old_phase_rise;
+  interrupts();
+}
+
 //----------------------------------------------------------------------------
 void setup()
 { //Set up pins
@@ -249,6 +301,7 @@
       SPI.setBitOrder( MSBFIRST);
       // initialize SPI:
       // The following line should not be neccessary. It uses a system library.
+      // Note PRR0 and PRR1 are defined for the Mega 2560 but smaller boards have just PRR.
       PRR0 &= ~4; // turn off PRR0.PRSPI bit so power isn't off
       SPI.begin();
       for (int channel = 0; channel < 4; channel++)
@@ -275,10 +328,11 @@
       CalibrateTurnAngle(32, 20);
       calibrationTime_ms = millis();
       attachInterrupt(IRPT_TURN,  ISR_TURN_rise,  RISING);
-      attachInterrupt(IRPT_RDR,   ISR_RDR_rise,   RISING);
+      //attachInterrupt(IRPT_RDR,   ISR_RDR_rise,   RISING);
       attachInterrupt(IRPT_GO,    ISR_GO_rise,    RISING);
       attachInterrupt(IRPT_ESTOP, ISR_ESTOP_rise, RISING);
-      attachInterrupt(IRPT_RVS,   ISR_RVS_rise,   RISING);
+      //attachInterrupt(IRPT_RVS,   ISR_RVS_rise,   RISING);
+      attachInterrupt(IRPT_MOTOR_FEEDBACK, ISR_MOTOR_FEEDBACK_rise, RISING);
       Print7headers(false);
       PrintHeaders();
 }
@@ -296,6 +350,16 @@
     unsigned long local_results[7];
 //  PrintDone();

+  // ToDo: Refactor this to not have a spinloop.
+  // We get three signals from the RC controller in turn, one each for RC_ESTP,
+  // RC_GO, and RC_TURN. The three signals are sent separately. We get triples of
+  // new RC values at about 30Hz, which is faster than the loop runs. It doesn't
+  // really matter if we are using exactly the latest value, as there isn't much
+  // change between one an the next, except for ESTP, and if we wait til the next
+  // loop pass for that, it should be ok. So just have the interrupt routines read
+  // the RC information and store it, then the loop can use the latest values.
+  // It should check that it has received any values, since the Arduino may be
+  // started before the RC controller is turned on.
   while (micros() < nextTime &&
     ~((RC_Done[RC_ESTP] == 1) && (RC_Done[RC_GO] == 1) && (RC_Done[RC_TURN] == 1) ))
     ;  //wait
@@ -303,14 +367,14 @@
     // got data;
     for (int i = 0; i < 8; i++)
         local_results[i] = RC_elapsed[i];
-  Print7( false, local_results);
+    Print7(false, local_results);
     processRC(local_results);
 //    Print7( true, local_results);

     Results.Clear();
     Results.kind = MSG_SENSOR;
     Results.angle_deg = TurnAngle_degx10() / 10;
-    //show_speed (&Results);
+    show_speed (&Results);

     // Report how long the loop took.
     unsigned long endTime = micros();
@@ -489,11 +553,11 @@
     /* 5th pulse is rudder (position 3 on receiver; controlled by Left left/right joystick on transmitter)
     Not used */
 //    results[RC_RDR] = (results[RC_RDR] > MIDDLE? HIGH: LOW);  // could be analog
-    Serial.println(results[RC_RDR]);
-    if (results[RC_RDR] >= HubAtZero)
+    Serial.println(results[RC_MOTOR_FEEDBACK]);
+    if (results[RC_MOTOR_FEEDBACK] >= HubAtZero)
         HubSpeed_kmPh = 0;
     else
-        HubSpeed_kmPh = HubSpeed2kmPh / results[RC_RDR];
+        HubSpeed_kmPh = HubSpeed2kmPh / results[RC_MOTOR_FEEDBACK];

 //  Serial.println("");  // New line

@@ -689,12 +753,6 @@
 #define SerialOdoOut  Serial3
 #define SerialMonitor Serial

-#if (VEHICLE_NUMBER == 1)
-#define WHEEL_DIAMETER_MM 397
-#endif
-#if (VEHICLE_NUMBER == 2)
-#define WHEEL_DIAMETER_MM 500
-#endif
 #define MEG 1000000
 #define MAX_SPEED_KPH 50
 #define MAX_SPEED_mmPs   ((MAX_SPEED_KPH * MEG) / 3600)
@@ -1208,4 +1266,4 @@
 {
   s7s.write(0x77);
   s7s.write(decimals);
-}+}


Change t* vars from ints to floats

Change t* vars from ints to floats


updated reset delay

updated reset delay

--- src/analog_sensors_board.ino
+++ src/analog_sensors_board.ino
@@ -142,7 +142,7 @@
     analogReference(INTERNAL);

     // (reset) protection delay
-    delay(5000);
+    delay(2500);

     // enable watchdog
     wdt_enable(WDTO_8S);


Update MultipleButtons.ino

Update MultipleButtons.ino

--- arduino/MultipleButtons/MultipleButtons.ino
+++ arduino/MultipleButtons/MultipleButtons.ino
@@ -11,9 +11,9 @@
  *   + detects the pressed and released events of multiple buttons
  */
 // Wiring:
-// - Black -> Ground
-// - Yellow -> Digital Pin
-// - Red -> 5v for LED light
+// - Put a wire in ground
+// - Put wires in Digital 6,7,8
+// - When you touch 6,7,8 to ground, the buttons are triggered

 #include <ezButton.h>

@@ -22,7 +22,8 @@
 ezButton button3(8);  // create ezButton object that attach to pin 8;

 void setup() {
-  Serial.begin(9600);
+  Serial.begin(115200);
+  Serial.println("Buttons started");
   button1.setDebounceTime(50); // set debounce time to 50 milliseconds
   button2.setDebounceTime(50); // set debounce time to 50 milliseconds
   button3.setDebounceTime(50); // set debounce time to 50 milliseconds


more accuracy/speed/power with full step instead of 16th step

--- arrowprint_firmware/arrowprint_firmware.ino
+++ arrowprint_firmware/arrowprint_firmware.ino
@@ -10,7 +10,7 @@
  */
 #include <aJSON.h>

-String version = "5.1";
+String version = "5.2";

@@ -24,16 +24,16 @@
 int hotheadtarget = 10;    //160 DEFAULT

 //physical movement scale (bigger == more);
-double tablexsteps    = 23000;
-double tableysteps    = 23000;
-double tablezsteps    = 349100;    //234000 (100mm) from top (STEPS FROM TABLE SURFACE TO TOP) 0,0,0 is FAR LEFT BOTTOM
-double tableesteps  = -1000000;
+double tablexsteps    = 1920.0;
+double tableysteps    = 2134.0;
+double tablezsteps    = 22400.0;    //234000 (100mm) from top (STEPS FROM TABLE SURFACE TO TOP) 0,0,0 is FAR LEFT BOTTOM
+double tableesteps  = -45000.0;

 //measured (1000 = 1mm)
-double tablexdistance = 134.765625;    //in microns (158mm )
-double tableydistance = 134.765625;    //in microns (200mm)
-double tablezdistance = 61.913;    //in microns (96mm)
-double tableedistance = 920.000;    //in microns (96mm)
+double tablexdistance = 180;    //in microns (158mm )
+double tableydistance = 200.0625;    //in microns (200mm)
+double tablezdistance = 69.2347;    //in microns (96mm)
+double tableedistance = 1000.000;    //in microns (96mm)

 // Motor pins
@@ -46,7 +46,7 @@
 double stepperXdestPosition = 0;
 double stepperXtimer = 0;
 int    stepperXtoggle = 0;
-double stepperXspeed = 110;
+double stepperXspeed = 3200;

 int motorpinYstep = 26;
 int motorpinYdir  = 27;
@@ -54,7 +54,7 @@
 double stepperYdestPosition = 0;
 double stepperYtimer = 0;
 int    stepperYtoggle = 0;
-double stepperYspeed = 110;  //slower for more power
+double stepperYspeed = 3200;  //slower for more power

 int motorpinZstep = 30;
 int motorpinZdir  = 31;
@@ -62,7 +62,7 @@
 double stepperZdestPosition = 0;
 double stepperZtimer = 0;
 int    stepperZtoggle = 0;
-double stepperZspeed = 110;
+double stepperZspeed = 3200;

 int motorpinEstep = 28;
 int motorpinEdir  = 29;
@@ -70,7 +70,7 @@
 double stepperEdestPosition = 0;
 double stepperEtimer = 0;
 int    stepperEtoggle = 0;
-double stepperEspeed = 110;
+double stepperEspeed = 6400;

 // Motor Zero switch pins
@@ -151,7 +151,7 @@
         aJson.deleteItem(msg);

         tempcounter++;
-        if (tempcounter > 5) {
+        if (tempcounter > 15) {
             thermistor();
             tempcounter = 0;
         }
@@ -185,6 +185,8 @@
         delay(250);
     }

+
+
 }
 //=======================================================================================

@@ -197,98 +199,71 @@
 //=======================================================================================

-void zeroplane() {
-      /////////////////////////////////////////////////////////// X LEFT RIGHT
+
+
+// START ZEROAXIS()
+void zeroaxis() {
+  /*
+      Runs each motor towards the zero switch and resets its position. Must be run at start.
+  */
+
+    ////////////////////////////////////////////////////////ZERO Z - UPDOWN
+    while (digitalRead(zZeropin) != zZeroNC) {
+      stepperZdestPosition = stepperZdestPosition + 1;
+      while (stepperZdistanceToGo() != 0) {
+        stepperZrun();
+      }
+    }
+
+    //top most is equal to tablezsteps
+    stepperZcurrPosition = tablezsteps;
+
+    //moves to zero (table surface)
+    stepperZdestPosition = 0;
+    while (stepperZdistanceToGo() != 0) {
+      stepperZrun();
+    }
+    lastz = 0;
+
+    /////////////////////////////////////////////////////////// X LEFT RIGHT

     while (digitalRead(xZeropin) != xZeroNC) {
-      stepperXdestPosition = stepperXdestPosition - 32;
-      while (stepperXdistanceToGo() != 0) {
+      stepperXdestPosition = stepperXdestPosition - 1;
+      while (stepperXdistanceToGo() > 0) {
         stepperXrun();
       }
     }
-
-    stepperXcurrPosition = -2000;
+    stepperXcurrPosition = 0;
+    lastx = 0;
+
     //moves to zero
     stepperXdestPosition = 0;
-    lastx = 0;
     while (stepperXdistanceToGo() != 0) {
       stepperXrun();
     }
+    lastx = 0;
+
+
     ////////////////////////////////////////////////////////////// Y TABLE FRONT BACK
+
     while (digitalRead(yZeropin) != yZeroNC) {
-      stepperYdestPosition = stepperYdestPosition + 32;
+      stepperYdestPosition = stepperYdestPosition + 1;
       while (stepperYdistanceToGo() != 0) {
         stepperYrun();
       }
     }
+    //zero switch is on high side
+    stepperYcurrPosition = tableysteps;
+
     //moves to 0
-    stepperYcurrPosition = tableysteps+10000;
     stepperYdestPosition = 0;
     lasty = 0;
     while (stepperYdistanceToGo() != 0) {
       stepperYrun();
     }
-}
-
-// START ZEROAXIS()
-void zeroaxis() {
-  /*
-      Runs each motor towards the zero switch and resets its position. Must be run at start.
-  */
-
-    ////////////////////////////////////////////////////////ZERO Z - UPDOWN
-    Serial.print("{ \"log\" : \"Attempting to zero Z axis\"}");
-
-    while (digitalRead(zZeropin) != zZeroNC) {
-      stepperZdestPosition = stepperZdestPosition + 16;
-      while (stepperZdistanceToGo() != 0) {
-        stepperZrun();
-      }
-    }
-
-    stepperZcurrPosition = tablezsteps + 6400;
-
-    //moves to zero
-    stepperZdestPosition = 0;
-    lastz = 0;
-    while (stepperZdistanceToGo() != 0) {
-      stepperZrun();
-    }
-    /////////////////////////////////////////////////////////// X LEFT RIGHT
-    Serial.print("{ \"log\" : \"Attempting to zero X axis\"}");
-    while (digitalRead(xZeropin) != xZeroNC) {
-      stepperXdestPosition = stepperXdestPosition - 32;
-      while (stepperXdistanceToGo() != 0) {
-        stepperXrun();
-      }
-    }
-
-    stepperXcurrPosition = -2000;
-    //moves to zero
-    stepperXdestPosition = 0;
-    lastx = 0;
-    while (stepperXdistanceToGo() != 0) {
-      stepperXrun();
-    }
-
-    Serial.print("{ \"log\" : \"X axis zero success\"}");
-    ////////////////////////////////////////////////////////////// Y TABLE FRONT BACK
-    Serial.print("{ \"log\" : \"Attempting to zero Y axis\"}");
-    while (digitalRead(yZeropin) != yZeroNC) {
-      stepperYdestPosition = stepperYdestPosition + 32;
-      while (stepperYdistanceToGo() != 0) {
-        stepperYrun();
-      }
-    }
-    //moves to 0
-    stepperYcurrPosition = tableysteps+10000;
-    stepperYdestPosition = 0;
-    lasty = 0;
-    while (stepperYdistanceToGo() != 0) {
-      stepperYrun();
-    }
+
     ////////////////////////////////////////////////////////////// E zero
-    Serial.print("{ \"log\" : \"Attempting to test E axis\"}");
+
     stepperEdestPosition = 0;  //1 rotation
     while (stepperEdistanceToGo() != 0) {
         stepperErun();
@@ -297,83 +272,56 @@
     stepperEcurrPosition = 0;
     stepperEdestPosition = 0;
     laste = 0;
-    Serial.print("{ \"log\" : \"Extruder stepper axis zero success\"}");
+
+    //WAIT
+    line(45.0, 45.0, 5.0, 0.0);

 }
 // END ZEROAXIS()
 // ==============================================================================================================================================================================
 // START LINE()
 void line(double x, double y, double z, double e) {
-
-  //DISTANCESTEPS
-   double distance = sqrt( pow((float)(x - lastx),2) + pow( (float)(y - lasty),2) + pow( (float)(z - lastz), 2) + pow( (float)(e - laste), 2));
-   double steps = round(distance*500);
+   double distance = sqrt( pow((float)(x - lastx),2) + pow( (float)(y - lasty),2) + pow( (float)(z - lastz), 2) + pow( (float)(e - laste), 2) );
+   double steps = round(distance*50); // distance to move * (1mm / (circum/steps per rotation))
+   if (steps == 0) { steps = steps + 1; }
+
+   for (int i = 0; i <= steps; i++) {
+     double stepratio = i/steps;
+
+     double newx = lastx + ((x-lastx) * stepratio);
+     double newy = lasty + ((y-lasty) * stepratio);
+     double newz = lastz + ((z-lastz) * stepratio);
+     double newe = laste + ((e-laste) * stepratio);
+
+     double newxsteps = tablexsteps*(newx/tablexdistance);
+     double newysteps = tableysteps*(newy/tableydistance);
+     double newzsteps = tablezsteps*(newz/tablezdistance);
+     double newesteps = tableesteps*(newe/tableedistance);
+
+     newxsteps = newxsteps/2;
+     newysteps = newysteps/2;
+     newzsteps = newzsteps/2;
+     newesteps = newesteps/2;
+
+     stepperXdestPosition = round(newxsteps)*2;
+     stepperYdestPosition = round(newysteps)*2;
+     stepperZdestPosition = round(newzsteps)*2;
+     stepperEdestPosition = round(newesteps)*2;
+
+
+
+     while ((stepperXdistanceToGo() != 0) || (stepperYdistanceToGo() != 0) || (stepperZdistanceToGo() != 0) || (stepperEdistanceToGo() != 0)) {
+         stepperXrun();
+         stepperYrun();
+         stepperZrun();
+         stepperErun();
+       }
+   }

-        //calculate new step positions from micron position
-   double nx = tablexsteps*(x/tablexdistance);
-   double ny = tableysteps*(y/tableydistance);
-   double nz = tablezsteps*(z/tablezdistance);
-   double ne = tableesteps*(e/tableedistance);
-
-   double cx = float(stepperXcurrPosition);
-   double cy = float(stepperYcurrPosition);
-   double cz = float(stepperZcurrPosition);
-   double ce = float(stepperEcurrPosition);
-
-
-   double dx = ((nx-cx)/steps);
-   double dy = ((ny-cy)/steps);
-   double dz = ((nz-cz)/steps);
-   double de = ((ne-ce)/steps);
-
-
-   //distance
-   /*
-   double deltax = lastx - x;
-   double deltay = lasty - y;
-   double deltaz = lastz - z;
-   double deltae = laste - e;
-   Serial.print("{ \"deltax\" : \"");
-   Serial.print(deltax);
-   Serial.print("\", \"deltay\" : \"");
-   Serial.print(deltay);
-   Serial.print("\", \"deltaz\" : \"");
-   Serial.print(deltaz);
-   Serial.print("\", \"deltae\" : \"");
-   Serial.print(deltae);
-   Serial.println("\"}");
-   */
-   //
-
    lastx = x;
    lasty = y;
    lastz = z;
    laste = e;
-
-   for (int i = 0; i <= steps; i++) {
-     double newx = cx + (dx*i);
-     double newy = cy + (dy*i);
-     double newz = cz + (dz*i);
-     double newe = ce + (de*i);
-
-     stepperXdestPosition = round(newx);
-     stepperYdestPosition = round(newy);
-     stepperZdestPosition = round(newz);
-     stepperEdestPosition = round(newe);
-
-
-     while ((stepperXdistanceToGo() != 0) || (stepperYdistanceToGo() != 0) || (stepperZdistanceToGo() != 0) || (stepperEdistanceToGo() != 0)) {
-       ///GET THESE INTO THE MAIN LOOP
-       // NEED TO REFACTOR EVENT LOOP
-
-         stepperXrun();
-         stepperYrun();
-         stepperZrun();
-         stepperErun();
-
-
-       }
-   }

 }
 // END LINE();
@@ -426,7 +374,6 @@
       if (jsonpz) {
         char* tempz = jsonpz->valuestring;
         g1z = atof(tempz);
-        zeroplane();
       }

       aJsonObject *jsonpe = aJson.getObjectItem(msg, "e");
@@ -443,9 +390,9 @@
   if (cmd == "G92") {
       aJsonObject *jsonpe = aJson.getObjectItem(msg, "e");
       if (jsonpe) {
-        stepperEcurrPosition = 0.0f;
-        stepperEdestPosition = 0.0f;
-        laste = 0.0f;
+        stepperEcurrPosition = 0.0;
+        stepperEdestPosition = 0.0;
+        laste = 0.0;
       }
     }///END G92

@@ -459,13 +406,12 @@

 ///////========================vvvvvvvv STEPPER CONTROLLERS vvvvvv==================

-double stepperXdistanceToGo() { return stepperXdestPosition - stepperXcurrPosition; }
+double stepperXdistanceToGo() { return abs(stepperXdestPosition - stepperXcurrPosition); }

 void stepperXrun() {
   double dir = 0;
-  stepperXdestPosition = round(stepperXdestPosition);
-  stepperXcurrPosition = round(stepperXcurrPosition);
-  if (stepperXdestPosition != stepperXcurrPosition) {
+
+  if (stepperXdistanceToGo() >= 1) {
     //SET DIRECTION
     if (stepperXdestPosition > stepperXcurrPosition) {
       digitalWrite(motorpinXdir, HIGH);
@@ -474,23 +420,29 @@
       digitalWrite(motorpinXdir, LOW);
       dir = -1;
     }
+
+    if (micros() < (stepperXtimer-stepperXspeed)) {
+      //rollover bug... fix
+      stepperXtimer = micros();
+    }
+
     //PULSE AT SPEED LIMIT
-    if (micros() > (stepperXtimer+stepperXspeed)) {
+    if (micros() >= (stepperXtimer+stepperXspeed)) {
       digitalWrite(motorpinXstep, stepperXtoggle);
       stepperXtimer = micros();
       stepperXtoggle = !stepperXtoggle;
       stepperXcurrPosition += dir;
     }
+
+
   }
 }

-double stepperYdistanceToGo() { return stepperYdestPosition - stepperYcurrPosition; }
+double stepperYdistanceToGo() { return abs(stepperYdestPosition - stepperYcurrPosition); }

 void stepperYrun() {
   double dir = 0;
-  stepperYdestPosition = round(stepperYdestPosition);
-  stepperYcurrPosition = round(stepperYcurrPosition);
-  if (stepperYdestPosition != stepperYcurrPosition) {
+  if (stepperYdistanceToGo() >= 1) {
     //SET DIRECTION
     if (stepperYdestPosition > stepperYcurrPosition) {
       digitalWrite(motorpinYdir, HIGH);
@@ -499,23 +451,26 @@
       digitalWrite(motorpinYdir, LOW);
       dir = -1;
     }
+    if (micros() < (stepperYtimer-stepperYspeed)) {
+      //rollover bug... fix
+      stepperYtimer = micros();
+    }
     //PULSE AT SPEED LIMIT
-    if (micros() > (stepperYtimer+stepperYspeed)) {
+    if (micros() >= (stepperYtimer+stepperYspeed)) {
       digitalWrite(motorpinYstep, stepperYtoggle);
       stepperYtimer = micros();
       stepperYtoggle = !stepperYtoggle;
       stepperYcurrPosition += dir;
     }
+
   }
 }

-double stepperZdistanceToGo() { return stepperZdestPosition - stepperZcurrPosition; }
+double stepperZdistanceToGo() { return abs(stepperZdestPosition - stepperZcurrPosition); }

 void stepperZrun() {
   double dir = 0;
-  stepperZdestPosition = round(stepperZdestPosition);
-  stepperZcurrPosition = round(stepperZcurrPosition);
-  if (stepperZdestPosition != stepperZcurrPosition) {
+  if (stepperZdistanceToGo() >= 1) {
     //SET DIRECTION
     if (stepperZdestPosition > stepperZcurrPosition) {
       digitalWrite(motorpinZdir, HIGH);
@@ -524,8 +479,12 @@
       digitalWrite(motorpinZdir, LOW);
       dir = -1;
     }
+    if (micros() < (stepperZtimer-stepperZspeed)) {
+      //rollover bug... fix
+      stepperZtimer = micros();
+    }
     //PULSE AT SPEED LIMIT
-    if (micros() > (stepperZtimer+stepperZspeed)) {
+    if (micros() >= (stepperZtimer+stepperZspeed)) {
       digitalWrite(motorpinZstep, stepperZtoggle);
       stepperZtimer = micros();
       stepperZtoggle = !stepperZtoggle;
@@ -534,13 +493,12 @@
   }
 }

-double stepperEdistanceToGo() { return stepperEdestPosition - stepperEcurrPosition; }
+double stepperEdistanceToGo() { return abs(stepperEdestPosition - stepperEcurrPosition); }

 void stepperErun() {
   double dir = 0;
-  stepperEdestPosition = round(stepperEdestPosition);
-  stepperEcurrPosition = round(stepperEcurrPosition);
-  if (stepperEdestPosition != stepperEcurrPosition) {
+
+  if (stepperEdistanceToGo() >= 1) {
     //SET DIRECTION
     if (stepperEdestPosition > stepperEcurrPosition) {
       digitalWrite(motorpinEdir, HIGH);
@@ -549,8 +507,12 @@
       digitalWrite(motorpinEdir, LOW);
       dir = -1;
     }
+    if (micros() < (stepperEtimer-stepperEspeed)) {
+      //rollover bug... fix
+      stepperEtimer = micros();
+    }
     //PULSE AT SPEED LIMIT
-    if (micros() > (stepperEtimer+stepperEspeed)) {
+    if (micros() >= (stepperEtimer+stepperEspeed)) {
       digitalWrite(motorpinEstep, stepperEtoggle);
       stepperEtimer = micros();
       stepperEtoggle = !stepperEtoggle;


fix new ecc key size for test

fix new ecc key size for test

--- Pinoccio/Pinoccio.ino
+++ Pinoccio/Pinoccio.ino
@@ -13,6 +13,13 @@
 #include "./sha1.h"
 #include "./hmac.h"
 }
+
+/* scratch
+typedef struct sockaddr_in {};
+#define time_t long
+#define time(x) millis()
+
+*/

 int RNG(uint8_t *p_dest, unsigned p_size)
 {
@@ -47,8 +54,8 @@
     uint8_t l_private1[ECC_BYTES];
     uint8_t l_private2[ECC_BYTES];

-    uint8_t l_public1[ECC_BYTES + 1];
-    uint8_t l_public2[ECC_BYTES + 1];
+    uint8_t l_public1[ECC_BYTES *2];
+    uint8_t l_public2[ECC_BYTES *2];

     uint8_t l_secret1[ECC_BYTES];
     uint8_t l_secret2[ECC_BYTES];


Fixed indent

Fixed indent

--- Arduino/hih.ino
+++ Arduino/hih.ino
@@ -13,45 +13,45 @@

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

 void loop()
-{
-  do {
-    measure();
-  } while (status != 0); // Status 1 means stale data.
-
-  String msg = "Temperature:\t" + (String)temperature + "\nHumidity:\t" + (String)humidity + "\n";
-  Serial.print(msg);
-
-  delay(1000);
+{
+	do {
+        measure();
+	} while (status != 0); // Status 1 means stale data.
+
+	String msg = "Temperature:\t" + (String)temperature + "\nHumidity:\t" + (String)humidity + "\n";
+	Serial.print(msg);
+
+	delay(1000);
 }

 void measure()
 {
-  Wire.beginTransmission(sensor);
-  Wire.endTransmission();
-
-  // Datasheet says the measurement cycle is ~36.65ms
-  delay(50);
-
-  Wire.requestFrom((int)sensor, 4);
-
-  while (Wire.available() == 0);
+	Wire.beginTransmission(sensor);
+	Wire.endTransmission();

-  meas[0] = Wire.read();
-  meas[1] = Wire.read();
-  meas[2] = Wire.read();
-  meas[3] = Wire.read();
-
-  Wire.endTransmission();
-
-  status = meas[0] >> 6;
-  _humidity = (uint16_t)(((meas[0] & 0x3f) << 8) | meas[1]);
-  _temperature = (uint16_t)((meas[2] << 6) | (meas[3] >> 2));
-
-  humidity = (float)_humidity / (pow(2, 14) - 2) * 100;
-  temperature = (float)_temperature / (pow(2, 14) - 2) * 165 - 40;
+	// Datasheet says the measurement cycle is ~36.65ms
+	delay(50);
+
+	Wire.requestFrom((int)sensor, 4);
+
+	while (Wire.available() == 0);
+
+	meas[0] = Wire.read();
+	meas[1] = Wire.read();
+	meas[2] = Wire.read();
+	meas[3] = Wire.read();
+
+	Wire.endTransmission();
+
+	status = meas[0] >> 6;
+	_humidity = (uint16_t)(((meas[0] & 0x3f) << 8) | meas[1]);
+	_temperature = (uint16_t)((meas[2] << 6) | (meas[3] >> 2));
+
+	humidity = (float)_humidity / (pow(2, 14) - 2) * 100;
+	temperature = (float)_temperature / (pow(2, 14) - 2) * 165 - 40;
 }


FO LP filtering for smooth walkers

FO LP filtering for smooth walkers

--- countdown/countdown.ino
+++ countdown/countdown.ino
@@ -5,6 +5,7 @@
 #define NUM_LEDS (ROWS*COLS)

 CRGB leds[NUM_LEDS];
+CRGB walker_leds[NUM_LEDS]; //separate array that holds the leds that 'walk/move out' of the table

 // Return 0-based led index for 0-based x and y grid co-ordinate values
 // The LED string snakes through the grid, so every row the positive x direction switches
@@ -31,7 +32,7 @@

 void step_led(){
   // First, turn off completely the led at step_counter (the light will leave this spot)
-  leds[step_counter] = CRGB::Black;
+  walker_leds[step_counter] = CRGB::Black;
   // Re-set the step period 'countdown timer'
   step_period = 1000/(1+leds_index);

@@ -54,18 +55,18 @@
     // Turn off the current colour in the current 'source' led
     if(colour_counter==2){
       // moved out blue
-      leds[leds_index] = CRGB::Yellow;
+      walker_leds[leds_index] = CRGB::Yellow;
     } else if(colour_counter==1) {
       // moved out green as well
-      leds[leds_index] = CRGB::Red;
+      walker_leds[leds_index] = CRGB::Red;
     } else if(colour_counter==0){
-      leds[leds_index] = CRGB::Black;
+      walker_leds[leds_index] = CRGB::Black;
     }
   }

   step_counter--;
   // Light up the properly-coloured led in the current position
-  leds[step_counter] = moving_colours[colour_counter];
+  walker_leds[step_counter] = moving_colours[colour_counter];
 }

 void update(){
@@ -81,8 +82,10 @@
   // Limit the brightness somewhat (scale is 0-255)
   LEDS.setBrightness(64);

-  for(uint8_t i=0; i<NUM_LEDS; ++i)
+  for(uint8_t i=0; i<NUM_LEDS; ++i){
     leds[i] = CRGB::White;
+    walker_leds[i] = CRGB::White;
+  }

   LEDS.show();
   Serial.begin(57600);
@@ -102,6 +105,10 @@

   if(millis()-prevUpdateTime >= UPDATE_TIME){
     prevUpdateTime = millis();
+    for(uint8_t i_led=0; i_led != NUM_LEDS; ++i_led){
+      for(uint8_t i=0; i!=3; ++i)
+        leds[i_led][i] = (uint8_t) (((uint16_t)leds[i_led][i]*19 + (uint16_t)walker_leds[i_led][i])/20);
+    }
     update();
   }


Update lightsource.ino

Update lightsource.ino

Minor tweaks

--- ollivanderslamp/lightsource.ino
+++ ollivanderslamp/lightsource.ino
@@ -66,14 +66,14 @@
 void loop() {
     if (analogRead(incendioPin)>4000) {
         state = 2;
-    }
+    }
     if (analogRead(lumosPin)>4000) {
         state = 1;
     }
     if (analogRead(noxPin)>4000) {
         state = 0;
     }
-    // Let's turn an LED on. How about #6, which is at the 6 o'clock position? Let's make it blue and bright.
+    // Let's turn the LEDs on.
     if (state == 0) {
         nox();
     }


code is separated into several files

code is separated into several files

--- code/PABS_sketch/PABS_sketch.ino
+++ code/PABS_sketch/PABS_sketch.ino
@@ -1,27 +1,6 @@
-int adminStartButton = 0;
-int adminResetButton = 1;
-int adminInterrupt = 2;
-int playerInerrupt = 3;
-int firstPlayerButton = 4;
-int secondPlayerButton = 5;
-int thirdPlayerButton = 6;
-int fourthPlayerButton = 7;
-int fifthPlayerButton = 8;
-int speakerButton = 9;
-int ledShiftRegisterClk = 10;
-int ledShiftRegisterData = 11;
-int ledShiftRegisterRefresh = 12;
-
-int led = 13;
-
-int displayShiftRegisterClk = A0;
-int displayShiftRegisterData = A1;
-int displayShiftRegisterRefresh = A2;
-int gameStateHighBit = A3;
-int gameStateLowBit = A4;
+#include "constants.h"

-byte digit[11] = {0b00001000,0b00111110,0b00010001,0b00010100, 0b00100110, 0b01000100, 0b01000000, 0b00011110,0b00000000,0b00000100, 0b01111111};

 void setup() {
   pinMode(led, OUTPUT);


Backup

Backup


add more test functions

add more test functions

--- signB_3d/signB_3d.ino
+++ signB_3d/signB_3d.ino
@@ -131,9 +131,9 @@
       int16_t p = pixelMap[x][y][1];
       //int16_t p[2] = pixelMap[x][y];
       leds[s][p] = CHSV(125, 255, 255);
-      FastLED.show();
+      FastLED.show();
       delay(20);
-    }
+    }
   }
   */
   ClearAll();
@@ -151,14 +151,20 @@
 }

 void testHorizontalLineDown() {
+  uint8_t pin;
+  uint16_t pixel;
+  uint8_t pinPrevious;
+  uint16_t pixelPrevious;
   for (uint8_t y = 0; y < MAP_HEIGHT; y++) {
     for (uint8_t x = 0; x < MAP_WIDTH; x++) {
-      uint8_t pin = pixelMap[y][x][0];
-      uint16_t pixel = pixelMap[y][x][1];
-      leds[pin][pixel] = segmentColor(pin);
-      uint8_t pinPrevious = pixelMap[y-1][x][0];
-      uint16_t pixelPrevious = pixelMap[y-1][x][1];
-      leds[pinPrevious][pixelPrevious] = 0;
+      if (x >= 2*y - 4 && x <= 114 - 2*y) {
+        pin = pixelMap[y][x][0];
+        pixel = pixelMap[y][x][1];
+        leds[pin][pixel] = segmentColor(pin);
+        pinPrevious = pixelMap[y-1][x][0];
+        pixelPrevious = pixelMap[y-1][x][1];
+        leds[pinPrevious][pixelPrevious] = 0;
+      }
     }
     FastLED.show();
     delay(1000);
@@ -172,7 +178,7 @@
     case 1 :
       return CRGB::Orange;
     case 2 :
-      return CRGB::Yellow;
+      return CRGB::Yellow;
     case 3 :
       return CRGB::Green;
     case 4 :
@@ -226,4 +232,3 @@
   }
 }
 */
-


Wait for the serial data to be sent

Wait for the serial data to be sent

--- receiver_analog/receiver_analog.ino
+++ receiver_analog/receiver_analog.ino
@@ -144,6 +144,9 @@
     // Turn off message indicator
     analogWrite(DEBUG_LED_PIN, DEBUG_LED_PWM_AWAKE);

+    // Wait for the serial data to be sent
+    Serial.flush();
+
     // Sleep 'till the next message is due
     goToSleep();
   }


adding comments.

adding comments.

--- src/rx5808-pro-diversity/rx5808-pro-diversity.ino
+++ src/rx5808-pro-diversity/rx5808-pro-diversity.ino
@@ -1095,7 +1095,7 @@
     delay(100);
     beep(100);
     uint8_t check_sum = 2;
-    Serial.write(2); // start of payload
+    Serial.write(2); // start of payload STX
     check_sum += channelIndex;
     Serial.write(channelIndex); // send channel
     for(uint8_t i=0; i < 10;i++) {
@@ -1105,7 +1105,7 @@
         check_sum += (char)call_sign[i];
         Serial.write(call_sign[i]); // send char of call_sign
     }
-    Serial.write(3);  // end of payload
+    Serial.write(3);  // end of payload ETX
     Serial.write(check_sum); // send ceck_sum for payload validation
 }
 #endif


Update ArduinoController.ino

Update ArduinoController.ino

--- ArduinoController/ArduinoController.ino
+++ ArduinoController/ArduinoController.ino
@@ -53,21 +53,13 @@
     [](){((KillSwitchController*)controllers[KILL_ADDR])->isr();},
     CHANGE
   );
-  clearBuffer();
-}
-
-// At baud rates around 115200, RX buffer gets filled with
-// garbage in the beginning. To fix this, we just clear it
-// before proceeding. Luckilly the guarbage is consistant!
-// The host will give an ACKNO to begin thus exiting  this
-// infinite loop.
-void clearBuffer() {
-  while(true) {
-    if(Serial.available()) {
-      if(Serial.read() != GARBAGE)
-        break;
-    }
-  }
+
+  // At baud rates around 115200, RX buffer gets filled with
+  // garbage in the beginning. To fix this, we just clear it
+  // before proceeding. Luckilly the guarbage is consistant!
+  // The host will give an ACKNO to begin thus exiting  this
+  // infinite loop.
+  while((!Serial.available())||(Serial.read()==GARBAGE));
 }

 void loop() {


beta mk I

beta mk I

--- piserverpanel/piserverpanel.ino
+++ piserverpanel/piserverpanel.ino
@@ -445,7 +445,27 @@
 }

 void animate_locked() {
-
+  int ms = 80;
+  int min_value = 0;
+  int max_value = 150;
+
+  led_color(pwm_yellow, pwm_yellow, 10);
+
+  pwm_yellow = pwm_yellow + fader_red;
+
+  if ( pwm_yellow > max_value+1 ) {
+    pwm_yellow = max_value;
+  }
+
+  if ( pwm_yellow <= min_value || pwm_yellow >= max_value ) {
+    fader_red = -fader_red;
+  }
+
+  if (fader_yellow > 0) {
+   delay(ms);
+  } else {
+   delay(ms);
+  }
 }

 void animate_system_reset() {


added debug mode and better comments, changed a bunch of stuff

--- super_freq.ino
+++ super_freq.ino
@@ -1,5 +1,6 @@
 #define LIN_OUT 1 // use the log output function
 #define FFT_N 128 // set number of FFT points
+#define DEBUG 1   // set to 1 to turn on Serial printing

 #include <math.h>
 #include <FFT.h>
@@ -11,9 +12,11 @@
 int sum_fft;
 float frequency;
 float SAMPLE_RATE = 9600.0;
-int SKIP_MULT = 16;
+int SKIP_MULT = 4;
 int MAX_FFT_BIN = 16383;
-int brightness_mult;
+int brightness;  // controls the LED brightness based on dB level
+// LEDs can be set up to 127, but it seems too bright so we tone it down a bit
+int MAX_BRIGHTNESS = 95;

 float base_freak = SAMPLE_RATE / FFT_N / 2;

@@ -30,7 +33,9 @@
 LPD8806 strip = LPD8806(nLEDs, dataPin, clockPin);

 void setup() {
-    Serial.begin(9600);
+    if (DEBUG) {
+        Serial.begin(9600);
+    }
     TIMSK0 = 0;           // turn off timer0 for lower jitter
     ADCSRA = 0xe5;        // set the adc to free running mode
     ADMUX = 0x40;         // use adc0
@@ -46,18 +51,25 @@
 void calculateFFT() {
     for (int i = 0 ; i < FFT_N * 2; i += 2) { // save samples
         /*
-         * sample at slower rate, minimum sample rate is 9.6 kHz
-         * so reduce sample rate by skipping ADC read cycles by
-         * SKIP_MULT
+         * A hack to sample at a slower rate.
+         * The minimum sample rate is 9.6 kHz, so reduce sample rate
+         * by skipping ADC read cycles, essentially spreading out our
+         * sample over time. Reducing the sample rate increases our
+         * frequency resolution, so we can differentiate frequencies
+         * close to one another, but at the expense of not detecting higher
+         * frequencies.
+         *
+         * The effective sample rate would then be:
+         * SAMPLE_RATE / SKIP_MULT
          */
         for (int j = 0; j < SKIP_MULT; j++) {
             while(!(ADCSRA & 0x10)); // wait for adc to be ready
             ADCSRA = 0xf5;           // restart adc
         }

-        byte m = ADCL;             // fetch adc data
-        byte j = ADCH;
-        int k = (j << 8) | m;      // form into an int
+        byte m = ADCL;             // fetch ADC data (low byte)
+        byte j = ADCH;             // fetch ADC data (high byte)
+        int k = (j << 8) | m;      // combine low/high bytes to form into an int
         k -= 0x0200;               // form into a signed int
         k <<= 6;                   // form into a 16b signed int
         fft_input[i] = k;          // put real data into even bins
@@ -71,18 +83,16 @@

 // Fill the dots progressively along the strip.
 void setColor(uint32_t c) {
-    int i;
-
-    for (i=0; i < strip.numPixels(); i++) {
+    for (int i=0; i < strip.numPixels(); i++) {
         strip.setPixelColor(i, c);
         strip.show();
     }
 }

 void loop() {
-    //cli();
+    cli();           // disable global interrupts
     calculateFFT();  // result is placed in fft_log_out
-    //sei();
+    sei();           // re-enable interrupts

     peak_index = 0;
     max_value = 0;
@@ -92,54 +102,63 @@
         if (max_value < fft_lin_out[i]) {
             // peak index determines frequency
             peak_index = i;
+            // max value determines brightness
             max_value = fft_lin_out[i];
         }
         if (i > 0) {
-            // sum of all bins determines brightness
+            /*
+             * maybe an alternate way to control brightness
+             * would be the sum of all non-zero bins, i.e.
+             * the total power in the sample. However, I don't
+             * have a handle on what the maximum sum would be.
+             */
             sum_fft += fft_lin_out[i];
         }
     }

     frequency = (peak_index * (SAMPLE_RATE / SKIP_MULT)) / (FFT_N / 4);
-    brightness_mult = floor(95 * max_value / MAX_FFT_BIN);
+    brightness = round(1.0 * MAX_BRIGHTNESS * sum_fft / MAX_FFT_BIN);

-    if (max_value < 80 || sum_fft < 400 || peak_index == 0) {
+    if (max_value < 80 || sum_fft < 3000 || peak_index == 0) {
         // signal too weak or we got the 1st peak (0Hz), no lights
         setColor(strip.Color(0, 0, 0));
     } else if (frequency > 0 && frequency < base_freak * 2) {
         // red
-        setColor(strip.Color(brightness_mult,   0,   0));
+        setColor(strip.Color(brightness, 0, 0));
     }
     else if (frequency >= base_freak * 2 && frequency < (base_freak * 3)) {
         // yellow
-        setColor(strip.Color( brightness_mult, brightness_mult,   0));
+        setColor(strip.Color(brightness, brightness, 0));
     }
     else if (frequency >= base_freak * 3 && frequency < (base_freak * 4)) {
         // green
-        setColor(strip.Color(  0, brightness_mult,   0));
+        setColor(strip.Color(0, brightness, 0));
     }
     else if (frequency >= base_freak * 4 && frequency < base_freak * 5) {
         // cyan
-        setColor(strip.Color(  0, brightness_mult, brightness_mult));
+        setColor(strip.Color(0, brightness, brightness));
     }
     else if (frequency >= base_freak * 5 && frequency < base_freak * 6) {
         // blue
-        setColor(strip.Color(  0,   0, brightness_mult));
+        setColor(strip.Color(0, 0, brightness));
     }
     else if (frequency >= base_freak * 6 && frequency < SAMPLE_RATE/4) {
         // violence!!!
-        setColor(strip.Color(brightness_mult,   0, brightness_mult));
+        setColor(strip.Color(brightness, 0, brightness));
     }

-    Serial.print("FFT sum: ");
-    Serial.print(sum_fft);
-    Serial.print("\tPeak index: ");
-    Serial.print(peak_index);
-    Serial.print("\tMax value: ");
-    Serial.print(max_value);
-    Serial.print("\tFrequency: ");
-    Serial.println(frequency);
-//    delay(30);
+    if (DEBUG) {
+        Serial.print("FFT sum: ");
+        Serial.print(sum_fft);
+        Serial.print("\tPeak index: ");
+        Serial.print(peak_index);
+        Serial.print("\tMax value: ");
+        Serial.print(max_value);
+        Serial.print("\tFrequency: ");
+        Serial.print(frequency);
+        Serial.print("\tBrightness: ");
+        Serial.println(brightness);
+    }
 }


Use microseconds function instead of milliseconds, and add random to try to broad noise bandwith

--- HBridgePWM/HBridgePWM.ino
+++ HBridgePWM/HBridgePWM.ino
@@ -18,7 +18,7 @@

 // Minimal time to have motor starting at maximum voltage. This will depend on the motor used
 // Try to reduce to get a smooth motion
-double minTime_ms = 30;
+long minTime_us = 10;

 // These constants will not change. Used here to
 // give names to set pin numbers:
@@ -39,7 +39,7 @@
 // The range was reduced
 double sensorValueMin = 255;//0
 double sensorValueMax = 767;//1023
-double deadBand = 0.2; // Use to ensure zero speed. Should not be zero
+double deadBand = 0.01; // Use to ensure zero speed. Should not be zero
 long initialTime = 0;
 long lastSerialInputTime = 0;
 boolean isCycleStarting = false;
@@ -110,25 +110,26 @@
    }
   }
   Serial.println(inputString);
-  inputString="";
+  inputString="";*/
 }

 void loop()
 {
   sensorValue = analogRead(analogInPin);
+  //Serial.println(sensorValue);
   setMode();
   computeAlphaSigned();
   computeEnableState();
   computeLogicState();

-  delay(30);
+  delayMicroseconds(minTime_us*random(100,300));

 //  // print the results to the serial monitor:
 //  Serial.print("alphaManual = " );
 //  Serial.print(alphaSigned);
 //  Serial.print("\t alphaUsed = ");
- //Serial.println(alphaSigned);
+//  Serial.println(alphaSigned);
 }
 void setMode()
 {
@@ -150,7 +151,7 @@
 {
   if (serialFrequency != 0)
   { // Fallbacks to zero as we received no message in the expected time (twice the time)
-    if ((millis()-lastSerialInputTime) > 2*1/serialFrequency*1000)
+    if ((millis()-lastSerialInputTime) > 2*1/serialFrequency*300)
     {
       alphaSigned = 0;
     }
@@ -158,24 +159,7 @@
     // If not in Serial control overwrite the value
   if (false == isSerialControl)
   {
-    // Compute the value corresponding to the deadband
-    double sensorDeadBandMax = sensorValueMin + (deadBand/2.0+0.5)*(sensorValueMax - sensorValueMin);
-    double sensorDeadBandMin = sensorValueMin + (-deadBand/2.0+0.5)*(sensorValueMax - sensorValueMin);
-    if (sensorValue < sensorDeadBandMin) //strictly to avoid alphaSigned equals zero
-    {
-      alphaSigned = (sensorValue-sensorValueMin)/(sensorDeadBandMax - sensorValueMin)-1;
-    }
-    else
-    {
-      if (sensorValue > sensorDeadBandMax)
-      {
-        alphaSigned = (sensorValue-sensorDeadBandMax)/(sensorValueMax - sensorDeadBandMax);
-      }
-      else
-      {
-        alphaSigned = 0;
-      }
-    }
+  alphaSigned = (sensorValue-sensorValueMin)/(sensorValueMax - sensorValueMin);
   }
   alphaSigned = min(1, max(-1, alphaSigned));
 }
@@ -197,9 +181,9 @@
     {
       if (isCycleStarting)
       {
-        if ((millis()-initialTime) > minTime_ms)
-        {
-          digitalWrite(HbridgeEnablePin, HIGH);
+        if ((micros()-initialTime) > minTime_us*random(100,300))
+        {
+          digitalWrite(HbridgeEnablePin, LOW);
           isCycleStarting = false;
         }
       }
@@ -207,14 +191,14 @@
       {
         // note that alpha can't be zero
         double alpha = fabs(alphaSigned);
-        if ((millis() - initialTime) < minTime_ms/alpha*(1-alpha)+minTime_ms)
+        if ((micros() - initialTime) < minTime_us*random(100,200)/alpha*(1-alpha)+minTime_us*random(100,200))
         {
-              digitalWrite(HbridgeEnablePin, LOW);
+              digitalWrite(HbridgeEnablePin, HIGH);
         }
         else
         {
-          digitalWrite(HbridgeEnablePin, HIGH); // or low?
-          initialTime = millis();
+          digitalWrite(HbridgeEnablePin, LOW); // or low?
+          initialTime = micros();
           isCycleStarting = true;
         }
       }


bleed

bleed

--- MTM_MASTER/MTM_MASTER.ino
+++ MTM_MASTER/MTM_MASTER.ino
@@ -6,6 +6,7 @@
 int error();
 int send(byte addr, byte data[], int n);
 int init();
+int bleed();

 void setup() {
     delay(100);
@@ -23,7 +24,10 @@
         if(!send(modules[i], 0, 1))
             return error();
     }
-
+    for(int i=0; i<NUM_MODULES; i++) {
+        if(!bleed(modules[i]))
+            return error();
+    }
 }

 int send(byte addr, byte data[], int n) {
@@ -40,6 +44,7 @@
     return -1;
 }

-int zero() {
-
+int bleed() {
+    if()
+    return 0;
 }