Update Firmware.ino

Update Firmware.ino

Added notes to describe structure and hardware

--- src/piggy_back_loggers/SD_prototype_Firmware/Firmware/Firmware.ino
+++ src/piggy_back_loggers/SD_prototype_Firmware/Firmware/Firmware.ino
@@ -1,3 +1,65 @@
+// Firmware for the CIWS Residential Datalogger
+// Arduino IDE ver. 1.8.7
+// Utah Water Research Lab
+// Updated: 10/23/2018
+// Note: F("String") keeps string literals in program memory and out of RAM. Saves RAM space. Very good. Don't remove the F. I know it looks funny. But don't do it. Really. The program might crash if you do. And then you'll have dishonor on yourself, dishonor on your cow...
+
+/*******************************************************************************************\
+* Hardware Description
+*                     ___________________                             ___
+*                    |                   |<------------------------->[___] RTC
+*  ________          |                   |                            _______
+* |        |         |                   |<------------------------->|       | SD
+* |        |<------->|                   |<-----[] Activate Serial   |______/
+* |________|         |___________________|<-----[] Sensor
+*  Serial             Controller
+*
+* Serial:          Serial interface for user interaction with the logger
+* Controller:      Arduino Pro/Pro Mini (used for SD library and lower power options)
+* SD:              External SD Card storage for the logger.
+* Activate Serial: Button to wake up the controller and activate the Serial interface
+* Sensor:          Hall Effect Sensor for logging pulses from water meters.
+* RTC:             Real Time Clock to track time and wake up controller every four seconds.
+\*******************************************************************************************/
+
+/*********************************************************\
+* Software Description
+* Overview:
+*   User inputs:
+*     Serial input.
+*   Device outputs:
+*     Serial output
+*     Datalog file
+*
+* Structure:
+*   1. Setup
+*   2. Handle Serial (for start-up configuration)
+*   3. Loop
+*        Enter Sleep (low-power mode)
+*        < Will wake up on Interrupt and continue: >
+*        If serial is enabled
+*          Handle serial input
+*        If four seconds are up
+*          Update the time
+*          Construct a timestamp
+*          Power-on the SD card
+*          Write data
+*          Power-off the SD card
+*      Repeat Loop
+*
+* Interrupts:
+*   1. INT0 ()
+*
+*   2. INT1 ()
+*
+\*********************************************************/
+
+#include <SPI.h>
+#include <SD.h>
+#include <avr/sleep.h>
+#include <avr/power.h>
+#include "handleSerial.h"
+
 void setup() {
   // put your setup code here, to run once:


cleanup commented out stuff from firmware

--- firmware/firmware.ino
+++ firmware/firmware.ino
@@ -4,8 +4,6 @@
 #include "Communication.h"
 #include "Hdlc.h"

-#define SHARP_READINGS 5 // takes 3 ms for .distace call, with 25 takes 13 ms
-#define SHARP_TOLERANCE_PERCENT 93
 #define SHARP_MODEL_GP2Y0A21Y 1080

 #define IR_LEFT             A1
@@ -20,10 +18,7 @@
 int m_distance_right = 0;
 int m_distance_front_left = 0;
 int m_distance_front_right = 0;
-//SharpIR sharp_left(IR_LEFT, SHARP_READINGS, SHARP_TOLERANCE_PERCENT, SHARP_MODEL_GP2Y0A21Y);
-//SharpIR sharp_right(IR_RIGHT, SHARP_READINGS, SHARP_TOLERANCE_PERCENT, SHARP_MODEL_GP2Y0A21Y);
-//SharpIR sharp_front_left(IR_FRONT_LEFT, SHARP_READINGS, SHARP_TOLERANCE_PERCENT, SHARP_MODEL_GP2Y0A21Y);
-//SharpIR sharp_front_right(IR_FRONT_RIGHT, SHARP_READINGS, SHARP_TOLERANCE_PERCENT, SHARP_MODEL_GP2Y0A21Y);
+
 SharpIR sharp_left(IR_LEFT, SHARP_MODEL_GP2Y0A21Y);
 SharpIR sharp_right(IR_RIGHT, SHARP_MODEL_GP2Y0A21Y);
 SharpIR sharp_front_left(IR_FRONT_LEFT, SHARP_MODEL_GP2Y0A21Y);


Update firmware.ino

Update firmware.ino

--- firmware/firmware.ino
+++ firmware/firmware.ino
@@ -14,7 +14,6 @@

 void setup() {
   Serial.begin(9600);
-<<<<<<< HEAD
   pinMode(BTN_D4,   INPUT);  digitalWrite(BTN_D4,   HIGH);
   pinMode(BTN_D7,   INPUT);  digitalWrite(BTN_D7,   HIGH);
   pinMode(BUZZER,   OUTPUT); digitalWrite(BUZZER,   LOW);


Cleanup.

Cleanup.

--- examples/RS485/CosaRS485slave/CosaRS485slave.ino
+++ examples/RS485/CosaRS485slave/CosaRS485slave.ino
@@ -85,6 +85,6 @@
   }
   DELAY(1000);

-  // Send reply and increment sequence number if successful
+  // Send reply
   if (rs485.send(&msg, sizeof(msg)) < 0) return;
 }


Keep log level at 1 on start up

Keep log level at 1 on start up

--- GEVCU.ino
+++ GEVCU.ino
@@ -281,8 +281,8 @@

 	uint8_t loglevel;
 	sysPrefs->read(EESYS_LOG_LEVEL, &loglevel);
-	Logger::setLoglevel((Logger::LogLevel)loglevel);
-	//Logger::setLoglevel((Logger::LogLevel)1);
+	//Logger::setLoglevel((Logger::LogLevel)loglevel);
+	Logger::setLoglevel((Logger::LogLevel)1);
 	sys_early_setup();
 	tickHandler = TickHandler::getInstance();
 	canHandlerEV = CanHandler::getInstanceEV();


added line tracking example

added line tracking example

--- examples/Lesson5/new_Line_tracking_car/new_Line_tracking_car.ino
+++ examples/Lesson5/new_Line_tracking_car/new_Line_tracking_car.ino
@@ -12,14 +12,14 @@

 void loop() {
   int num1,num2,num3;
-  num1 = eBot.readLS1();
-  num2 = eBot.readLS2();
-  num3 = eBot.readLS3();
+  num1 = eBot.getLine1();
+  num2 = eBot.getLine2();
+  num3 = eBot.getLine3();
   if ((num1 == 0) && num2 && num3) {
     eBot.setDirection(EBot::ROTATELEFT);
     delay(2);
     while(1) {
-      num2 = eBot.readLS2();
+      num2 = eBot.getLine2();
       if (num2 == 1) {
         eBot.setDirection(EBot::ROTATELEFT);
         delay(2);
@@ -31,7 +31,7 @@
     eBot.setDirection(EBot::ROTATERIGHT);
     delay(2);
     while(1) {
-      num2 = eBot.readLS2();
+      num2 = eBot.getLine2();
       if (num2 == 1) {
         eBot.setDirection(EBot::ROTATERIGHT);
         delay(2);


Working example of using the Flagger class

--- peachyLifter/peachyLifter.ino
+++ peachyLifter/peachyLifter.ino
@@ -6,16 +6,14 @@
 //To get a "tick" time of 200us we do:
 // <time per tick> * <Clock frequency> / <prescaler>
 // 200e-6 * 16e6 / 64 = 50
-#define CPU_FREQ 16e6
-#define TICK_TIME 200e-6
+#define CPU_FREQ 16e6 //MHz
+#define TICK_TIME 200e-6 //seconds
 #define TIM2_PRESCALER 64 //Dependant on the setupTIM2_ISR() function
 #define TIM2_START 256-TICK_TIME*CPU_FREQ/TIM2_PRESCALER
-//int8_t g_tim2_start = 256-g_tick_time*g_cpu_freq/g_tim2_prescaler;
-//tim2_start = -50; note negative works here due to 2's compliment. (-50 == 206) in the 8 bit data types

-uint16_t interrupt_count=0;
-
+uint16_t g_interrupt_count=0;
 Flagger g_Flagger;
+uint8_t g_1000ms_flag = g_Flagger.registerFlag(5000);

 void setup()
 {
@@ -59,21 +57,23 @@

 ISR(TIMER2_OVF_vect){
   TCNT2=TIM2_START; //Reset the timer to start value for consistant roll overs
-	digitalWrite(ledPin, digitalRead(ledPin) ^ 1); //Toggle LED on each interrupt cycle
-  interrupt_count++;
+  g_interrupt_count++;
 	g_Flagger.tick();
-
   //Flag cleared automagically
 }

 void loop()
 {
-  if (interrupt_count>5000){
+  if (g_interrupt_count>5000){
     Serial.print("Interrupt Count=");
-    Serial.println(interrupt_count);
-    interrupt_count=0;
+    Serial.println(g_interrupt_count);
+    g_interrupt_count=0;
   }
-  int bar = 0;

+	//This happens once a second
+	if (g_Flagger.getFlag(g_1000ms_flag)){
+		digitalWrite(ledPin, digitalRead(ledPin) ^ 1); //Toggle LED
+		g_Flagger.clearFlag(g_1000ms_flag);
+	}
 }


Update ServoController.ino

Update ServoController.ino

--- software/Arduino/ServoController/ServoController.ino
+++ software/Arduino/ServoController/ServoController.ino
@@ -137,14 +137,14 @@
 */
 int zeroGyro(int calibrationSamples) {
   float zSum = 0;
+  digitalWrite(LED, HIGH);
   for (int i = 0; i < calibrationSamples; i++) {
     imu.readGyro();
     float z = imu.calcGyro(imu.gz);
     zSum += z;
-    if (i % 23 == 0)
-      blinkLED(20, 1);
-    delay(10);
+    delay(5);
   }
+  blinkLED(300, 5);
   return zSum / calibrationSamples;
 }


tab削除

tab削除

--- 1_practice/esp32_27_goo_lcd3/esp32_27_goo_lcd3.ino
+++ 1_practice/esp32_27_goo_lcd3/esp32_27_goo_lcd3.ino
@@ -196,13 +196,13 @@
             if(sec==0){                             // 現在時刻の秒が0のとき
                 wifi_udp(buf[i]);                   // 予定を送信
                 chime=chimeBells(PIN_BUZZER,chime); // チャイム音
-				String s = buf[i];
-				if(s.indexOf("AC=") == 6){          // 予定の内容がAC制御の時
+                String s = buf[i];
+                if(s.indexOf("AC=") == 6){          // 予定の内容がAC制御の時
                     int ac=s.substring(9).toInt();  // 「AC=」の数値を変数acへ
                     if(ac) httpGet(DEV_AC_ON);      // ACリレーをONにする
                     else httpGet(DEV_AC_OFF);       // ACリレーをOFFにする
                 }
-				if(s.indexOf("IR=") == 6){          // 予定の内容がAC制御の時
+                if(s.indexOf("IR=") == 6){          // 予定の内容がAC制御の時
                     int ir=s.substring(9).toInt();  // 「AC=」の数値を変数irへ
                     if(ir) httpPost(DEV_IR,IR_ON);  // エアコンの電源をONにする
                     else httpPost(DEV_IR,IR_OFF);   // エアコンの電源をOFFにする


Removes temporary prototyping code from Arduino sketch

--- arduino/booth_controller/booth_controller.ino
+++ arduino/booth_controller/booth_controller.ino
@@ -1,29 +1,16 @@
 #include <Wire.h>
 #include <SegmentDisplay.h>
-
-/*
-* temporary - will replace with approriate libaries for 7-segment display
-*/
-#include <LiquidCrystal.h>

 // after bit shifting will be converted to I2C slave address 8
 #define SLAVE_ADDRESS 0x04

-/*
-* temporary - initialize lcd object and set I2C simulating arming button
-* pin/state
-*/
-LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
-const char armingPin = 6;
-char armingButtonState = LOW;
-
 SegmentDisplay segmentDisplay;

 // armed indicator led pin
-const char armedPin = 8;
+const char armedPin = 4;

 // user trigger button pin and state
-const char triggerPin = 7;
+const char triggerPin = 5;
 char triggerState = LOW;

 // the controller must be armed by an I2C message before the user button will be
@@ -51,14 +38,8 @@
   Wire.onReceive(receiveData);
   Wire.onRequest(sendData);

-  /*
-  * temporary - setup and test lcd
-  */
-  lcd.begin(16, 2);
-  printStatus();
-
   // setup the common cathode segment display
-  segmentDisplay.initialize(10, 9, 6, 17, 16, 15, 14, 0);
+  segmentDisplay.initialize(6, 7, 8, 9, 10, 11, 12, 13);

   // set the armedPin to OUTPUT
   pinMode(armedPin, OUTPUT);
@@ -73,11 +54,6 @@
   if (triggerState == HIGH && systemArmed && triggerReady) {
     digitalWrite(armedPin, LOW);
     triggerReady = false;
-
-    /*
-    * temporary
-    */
-    printStatus();

     countdown();
   }
@@ -95,11 +71,7 @@
         disarmAfterCountdown();
         break;
       default:
-        /*
-        * temporary
-        */
-        lcd.clear();
-        lcd.print("Unrecognized cmd");
+        break;
     }
   }
 }
@@ -114,21 +86,11 @@
     systemArmed = true;
     triggerReady = true;
     digitalWrite(armedPin, HIGH);
-
-    /*
-    * temporary
-    */
-    printStatus();
   }
 }

 void disarmAfterCountdown() {
   systemArmed = false;
-
-  /*
-  * temporary
-  */
-  printStatus();

   outCode = 2;
 }
@@ -138,37 +100,14 @@
   long curr = millis();
   long delta = millis() - curr;
   while ((interval - delta) >= 0) {
-    /*
-    * temporary
-    */
-    //lcd.setCursor(15, 0);
-    //lcd.print((((interval - delta)) / 1000) + 1);

     segmentDisplay.print((((interval - delta)) / 1000) + 1);

     delta = millis() - curr;
   }

-  /*
-  * temporary
-  */
-  //lcd.setCursor(15, 0);
-  //lcd.print(" ");
-
   segmentDisplay.clear();

   outCode = 1;
 }

-/*
-* temporay - print system state to lcd display
-*/
-void printStatus() {
-  lcd.clear();
-  lcd.print("Sys. armed:  ");
-  lcd.print(systemArmed);
-  lcd.setCursor(0, 1);
-  lcd.print("Trig. ready: ");
-  lcd.print(triggerReady);
-}
-


Add header files to demo

Add header files to demo

--- examples/AstronomyDemo/AstronomyDemo.ino
+++ examples/AstronomyDemo/AstronomyDemo.ino
@@ -24,7 +24,8 @@
 */

 #include <Arduino.h>
-#include <ESPWiFi.h>
+#include <ESP8266WiFi.h>
+#include <ESPHTTPClient.h>
 #include <time.h>
 #include "Astronomy.h"


:art: Fix double log in example

:art: Fix double log in example

--- examples/FullyFeatured/FullyFeatured.ino
+++ examples/FullyFeatured/FullyFeatured.ino
@@ -57,7 +57,6 @@
   Serial.println("Disconnected from MQTT.");

   if (WiFi.isConnected()) {
-    Serial.println("Connecting to MQTT...");
     mqttReconnectTimer.once(2, connectToMqtt);
   }
 }
@@ -120,4 +119,4 @@
 }

 void loop() {
-}+}


code stappenmotor aangepast

code stappenmotor aangepast

--- programmaNano/programmaNano.ino
+++ programmaNano/programmaNano.ino
@@ -6,7 +6,7 @@
 unsigned long previousMillisStappenmotor = 0;

 const long interval = 50;
-const long intervalStappenmotor = 50;
+const long intervalStappenmotor = 10;

 #define echoPin 5          // Echo Pin
 #define trigPin 4          // Trigger Pin
@@ -81,124 +81,121 @@
 }

 void 1draaiNaarBeneden(){
+  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor && currentMillis - previousMillisStappenmotor < intervalStappenmotor+10) {
+    digitalWrite(coila1, HIGH);
+    digitalWrite(coila2, LOW);
+    digitalWrite(coilb1, LOW);
+    digitalWrite(coilb2, HIGH);
+  }
+
+  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor+10 && currentMillis - previousMillisStappenmotor < intervalStappenmotor+20) {
+
+    digitalWrite(coila1, LOW);
+    digitalWrite(coila2, LOW);
+    digitalWrite(coilb1, LOW);
+    digitalWrite(coilb2, HIGH);
+  }
+  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor+20 && currentMillis - previousMillisStappenmotor < intervalStappenmotor+30) {
+
+    digitalWrite(coila1, LOW);
+    digitalWrite(coila2, HIGH);
+    digitalWrite(coilb1, LOW);
+    digitalWrite(coilb2, HIGH);
+
+  }
+  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor+30 && currentMillis - previousMillisStappenmotor < intervalStappenmotor+40) {
+
+    digitalWrite(coila1, LOW);
+    digitalWrite(coila2, HIGH);
+    digitalWrite(coilb1, LOW);
+    digitalWrite(coilb2, LOW);
+  }
+  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor+40&& currentMillis - previousMillisStappenmotor < intervalStappenmotor+50) {
+
+    digitalWrite(coila1, LOW);
+    digitalWrite(coila2, HIGH);
+    digitalWrite(coilb1, HIGH);
+    digitalWrite(coilb2, LOW);
+  }
+  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor+50 && currentMillis - previousMillisStappenmotor < intervalStappenmotor+60) {
+
+    digitalWrite(coila1, LOW);
+    digitalWrite(coila2, LOW);
+    digitalWrite(coilb1, HIGH);
+    digitalWrite(coilb2, LOW);
+  }
+  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor+60 && currentMillis - previousMillisStappenmotor < intervalStappenmotor+70) {
+
+    digitalWrite(coila1, HIGH);
+    digitalWrite(coila2, LOW);
+    digitalWrite(coilb1, HIGH);
+    digitalWrite(coilb2, LOW);
+  }
+  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor+70) {
+  previousMillisStappenmotor = currentMillis;
+    digitalWrite(coila1, HIGH);
+    digitalWrite(coila2, LOW);
+    digitalWrite(coilb1, LOW);
+    digitalWrite(coilb2, LOW);
+  }
+}
+
+void 1draaiNaarBoven(){
+  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor && currentMillis - previousMillisStappenmotor < intervalStappenmotor+10) {
+
+    digitalWrite(coila1, HIGH);
+    digitalWrite(coila2, LOW);
+    digitalWrite(coilb1, LOW);
+    digitalWrite(coilb2, LOW);
+  }
+  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor && currentMillis - previousMillisStappenmotor < intervalStappenmotor+20) {
+
+    digitalWrite(coila1, HIGH);
+    digitalWrite(coila2, LOW);
+    digitalWrite(coilb1, HIGH);
+    digitalWrite(coilb2, LOW);
+  }
+  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor && currentMillis - previousMillisStappenmotor < intervalStappenmotor+30) {
+
+    digitalWrite(coila1, LOW);
+    digitalWrite(coila2, LOW);
+    digitalWrite(coilb1, HIGH);
+    digitalWrite(coilb2, LOW);
+  }
+  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor && currentMillis - previousMillisStappenmotor < intervalStappenmotor+40) {
+
+    digitalWrite(coila1, LOW);
+    digitalWrite(coila2, HIGH);
+    digitalWrite(coilb1, HIGH);
+    digitalWrite(coilb2, LOW);
+  }
+  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor && currentMillis - previousMillisStappenmotor < intervalStappenmotor+50) {
+
+    digitalWrite(coila1, LOW);
+    digitalWrite(coila2, HIGH);
+    digitalWrite(coilb1, LOW);
+    digitalWrite(coilb2, LOW);
+  }
+  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor && currentMillis - previousMillisStappenmotor < intervalStappenmotor+60) {
+
+    digitalWrite(coila1, LOW);
+    digitalWrite(coila2, HIGH);
+    digitalWrite(coilb1, LOW);
+    digitalWrite(coilb2, HIGH);
+  }
+  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor && currentMillis - previousMillisStappenmotor < intervalStappenmotor+70) {
+
+    digitalWrite(coila1, LOW);
+    digitalWrite(coila2, LOW);
+    digitalWrite(coilb1, LOW);
+    digitalWrite(coilb2, HIGH);
+  }
   if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor) {
     previousMillisStappenmotor = currentMillis;
     digitalWrite(coila1, HIGH);
     digitalWrite(coila2, LOW);
     digitalWrite(coilb1, LOW);
     digitalWrite(coilb2, HIGH);
-    delay(10);
-  }
-
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor) {
-  previousMillisStappenmotor = currentMillis;
-
-    digitalWrite(coila1, LOW);
-    digitalWrite(coila2, LOW);
-    digitalWrite(coilb1, LOW);
-    digitalWrite(coilb2, HIGH);
-  }
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor) {
-  previousMillisStappenmotor = currentMillis;
-    digitalWrite(coila1, LOW);
-    digitalWrite(coila2, HIGH);
-    digitalWrite(coilb1, LOW);
-    digitalWrite(coilb2, HIGH);
-    delay(10);
-  }
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor) {
-  previousMillisStappenmotor = currentMillis;
-    digitalWrite(coila1, LOW);
-    digitalWrite(coila2, HIGH);
-    digitalWrite(coilb1, LOW);
-    digitalWrite(coilb2, LOW);
-  }
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor) {
-  previousMillisStappenmotor = currentMillis;
-    digitalWrite(coila1, LOW);
-    digitalWrite(coila2, HIGH);
-    digitalWrite(coilb1, HIGH);
-    digitalWrite(coilb2, LOW);
-  }
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor) {
-  previousMillisStappenmotor = currentMillis;
-    digitalWrite(coila1, LOW);
-    digitalWrite(coila2, LOW);
-    digitalWrite(coilb1, HIGH);
-    digitalWrite(coilb2, LOW);
-  }
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor) {
-  previousMillisStappenmotor = currentMillis;
-    digitalWrite(coila1, HIGH);
-    digitalWrite(coila2, LOW);
-    digitalWrite(coilb1, HIGH);
-    digitalWrite(coilb2, LOW);
-  }
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor) {
-  previousMillisStappenmotor = currentMillis;
-    digitalWrite(coila1, HIGH);
-    digitalWrite(coila2, LOW);
-    digitalWrite(coilb1, LOW);
-    digitalWrite(coilb2, LOW);
-  }
-}
-
-void 1draaiNaarBoven(){
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor) {
-  previousMillisStappenmotor = currentMillis;
-    digitalWrite(coila1, HIGH);
-    digitalWrite(coila2, LOW);
-    digitalWrite(coilb1, LOW);
-    digitalWrite(coilb2, LOW);
-  }
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor) {
-  previousMillisStappenmotor = currentMillis;
-    digitalWrite(coila1, HIGH);
-    digitalWrite(coila2, LOW);
-    digitalWrite(coilb1, HIGH);
-    digitalWrite(coilb2, LOW);
-  }
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor) {
-  previousMillisStappenmotor = currentMillis;
-    digitalWrite(coila1, LOW);
-    digitalWrite(coila2, LOW);
-    digitalWrite(coilb1, HIGH);
-    digitalWrite(coilb2, LOW);
-  }
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor) {
-    previousMillisStappenmotor = currentMillis;
-    digitalWrite(coila1, LOW);
-    digitalWrite(coila2, HIGH);
-    digitalWrite(coilb1, HIGH);
-    digitalWrite(coilb2, LOW);
-  }
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor) {
-    previousMillisStappenmotor = currentMillis;
-    digitalWrite(coila1, LOW);
-    digitalWrite(coila2, HIGH);
-    digitalWrite(coilb1, LOW);
-    digitalWrite(coilb2, LOW);
-  }
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor) {
-    previousMillisStappenmotor = currentMillis;
-    digitalWrite(coila1, LOW);
-    digitalWrite(coila2, HIGH);
-    digitalWrite(coilb1, LOW);
-    digitalWrite(coilb2, HIGH);
-  }
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor) {
-    previousMillisStappenmotor = currentMillis;
-    digitalWrite(coila1, LOW);
-    digitalWrite(coila2, LOW);
-    digitalWrite(coilb1, LOW);
-    digitalWrite(coilb2, HIGH);
-  }
-  if (currentMillis - previousMillisStappenmotor >= intervalStappenmotor) {
-    previousMillisStappenmotor = currentMillis;
-    digitalWrite(coila1, HIGH);
-    digitalWrite(coila2, LOW);
-    digitalWrite(coilb1, LOW);
-    digitalWrite(coilb2, HIGH);
-  }
-}
-
+  }
+}
+


Updated rawCsineFreq to include delay for frequency


Fix pen going down at the beginning of every run

Fixes #11.

--- firmware/firmware.ino
+++ firmware/firmware.ino
@@ -328,9 +328,8 @@
   initRobotSetup();
   initPosition();

+  servoPen.write(servo_position);
   servoPen.attach(servopin);
-  delay(100);
-  servoPen.write(servo_position);
   delay(1000);

   goHome();
@@ -414,4 +413,4 @@
   Serial.print(digitalRead(xlimit_pin2)); Serial.print(" ");
   Serial.print(digitalRead(ylimit_pin1)); Serial.print(" ");
   Serial.println(digitalRead(ylimit_pin2));
-}+}


reduce memory footprint of the sketch

reduce memory footprint of the sketch

--- sketches/Energino/Energino.ino
+++ sketches/Energino/Energino.ino
@@ -49,18 +49,18 @@
  */

 #include <SPI.h>
+#include <SD.h>
 #include <Ethernet.h>
 #include <EEPROM.h>
 #include <avr/eeprom.h>

 // comment/uncomment to disable/enable debug
-//#define DEBUG
+#define DEBUG

 // comment/uncomment to disable/enable ethernet support
-#define NOETH
+//#define NOETH

 #define RELAY_PIN 3
-#define STRING_BUFFER_SIZE 300

 #ifdef DEBUG
 #define DBG if(1)
@@ -84,10 +84,6 @@
 int SENSITIVITY = 850;
 int PERIOD = 2000;

-// Accumulators
-long VRaw = 0;
-long IRaw = 0;
-
 // Control loop paramters
 long sleep = 0;
 long delta = 0;
@@ -98,23 +94,14 @@

 #ifndef NOETH

-  // Buffers used for parsing HTTP request lines
-  char buffer[STRING_BUFFER_SIZE];
-
   // Server configuration parameters, energino will listen for
   // incoming requests on this port
   const long SERVER_PORT = 8180;

   // This configuration is used when DHCP fails
-  IPAddress IP(172,25,18,219);
+  IPAddress IP(192,168,1,10);
   IPAddress MASK(255,255,255,0);
-  IPAddress GW(172,25,18,254);
-
-  // Not found page
-  const char CONTENT_404[] = "HTTP/1.1 404 Not Found\n\n";
-
-  // Not implemented page
-  const char CONTENT_501[] = "HTTP/1.1 501 Not Implemented\n\n";
+  IPAddress GW(192,168,1,1);

   // JSON response header and footer
   const char JSON_RESPONSE_BEGIN[] = "HTTP/1.1 200 OK\nContent-Type: application/json\n\n[";
@@ -134,27 +121,29 @@

 // Permanent configuration
 struct settings_t {
-  char magic[17];
-  byte mac[6];
-  char apikey[49];
+  char magic[9];
   long period;
   int r1;
   int r2;
   int offset;
   int sensitivity;
+#ifndef NOETH
+  byte mac[6];
+  char apikey[49];
   long feed;
   IPAddress host;
   long port;
+#endif
 } settings;

 void reset() {
-  DBG Serial.println("Writing defaults.");
   strcpy (settings.magic,MAGIC);
   settings.period = PERIOD;
   settings.r1 = R1;
   settings.r2 = R2;
   settings.offset = OFFSET;
   settings.sensitivity = SENSITIVITY;
+#ifndef NOETH
   settings.feed = FEED;
   settings.host = HOST;
   settings.port = PORT;
@@ -166,6 +155,7 @@
   for (int i = 3; i < 6; i++) {
     settings.mac[i] = random(0, 255);
   }
+#endif
 }

 void setup() {
@@ -178,31 +168,34 @@
   eeprom_read_block((void*)&settings, (void*)0, sizeof(settings));
   if (strcmp(settings.magic, MAGIC) != 0) {
     reset();
+    DBG Serial.println("write defaults");
     eeprom_write_block((const void*)&settings, (void*)0, sizeof(settings));
   }
   // set sleep counter
   resetSleep(settings.period);
   #ifndef NOETH
-    // Print hw address
-    char macstr[18];
-    snprintf(macstr, 18, "%02x:%02x:%02x:%02x:%02x:%02x", settings.mac[0], settings.mac[1], settings.mac[2], settings.mac[3], settings.mac[4], settings.mac[5]);
-    DBG Serial.print("HWAddr: ");
-    DBG Serial.println(macstr);
     // Try to configure the ethernet using DHCP
     delay(2000);
-    DBG Serial.println("Running DHCP...");
+    DBG Serial.println("dhcp");
     if (Ethernet.begin(settings.mac) == 0) {
-      DBG Serial.println("DHCP failed, using static IP.");
+      DBG Serial.println("dhcp fail");
       // Use static IP
       Ethernet.begin(settings.mac, IP, MASK, GW);
     }
     // Print IP
-    DBG Serial.print("IPAddr: ");
+    DBG Serial.print("ip: ");
     DBG Serial.println(Ethernet.localIP());
     // Give the Ethernet shield a second to initialize:
     delay(1000);
     // Start server
     server.begin();
+    // Init SD
+    pinMode(10, OUTPUT);
+    // see if the card is present and can be initialized:
+    if (!SD.begin(4)) {
+      Serial.println("sd fail");
+      return;
+    }
   #endif
 }

@@ -211,7 +204,7 @@
   // Make sure that update period is not too high
   #ifndef NOETH
     if ((settings.feed != 0) && (settings.period < MIN_ETHERNET_PERIOD)) {
-      DBG Serial.println("Update period is too high, resetting.");
+      DBG Serial.println("period too high");
       resetSleep(MIN_ETHERNET_PERIOD);
     }
   #endif
@@ -229,8 +222,8 @@

   // Instant values are too floating,
   // let's smooth them up
-  VRaw = 0;
-  IRaw = 0;
+  long VRaw = 0;
+  long IRaw = 0;

   for(long i = 0; i < sleep; i++) {
     VRaw += analogRead(A1);
@@ -243,7 +236,7 @@

   // send data to remote host
   #ifndef NOETH
-    sendData();
+    //sendData();
   #endif

   // dump to serial
@@ -293,46 +286,9 @@
   // null-terminate input buffer
   inputBytes[i] = '\0';
   // execute command
-  if (cmd == 'P') {
-    int value = atoi(inputBytesPtr);
-    if (value > 0) {
-      resetSleep(value);
-    }
-  }
-  else if (cmd == 'A') {
-    int value = atoi(inputBytesPtr);
-    if (value >= 0) {
-      settings.r1 = value;
-    }
-  }
-  else if (cmd == 'B') {
-    int value = atoi(inputBytesPtr);
-    if (value >= 0) {
-      settings.r2 = value;
-    }
-  }
-  else if (cmd == 'C') {
-    int value = atoi(inputBytesPtr);
-    if (value >= 0) {
-      settings.offset = value;
-    }
-  }
-  else if (cmd == 'D') {
-    int value = atoi(inputBytesPtr);
-    if (value >= 0) {
-      settings.sensitivity = value;
-    }
-  }
-  else if (cmd == 'S') {
-    int value = atoi(inputBytesPtr);
-    if (value >= 0) {
-      digitalWrite(RELAY_PIN, HIGH);
-    }
-    else {
-      digitalWrite(RELAY_PIN, LOW);
-    }
-  }
-  #ifndef NOETH
+  if (cmd == 'R') {
+    reset();
+  }
   else if (cmd == 'F') {
     long value = atol(inputBytesPtr);
     if (value >= 0) {
@@ -350,22 +306,42 @@
       host[i] = atoi(p);
       p = strtok(NULL, ".");
     }
-    IPAddress hostIP = IPAddress(host);
-    DBG Serial.print("New host ip address: ");
-    DBG Serial.println(hostIP);
     settings.host=IPAddress(host);
   }
   else if (cmd == 'O') {
     long value = atol(inputBytesPtr);
     if (value > 0) {
-      DBG Serial.print("New host port: ");
-      DBG Serial.println(value);
       settings.port = value;
     }
   }
-  #endif
-  else if (cmd == 'R') {
-    reset();
+  else {
+    int value = atoi(inputBytesPtr);
+    if (value > 0) {
+      return;
+    }
+    if (cmd == 'P') {
+      resetSleep(value);
+    }
+    else if (cmd == 'A') {
+      settings.r1 = value;
+    }
+    else if (cmd == 'B') {
+        settings.r2 = value;
+    }
+    else if (cmd == 'C') {
+        settings.offset = value;
+    }
+    else if (cmd == 'D') {
+        settings.sensitivity = value;
+    }
+    else if (cmd == 'S') {
+      if (value >= 0) {
+        digitalWrite(RELAY_PIN, HIGH);
+      }
+      else {
+        digitalWrite(RELAY_PIN, LOW);
+      }
+    }
   }
   eeprom_write_block((const void*)&settings, (void*)0, sizeof(settings));
 }
@@ -376,20 +352,20 @@
 void handleRequests() {
   EthernetClient request = server.available();
   if (request) {
-    DBG Serial.println("Got request: ");
     int idx = 0;
+    char buffer[50];
     while (request.connected() && request.available()) {
       // Read char by char HTTP request
       char c = request.read();
       DBG Serial.print(c);
       // Store characters to string
-      if (idx < STRING_BUFFER_SIZE) {
+      if (idx < 50) {
         buffer[idx] = c;
       }
       idx++;
       // If you've gotten to the end of the line (received a newline
       // character) the http request has ended, so you can send a reply
-      if (c == '\n' || idx >= STRING_BUFFER_SIZE) {
+      if (c == '\n' || idx >= 50) {
         //char method [5];
         char * method;
         method = strtok (buffer, " ");
@@ -400,12 +376,10 @@
           if (strcmp(toks, "read") == 0) {
             toks = strtok (NULL, "/");
             if (strcmp(toks, "datastreams") == 0) {
-              DBG Serial.println("Sending full datastream");
-              sendContent(request,getDatastream());
+              sendContent(request);
               break;
             }
             else if (strcmp(toks, "switch") == 0) {
-              DBG Serial.println("Sending switch status");
               sendContent(request, digitalRead(RELAY_PIN));
               break;
             }
@@ -415,23 +389,34 @@
             if (strcmp(toks, "switch") == 0) {
               toks = strtok (NULL, "/");
               if (atoi(toks) > 0) {
-                DBG Serial.println("Setting switch status to HIGH");
+                DBG Serial.println("switch up");
                 digitalWrite(RELAY_PIN, HIGH);
               }
               else {
-                DBG Serial.println("Setting switch status to LOW");
+                DBG Serial.println("switch down");
                 digitalWrite(RELAY_PIN, LOW);
               }
               sendContent(request, digitalRead(RELAY_PIN));
               break;
             }
-          }
+          }
+          else {
+            File dataFile = SD.open("a.htm");
+            if (dataFile) {
+              while (dataFile.available()) {
+                  request.write(dataFile.read());
+              }
+              dataFile.close();
+            } else {
+              Serial.println(dataFile);
+            }
+          }
           // send a not found response header
-          request.println(CONTENT_404);
+          request.println("HTTP/1.1 404 Not Found\n\n");
           request.println();
           break;
         }
-        request.println(CONTENT_501);
+        request.println("HTTP/1.1 501 Not Implemented\n\n");
         request.println();
         break;
       }
@@ -450,13 +435,10 @@
     return;
   }
   // try to connect
-  DBG Serial.println("Connecting.");
   EthernetClient client;
   int ret = client.connect(settings.host, settings.port);
   if (ret == 1) {
     // build json document
-    char *json = getDatastream();
-    DBG Serial.println("connected.");
     DBG Serial.print("PUT /v2/feeds/");
     DBG Serial.println(settings.feed);
     // send the HTTP PUT request.
@@ -467,12 +449,10 @@
     client.println(settings.apikey);
     client.print("User-Agent: ");
     client.println(MAGIC);
-    client.print("Content-Length: ");
-    client.println(strlen(json));
     client.print("Content-Type: application/json\n");
     client.print("\n");
     // here's the actual content of the PUT request:
-    client.print(json);
+    writeDataStream(client);
     delay(1000);
     // if there are incoming bytes available
     // from the server, read them and print them:
@@ -485,7 +465,7 @@
   }
   else {
     // if you couldn't make a connection:
-    DBG Serial.println("Unable to connect.");
+    DBG Serial.println("fail");
   }
 }

@@ -495,31 +475,30 @@
   request.print(JSON_RESPONSE_END);
 }

-void sendContent(EthernetClient &request, char *value) {
+void sendContent(EthernetClient &request) {
   request.println(JSON_RESPONSE_BEGIN);
-  request.print(value);
+  writeDataStream(request);
   request.print(JSON_RESPONSE_END);
 }

-char * getDatastream() {
+void writeDataStream(EthernetClient &request) {
   char r[10];
-  strcpy (buffer,"{\"version\":\"1.0.0\",");
-  strcat (buffer,"\"datastreams\":[");
-  strcat (buffer,"{\"id\":\"current\",\"current_value\":");
-  strcat (buffer,dtostrf (IFinal, 5, 3, r));
-  strcat (buffer,"},");
-  strcat (buffer,"{\"id\":\"voltage\",\"current_value\":");
-  strcat (buffer,dtostrf (VFinal, 5, 3, r));
-  strcat (buffer,"},");
-  strcat (buffer,"{\"id\":\"watts\",\"current_value\":");
-  strcat (buffer,dtostrf (VFinal * IFinal, 5, 3, r));
-  strcat (buffer,"},");
-  strcat (buffer,"{\"id\":\"switch\", \"current_value\":");
-  strcat (buffer,itoa(digitalRead(RELAY_PIN),r,10));
-  strcat (buffer,"}");
-  strcat (buffer,"]}");
-}
-
+  request.print("{\"version\":\"1.0.0\",");
+  request.print("\"datastreams\":[");
+  request.print("{\"id\":\"current\",\"current_value\":");
+  request.print(dtostrf (IFinal, 5, 3, r));
+  request.print("},");
+  request.print("{\"id\":\"voltage\",\"current_value\":");
+  request.print(dtostrf (VFinal, 5, 3, r));
+  request.print("},");
+  request.print("{\"id\":\"watts\",\"current_value\":");
+  request.print(dtostrf (VFinal * IFinal, 5, 3, r));
+  request.print("},");
+  request.print("{\"id\":\"switch\", \"current_value\":");
+  request.print(itoa(digitalRead(RELAY_PIN),r,10));
+  request.print("}");
+  request.print("]}");;
+}
 #endif

 void dumpToSerial() {


remove question

remove question

--- software/decision/decision.ino
+++ software/decision/decision.ino
@@ -5,7 +5,6 @@
 #define MAGS 4
 #define RPM_AVG 5
 #define HALL P1_5
-#define QUESTION P1_4

 #define SHIFT_OFFSET 10

@@ -45,8 +44,6 @@

   // pull up to start
   pinMode(HALL, INPUT_PULLUP);
-  pinMode(QUESTION, OUTPUT);
-  digitalWrite(QUESTION, HIGH);

   // initialize variables
   switched = 0;
@@ -135,8 +132,8 @@
     average += rps[idx];

   // calculate RPM from the RPS moving average
+  average /= RPM_AVG;
   average *= 60;
-  average /= RPM_AVG;
   average /= MAGS;

   // reset mag_count for the next pass


Add ADC averaging to mitigate noise in the battery voltage measurement

--- battery-monitor.ino
+++ battery-monitor.ino
@@ -4,6 +4,7 @@
 #define R2 21440 // Resistor R2 Ohms
 #define CONNECT_WAIT_MILLIS 10000
 #define LOW_THRESHOLD 12000 // milliVolts
+#define ADC_SAMPLES 20
 #define SLEEP_SECS 3600 // 1 hour
 //#define SLEEP_SECS 15

@@ -70,9 +71,7 @@

 void publishVoltageEvent() {
     char eventData[5];
-    uint16_t milliVolts = getBatteryMilliVolts();
-    delay(10);
-    milliVolts = getBatteryMilliVolts();
+    uint16_t milliVolts = getAvgBatteryMilliVolts();
     sprintf(eventData, "%.1f", milliVolts / 1000.0);
     if (milliVolts < LOW_THRESHOLD) {
         Particle.publish(LOW_EVENT, eventData, 60, PRIVATE);
@@ -107,6 +106,15 @@
     flashing = true;
 }

+uint16_t getAvgBatteryMilliVolts() {
+    uint16_t mV = 0;
+    for (int i = 0; i < ADC_SAMPLES; i++) {
+        mV += readMilliVolts(BATTERY_PIN);
+        delay(3);
+    }
+    return round(mV * DIV_RATIO / (float) ADC_SAMPLES);
+}
+
 uint16_t getBatteryMilliVolts() {
 	uint16_t mV = readMilliVolts(BATTERY_PIN);
 	return round(mV * DIV_RATIO);


initial commit

initial commit

--- FireFlies/FireFlies.ino
+++ FireFlies/FireFlies.ino
@@ -7,32 +7,45 @@
  This example code is in the public domain.
  */

-int leds[] = {9, 10, 11};
-int bright[];
-int fade[];
-int led = 9;           // the pin that the LED is attached to
-int brightness = 0;    // how bright the LED is
-int fadeAmount = 5;    // how many points to fade the LED by
+const int LEDNUM = 6;
+const int SLEEPINTERVAL = 1;
+
+int leds[] = {3, 5, 6, 9, 10, 11};
+int brightness[LEDNUM];
+int fade[LEDNUM];
+int sleep[LEDNUM];

 // the setup routine runs once when you press reset:
 void setup()  {
-  for (int i = 0; i < 3; i++) {
+  randomSeed(analogRead(0));
+  for (int i = 0; i < LEDNUM; i++) {
     pinMode(leds[i], OUTPUT);
+    brightness[i] = 0;
+    fade[i] = 15;
+    sleep[i] = random(10);
   }
 }

 // the loop routine runs over and over again forever:
-void loop()  {
-  // set the brightness of pin 9:
-  analogWrite(led, brightness);
-
-  // change the brightness for next time through the loop:
-  brightness = brightness + fadeAmount;
-
-  // reverse the direction of the fading at the ends of the fade:
-  if (brightness == 0 || brightness == 255) {
-    fadeAmount = -fadeAmount ;
-  }
+void loop()  {
+  for (int i = 0; i < LEDNUM; i++)
+  {
+    if (sleep[i] > 0) {
+      sleep[i] = sleep[i] - SLEEPINTERVAL;
+    } else {
+      brightness[i] = brightness[i] + fade[i];
+      if (brightness[i] < 0) {
+        brightness[i] = 0;
+        sleep[i] = random(1000);
+        fade[i] = -fade[i];
+      }
+      if (brightness[i] > 254) {
+        brightness[i] = 254;
+        fade[i] = -fade[i];
+      }
+      analogWrite(leds[i], brightness[i]);
+    }
+  }
   // wait for 30 milliseconds to see the dimming effect
   delay(30);
 }


off by one error in /data report count

off by one error in /data report count

--- ardesp/waterelf/waterelf.ino
+++ ardesp/waterelf/waterelf.ino
@@ -40,7 +40,7 @@

 /////////////////////////////////////////////////////////////////////////////
 // data monitoring stuff
-const int MONITOR_POINTS = 60;
+const int MONITOR_POINTS = 60; // number of data points to store
 struct monitor_t {
   unsigned long timestamp;
   float celsius;
@@ -49,6 +49,7 @@
 monitor_t monitorData[MONITOR_POINTS];
 int monitorCursor = 0;
 int monitorSize = 0;
+const int DATA_ENTRIES = 30; // size of /data report; must be <= MONITOR_POINTS
 void updateSensorData(monitor_t *monitorData);
 void getTemperature(float* celsius, float* fahrenheit);
 void printMonitorEntry(monitor_t m, String* buf);
@@ -99,15 +100,15 @@

   int m = monitorCursor;
   updateSensorData(monitorData);
-  Serial.print("monitorData[monitorCursor].celsius:" );
-  Serial.println(monitorData[m].celsius);
+  // Serial.print("monitorData[monitorCursor].celsius:" );
+  // Serial.println(monitorData[m].celsius);
   delay(100);
 }

 /////////////////////////////////////////////////////////////////////////////
 // wifi management stuff ////////////////////////////////////////////////////
 void handleNotFound() {
-  Serial.print("\t\t\t\t URI Not Found: ");
+  Serial.print("URI Not Found: ");
   Serial.println(server.uri());
   // TODO send redirect to /? or just use handle_root?
   server.send(200, "text/plain", "URI Not Found");
@@ -123,6 +124,8 @@
   delay(100);
 }

+// TODO handle_actuator form
+
 void handle_data() {
   Serial.println("serving page at /data");
   String toSend = pageTop;
@@ -130,13 +133,12 @@
   toSend += pageTop2;
   toSend += "<pre>\n";

-  Serial.print("monitorCursor="); Serial.println(monitorCursor);
-  Serial.print("monitorSize=");   Serial.println(monitorSize);
-  const int DATA_ENTRIES = 30;
+  Serial.print("monitorCursor="); Serial.print(monitorCursor);
+  Serial.print(" monitorSize=");  Serial.println(monitorSize);
   int mSize = monitorSize;
   for(
-    int i = monitorCursor - 1, j = 0;
-    j <= DATA_ENTRIES && j <= MONITOR_POINTS;
+    int i = monitorCursor - 1, j = 1;
+    j <= DATA_ENTRIES && j <= monitorSize;
     i--, j++
   ) {
     Serial.print("printMonitorEntry(monitorData["); Serial.print(i);
@@ -281,8 +283,8 @@
 /////////////////////////////////////////////////////////////////////////////
 // sensor stuff /////////////////////////////////////////////////////////////
 void updateSensorData(monitor_t *monitorData) {
-  Serial.print("monitorCursor = "); Serial.println(monitorCursor);
-  Serial.print("monitorSize = ");   Serial.println(monitorSize);
+  // Serial.print("monitorCursor = "); Serial.print(monitorCursor);
+  // Serial.print(" monitorSize = ");  Serial.println(monitorSize);

   monitor_t* now = &monitorData[monitorCursor];
   if(monitorSize < MONITOR_POINTS)
@@ -314,34 +316,32 @@
   Serial.println("getTemperature()...");

   while(!ds.search(addr)) {
-    Serial.println("no more addresses; resetting...");
-    Serial.println();
+    Serial.println("  no more addresses; resetting...");
     ds.reset_search();
     delay(250);
   }

   if(OneWire::crc8(addr, 7) != addr[7]) {
-      Serial.println("CRC is not valid!");
+      Serial.println("  CRC is not valid!");
       return;
   }
-  Serial.println();

   // the first ROM byte indicates which chip
   switch(addr[0]) {
     case 0x10:
-      Serial.println("  chip = DS18S20");  // or old DS1820
+      Serial.print("  chip=DS18S20");  // or old DS1820
       type_s = 1;
       break;
     case 0x28:
-      Serial.println("  chip = DS18B20");
+      Serial.println("  chip=DS18B20");
       type_s = 0;
       break;
     case 0x22:
-      Serial.println("  chip = DS1822");
+      Serial.println("  chip=DS1822");
       type_s = 0;
       break;
     default:
-      Serial.println("device is not a DS18x20 family device.");
+      Serial.println("  device is not a DS18x20 family device :-(");
       return;
   }

@@ -356,7 +356,7 @@
   ds.select(addr);
   ds.write(0xBE);       // read scratchpad

-  Serial.print("  Data = ");
+  Serial.print(" ; data=");
   Serial.print(present, HEX);
   Serial.print(" ");
   for(i = 0; i < 9; i++) { // we need 9 bytes


Fix #553: add CFG_au915, other region to ttn-abp example

--- examples/ttn-abp/ttn-abp.ino
+++ examples/ttn-abp/ttn-abp.ino
@@ -237,7 +237,8 @@
     // frequencies, so be sure to configure the full frequency range of
     // your network here (unless your network autoconfigures them).
     // Setting up channels should happen after LMIC_setSession, as that
-    // configures the minimal channel set.
+    // configures the minimal channel set. The LMIC doesn't let you change
+    // the three basic settings, but we show them here.
     LMIC_setupChannel(0, 868100000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_CENTI);      // g-band
     LMIC_setupChannel(1, 868300000, DR_RANGE_MAP(DR_SF12, DR_SF7B), BAND_CENTI);      // g-band
     LMIC_setupChannel(2, 868500000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_CENTI);      // g-band
@@ -251,12 +252,39 @@
     // devices' ping slots. LMIC does not have an easy way to define set this
     // frequency and support for class B is spotty and untested, so this
     // frequency is not configured here.
-    #elif defined(CFG_us915)
-    // NA-US channels 0-71 are configured automatically
+    #elif defined(CFG_us915) || defined(CFG_au915)
+    // NA-US and AU channels 0-71 are configured automatically
     // but only one group of 8 should (a subband) should be active
     // TTN recommends the second sub band, 1 in a zero based count.
     // https://github.com/TheThingsNetwork/gateway-conf/blob/master/US-global_conf.json
     LMIC_selectSubBand(1);
+    #elif defined(CFG_as923)
+    // Set up the channels used in your country. Only two are defined by default,
+    // and they cannot be changed.  Use BAND_CENTI to indicate 1% duty cycle.
+    // LMIC_setupChannel(0, 923200000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_CENTI);
+    // LMIC_setupChannel(1, 923400000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_CENTI);
+
+    // ... extra definitions for channels 2..n here
+    #elif defined(CFG_kr920)
+    // Set up the channels used in your country. Three are defined by default,
+    // and they cannot be changed. Duty cycle doesn't matter, but is conventionally
+    // BAND_MILLI.
+    // LMIC_setupChannel(0, 922100000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_MILLI);
+    // LMIC_setupChannel(1, 922300000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_MILLI);
+    // LMIC_setupChannel(2, 922500000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_MILLI);
+
+    // ... extra definitions for channels 3..n here.
+    #elif defined(CFG_in866)
+    // Set up the channels used in your country. Three are defined by default,
+    // and they cannot be changed. Duty cycle doesn't matter, but is conventionally
+    // BAND_MILLI.
+    // LMIC_setupChannel(0, 865062500, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_MILLI);
+    // LMIC_setupChannel(1, 865402500, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_MILLI);
+    // LMIC_setupChannel(2, 865985000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_MILLI);
+
+    // ... extra definitions for channels 3..n here.
+    #else
+    # error Region not supported
     #endif

     // Disable link check validation


TODO-721: ~180ms per secure beacon generated

--- test_SECFRAME/test_SECFRAME.ino
+++ test_SECFRAME/test_SECFRAME.ino
@@ -743,7 +743,8 @@
   AssertIsEqual(0x00, buf[11]); // Body length 0.
   //AssertIsEqual(0xXX, buf[12]); // CRC will vary with ID.
   //
-  for(int idLen = 0; idLen <= 4; ++idLen)
+//  const unsigned long before = millis();
+  for(int idLen = 0; idLen <= 8; ++idLen)
     {
     // Secure beacon...  All zeros key; ID and IV as from spec Example 3 at 20160207.
     const uint8_t *const key = zeroKey;
@@ -754,6 +755,8 @@
     const uint8_t sb1 = OTRadioLink::generateSecureBeaconRaw(buf, sizeof(buf), id, idLen, iv, OTAESGCM::fixed32BTextSize12BNonce16BTagSimpleEnc_DEFAULT_STATELESS, NULL, key);
     AssertIsEqual(27 + idLen, sb1);
     }
+//  const unsigned long after = millis();
+//  Serial.println(after - before); // DHD20160207: 1442 for 8 rounds, or ~180ms per encryption.
   }


TODO-728: more extensive tests, failing

TODO-728: more extensive tests, failing

--- test_SECFRAME/test_SECFRAME.ino
+++ test_SECFRAME/test_SECFRAME.ino
@@ -989,6 +989,31 @@
     { AssertIsEqual(0, OTV0P2BASE::getNextMatchingNodeID(0, ID0, i, NULL)); }
   for(uint8_t i = 1; i <= sizeof(ID0); ++i)
     { AssertIsEqual(-1, OTV0P2BASE::getNextMatchingNodeID(1, ID0, i, NULL)); }
+  // Updating to a new (up-by-one) count and reading back should work.
+  const uint8_t newCount2[] = { 0, 1, 2, 3, 4, 6 };
+  AssertIsTrue(OTRadioLink::SimpleSecureFrame32or0BodyRXV0p2::getInstance().updateRXMessageCountAfterAuthentication(ID0, newCount2));
+  AssertIsTrue(OTRadioLink::SimpleSecureFrame32or0BodyRXV0p2::getInstance().getLastRXMessageCounter(ID0, mcbuf));
+  AssertIsEqual(0, memcmp(mcbuf, newCount2, sizeof(mcbuf)));
+  // Updating to a new (up-by-slightly-more-than-one) count and reading back should work.
+  const uint8_t newCount3[] = { 0, 1, 2, 3, 4, 9 };
+  AssertIsTrue(OTRadioLink::SimpleSecureFrame32or0BodyRXV0p2::getInstance().updateRXMessageCountAfterAuthentication(ID0, newCount3));
+  AssertIsTrue(OTRadioLink::SimpleSecureFrame32or0BodyRXV0p2::getInstance().getLastRXMessageCounter(ID0, mcbuf));
+  AssertIsEqual(0, memcmp(mcbuf, newCount3, sizeof(mcbuf)));
+  // Updating to a new (up-by-much-more-than-one) count and reading back should work.
+  const uint8_t newCount4[] = { 0, 1, 2, 3, 4, 99 };
+  AssertIsTrue(OTRadioLink::SimpleSecureFrame32or0BodyRXV0p2::getInstance().updateRXMessageCountAfterAuthentication(ID0, newCount4));
+  AssertIsTrue(OTRadioLink::SimpleSecureFrame32or0BodyRXV0p2::getInstance().getLastRXMessageCounter(ID0, mcbuf));
+  AssertIsEqual(0, memcmp(mcbuf, newCount4, sizeof(mcbuf)));
+  // Updating to a new (up-by-much-much-more-than-one) count and reading back should work.
+  const uint8_t newCount5[] = { 0, 1, 0x99, 1, 0x81, (OTV0P2BASE::randRNG8() & 0x7f) };
+  AssertIsTrue(OTRadioLink::SimpleSecureFrame32or0BodyRXV0p2::getInstance().updateRXMessageCountAfterAuthentication(ID0, newCount5));
+  AssertIsTrue(OTRadioLink::SimpleSecureFrame32or0BodyRXV0p2::getInstance().getLastRXMessageCounter(ID0, mcbuf));
+  AssertIsEqual(0, memcmp(mcbuf, newCount5, sizeof(mcbuf)));
+  // Updating to a new (up-by-one) count and reading back should work.
+  const uint8_t newCount6[] = { 0, 1, 0x99, 1, 0x81, 1+newCount[5] };
+  AssertIsTrue(OTRadioLink::SimpleSecureFrame32or0BodyRXV0p2::getInstance().updateRXMessageCountAfterAuthentication(ID0, newCount6));
+  AssertIsTrue(OTRadioLink::SimpleSecureFrame32or0BodyRXV0p2::getInstance().getLastRXMessageCounter(ID0, mcbuf));
+  AssertIsEqual(0, memcmp(mcbuf, newCount6, sizeof(mcbuf)));
   }


Started motor functions

Started motor functions

--- ROD.ino
+++ ROD.ino
@@ -1,13 +1,41 @@
-void drive(int X, int y, int speed)
-{
-
-}
-void setup()
-{
-
-}

-void loop()
-{
+void setup() {
+  Serial.begin(9600);
+  //set outputs
+  for (int i = 0; i < 2; i++)
+  {
+    pinMode(inApin[i], OUTPUT);
+    pinMode(inBpin[i], OUTPUT);
+    pinMode(pwmpin[i], OUTPUT);
+  }
+  //set motor pins low
+  for (int i = 0; i < 2; i++)
+  {
+    digitalWrite(inApin[i], LOW);
+    digitalWrite(inBpin[i], LOW);
+  }

-}
+
+
+  void loop() {
+    drive();//continuously drive motor
+  }
+  void drive(int x, int y, int velocity)//sends control signal to motor shield
+  {
+    int speed0;//speed left motor
+    int speed1;//speed right motor
+    int direction0;//direction left motor
+    int direction1;//direction right motor
+    calcultateSpeedDirection (x, y, velocity);//calculate parameters
+    adjustMotor(0, direction0, speed0);//run left motor
+    adjustMotor (1, direction1, speed1);//run right motor
+  }
+  void adjustMotor(uint8_t motor, uint8_t direct, uint8_t pwm)//sends signal to run motor
+  {
+
+  }
+  void calcultateSpeedDirection (x, y, velocity)//converts input in controller-format to suitable combination of track movements
+  {
+
+  }
+


Update AD7173-8.ino

Update AD7173-8.ino

updated chip illustration


ditched all fading for short term reliablitiy and skipped trouble shooting :)

--- Room_System_Ardu/Room_System_Ardu.ino
+++ Room_System_Ardu/Room_System_Ardu.ino
@@ -72,7 +72,7 @@
 }

 void loop() {
-  Now = (int) millis() / 1000; // everything is done in seconds
+  Now = millis() / 1000; // everything is done in seconds

   Lights_ON = not digitalRead(Lights_Pin);
   Flashing_Lights = not digitalRead(Flash_Pin);
@@ -123,15 +123,15 @@
     FastLED.delay(1000 / UPDATES_PER_SECOND);
   }
   else if (Lights_ON) {
-    if ((Now - Start) > fade_time) {
-      Brightness = 255;
-    }
-    else if ((Now - Start > 0) && (Now - Start < fade_time)) {
-      Brightness = (int) (Now - Start) / fade_time;
-    }
-    else {
-      Brightness = 255;
-    }
+//    if ((Now - Start) > fade_time) {
+//      Brightness = 255;
+//    }
+//    else if ((Now - Start > 0) && (Now - Start < fade_time)) {
+//      Brightness = (int) (Now - Start) / fade_time;
+//    }
+//    else {
+//      Brightness = 255;
+//    }

     static uint8_t startIndex = 0;
     startIndex = startIndex + 1; /* motion speed */
@@ -149,24 +149,24 @@
     FastLED.delay(1000 / UPDATES_PER_SECOND);
   }
   else if (Reading_Lights) {
-    if ((Now - Reading_Start > Reading_duration) && (Reading_Fade_Start == 0)) {
-      Reading_Fade_Start = Now;
-      Serial.print("Start fade");
-    }
-    else if (Now - Reading_Start < Reading_duration) {
-      Serial.print(Now - Reading_Start);
-      Reading_Fade_Start = 0;
-    }
-    if (Reading_Fade_Start > 0) {
-      Serial.print(Now - Reading_Fade_Start);
-      Brightness = (int) ((1-((Now - Reading_Fade_Start) / fade_time)) * 255);
-    }
-    if (Now - Reading_Fade_Start >= fade_time) {
-      Serial.println("Lights off");
-      Reading_Lights = false;
-    }
-    Serial.print("Reading");
-    Serial.println(Brightness);
+//    if ((Now - Reading_Start > Reading_duration) && (Reading_Fade_Start == 0)) {
+//      Reading_Fade_Start = Now;
+//      Serial.print("Start fade");
+//    }
+//    else if (Now - Reading_Start < Reading_duration) {
+//      Serial.print(Now - Reading_Start);
+//      Reading_Fade_Start = 0;
+//    }
+//    if (Reading_Fade_Start > 0) {
+//      Serial.print(Now - Reading_Fade_Start);
+//      Brightness = (int) ((1-((Now - Reading_Fade_Start) / fade_time)) * 255);
+//    }
+//    if (Now - Reading_Fade_Start >= fade_time) {
+//      Serial.println("Lights off");
+//      Reading_Lights = false;
+//    }
+//    Serial.print("Reading");
+//    Serial.println(Brightness);
     static uint8_t startIndex = 0;
     startIndex = startIndex + 1; /* motion speed */
     currentPalette = LavaColors_p;


Kleine fixes workshop sketch

Kleine fixes workshop sketch

--- software/arduino/iota-workshop/iota-workshop.ino
+++ software/arduino/iota-workshop/iota-workshop.ino
@@ -52,39 +52,48 @@
 }

 void longPress() {
-  getTemperature();
-  getLuminance();
+  readSensors();
 }

 /*
    Temperatuursensor
 */
-void getTemperature() {
+float getTemperature() {
   // Sensor activeren
   temp_sensor.shutdown(false);
   delay(100);

   float temperature = temp_sensor.temp();
-  Serial.print("Temperatuur: ");
-  Serial.print(temperature);
-  Serial.println("°C");

   // Sensor deactiveren
   temp_sensor.shutdown(true);
+
+  return temperature;
 }

 /*
    Lichtsensor
 */
-void getLuminance() {
+float getLuminance() {
   // Meet voltage op analoge input en reken dit om in het equivalente aantal lux
   float volts = analogRead(A0) * 3.3 / 1024.0;
   float amps = volts / 10000.0;  // 10k weerstand
   float microamps = amps * 1000000;
   float lux = microamps * 2.0;

+  return lux;
+}
+
+/*
+   Lees sensoren uit
+*/
+void readSensors() {
+  Serial.print("Temperatuur: ");
+  Serial.print(getTemperature());
+  Serial.println("°C");
+
   Serial.print("Hoevelheid licht: ");
-  Serial.print(lux);
+  Serial.print(getLuminance());
   Serial.println(" lux");
 }

@@ -133,7 +142,7 @@
   setLed(false); // led uit

   // Initialiseer RGB leds
-  FastLED.addLeds<RGB_LED_TYPE, RGB_LED_DATA_PIN, RGB_LED_CLOCK_PIN, RGB_COLOR_ORDER>(leds, RGB_NUM_LEDS); //.setCorrection(TypicalLEDStrip);
+  FastLED.addLeds<RGB_LED_TYPE, RGB_LED_DATA_PIN, RGB_LED_CLOCK_PIN, RGB_COLOR_ORDER>(leds, RGB_NUM_LEDS).setCorrection(TypicalLEDStrip);
   FastLED.setBrightness(RGB_LED_BRIGHTNESS);
   setRgbLeds(CRGB::Black); // beide leds uit

@@ -153,11 +162,10 @@
   Serial.println(WiFi.localIP());

   // Lees beide sensoren uit
-  getTemperature();
-  getLuminance();
+  readSensors();
 }

-/**
+/*
    Functie wordt continue aangroepen, voeg hier je eigen logica aan toe
 */
 void loop() {


Replace modulo operator from collectBits() with faster bitwise operation

--- Arduino/noise_multiplier/noise_multiplier.ino
+++ Arduino/noise_multiplier/noise_multiplier.ino
@@ -71,11 +71,12 @@
   }
 }

-
+//@return true if byte is full/complete
 boolean collectBit(byte inputBit, byte *currentByte){
   static int bitCounter = 0;
   *currentByte |= inputBit << bitCounter;
-   bitCounter = ++bitCounter % 8;
+  //modulo is very slow, so we do a bitwise operation. Equivelant to % 8
+   bitCounter = (++bitCounter) & 0b00000111;

   if (bitCounter == 0) {
     return true;


[Arduino] Reinit in loop() in case it failed.

Signed-off-by: Juri Berlanda <738ab29df2b6849f3ca85cffd121042aabdbdda0@hotmail.com>

--- Arduino/vj-flight-controller/vj-flight-controller.ino
+++ Arduino/vj-flight-controller/vj-flight-controller.ino
@@ -228,7 +228,12 @@
 // ================================================================
 void loop() {
   // if programming failed, don't try to do anything
-  if (!dmpReady) return;
+  if (!dmpReady) {
+    wdt_disable();
+    delay(1000);
+    setup();
+    return;
+  }

   readData();

@@ -239,4 +244,4 @@
   sendData();

   wdt_reset();
-}
+}


Adding band C/Immersion race band. Adding best channel to band scan. Adjusting UI to support 40 channels.


updating disc start timings and serial feedback

--- Exhibit_MomentumTable.ino
+++ Exhibit_MomentumTable.ino
@@ -15,7 +15,7 @@
 #define DESIREDRPM_TABLE    60      //desired RPM on output wheel
 //#define DESIREDRPM_MOTOR    600     //desired motor RPM (this may be superfulous)
 #define DISCSLIPCOUNT       250     //How long alarm cond before alarm signal
-#define LOCKEDDISCRPM       20     //RPM to consider as "disc stopped"
+#define LOCKEDDISCRPM       30     //RPM to consider as "disc stopped"
 #define ROTATIONVARIANCE    2      //Variance in RPM before alarm condition
 //#define TRANSMISSIONRATIO   10      //Tranmission drive ratio n:1
 #define NUMBEROFRESTARTS    3     //#of restarts attempted after stopped state
@@ -61,6 +61,7 @@
 client.setServer(mqtt_server, 1883);
 client.setCallback(callback);
 Serial.begin(115200);
+Serial.println("");
 /////////////////////////////
 delay(5000);
 motionControlStart(); // remove when MQTT is active. testing only
@@ -115,6 +116,7 @@
         delay(3000); // wait for 3 second for a rotation
         if (pulseCount == 0){               // if no rotation detected in interrupt
             digitalWrite(STARTRELAYPIN, LOW); // turn off motor becuase of no rotation
+			Serial.println("No rotation detected -- attempting restart");
             restartCount++;
             delay (10000); // delay 10 seconds before attempting restart
             pulseCount = 0; // reset pulse count
@@ -122,10 +124,10 @@
             }
         if (pulseCount > 1){
         Serial.println("motion started, system running");
+		delay(3000); 	// wait 3 seconds for disc to come up to fast enough speed
+						// to not trip locked rotor function
         restartCount = 0; // set restart counter to 0, since we're started
         allStopVar = 0; // Set allstop condition to off
-		Serial.print("AllStopVar ");
-		Serial.println(allStopVar);
         }
     }
     if (restartCount >= NUMBEROFRESTARTS) {


line removed in comments, line 23

line removed in comments, line 23

This was just a test.

--- VernierThermistorDisplay/VernierThermistorDisplay.ino
+++ VernierThermistorDisplay/VernierThermistorDisplay.ino
@@ -20,7 +20,6 @@
 The print function is used with the SoftwareSerial library
 to send display data to the S7S.
 Here is the wiring for display with a UART serial connection:
-
    Arduino -------------- Serial 7-Segment
      5V   --------------------  VCC
      GND  --------------------  GND


Multiply by 180 based on test

Multiply by 180 based on test

--- Arduino/IMU_9DOF/IMU_9DOF.ino
+++ Arduino/IMU_9DOF/IMU_9DOF.ino
@@ -288,7 +288,7 @@
         Now = micros();
         deltat = ((Now - lastUpdate)/1000000.0f); // set integration time by time elapsed since last filter update
         lastUpdate = Now;
-        MadgwickQuaternionUpdate(ax, ay, az, gx*PI/180*250.0f/32768.0*100, gy*PI/180.0*250.0f/32768.0*100, gz*PI/180.0*250.0f/32768.0*100,  mx,  my,  mz);
+        MadgwickQuaternionUpdate(ax, ay, az, gx*PI/180*250.0f/32768.0*180, gy*PI/180.0*250.0f/32768.0*180, gz*PI/180.0*250.0f/32768.0*180,  mx,  my,  mz);

     }


changing baud rate, higher one seems to be noisy

--- LED_DRIVER/LED_DRIVER.ino
+++ LED_DRIVER/LED_DRIVER.ino
@@ -18,7 +18,7 @@
 const unsigned short LED_INTERVAL = 1000; //how often we should toggle the LED state (simply: how often we should blink the lights)

 void setup() {
-  serialInput.begin(38400); //higher BAUD RATE seems to crash it
+  serialInput.begin(9600); //higher BAUD RATE seems to crash it
   pinMode(STOP, OUTPUT);
   pinMode(RIGHT, OUTPUT);
   pinMode(LEFT, OUTPUT);


Delete Otto_avoid.ino

Delete Otto_avoid.ino


Changed pin connections to suit programming shield and serial comms.

--- Programmer/Programmer.ino
+++ Programmer/Programmer.ino
@@ -46,10 +46,10 @@
  * D04:
  *~D05:
  *~D06:
- * D07: nRF24LE1 PROG
- * D08: nRF24LE1 _RESET_
- *~D09: nRF24LE1 FCSN
- *~D10:
+ * D07:
+ * D08: nRF24LE1 PROG
+ *~D09: nRF24LE1 _RESET_
+ *~D10: nRF24LE1 FCSN
  *~D11: SPI MOSI, nRF24LE1 FMOSI
  * D12: SPI MISO, nRF24LE1 FMISO
  * D13: SPI SCK, On board Status LED, nRF24LE1 FSCK
@@ -69,15 +69,19 @@
  Interupts:
  0:
  1:
+

  */
 #include <SPI.h>

 // Specify pins in use
-#define PROG      7   // nRF24LE1 Program
-#define _RESET_   8   // nRF24LE1 Reset
-#define _FCSN_    9   // nRF24LE1 Chip select
+#define PROG      8   // nRF24LE1 Program
+#define _RESET_   9   // nRF24LE1 Reset
+#define _FCSN_    10  // nRF24LE1 Chip select
+
+#define TXD       10  // nRF24LE1 UART/TXD
+#define RXD       7   // nRF24LE1 UART/RXD

 // SPI Flash operations commands
 #define WREN 		0x06  // Set flase write enable latch
@@ -401,7 +405,7 @@
         Serial.print(" ");
         Serial.println(hexRecord.rec_data[index]);
         digitalWrite(_FCSN_, HIGH);
-        //goto done;
+        goto done;
       }
     }
     digitalWrite(_FCSN_, HIGH);


--- _72-homekit-accessories-Aircon/_72-homekit-accessories-Aircon.ino
+++ _72-homekit-accessories-Aircon/_72-homekit-accessories-Aircon.ino
@@ -28,9 +28,9 @@

 #include "/usr/local/src/aptls_setting.h"

-const char* subscribe_cmd   = "esp8266/cmd/ac";
-const char* subscribe_set   = "esp8266/cmd/acset";
-const char* reporting_topic = "report/pirtest";
+const char* subscribe_cmd           = "esp8266/cmd/ac";
+const char* subscribe_set           = "esp8266/cmd/acset";
+const char* reporting_topic         = "report/pirtest";
 const char* homekit_reporting_topic = "homekit/bedroom/aircon/get";
 const char* homekit_subscribe_topic = "homekit/bedroom/aircon/set";
 const char* hellotopic              = "HELLO";
@@ -120,6 +120,7 @@
   JsonObject& root = jsonBuffer.createObject();
   root["ac_mode"]           = ir_data.ac_mode;
   root["ac_temp"]           = ir_data.ac_temp;
+  root["ac_flow"]           = ir_data.ac_flow;
   root["cur_temp"]          = temperature * 0.01;
   root["cur_humi"]          = humidity;
   root["presence"]          = uint8_t(bpresence);
@@ -149,7 +150,7 @@

 void ICACHE_RAM_ATTR parseMqttMsg(String receivedpayload, String receivedtopic)
 {
-  char json[] = "{\"ac_mode\":0,\"ac_temp\":27}";
+  char json[] = "{\"ac_mode\":0,\"ac_temp\":27,\"ac_flow\":2}";

   receivedpayload.toCharArray(json, 150);
   StaticJsonBuffer<150> jsonBuffer;
@@ -167,11 +168,13 @@
       if (ir_data.ac_temp != root["ac_temp"])
       {
         ir_data.ac_temp = root["ac_temp"];
+
         if (ir_data.ac_mode == 1)
         {
           ir_data.haveData = true;
         }
       }
+      ir_data.ac_flow = root["ac_flow"];
     }

     if (root.containsKey("ac_mode"))
@@ -463,7 +466,7 @@
     bpir_isr = false;
   }

-  if ((millis() - lastpirMillis < MAX_PIR_TIME) && ( lastpirMillis != 0))
+  if (((millis() - lastpirMillis) < MAX_PIR_TIME) && ( lastpirMillis != 0))
   {
     bpresence = true;
   }
@@ -472,7 +475,7 @@
     bpresence = false;
   }

-  if (!bpresence && ir_data.ac_presence_mode == 1)
+  if (!bpresence && (ir_data.ac_presence_mode == 1))
   {
     Serial.println("[IR] -----> AC Power Down");
     lgWhisen.power_down();


implemented analog-output

implemented analog-output

--- ksp-gegi/ksp-gegi.ino
+++ ksp-gegi/ksp-gegi.ino
@@ -15,7 +15,7 @@
 const uint8_t nPins = 7; // długość tabel poniżej
 const uint8_t switchPins[] = {4,  5, 8, 12, 0, 0,  0};	// Dx: stage, RCS, SAS, gear switch, overheat, lowpower, lowfuel
 const uint8_t onPins[] =     {0, 13, 9,  0, 0, 0,  0};	// Gx: stage, RCS, SAS, overheat, lowpower, lowfuel ON (green)
-const uint8_t offPins[] =    {0,  0, 0,  0, 6, 7, 10};	// Rx: stage, RCS, SAS, overheat, lowpower, lowfuel OFF (red)
+const uint8_t offPins[] =    {0,  0, 0,  0, 6, 7,  3};	// Rx: stage, RCS, SAS, overheat, lowpower, lowfuel OFF (red)
 uint8_t lastPinState[] = {HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH};
 uint8_t lastLedState[] =  {0, 0, 0, 0, 0, 0, 0};	// bits: 0=GxON, 1=RxON, 2=GxBLINK, 3=RxBLINK

@@ -23,12 +23,16 @@
 unsigned long lastBlink = 0;
 const unsigned long blinkInterval = 500;

-// analog control
+// analog control input
 const uint8_t nAPins = 2;
 const uint8_t aPins[] = {A0, A1};	// pot: throttle, timewarp
-const int lastAValue[] = {0, 0};
-const int aValue[] = {0, 0};
+int lastAValue[] = {0, 0};
+int aValue[] = {0, 0};
 const int aThreshold[] = {2, 2};
+
+// analog control output
+const uint8_t nAOutPins = 1;
+const uint8_t aOutPins[] = {10};	// vmeter: g-force

 // serial port
 #define SERIAL_SPEED 9600
@@ -105,17 +109,16 @@
 	}
 }

-void checkSerialInput() {
-  uint8_t c;
-  uint8_t val=0,id=0,nval=0;
-  // format: "^LG1=0$" turn off green led 1 (RCS), "^LR2=1$" turn off red led 2 (SCS)
-  if (Serial.available()>0) {
-  if (Serial.find("L")) {
+// commands like: ^L{GR}{id}={val}$
+// format: "^LG1=0$" turn off green led 1 (RCS), "^LR2=1$" turn off red led 2 (SCS)
+void handleSerialInputLed() {
+    uint8_t c;
+    uint8_t val=0,id=0,nval=0;
     c = Serial.read();
     id = Serial.parseInt();  // skip '='
     val = Serial.parseInt(); // skip newline
 //    Serial.print(c); Serial.print(id); Serial.println(val);  // echo for ack
-	if (id>0 && id<=nPins) {
+	if (id>=0 && id<=nPins) {
                 nval = lastLedState[id];
                 if (c=='G') {
                   nval = nval & 0b11111010;
@@ -129,7 +132,29 @@
                 }
 		lastLedState[id] = nval;
 	}
-  }
+}
+
+// commands like ^A{id}={val}$
+void handleSerialInputAnalogOut() {
+    uint8_t val=0,id=0;
+    id = Serial.parseInt();  // skip '='
+    val = Serial.parseInt(); // skip newline
+//    Serial.print(id); Serial.println(val);  // echo for ack
+	if (id>=0 && id<=nAOutPins) {
+		analogWrite(aOutPins[id], val);
+	}
+}
+
+void checkSerialInput() {
+  uint8_t c;
+  if (Serial.available()>0) {
+    c = Serial.read();
+	if (c == 'L') {
+	  handleSerialInputLed();
+	}
+	if (c == 'A') {
+	  handleSerialInputAnalogOut();
+	}
   }
 }

@@ -174,4 +199,3 @@
   updateLeds();
   delay(200);
 }
-


fixed compile error

fixed compile error

--- firmware/beer/beersensor.ino
+++ firmware/beer/beersensor.ino
@@ -48,6 +48,7 @@
 int currentSecond = 1;
 int previousSecond = 0;
 int animationStep = 0;
+String *strArr = new String[20];

 const char* pin0Name = "pin0Value";
 const char* pin1Name = "pin1Value";


cleaned up firmware, made it emit only 2 events, start and stop flow with total usage on the stop event

--- firmware/beer/beersensor.ino
+++ firmware/beer/beersensor.ino
@@ -3,18 +3,26 @@
 #include "neopixel.h"

 //photon has 2048 bytes of emulated EEPROM
-#define EEPROM_ADDR_T0 0 //400 bytes per tap
-#define EEPROM_ADDR_T1 400
-#define EEPROM_ADDR_T2 800
+#define EEPROM_ADDR_T0 0 //600 bytes per tap
+#define EEPROM_ADDR_T1 600
+#define EEPROM_ADDR_T2 1200

 #define PIXEL_TYPE WS2812B
 #define PIXEL_COUNT 14
+
+#define FLOW_PIN_T0 D6
+#define FLOW_PIN_T1 D5
+#define FLOW_PIN_T2 D4
+#define LED_PIN_T0 D3
+#define LED_PIN_T1 D2
+#define LED_PIN_T2 D1

 struct TapObject
 {
   int pulseCount;
   int maxPulseCount;
   int instantPulseCount;
+  int flowStartPulseCount;
   int previousPulseCount;
   int flowing;
   int previousFlowing;
@@ -27,15 +35,15 @@
 };

 //initialize taps
-TapObject T0 = {1000, 1000, 0, 0, 0, 0, 100, 1, 0, 0, D6, D3};
-TapObject T1 = {1000, 1000, 0, 0, 0, 0, 100, 1, 0, 0, D5, D2};
-TapObject T2 = {1000, 1000, 0, 0, 0, 0, 100, 1, 0, 0, D4, D1};
+TapObject T0 = {1000, 1000, 0, 0, 0, 0, 0, 100, 1, 0, 0, FLOW_PIN_T0, LED_PIN_T0};
+TapObject T1 = {1000, 1000, 0, 0, 0, 0, 0, 100, 1, 0, 0, FLOW_PIN_T1, LED_PIN_T1};
+TapObject T2 = {1000, 1000, 0, 0, 0, 0, 0, 100, 1, 0, 0, FLOW_PIN_T2, LED_PIN_T2};

 int ledPin = D7;

-Adafruit_NeoPixel stripT0 = Adafruit_NeoPixel(PIXEL_COUNT, T0.ledPin, PIXEL_TYPE);
-Adafruit_NeoPixel stripT1 = Adafruit_NeoPixel(PIXEL_COUNT, T1.ledPin, PIXEL_TYPE);
-Adafruit_NeoPixel stripT2 = Adafruit_NeoPixel(PIXEL_COUNT, T2.ledPin, PIXEL_TYPE);
+Adafruit_NeoPixel stripT0 = Adafruit_NeoPixel(PIXEL_COUNT, LED_PIN_T0, PIXEL_TYPE);
+Adafruit_NeoPixel stripT1 = Adafruit_NeoPixel(PIXEL_COUNT, LED_PIN_T1, PIXEL_TYPE);
+Adafruit_NeoPixel stripT2 = Adafruit_NeoPixel(PIXEL_COUNT, LED_PIN_T2, PIXEL_TYPE);

 int flowTapPin0Value = 0;
 int flowTapPin1Value = 0;
@@ -120,9 +128,17 @@
   }
   else if(command.equals("setCalibration"))
   {
+    //set the calibration value (maxPulseCount)
     //args[1] == tap you want to set (0-3)
     //args[2] == calibration value (total number of pulses in a keg)
     setCalibration(args[1].toInt(), args[2].toInt());
+  }
+  else if(command.equals("setPulseCount"))
+  {
+    //set the pulseCount for a tap manually
+    //args[1] == tap you want to set (0-3)
+    //args[2] == calibration value (total number of pulses in a keg)
+    setPulseCount(args[1].toInt(), args[2].toInt());
   }

   return 1;
@@ -209,6 +225,7 @@
   {
     if(T0.flowing)
     {
+      T0.flowStartPulseCount = T0.pulseCount;
       //publish a start event
       Particle.publish("start-flow-T0", String(T0.maxPulseCount) +
                        "," + String(T0.pulseCount) + "," + String(T0.percentFull));
@@ -216,8 +233,11 @@
     else
     {
       //publish a stop event
-      Particle.publish("stop-flow-T0", String(T0.maxPulseCount) +
-                       "," + String(T0.pulseCount) + "," + String(T0.percentFull));
+      String data = String(T0.maxPulseCount) +
+                       "," + String(T0.pulseCount) + "," + String(T0.percentFull) +
+                       "," + String(T0.flowStartPulseCount - T0.pulseCount);
+      Serial.println("stop-flow-T0 Data: " + data);
+      Particle.publish("stop-flow-T0", data);
     }
   }

@@ -225,6 +245,7 @@
   {
     if(T1.flowing)
     {
+      T1.flowStartPulseCount = T1.pulseCount;
       //publish a start event
       Particle.publish("start-flow-T1", String(T1.maxPulseCount) +
                        "," + String(T1.pulseCount) + "," + String(T1.percentFull));
@@ -232,8 +253,11 @@
     else
     {
       //publish a stop event
-      Particle.publish("stop-flow-T1", String(T1.maxPulseCount) +
-                       "," + String(T1.pulseCount) + "," + String(T1.percentFull));
+      String data = String(T1.maxPulseCount) +
+                       "," + String(T1.pulseCount) + "," + String(T1.percentFull) +
+                       "," + String(T1.flowStartPulseCount - T1.pulseCount);
+      Serial.println("stop-flow-T1 Data: " + data);
+      Particle.publish("stop-flow-T1", data);
     }
   }

@@ -241,15 +265,18 @@
   {
     if(T2.flowing)
     {
+      T2.flowStartPulseCount = T2.pulseCount;
       //publish a start event
       Particle.publish("start-flow-T2", String(T2.maxPulseCount) +
                        "," + String(T2.pulseCount) + "," + String(T2.percentFull));
     }
     else
     {
-      //publish a stop event
-      Particle.publish("stop-flow-T2", String(T2.maxPulseCount) +
-                       "," + String(T2.pulseCount) + "," + String(T2.percentFull));
+      String data = String(T2.maxPulseCount) +
+                       "," + String(T2.pulseCount) + "," + String(T2.percentFull) +
+                       "," + String(T2.flowStartPulseCount - T2.pulseCount);
+      Serial.println("stop-flow-T2 Data: " + data);
+      Particle.publish("stop-flow-T2", data);
     }
   }
 }
@@ -272,28 +299,46 @@
   return 1;
 }

-int setCalibration(int tap, int val)
+int setPulseCount(int tap, int val)
 {
   if(tap == 0)
   {
-    T0.maxPulseCount = val;
+    T0.pulseCount = val;
   }
   else if(tap == 1)
   {
-    T1.maxPulseCount = val;
+    T1.pulseCount = val;
   }
   else if(tap == 2)
   {
-    T2.maxPulseCount = val;
+    T2.pulseCount = val;
   }
   writeToEEPROM();
   return 1;
 }

+int setCalibration(int tap, int val)
+{
+  if(tap == 0)
+  {
+    T0.maxPulseCount = val;
+  }
+  else if(tap == 1)
+  {
+    T1.maxPulseCount = val;
+  }
+  else if(tap == 2)
+  {
+    T2.maxPulseCount = val;
+  }
+  writeToEEPROM();
+  return 1;
+}
+
 void pinValT0()
 {
   T0.previousFlowing = T0.flowing;
-  if(digitalRead(T0.flowPin) == HIGH)
+  if(digitalRead(FLOW_PIN_T0) == HIGH)
   {
     if(flowTapPin0Value == 0)
     {
@@ -334,7 +379,7 @@
 void pinValT1()
 {
   T1.previousFlowing = T1.flowing;
-  if(digitalRead(T1.flowPin) == HIGH)
+  if(digitalRead(FLOW_PIN_T1) == HIGH)
   {
     if(flowTapPin1Value == 0)
     {
@@ -375,7 +420,7 @@
 void pinValT2()
 {
   T2.previousFlowing = T2.flowing;
-  if(digitalRead(T2.flowPin) == HIGH)
+  if(digitalRead(FLOW_PIN_T2) == HIGH)
   {
     if(flowTapPin2Value == 0)
     {
@@ -399,6 +444,7 @@
   T2.currentSecond = Time.second();
   if(T2.currentSecond != T2.previousSecond)
   {
+
       T2.instantPulseCount = 0;
       if(T2.previousPulseCount != T2.pulseCount)
       {


BabelFish: Make space for bigger Tiny BASIC

--- Utils/BabelFish/BabelFish.ino
+++ Utils/BabelFish/BabelFish.ino
@@ -263,9 +263,15 @@

 struct { byte *gt1; char *name; } gt1Files[12] = {
 /* 1  */ TinyBASIC_gt1, "Tiny BASIC",
+#if maxStorage >= 32768
 /* 2  */ WozMon_gt1,    "WozMon",
 /* 3  */ Terminal_gt1,  "Terminal",
 /* 4  */ Blinky_gt1,    "Blinky",
+#else
+         0,              "(Empty)",
+         0,              "(Empty)",
+         0,              "(Empty)",
+#endif
 /* 5  */ bricks_gt1,    "Bricks game [xbx]",
 #if maxStorage >= 32768
 /* 6  */ lines_gt1,     "Lines demo [at67]",


Update K_Nearest_Neighbors_Cups.ino

Update K_Nearest_Neighbors_Cups.ino

Changed "Box Detected" to "Cup Detected".

--- K_Nearest_Neighbors_Cups/K_Nearest_Neighbors_Cups.ino
+++ K_Nearest_Neighbors_Cups/K_Nearest_Neighbors_Cups.ino
@@ -297,7 +297,7 @@

   // Sensor was tripped and wasn't right before.
   if(IR_Sensor1 == LOW && !wait) {
-    Serial.println("Box Detected");
+    Serial.println("Cup Detected");

     delay(2000);


bug fix

bug fix

--- arduino/motor_driver/motor_driver.ino
+++ arduino/motor_driver/motor_driver.ino
@@ -524,7 +524,7 @@

 void oscGo(OscMessage &m) {
   // /go/motor0pos,motor1pos,motor2pos,motor3pos long ints
-  if (state != OK || m.size() != 4) return;
+  if (state != OK || m.size() <= 4) return;

   double value = m.getFloat(MOTOR_ID);
   pidSetpoint = value;


After a harrowing afternoon, Towers now control IR floodlights

--- src/Tower/Tower.ino
+++ src/Tower/Tower.ino
@@ -139,6 +139,9 @@
   // put your setup code here, to run once:
   Serial.begin(115200);

+  Serial << F("Pausing after boot 1 sec...") << endl;
+  myDelay(1000UL);
+
   // random seed.
   randomSeed(analogRead(A3)); // or some other unconected pin

@@ -175,6 +178,9 @@

   // start the IR control of the floodlight
   flood.begin();
+
+  Serial << F("Free RAM: ") << freeRam() << endl;
+
 }

 void loop() {
@@ -280,6 +286,7 @@

   if ( networkTimeout.check() ) {
     Serial << F("Network timeout.") << endl;
+    Serial << F("Free RAM: ") << freeRam() << endl;
     networkTimedOut = true;
   }
   if( systemResetFlag ) {
@@ -303,7 +310,9 @@
 boolean systemReseted() {
   // with EMI, be very sure.
   Metro readTime(DEBOUNCE_TIME);
+  readTime.interval(DEBOUNCE_TIME);
   readTime.reset();
+
   while( !readTime.check() ) systemReset.update();

   // at system power up, relay is open, meaning pin will read HIGH.
@@ -330,7 +339,7 @@
   if( inPeriod == 0 ) {
     period = random(TEST_PATTERN_PERIOD / 2, TEST_PATTERN_PERIOD * 2);
     direction *= -1;
-    delay(1); // only want to trip this test once per period
+    myDelay(1); // only want to trip this test once per period
     Serial << F("Test pattern period: ") << period << F(" direction: ") << direction << endl;
   }

@@ -617,12 +626,13 @@
 }

 void Flood::on() {
-  send(K24_ON);
+  sendMultiple(K24_ON,2);
   this->isOn = true;
 }
 void Flood::off() {
-  send(K24_OFF);
-  this->isOn = false;
+//  send(K24_OFF);
+  send(K24_SMOOTH);
+//  this->isOn = false;
 }

 void Flood::setColor(byte color) {
@@ -666,10 +676,15 @@
 void Flood::sendMultiple(unsigned long data, byte repeats) {
   send(data);
   for( byte i=1; i < repeats; i++ ) {
-    delay(8); // need a 8ms interval before resend
+    myDelay(8); // need a 8ms interval before resend
     send(data);
 //    send(K24_REPEAT);
   }
 }

-
+int freeRam () {
+  extern int __heap_start, *__brkval;
+  int v;
+  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
+}
+


All functionality complete

All functionality complete

--- Arduino_Code/Arduino_Code.ino
+++ Arduino_Code/Arduino_Code.ino
@@ -2,10 +2,9 @@
 Created by Geoff Spielman on 2016-06-25.
 Copyright (c) 2016 Geoff Spielman. All rights reserved.
 */
-
-#include <HashMap.h>
 #include <QueueList.h>

+//Hardware
 const int btn0 = 2;
 const int btn1 = 3;
 const int btn2 = 4;
@@ -15,6 +14,11 @@
 const int led2 = 10;
 const int led3 = 11;

+const int morLed = 12;
+const int morBtn = 7;
+const int morBuz = 6;
+
+
 int btn[] = {btn0, btn1, btn2, btn3};
 int led[] = {led0, led1, led2, led3};

@@ -37,32 +41,41 @@
 String sendMorse = "";

 //The queue for the morse code
-QueueList<char> morQue;
-
-//To control how morse code is output
-const int dotLength = 500;
-const int dashLength = 3*dotLength;
-
-//hash morse code 'characters' to their appropriate responces.
-const byte HASH_SIZE = 5;
-HashType<char*,int> hashRawArray[HASH_SIZE];
-HashMap<char*,int> morseMap = HashMap<char*,int>(hashRawArray , HASH_SIZE );
+QueueList<int> morQue;
+
+/*According to Wikiepedia:
+ * Length of dash is three times the length of a dot
+ * Space between dash or dot is equal to the length of a dot
+ * letters are seperated by a pause equal to the length of a dash (three dots)
+ * words are seperated by 7 dots
+ * For our application, we will say the space between messages is 12 dots
+ */
+//morse code parameters
 int morState = 0;
 unsigned long morLength = 0;
 unsigned long morStart = 0;
 boolean morseAvailable = false;
-const int dot = 700;
+const int dot = 300;
+const int buzzerLevel = 8; //18 is pretty good
+boolean morINlast = false;
+boolean morINstate = false;
+unsigned long morINlastChange = 0;
+unsigned long morTimePressed = 0;
+unsigned long morTimeReleased = 0;
+String morMessage = "";
+

 //Status trackers
 boolean displayingSequence = false;
 boolean repeatingSequence = false;
 boolean displayResultAnimation = false;
 boolean creatingSequence = false;
+boolean playerWasCorrect = true;
 boolean listeningToButtons = false;
-boolean playerWasCorrect = true;
+boolean gameOver;

 //customizable display, just set indexes appropriately in displayResultAnimation
-int animationArr[] = {0,1,2,3,0,1,2,3,0,1,2,3,0,-1,0,-1,0,-1,0};
+int animationArr[] = {0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3,0,-1,0,-1,0,-1,0};
 int animationIndex = -1;
 int endI;
 const int animationLEDonDuration = 100;
@@ -85,24 +98,6 @@
     pinMode(led[i], OUTPUT);
   }
   recString.reserve(400);
-
-
-/*Since you can't store anything other than integers in this HashMap:
- * Last digit is if it should be on (1) or off(0) (use mod 10 to determine)
- * All other digits are how many units to perform the action (truncate divide by 10 to determine)
- */
-morseMap[0](".", 11);
-morseMap[1]("/", 31);
-morseMap[2](" ", 30); //space between letters
-morseMap[3]("|", 70); //space between words
-morseMap[4]("?", 120);//space between messages (arbitrary, in case there are multiple)
-//morseMap.debug(); //print it
-/*According to Wikiepedia:
- * Length of dash is three times the length of a dot
- * Space between dash or dot is equal to the length of a dot
- * letters are seperated by a pause equal to the length of a dash (three dots)
- * words are seperated by 7 dots
- */
 }

@@ -123,11 +118,7 @@
         displayingSequence = false;
         repeatingSequence = true;
         listeningToButtons = true;
-        for (int i = 0; i < seqLength; i ++)
-        {
-          btnLog[i] = -1;
-        }
-        btnLogIndex = 0;
+        resetButtonLog();
         seqIndex = 0;
       }
       timeLEDlastChanged = millis();
@@ -160,12 +151,8 @@
         }
       }
       displayResultAnimation = true;
+      repeatingSequence = false;
       listeningToButtons = false;
-      repeatingSequence = false;
-      //clear button log
-      for (int i = 0; i < seqLength; i ++)
-          btnLog[i] = -1;
-      btnLogIndex = 0;
       LEDon = false;
       animationIndex = -1;
     }
@@ -180,11 +167,11 @@
       if (playerWasCorrect)
       {
         animationIndex = 0;
-        endI = 11;
+        endI = 15;
       }
       else {
-        animationIndex = 12;
-        endI = 18;
+        animationIndex = 16;
+        endI = 22;
       }
     }
     //if an LED has been on and it's time to turn it off
@@ -198,8 +185,14 @@
       if(animationIndex == (endI + 1))
       {
         displayResultAnimation = false;
-        creatingSequence = true;
-        listeningToButtons = true;
+        if (playerWasCorrect) {
+          creatingSequence = true;
+          listeningToButtons = true;
+          resetButtonLog();
+        }
+        else
+          gameOver = true;
+
       }
       timeLEDlastChanged = millis();
     }
@@ -223,16 +216,23 @@
         sendSequence += String(btnLog[i]);
       }
       Serial.println(sendSequence);
+      sendSequence = "";
       creatingSequence = false;
-    }
+      listeningToButtons = false;
+    }
+  }
+
+  if (gameOver)
+  {
+    Serial.println("Game Over");
+    gameOver = false;
   }

   //-----------------------------------------------------------------------------------------------
   //----------------------seperate from status blocks of code -------------------------------------
   //-----------------------------------------------------------------------------------------------
-  if (listeningToButtons)
-  {
+  if (listeningToButtons){
     for (int i = 0; i < 4; i ++)
     {
       int cur = digitalRead(btn[i]);
@@ -264,42 +264,77 @@
     prevButtonState[i] = cur;
     }
   }
+
+  //Morse Code button specifically (always listening)
+    boolean curINmor = digitalRead(morBtn);
+    if (curINmor != morINlast)
+      morINlastChange = millis();
+    if (((millis() - morINlastChange) > debounceTime) && (curINmor != morINstate))
+    {
+      morINstate = curINmor;
+      if (curINmor)
+      {
+        morTimePressed = millis();
+        int diff = morTimePressed - morTimeReleased;
+        if (diff >= (2 * dot) && diff < (5 * dot)) //between letters is 3 dots
+            morMessage += " ";
+        else if (diff >= (5 * dot) && diff < (10 * dot)) //between words is 7 dots
+            morMessage += "|";
+      }
+      else {
+        morTimeReleased = millis();
+        int diff = morTimeReleased - morTimePressed;
+        if (diff < (1.75 * dot)) //single dot
+            morMessage += ".";
+        else if (diff >= (1.75 * dot)) //dash
+            morMessage += "-";
+      }
+    }
+    morINlast = curINmor;
+
+
+  //always see if enough time has passed to send a message
+  if (morMessage != "" && (millis() - morTimeReleased > (dot * 11)) && !curINmor) //using 11 as an offest
+  {
+    Serial.println(morMessage);
+    morMessage = "";
+  }
+
+

-  //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2
   //if we're not in bypass mode and a change needs to be made
   if (morseAvailable && (millis() - morStart > morLength))
-  {
-    //converts next char to a char pointer (Extra character for null terminator
-    char next[2];
-    String(morQue.peek()).toCharArray(next, 2);
-    Serial.println(morseMap.getValueOf(next));
-    Serial.println(morQue.peek());
+  {
     //if the state is currently on
     if (morState)
     {
+       morState = 0;
+       digitalWrite(morLed, LOW);
+       analogWrite(morBuz, 0);
+
+
       //if the next character is another dit or dah, you must wait one dot duration worth
-      //if (morseMap.getValueOf(next) % 10 == 1)
-     // {
-
-     // }
-
+      if (morQue.peek() % 10)
+        morLength = dot;
+      //otherwise next is a pause of some sort
+      else
+      {
+        morLength = (morQue.pop() / 10) * dot;
+       //we have run out of morse code
+        if(morQue.isEmpty())
+         morseAvailable = false;
+      }
     }
     //just finished a pause, so no matter what we need the next character
     else{
-
-    }
-    //we have run out of characters
-    //if(!morQue.isEmpty())
-    //{
-      //morQue.pop(
-   //   Serial.println("Empty");
-   // }
-  }
-
-
+      morState = 1;
+      digitalWrite(morLed, HIGH);
+      analogWrite(morBuz, buzzerLevel);
+      morLength = (morQue.pop() / 10) * dot;
+    }
+   morStart = millis();
+  }
 }//end loop
-
-

 //expect morse code to start with . or - and sequences are in the form 12031021, BOTH END WITH ~
@@ -316,16 +351,31 @@
       //start index = inclusive, end index = exlusive (this removes tilde)
       recString = recString.substring(0, endIndex);

-
-      //PROCESS MORSE CODE (space between letters, pipe between words)
+      //PROCESS MORSE CODE (space between letters, pipe between words,? after message)
       if (recString.charAt(0) == '.' || recString.charAt(0) == '-')
       {
         //Add to Queue
+        //Last digit is if it should be on (1) or off(0)
+        //All other digits are how many units to perform the action
         for (int i = 0; i < recString.length(); i++)
         {
-          morQue.push(recString.charAt(i));
+          switch(recString.charAt(i)){
+            case '.':
+              morQue.push(11);
+              break;
+            case '-':
+              morQue.push(31);
+              break;
+            case ' ':
+              morQue.push(30); //space between letters
+              break;
+            case '|':
+              morQue.push(70); //space between words
+              break;
+          }
         }
-        morseAvailable = true;
+        morQue.push(120); //space between messages (arbitrary, in case there are multiple messages)
+        morseAvailable = true;
       }

       //PROCESS SEQUENCE
@@ -340,9 +390,7 @@
         seqLength = recString.length();
         displayingSequence = true;
         //erase as much of the button log as required to enter the correct sequence
-        for (int i = 0; i < seqLength; i ++)
-          btnLog[i] = -1;
-        btnLogIndex = 0;
+        resetButtonLog();
       }
       recString = "";
     }
@@ -350,310 +398,8 @@
 }

-
-
-
-
-/*
-  'all this does is read all the buttons and light them up when pressed
-  if (playerCreating || playerRepeating)
-  {
-    'if button is pressed, turn on LED
-    for (int i = 0; i < 4; i ++) {
-      if (digitalRead(btn[i]) == 1) {
-        digitalWrite(led[i], HIGH);
-      }
-      else {
-        digitalWrite(led[i], LOW);
-      }
-    }
-  }
-
-  if (arduinoTurn) {
-    /*
-     Serial.println("ITS MY TURN!!");
-     Serial.print("seqIndex: ");
-     Serial.println(seqIndex);
-     Serial.print("seqSize: ");
-     Serial.println(seqSize);
-     */
-     /*
-
-
-    //If sequence index is less than the length, we are still outputting the sequence
-    if((seqIndex < seqSize) && playerRepeating == false && playerCreating == false)
-    {
-      //If an LED was on and change must be made
-      if (LEDon && (millis() - timeOfLastChange >= 1000))
-      {
-        digitalWrite(led[seqArr[seqIndex]], LOW);
-        LEDon = false;
-        seqIndex += 1;
-        if (seqIndex == seqSize)
-        {
-          playerRepeating = true;
-          for (int i = 0; i < 4; i ++)
-            prevBtns[i] = false;
-          seqIndex = 0;
-        }
-        timeOfLastChange = millis();
-
-      }
-      //LED is off and change must be made
-      else if (!LEDon && (millis() - timeOfLastChange >= 500))
-      {
-          digitalWrite(led[seqArr[seqIndex]], HIGH);
-          LEDon = true;
-          timeOfLastChange = millis();
-      }
-
-    }
-    else if (playerRepeating && (seqIndex < seqSize))
-    {
-      //Check each button for change
-      for (int i = 0; i < 4; i ++)
-      {
-        'if the button wasn't pressed previously and is now
-        if (!prevBtns[i] && digitalRead(btn[i]))
-        {
-          prevBtns[i] = true;
-          delay(150);
-        }
-        else if(prevBtns[i] && !digitalRead(btn[i]))
-        {
-          prevBtns[i] = false;
-          repeatArr[seqIndex] = i;
-          seqIndex += 1;
-          //Check user for correctness once the entire sequence has been entered
-          if (seqIndex == seqSize)
-          {
-            boolean correct = true;
-            for(int i = 0; i < 4; i ++)
-            {
-              if(seqArr[i] != repeatArr[i])
-                correct = false;
-            }
-            if(correct)
-            {
-              //PLAYER CORRECT,prepare for create phase
-              //Simple display
-              for (int o = 0; o < 3; o ++)
-              {
-                for (int i = 0; i < 4; i ++)
-                {
-                  digitalWrite(led[i], HIGH);
-                  delay(150);
-                  digitalWrite(led[i], LOW);
-                }
-              }
-              playerRepeating = false;
-              playerCreating = true;
-              seqIndex = 0;
-              for (int i = 0; i < 4; i ++)
-                prevBtns[i] = false;
-            }
-            else {
-              for (int i = 0; i < 5; i ++)
-              {
-                digitalWrite(led[0], HIGH);
-                delay(180);
-                digitalWrite(led[0], LOW);
-                delay(120);
-              }
-
-              //REMOVE THIS FOR MESSAGES, JUST FOR TESTING SEQUENCES
-              playerRepeating = false;
-              playerCreating = true;
-              seqIndex = 0;
-              for (int i = 0; i < 4; i ++)
-                prevBtns[i] = false;
-            }
-
-          }
-         }
-      }
-    }
-
-
-    else if (playerCreating && (seqIndex < seqSize))
-    {
-      //Check each button for change
-      for (int i = 0; i < 4; i ++)
-      {
-        if (!prevBtns[i] && digitalRead(btn[i]))
-        {
-          prevBtns[i] = true;
-        }
-        else if(prevBtns[i] && (digitalRead(btn[i]) == false))
-        {
-          prevBtns[i] = false;
-          seqArr[seqIndex] = i;
-          seqIndex += 1;
-          if (seqIndex == seqSize)
-          {
-            //Convert int array to string
-            String oString;
-            for (int i = 0; i < seqSize; i++)
-            {
-              oString = String(oString + String(seqArr[i]));
-            }
-            Serial.println(oString);
-            for (int i = 0; i < 4; i ++)
-              digitalWrite(led[i], LOW);
-            playerCreating = false;
-            //TAKE THIS OUT LATER
-            arduinoTurn = false;
-          }
-        }
-      }
-
-    }
-
-
-
-
-
-
-    //arduinoTurn = false;
-  }
-  /*
-  Serial.println(" ");
-  Serial.print("Button0: ");
-  Serial.print(digitalRead(btn0));
-  Serial.print("   Button1: ");
-  Serial.print(digitalRead(btn1));
-  Serial.print("   Button2: ");
-  Serial.print(digitalRead(btn2));
-  Serial.print("   Button3: ");
-  Serial.print(digitalRead(btn3));
-  Serial.println(" ");
-  */
-
-
-/*
-void serialEvent()
-{
-  while (Serial.available())
-  {
-    char inChar = (char)Serial.read();
-    recString += inChar;
-    /*
-    Serial.print("inChar: ");
-    Serial.println(inChar);
-    */
-    /*
-    if (inChar == '|')
-    {
-      int endIndex = recString.indexOf("|");
-      if (endIndex == -1)
-      {
-        endIndex = recString.indexOf("/n");
-      }
-      //PROCESS MESSAGE
-      if (recString.charAt(0) == 'm') {
-        recMessage= recString.substring(2, endIndex);
-        Serial.print("Received Message:");
-        Serial.println(recMessage);
-
-      //PROCESS SEQUENCE
-      }
-      if (recString.charAt(0) == 's') {
-        seqSize = (recString.length()-1)/2;
-        /*
-        int* seq = new int[(recString.length()-1)/2];
-        Serial.println(sizeof(*seq));
-        for (int i = 2; i < recString.length(); i++)
-        {
-        }
-        */
-        /*
-        for (int i = 2; i <= (seqSize*2); i += 2)
-        {
-          seqArr[i/2 -1] = recString.charAt(i) - '0';
-        }
-        /*
-        Verify that you can actually create arrays of variable size
-        Serial.print("Created array size: ");
-        Serial.println(sizeof(seqArr) / sizeof(int));
-
-        //Test Sequence Array
-        for (int i = 0; i < digits; i ++)
-        {
-          Serial.println(seqArr[i]);
-        }
-        */
-        /*
-        seqIndex = 0;
-        LEDon = false;
-        for (int i = 0; i < 4; i ++)
-          prevBtns[i] = false;
-        arduinoTurn = true;
-      }
-
-
-      //Output sequence to user
-
-
-
-      recString = "";
-    }
-  }
+void resetButtonLog(){
+  for (int i = 0; i < seqLength; i ++)
+    btnLog[i] = -1;
+  btnLogIndex = 0;
 }
-
-/*
-const int led = 13;
-const int mtrL = 6;
-const int mtrR = 5;
-
-int mL = 0, mR = 0;
-
-String inputString = "";
-boolean needChange = false;
-
-void setup() {
-  Serial.begin(9600);
-  pinMode(led, OUTPUT);
-  inputString.reserve(200);
-  Serial.println("-----Start-----");
-}
-
-void loop() {
-
-  if (needChange)
-  {
-    //Serial.print("Arduino rec: ");
-    //Serial.println(inputString);
-    Serial.print("Left Motor: ");
-    Serial.print(mL);
-    Serial.print("   Right Motor: ");
-    Serial.println(mR);
-
-    analogWrite(mtrL, mL);
-    analogWrite(mtrR, mR);
-    inputString = "";
-    needChange = false;
-  }
-}
-
-void serialEvent()
-{
-  while (Serial.available())
-  {
-    char inChar = (char)Serial.read();
-    inputString += inChar;
-    if (inChar == '\n' || inChar == '!') //if 'end with newline' is not enabled on serial monitor, end with !
-    {
-      int commaIndex = inputString.indexOf(",");
-      int endIndex = inputString.indexOf("!");
-      if (endIndex == -1)
-      {
-        endIndex = inputString.indexOf("/n");
-      }
-      mL = inputString.substring(0, commaIndex).toInt();
-      mR = inputString.substring(commaIndex + 1, endIndex).toInt();
-      needChange = true;
-    }
-  }
-}
-*/
-


Deleted legacy code

Deleted legacy code

--- MiniSumoSpin/MiniSumoSpin.ino
+++ MiniSumoSpin/MiniSumoSpin.ino
@@ -1,23 +0,0 @@
-#include <MiniRobot.h>
-
-MiniRobot robot;
-int steps;
-
-void setup() {
-}
-
-void loop() {
-  if ((robot.leftEdge() || robot.rightEdge()) && steps > 0) {
-    steps--;
-    robot.leftBackward();
-    robot.rightBackward();
-  } else if (robot.distanceToEnemy() > 0) {
-    steps = 100;
-    robot.leftForward();
-    robot.rightForward();
-  } else {
-    steps = 100;
-    robot.leftBackward();
-    robot.rightForward();
-  }
-}


Changed findHeading to heading. Also added another parameter to heading. The prototype is now int heading(LSM303::vector from, LSM303::vector avg);

--- ZumoMotors/examples/CompassExample/CompassExample.ino
+++ ZumoMotors/examples/CompassExample/CompassExample.ino
@@ -191,10 +191,10 @@
   motors.setLeftSpeed(-SPEED*adjust - 100);
 }

-int findHeading(LSM303::vector from)
-{
-  int x = (int)compass.m.x;
-  int y = (int)compass.m.y;
+int heading(LSM303::vector from, LSM303::vector avg)
+{
+  int x = (int)avg.x;
+  int y = (int)avg.y;
   float xScaled =  2.0*(float)(x - compass.m_min.x) / ( compass.m_max.x - compass.m_min.x) - 1.0;
   float yScaled =  2.0*(float)(y -  compass.m_min.y) / (compass.m_max.y - compass.m_min.y) - 1.0;

@@ -231,7 +231,6 @@
   avg.x /= 10.0;
   avg.y /= 10.0;
   avg.z = 0;
-  compass.m = avg;
   //return compass.heading((LSM303::vector){1,0,0});
-  return findHeading((LSM303::vector){1,0,0});
+  return heading((LSM303::vector){1,0,0},avg);
 }


commented 	modified:   mcu_main/mcu_main.ino

--- mcu_main/mcu_main.ino
+++ mcu_main/mcu_main.ino
@@ -3,6 +3,7 @@
 const int C = 10;
 const int D = 11;

+//!  struct storing the state information
 class State
 {
   public:


Wrong function call. It should be analogRead(), not digitalRead().

--- Calibration/sdWrite/sdWrite.ino
+++ Calibration/sdWrite/sdWrite.ino
@@ -12,7 +12,7 @@
 // and Uno without ethernet shield
 const int SDCardPin = 10;
 // Analog 0
-const int tempPin = 11;
+const int tempPin = A0;
 // Range of TMP36
 const int TMP36_range = 1023;
 // Maximum voltage response of TMP36
@@ -79,15 +79,15 @@
  * spanning 0 to 1023.
  * pinNum is the digital pin number.
  * voltMax is the maximum voltage response of the sensor
+ * Returns Temperature reading in Celsius
  */
 double temperature(int sensorRange, int pinNum, unsigned voltMax)
 {
         // Read raw value, which is 0-sensorRange
-        double sensorValue = (double)digitalRead(pinNum);
-
+        double sensorValue = (double)analogRead(pinNum);
         // Compute as fraction of voltage against voltage max
         double voltage = (sensorValue / sensorRange) * voltMax;
-
+        Serial.println(voltToTemp(voltage));
         return voltToTemp(voltage);
 }


added beta change in time, tests on table seems pretty good, cannot detect drift during 5 mins already

--- arduino_st/arduino_st.ino
+++ arduino_st/arduino_st.ino
@@ -189,10 +189,11 @@
 //---------------------------------------------------------------------------------------------------
 #define twoKpDef  (2.0f * 0.5f)
 #define twoKiDef  (2.0f * 0.25f)
-#define betaDef	  0.05f
+#define betaDef	  0.05f //it was 0.2 originaly

 void MadgwickAHRSupdateIMU(float dt, Quaternion& q, float gx, float gy, float gz,  const VectorFloat& a)
 {
+    static float total_time = 0;
     float _2q0, _2q1, _2q2, _2q3, _4q0, _4q1, _4q2 ,_8q1, _8q2, q0q0, q1q1, q2q2, q3q3;

     // Rate of change of quaternion from gyroscope
@@ -227,7 +228,9 @@
             4.0f * q1q1 * q.z - _2q1 * a.x + 4.0f * q2q2 * q.z - _2q2 * a.y
     };
     so.normalize();
-    so.scale(betaDef);
+    so.scale(betaDef + betaDef * total_time / 20.); //time correction rises each divider seconds
+    total_time += dt;
+
     qDot -= so;
     qDot *= dt;


Boss 1, 10Kpts, Boss 2, 20Kpts

Boss 1, 10Kpts, Boss 2, 20Kpts

--- arduboy-game/arduboy-game.ino
+++ arduboy-game/arduboy-game.ino
@@ -447,11 +447,11 @@
     if (!isBossAlive) {
       boolean spawnedBoss = false;

-      if ((score >= 500) && (!spawnedBossOne)) {
+      if ((score >= 10000) && (!spawnedBossOne)) {
         boss.set(129, 10, 1);
         spawnedBossOne = true;
         spawnedBoss = true;
-      } else if ((score >= 12000) && (!spawnedBossTwo)) {
+      } else if ((score >= 20000) && (!spawnedBossTwo)) {
         boss.set(129, 24, 2);
         spawnedBossTwo = true;
         spawnedBoss = true;


updated arduino code to include feeder

updated arduino code to include feeder

--- arduino/KittyCar/KittyCar.ino
+++ arduino/KittyCar/KittyCar.ino
@@ -10,10 +10,13 @@
   // pin 13 triggers the Frolic BOLT
   pinMode(13, OUTPUT);
   digitalWrite(13, LOW);
+
+  // pin 12 triggers the auto-feeder
+  pinMode(12, OUTPUT);
+  digitalWrite(12, LOW);
 }

 void loop() {
-  // print the string when a newline arrives:
   if (stringComplete) {

     if (inputString[0] == 't'){
@@ -21,7 +24,12 @@
       delay(100);
       digitalWrite(13, LOW);
     }
-    Serial.println(inputString);
+    else if(inputString[0] == 's'){
+      digitalWrite(12, HIGH);
+      delay(5000);
+      digitalWrite(12, LOW);
+    }
+    //Serial.println(inputString);
     // clear the string:
     inputString = "";
     stringComplete = false;