backup

backup

--- tetrisdoor.ino
+++ tetrisdoor.ino
@@ -1,17 +1,13 @@
 #include "application.h"
-#include "neopixel/neopixel.h"
-#include "MQTT/MQTT.h"
-
-#include "application.h"
+#include "neopixel__spark_internet_button/neopixel__spark_internet_button.h"

 #define PIXEL_PIN      D0
 #define PIXEL_TYPE     WS2811
-
-#define matrixx        10
-#define matrixy         5
-#define fallspeedorg  800
-
-int pos[2]                   = { 5, 1};
+#define matrixx         5
+#define matrixy        10
+#define fallspeedorg   80
+
+int pos[2]                   = { 3, 1};
 int bricks[7][4][2]          = { {{0, 1}, {-1, 0}, {0, 0}, {1, 0}}, {{-1, 1}, {-1, 0}, {0, 0}, {1, 0}}, {{1, 1}, {-1, 0}, {0, 0}, {1, 0}}, {{-1, 0}, {0, 0}, {0, 1}, {1, 1}}, {{-1, 1}, {0, 1}, {0, 0}, {1, 0}}, {{1, 0}, {1, 1}, {0, 1}, {0, 0}}, {{-1, 0}, {0, 0}, {1, 0}, {2, 0}}};
 int colors[7][3]             = { {255, 0, 0}, {100, 255, 0}, {0, 0, 255}, {255, 255, 0}, {0, 255, 255}, {255, 100, 0}, {255, 255, 255}};
 int matrix[matrixx][matrixy] = { 0};
@@ -26,56 +22,15 @@
 int fullrow                  = 0;
 int rowtodelete              = 0;
 int gameover                 = 0;
-int mode                     = 0;
+int mode                     = 1;
 int currentColor[3]          = {0};

-Adafruit_NeoPixel strip = Adafruit_NeoPixel((matrixx * matrixy), PIXEL_PIN, PIXEL_TYPE);
-
-void callback(char* topic, byte* payload, unsigned int length);
-
-MQTT client("ansinas", 1883, callback);
-
-void callback(char* topic, byte* payload, unsigned int length) {
-    char p[length + 1];
-    memcpy(p, payload, length);
-    p[length] = NULL;
-    String message(p);
-
-    if (message.equals("LEFT")){
-        left();
-    }
-
-    if (message.equals("RIGHT")){
-        right();
-    }
-
-    if (message.equals("DOWN")){
-        down();
-    }
-
-    if (message.equals("ROTATE")){
-        rotate();
-    }
-
-}
-
-void setup() {
-
-    strip.begin();
-
-    for(int i = 0; i < strip.numPixels(); i++){
-        strip.setPixelColor(i, strip.Color(1, 0, 0));
-    }
-
-    strip.show();
-
-    client.connect("tetrisdoor");
-
-    if (client.isConnected()) {
-        client.publish("tetrisdoor","start");
-        client.subscribe("tetrisdoor");
-    }
-
+Adafruit_NeoPixel strip = Adafruit_NeoPixel( (matrixx * matrixy) , PIXEL_PIN, PIXEL_TYPE);
+
+void setup()
+{
+  strip.begin();
+  strip.show(); // Initialize all pixels to 'off'
 }

 void checkend(){
@@ -92,7 +47,7 @@

   if(gameover == 1){

-    pos[0] = 5;
+    pos[0] = 3;
     pos[1] = 1;

     for(int x = 0; x < matrixx; x++){
@@ -288,7 +243,8 @@
     }

   }
-
+
+/*
   for(int e = 0; e < 4; e++){
     truepos[0] = current[e][0]+pos[0];
     truepos[1] = current[e][1]+pos[1];
@@ -300,23 +256,23 @@
     }

   }
-
+  */
   strip.show();
 }

 void loop() {

-    if (client.isConnected()){
-        client.loop();
-    }
-
     if(mode == 0){
-
-          for(int i = 0; i < strip.numPixels(); i++){
-            strip.setPixelColor(i, strip.Color(currentColor[0], currentColor[1], currentColor[2]));
-          }
-
-    }
+      for(int x = 0; x < matrixx; x++){
+        for(int y = 0; y < matrixy; y ++){
+            matrix[x][y] = 0;
+        }
+      }
+      matrix[1][1] = 1;
+      show();
+    }
+
+

     if(mode == 1){
         if(fallcount == fallspeed){
@@ -328,6 +284,6 @@
         checkrows();
         checkend();
         show();
-        delay(100);
-    }
-}
+        delay(1);
+    }
+}


Update sketch_reco.ino

Update sketch_reco.ino

--- dragino/sketch_reco.ino
+++ dragino/sketch_reco.ino
@@ -1,3 +1,15 @@
+//Hello, this is a sketch to get remote control to your dragino device by bridge mode
+//The original source and Pubsubclient code comes from:
+//https://github.com/knolleary/pubsubclient
+//this is a modified sketch from those repository
+//
+//Este es un sketch de prueba para tomar control remoto de su dispositivo dragino en modo bridge
+//la libreria Pubsubclient.* y el codigo fuente proviene desde:
+//https://github.com/knolleary/pubsubclient
+//y este es un sketch modificado desde el repositorio origen y adaptado para funcionar con nuestra
+//plataforma ior.redlibre.cl
+
+
 #include <SPI.h>
 #include <PubSubClient.h>
 #include <YunClient.h>


Add FIXME about only using *one* CGRAM character


Fix indent

Fix indent

--- tests/BlynkBuildTest/BlynkBuildTest.ino
+++ tests/BlynkBuildTest/BlynkBuildTest.ino
@@ -7,7 +7,7 @@
  **************************************************************/

 #if defined(ARDUINO_AVR_GEMMA) \
-    || defined(ARDUINO_attiny)
+  || defined(ARDUINO_attiny)

   #define BLYNK_NO_INFO
   #define BLYNK_NO_BUILTIN


modified for pure record, no feedback

modified for pure record, no feedback

--- v2/data-record/firmware/data-record.ino
+++ v2/data-record/firmware/data-record.ino
@@ -159,7 +159,8 @@
     int y = getVibration();

     // write that value to the vibration motor
-    analogWrite(VIBPIN,y);
+    // can comment this out for pure data record
+//    analogWrite(VIBPIN,y);

 //    recordSerial();
     recordSD();


Re type variables and make some variables constants for speed settings. Change some variables used as booleans to actually booleans.

--- padawan360_body/padawan360_body.ino
+++ padawan360_body/padawan360_body.ino
@@ -39,25 +39,25 @@
 //************************** Set speed and turn speeds here************************************//

 //set these 3 to whatever speeds work for you. 0-stop, 127-full speed.
-byte drivespeed1 = 50;
+const byte DRIVESPEED1 = 50;
 //Recommend beginner: 50 to 75, experienced: 100 to 127, I like 100.
-byte drivespeed2 = 100;
+const byte DRIVESPEED2 = 100;
 //Set to 0 if you only want 2 speeds.
-byte drivespeed3 = 127;
-
-byte drivespeed = drivespeed1;
+const byte DRIVESPEED3 = 127;
+
+byte drivespeed = DRIVESPEED1;

 // the higher this number the faster the droid will spin in place, lower - easier to control.
 // Recommend beginner: 40 to 50, experienced: 50 $ up, I like 70
-byte turnspeed = 70;
+const byte TURNSPEED = 70;
 // If using a speed controller for the dome, sets the top speed. You'll want to vary it potenitally
 // depending on your motor. My Pittman is really fast so I dial this down a ways from top speed.
 // Use a number up to 127 for serial
-byte domespeed = 80;
+const byte DOMESPEED = 80;

 // Ramping- the lower this number the longer R2 will take to speedup or slow down,
 // change this by incriments of 1
-byte ramping = 5;
+const byte RAMPING = 5;

 // Compensation is for deadband/deadzone checking. There's a little play in the neutral zone
 // which gets a reading of a value of something other than 0 when you're not moving the stick.
@@ -66,15 +66,15 @@
 // direct method calls against the Syren/Sabertooth library itself but it's not supported in all
 // serial modes so just manage and check it in software here
 // use the lowest number with no drift
-// domeDeadZoneRange for the left stick, driveDeadZoneRange for the left stick
-byte domeDeadZoneRange = 20;
-byte driveDeadZoneRange = 20;
+// DOMEDEADZONERANGE for the left stick, DRIVEDEADZONERANGE for the left stick
+const byte DOMEDEADZONERANGE = 20;
+const byte DRIVEDEADZONERANGE = 20;

 // Set the baude rate for the Syren motor controller
 // for packetized options are: 2400, 9600, 19200 and 38400. I think you need to pick one that works
 // and I think it varies across different firmware versions.
 // for simple serial use 9600
-int domeBaudeRate = 2400;
+const int DOMEBAUDRATE = 2400;

 // Comment the SYRENSIMPLE out for packetized serial connection to Syren - Recomended.
 // I've never tested Syrene Simple, it's a carry-over from DanF's library.
@@ -113,47 +113,46 @@
 // 0 = full volume, 255 off
 byte vol = 20;
 // 0 = drive motors off ( right stick disabled ) at start
-byte isDriveEnabled = 0;
+boolean isDriveEnabled = false;

 // Automated function variables
 // Used as a boolean to turn on/off automated functions like periodic random sounds and periodic dome turns
-byte isInAutomationMode = 0;
+boolean isInAutomationMode = false;
 unsigned long automateMillis = 0;
 byte automateDelay = random(5,20);// set this to min and max seconds between sounds
 //How much the dome may turn during automation.
 int turnDirection = 20;
 // Action number used to randomly choose a sound effect or a dome turn
 byte automateAction = 0;
-unsigned long DriveMillis = 0;
-int driveThrottle = 0;
-int sticknum = 0;
-int domeThrottle = 0;
-int turnThrottle = 0;
-
-int firstLoadOnConnect = 0;
+char driveThrottle = 0;
+char sticknum = 0;
+char domeThrottle = 0;
+char turnThrottle = 0;
+
+boolean firstLoadOnConnect = false;

 // this is legacy right now. The rest of the sketch isn't set to send any of this
 // data to another arduino like the original Padawan sketch does
 // right now just using it to track whether or not the HP light is on so we can
 // fire the correct I2C event to turn on/off the HP light.
-struct SEND_DATA_STRUCTURE{
-  //put your variable definitions here for the data you want to send
-  //THIS MUST BE EXACTLY THE SAME ON THE OTHER ARDUINO
-  int hpx; // hp movement
-  int hpy; // hp movement
-  int hpl; // hp light
-  int hpa; // hp automation
-  int dsp; // 0 = random, 1 = alarm, 5 = leia, 11 = alarm2, 100 = no change
-};
-
-SEND_DATA_STRUCTURE domeData;//give a name to the group of data
+//struct SEND_DATA_STRUCTURE{
+//  //put your variable definitions here for the data you want to send
+//  //THIS MUST BE EXACTLY THE SAME ON THE OTHER ARDUINO
+//  int hpl; // hp light
+//  int dsp; // 0 = random, 1 = alarm, 5 = leia, 11 = alarm2, 100 = no change
+//};
+//SEND_DATA_STRUCTURE domeData;//give a name to the group of data
+
+boolean isHPOn = false;
+
+

 MP3Trigger mp3Trigger;
 USB Usb;
 XBOXRECV Xbox(&Usb);

 void setup(){
-  SyRSerial.begin(domeBaudeRate);
+  SyRSerial.begin(DOMEBAUDRATE);
   #if defined(SYRENSIMPLE)
     SyR.motor(0);
   #else
@@ -217,51 +216,51 @@
     ST.drive(0);
     ST.turn(0);
     SyR.motor(1,0);
-    firstLoadOnConnect = 0;
+    firstLoadOnConnect = false;
     return;
   }

   // After the controller connects, Blink all the LEDs so we know drives are disengaged at start
-  if(firstLoadOnConnect == 0){
-    firstLoadOnConnect = 1;
+  if(!firstLoadOnConnect){
+    firstLoadOnConnect = true;
     mp3Trigger.play(21);
     Xbox.setLedMode(ROTATING, 0);
   }

   // enable / disable right stick (droid movement) & play a sound to signal motor state
   if(Xbox.getButtonClick(START, 0)) {
-    if (isDriveEnabled < 1){
-      isDriveEnabled = 1;
+    if(isDriveEnabled){
+      isDriveEnabled = false;
+      Xbox.setLedMode(ROTATING, 0);
+      mp3Trigger.play(53);
+    } else {
+      isDriveEnabled = true;
       mp3Trigger.play(52);
       // //When the drive is enabled, set our LED accordingly to indicate speed
-      if(drivespeed == drivespeed1){
+      if(drivespeed == DRIVESPEED1){
         Xbox.setLedOn(LED1, 0);
-      } else if(drivespeed == drivespeed2 && (drivespeed3!=0)){
+      } else if(drivespeed == DRIVESPEED2 && (DRIVESPEED3!=0)){
         Xbox.setLedOn(LED2, 0);
       } else {
         Xbox.setLedOn(LED3, 0);
       }
-    } else {
-      isDriveEnabled = 0;
-      Xbox.setLedMode(ROTATING, 0);
-      mp3Trigger.play(53);
     }
   }

   //Toggle automation mode with the BACK button
   if(Xbox.getButtonClick(BACK, 0)) {
-    if (isInAutomationMode < 1){
-      isInAutomationMode = 1;
-      mp3Trigger.play(52);
-    } else {
-      isInAutomationMode = 0;
+    if(isInAutomationMode){
+      isInAutomationMode = false;
       automateAction = 0;
       mp3Trigger.play(53);
+    } else {
+      isInAutomationMode = true;
+      mp3Trigger.play(52);
     }
   }

   // Plays random sounds or dome movements for automations when in automation mode
-  if(isInAutomationMode == 1){
+  if(isInAutomationMode){
     unsigned long currentMillis = millis();

     if(currentMillis - automateMillis > (automateDelay*1000)){
@@ -451,13 +450,13 @@
   // turn hp light on & off with Left Analog Stick Press (L3)
   if(Xbox.getButtonClick(L3, 0))  {
     // if hp light is on, turn it off
-    if(domeData.hpl == 1){
-      domeData.hpl = 0;
+    if(isHPOn){
+      isHPOn = false;
       // turn hp light off
       // Front HPEvent 2 - ledOFF - I2C
       triggerI2C(25, 2);
     } else {
-      domeData.hpl = 1;
+      isHPOn = true;
       // turn hp light on
       // Front HPEvent 4 - whiteOn - I2C
       triggerI2C(25, 1);
@@ -468,24 +467,24 @@
   // Change drivespeed if drive is eabled
   // Press Right Analog Stick (R3)
   // Set LEDs for speed - 1 LED, Low. 2 LED - Med. 3 LED High
-  if(Xbox.getButtonClick(R3, 0) && isDriveEnabled == 1) {
+  if(Xbox.getButtonClick(R3, 0) && isDriveEnabled) {
     //if in lowest speed
-    if(drivespeed == drivespeed1){
+    if(drivespeed == DRIVESPEED1){
       //change to medium speed and play sound 3-tone
-      drivespeed = drivespeed2;
+      drivespeed = DRIVESPEED2;
       Xbox.setLedOn(LED2, 0);
       mp3Trigger.play(53);
       triggerI2C(10, 22);
-    } else if(drivespeed == drivespeed2 && (drivespeed3!=0)){
+    } else if(drivespeed == DRIVESPEED2 && (DRIVESPEED3!=0)){
       //change to high speed and play sound scream
-      drivespeed = drivespeed3;
+      drivespeed = DRIVESPEED3;
       Xbox.setLedOn(LED3, 0);
       mp3Trigger.play(1);
       triggerI2C(10, 23);
     } else {
       //we must be in high speed
       //change to low speed and play sound 2-tone
-      drivespeed = drivespeed1;
+      drivespeed = DRIVESPEED1;
       Xbox.setLedOn(LED1, 0);
       mp3Trigger.play(52);
       triggerI2C(10, 21);
@@ -498,19 +497,19 @@
   // Sabertooth runs at 8 bit signed. -127 to 127 for speed (full speed reverse and  full speed forward)
   // Map the 360 stick values to our min/max current drive speed
   sticknum = (map(Xbox.getAnalogHat(RightHatY, 0), -32768, 32767, -drivespeed, drivespeed));
-  if(sticknum > -driveDeadZoneRange && sticknum < driveDeadZoneRange){
+  if(sticknum > -DRIVEDEADZONERANGE && sticknum < DRIVEDEADZONERANGE){
     // stick is in dead zone - don't drive
     driveThrottle = 0;
   } else {
     if(driveThrottle < sticknum){
-      if(sticknum - driveThrottle < (ramping+1) ){
-        driveThrottle+=ramping;
+      if(sticknum - driveThrottle < (RAMPING+1) ){
+        driveThrottle+=RAMPING;
       } else {
         driveThrottle = sticknum;
       }
     } else if(driveThrottle > sticknum){
-      if(driveThrottle - sticknum < (ramping+1) ){
-        driveThrottle-=ramping;
+      if(driveThrottle - sticknum < (RAMPING+1) ){
+        driveThrottle-=RAMPING;
       } else {
         driveThrottle = sticknum;
       }
@@ -519,20 +518,20 @@

   turnThrottle = map(Xbox.getAnalogHat(RightHatX, 0), -32768, 32767, 0, 255);
   if(turnThrottle <= 200 && turnThrottle >= 54)
-    turnThrottle = map(turnThrottle, 54, 200, -(turnspeed/3), (turnspeed/3));
+    turnThrottle = map(turnThrottle, 54, 200, -(TURNSPEED/3), (TURNSPEED/3));
   else if(turnThrottle > 200)
-    turnThrottle = map(turnThrottle, 201, 255, turnspeed/3, turnspeed);
+    turnThrottle = map(turnThrottle, 201, 255, TURNSPEED/3, TURNSPEED);
   else if(turnThrottle < 54)
-    turnThrottle = map(turnThrottle, 0, 53, -turnspeed, -(turnspeed/3));
+    turnThrottle = map(turnThrottle, 0, 53, -TURNSPEED, -(TURNSPEED/3));

   // DRIVE!
   // right stick (drive)
-  if (isDriveEnabled == 1){
+  if (isDriveEnabled){
     // Only do deadzone check for turning here. Our Drive throttle speed has some math applied
-    // for ramping and stuff, so just keep it separate here
-    if(turnThrottle > -driveDeadZoneRange && turnThrottle < driveDeadZoneRange){
+    // for RAMPING and stuff, so just keep it separate here
+    if(turnThrottle > -DRIVEDEADZONERANGE && turnThrottle < DRIVEDEADZONERANGE){
       // stick is in dead zone - don't turn
       turnThrottle = 0;
     }
@@ -541,8 +540,8 @@
   }

   // DOME DRIVE!
-  domeThrottle = (map(Xbox.getAnalogHat(LeftHatX, 0), -32768, 32767, -domespeed, domespeed));
-  if (domeThrottle > -domeDeadZoneRange && domeThrottle < domeDeadZoneRange){
+  domeThrottle = (map(Xbox.getAnalogHat(LeftHatX, 0), -32768, 32767, -DOMESPEED, DOMESPEED));
+  if (domeThrottle > -DOMEDEADZONERANGE && domeThrottle < DOMEDEADZONERANGE){
     //stick in dead zone - don't spin dome
     domeThrottle = 0;
   }
@@ -556,8 +555,8 @@
   #endif
 } // END loop()

-void triggerI2C(int deviceID, int eventID){
-  Wire.beginTransmission(deviceID);
-  Wire.write(eventID);
-  Wire.endTransmission();
+void triggerI2C(byte deviceID, byte eventID){
+  //Wire.beginTransmission(deviceID);
+  //Wire.write(eventID);
+  //Wire.endTransmission();
 }


update sketch

update sketch

--- teensytty/teensytty.ino
+++ teensytty/teensytty.ino
@@ -5,6 +5,9 @@
  * ASR33 teletype connects to the hardware serial port, via 20mA current-loop.
  * USB serial connects to the host system.
  * This driver performs character translation and other functions.
+ *
+ * NB depends on a hacked AltSoftSerial:
+ * https://github.com/hughpyle/AltSoftSerial/tree/hacking
  *
  * 2018-09-03 update for with arduino 1.8.6
  */


NOTICE ME NAM

NOTICE ME NAM

--- 2018-FirefighterL1/Left_Right_Follow.ino
+++ 2018-FirefighterL1/Left_Right_Follow.ino
@@ -27,6 +27,13 @@
   }
 }

+void secondDogCheck() { //robot is facing downward where the second dog could potentially be
+  double dogDistance = 3;
+  if(frontRightUltrasonic.getDistance() < dogDistance){
+    dog2 = true;
+  }
+}
+
 void levelOneNav() {
   int followDirection = 0; //left follow or right follow
   int lowerleftroomdistance = 10; //distance to activate Rick's Code
@@ -34,7 +41,13 @@
   double lateralMove = 5; //how far the robot should move to exit the lower right room

   upperRightRoom();
+  secondDogCheck();

+  if(dog2){
+    //turn around and get to the lower right room the long way
+  } else {
+    //proceed forward and get to the lower right room the short way
+  }
   while(followDirection >= 7)
   {
     if (frontRightUltrasonic.getDistance() > closeToWall && leftUltrasonic.getDistance() < closeToWall)


output pin changed d1=red, d2=green, d3=(input on NodeMCU1 | flash button, d4=blue) and comments added

--- nodemcu-rgbstrip.ino
+++ nodemcu-rgbstrip.ino
@@ -56,9 +56,11 @@
   Serial.begin(115200);
   Serial.println(FPSTR(SETUPSTR));

-  pinMode(D1, OUTPUT);
-  pinMode(D2, OUTPUT);
-  pinMode(D3, OUTPUT);
+  pinMode(D1, OUTPUT);  /* RED */
+  pinMode(D2, OUTPUT);  /* GREEN */
+  pinMode(D4, OUTPUT);  /* BLUE */
+  pinMode(D3, INPUT);   /* for the FLASH => reset config button */
+
   analogWriteFreq(PWM_FREQ);
   analogWriteRange(1023);

@@ -98,6 +100,7 @@
     ESP.reset();
   }

+  /* No saved config file => start in AP mode with the config portal */
   if (!hasSavedConfig) {
     // Setup WiFiManager and start the config portal
     WiFiManager wfMan;
@@ -140,5 +143,5 @@
 void loop() {
   // put your main code here, to run repeatedly:
   // myServer.handleClient();
-  delay(2000);
+  delay(1000);
 }


replace for-loops by range for loop

replace for-loops by range for loop

--- ksp-gegi/ksp-gegi.ino
+++ ksp-gegi/ksp-gegi.ino
@@ -167,8 +167,8 @@
 }

 void updatePins() {
-  for (uint8_t i = 0; i < ndigiPins; ++i) {
-    digiPins[i].updateSwitch();
+  for (auto &p : digiPins) {
+    p.updateSwitch();
   }
 }

@@ -180,9 +180,9 @@
     c = Serial.read();
     id = Serial.parseInt();  // skip '='
     val = Serial.parseInt(); // skip newline
-    for (uint8_t i = 0; i < ndigiPins; ++i) {
-      if (digiPins[i].getId()==id) {
-        digiPins[i].updateLedState(c, val);
+    for (auto &p : digiPins) {
+      if (p.getId()==id) {
+        p.updateLedState(c, val);
       }
 //    Serial.print(c); Serial.print(id); Serial.println(val);  // echo for ack
     }


Update Library for Ultra High Resolution Mode.

--- arduino.ino
+++ arduino.ino
@@ -1,5 +1,6 @@
 #include <EEPROM.h>
-#include "SparkFunBME280.h"
+#include <Adafruit_Sensor.h>
+#include <Adafruit_BMP280.h>
 #include "Wire.h"
 #include "SPI.h"

@@ -12,7 +13,7 @@
 #define SAMPLING 1                  // Samples Per Second.

 // DON'T TOUCH IN THE CODE BELOW
-BME280 barometer;
+Adafruit_BMP280 bmp;

 float altReference = -900;
 uint32_t entriesCounter = 0;
@@ -122,17 +123,10 @@
   Serial.begin(115200);
   Serial.println("Altimeter v1.0 - Equipe Rocket 2017");

-  barometer.settings.commInterface = I2C_MODE;
-  barometer.settings.I2CAddress = 0x76;
-  barometer.settings.runMode = 3;
-  barometer.settings.tStandby = 0;
-  barometer.settings.filter = 4;
-  barometer.settings.tempOverSample = 5;
-  barometer.settings.pressOverSample = 5;
-  barometer.settings.humidOverSample = 1;
-  delay(50);
-  barometer.begin();
-  delay(50);
+  if (!bmp.begin()) {
+    Serial.println("Could not find a valid BMP280 sensor, check wiring!");
+    while (1);
+  }

   Wire.begin();

@@ -163,14 +157,12 @@
   if(debugMode) {
     listenCommanader();
   } else {
-    barometer.readTempC();
-
-    if(altReference==-900) {
-      altReference = barometer.readFloatAltitudeMeters();
+    if(altReference == -900) {
+      altReference = bmp.readPressure();
       delay(50);
     }

-    float lastAlt = barometer.readFloatAltitudeMeters() - altReference;
+    float lastAlt = bmp.readAltitude(altReference);

     Serial.print("Current Altitude (m): ");
     Serial.println(lastAlt);
@@ -180,6 +172,6 @@

     updateEntriesCount(entriesCounter);

-    delay(1000/SAMPLING);
+    delay(960/SAMPLING);
   }
 }


Valid pwmdepth values are from between [1024..10240].

--- webserver.ino
+++ webserver.ino
@@ -183,7 +183,7 @@
   webServer.on( "/api/pwmdepth", []() {
     if ( webServer.arg( "newpwmdepth" ) != "" ) {
       unsigned int newPWMdepth = webServer.arg( "newpwmdepth" ).toInt();
-      if ( newPWMdepth < 1023 || newPWMdepth > 10230 ) {
+      if ( newPWMdepth < 1024 || newPWMdepth > 10240 ) {
         webServer.send( 200, FPSTR( textplainHEADER ), F( "ERROR - Invalid PWM depth" ) );
         return;
       }


Fixed OLED flip routine.

Fixed OLED flip routine.

--- webserver.ino
+++ webserver.ino
@@ -76,9 +76,9 @@

   webServer.on( "/api/flipoled", []() {
     OLEDflipped = !OLEDflipped;
-    if ( !OLEDflipped ) {
-      OLED.init();
-    } else {
+    OLED.end();
+    OLED.init();
+    if ( OLEDflipped ) {
       OLED.flipScreenVertically();
     }
     writeConfigFile();


Very basic control

Very basic control

--- PID/PID.ino
+++ PID/PID.ino
@@ -21,7 +21,7 @@
 int inputPin=0, outputPin=3;

 //Specify the links and initial tuning parameters
-PID myPID(&Input, &Output, &Setpoint,2,5,1, DIRECT);
+PID myPID(&Input, &Output, &Setpoint, 1, 5, 1, DIRECT);
 unsigned long serialTime; //this will help us know when to talk with processing

 int count =0;
@@ -36,7 +36,7 @@

 void setup()
 {
-  Serial.begin(9600);
+  Serial.begin(57600);
   pinMode(PIN_INT_LEFT, INPUT );

@@ -45,12 +45,13 @@

   //initialize the variables we're linked to
   Input = 0;
-  Setpoint = 100;
+  Setpoint = 600;

   //turn the PID on
   myPID.SetMode(AUTOMATIC);

   //Serial.println("Begin");
+
 }

 void loop()
@@ -67,36 +68,47 @@
         count = 0;
         //Serial.println(ms_per_int);

+        ms_per_int = constrain(ms_per_int, 100, 700);
+
         // Convert to byte value for processing for now
         speed_motor_left = map(ms_per_int, 100, 700, 700, 100);
         //speed_motor_left = ms_per_int;
         Input = speed_motor_left;
-        //Serial.print(" : "); Serial.print(pwm_motor_left);
-        //Serial.print(" - "); Serial.println(speed_motor_left);
+        //Serial.print(" : "); Serial.print(speed_motor_left);
+        //Serial.print(" - "); Serial.println(Input);
       }

     }
     count++; // Up the sample count

+    /*
     speed_requested = analogRead(PIN_POT) / 4;
     if (speed_requested < 75) {
       // Can't go slower than this
       speed_requested = 0;
     }
-
+    */
     //Serial.println(speed_requested);

     //pid-related code
     myPID.Compute();

+
+    pwm_motor_left = Output;
+    pwm_motor_left = constrain(pwm_motor_left, 100, 180);
+    //if (pwm_motor_left < 90) pwm_motor_left = 90;
+    analogWrite(PIN_MOTOR_LEFT, pwm_motor_left);
+
+    /*
     // Send it to the motor if changed
     if (pwm_motor_left != speed_requested) {
       pwm_motor_left = speed_requested;

-      //byte pwm_motor_left = map(Output, 0, 1000, 0, 255);
-      //if (pwm_motor_left < 75) pwm_motor_left = 0;
+      //pwm_motor_left = map(Output, 0, 1000, 0, 255);
+      if (pwm_motor_left < 75) pwm_motor_left = 0;
       analogWrite(PIN_MOTOR_LEFT, pwm_motor_left);
     }
+    */

   }


use 57600

use 57600

Signed-off-by: Robert Nelson <d6c41255011d14bfa93d8562b946ca186cfa0c7b@gmail.com>

--- ws_bm_rtc.ino
+++ ws_bm_rtc.ino
@@ -9,10 +9,10 @@
 char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

 void setup () {
-  while (!Serial);     // will pause Zero, Leonardo, etc until serial console opens
+  //while (!Serial);     // will pause Zero, Leonardo, etc until serial console opens
   uint32_t currentFrequency;

-  Serial.begin(115200);
+  Serial.begin(57600);
   Serial.println("Hello!");

   if (! rtc.begin()) {


notify bacpac ROM reading finished by using PWRBTN

--- d_BacpacCommands.ino
+++ d_BacpacCommands.ino
@@ -240,6 +240,10 @@
   if (debug) {
     Serial.println("");
   }
+  // notify SMARTY that ROM has read successfully
+  digitalWrite(PWRBTN, LOW); pinMode(PWRBTN, OUTPUT);
+  delay(200);
+  pinMode(PWRBTN, INPUT_PULLUP);
 }

 void _I2CmasterRead()


Variable "op" : Char -> Str

Variable "op" : Char -> Str

--- wake-on-ring.ino
+++ wake-on-ring.ino
@@ -75,7 +75,7 @@
 	int packetSize = Udp.parsePacket();
 	if(packetSize) { // Si il y a un paquet
 		Udp.read(packetBuffer,32); // le lire
-//		String op = (packetBuffer[0], packetBuffer[1], packetBuffer[2], packetBuffer[3], '\0');
+		op = String(String(packetBuffer[0]) + String(packetBuffer[1]) + String(packetBuffer[2]) + String(packetBuffer[3])) ;
 		lame = packetBuffer[4]-'0'; // et convertir le 5e caractére en chiffre (char -> int)
 		if(op == "lame") {
 		  switch (lame) {


Fix example

Fix example

--- examples/Sgp4Predictor/Sgp4Predictor.ino
+++ examples/Sgp4Predictor/Sgp4Predictor.ino
@@ -1,98 +1,98 @@
-#include <Sgp4.h>
-#include <Ticker.h>
-
-Sgp4 sat;
-unsigned long unixtime = 1458950400;
-int timezone = 12 ;  //utc + 12
-
-int  year; int mon; int day; int hr; int min; double sec;
-
-
-
-void Predict(int many){
-
-    passinfo overpass;                       //structure to store overpass info
-    sat.initpredpoint( unixtime , 0.0 );     //finds the startpoint
-
-    bool error;
-    unsigned long start = millis();
-    for (int i = 0; i<many ; i++){
-        error = sat.nextpass(&overpass,20);     //search for the next overpass, if there are more than 20 maximums below the horizon it returns false
-        delay(0);
-
-        if ( error == 1){ //no error, prints overpass information
-
-          invjday(overpass.jdstart ,timezone ,true , year, mon, day, hr, min, sec);
-          Serial.println("Overpass " + String(day) + ' ' + String(mon) + ' ' + String(year));
-          Serial.println("  Start: az=" + String(overpass.azstart) + "° " + String(hr) + ':' + String(min) + ':' + String(sec));
-
-          invjday(overpass.jdmax ,timezone ,true , year, mon, day, hr, min, sec);
-          Serial.println("  Max: elev=" + String(overpass.maxelevation) + "° " + String(hr) + ':' + String(min) + ':' + String(sec));
-
-          invjday(overpass.jdstop ,timezone ,true , year, mon, day, hr, min, sec);
-          Serial.println("  Stop: az=" + String(overpass.azstop) + "° " + String(hr) + ':' + String(min) + ':' + String(sec));
-
-          switch(overpass.transit){
-              case none:
-                  break;
-              case enter:
-                  invjday(overpass.jdtransit ,timezone ,true , year, mon, day, hr, min, sec);
-                  Serial.println("  Enter earth shadow: " + String(hr) + ':' + String(min) + ':' + String(sec));
-                  break;
-              case leave:
-                  invjday(overpass.jdtransit ,timezone ,true , year, mon, day, hr, min, sec);
-                  Serial.println("  Leave earth shadow: " + String(hr) + ':' + String(min) + ':' + String(sec));
-                  break;
-          }
-          switch(overpass.sight){
-              case lighted:
-                  Serial.println("  Visible");
-                  break;
-              case eclipsed:
-                  Serial.println("  Not visible");
-                  break;
-              case daylight:
-                  Serial.println("  Daylight");
-                  break;
-          }
-
-
-        }else{
-            Serial.println("Prediction error");
-        }
-        delay(0);
-    }
-    unsigned long einde = millis();
-    Serial.println("Time: " + String(einde-start) + " milliseconds");
-
-}
-
-
-void setup() {
-
-  Serial.begin(115200);
-  Serial.println();
-
-  sat.site(-0.5276847,166.9359231,34); //set site latitude[°], longitude[°] and altitude[m]
-
-  char satname[] = "ISS (ZARYA)";
-  char tle_line1[] = "1 25544U 98067A   16065.25775256 -.00164574  00000-0 -25195-2 0  9990";  //Line one from the TLE data
-  char tle_line2[] = "2 25544  51.6436 216.3171 0002750 185.0333 238.0864 15.54246933988812";  //Line two from the TLE data
-
-  sat.init(satname,tle_line1,tle_line2);     //initialize satellite parameters
-
-  //Display TLE epoch time
-  double jdC = sat.satrec.jdsatepoch;
-  invjday(jdC , timezone, true, year, mon, day, hr, min, sec);
-  Serial.println("Epoch: " + String(day) + '/' + String(mon) + '/' + String(year) + ' ' + String(hr) + ':' + String(min) + ':' + String(sec));
-  Serial.println();
-
-  Predict(50);   //Calculates the next 50 overpasses
-
-}
-
-
-void loop() {
-
-}
+#include <Sgp4.h>
+#include <Ticker.h>

+Sgp4 sat;
+unsigned long unixtime = 1458950400;
+int timezone = 12 ;  //utc + 12
+
+int  year; int mon; int day; int hr; int minute; double sec;
+
+
+
+void Predict(int many){
+
+    passinfo overpass;                       //structure to store overpass info
+    sat.initpredpoint( unixtime , 0.0 );     //finds the startpoint
+
+    bool error;
+    unsigned long start = millis();
+    for (int i = 0; i<many ; i++){
+        error = sat.nextpass(&overpass,20);     //search for the next overpass, if there are more than 20 maximums below the horizon it returns false
+        delay(0);
+
+        if ( error == 1){ //no error, prints overpass information
+
+          invjday(overpass.jdstart ,timezone ,true , year, mon, day, hr, minute, sec);
+          Serial.println("Overpass " + String(day) + ' ' + String(mon) + ' ' + String(year));
+          Serial.println("  Start: az=" + String(overpass.azstart) + "° " + String(hr) + ':' + String(minute) + ':' + String(sec));
+
+          invjday(overpass.jdmax ,timezone ,true , year, mon, day, hr, minute, sec);
+          Serial.println("  Max: elev=" + String(overpass.maxelevation) + "° " + String(hr) + ':' + String(minute) + ':' + String(sec));
+
+          invjday(overpass.jdstop ,timezone ,true , year, mon, day, hr, minute, sec);
+          Serial.println("  Stop: az=" + String(overpass.azstop) + "° " + String(hr) + ':' + String(minute) + ':' + String(sec));
+
+          switch(overpass.transit){
+              case none:
+                  break;
+              case enter:
+                  invjday(overpass.jdtransit ,timezone ,true , year, mon, day, hr, minute, sec);
+                  Serial.println("  Enter earth shadow: " + String(hr) + ':' + String(minute) + ':' + String(sec));
+                  break;
+              case leave:
+                  invjday(overpass.jdtransit ,timezone ,true , year, mon, day, hr, minute, sec);
+                  Serial.println("  Leave earth shadow: " + String(hr) + ':' + String(minute) + ':' + String(sec));
+                  break;
+          }
+          switch(overpass.sight){
+              case lighted:
+                  Serial.println("  Visible");
+                  break;
+              case eclipsed:
+                  Serial.println("  Not visible");
+                  break;
+              case daylight:
+                  Serial.println("  Daylight");
+                  break;
+          }
+
+
+        }else{
+            Serial.println("Prediction error");
+        }
+        delay(0);
+    }
+    unsigned long einde = millis();
+    Serial.println("Time: " + String(einde-start) + " milliseconds");
+
+}
+
+
+void setup() {
+
+  Serial.begin(115200);
+  Serial.println();
+
+  sat.site(-0.5276847,166.9359231,34); //set site latitude[°], longitude[°] and altitude[m]
+
+  char satname[] = "ISS (ZARYA)";
+  char tle_line1[] = "1 25544U 98067A   16065.25775256 -.00164574  00000-0 -25195-2 0  9990";  //Line one from the TLE data
+  char tle_line2[] = "2 25544  51.6436 216.3171 0002750 185.0333 238.0864 15.54246933988812";  //Line two from the TLE data
+
+  sat.init(satname,tle_line1,tle_line2);     //initialize satellite parameters
+
+  //Display TLE epoch time
+  double jdC = sat.satrec.jdsatepoch;
+  invjday(jdC , timezone, true, year, mon, day, hr, minute, sec);
+  Serial.println("Epoch: " + String(day) + '/' + String(mon) + '/' + String(year) + ' ' + String(hr) + ':' + String(minute) + ':' + String(sec));
+  Serial.println();
+
+  Predict(50);   //Calculates the next 50 overpasses
+
+}
+
+
+void loop() {
+
+}
+


Update MRLCommOculus4.ino

Update MRLCommOculus4.ino

--- home/Alessandruino/MRLCommOculus4.ino
+++ home/Alessandruino/MRLCommOculus4.ino
@@ -17,8 +17,26 @@
 * perhaps avrdude ?
 *
 */
+#include "I2Cdev.h"
+#include "MPU6050.h"
+#include <HMC5883L.h>
+#include <L3G4200D.h>

 #include <Servo.h>
+
+MPU6050 accelgyro;
+HMC5883L mag;
+L3G4200D gyro;
+
+
+//MPU6050 accelgyro(0x69); // <-- use for AD0 high
+
+int16_t ax, ay, az;
+int16_t gx, gy, gz;
+int16_t ax2, ay2, az2;
+int16_t mx, my, mz;
+int16_t avx, avy, avz;
+int cnt;
 #define MRLCOMM_VERSION				24

 // serial protocol functions


edit: serial_source.inoからサーボを扱えるようにした

edit: serial_source.inoからサーボを扱えるようにした

--- hardware/serial_source/serial_source.ino
+++ hardware/serial_source/serial_source.ino
@@ -1,14 +1,19 @@
-int analogValue;
+#include <Servo.h>
+
+double analogValue;
+int angle;
+Servo servo1;

 void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
+  servo1.attach(9);
+  servo1.write(0);
 }

 void loop() {
-  // put your main code here, to run repeatedly:
-  analogValue = analogRead(0);
-
-  Serial.println(analogValue);
-  delay(10);
+  analogValue = double(analogRead(0));
+  angle = int(analogValue/1024.0 * 180);
+  servo1.write(angle);
+  Serial.println(angle);
 }


Clean-up and improve comments

Clean-up and improve comments

--- avr/avr.ino
+++ avr/avr.ino
@@ -97,12 +97,11 @@
 	// Timer magic
 	cli();
 	TCCR1A = 0;
-	TCCR1B = _BV(CS11) | _BV(CS10); // Clock divider 64, 64/16e6 = 40µs cycle
-	TCNT1 = 0; // set timer counter initial value (16 bit value)
-	TIMSK1 = _BV(OCIE1A); // enable timer compare match 1A interrupt
-	OCR1A = 1; // Go to the interrupt vector ASAP
+	TCCR1B = _BV(CS11) | _BV(CS10); // Clock divider 64, 64/16e6 = 40µs tick
+	TCNT1 = 0; // Set timer counter initial value (16 bit value)
+	TIMSK1 = _BV(OCIE1A); // Go to interrupt vector when timer reaches target
+	OCR1A = 1; // Go to the interrupt vector ASAP after startup
 	sei();
-
 }

 void loop() {
@@ -209,9 +208,7 @@

 ISR(TIMER1_COMPA_vect)
 {
-	// Force screen off if not yet happened (force OC1A on)
-	TCCR1A = (1 << COM1A1);
-	TCCR1C = (1 << FOC1A);
+	// Screen is off when we hit here (OC1A has been set LOW)

 	// Load new data to LED driver
 	digitalWrite(PIN_COL_LATCH, HIGH);
@@ -232,18 +229,19 @@
 		digitalWrite(PIN_COL_BIT0, col_i & 0b001);
       	}

-	// Main screen turn on! (force OC1A on)
-	TCCR1A = (1 << COM1A1) | (1 << COM1A0);
-	TCCR1C = (1 << FOC1A);
+	// Main screen turn on! (Use Compare Output magic with OC1A)
+	TCCR1A = _BV(COM1A1) | _BV(COM1A0); // Set HIGH on match
+	TCCR1C = _BV(FOC1A); // Force match (turns the screen on)
+	TCCR1A = _BV(COM1A1); // On timer match set turn off the screen.

-	// Say we want to turn off when we hit the target even if interrupt doesn't run
-	TCCR1A = (1 << COM1A1);
-
 	// Restart timer counter
 	TCNT1 = 0;

 	// Set run length
 	OCR1A = pwm_lengths[pwm_i];
+
+	// We have done all time-critical stuff for now
+	sei();

 	/* After turning on the screen, we have "plenty" of CPU cycles
 	 * to spend. Preparing a new segment to display.
@@ -255,7 +253,6 @@
 	 * 3. Rows
 	 * 4. Flip frame, if available, otherwise; repeat.
 	 */
-	sei();
 	pwm_i++;
 	if (pwm_i >= ARRAY_SIZE(pwm_lengths)) {
 		pwm_i = 0;


version output on web console

version output on web console

--- FirmwareManager/src/FirmwareManager.ino
+++ FirmwareManager/src/FirmwareManager.ino
@@ -667,7 +667,7 @@
         root["conf_ip_mask"] = confIPMask;
         root["conf_ip_dns"] = confIPDNS;
         root["hostname"] = host;
-        root["fw_version"] = FW_VERSION;
+        root["fw_version"] = isRelaxedFirmware ? FW_VERSION "-rlx" : FW_VERSION "-std";
         root["video_resolution"] = configuredResolution;
         root["video_mode"] = videoMode;
         root["reset_mode"] = resetMode;


Brightness and contrast now software controlled

--- DigitalVFO.ino
+++ DigitalVFO.ino
@@ -2,7 +2,7 @@
 // A digital VFO using the DDS-60 card.
 //
 // The VFO will generate signals in the range 1.000000MHz to 30.000000MHz
-// with a step of 1Hz.
+// with a step ranging down to 1Hz.
 //
 // The interface will be a single rotary encoder with a built-in pushbutton.
 // The frequency display will have a 'selected' digit which can be moved left
@@ -16,12 +16,12 @@

 //#define RESET   // define if resetting all EEPROM data
-#define DEBUG   // define if debugging
+//#define DEBUG   // define if debugging

 // Digital VFO program name & version
 const char *ProgramName = "DigitalVFO";
-const char *Version = "0.7";
+const char *Version = "0.8";
 const char *Callsign = "vk4fawr";
 const char *Callsign16 = "vk4fawr         ";

@@ -46,6 +46,7 @@
 const int re_pinPush = 4;  // encoder pushbutton pin

 // define pin controlling contrast
+const byte mc_Brightness = 5;
 const byte mc_Contrast = 6;

 // max and min frequency showable
@@ -103,8 +104,9 @@
 #define vfo_Click     5
 #define vfo_HoldClick 6

-// default LCD contrast
-const int DefaultLcdContrast = 50;
+// default LCD contrast & brightness
+const int DefaultLcdContrast = 70;
+const int DefaultLcdBrightness = 150;

 ////////////////////////////////////////////////////////////////////////////////
@@ -120,7 +122,7 @@
 typedef byte VFOEvent;

 int LcdContrast;
-
+int LcdBrightness = 255;

 ////////////////////////////////////////////////////////////////////////////////
 // Utility routines
@@ -198,8 +200,8 @@
 // display a simple banner
 void banner(void)
 {
-  Serial.print(ProgramName); Serial.print(" "); Serial.println(Version);
-  Serial.println(Callsign);
+  Serial.print(ProgramName); Serial.print(" "); Serial.print(Version);
+  Serial.print(" ("); Serial.print(Callsign); Serial.println(")");
   lcd.clear();
   lcd.setCursor(0, 0);
   lcd.write(ProgramName);
@@ -279,7 +281,7 @@

 ////////////////////////////////////////////////////////////////////////////////
-// Code to handle the menus.
+// Code to handle the DigitalVFO menus.
 ////////////////////////////////////////////////////////////////////////////////

 // typedef for a menu display handler
@@ -290,23 +292,28 @@
 // this handles selecting a particular item
 typedef void (*MenuAction)(Menu *menu, int slot_num);

+//------------------------------------------
+// A structure defining a menu page.
+//
+// This structure is passed to show_menu().
 struct Menu
 {
-  const char *title;
-  MenuDisplay display;
-  MenuAction action;
-  int num_items;
-  const char **items;
+  const char *title;      // title displayed on menu page
+  MenuDisplay display;    // routine to draw the menu page
+  MenuAction action;      // routine called when a 'select' action is made
+  int num_items;          // number of selection items in the list
+  const char **items;     // list of poiunter to selction item text
 };

+// Draw a menu page from the passed "menu" structure.
 void show_menu(struct Menu *menu)
 {
-  int item_index = 0;
-
-  // update the menu display
+  int item_index = 0;     // draw the first item
+
+  // draw the menu page
   menu->display(menu, item_index);

-  flush_events();
+  flush_events();         // get rid of any stray events to this point

   while (true)
   {
@@ -641,11 +648,15 @@
 const int AddressContrast = AddressSelDigit + AddressSelDigitSize;
 const int AddressContrastSize = sizeof(LcdContrast);

+// address for byte 'brightness'
+const int AddressBrightness = AddressContrast + AddressContrastSize;
+const int AddressBrightnessSize = sizeof(LcdBrightness);
+
 // number of frequency save slots in EEPROM
 const int NumSaveSlots = 10;

 const int SaveFreqSize = sizeof(long);
-const int SaveFreqBase = AddressContrast + AddressContrastSize;
+const int SaveFreqBase = AddressBrightness + AddressBrightnessSize;
 const int SaveFreqBaseSize = NumSaveSlots * SaveFreqSize;

 //also save the offset for each frequency
@@ -659,8 +670,11 @@
 // save VFO state to EEPROM
 void save_to_eeprom(void)
 {
+  Serial.println("save_to_eeprom() called");
+
   EEPROM.put(AddressFreq, VfoFrequency);
   EEPROM.put(AddressSelDigit, VfoSelectDigit);
+  EEPROM.put(AddressBrightness, LcdBrightness);
   EEPROM.put(AddressContrast, LcdContrast);
 }

@@ -669,6 +683,7 @@
 {
   EEPROM.get(AddressFreq, VfoFrequency);
   EEPROM.get(AddressSelDigit, VfoSelectDigit);
+  EEPROM.get(AddressBrightness, LcdBrightness);
   EEPROM.get(AddressContrast, LcdContrast);
 }

@@ -693,18 +708,21 @@
 }

 // print all EEPROM saved data to console
-void dump_eeprom()
+void dump_eeprom(void)
 {
   Frequency ulong;
   SelOffset offset;
+  int brightness;
   int contrast;

   EEPROM.get(AddressFreq, ulong);
   EEPROM.get(AddressSelDigit, offset);
+  EEPROM.get(AddressBrightness, brightness);
   EEPROM.get(AddressContrast, contrast);
   Serial.println("=================================================");
   Serial.print("dump_eeprom: VfoFrequency="); Serial.println(ulong);
   Serial.print("             AddressSelDigit="); Serial.println(offset);
+  Serial.print("             LcdBrightness="); Serial.println(brightness);
   Serial.print("             LcdContrast="); Serial.println(contrast);

   for (int i = 0; i < NumSaveSlots; ++i)
@@ -750,6 +768,7 @@
   // zero the frequency+selected values
   VfoFrequency = MIN_FREQ;
   VfoSelectDigit = 0;
+  LcdBrightness = DefaultLcdBrightness;
   LcdContrast = DefaultLcdContrast;

   save_to_eeprom();
@@ -775,28 +794,34 @@
   lcd.noCursor();
   lcd.createChar(SPACE_CHAR, sel_digits[SPACE_INDEX]);

-  // initialize contrast control
+  pinMode(mc_Brightness, OUTPUT);
   pinMode(mc_Contrast, OUTPUT);
-  analogWrite(mc_Contrast, DefaultLcdContrast);

   // get state back from EEPROM
   restore_from_eeprom();
+  analogWrite(mc_Brightness, LcdBrightness);
+  analogWrite(mc_Contrast, LcdContrast);

   // set up the rotary encoder
   re_setup(VfoSelectDigit);

   // show program name and version number
-#ifndef DEBUG
   banner();
   if (pop_event() == vfo_HoldClick)
-    Serial.println("Would reset here");
-#endif
+  {
+    LcdBrightness = DefaultLcdBrightness;
+    LcdContrast = DefaultLcdContrast;
+    Serial.print("Reset brightness to "); Serial.print(LcdBrightness);
+    analogWrite(mc_Brightness, LcdBrightness);
+    Serial.print(" and contrast to "); Serial.println(LcdContrast);
+    analogWrite(mc_Contrast, LcdContrast);
+  }

   // we sometimes see random events on powerup, flush them here
   flush_events();

+#ifdef DEBUG
   // dump EEPROM values
-#ifdef DEBUG
   dump_eeprom();
 #endif

@@ -822,31 +847,34 @@
 const char *menu_items[] = {"Save slot", "Restore slot", "Delete slot", "Settings"};
 #define NumMainMenuItems (sizeof(menu_items)/sizeof(const char *))

-Menu main_menu = {"Menu", menu_display, menu_select,
-                  NumMainMenuItems, menu_items};
-
-Menu save_menu = {menu_items[0], savresdel_display, save_select,
-                  NumSaveSlots, NULL};
-
-Menu restore_menu = {menu_items[1], savresdel_display, restore_select,
-                     NumSaveSlots, NULL};
-
-Menu delete_menu = {menu_items[2], savresdel_display, delete_select,
-                    NumSaveSlots, NULL};
+struct Menu main_menu = {"Menu", menu_display, menu_select,
+                         NumMainMenuItems, menu_items};
+
+struct Menu save_menu = {menu_items[0], savresdel_display, save_select,
+                         NumSaveSlots, NULL};
+
+struct Menu restore_menu = {menu_items[1], savresdel_display, restore_select,
+                            NumSaveSlots, NULL};
+
+struct Menu delete_menu = {menu_items[2], savresdel_display, delete_select,
+                           NumSaveSlots, NULL};

 const char *settings_items[] = {"Brightness", "Contrast"};
 #define NumSettingsMenuItems (sizeof(settings_items)/sizeof(const char *))

-Menu settings_menu = {menu_items[3], menu_display, settings_select,
-                      NumSettingsMenuItems, settings_items};
-
-const char *contrast_items[] = {"Decrease", "Increase"};
-#define NumContrastMenuItems (sizeof(settings_items)/sizeof(const char *))
-
-Menu contrast_menu = {settings_items[1], menu_display, contrast_select,
-                      NumContrastMenuItems, contrast_items};
-
-void menu_display(Menu *menu, int slot_num)
+struct Menu settings_menu = {menu_items[3], menu_display, settings_select,
+                             NumSettingsMenuItems, settings_items};
+
+const char *inc_dec_items[] = {"Increase", "Decrease"};
+#define NumIncDecMenuItems (sizeof(inc_dec_items)/sizeof(const char *))
+
+struct Menu brightness_menu = {settings_items[0], menu_display, brightness_select,
+                               NumIncDecMenuItems, inc_dec_items};
+
+struct Menu contrast_menu = {settings_items[1], menu_display, contrast_select,
+                             NumIncDecMenuItems, inc_dec_items};
+
+void menu_display(struct Menu *menu, int slot_num)
 {
   // figure out max length of item strings
   int max_len = 0;
@@ -870,7 +898,7 @@
   lcd.write(menu->items[slot_num]);
 }

-void menu_select(Menu *menu, int slot_num)
+void menu_select(struct Menu *menu, int slot_num)
 {
   const char *action_text = menu->items[slot_num];

@@ -901,7 +929,7 @@
 }

 // draw the Save, Restore or Delete screen
-void savresdel_display(Menu *menu, int slot_num)
+void savresdel_display(struct Menu *menu, int slot_num)
 {
   Frequency freq;
   SelOffset offset;
@@ -948,7 +976,7 @@
   lcd.display();
 }

-void save_select(Menu *menu, int slot_num)
+void save_select(struct Menu *menu, int slot_num)
 {
   // display an 'action flash'
   action_flash();
@@ -958,7 +986,7 @@
   savresdel_display(menu, slot_num);
 }

-void restore_select(Menu *menu, int slot_num)
+void restore_select(struct Menu *menu, int slot_num)
 {
   // display an 'action flash'
   action_flash();
@@ -968,7 +996,7 @@
   savresdel_display(menu, slot_num);
 }

-void delete_select(Menu *menu, int slot_num)
+void delete_select(struct Menu *menu, int slot_num)
 {
   // display an 'action flash'
   action_flash();
@@ -978,27 +1006,56 @@
   savresdel_display(menu, slot_num);
 }

-void settings_select(Menu *menu, int slot_num)
+void settings_select(struct Menu *menu, int slot_num)
 {
   Serial.print("settings_select() called, slot_num="); Serial.println(slot_num);
-  show_menu(&contrast_menu);
-}
-
-void contrast_select(Menu *menu, int slot_num)
-{
   if (slot_num == 0)
-      LcdContrast += 5;
+      show_menu(&brightness_menu);
   else if (slot_num == 1)
-      LcdContrast -= 5;
+      show_menu(&contrast_menu);
+}
+
+void contrast_select(struct Menu *menu, int slot_num)
+{
+  Serial.print("contrast_select(): slot_num="); Serial.println(slot_num);
+
+  // adjust contrast
+  // +/- opposite to that for brightness because increasing
+  // voltage has the opposite effect with contrast
+  if (slot_num == 0)        // "increase" item selected
+    LcdContrast -= 10;
+  else if (slot_num == 1)   // "decrease" item selected
+    LcdContrast += 10;
   else
-    abort("Bad slot numvber");
+    abort("Bad slot number");

   if (LcdContrast < 0)
     LcdContrast = 0;
   if (LcdContrast > 125)
     LcdContrast = 125;
   analogWrite(mc_Contrast, LcdContrast);
-  save_to_eeprom();
+  Serial.print("Set contrast to "); Serial.println(LcdContrast);
+  action_flash();
+}
+
+void brightness_select(struct Menu *menu, int slot_num)
+{
+  Serial.print("brightness_select(): slot_num="); Serial.println(slot_num);
+
+  if (slot_num == 0)        // "increase" item selected
+    LcdBrightness += 10;
+  else if (slot_num == 1)   // "increase" item selected
+    LcdBrightness -= 10;
+  else
+    abort("Bad slot numvber");
+
+  if (LcdBrightness < 0)
+    LcdBrightness = 0;
+  if (LcdBrightness > 255)
+    LcdBrightness = 255;
+
+  analogWrite(mc_Brightness, LcdBrightness);
+  Serial.print("Set brightness to "); Serial.println(LcdBrightness);
   action_flash();
 }

@@ -1054,8 +1111,7 @@
       case vfo_HoldClick:
         Serial.println("Got vfo_HoldClick: calling show_menu()");
         show_menu(&main_menu);
-//        save_to_eeprom();
-        dump_queue("After show_menu()");
+        save_to_eeprom();  // save any changes made in the menu syste,
         show_main_screen();
         break;
       default:


record max speed in EEPROM

record max speed in EEPROM

--- ScooterSpeedo.ino
+++ ScooterSpeedo.ino
@@ -13,6 +13,7 @@
 */

 #include <math.h>
+#include <EEPROM.h>
 #include <LiquidCrystal.h>
 #include <Wire.h>
 #include <Adafruit_MMA8451.h>
@@ -23,6 +24,10 @@
 const double WHEEL_CIRCUMFERENCE = 2 * WHEEL_RADIUS * PI;
 double kph = 0.0;
 double mph = 0.0;
+
+// Read the max recorded KPH and store it in memory
+const int MAX_RECORD_KPH_ADDRESS = 0;
+double maxRecordKph = 0.0;

 // Hall effect sensor read pin, make it an interrupt pin so we catch all revolutions
 const byte HALL_SENSOR = 2;
@@ -73,6 +78,20 @@

   delay(2000);
   lcd.clear();
+
+  EEPROM.get(MAX_RECORD_KPH_ADDRESS, maxRecordKph);
+  if (isnan(maxRecordKph)) {
+    maxRecordKph = 0.0;
+  }
+
+  lcd.print("Max kph: ");
+  lcd.print(maxRecordKph);
+  lcd.setCursor(0,1);
+  lcd.print("Max mph: ");
+  lcd.print(kphToMph(maxRecordKph));
+
+  delay(2000);
+  lcd.clear();
 }

 void loop() {
@@ -118,9 +137,29 @@
   if (isnan(cmps)) {
     cmps = 0.0;
   }
-  return cmps/10000.0 * 360.0;
+  double k = cmps/10000.0 * 360.0;
+  if (k > maxRecordKph) {
+    noInterrupts();
+    maxRecordKph = k;
+    lcd.print("New Max!");
+    lcd.setCursor(0,1);
+    lcd.print(k);
+    lcd.print("kph");
+    setMaxSpeed(k);
+    interrupts();
+    delay(1000);
+  }
+  return k;
 }

 double calculateMPH() {
-   return kph * 1.6093;
+   return kphToMph(kph);
 }
+
+double kphToMph(double k) {
+  return k * 1.6093;
+};
+
+void setMaxSpeed(double k) {
+  EEPROM.put(MAX_RECORD_KPH_ADDRESS, k);
+}


Added better altitude calculation

Added better altitude calculation

--- OpenRocket.ino
+++ OpenRocket.ino
@@ -385,7 +385,7 @@
     temperature = bmp085GetTemperature(bmp085ReadUT());
     pressure = bmp085GetPressure(bmp085ReadUP());
     //atm = pressure / 101325;
-    alti = calcAltitude(pressure);
+    alti = calcAltitude(pressure, getKelvin(temperature));
     //dtostrf(floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, charBuf);
     Serial.print("Time: "); Serial.println(timestamp);
     //Serial.print("Temp: "); Serial.print(temperature, 2); Serial.println(" C");
@@ -570,8 +570,8 @@
   Wire.endTransmission();     // end transmission
 }

-int readRegister(int deviceAddress, byte address){
-
+int readRegister(int deviceAddress, byte address)
+{
   int v;
   Wire.beginTransmission(deviceAddress);
   Wire.write(address); // register to read
@@ -587,13 +587,39 @@
   return v;
 }

-float calcAltitude(float pressure){
-
-  float A = pressure/101325;
-  float B = 1/5.25588;
-  float C = pow(A,B);
-  C = 1 - C;
-  C = C /0.0000225577;
-
-  return C;
-}
+float calcAltitude(float pressure, float temperature)
+{
+  static float p0 = 0;
+  static float pressArray[] = {0, 0, 0, 0, 0};
+
+  if (p0 == 0)
+  {
+    for (int i = 0; i < 5; i++)
+    {
+      if (pressArray[i] == 0)
+      {
+        pressArray[i] = pressure;
+
+        if (i == 4)
+        {
+          p0 = (pressArray[0]+pressArray[1]+pressArray[2]+pressArray[3]+pressArray[4])/5;
+        }
+        break;
+      }
+    }
+  }
+
+  if (p0 != 0)
+  {
+    return (-29.4289 * temperature * log(pressure/p0));
+  }
+  else
+  {
+    return 0;
+  }
+}
+
+float getKelvin(float celsius)
+{
+  return celsius + 273.15;
+}


modified:   mcu_main/mcu_main.ino

modified:   mcu_main/mcu_main.ino

--- mcu_main/mcu_main.ino
+++ mcu_main/mcu_main.ino
@@ -33,6 +33,8 @@
   Serial.begin(9600);
 }

+
+
 void loop()
 {
   String cmd;
@@ -54,18 +56,12 @@

   if(cmd.length() > 3)
-  {
-//    State state;
-//    state.spd     =  cmd[1];
-//    state.steps   =  cmd[2]<<8  +  cmd[3];
-//    state.running =  true;
-//    state.cw      =  cmd[0]  &  0x01;
-
-  State state;
-  state.spd = cmd[1];
-  state.steps = cmd[2];
-  state.running = true;
-  state.cw = true;
+  {
+    State state;
+    state.spd = cmd[1] * 5;
+    state.steps =  cmd[3] + (cmd[2] << 8);
+    state.running = true;
+    state.cw = cmd[0] & 0x01;

     wave(&state);
   }


displayCalStatus changes to OLED

displayCalStatus changes to OLED

--- test/Arduino/MicroView/MicroView_ino/MicroView_ino.ino
+++ test/Arduino/MicroView/MicroView_ino/MicroView_ino.ino
@@ -135,22 +135,46 @@
   system = gyro = accel = mag = 0;
   bno.getCalibration(&system, &gyro, &accel, &mag);

+
   /* The data should be ignored until the system calibration is > 0 */
-  Serial.print("\t");
+  //Serial.print("\t");
   if (!system)
   {
-    Serial.print("! ");
+    uView.clear(PAGE);
+    uView.setCursor(0, 0*fontHeight);
+    uView.print("Waiting...");
+    // show it
+    uView.display();
   }

-  /* Display the individual values */
-  Serial.print("Sys:");
-  Serial.print(system, DEC);
-  Serial.print(" G:");
-  Serial.print(gyro, DEC);
-  Serial.print(" A:");
-  Serial.print(accel, DEC);
-  Serial.print(" M:");
-  Serial.print(mag, DEC);
+
+  uView.clear(PAGE);
+
+  uView.setCursor(0, 0*fontHeight);
+  uView.print("Callibrat:");
+
+  // Sys
+  uView.setCursor(0, 1*fontHeight);
+  uView.print("Sys:  ");
+  uView.print(system, DEC);
+
+  // Gyrocope
+  uView.setCursor(0, 2*fontHeight);
+  uView.print("Gyro: ");
+  uView.print(gyro, DEC);
+
+  // Accelerometer
+  uView.setCursor(0, 3*fontHeight);
+  uView.print("Accel:");
+  uView.print(accel, DEC);
+
+  // Magnetometer
+  uView.setCursor(0, 4*fontHeight);
+  uView.print("Mag:  ");
+  uView.print(mag, DEC);
+
+  // show it
+  uView.display();
 }

@@ -207,46 +231,18 @@

 void loop(void)
 {
-  /*
-  // MicroView
-   // TEXT Font 0
-   uView.clear(PAGE);
-   uView.setCursor(0,40);
-   uView.print("  Font 0  ");
-   uView.display();
-
-   uView.setFontType(0);
-   uView.setCursor(0,0);
-   uView.print("01234567890ABCDabcd01234567890ABCDabcd");
-   uView.display();
-   delay(1500);
-
-
-   // TEXT Font 1
-   uView.clear(PAGE);
-   uView.setCursor(0,40);
-   uView.print("  Font 1  ");
-   uView.display();
-
-   uView.setFontType(1);
-   uView.setCursor(0,0);
-   uView.print("0123ABCDabcd");
-   uView.display();
-   delay(1500);
-   uView.clear(PAGE);
-   */
-
   /* Get a new sensor event */
   sensors_event_t event;
   bno.getEvent(&event);

-  /* Display the floating point data */
+  /* Display the floating point data * /
   Serial.print("X: ");
   Serial.print(event.orientation.x, 4);
   Serial.print("\tY: ");
   Serial.print(event.orientation.y, 4);
   Serial.print("\tZ: ");
   Serial.print(event.orientation.z, 4);
+*/

   /* Optional: Display calibration status */
   displayCalStatus();
@@ -254,9 +250,6 @@
   /* Optional: Display sensor status (debug only) */
   //displaySensorStatus();

-  /* New line for the next sample */
-  Serial.println("");
-
   /* Wait the specified delay before requesting nex data */
   delay(BNO055_SAMPLERATE_DELAY_MS);
 }


Update SimpleXbeeRX64.ino

Update SimpleXbeeRX64.ino

--- Arduino/SimpleXbeeRX64.ino
+++ Arduino/SimpleXbeeRX64.ino
@@ -22,7 +22,7 @@
 uint8_t  lengthSegLow;

 // We only get one LED to play with
-int statusLed 	 = 6;
+int statusLed 	   = 6;
 int errorLed 	   = 6;

 HardwareSerial Uart = HardwareSerial();


TW-50: Started working on simple background that changes based on what time it is currently.

--- tinywatch.ino
+++ tinywatch.ino
@@ -10,6 +10,9 @@
 //Buffer used for drawing.
 RenderBuffer<uint16_t,20> buffer;
 char isTimeSet = 0;
+//Temp sleep
+char isSleep = 1;
+

 //Pinouts for TinyShield BLE.
 #define BLE_REQ 10
@@ -60,21 +63,29 @@
   BLECentral central = blePeripheral.central();
   if(central && central.connected()){
     if(isTimeSet){
+      renderBackground();
       renderTime();
       renderDate();
+      refreshScreen();
     }
   } else{
-    messageWithSecondDelay("searching...");
+    messageWithSecondDelay("Searching...");
   }
-  refreshScreen();
+
+  //temp sleep
+  isSleep ? display.on() : display.off();
+  if(display.getButtons(TSButtonUpperLeft)){
+    isSleep = isSleep ? 0 : 1;
+    delay(250);
+  }
 }

 void blePeripheralConnectHandler(BLECentral& central) {
-  messageWithSecondDelay("connected...");
+  messageWithSecondDelay("Connected...");
 }

 void blePeripheralDisconnectHandler(BLECentral& central) {
-  messageWithSecondDelay("disconnected...");
+  messageWithSecondDelay("Disconnected...");
 }

 void setTimeHandler(BLECentral& central, BLECharacteristic& characteristic){
@@ -101,7 +112,32 @@
   buffer.drawText(stringBuffer.start().putDec(month()).put("-").putDec(day()).put("-").putDec(year()).get(),24,34,buffer.rgb(255,255,255), &liberationSans_8ptFontInfo);
 }

-//TODO: Method to render background.
+void renderBackground(){
+  //Dawn
+  if (hour(), 7)
+    buffer.drawRect(0,0,96,64)->filledRect(buffer.rgb(98,90,70));
+  if (hour(),8)
+    buffer.drawRect(0,0,96,64)->filledRect(buffer.rgb(95,40,20));
+  if (hour(), 9)
+    buffer.drawRect(0,0,96,64)->filledRect(buffer.rgb(88, 57, 30));
+  if (hour(),10)
+    buffer.drawRect(0,0,96,64)->filledRect(buffer.rgb(100, 97, 100));
+  if (hour(),11)
+    buffer.drawRect(0,0,96,64)->filledRect(buffer.rgb(100, 100, 100));
+  //Sun
+  if (hour(),12)
+    buffer.drawRect(0,0,96,64)->filledRect(buffer.rgb(100, 100, 97));
+  if (hour(),13)
+    buffer.drawRect(0,0,96,64)->filledRect(buffer.rgb(100, 100, 100));
+  //Dusk
+  if (hour(),20)
+    buffer.drawRect(0,0,96,64)->filledRect(buffer.rgb(97,85,56));
+  //Night
+  if (hour(),21)
+    buffer.drawRect(0,0,96,64)->filledRect(buffer.rgb(0, 0, 0));
+  //Ocean
+  buffer.drawRect(0,48,94,16)->filledRect(buffer.rgb(28, 107, 160));
+}

 //TODO: Method to render orientation.


Dynamically play the song based on the color

--- EmotionalClothing.ino
+++ EmotionalClothing.ino
@@ -72,10 +72,33 @@
   Serial.print(" S: "); Serial.print(hsl[1]);
   Serial.print(" L: "); Serial.print(hsl[2]); Serial.println();

+  int hue = hsl[0];
+  double saturation = hsl[1];
+  double light = hsl[2];
+
   root.rewind();
   FatReader file;

-  file.open(root, "MACNTOSH.WAV");
+  if (light < 0.2) {                // Black
+    file.open(root, "gmechngd.wav");
+  } else if (light > 0.8) {         // White
+    file.open(root, "avemaria.wav");
+  } else if (saturation < 0.25) {   // Gray
+    file.open(root, "veridquo.wav");
+  } else if (hue < 10) {            // Red
+    file.open(root, "nitefate.wav");
+  } else if (hue < 40) {            // Orange
+    file.open(root, "mariothm.wav");
+  } else if (hue < 90) {            // Yellow
+    file.open(root, "wiishopc.wav");
+  } else if (hue < 150) {           // Green
+    file.open(root, "swedenmc.wav");
+  } else if (hue < 270) {           // Blue
+    file.open(root, "animcros.wav");
+  } else if (hue < 330) {           // Magenta
+    file.open(root, "wndrland.wav");
+  } else file.open(root, "nitefate.wav"); // Red
+
   if (!wave.create(file)) Serial.println("Can't open the file");
   wave.play();
   while(wave.isplaying) delay(100);


Add support for Moonbase board

Add support for Moonbase board

--- SimpleClientDHTSSL.ino
+++ SimpleClientDHTSSL.ino
@@ -1,3 +1,4 @@
+#define MOONBASE_BOARD
 /* WeMos DHT Server
  *
  * Connect to WiFi and respond to http requests with temperature and humidity
@@ -11,21 +12,32 @@

 #include <ESP8266WiFi.h>
 #include <WiFiClientSecure.h>
+
+
+#ifdef MOONBASE_BOARD
+#include <Wire.h>
+#include <HTS221.h>
+#include <LPS25H.h>
+
+#else
 #include <DHT.h>
-
 #define DHTTYPE DHT22   // DHT Shield uses DHT 11
 #define DHTPIN D4       // DHT Shield uses pin D4
+#endif

 //const char* DEVNAME = "VCW100” ; const char* ISSUEID  = “ZGKL01”; const char* ssid = ""; const char* password = “”;

 IPAddress server(120,138,27,109);

+#ifdef MOONBASE_BOARD
+#else
 // Initialize DHT sensor
 // Note that older versions of this library took an optional third parameter to
 // tweak the timings for faster processors.  This parameter is no longer needed
 // as the current DHT reading algorithm adjusts itself to work on faster procs.
 DHT dht(DHTPIN, DHTTYPE);
+#endif

 float humidity, temperature;                 // Raw float values from the sensor
 char str_humidity[10], str_temperature[10];  // Rounded sensor values and as strings
@@ -49,14 +61,20 @@
     // Save the last time you read the sensor
     previousMillis = currentMillis;

+#ifdef MOONBASE_BOARD
+    humidity = smeHumidity.readHumidity();
+    temperature = smeHumidity.readTemperature();
+    pressure = smePressure.readTemperature();
+#else
     // Reading temperature and humidity takes about 250 milliseconds!
     // Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor)
     humidity = dht.readHumidity();        // Read humidity as a percent
     temperature = dht.readTemperature();  // Read temperature as Celsius
+#endif

     // Check if any reads failed and exit early (to try again).
     if (isnan(humidity) || isnan(temperature)) {
-      Serial.println("Failed to read from DHT sensor!");
+      Serial.println("Failed to read from sensors!");
       return;
     }

@@ -64,6 +82,11 @@
     dtostrf(humidity, 1, 2, str_humidity);
     dtostrf(temperature, 1, 2, str_temperature);

+#ifdef MOONBASE_BOARD
+    dtostrf(pressure, 1, 2, str_pressure);
+    Serial.print("Pressure: ");
+    Serial.print(str_Pressure);
+#endif
     Serial.print("Humidity: ");
     Serial.print(str_humidity);
     Serial.print(" %\t");
@@ -113,9 +136,16 @@
 {
   // Open the Arduino IDE Serial Monitor to see what the code is doing
   Serial.begin(115200);
+#ifdef MOONBASE_BOARD
+    Wire.begin();
+    smePressure.begin();
+    smeHumidity.begin();
+    Serial.println("VCW sensor Server");
+#else
   dht.begin();
-
   Serial.println("WeMos DHT Server");
+#endif
+
   _ESP_id = ESP.getChipId();  // uint32 -> unsigned long on arduino
   Serial.println(_ESP_id,HEX);
   Serial.println("");
@@ -132,7 +162,12 @@
   delay(60000);
   read_sensor();

-  if (WiFiState == UP) { httpsRequest(temperature,humidity); }
+  if (WiFiState == UP)
+#ifdef MOONBASE_BOARD
+  	{ httpsRequest(temperature,humidity, pressure); }
+#else
+  	{ httpsRequest(temperature,humidity); }
+#endif

   // Connect to your WiFi network
   if (WiFiState == DOWN) {
@@ -151,7 +186,11 @@

 // this method makes a HTTP connection to the server:
-void httpRequest(float temp, float humid) {
+void httpRequest(float temp, float humid
+#ifdef MOONBASE_BOARD
+, float pressure
+#endif
+) {

   // Use WiFiClient class to create TCP connections
   WiFiClient client;
@@ -172,6 +211,10 @@
   url += temp;
   url += "&indoorhumidity=";
   url += humid;
+#ifdef MOONBASE_BOARD
+  url += "&indoorpressure=";
+  url += pressure;
+#endif

   Serial.print("Requesting URL: ");
@@ -212,7 +255,11 @@
 const char* fingerprint = "CF 05 98 89 CA FF 8E D8 5E 5C E0 C2 E4 F7 E6 C3 C7 50 DD 5C";

 // this method makes a HTTP connection to the server:
-void httpsRequest(float temp, float humid) {
+void httpsRequest(float temp, float humid
+#ifdef MOONBASE_BOARD
+, float pressure
+#endif
+) {

   // Use WiFiClientSecure class to create TLS connection
   WiFiClientSecure client;
@@ -241,6 +288,10 @@
   url += temp;
   url += "&indoorhumidity=";
   url += humid;
+#ifdef MOONBASE_BOARD
+  url += "&indoorpressure=";
+  url += pressure;
+#endif


Deleted

Deleted

--- Slidebright.ino
+++ Slidebright.ino
@@ -1,953 +0,0 @@
-/*
-** SlideBright - Firmware for the overengineered Hexbright flashlight.
-**               Hexbright: http://hexbright.com/
-**                                ~ Tobias Jäger <Tobias.Jaeger@slidetex.de>
-**
-**
-** Based on darcbright by Robert Quattlebaum <darco@deepdarc.com>
-**
-** List of Modes:
-**  * 3-brightnesse-level mode (43,175,500)
-**  * momentary mode
-**  * strobe mode
-**  * ajust-brightness-by-roll mode
-*/
-
-/*
-Accelorometer axies:
-
-(x,y,z)
-
-If the flashlight is facing straight up:
-  (0, 21, 0)
-
-If the flashlight is facing straight down:
-  (0, -21, 0)
-
-If the flashlight is battery-up:
-  (0, 0, -21)
-
-If the flashlight is battery-down:
-  (0, 0, 21)
-
-If the flashlight is logo-up:
-  (-21, 0, 0)
-
-If the flashlight is logo-down:
-  (21, 0, 0)
-
-*/
-
-#include <math.h>
-#include <Wire.h>
-#include <EEPROM.h>
-#include "pt.h"
-#include <avr/wdt.h>
-
-// Settings
-#define VOLTAGE_NOMINAL               3330
-#define VOLTAGE_LOW                   3100
-#define OVERTEMP_SHUTDOWN_C           60
-#define OVERTEMP_THROTTLE_C           50
-#define OVERTEMP_SHUTDOWN             (OVERTEMP_SHUTDOWN_C*10+500)
-#define OVERTEMP_THROTTLE             (OVERTEMP_THROTTLE_C*10+500)
-#define BUTTON_BRIGHTNESS_THRESHOLD   1000 // time in ms, after which a button press turns off
-#define BUTTON_DEBOUNCE               20
-#define POWER_ON_BUTTON_THRESHOLD     150 // Period of time button initially needs to be held to keep the light on.
-
-#define BRT_MIN_LUMEN          4
-#define BRT_MED_LUMEN          255                        // 175 lumens
-#define BRT_LOW_LUMEN          (BRT_MED_LUMEN/4)            // 43 lumens
-#define BRT_MAX_LUMEN          (BRT_MED_LUMEN+(3*255))    // 500 lumens
-
-
-
-// Constants
-#define ACC_ADDRESS             0x4C
-#define ACC_REG_XOUT            0
-#define ACC_REG_YOUT            1
-#define ACC_REG_ZOUT            2
-#define ACC_REG_TILT            3
-#define ACC_REG_INTS            6
-#define ACC_REG_MODE            7
-
-// Pin assignments
-#define DPIN_RLED_SW            2
-#define DPIN_GLED               5
-#define DPIN_PWR                8
-#define DPIN_DRV_MODE           9
-#define DPIN_DRV_EN             10
-#define DPIN_ACC_INT            3
-#define APIN_TEMP               0
-#define APIN_CHARGE             3
-
-// Interrupts
-#define INT_SW                  0
-#define INT_ACC                 1
-
-// State
-byte light_mode;
-unsigned short overtemp_max;
-unsigned short amount_current;
-unsigned short amount_begin;
-unsigned short amount_end;
-unsigned short amount_fade_duration;
-unsigned long amount_fade_start;
-byte amount_flash,amount_off;
-
-// Protothread States
-struct pt fade_control_pt;
-struct pt power_pt;
-struct pt button_led_pt;
-
-// Mode Protothread States
-struct pt light_pt;
-struct pt light_momentary_pt;
-struct pt light_blinky_pt;
-struct pt light_knob_pt;
-
-// Variables updated every loop
-bool button_is_pressed;
-unsigned long button_pressed_time;
-unsigned long button_released_time;
-unsigned long button_pressed_duration;
-unsigned long button_released_duration;
-short vcc_current;
-short vcc_filter_table[3];
-short vcc_filtered;
-short temp_filter_table[3];
-short temp_filtered;
-short temp_current;
-enum {
-    BATT_DISCHARGING,
-    BATT_CHARGING,
-    BATT_CHARGED,
-} batt_state;
-unsigned long time_current;
-float angle_pitch;
-float angle_roll;
-
-#define PT_WAIT_FOR_PERIOD(pt,x) \
-    lastTime =  time_current; \
-    PT_WAIT_UNTIL(pt, (time_current-lastTime) > (x));
-
-bool orientation_enabled;
-
-void
-enable_orientation(void) {
-  pinMode(DPIN_ACC_INT,  INPUT);
-  digitalWrite(DPIN_ACC_INT,  HIGH);
-
-  // Configure accelerometer
-  static const byte config[] = {
-    ACC_REG_INTS,  // First register (see next line)
-    0xE4,  // Interrupts: shakes, taps
-    0x00,  // Mode: not enabled yet
-    0x00,  // Sample rate: 120 Hz
-    0x0F,  // Tap threshold
-    0x10   // Tap debounce samples
-  };
-  Wire.beginTransmission(ACC_ADDRESS);
-  Wire.write(config, sizeof(config));
-  Wire.endTransmission();
-
-  // Enable accelerometer
-  static const byte enable[] = {ACC_REG_MODE, 0x01};  // Mode: active!
-  Wire.beginTransmission(ACC_ADDRESS);
-  Wire.write(enable, sizeof(enable));
-  Wire.endTransmission();
-
-  orientation_enabled = 1;
-}
-
-void
-update_loop_variables(void) {
-  static char i;
-
-  // Time stamp for this loop cycle.
-  time_current = millis();
-
-  // Grab the voltage and the temperature.
-  vcc_filter_table[i] = vcc_current = readVcc();
-  temp_filter_table[i] = analogRead(APIN_TEMP);
-
-  temp_current = temp_filter_table[i]*(long)vcc_current/1024;
-
-  vcc_filtered = median_short(vcc_filter_table[0],vcc_filter_table[1],vcc_filter_table[2]);
-
-  temp_filtered *= 7;
-  temp_filtered += median_short(temp_filter_table[0],temp_filter_table[1],temp_filter_table[2])*(long)vcc_filtered/1024;
-  temp_filtered /= 8;
-
-  if(++i==3)
-    i=0;
-
-  // Read out the state of but button.
-  {
-    bool prev_value = digitalRead(DPIN_RLED_SW);
-    pinMode(DPIN_RLED_SW,  INPUT);
-    digitalWrite(DPIN_RLED_SW, 0);
-    button_is_pressed = digitalRead(DPIN_RLED_SW);
-    pinMode(DPIN_RLED_SW,  OUTPUT);
-    digitalWrite(DPIN_RLED_SW, prev_value);
-  }
-
-  if(button_is_pressed) {
-    button_released_time = time_current;
-    button_pressed_duration = time_current - button_pressed_time;
-  } else {
-    button_pressed_time = time_current;
-    button_released_duration = time_current - button_released_time;
-    button_pressed_duration = 0;
-  }
-
-  short chargeState = analogRead(APIN_CHARGE);
-
-  if (chargeState < 128) {  // Low - charging
-    batt_state = BATT_CHARGING;
-  } else if (chargeState > 768) {  // High - fully charged.
-    batt_state = BATT_CHARGED;
-  } else {  // Hi-Z - Not charging, not pulged in.
-    // But if the voltage is over 3.4 volts, then we know we are plugged in.
-    if(vcc_current>3400)
-      batt_state = BATT_CHARGING;
-    else
-      batt_state = BATT_DISCHARGING;
-  }
-
-  if(orientation_enabled) {
-    char acc[3];
-    readAccelFiltered(acc);
-    angle_roll = atan2(acc[0],acc[2]);
-    angle_pitch = atan2(acc[1],sqrt(acc[0]*acc[0]+acc[2]*acc[2]));
-  }
-
-  // Check if the accelerometer wants to interrupt
-//  byte tapped = 0, shaked = 0;
-//  if (!digitalRead(DPIN_ACC_INT)) {
-//    Wire.beginTransmission(ACC_ADDRESS);
-//    Wire.write(ACC_REG_TILT);
-//    Wire.endTransmission(false);       // End, but do not stop!
-//    Wire.requestFrom(ACC_ADDRESS, 1);  // This one stops.
-//    byte tilt = Wire.read();
-//
-//    if (time-lastAccTime > 500) {
-//      lastAccTime = time;
-//
-//      tapped = !!(tilt & 0x20);
-//      shaked = !!(tilt & 0x80);
-//
-//      if (tapped) Serial.println("Tap!");
-//      if (shaked) Serial.println("Shake!");
-//    }
-//  }
-}
-
-
-short
-readVcc(void) {
-  short result;
-  // Read 1.1V reference against AVcc
-  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
-  delay(2); // Wait for Vref to settle
-  noInterrupts();
-  ADCSRA |= _BV(ADSC); // Convert
-  while (bit_is_set(ADCSRA,ADSC));
-  interrupts();
-  result = ADCL;
-  result |= ADCH<<8;
-  result = 1126400L / result; // Back-calculate AVcc in mV
-  return result;
-}
-
-void readAccel(char *acc)
-{
-  while (1)
-  {
-    Wire.beginTransmission(ACC_ADDRESS);
-    Wire.write(ACC_REG_XOUT);
-    Wire.endTransmission(false);       // End, but do not stop!
-    Wire.requestFrom(ACC_ADDRESS, 3);  // This one stops.
-
-    for (int i = 0; i < 3; i++)
-    {
-      if (!Wire.available())
-        continue;
-      acc[i] = Wire.read();
-      if (acc[i] & 0x40)  // Indicates failed read; redo!
-        continue;
-      if (acc[i] & 0x20)  // Sign-extend
-        acc[i] |= 0xC0;
-    }
-    break;
-  }
-}
-
-void readAccelFiltered(char *acc_filtered) {
-  static char acc[3][3];
-  static char i;
-  readAccel(acc[i++]);
-  if(i==3)
-    i=0;
-  acc_filtered[0] = median_char(acc[0][0],acc[1][0],acc[2][0]);
-  acc_filtered[1] = median_char(acc[0][1],acc[1][1],acc[2][1]);
-  acc_filtered[2] = median_char(acc[0][2],acc[1][2],acc[2][2]);
-}
-
-
-/* Returns the median value of the given three parameters */
-char median_char(char a, char b, char c) {
-    if(a<c) {
-        if(b<a) {
-            return a;
-        } else if(c<b) {
-            return c;
-        }
-    } else {
-        if(a<b) {
-            return a;
-        } else if(b<c) {
-            return c;
-        }
-    }
-    return b;
-}
-short median_short(short a, short b, short c) {
-    if(a<c) {
-        if(b<a) {
-            return a;
-        } else if(c<b) {
-            return c;
-        }
-    } else {
-        if(a<b) {
-            return a;
-        } else if(b<c) {
-            return c;
-        }
-    }
-    return b;
-}
-
-
-void
-retrieve_settings(void) {
-  byte data[4];
-  data[0] = EEPROM.read(0);
-  data[1] = EEPROM.read(1);
-  data[2] = EEPROM.read(2);
-  data[3] = EEPROM.read(3);
-  if(data[0] == (byte)~(data[1]^data[2]^data[3] + sizeof(data))) {
-    light_mode = data[1];
-    if(light_mode) {
-      set_amount(data[2]+((unsigned short)data[3]<<8));
-    }
-    Serial.println("Settings retrieved");
-  }
-}
-
-void
-save_settings(void) {
-  byte data[4];
-  data[1] = light_mode;
-  data[2] = (byte)amount_current;
-  data[3] = (amount_current>>8);
-  data[0] = ~(data[1]^data[2]^data[3] + sizeof(data));
-  EEPROM.write(0,data[0]);
-  EEPROM.write(1,data[1]);
-  EEPROM.write(2,data[2]);
-  EEPROM.write(3,data[3]);
-}
-
-void set_brightness(unsigned short b) {
-  noInterrupts();
-  if(b<=255) {
-    digitalWrite(DPIN_DRV_MODE, LOW);
-    analogWrite(DPIN_DRV_EN, b);
-  } else if(b<=BRT_MAX_LUMEN) {
-    analogWrite(DPIN_DRV_MODE, ((long)b-BRT_MED_LUMEN)*255/((long)BRT_MAX_LUMEN-BRT_MED_LUMEN));
-    digitalWrite(DPIN_DRV_EN, HIGH);
-  } else {
-    digitalWrite(DPIN_DRV_EN, HIGH);
-    digitalWrite(DPIN_DRV_MODE, HIGH);
-  }
-  interrupts();
-}
-
-void
-set_amount(unsigned short amount) {
-  amount_current = amount_begin = amount_end = amount;
-  amount_fade_duration = 0;
-  amount_off = 0;
-
-  set_brightness(amount_current);
-  pinMode(DPIN_PWR, OUTPUT);
-  if(time_current<POWER_ON_BUTTON_THRESHOLD || amount_current==0)
-    digitalWrite(DPIN_PWR, LOW);
-  else
-    digitalWrite(DPIN_PWR, HIGH);
-}
-
-void
-fade_to_amount(unsigned short amount, unsigned short fade_duration) {
-  amount_begin = amount_current;
-  amount_end = amount;
-  amount_fade_duration = fade_duration;
-  amount_fade_start = millis();
-  amount_off = 0;
-}
-
-PT_THREAD(fade_control_pt_func(struct pt *pt))
-{
-  static long fade_time;
-
-  PT_BEGIN(pt);
-
-  do {
-    PT_YIELD(pt);
-
-    if(amount_flash) {
-      analogWrite(DPIN_DRV_EN, 0);
-      fade_time =  time_current;
-      PT_WAIT_UNTIL(pt, (time_current-fade_time) > (100));
-    }
-
-    amount_flash = 0;
-
-    fade_time = time_current - amount_fade_start;
-
-    if(fade_time >= amount_fade_duration) {
-      if(amount_current != amount_end) {
-        amount_current = amount_end;
-      }
-    } else {
-      amount_current = (((long)amount_end - (long)amount_begin)*fade_time)/amount_fade_duration + amount_begin;
-    }
-
-    pinMode(DPIN_PWR, OUTPUT);
-    if(time_current<POWER_ON_BUTTON_THRESHOLD || amount_current==0)
-      digitalWrite(DPIN_PWR, LOW);
-    else
-      digitalWrite(DPIN_PWR, HIGH);
-
-    if(amount_current>overtemp_max) {
-      amount_current = overtemp_max;
-    }
-
-    set_brightness(amount_off?0:amount_current);
-  } while(1);
-
-  PT_END(pt);
-}
-
-PT_THREAD(button_led_pt_func(struct pt *pt))
-{
-  PT_BEGIN(pt);
-
-  do {
-    switch(batt_state) {
-    case BATT_CHARGING:
-      {
-        const unsigned long pulseTime = time_current;
-        // Smoothly pulse the green LED over a two-second interval,
-        // as if it were "breathing". This is the charging indication.
-        byte pulse = ((pulseTime>>2)&0xFF);
-        pulse = ((pulse * pulse) >> 8);
-        pulse = ((pulseTime>>2)&0x0100)?0xFF-pulse:pulse;
-        analogWrite(DPIN_GLED, pulse);
-      }
-      if(overtemp_max<BRT_MAX_LUMEN) {
-        digitalWrite(DPIN_RLED_SW, (time_current&0x03FF)>0x01FF?LOW:HIGH);
-      } else {
-        digitalWrite(DPIN_RLED_SW, LOW);
-      }
-      break;
-    case BATT_CHARGED:
-      // Solid green LED.
-      digitalWrite(DPIN_GLED, HIGH);
-      if(overtemp_max<BRT_MAX_LUMEN) {
-        digitalWrite(DPIN_RLED_SW, (time_current&0x03FF)>0x01FF?LOW:HIGH);
-      } else {
-        digitalWrite(DPIN_RLED_SW, LOW);
-      }
-      break;
-    case BATT_DISCHARGING:
-      // Blink the indicator LED now and then.
-      if(overtemp_max<BRT_MAX_LUMEN) {
-        digitalWrite(DPIN_RLED_SW, (time_current&0x03FF)>50?LOW:HIGH);
-        digitalWrite(DPIN_GLED, LOW);
-      } else {
-        digitalWrite(DPIN_GLED, (time_current&0x03FF)>10?LOW:HIGH);
-        digitalWrite(DPIN_RLED_SW, LOW);
-      }
-      break;
-    }
-    PT_YIELD(pt);
-  } while(1);
-
-  PT_END(pt);
-}
-
-PT_THREAD(power_pt_func(struct pt *pt))
-{
-  static unsigned short count;
-  count++;
-  PT_BEGIN(pt);
-
-  overtemp_max = BRT_MAX_LUMEN;
-  do {
-    // Check the temperature sensor
-    {
-      static bool low_power_condition = false;
-      static uint8_t anti_flicker = 255;
-
-      if(temp_filtered > OVERTEMP_SHUTDOWN) {
-        if(amount_current)
-          Serial.println("Overheat shutdown!");
-        set_amount(0);
-        digitalWrite(DPIN_DRV_MODE, LOW);
-        digitalWrite(DPIN_DRV_EN, LOW);
-        digitalWrite(DPIN_PWR, LOW);
-      }
-
-      if(low_power_condition || (vcc_current<VOLTAGE_LOW)) {
-        if(!low_power_condition) {
-          overtemp_max = amount_current;
-        }
-        low_power_condition = true;
-        if((vcc_filtered < VOLTAGE_LOW) && (overtemp_max > BRT_MIN_LUMEN)) {
-          digitalWrite(DPIN_DRV_EN, LOW);
-          digitalWrite(DPIN_DRV_MODE, LOW);
-          analogWrite(DPIN_DRV_EN,BRT_MIN_LUMEN);
-          overtemp_max = overtemp_max/2 + BRT_MIN_LUMEN;
-          anti_flicker = 0;
-        }
-      }
-
-      if(anti_flicker == 255) {
-        if((vcc_filtered > VOLTAGE_NOMINAL+50) && (overtemp_max != BRT_MAX_LUMEN))
-          overtemp_max++;
-          anti_flicker -= 10;
-      } else {
-        anti_flicker++;
-      }
-
-      if(temp_filtered > OVERTEMP_THROTTLE) {
-        short new_max = (256-((temp_filtered-OVERTEMP_THROTTLE)*2)<<2)-1;
-        if((overtemp_max>BRT_MIN_LUMEN) && (new_max<(signed)overtemp_max)) {
-          overtemp_max--;
-          anti_flicker = 0;
-        }
-      }
-
-      static unsigned long lastStatTime;
-      if(time_current-lastStatTime > 1000) {
-        while(time_current-lastStatTime > 1000)
-          lastStatTime += 1000;
-
-        Serial.print("stat: ");
-        Serial.print(time_current);
-
-        switch(batt_state) {
-        case BATT_CHARGING:
-          Serial.print(" [CHARGING]");
-          break;
-        case BATT_CHARGED:
-          Serial.print(" [CHARGED]");
-          break;
-        case BATT_DISCHARGING:
-          Serial.print(" [BATTERY]");
-          break;
-        }
-
-        Serial.print(" lHz=");
-        Serial.print(count);
-        count = 0;
-
-        Serial.print(" duty=");
-        Serial.print(amount_current);
-
-        Serial.print(" Vcc=");
-        Serial.print(vcc_filtered);
-        Serial.print("mv");
-
-        Serial.print(" Temp=");
-        Serial.print((temp_filtered-500)/10.0f);
-        Serial.print("C");
-
-        if(orientation_enabled) {
-          Serial.print(" roll=");
-          Serial.print(angle_roll);
-
-          Serial.print(" pitch=");
-          Serial.print(angle_pitch);
-        }
-
-        if(overtemp_max<BRT_MAX_LUMEN) {
-          Serial.print(" THRTTL=");
-          Serial.print(overtemp_max);
-        }
-        Serial.println("");
-        }
-    }
-
-    PT_YIELD(pt);
-  } while(1);
-
-  PT_END(pt);
-}
-
-PT_THREAD(light_momentary_pt_func(struct pt *pt))
-{
-  // If more than two minutes go by without the user
-  // pressing a button, then go ahead and shut down.
-  if(button_released_duration > 120000) {
-    pinMode(DPIN_PWR, OUTPUT);
-    digitalWrite(DPIN_PWR, LOW);
-  }
-
-  PT_BEGIN(pt);
-
-  do {
-    pinMode(DPIN_PWR, OUTPUT);
-    digitalWrite(DPIN_PWR, HIGH);
-    amount_off = 0;
-
-    PT_WAIT_UNTIL(pt, !button_is_pressed);
-
-    amount_off = 1;
-
-    PT_WAIT_UNTIL(pt, button_is_pressed);
-  } while(amount_current);
-
-  PT_END(pt);
-}
-
-PT_THREAD(light_blinky_pt_func(struct pt *pt))
-{
-  PT_BEGIN(pt);
-
-  PT_WAIT_UNTIL(pt, !button_is_pressed && (button_released_duration > BUTTON_DEBOUNCE));
-  button_pressed_duration = 0;
-
-  do {
-    amount_off = !((time_current&0xFF)<=64) || !((time_current&0x1F)<=16);
-    PT_YIELD(pt);
-  } while(amount_current && (button_pressed_duration<BUTTON_DEBOUNCE));
-
-  amount_off = 0;
-  PT_WAIT_UNTIL(pt,!button_is_pressed);
-
-  PT_END(pt);
-}
-
-PT_THREAD(light_knob_pt_func(struct pt *pt))
-{
-  static unsigned long lastTime;
-  static float lastKnobAngle, knob;
-
-  PT_BEGIN(pt);
-
-  enable_orientation();
-
-  // Set the initial knob value based on our current light bightness level.
-  knob = sqrt((float)amount_current/(float)BRT_MAX_LUMEN);
-
-  // Wait for the user to let go of the button.
-  PT_WAIT_UNTIL(pt,!button_is_pressed);
-
-  // Wait for a brief moment for any vibrations to stabalize.
-  PT_WAIT_FOR_PERIOD(pt,50);
-
-  lastKnobAngle = angle_roll;
-
-  do {
-    {
-      // Make apparent brightness changes linear by squaring the
-      // value and dividing back down into range.  This gives us
-      // a gamma correction of 2.0, which is close enough.
-      unsigned short bright = (uint16_t)(knob * knob * BRT_MAX_LUMEN);
-
-      // Avoid ever appearing off in this mode!
-      if (bright < BRT_MIN_LUMEN) bright = BRT_MIN_LUMEN;
-
-      if((amount_current != amount_end) || abs((int16_t)(amount_end-bright)) > 4)
-        fade_to_amount(bright,100);
-    }
-
-    PT_WAIT_FOR_PERIOD(pt,50);
-
-    {
-      #define DEG_TO_RAD(x)    ((PI*(x))/180.0f)
-      float change = angle_roll - lastKnobAngle;
-      lastKnobAngle = angle_roll;
-
-      // Don't bother updating our brightness reading if our angle isn't good.
-      if(abs(angle_pitch) < DEG_TO_RAD(60)) {
-        if (change >  PI) change -= 2.0f*PI;
-        if (change < -PI) change += 2.0f*PI;
-        knob += change / -7.0f;
-        if (knob < 0) knob = 0;
-        if (knob > 1) knob = 1;
-      }
-    }
-  } while(amount_current && (button_pressed_duration<BUTTON_DEBOUNCE));
-
-  PT_WAIT_UNTIL(pt,!button_is_pressed);
-
-  PT_END(pt);
-}
-
-PT_THREAD(light_pt_func(struct pt *pt))
-{
-  static unsigned long lastTime;
-  static byte level;
-
-  PT_BEGIN(pt);
-
-  // Estimate what the current brighness level is closest to.
-  if(amount_current < (BRT_LOW_LUMEN/2)) {
-    level = 0;
-  } else if(amount_current < (BRT_MED_LUMEN/2)) {
-    level = 1;
-  } else if(amount_current < (BRT_MAX_LUMEN/2)) {
-    level = 2;
-  } else {
-    level = 3;
-  }
-
-  button_released_time = time_current;
-  button_released_duration = 0;
-
-  Serial.println("Starting light thread.");
-  do {
-    PT_WAIT_UNTIL(pt, button_is_pressed && (button_pressed_duration > BUTTON_DEBOUNCE));
-
-    if(!amount_current || (button_released_duration<BUTTON_BRIGHTNESS_THRESHOLD)) {
-      level++;
-      level &= 3;
-      Serial.print("intensity=");
-      Serial.println(level);
-    } else {
-      Serial.println("turning off");
-      level = 0;
-    }
-
-    switch(level) {
-    case 0:
-      break;
-
-    case 1:
-      fade_to_amount(BRT_LOW_LUMEN,250);
-      break;
-
-    case 2:
-      fade_to_amount(BRT_MED_LUMEN,500);
-      break;
-
-    case 3:
-      fade_to_amount(BRT_MAX_LUMEN,500);
-      break;
-    }
-
-    PT_WAIT_UNTIL(pt, !button_is_pressed && (button_released_duration > BUTTON_DEBOUNCE));
-
-    if(!level)
-      fade_to_amount(0,500);
-  } while(1);
-
-  PT_END(pt);
-}
-
-void
-check_serial_port(void)
-{
-  // Check the serial port
-  if(Serial.available()) {
-    char c = Serial.read();
-    switch(c) {
-    case '+':
-      if(BRT_MAX_LUMEN-amount_current<BRT_MIN_LUMEN)
-        set_amount(BRT_MAX_LUMEN);
-      else
-        set_amount(amount_current+BRT_MIN_LUMEN);
-      break;
-
-    case '-':
-      if(amount_current<BRT_MIN_LUMEN)
-        set_amount(0);
-      else
-        set_amount(amount_current-BRT_MIN_LUMEN);
-      break;
-
-    case 'X':
-    case 'x': set_amount(0); break;
-    case 'H':
-    case 'h': set_amount(BRT_MAX_LUMEN); amount_off = 0; break;
-
-    case '0': light_mode = 0; amount_off = 0; break;
-    case '1': light_mode = 1; amount_off = 0; break;
-    case '2': light_mode = 2; amount_off = 0; break;
-    case '3': light_mode = 3; amount_off = 0; break;
-    case '4': light_mode = 4; amount_off = 0; break;
-    case '5': light_mode = 5; amount_off = 0; break;
-
-    case 'R':
-      // Let the watchdog reset us.
-      Serial.println("Rebooting");
-      wdt_enable(WDTO_15MS);
-      while(1) { }
-      break;
-      /*
-    case 'C':
-    case 'c': Serial.println("+------+---------------------+");
-              Serial.println("| +    | increase brightness |");
-              Serial.println("| -    | decrease brightness |");
-              Serial.println("| x/X  | turn light off      |");
-              Serial.println("| h/H  | max brightness      |");
-              Serial.println("| 0..5 | set light_mode      |");
-              Serial.println("| c/C  | list commands       |");
-              Serial.println("| R    | reboot              |");
-              Serial.println("+------+---------------------+");
-    */
-    default:
-      break;
-    }
-  }
-}
-
-void
-setup(void)
-{
-  // Set our watchdog to kill us if we don't
-  // check in every two seconds.
-  wdt_enable(WDTO_2S);
-
-  // We just powered on!  That means either we got plugged
-  // into USB, or (more likely) the user is pressing the
-  // power button.  We need to pull up the enable pin of
-  // the regulator very soon so we don't lose power.
-
-  // We don't pull the pin high here quite yet because
-  // we will do that when we transition out of MODE_OFF,
-  // somewhere in the main loop. Delaying this as long
-  // as possible acts like a debounce for accidental button
-  // taps.
-  pinMode(DPIN_PWR,      INPUT);
-  digitalWrite(DPIN_PWR, LOW);
-
-  // Initialize GPIO
-  pinMode(DPIN_RLED_SW,  INPUT);
-  pinMode(DPIN_GLED,     OUTPUT);
-  pinMode(DPIN_DRV_MODE, OUTPUT);
-  pinMode(DPIN_DRV_EN,   OUTPUT);
-  digitalWrite(DPIN_DRV_MODE, LOW);
-  digitalWrite(DPIN_DRV_EN,   LOW);
-
-  // Initialize serial busses
-  Serial.begin(9600);
-  Wire.begin();
-
-  button_released_time = millis();
-  button_pressed_time = millis();
-
-  update_loop_variables();
-  update_loop_variables();
-  update_loop_variables();
-
-  // Don't bother loading the settings if we are connected to USB.
-  // Only load the settings when we are running from the battery.
-  if (batt_state == BATT_DISCHARGING) {
-    retrieve_settings();
-  }
-
-  Serial.println("Powered up!");
-}
-
-void
-loop(void)
-{
-  static unsigned long lastTime;
-  unsigned long time = millis();
-
-  // Reset the watchdog timer
-  wdt_reset();
-
-  update_loop_variables();
-
-  check_serial_port();
-
-  button_led_pt_func(&button_led_pt);
-
-  power_pt_func(&power_pt);
-
-  fade_control_pt_func(&fade_control_pt);
-
-#define NUMBER_OF_MODES    (4)
-
-  static byte last_mode;
-  static byte save_mode;
-  if((button_pressed_duration > 2048+1024+512*NUMBER_OF_MODES+1024)) {
-    if(save_mode == 1) {
-      amount_off = 1;
-      save_settings();
-      amount_off = 0;
-      save_mode = 2;
-    }
-  } else if((button_pressed_duration > 2048+1024+512*NUMBER_OF_MODES)) {
-    amount_off = ((button_pressed_duration/64) & 1);
-    if(save_mode == 0) {
-      save_mode = 1;
-      last_mode = 0;
-    }
-  } else if((button_pressed_duration > 2048)) {
-    byte selected_mode = (button_pressed_duration-2048)/512 + 1;
-    amount_off = 0;
-    if(selected_mode-1>=light_mode) {
-      selected_mode++;
-    }
-    if(selected_mode > NUMBER_OF_MODES)
-      selected_mode = NUMBER_OF_MODES;
-    if(selected_mode-1==light_mode)
-      selected_mode--;
-    if(selected_mode != last_mode) {
-      amount_flash = 1;
-      last_mode = selected_mode;
-      Serial.print("Mode selected: ");
-      Serial.println(selected_mode-1);
-    }
-  } else {
-    char thread_status;
-    if(save_mode) {
-      save_mode = 0;
-      amount_off = 0;
-      button_pressed_duration = 0;
-      button_released_duration = 0;
-    }
-    if(last_mode) {
-      light_mode = last_mode-1;
-      last_mode = 0;
-      Serial.print("Mode change: ");
-      Serial.println(light_mode);
-      PT_INIT(&light_pt);
-      PT_INIT(&light_momentary_pt);
-      PT_INIT(&light_blinky_pt);
-      PT_INIT(&light_knob_pt);
-    }
-    switch(light_mode) {
-      default:
-      case 0: thread_status = light_momentary_pt_func(&light_momentary_pt); break;
-      case 1: thread_status = light_pt_func(&light_pt); break;
-      case 2: thread_status = light_blinky_pt_func(&light_blinky_pt); break;
-      case 3: thread_status = light_knob_pt_func(&light_knob_pt); break;
-    }
-    if(!PT_SCHEDULE(thread_status)) {
-      light_mode = 0;
-      fade_to_amount(0,500);
-    }
-  }
-
-  return;
-}
-
-


Add utility functions.

Add utility functions.

--- software/XTendPayloadTeensy/XTendPayloadTeensy.ino
+++ software/XTendPayloadTeensy/XTendPayloadTeensy.ino
@@ -113,32 +113,36 @@

   if ( sentenceBufRdy ) {
     while( sentenceBuf[i+1] != 0 ) {
-        Serial2.write( sentenceBuf[i] );
-        Serial1.write( sentenceBuf[i] );//for logging
-        i++;
+      printAndSendChar( sentenceBuf[i] );
+      i++;
     }
     sentenceRdy = false;
   } else { // Buffer data is being updated. Use current sentence
     while( sentence[i+1] != 0 ) {
-        Serial2.write( sentenceBuf[i] );
-        Serial1.write( sentenceBuf2[i] );//for logging
-        i++;
+      printAndSendChar( sentenceBuf[i] );
+      i++;
     }
   }
-
-  Serial2.print(" "+(String)numb); //also puts the 0 at the end of TX string
-  Serial1.print(" "+(String)numb);
-  Serial2.write(10);
-  Serial1.write(10);
+
+  printAndSendString( " " + (String)numb ); //also puts the 0 at the end of TX string
+  printAndSendChar( 10 );
 }

 void transmit() {
   txFlag = true;
   help = 0;
 }
-void printAndSend(String whatToSend){ //sends message to both logger and rf module
+
+void printAndSendString( String whatToSend ){ //sends message to both logger and rf module
   Serial2.print( whatToSend ); // RF module
   Serial1.print( whatToSend ); // Logger
+  Serial.print( whatToSend ); // Terminal
+}
+
+void printAndSendChar( char whatToSend ){ //sends message to both logger and rf module
+  Serial2.write( whatToSend ); // RF module
+  Serial1.write( whatToSend ); // Logger
+  Serial.write( whatToSend ); // Terminal
 }

 time_t getTeensy3Time() {


Complete canbus set_mask_filter_recv example

--- examples/set_mask_filter_recv/set_mask_filter_recv.ino
+++ examples/set_mask_filter_recv/set_mask_filter_recv.ino
@@ -4,7 +4,6 @@
 // loovee, 2014-7-8

 #include <SPI.h>
-#include "mcp_can.h"

 /*SAMD core*/
 #ifdef ARDUINO_SAMD_VARIANT_COMPLIANCE
@@ -13,13 +12,24 @@
     #define SERIAL Serial
 #endif

+//#define CAN_2518FD
+#define CAN_2515
 // the cs pin of the version after v1.1 is default to D9
 // v0.9b and v1.0 is default D10
+
+#ifdef CAN_2518FD
+#include "mcp2518fd_can.h"
+const int SPI_CS_PIN = BCM8;
+mcp2518fd CAN(SPI_CS_PIN); // Set CS pin
+#endif
+
+#ifdef CAN_2515
+#include "mcp2515_can.h"
 const int SPI_CS_PIN = 9;
+mcp2515_can CAN(SPI_CS_PIN); // Set CS pin
+#endif

-MCP_CAN CAN(SPI_CS_PIN);                                    // Set CS pin
-
-const byte interruptPin = 0;
+const byte interruptPin = 2;
 unsigned char flagRecv = 0;
 unsigned char len = 0;
 unsigned char buf[8];
@@ -27,8 +37,13 @@

 void setup() {
     SERIAL.begin(115200);
-
-    while (CAN_OK != CAN.begin(CAN_500KBPS)) {            // init can bus : baudrate = 500k
+    while(!Serial){};
+
+#ifdef CAN_2518FD
+    while (0 != CAN.begin((byte)CAN_500K_1M)) {            // init can bus : baudrate = 500k
+#else
+    while (CAN_OK != CAN.begin(CAN_500KBPS)) {             // init can bus : baudrate = 500k
+#endif
         SERIAL.println("CAN BUS Shield init fail");
         SERIAL.println(" Init CAN BUS Shield again");
         delay(100);


Fixed bug in serial printing

Fixed bug in serial printing


add some comments

add some comments

--- projects/ask/stm32f1init/stm32f1init.ino
+++ projects/ask/stm32f1init/stm32f1init.ino
@@ -29,13 +29,11 @@
 #include BOOT_LOADER
 };

-uint8_t check;
-
-enum {
-    ACK = 0x79,
-    NAK = 0x1F,
-};
-
+uint8_t check;  // this checksum will get updated on each call to sendByte()
+
+enum { ACK = 0x79, NAK = 0x1F };
+
+// boot request codes sent to the target, based on STM's USART protocol
 enum {
     GET_CMD = 0x00,
     GETID_CMD = 0x02,
@@ -45,10 +43,13 @@
     RDUNP_CMD = 0x92,
 };

+// get the specific data byte to send to the target
 static uint8_t getData (uint16_t index) {
+    // this is equivalent to data[index] on ARM chips
     return pgm_read_byte(data + index);
 }

+// read a reply from the target, or return 0 after a certain amount of time
 static uint8_t getReply () {
     for (long i = 0; i < TIMEOUT; ++i)
         if (Target.available())
@@ -56,30 +57,33 @@
     return 0;
 }

+// wait for an ACK reply, else print an error message and halt
 static void wantAck () {
     uint8_t b = 0;
+    // wait a bit longer than normal getReply() timeouts, if needed
     for (int i = 0; i < 5; ++i) {
         b = getReply();
         if (b == 0) {
-            Serial.print('.');
+            Serial.print('.'); // each retry prints a dot
             continue;
         }
         if (b != ACK)
             break;
-        check = 0;
+        check = 0; // the global checksum is always cleared after an ACK
         return;
     }
     Serial.print(" FAILED - got 0x");
     Serial.println(b, HEX);
-    while (true)
-        ; // halt
-}
-
+    while (true) ; // halt
+}
+
+// send a byte to the target and update the global checkum value
 static void sendByte (uint8_t b) {
     check ^= b;
     Target.write(b);
 }

+// send a command and wait for the coorresponding ACK
 static void sendCmd (uint8_t cmd) {
     Serial.flush();
     sendByte(cmd);
@@ -87,6 +91,7 @@
     wantAck();
 }

+// special infinite loop to trigger target autobaud and wait for ACK or NAK
 static void connectToTarget () {
 #ifdef __AVR_ATmega328P__   // use a modified SoftwareSerial implementation
     Target.begin(9600);
@@ -100,9 +105,10 @@
         Target.write(0x7F);
         b = getReply();
         //Serial.print(b, HEX);
-    } while (b != ACK && b != NAK);
-}
-
+    } while (b != ACK && b != NAK); // NAK is fine, it's still a response
+}
+
+// boot loader request for the boot version, ignoring the rest
 static uint8_t getBootVersion () {
     sendCmd(GET_CMD);
     uint8_t n = getReply();
@@ -113,6 +119,7 @@
     return bootRev;
 }

+// boot loader request for the chip type, as 16-bit int
 static uint16_t getChipType () {
     sendCmd(GETID_CMD);
     getReply(); // should be 1
@@ -122,6 +129,7 @@
     return chipType;
 }

+// boot loader request for a mass erase of flash memory
 static void massErase () {
 #if 1
     sendCmd(ERASE_CMD);
@@ -137,6 +145,7 @@
 #endif
 }

+// main sketch logic
 void setup () {
     Serial.begin(115200);
     Serial.print("[stm32f1init] ");


Adding a playlist with different samples and red flashing LED to indicate an alarm.

--- CatProtect/CatProtect.ino
+++ CatProtect/CatProtect.ino
@@ -41,6 +41,29 @@
 MotionSensor motionSensor;

+/// A list of voice sample file names
+const char* const voiceSampleList[] = {
+	"v0.snd",
+	"v1.snd",
+	"v2.snd",
+	"v3.snd",
+	"v4.snd",
+	"v5.snd" };
+
+/// The number of voice samples
+const int voiceSampleCount = 6;
+
+/// The next voice sample to play.
+/// They play in a loop.
+int nextVoiceSampleIndex = 0;
+
+/// Flag if we had an alarm.
+/// The LED will flash red, after an alarm was played.
+bool alarmPlayed = false;
+
+
+/// Arduino setup method.
+///
 void setup() {
 	// Set the initial state.
 	logicState = WaitForSensor;
@@ -63,12 +86,14 @@
 		signalError();
 		return;
 	}
-
+
 	Serial.println(F("Success!"));
 	Serial.flush();
 }

+/// Arduino loop method.
+///
 void loop() {
 	// Get the current time for this loop iteration.
 	const unsigned long currentTime = millis();
@@ -81,19 +106,33 @@
 		// If the board goes into alarm state, play the sound.
 		// This will block the loop, until the sound finishes.
 		if (logicState == AlarmState) {
-			if (!audioPlayer.play("voice.snd")) {
+			// Get the filename for the next voice sample.
+			const char *fileName = voiceSampleList[nextVoiceSampleIndex];
+			// Play the sound.
+			if (!audioPlayer.play(fileName)) {
+				// On error go into error state.
 				Serial.println(F("Error on play."));
 				Serial.flush();
-				return;
+				signalError();
+			} else {
+				// Increase the next voice sample index
+				++nextVoiceSampleIndex;
+				if (nextVoiceSampleIndex >= voiceSampleCount) {
+					nextVoiceSampleIndex = 0;
+				}
+				// Go back into idle state after the sound.
+				// The sensor might stay in alarm state for a while.
+				logicState = IdleState;
+				// Remember an alarm was played, the LED will flash red.
+				alarmPlayed = true;
 			}
-			// Go back into idle state after the sound.
-			// The sensor might stay in alarm state for a while.
-			logicState = IdleState;
 		}
 	}
 }

+/// The motion callback which is called every time when the sensor state changes.
+///
 void onMotion(const unsigned long currentTime, MotionSensor::Status status)
 {
 	if (status == MotionSensor::WaitStablilize) {
@@ -103,7 +142,12 @@
 	} else if (status == MotionSensor::Idle) {
 		Serial.println(F("Sensor is in idle state."));
 		Serial.flush();
-		ledController.setState(LEDController::Green, LEDController::FlashVerySlow);
+		// If an alarm was played, let the LED flash red.
+		if (alarmPlayed) {
+			ledController.setState(LEDController::Red, LEDController::FlashVerySlow);
+		} else {
+			ledController.setState(LEDController::Green, LEDController::FlashVerySlow);
+		}
 		logicState = IdleState; // Ready to observe.
 	} else if (status == MotionSensor::Alarm) {
 		Serial.println(F("Sensor alarm."));