FFT is now working, and the frequency range can be modified by changing the down_sampling_rate parameter

--- Arduino/_nano_firmware/nanoFirmware2/nanoFirmware2.ino
+++ Arduino/_nano_firmware/nanoFirmware2/nanoFirmware2.ino
@@ -10,7 +10,8 @@

 // do #defines BEFORE #includes
 #define LOG_OUT 1 // use the log output function
-#define FFT_N 128 // set to 256 point fft
+#define FFT_N 256 // set to 256 point fft
+#define WINDOW 1 // Enable windowing

 #include <FFT.h> // include the library
 //#include <prescaler.h>
@@ -32,9 +33,29 @@
 String data;

 int sampling_freq_hz = 200;
+int down_sampling_rate = 20;
+int down_sampling_counter = 0;
 int millisecond_delay = 16; //This should be the same as 1000 / 200;
 int microsecond_delay = millisecond_delay * 1000;
-//int sampling_period_ms = 1000 / sampling_freq_hz;
+
+// Define various ADC prescalers
+//Initialization flags
+const unsigned char PS_2_i = 0xe1;
+const unsigned char PS_4_i = 0xe2;
+const unsigned char PS_8_i = 0xe3;
+const unsigned char PS_16_i = 0xe4;
+const unsigned char PS_32_i = 0xe5; //Chosen Prescaler
+const unsigned char PS_64_i = 0xe6;
+const unsigned char PS_128_i = 0xe7;
+
+//Code flags -> should use the same prescaler as the initialization
+const unsigned char PS_2_c = 0xf1;
+const unsigned char PS_4_c = 0xf2;
+const unsigned char PS_8_c = 0xf3;
+const unsigned char PS_16_c = 0xf4;
+const unsigned char PS_32_c = 0xf5; // Chosen Prescaler
+const unsigned char PS_64_c = 0xf6;
+const unsigned char PS_128_c = 0xf7;

 void setup() {
     // declare the ledPin as an OUTPUT:
@@ -45,8 +66,9 @@
   digitalWrite(digitalSelectPin, HIGH); //Set to HIGH for 6G sensitivity, OR LOW for 1.5G sensitivity
   digitalWrite(digitalSleepPin, HIGH);
   Serial.begin(115200); // use the serial port
-  TIMSK0 = 0; // turn off timer0 for lower jitter - delay() and millis() killed
-  ADCSRA = 0xe7; // set the adc to free running mode // This is the default -> 229 or 0xe5
+  TIMSK0 = 0; //Reduces jitter
+  ADCSRA = PS_32_i; //HERE!!!!!!
+
   ADMUX = 0x40; // use adc0
   DIDR0 = 0x01; // turn off the digital input for adc0
 }
@@ -58,37 +80,47 @@
 //  sensorY = analogRead(sensorY_pin);
 //  sensorX = analogRead(sensorX_pin);
     cli();  // UDRE interrupt slows this way down on arduino1.0
-    for (int i = 0 ; i < 2*FFT_N; i += 2) { // save 256 samples
+    for (int i = 0 ; i < 2 * FFT_N; i += 2) { // save 256 samples
       while(!(ADCSRA & 0x10)); // wait for adc to be ready -> Checking bit 4
-      ADCSRA = 0xf7; // restart adc
+
+      ADCSRA = PS_32_c; // restart adc // HERE!!!!!!
+
       byte m = ADCL; // fetch adc data
       byte j = ADCH;
       int k = (j << 8) | m; // form into an int
       k -= 0x0200; // form into a signed int
       k <<= 6; // form into a 16b signed int
+
+      if(down_sampling_counter % down_sampling_rate == 0)
+      {
       fft_input[i] = k; // put real data into even bins
       fft_input[i+1] = 0; // set odd bins to 0
-//      delay(millisecond_delay); //How many milisecconds between samples
-//      delayMicroseconds(2000);
-//    delay(millisecond_delay);
+      } else{
+        i-=2;
+      }
+      down_sampling_counter++;
+//      delay(1);
     }
+
     // window data, then reorder, then run, then take output
     fft_window(); // window the data for better frequency response
     fft_reorder(); // reorder the data before doing the fft
     fft_run(); // process the data in the fft
     fft_mag_log(); // take the output of the fft
     sei(); // turn interrupts back on
+
     Serial.println("Fourier Transform:");
-    for(int i = 0 ; i < FFT_N; i++){
+    for(int i = 0 ; i < FFT_N/2; i++){
       Serial.print(fft_log_out[i]);
       Serial.print(",");
-//      if(i%100==99){
-//        Serial.println("");
-//      }
     }
     Serial.println("");

+//delay(2000);
+
+//When TIMSK0 is on:
 delay(120000);
+
 //    delay(500000);
   }
 //  if (millis() - lastPrintTime >= delayInMillis) {


Reboot if there's no connection for over 5 minutes.

--- src/homie-sonoff-touch.ino
+++ src/homie-sonoff-touch.ino
@@ -2,7 +2,7 @@
 #include <Homie.h>

 #define FW_NAME "homie-sonoff-touch"
-#define FW_VERSION "2.0.2"
+#define FW_VERSION "2.0.3"

 /* Magic sequence for Autodetectable Binary Upload */
 const char *__FLAGGED_FW_NAME = "\xbf\x84\xe4\x13\x54" FW_NAME "\x93\x44\x6b\xa7\x75";
@@ -60,17 +60,6 @@

 void loopHandler() {

-  if ( Homie.isConnected() ) {
-    // This counter will stop when disconnected
-    connectedMillis = millis();
-  } else {
-    if (millis() - connectedMillis >= 60000 ) {
-      Serial.println("Restarting in ten seconds");
-      delay(10000);
-      //FIXME Don't do this during an update!
-      ESP.restart();
-    };
-  }
   // Update button state
   button1.Update();

@@ -157,5 +146,19 @@
 }

 void loop() {
+
+  if ( Homie.isConnected() ) {
+    // This counter will stop when disconnected
+    connectedMillis = millis();
+  } else {
+    // If disconnected for over 5 minutes
+    if ( millis() - connectedMillis >= 300000 ) {
+      Serial.println("Restarting in ten seconds");
+      delay(10000);
+      // The chances of being in OTA whilst disconnected from MQTT are slim.
+      ESP.restart();
+    };
+  }
+
   Homie.loop();
 }


Adds version, refactors a bunch

Adds version, refactors a bunch

--- lockdown.ino
+++ lockdown.ino
@@ -1,3 +1,5 @@
+const String VERSION = "0.1.0";
+
 const int EGRESS = 0;
 const int MOTION = 1;
 const int TRIP   = 2;
@@ -23,6 +25,24 @@
 }

 void loop() {
+  checkForIncoming();
+  checkAllSensors();
+}
+
+void outputState(int i, int type) {
+  Serial.print("{\"result\":{\"type\":\"");
+  Serial.print(TYPES[type]);
+  Serial.print("\",\"id\":");
+  Serial.print(i);
+  Serial.print(",\"state\":");
+  Serial.print(states[i]);
+  Serial.print(",\"millis\":");
+  Serial.print(millis());
+  Serial.println("}}");
+}
+
+
+void checkForIncoming() {
   incoming = "";
   byte incomingByte;

@@ -33,42 +53,31 @@
       incoming += char(incomingByte);
     }

-    delay(10);
+    // give a chance for each byte to make it to the stream
+    delay(1);
   }

   if (incoming != "") {
-    // Serial.print(incoming);
-    if (incoming == "{\"message\":\"status\"}") {
+    if (incoming == "{\"method\":\"status\"}") {
       status();
+    } else if (incoming == "{\"method\":\"version\"}") {
+      version();
     } else {
-      error("unknown message");
+      error("unknown method");
     }
   }
-
+}
+
+
+void checkAllSensors() {
   for (int i=22; i<54; i++) {
-    //read the pushbutton value into a variable
-    states[i] = digitalRead(i);
-
-    //print out the value of the pushbutton
-    if (states[i] != lastStates[i]) {
-      outputState(i, EGRESS);
-      lastStates[i] = states[i];
-    }
+    inputStatus(i, true);
   }

   digitalWrite(13, digitalRead(22));
-}
-
-void outputState(int i, int type) {
-  Serial.print("{\"type\":\"");
-  Serial.print(TYPES[type]);
-  Serial.print("\",\"id\":");
-  Serial.print(i);
-  Serial.print(",\"state\":");
-  Serial.print(states[i]);
-  Serial.print(",\"millis\":");
-  Serial.print(millis());
-  Serial.println("}");
+
+  // just a little bit of delay to debounce
+  delay(10);
 }

@@ -80,6 +89,27 @@
 }

+// Get the state of a single input and optionally automatically output it
+void inputStatus(int id, bool output) {
+  states[id] = digitalRead(id);
+
+  if (states[id] != lastStates[id]) {
+    if (output) {
+      outputState(id, EGRESS);
+    }
+    lastStates[id] = states[id];
+  }
+}
+
+
+// Return status all inputs
+void version() {
+  Serial.print("{\"result\":\"");
+  Serial.print(VERSION);
+  Serial.println("\"}");
+}
+
+
 // Return an error messagse
 void error(String message) {
   Serial.print("{\"error\":\"");


Removed junk I forgot about.

Removed junk I forgot about.

--- examples/MuxTest/MuxTest.ino
+++ examples/MuxTest/MuxTest.ino
@@ -40,10 +40,10 @@
   TCM.setMUX(channel);                                                        // Set MUX channel, enable MUX, and start MAX31855 conversion process.
   TCM.getTemp(external, internal, scale, error);                              // Read MAX31855

-  if(channel == 0){
+  if(channel == 0){                                                           // Just print the channel 1's cold junction
     Serial.println("Cold Junction Temperature:");
     Serial.print(internal);
-    Serial.write(0xB0);                                                        // Print ° 'degree'   // Arduino IDE's UTF-8 encoding adds extra character infront of printed degree symbol.
+    Serial.write(0xB0);                                                       // Print ° 'degree'   // Arduino IDE's UTF-8 encoding adds extra character infront of printed degree symbol.
     Serial.println("C");
     Serial.println();
   }
@@ -64,26 +64,6 @@
     Serial.println();
   }

-/*  if(channel == 7){
-    average = 0;
-
-    for(byte i = 0; i < 8; i++)
-      average += avg[i];
-
-    average /= 8;
-
-    Serial.println("Average Cold Junction Temperature:");
-    Serial.print(average);
-    Serial.write(0xB0);                                                        // Print ° 'degree'
-    Serial.println("C");
-
-/*
-  Serial.print(TCM.intTemp(2));
-  Serial.write(0xB0);
-  Serial.println("F");
-  Serial.println();
-} */
-
   if(channel == 7){
     channel = 0;
     delay(5000);


Update PlayDRO.ino

Update PlayDRO.ino

--- examples/PlayDRO/PlayDRO.ino
+++ examples/PlayDRO/PlayDRO.ino
@@ -101,4 +101,4 @@
   }

   return 0;
-}+}


Stuff

Stuff

--- sketch_steppermotor/sketch_steppermotor.ino
+++ sketch_steppermotor/sketch_steppermotor.ino
@@ -32,10 +32,11 @@
   pinMode(fan0, OUTPUT);
   pinMode(fan2, OUTPUT);
   pinMode(readySig, OUTPUT);
+  digitalWrite(fan2, LOW);

   digitalWrite(readySig, HIGH);
 //  analogWrite(fan0, 255);
-//  analogWrite(fan2, 225);
+//  analogWrite(fan2, 0);
   Serial.begin(9600);

 //  pinMode(slaveSelectPin, OUTPUT);


Renamed "berenbach" to "p" and added blocking of "p" routes

--- signalboxes/kelberg/kelberg.ino
+++ signalboxes/kelberg/kelberg.ino
@@ -10,11 +10,11 @@
 int PIN_LED_SIGNAL_A2 = A11;
 int PIN_LED_SWITCHING_PERMISSION = A12;
 int PIN_LED_ROUTE_A = A13;
-int PIN_LED_ROUTE_BERENBACH = A14;
+int PIN_LED_ROUTE_P = A14;
 // White LED
-int PIN_LED_ROUTE_A_FIXATION = A15;
+int PIN_LED_ROUTE_AP_FIXATION = A15;
 // Blue LED in "route recall" box
-int PIN_LED_ROUTE_A_RECALL = 49;
+int PIN_LED_ROUTE_AP_RECALL = 49;

 // Levers and lock
 int PIN_LEVER_SWITCH_5 = 22;
@@ -25,12 +25,12 @@
 // Route levers
 int PIN_LEVER_ROUTE_A1 = 36;
 int PIN_LEVER_ROUTE_A2 = 38;
-int PIN_LEVER_ROUTE_BERENBACH1 = 40;
-int PIN_LEVER_ROUTE_BERENBACH2 = 42;
+int PIN_LEVER_ROUTE_P1 = 40;
+int PIN_LEVER_ROUTE_P2 = 42;
 // Push button for route fixing
-int PIN_BUTTON_ROUTE_A_FIXATION = 46;
+int PIN_BUTTON_ROUTE_AP_FIXATION = 46;
 // Switch/lock for route recall
-int PIN_LOCK_ROUTE_A_RECALL = 47;
+int PIN_LOCK_ROUTE_AP_RECALL = 47;

 // Output pins (pull to 0 means go out of the ground position)
 int PIN_OUTPUT_SWITCH_1 = A1;
@@ -45,12 +45,12 @@
 int SWITCHING_PERMISSION = 2;  // Note: PLUS means 'key in lock'.
 int ROUTE_A1 = 3;
 int ROUTE_A2 = 4;
-int ROUTE_BERENBACH1 = 5;
-int ROUTE_BERENBACH2 = 6;
-int ROUTE_A_FIXATION = 7;
+int ROUTE_P1 = 5;
+int ROUTE_P2 = 6;
+int ROUTE_AP_FIXATION = 7;
 int SIGNAL_A1 = 8;
 int SIGNAL_A2 = 9;
-int ROUTE_A_RECALL = 10;
+int ROUTE_AP_RECALL = 10;

 // The two possible positions. Plus is the default, minus the actuated state.
 bool PLUS = true;
@@ -80,8 +80,8 @@
   // Requirements fulfilled by the switches.
   requirements_fulfilled[ROUTE_A1] = false;
   requirements_fulfilled[ROUTE_A2] = false;
-  requirements_fulfilled[ROUTE_BERENBACH1] = false;
-  requirements_fulfilled[ROUTE_BERENBACH2] = false;
+  requirements_fulfilled[ROUTE_P1] = false;
+  requirements_fulfilled[ROUTE_P2] = false;
   if (current_position[SWITCH_5] == PLUS &&
       current_position[SWITCH_1] == PLUS &&
       current_position[SWITCHING_PERMISSION] == PLUS) {
@@ -94,11 +94,11 @@
   }
   if (current_position[SWITCH_1] == PLUS &&
       current_position[SWITCHING_PERMISSION] == PLUS) {
-    requirements_fulfilled[ROUTE_BERENBACH1] = true;
+    requirements_fulfilled[ROUTE_P1] = true;
   }
   if (current_position[SWITCH_1] == MINUS &&
       current_position[SWITCHING_PERMISSION] == PLUS) {
-    requirements_fulfilled[ROUTE_BERENBACH2] = true;
+    requirements_fulfilled[ROUTE_P2] = true;
   }

 }
@@ -116,8 +116,8 @@
   // Route levers block each other. And they block switches.
   if (current_position[ROUTE_A1] == MINUS) {
     blocked[ROUTE_A2] = true;
-    blocked[ROUTE_BERENBACH1] = true;
-    blocked[ROUTE_BERENBACH2] = true;
+    blocked[ROUTE_P1] = true;
+    blocked[ROUTE_P2] = true;

     blocked[SWITCH_5] = true;
     blocked[SWITCH_1] = true;
@@ -125,37 +125,39 @@
   }
   if (current_position[ROUTE_A2] == MINUS) {
     blocked[ROUTE_A1] = true;
-    blocked[ROUTE_BERENBACH1] = true;
-    blocked[ROUTE_BERENBACH2] = true;
+    blocked[ROUTE_P1] = true;
+    blocked[ROUTE_P2] = true;

     blocked[SWITCH_5] = true;
     blocked[SWITCH_1] = true;
     blocked[SWITCHING_PERMISSION] = true;
   }
-  if (current_position[ROUTE_BERENBACH1] == MINUS) {
+  if (current_position[ROUTE_P1] == MINUS) {
     blocked[ROUTE_A1] = true;
     blocked[ROUTE_A2] = true;
-    blocked[ROUTE_BERENBACH2] = true;
+    blocked[ROUTE_P2] = true;

     blocked[SWITCH_1] = true;
     blocked[SWITCHING_PERMISSION] = true;
   }
-  if (current_position[ROUTE_BERENBACH2] == MINUS) {
+  if (current_position[ROUTE_P2] == MINUS) {
     blocked[ROUTE_A1] = true;
     blocked[ROUTE_A2] = true;
-    blocked[ROUTE_BERENBACH1] = true;
+    blocked[ROUTE_P1] = true;

     blocked[SWITCH_1] = true;
     blocked[SWITCHING_PERMISSION] = true;
   }

   // Route fixation blocks routes.
-  if (current_position[ROUTE_A_FIXATION] == MINUS) {
+  if (current_position[ROUTE_AP_FIXATION] == MINUS) {
     blocked[ROUTE_A1] = true;
     blocked[ROUTE_A2] = true;
+    blocked[ROUTE_P1] = true;
+    blocked[ROUTE_P2] = true;
     // Special case: also keep yourself blocked (it is only un-blocked by
     // moving a signal back to PLUS).
-    blocked[ROUTE_A_FIXATION] = true;
+    blocked[ROUTE_AP_FIXATION] = true;
   }

   // Signals also block routes.
@@ -209,8 +211,8 @@
   // it can be thrown once (instead of through normal requirements, then it
   // would have been possible to throw it multiple times). It also enables the
   // corresponding route recall.
-  if (number == ROUTE_A_FIXATION && new_position == MINUS) {
-    requirements_fulfilled[ROUTE_A_RECALL] = true;
+  if (number == ROUTE_AP_FIXATION && new_position == MINUS) {
+    requirements_fulfilled[ROUTE_AP_RECALL] = true;
     if (current_position[ROUTE_A1] == MINUS) {
       requirements_fulfilled[SIGNAL_A1] = true;
     }
@@ -220,9 +222,9 @@
   }

   // Special case: route recall frees the route fixation.
-  if (number == ROUTE_A_RECALL) {
+  if (number == ROUTE_AP_RECALL) {
     // Any new position is OK, we don't care which way the lock is turned.
-    change_position(ROUTE_A_FIXATION, PLUS);
+    change_position(ROUTE_AP_FIXATION, PLUS);
   }

   // Special case: signals going back to PLUS remove their own "requirements
@@ -309,12 +311,12 @@
   pinMode(PIN_LOCK_SWITCHING_PERMISSION, INPUT_PULLUP);
   pinMode(PIN_LEVER_ROUTE_A1, INPUT_PULLUP);
   pinMode(PIN_LEVER_ROUTE_A2, INPUT_PULLUP);
-  pinMode(PIN_LEVER_ROUTE_BERENBACH1, INPUT_PULLUP);
-  pinMode(PIN_LEVER_ROUTE_BERENBACH2, INPUT_PULLUP);
+  pinMode(PIN_LEVER_ROUTE_P1, INPUT_PULLUP);
+  pinMode(PIN_LEVER_ROUTE_P2, INPUT_PULLUP);
   pinMode(PIN_LEVER_SIGNAL_A1, INPUT_PULLUP);
   pinMode(PIN_LEVER_SIGNAL_A2, INPUT_PULLUP);
-  pinMode(PIN_BUTTON_ROUTE_A_FIXATION, INPUT_PULLUP);
-  pinMode(PIN_LOCK_ROUTE_A_RECALL, INPUT_PULLUP);
+  pinMode(PIN_BUTTON_ROUTE_AP_FIXATION, INPUT_PULLUP);
+  pinMode(PIN_LOCK_ROUTE_AP_RECALL, INPUT_PULLUP);

   // Attach the LEDs.
   pinMode(13, OUTPUT);
@@ -324,9 +326,9 @@
   pinMode(PIN_LED_SIGNAL_A1, OUTPUT);
   pinMode(PIN_LED_SWITCHING_PERMISSION, OUTPUT);
   pinMode(PIN_LED_ROUTE_A, OUTPUT);
-  pinMode(PIN_LED_ROUTE_BERENBACH, OUTPUT);
-  pinMode(PIN_LED_ROUTE_A_FIXATION, OUTPUT);
-  pinMode(PIN_LED_ROUTE_A_RECALL, OUTPUT);
+  pinMode(PIN_LED_ROUTE_P, OUTPUT);
+  pinMode(PIN_LED_ROUTE_AP_FIXATION, OUTPUT);
+  pinMode(PIN_LED_ROUTE_AP_RECALL, OUTPUT);

   // Attach the output pins
   pinMode(PIN_OUTPUT_SWITCH_1, OUTPUT);
@@ -346,18 +348,18 @@
   levers[SWITCHING_PERMISSION].attach(PIN_LOCK_SWITCHING_PERMISSION);
   levers[ROUTE_A1].attach(PIN_LEVER_ROUTE_A1);
   levers[ROUTE_A2].attach(PIN_LEVER_ROUTE_A2);
-  levers[ROUTE_BERENBACH1].attach(PIN_LEVER_ROUTE_BERENBACH1);
-  levers[ROUTE_BERENBACH2].attach(PIN_LEVER_ROUTE_BERENBACH2);
+  levers[ROUTE_P1].attach(PIN_LEVER_ROUTE_P1);
+  levers[ROUTE_P2].attach(PIN_LEVER_ROUTE_P2);
   levers[SIGNAL_A1].attach(PIN_LEVER_SIGNAL_A1);
   levers[SIGNAL_A2].attach(PIN_LEVER_SIGNAL_A2);
-  levers[ROUTE_A_FIXATION].attach(PIN_BUTTON_ROUTE_A_FIXATION);
-  levers[ROUTE_A_RECALL].attach(PIN_LOCK_ROUTE_A_RECALL);
+  levers[ROUTE_AP_FIXATION].attach(PIN_BUTTON_ROUTE_AP_FIXATION);
+  levers[ROUTE_AP_RECALL].attach(PIN_LOCK_ROUTE_AP_RECALL);

   for (int number = 0; number < ARRAY_SIZE; number++) {
     levers[number].interval(200);
   }
   // Special case: route fixation button should take some seconds to activate.
-  levers[ROUTE_A_FIXATION].interval(2000);
+  levers[ROUTE_AP_FIXATION].interval(2000);

   // look up the initial lever positions and update accordingly.
   for (int number = 0; number < ARRAY_SIZE; number++) {
@@ -392,15 +394,15 @@
   update_single_lever_led(PIN_LED_SWITCHING_PERMISSION, SWITCHING_PERMISSION);

   update_dual_lever_led(PIN_LED_ROUTE_A, ROUTE_A1, ROUTE_A2);
-  update_dual_lever_led(PIN_LED_ROUTE_BERENBACH, ROUTE_BERENBACH1, ROUTE_BERENBACH2);
-
-  if (current_position[ROUTE_A_FIXATION] == PLUS) {
-    digitalWrite(PIN_LED_ROUTE_A_FIXATION, LOW);
-    digitalWrite(PIN_LED_ROUTE_A_RECALL, LOW);
-  }
-  else {
-    digitalWrite(PIN_LED_ROUTE_A_FIXATION, HIGH);
-    digitalWrite(PIN_LED_ROUTE_A_RECALL, HIGH);
+  update_dual_lever_led(PIN_LED_ROUTE_P, ROUTE_P1, ROUTE_P2);
+
+  if (current_position[ROUTE_AP_FIXATION] == PLUS) {
+    digitalWrite(PIN_LED_ROUTE_AP_FIXATION, LOW);
+    digitalWrite(PIN_LED_ROUTE_AP_RECALL, LOW);
+  }
+  else {
+    digitalWrite(PIN_LED_ROUTE_AP_FIXATION, HIGH);
+    digitalWrite(PIN_LED_ROUTE_AP_RECALL, HIGH);
   }

   // TODO: update the outgoing pins.


More accurate accel readings

More accurate accel readings

--- heartbeat_with_pulse.ino
+++ heartbeat_with_pulse.ino
@@ -208,9 +208,9 @@
 int getMagnitude() {
   float avgMag = 0;
   for(int x = 0 ; x < sampleSize ; x++) {
-    int aX = analogRead(ACCELX_PIN);
-    int aY = analogRead(ACCELY_PIN);
-    int aZ = analogRead(ACCELZ_PIN);
+    float aX = analogRead(ACCELX_PIN);
+    float aY = analogRead(ACCELY_PIN);
+    float aZ = analogRead(ACCELZ_PIN);

     float magnitude = sqrt((aX * aX) + (aY * aY) + (aZ * aZ));
     avgMag += magnitude;


reducing sW by combining bufJSON and bbuf

--- Arduino/hardware/REV10/REV10MessagePathTest/REV10SecureBHR/REV10SecureBHR.ino
+++ Arduino/hardware/REV10/REV10MessagePathTest/REV10SecureBHR/REV10SecureBHR.ino
@@ -218,11 +218,12 @@
 // - Just boiler hub (e.g. CONFIG_REV8_SECURE_BHR)
 // - Unit acting as stats-hub (e.g. CONFIG_REV11_SECURE_STATSHUB)
 // relay + bh
+constexpr size_t RX_WorkspaceSize = OTAESGCM::OTAES128GCMGenericWithWorkspace<>::workspaceRequiredDec + 16 + 58;
 inline bool decodeAndHandleSecureFrame(volatile const uint8_t * const msg)
 {
-    constexpr size_t workspaceSize = OTAESGCM::OTAES128GCMGenericWithWorkspace<>::workspaceRequiredDec + 74;
-    uint8_t workspace[workspaceSize];
-    OTV0P2BASE::ScratchSpaceL sW(workspace, workspaceSize);
+//    constexpr size_t workspaceSize = OTAESGCM::OTAES128GCMGenericWithWorkspace<>::workspaceRequiredDec + 74;
+    uint8_t workspace[RX_WorkspaceSize];
+    OTV0P2BASE::ScratchSpaceL sW(workspace, sizeof(workspace));
     return (OTRadioLink::decodeAndHandleOTSecureOFrameWithWorkspace<OTRadioLink::SimpleSecureFrame32or0BodyRXV0p2,
                                                     OTAESGCM::fixed32BTextSize12BNonce16BTagSimpleDec_DEFAULT_WITH_LWORKSPACE,
                                                    OTV0P2BASE::getPrimaryBuilding16ByteSecretKey,
@@ -281,6 +282,11 @@
 // Sends stats on primary radio channel 0 with possible duplicate to secondary channel.
 // If sending encrypted then ID/counter fields (eg @ and + for JSON) are omitted
 // as assumed supplied by security layer to remote recipent.
+constexpr uint8_t TX_MSG_BUF_SIZE = 1 + 64 + 1;
+// Size for JSON in 'O' frame is:
+constexpr uint8_t bufJSONlen = OTRadioLink::ENC_BODY_SMALL_FIXED_PTEXT_MAX_SIZE - 2 + 1 + 2;  // Not sure what -2 + 1 + 2 is about. +2 is from the pTextBuffer definition.
+constexpr uint8_t TX_ScratchSpaceNeeded = TX_MSG_BUF_SIZE + bufJSONlen;
+constexpr size_t TX_WorkspaceSize = OTRadioLink::SimpleSecureFrame32or0BodyTXBase::generateSecureOFrameRawForTX_total_scratch_usage_OTAESGCM_2p0 + TX_ScratchSpaceNeeded;
 static void bareStatsTX()
 {
     // Note if radio/comms channel is itself framed.
@@ -294,16 +300,25 @@
     //   * max binary length, or max JSON length + 1 for CRC + 1 to allow detection of oversize message
     //   * terminating 0xff
     // Buffer need be no larger than leading length byte + typical 64-byte radio module TX buffer limit + optional terminator.
-    const uint8_t MSG_BUF_SIZE = 1 + 64 + 1;
-    uint8_t buf[MSG_BUF_SIZE];
+//    constexpr uint8_t MSG_BUF_SIZE = 1 + 64 + 1;
+
+    // Allow space in workspace for:
+    //   * Msg buffer
+    //   *
+    //   * Decode routine
+//    constexpr uint8_t scratchSpaceNeededHere = MSG_BUF_SIZE;
+//    constexpr size_t workspaceSize = OTRadioLink::SimpleSecureFrame32or0BodyTXBase::generateSecureOFrameRawForTX_total_scratch_usage_OTAESGCM_2p0 + scratchSpaceNeededHere;
+    uint8_t workspace[TX_WorkspaceSize];
+    OTV0P2BASE::ScratchSpaceL sW(workspace, sizeof(workspace));

     // Send binary *or* JSON on each attempt so as not to overwhelm the receiver.
     {
         // Send JSON message.
         bool sendingJSONFailed = false; // Set true and stop attempting JSON send in case of error.

+
         // Set pointer location based on whether start of message will have preamble TODO move to OTRFM23BLink queueToSend?
-        uint8_t *bptr = buf;
+        uint8_t *bptr = sW.buf;
         // Leave space for possible leading frame-length byte, eg for encrypted frame.
         ++bptr;
         // Where to write the real frame content.
@@ -326,13 +341,14 @@

         // Buffer to write JSON to before encryption.
         // Size for JSON in 'O' frame is:
-        constexpr uint8_t maxSecureJSONSize = OTRadioLink::ENC_BODY_SMALL_FIXED_PTEXT_MAX_SIZE - 2 + 1;
+//        constexpr uint8_t maxSecureJSONSize = OTRadioLink::ENC_BODY_SMALL_FIXED_PTEXT_MAX_SIZE - 2 + 1;
         // writeJSON() requires two further bytes including one for the trailing '\0'.
-        uint8_t ptextBuf[maxSecureJSONSize + 2];
+//        uint8_t ptextBuf[maxSecureJSONSize + 2];

         // Redirect JSON output appropriately.
-        uint8_t *const bufJSON = ptextBuf;
-        constexpr uint8_t bufJSONlen = sizeof(ptextBuf);
+//        uint8_t *const bufJSON = ptextBuf;
+        uint8_t *const bufJSON = sW.buf + TX_MSG_BUF_SIZE;
+//        constexpr uint8_t bufJSONlen = maxSecureJSONSize;

         // Number of bytes written for body.
         // For non-secure, this is the size of the JSON text.
@@ -352,10 +368,11 @@
         // Push the JSON output to Serial.
         if(!sendingJSONFailed) {
             // Insert synthetic full ID/@ field for local stats, but no sequence number for now.
-            Serial.print(F("{\"@\":\""));
-            for(int i = 0; i < OTV0P2BASE::OpenTRV_Node_ID_Bytes; ++i) { Serial.print(eeprom_read_byte((uint8_t *)V0P2BASE_EE_START_ID+i), HEX); }
-            Serial.print(F("\","));
-            Serial.write(bufJSON+1, wrote-1);
+//            Serial.print(F("{\"@\":\"")); \\ XXX
+//            for(int i = 0; i < OTV0P2BASE::OpenTRV_Node_ID_Bytes; ++i) { Serial.print(eeprom_read_byte((uint8_t *)V0P2BASE_EE_START_ID+i), HEX); }
+//            Serial.print(F("\","));
+//            Serial.write(bufJSON+1, wrote-1);
+            Serial.write(bufJSON, wrote);
             Serial.println();
             OTV0P2BASE::flushSerialSCTSensitive(); // Ensure all flushed since system clock may be messed with...
         }
@@ -373,10 +390,9 @@
         // then build encrypted frame from raw JSON.
         if(!sendingJSONFailed) {
             // Explicit-workspace version of encryption.
+            OTV0P2BASE::ScratchSpaceL subScratch(sW, TX_ScratchSpaceNeeded);
             const OTRadioLink::SimpleSecureFrame32or0BodyTXBase::fixed32BTextSize12BNonce16BTagSimpleEncWithLWorkspace_ptr_t eW = OTAESGCM::fixed32BTextSize12BNonce16BTagSimpleEnc_DEFAULT_WITH_LWORKSPACE;
-            constexpr size_t workspaceSize = OTRadioLink::SimpleSecureFrame32or0BodyTXBase::generateSecureOFrameRawForTX_total_scratch_usage_OTAESGCM_2p0;
-            uint8_t workspace[workspaceSize];
-            OTV0P2BASE::ScratchSpaceL sW(workspace, workspaceSize);
+
             constexpr uint8_t txIDLen = OTRadioLink::ENC_BODY_DEFAULT_ID_BYTES;
             // When sending on a channel with framing, do not explicitly send the frame length byte.
             constexpr uint8_t offset = 1;
@@ -385,8 +401,8 @@
             // Distinguished 'invalid' valve position; never mistaken for a real valve.
             constexpr uint8_t valvePC = 0x7f;
             const uint8_t bodylen = OTRadioLink::SimpleSecureFrame32or0BodyTXV0p2::getInstance().generateSecureOFrameRawForTX(
-                  realTXFrameStart - offset, sizeof(buf) - (realTXFrameStart-buf) + offset,
-                  txIDLen, valvePC, (const char *)bufJSON, eW, sW, key);
+                  realTXFrameStart - offset, TX_MSG_BUF_SIZE - (realTXFrameStart-sW.buf) + offset,
+                  txIDLen, valvePC, (const char *)bufJSON, eW, subScratch, key);
             sendingJSONFailed = (0 == bodylen);
             wrote = bodylen - offset;
             if (sendingJSONFailed) OTV0P2BASE::serialPrintlnAndFlush(F("!TX Enc")); // Know why TX failed.
@@ -396,10 +412,8 @@
             // Write out unadjusted JSON or encrypted frame on secondary radio.
             // Assumes that framing (or not) of primary and secondary radios is the same (usually: both framed).
             SecondaryRadio.queueToSend(realTXFrameStart, wrote);
-        }
-        if(!sendingJSONFailed) {
             // Send directly to the primary radio...
-            if(!PrimaryRadio.queueToSend(realTXFrameStart, wrote)) { sendingJSONFailed = true; }
+            PrimaryRadio.queueToSend(realTXFrameStart, wrote);
         }
     }
     if(neededWaking) { OTV0P2BASE::flushSerialProductive(); OTV0P2BASE::powerDownSerial(); }
@@ -487,6 +501,20 @@
         PCICR = 1 ;//| 4;  // 0x1 enables PB/PCMSK0. 0x4 enables PD/PCMSK2.
         PCMSK0 = RFM23B_INT_MASK;
     }
+
+
+
+    /****************************/
+    OTV0P2BASE::serialPrintAndFlush(F("scratchspace TX: "));
+    OTV0P2BASE::serialPrintAndFlush(((uint16_t) TX_WorkspaceSize));
+    OTV0P2BASE::serialPrintAndFlush(F(", RX: "));
+    OTV0P2BASE::serialPrintAndFlush(((uint16_t) RX_WorkspaceSize));
+    OTV0P2BASE::serialPrintlnAndFlush();
+    /****************************/
+
+
+
+
     PrimaryRadio.listen(true);
     // Do early 'wake-up' stats transmission if possible
     // when everything else is set up and ready and allowed (TODO-636)
@@ -529,7 +557,7 @@
     const int16_t minsp = OTV0P2BASE::MemoryChecks::getMinSPSpaceBelowStackToEnd();
     const uint8_t location = OTV0P2BASE::MemoryChecks::getLocation();
     OTV0P2BASE::serialPrintAndFlush(F("minsp: "));
-    OTV0P2BASE::serialPrintAndFlush(minsp, HEX);
+    OTV0P2BASE::serialPrintAndFlush(minsp);
     OTV0P2BASE::serialPrintAndFlush(F(" loc:"));
     OTV0P2BASE::serialPrintAndFlush(location);
     OTV0P2BASE::serialPrintlnAndFlush();


Update Beacon.ino

Update Beacon.ino

--- FastLED/Beacon.ino
+++ FastLED/Beacon.ino
@@ -13,6 +13,7 @@
 CRGB green  = CHSV( 85, 0, 0);
 CRGB blue  = CHSV( 150, 0, 0);
 CRGB beaconColor = CHSV( 0, 0, 0);
+CRGB baseColor = CHSV( 0, 0, 0);

 uint8_t  colors = 3;
 uint32_t currentPalette =  [red,  green,  blue];
@@ -52,16 +53,16 @@
     char strBuffer[40] = "";
     str.toCharArray(strBuffer, 40);
     colorFromID = strtok(strBuffer, "~");
-    colorRecieved = atof(strtok(NULL, "~"));
+    baseColor = atof(strtok(NULL, "~"));

     // DEBUG
-    String sColorRecieved = String(colorRecieved);
+    String sColorRecieved = String(baseColor);
     Particle.publish("Color_Recieved", System.deviceID() + "~" + sColorRecieved);
 }

 void whileTouching() {
 	uint8_t colorIndex = 0;
-	uint8_t satBright = 0;
+	uint8_t satBright = 20;
 	CRGB color = red;

     while (touchEvent != CapTouch::ReleaseEvent) {
@@ -69,7 +70,7 @@
 		color.saturation = satBright;
 		color.brightness = satBright;
 		if(satBright >= 255){
-			satBright = 0;
+			satBright = 20;
 			colorIndex +=1;
 			color = currentPalette[colorIndex % colors];
 		}


Switch on logging

Switch on logging

--- examples/ping.ino
+++ examples/ping.ino
@@ -22,6 +22,8 @@
 #include <SPI.h>
 #include <Ethernet.h>
 #include <SnowPlowTracker.h>
+
+#define LOGGING

 // MAC address of this Arduino. Don't make const
 byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0xF8, 0xA0 };


Remove protocol from get/post requests

Remove protocol from get/post requests

--- examples/esp8266_firmware/esp8266_firmware.ino
+++ examples/esp8266_firmware/esp8266_firmware.ino
@@ -320,6 +320,13 @@
 			Serial.begin(baud_rate);
 		} else if (command == COMMAND_GET || command == COMMAND_POST) {
 			// get <address>:<port>/<path> or get <address/<path>
+
+			// Filter out protocol. Find first colon, check if it's got // after it, if yes, remove everything up to that point.
+			int colon_index = args.indexOf(':');
+			if (args.length() > colon_index + 3 && colon_index != -1 && args[colon_index + 1] == '/' && args[colon_index + 2] == '/') {
+				args = args.substring(colon_index + 3);
+			}
+
 			String method = command == COMMAND_POST ? "POST" : "GET";

 			int port_start = args.indexOf(":");


ADC calibration v3

ADC calibration v3

--- hal100/hal100.ino
+++ hal100/hal100.ino
@@ -101,7 +101,7 @@
 		Serial.println(payload->status.adc.rfl);

 		float rfl = payload->status.adc.rfl;
-		float fwd = payload->status.adc.fwd + 14.0;
+		float fwd = payload->status.adc.fwd * 1.3;
 		float p = sqrt(rfl / fwd);
 		valueSWR = (1 + p) / (1 - p);
 		Serial.print("Value SWR=");


Switch .ino to reference local libary, not global

--- code/ArduCAM_online_example/ArduCAM_online_example.ino
+++ code/ArduCAM_online_example/ArduCAM_online_example.ino
@@ -11,7 +11,7 @@
 // This program requires the ArduCAM V3.0.0 (or above) library and Rev.C ArduCAM shield
 // and use Arduino IDE 1.5.2 compiler

-#include <ArduCAM.h>
+#include "ArduCAM.h"
 #include "memorysaver.h"
 #include <UTFT_SPI.h>
 #include <Wire.h>
@@ -29,7 +29,7 @@
     Wire.begin();
   #endif
   #if defined(__arm__)
-    Wire1.begin();
+    Wire1.begin();
   #endif
   Serial.begin(115200);
   Serial.println("hello");


Fix Debounce example to work as described

This alters the debounce example code to toggle the LED rather than just use
the button state to set the LED state.

Fixes #293

--- build/shared/examples/02.Digital/Debounce/Debounce.ino
+++ build/shared/examples/02.Digital/Debounce/Debounce.ino
@@ -19,6 +19,8 @@
  by David A. Mellis
  modified 30 Aug 2011
  by Limor Fried
+ modified 28 Dec 2012
+ by Mike Walters

 This example code is in the public domain.

@@ -43,6 +45,9 @@
 void setup() {
   pinMode(buttonPin, INPUT);
   pinMode(ledPin, OUTPUT);
+
+  // set initial LED state
+  digitalWrite(ledPin, ledState);
 }

 void loop() {
@@ -62,12 +67,21 @@
   if ((millis() - lastDebounceTime) > debounceDelay) {
     // whatever the reading is at, it's been there for longer
     // than the debounce delay, so take it as the actual current state:
-    buttonState = reading;
+
+    // if the button state has changed:
+    if (reading != buttonState) {
+      buttonState = reading;
+
+      // only toggle the LED if the new button state is HIGH
+      if (buttonState == HIGH) {
+        ledState = !ledState;
+
+        // set the LED:
+        digitalWrite(ledPin, ledState);
+      }
+    }
   }

-  // set the LED using the state of the button:
-  digitalWrite(ledPin, buttonState);
-
   // save the reading.  Next time through the loop,
   // it'll be the lastButtonState:
   lastButtonState = reading;


Adding structure to handle power operations

Signed-off-by: AulusDiniz <aulus999gmail.com>
Signed-off-by: ArthurJahn <32058878fe6329cceda3046384631798b4fc16ef@gmail.com>

--- core_app/core_app.ino
+++ core_app/core_app.ino
@@ -35,6 +35,8 @@
 /* Current State */
 int curState = ALARM_OFF;

+char *pwrOpTopic = "sisafa/sisafa_test/test";
+
 SIM908Client simClient(0,1,5,4,3);

 PubSubClient mqttClient(server, port, msg_callback, simClient);
@@ -53,6 +55,7 @@
   //setup used message protocol
   if (mqttClient.connect("10k2D129", "sisafa_test", "T5KIP1")) {
     //when connected, must subscribe topic power_op
+    mqttClient.subscribe(pwrOpTopic);
   }
   else{
     //restart shield


updated parallel out 2

updated parallel out 2

--- proj/parallel_out_test_2/parallel_out_test_2.ino
+++ proj/parallel_out_test_2/parallel_out_test_2.ino
@@ -1,9 +1,7 @@
 #include<FastLED.h>
-

 #define NUM_LED 90
 #define NUM_STRIPS 8
-

 CRGB leds[NUM_STRIPS * NUM_LED];


set time timeout length at top

set time timeout length at top

--- BlackLED.ino
+++ BlackLED.ino
@@ -11,7 +11,7 @@
 //#define _use_FastLED  //for all types of chips but only 3 channel !!only LPD8806 implemented in code
 #define _use_octoWS2811 //for all WS2811 type chips

-#define blackOnPollTimeOut true
+const static uint32_t blackOnPollTimeOut = 50000; //recoment more than 20000 ms

 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 //
@@ -117,7 +117,7 @@
 unsigned long currentMillis = 0;
 unsigned long previousMillis = 0;

-unsigned long lastPoll = 0;
+uint32_t lastPoll = 0;

 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 //
@@ -350,7 +350,7 @@
               //T_ArtPoll* poll = (T_ArtPoll*)udp_buffer;
               //if(poll->TalkToMe & 0x2){

-              #ifdef blackOnPollTimeOut == true
+              #ifdef blackOnPollTimeOut >= 1
                 lastPoll = millis();
               #endif

@@ -495,9 +495,9 @@

   // read temperature value
   tempVal = analogRead(38) * 0.01 + tempVal * 0.99;
-  #ifdef blackOnPollTimeOut == true
+  #ifdef blackOnPollTimeOut >= 1
     currentMillis = millis();
-    if (currentMillis - lastPoll > 20000) {
+    if (currentMillis - lastPoll > blackOnPollTimeOut) {
       for (int i = 0; i < num_led_per_output * 8; i++) {
         LEDS.setPixel(i, 0);
       }


added potentiometer test

added potentiometer test

--- proj/ledvo_lounge_final/ledvo_lounge_final.ino
+++ proj/ledvo_lounge_final/ledvo_lounge_final.ino
@@ -189,6 +189,7 @@
     if (anim_autopilot) {
       EVERY_N_SECONDS(60) {
         gAnimCounter = (gAnimCounter + 1) % numAnimation;
+        anim_switch = true;
       }
     }


added full range ADC conversion for ACS current sensor

--- src/analog_sensors_board.ino
+++ src/analog_sensors_board.ino
@@ -89,8 +89,11 @@
 // Voltage Divider (for battery levels)
 const float BAT_RK = (BAT_R1 + BAT_R2) / BAT_R2;

-// Allegro ACS715 0A to 30A
-const float ACS715_CONV = ADC_INTERNAL_MV / ACS715_MVA;         // Amps per ADC level
+// Allegro ACS715 0A to 30A     (using 2.56V ADC ref)
+//const float ACS715_CONV = ADC_INTERNAL_MV / ACS715_MVA;         // Amps per ADC level
+
+// Allegro ACS715 0A to 30A     (using 5.00V ADC ref)
+const float ACS715_CONV = ADC_DEFAULT_MV / ACS715_MVA;          // Amps per ADC level

 // Allegro ACS714 current sensor
 //const int ACS_ZERO = (int) 2500 / ADC_INTERNAL_MV;            // ADC reading for 2.5V (~ 1007)
@@ -185,7 +188,10 @@
     // }

     // switch to precise reference (2.56V)
-    analogReference(INTERNAL);
+    //analogReference(INTERNAL);
+
+    // switch to default reference (5V on Arduino Uno/Leonardo)
+    analogReference(DEFAULT);

     // Arduino Leonardo has some difficulties entering in bootloarder upload mode
     // if it is sending data to serial in loop() preventing firmware update without
@@ -381,6 +387,9 @@

     // limit data rate
     if(delta >= DELAY_SLOW) {
+        // switch to precise reference (2.56V)
+        analogReference(INTERNAL);
+
         // analog inputs (battery)
         raw_bat0 = analogRead(A0);      // J4 (pin 1)
         raw_bat0 = analogRead(A0);      // J4 (pin 1)
@@ -454,6 +463,13 @@

         // send indicators report
         report_indicators();
+
+
+        // switch to default reference (5V on Arduino Uno/Leonardo)
+        analogReference(DEFAULT);
+
+        // discard the first ADC conversion
+        analogRead(A11);

         // send timestamp


add command 'b' (brightness min value)

add command 'b' (brightness min value)

--- arduino-neopixel.ino
+++ arduino-neopixel.ino
@@ -28,7 +28,7 @@
 int e_color_g = 0;
 int e_color_b = 0;

-#define BRIGHTNESS_MIN 0.5 // 平常時のBrightness
+float brightness_min = 0.5; // 平常時のBrightness
 float brightness = 1;

 int divide = 2; // LEDパターンの分割数
@@ -101,13 +101,21 @@
       Serial.println(slit_position);
       updateLED();
     }
+    else if(command=="b") { // set brightness min value
+      // TODO argument check
+      // argument is float
+      brightness_min = argument.toInt();
+      Serial.print("set brightness min value: ");
+      Serial.println(brightness_min);
+      updateLED();
+    }
     else {
       Serial.print("Command not found: ");
       Serial.println(command);
     }
   }
   else {
-    if(BRIGHTNESS_MIN < brightness) {
+    if(brightness_min < brightness) {
       brightness -= 0.01;
       updateLED();
     }


Set wake periods to Orcas Center 9/2015 schedule

--- sketches/control/single_bench/single_bench.ino
+++ sketches/control/single_bench/single_bench.ino
@@ -32,11 +32,11 @@
 // Length of first MaxM light cycle in seconds
 // The light scripts on the MaxMs MUST be
 // shorter than this value.
-const byte maxm1_cycle = 90;
+const byte maxm1_cycle = 75;
 // const byte maxm1_cycle = 30;

 // Seconds after starting first MaxM to start second
-const byte maxm2_offset = 30;
+const byte maxm2_offset = 20;
 // const byte maxm2_offset = 15;

 // Length of time check cycle in seconds
@@ -128,15 +128,28 @@
 // 2. The sleep time of one period must be earlier than the
 //    wake time of the next period.
 // 3. This implies that the periods cannot overlap.
+
+// Set to Orcas Center schedule 9/2015
 Wakeperiod wps[] = {
-    /* {3, hm2min(8, 30), hm2min(8, 32)}, */
-    /* {3, hm2min(8, 34), hm2min(8, 36)}, */
-    /* {3, hm2min(8, 37), hm2min(8, 38)}, */
-    /* {3, hm2min(8, 40), hm2min(8, 42)}, */
-    /* {3, hm2min(9, 1), hm2min(9, 8)}, */
-    /* {3, hm2min(9, 22), hm2min(9, 24)}, */
-    /* {3, hm2min(9, 30), hm2min(9, 38)}, */
-    {3, hm2min(11, 0), hm2min(13, 0)},
+    {4,  hm2min(10, 0),  hm2min(22, 0)},
+    {5,  hm2min(17, 30), hm2min(22, 0)},
+    {6,  hm2min(17, 30), hm2min(22, 0)},
+    {8,  hm2min(10, 0),  hm2min(17, 0)},
+    {9,  hm2min(10, 0),  hm2min(17, 0)},
+    {10, hm2min(10, 0),  hm2min(17, 0)},
+    {11, hm2min(10, 0),  hm2min(17, 0)},
+    {15, hm2min(10, 0),  hm2min(17, 0)},
+    {16, hm2min(10, 0),  hm2min(17, 0)},
+    {17, hm2min(10, 0),  hm2min(17, 0)},
+    {18, hm2min(10, 0),  hm2min(17, 0)},
+    {18, hm2min(18, 30), hm2min(22, 0)},
+    {19, hm2min(17, 0),  hm2min(22, 0)},
+    {22, hm2min(10, 0),  hm2min(17, 0)},
+    {23, hm2min(10, 0),  hm2min(17, 0)},
+    {24, hm2min(10, 0),  hm2min(17, 0)},
+    {25, hm2min(10, 0),  hm2min(17, 0)},
+    {26, hm2min(17, 30), hm2min(22, 0)},
+    {29, hm2min(10, 0),  hm2min(17, 0)},
 };
 byte num_wps = sizeof(wps) / sizeof(wps[0]);


Brighter heartbeats

Brighter heartbeats

--- heartbeat_with_pulse.ino
+++ heartbeat_with_pulse.ino
@@ -350,13 +350,13 @@
   // Activate effect based on mode
   if(mode == 1) {
     // Bright pulse meter
-    minBrightnessDivisor = 150;
-    maxBrightnessDivisor = 300;
+    minBrightnessDivisor = 200;
+    maxBrightnessDivisor = 400;
     loopHeartRate();
   } else if (mode == 2) {
     // Less bright pulse meter
-    minBrightnessDivisor = 200;
-    maxBrightnessDivisor = 400;
+    minBrightnessDivisor = 300;
+    maxBrightnessDivisor = 600;
     loopHeartRate();
   } else if (mode == 3) {
     FastLED.setBrightness(BRIGHTNESS);


Comment about license

Comment about license

--- Blink2/Blink2.ino
+++ Blink2/Blink2.ino
@@ -2,7 +2,8 @@
   Blink 2
   Turns on an LED on for one second, then off for one second, repeatedly.

-  This example code is in the public domain.
+  This example code is in the public domain.
+  (but actually, we'll soon be putting most of this out there under the Apache Software Licene)
  */

 // Pin 13 has an LED connected on most Arduino boards.


keep the currentCode variable in the main source. make RESET_KEY a const auto-format the code

--- GarageKeypadSketch.ino
+++ GarageKeypadSketch.ino
@@ -1,18 +1,20 @@
 /*
   May control my garage door using a keypad
 */
-
+
 #include <Keypad.h>

-// I want to keep the secret code in another file so that I can
-// make the rest of the source code public.
+// I want to keep the secret code in another file so that I can
+// make the rest of the source code public.
 // Include the secret code with:
 #include "secretcode.h"
 //which should define the secret like this:
 //
 //const byte CODELENGTH = 5;
 //const String correctCode = "12345";
-//      String currentCode = "00000";
+
+char currentCode[sizeof(correctCode)];
+const char RESET_KEY = '*';

 const byte ROWS = 4; //four rows
 const byte COLS = 3; //three columns
@@ -20,10 +22,10 @@
 byte index = 0;

 char keys[ROWS][COLS] = {
-  {'1','2','3'},
-  {'4','5','6'},
-  {'7','8','9'},
-  {'*','0','#'}
+  {'1', '2', '3'},
+  {'4', '5', '6'},
+  {'7', '8', '9'},
+  {'*', '0', '#'}
 };
 byte rowPins[ROWS] = {8, 7, 6, 5}; //connect to the row pinouts of the keypad
 byte colPins[COLS] = {4, 3, 2}; //connect to the column pinouts of the keypad
@@ -32,59 +34,58 @@

 const int ledPin =  12;

-void setup(){
+void setup() {
   Serial.begin(9600);
   keypad.addEventListener(keypadEvent);
   pinMode(ledPin, OUTPUT);
   digitalWrite(ledPin, HIGH);
 }

-void loop(){
+void loop() {
   keypad.getKey();
 }
-
-void keypadEvent(KeypadEvent key){
-    if (keypad.getState() == PRESSED){
-        Serial.print(key);
-        Serial.print(' ');
-        Serial.println("PRESSED");
-        RecordKey(key);
-    }
+
+void keypadEvent(KeypadEvent key) {
+  if (keypad.getState() == PRESSED) {
+    Serial.print(key);
+    Serial.print(' ');
+    Serial.println("PRESSED");
+    RecordKey(key);
+  }
 }

-void RecordKey(char key){
-  if('*' == key){
+void RecordKey(char key) {
+  if (RESET_KEY == key) {
     index = 0;
     return;
   }
-
+
   currentCode[index] = key;
   index++;
-
-  if(index == CODELENGTH){
+
+  if (index == CODELENGTH) {
     checkCode();
     index = 0;
   }
 }

-void checkCode(){
+void checkCode() {
   Serial.print("checking code: ");
   Serial.println(currentCode);
-
-  if(currentCode == correctCode){
+
+  if (correctCode.equals(currentCode)) {
     Serial.println("code accepted");
     OpenTheDoor();
   }
-  else{
+  else {
     Serial.println("code rejected");
   }
 }

-void OpenTheDoor(){
+void OpenTheDoor() {
   Serial.println("closing relay . . .");
   digitalWrite(ledPin, LOW);
   delay(500);
   digitalWrite(ledPin, HIGH);
   Serial.println("opening relay");
 }
-


Performance Enhancements

Performance Enhancements

— Additional bit manipulation functions added (Line 93)
— Code structure fixed to easily enable/change functionality of program
— Reduce repetitiveness code
— Removed superfluous macros

--- Elcano_C5_Sonar/Elcano_C5_Sonar.ino
+++ Elcano_C5_Sonar/Elcano_C5_Sonar.ino
@@ -3,9 +3,8 @@
     The board uses an Arduino Micro, with interrupts on digital pins 0, 1, 2, 3 and 7.

     The interrupt numbers are 2, 3, 1, 0 and 4 respectively.
-*/
-
-/*  Two boards can hold 12 sonars on the points of a clock.
+
+    Two boards can hold 12 sonars on the points of a clock.
     The front board holds Sonar 12 (straight ahead)
     and 1, 2, and 3F to the right.
     It also holds 9F, 10, and 11 to the left.
@@ -46,41 +45,27 @@
 //  MISO    This processor's serial output
 // #################################################################################################

-
-#define cbi(port, bit) (port &= ~(1 << bit))    //Clear a bit
-#define sbi(port, bit) (port |= (1 << bit))     //Set a bit
-
-//When DEBUG_MODE is true, send data over Serial, false send data over SPI
-#define DEBUG_MODE      true
-
-//When sedning over Serial, true gives verbose output
-#define VERBOSE_DEBUG   false
-// -------------------------------------------------------------------------------------------------
-
-#define PW_OR3        7     //Pulse 9, 10 or 11 ====>> (actually pulse 1, 2, or 3 - Tai B.)
-#define IRQright_ID   4     //The interrupt ID relating to pin above
-
-#define PW_OR1        3     //Pulse on 6 or 12
-#define IRQcenter_ID  0     //The interrupt ID relating to pin above
-
+#define DEBUG_MODE       true   //When DEBUG_MODE is true, send data over Serial, false send data over SPI
+#define VERBOSE_DEBUG   false   //When sedning over Serial, true gives verbose output
+// -------------------------------------------------------------------------------------------------
+
+//Pin configuration for the Arduino Micro (atmega32u4)
 //If using I2C to communicate with rear board, its SDA will need to share pin 2 with PW_OR2
-#define PW_OR2        2     //Pulse on 1, 2, or 3; or I2C. (actually pulse on 9, 10, or 11 - Tai B.)
-#define IRQleft_ID    1     //The interrupt ID relating to pin above
-// -------------------------------------------------------------------------------------------------
-
-//S-DECx pins good - Tai B.
-#define S_DEC1        5     //Low order bit for selecting the round
-#define S_DEC2        6     //Hi bit of round select
-
-//POWER good - Tai B.
-#define V_EN         13     //Apply power to sonars
-#define V_TOGGLE      4     //(V_TOGGLE) HIGH for 3.4v, LOW for 5v sonar power
-
-#define F_BSY        11     //pin signals to rear sonar board       IMPORTANT - FBSY should be pin  11 was 9
-#define R_BSY         8     //pin signals from rear sonar bord      IMPORTANT - RBSY should be pin  8 was 10
-// -------------------------------------------------------------------------------------------------
-
-#define DEBUG_PIN   A0      //Light-emitting diode indicator for DEBUG_status = TRUE
+#define PW_OR3       7     //Pulse on 9, 10 or 11 ====>> (actually pulse 1, 2, or 3 - Tai B.)
+#define PW_OR1       3     //Pulse on 6 or 12
+#define PW_OR2       2     //Pulse on 1, 2, or 3; or I2C. (actually pulse on 9, 10, or 11 - Tai B.)
+
+#define S_DEC1       5     //Low order bit for selecting the round     //S-DECx pins good - Tai B.
+#define S_DEC2       6     //Hi bit of round select
+
+#define V_ENABLE    13     //Apply power to sonars                     //POWER good - Tai B.
+#define V_TOGGLE     4     //(V_TOGGLE) HIGH for 3.4v, LOW for 5v sonar power
+
+#define F_BSY       11     //pin signals to rear sonar board       IMPORTANT - FBSY should be pin 11 was 9
+#define R_BSY        8     //pin signals from rear sonar bord      IMPORTANT - RBSY should be pin 8 was 10
+// -------------------------------------------------------------------------------------------------
+
+#define DEBUG_PIN   A0     //Light-emitting diode indicator for DEBUG_status = TRUE

 //Analog input pins from sonars
 // #define ANx  Ay // x is clock position; Ay is the analog input channel
@@ -98,17 +83,25 @@
 #define ROUND_DELAY     100 //ms between rounds, seems to help stability

 //Modify EXPECTED_SIGNALS to match which sonars are on the board.
-#define EXPECTED_SIGNALS1   3
-#define EXPECTED_SIGNALS2   3
-#define EXPECTED_SIGNALS3   2
-#define COMMAND_GO          1
+#define EXPECTED_SIGNALS1    3
+#define EXPECTED_SIGNALS2    3
+#define EXPECTED_SIGNALS3    2
+#define COMMAND_GO           1
 #define RANGE_DATA_SIZE     13
-
-#include "pins_arduino.h"
-
-enum STATE { INITIAL, READY, ROUND1, ROUND2, ROUND3 };
-
-STATE boardState = INITIAL;     //initializing sonar board state
+// -------------------------------------------------------------------------------------------------
+
+//Bit Manipulation Functions
+#define cbi(port, bit) (port &= ~(1 << bit))        //Clear a bit
+#define sbi(port, bit) (port |= (1 << bit))         //Set a bit
+#define tbi(port, bit) (port ^= (1 << bit))         //toggle a bit
+#define ibh(port, bit) ((port & (1 << bit)) > 0)    //Is a bit high
+#define ibl(port, bit) ((port & (1 << bit)) == 0)   //Is a bit low
+// -------------------------------------------------------------------------------------------------
+
+enum STATE : byte { INITIAL, READY, ROUND1, ROUND2, ROUND3 };
+STATE boardState;   //initializing sonar board state
+
+// enum SONAR : byte {};

 volatile byte SignalsReceived;
 volatile unsigned long timeLeft;
@@ -116,30 +109,30 @@
 volatile unsigned long timeCenter;

 volatile unsigned long timeStart;
-// volatile unsigned long timeLeftStart;        //currently not being used
-// volatile unsigned long timeRightStart;       //currently not being used
-// volatile unsigned long timeCenterStart;      //currently not being used
-
-volatile boolean timeStartSet;
-// volatile boolean timeLeftStartSet;           //currently not being used
-// volatile boolean timeRightStartSet;          //currently not being used
-// volatile boolean timeCenterStartSet;         //currently not being used
+// volatile unsigned long timeLeftStart;       //currently not being used
+// volatile unsigned long timeRightStart;      //currently not being used
+// volatile unsigned long timeCenterStart;     //currently not being used
+
+volatile bool timeStartSet;
+// volatile bool timeLeftStartSet;             //currently not being used
+// volatile bool timeRightStartSet;            //currently not being used
+// volatile bool timeCenterStartSet;           //currently not being used

 //For SPI communications
 volatile unsigned long timeWriteStart;
 volatile byte valueIn;
-volatile boolean processIt;
-
-int range[RANGE_DATA_SIZE] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
-int analogRange[RANGE_DATA_SIZE] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
+volatile bool processIt;
+
+int range[RANGE_DATA_SIZE]{};
+int analogRange[RANGE_DATA_SIZE]{};
+
 int roundCount, timeoutStart, timeSinceLastRound;
+byte boardCount; //just the front board

 volatile int isr1Count, isr2Count, isr3Count;

-const byte BoardCount = 1;      //just the front board
-const int SCALE_FACTOR = 58;    //to calculate the distance, use the scale factor of 58us per cm
+const byte SCALE_FACTOR = 58;   //to calculate the distance, use the scale factor of 58us per cm
 const int BAUD_RATE = 115200;
-

 // -------------------------------------------------------------------------------------------------
 void setup()
@@ -149,31 +142,33 @@

     if (DEBUG_MODE)
     {
+        //Baud rate configured for 115200
+        //It communicates on digital pins 0 (RX) and 1 (TX) as well as with the computer via USB
+        Serial.begin(BAUD_RATE);
+
         digitalWrite(DEBUG_PIN, HIGH);
     }
-
-    //Serial Peripheral Interface (SPI) Setup
-    pinMode(MISO, OUTPUT);
-
-    //SPI Control Register (SPCR)
-    SPCR |= _BV(SPE);   //Turn on SPI in slave mode (SPI Enable)
-    SPCR |= _BV(SPIE);  //Turn on interrupts for SPI (SPI Interrupt Enable)
-
-    processIt = false;  //False until we have a request to process
-
+    else
+    {
+        //Serial Peripheral Interface (SPI) Setup
+        pinMode(MISO, OUTPUT);
+
+        //SPI Control Register (SPCR)
+        SPCR |= _BV(SPE);   //Turn on SPI in slave mode (SPI Enable)
+        SPCR |= _BV(SPIE);  //Turn on interrupts for SPI (SPI Interrupt Enable)
+
+        processIt = false;  //False until we have a request to process
+    }
+
     // timeLeftStart = timeRightStart = timeCenterStart = 0;
     timeLeft = timeRight = timeCenter = timeStart = 0;
     roundCount = timeoutStart = timeSinceLastRound = 0;
     isr1Count = isr2Count = isr3Count = 0;

-    timeLeftStartSet = false;
-    timeRightStartSet = false;
-    timeCenterStartSet = false;
+    // timeLeftStartSet = false;
+    // timeRightStartSet = false;
+    // timeCenterStartSet = false;
     timeStartSet = false;
-
-    //Baud rate configured for 115200
-    //It communicates on digital pins 0 (RX) and 1 (TX) as well as with the computer via USB
-    Serial.begin(BAUD_RATE);

     pinMode(S_DEC1, OUTPUT);        //Pin 5 (PWM)       --> SD1
     pinMode(S_DEC2, OUTPUT);        //Pin 6 (PWM/A7)    --> SD2
@@ -183,20 +178,21 @@
     pinMode(PW_OR2, INPUT);         //Pin 2 (SDA)       --> PW2
     pinMode(PW_OR3, INPUT);         //Pin 7             --> PW3

-
-    boardState = INITIAL;
-    BoardCount = 1;
-
-    digitalWrite(S_DEC1, LOW);
-    digitalWrite(S_DEC2, LOW);
+    boardState = INITIAL;
+    SignalsReceived = 0;
+    boardCount = 1;
+
+    // digitalWrite(S_DEC1, LOW);
+    // digitalWrite(S_DEC2, LOW);
+    setRound(0, 0);

     digitalWrite(F_BSY, HIGH); //Signal rear board that we are here; See if there is a rear board
-
-    //Select 5V power(LOW), or 3.8V power(HIGH)
-    digitalWrite(V_TOGGLE, LOW);    //Pin 4 (A6)        --> VTOG
+    digitalWrite(V_TOGGLE, LOW); //Select 5V power(LOW), or 3.8V power(HIGH)
+//    digitalWrite(V_TOGGLE, HIGH); //Select 5V power(LOW), or 3.8V power(HIGH)
+

     //Turn on sonars
-    digitalWrite(V_EN, HIGH);
+    digitalWrite(V_ENABLE, HIGH);

     //for (int i = 0; i < 1000; i++)
@@ -205,7 +201,7 @@
     //    byte Rear = digitalRead(R_BSY);
     //    if (Rear == HIGH)
     //    {
-    //        BoardCount = 2;
+    //        boardCount = 2;
     //        //Need to dynamically attach/detacy PW_OR2 so that it is shared between IntRight and I2C
     //        break;
     //    }
@@ -214,9 +210,9 @@
     //Required delay above 175ms after power-up with the board for all XL-MaxSonars to be ready
     delay(200); //Per sonar datasheet, needs 175ms for boot

-    attachInterrupt(IRQleft_ID, IsrLeft, CHANGE);
-    attachInterrupt(IRQcenter_ID, IsrCenter, CHANGE);
-    attachInterrupt(IRQright_ID, IsrRight, CHANGE);
+    attachInterrupt( digitalPinToInterrupt(PW_OR2), IsrLeft, CHANGE );
+    attachInterrupt( digitalPinToInterrupt(PW_OR1), IsrCenter, CHANGE );
+    attachInterrupt( digitalPinToInterrupt(PW_OR3), IsrRight, CHANGE );

     digitalWrite(F_BSY, LOW); //Open for business
     boardState = READY;
@@ -241,7 +237,8 @@
     isr1Count++;

     //Checks the PWM from PW_OR3 is HIGH
-    if (digitalRead(PW_OR3) == HIGH && !timeStartSet)
+    if (digitalRead(PW_OR3) == HIGH && timeStartSet == false)
+    // if (ibh(PINE, PE6) && !timeStartSet)
     {
         timeStart = micros();
         timeStartSet = true;
@@ -263,7 +260,8 @@

     isr2Count++;

-    if (digitalRead(PW_OR1) == HIGH && !timeStartSet)
+    if (digitalRead(PW_OR1) == HIGH && timeStartSet == false)
+    // if (ibh(PIND, PD2) && !timeStartSet)
     {
         timeStart = micros();
         timeStartSet = true;
@@ -282,13 +280,12 @@
 void IsrRight()
 {
     //ISR for end of pulse on sonar 1, 2 or 3
-    //Log time of the pulse end
-
     noInterrupts();

     isr3Count++;

-    if (digitalRead(PW_OR2) == HIGH && !timeStartSet)
+    if (digitalRead(PW_OR2) == HIGH && timeStartSet == false)
+    // if (ibh(PIND, PD1) && !timeStartSet)
     {
         timeStart = micros();
         timeStartSet = true;
@@ -307,25 +304,19 @@
 {
     boardState = READY;

-    digitalWrite(S_DEC1, LOW);
-    digitalWrite(S_DEC2, LOW);   // superfluous
+    setRound(0, 0); //Send a pulse on sonars, superfluous
+
     //readInput(); //Sonar is slave waiting for command from master
     //TO DO: Send start signal to rear board.

+    interrupts(); // Not sure if we need this here at all
+
 //****** ROUND 1 ***************************************************************
     boardState = ROUND1;
     SignalsReceived = 0;
-    //Send a pulse on sonars
-    interrupts();
-    //digitalWrite(S_DEC2, HIGH);
-    setRound(0, 1);
-
-    timeoutStart = millis();
-    while (SignalsReceived < EXPECTED_SIGNALS1)
-    {
-        if ((millis() - timeoutStart) > TIMEOUT_PERIOD) { break; }
-    }
-    delay(ROUND_DELAY);
+
+    setRound(0, 1); //Send a pulse on sonars
+    delayPeriod(EXPECTED_SIGNALS1);

     //==== extra interrupt data holders for timing tests ========
     //    timeLeftStartSet = false;
@@ -339,25 +330,17 @@
     range[3]  = (timeRight - timeStart) / SCALE_FACTOR;
     range[9]  = (timeLeft - timeStart) / SCALE_FACTOR;

-    analogRange[12] = analogRead(AN12);
-    analogRange[3] =  analogRead(AN3);
-    analogRange[9] =  analogRead(AN9);
+    // analogRange[12] = analogRead(AN12);
+    // analogRange[3] =  analogRead(AN3);
+    // analogRange[9] =  analogRead(AN9);

 //****** ROUND 3 ***************************************************************
-    // Gray code; only one bit changes at a time
     boardState = ROUND3;
-    SignalsReceived = 0;
-    //Send a pulse on sonars
-    //digitalWrite(S_DEC1, HIGH);
-    setRound(1, 1);
-
-    timeoutStart = millis();
-    while (SignalsReceived < EXPECTED_SIGNALS3)
-    {
-        if ((millis() - timeoutStart) > TIMEOUT_PERIOD) { break; }
-    }
-    delay(ROUND_DELAY);
+    SignalsReceived = 0;
+
+    setRound(1, 1); //Send a pulse on sonars
+    delayPeriod(EXPECTED_SIGNALS3);

     //==== extra interrupt data holders for timing tests ========
     //    timeLeftStartSet = false;
@@ -369,23 +352,16 @@
     range[10] = (timeLeft - timeStart) / SCALE_FACTOR;
     range[1]  = (timeRight - timeStart) / SCALE_FACTOR;

-    analogRange[10] = analogRead(AN10);
-    analogRange[1] =  analogRead(AN1);
+    // analogRange[10] = analogRead(AN10);
+    // analogRange[1] =  analogRead(AN1);

 //****** ROUND 2 ***************************************************************
     boardState = ROUND2;
-    SignalsReceived = 0;
-    //Send a pulse on sonars
-    //digitalWrite(S_DEC2, LOW);
-    setRound(1, 0);
-
-    timeoutStart = millis();
-    while (SignalsReceived < EXPECTED_SIGNALS2)
-    {
-        if ((millis() - timeoutStart) > TIMEOUT_PERIOD) { break; }
-    }
-    delay(ROUND_DELAY);
+    SignalsReceived = 0;
+
+    setRound(1, 0); //Send a pulse on sonars
+    delayPeriod(EXPECTED_SIGNALS2);

     //==== extra interrupt data holders for timing tests ========
     //    timeLeftStartSet = false;
@@ -399,14 +375,12 @@
     range[2]  = (timeRight - timeStart) / SCALE_FACTOR;
     range[6]  = (timeCenter - timeStart) / SCALE_FACTOR;

-    analogRange[11] = analogRead(AN11);
-    analogRange[2] =  analogRead(AN2);
-    analogRange[6] =  analogRead(AN6);
-
-
+    // analogRange[11] = analogRead(AN11);
+    // analogRange[2] =  analogRead(AN2);
+    // analogRange[6] =  analogRead(AN6);
+
     //TO DO: Receive data from rear board
     writeOutput();
-    boardState = READY;
     roundCount++;
 }

@@ -463,6 +437,19 @@
         cbi(PORTC, PORTC6);     // digitalWrite(S_DEC1, LOW);
         cbi(PORTD, PORTD7);     // digitalWrite(S_DEC2, LOW);
     }
+}
+
+
+// -------------------------------------------------------------------------------------------------
+void delayPeriod(byte expectedSingal)
+{
+    timeoutStart = millis();
+    while (SignalsReceived < expectedSingal)
+    {
+        if ((millis() - timeoutStart) > TIMEOUT_PERIOD) { break; }
+    }
+
+    delay(ROUND_DELAY);
 }

@@ -508,10 +495,10 @@
             Serial.print(" Vals: ");
         }

-        for (int index = 1; index < RANGE_DATA_SIZE; ++index)
+        for (int index = 1; index < RANGE_DATA_SIZE; index++)
         {
             //Prints out only the sonars for one board (9, 10, 11, 12, 1, 2, 3)
-            if (BoardCount == 1 && (index == 4 || index == 5 || index == 7 || index == 8)) { continue; }
+            if (boardCount == 1 && (index == 4 || index == 5 || index == 7 || index == 8)) { continue; }

             if (index < 10) { Serial.print("[ "); }
             else { Serial.print('['); }


Update pt_ex4_led_individually.ino

Update pt_ex4_led_individually.ino

--- pt_ex/pt_ex4_led_individually.ino
+++ pt_ex/pt_ex4_led_individually.ino
@@ -151,13 +151,17 @@

         Serial.println(p);
         if ( 11 == p ) state1 = 1;
-        else if ( 12 == p ) state1 = 0;
+        else if ( 12 == p ) {
+          state1 = 0;
+          state2 = 0;
+        }
         else if ( 21 == p ) state2 = 1;
-        else if ( 22 == p ) state2 = 0;
+        else if ( 22 == p ) {
+          state3 = 0;
+          state4 = 0;
+        }
         else if ( 31 == p ) state3 = 1;
-        else if ( 32 == p ) state3 = 0;
         else if ( 41 == p ) state4 = 1;
-        else if ( 42 == p ) state4 = 0;
         else if ( 51 == p ) state5 = 1;
         else if ( 52 == p ) state5 = 0;
         else if ( 61 == p ) state6 = 1;


feat: Switching to external antenna

feat: Switching to external antenna

--- kiln.ino
+++ kiln.ino
@@ -78,6 +78,9 @@
 		/*sleep(MEASUREMENT_INTERVAL);*/
 	} else {
 		Serial.println("Oh noes!  Couldn't read from our sensors!");
+
+		delay(1000);
+		Serial.println(String::format("Wifi strength: %d", WiFi.RSSI()));
 	}

 	// we'll only get here if something went wrong.  wait a little while before
@@ -88,6 +91,8 @@
 void wakeUp() {
 	pinMode(POWER_PIN, OUTPUT);
 	digitalWrite(POWER_PIN, HIGH);
+
+	WiFi.selectAntenna(ANT_EXTERNAL);

 	delay(WAKEUP_DELAY);


Move display configuration to setup().

Move display configuration to setup().

--- main.ino
+++ main.ino
@@ -20,10 +20,6 @@
     static int count = 0;

     display.clearDisplay();
-
-    display.setRotation(0);
-    display.setTextSize(1);
-    display.setTextColor(BLACK);

     display.setCursor(0,0);
     display.println("   2.5  10");
@@ -58,6 +54,11 @@
 void setup()
 {
     display.begin();
+
+    display.setRotation(2);
+    display.setTextSize(1);
+    display.setTextColor(BLACK);
+
     display.clearDisplay();
     display.setCursor(0,0);
     display.println("START");


updated LCD display, changed pressure display unit to hPa

--- mwsLCD/mwsLCD.ino
+++ mwsLCD/mwsLCD.ino
@@ -584,7 +584,7 @@
   lcd.clear();
   lcd.print("Pressure (hPa)");
   lcd.setCursor(0, 2);
-  lcd.print(pressure);
+  lcd.print(pressure/100.0);
   delay(2000);

   //Serial.print(",batt_lvl=");


removed spaces

removed spaces

--- wifisense_GWY/wifisense_GWY.ino
+++ wifisense_GWY/wifisense_GWY.ino
@@ -6,8 +6,6 @@

 // This #include statement was automatically added by the Particle IDE.
 #include <MQTT.h>
-
-//

 // xbee object
 XBee xbee = XBee();


fix mute in ctcss example

fix mute in ctcss example

--- examples/CTCSS/CTCSS.ino
+++ examples/CTCSS/CTCSS.ino
@@ -101,7 +101,7 @@
   Serial.print("ctcss tone: ");
   Serial.println(radio.getCtcssFreqHz());
   // mute audio until we get a CTCSS tone
-//  radio.setMute();
+  radio.setMute();
   muted = true;

   // configure Arduino LED for
@@ -117,13 +117,13 @@
     if (radio.getCtcssToneDetected()) {
       if (muted) {
         muted = false;
-  //      radio.setUnmute();
+        radio.setUnmute();
         Serial.println("tone");
       }
     } else {
       if (!muted) {
         muted = true;
-  //      radio.setMute();
+        radio.setMute();
         Serial.println("no tone");
       }
     }
@@ -139,13 +139,17 @@
       // set to transmit
       radio.setModeTransmit();
       Serial.println("Tx");
-      //radio.setTxSourceMic();
-      //radio.setRfPower(1);
+
+      radio.setUnmute(); // can't mute during transmit
+      muted = false;
     }
   } else if (currently_tx) {
     radio.setModeReceive();
     currently_tx = false;
     Serial.println("Rx");
+
+    radio.setMute(); // default to mute during rx
+    muted = true;
   }

   // handle serial commands


RFID tag stuck on reader to continue logging

--- module/module.ino
+++ module/module.ino
@@ -175,15 +175,12 @@
 				soundFeedback(reject);
 				Serial.print(messages.cancel);
 				sendCount = (millis() - startTime)/1000;
-				while(1) {
-					if (sendCount > minCount) {
-						Serial.println(sendCount);
-					}
-          else {
-            Serial.println(0);
-          }
+				if (sendCount > minCount) {
+          return sendCount;
 				}
-				return sendCount;
+        else {
+				  return 0;
+        }
 			}
 		}
 		else {
@@ -227,10 +224,7 @@
 					// calculate elapsed time and push to ThingSpeak log
 					sendCount = (millis() - startTime)/1000;
 					Serial.print("Sending... Time: ");
-					while (1) {
-						Serial.println(sendCount);
-					}
-					//Serial.println(sendCount);
+					Serial.println(sendCount);
 					// Make sure logs are properly spaced out
 					if ( (millis() - lastSend) < sendInterval) {
 						delay(sendInterval);
@@ -239,7 +233,6 @@
 					updateThingSpeak(sendCount);
 					lastSend = millis();
 					Serial.println("Done");
-					return sendCount;
 				}
 				periodCount = 0;
 			}
@@ -248,6 +241,7 @@
 		// record the previous state
 		lastPeriodX = periodX;
 		lastPeriodY = periodY;
+
 		delay(pollInterval);
 	}
 }


fixed typo in sensor_array

fixed typo in sensor_array

--- exhaust_sensor_array.ino
+++ exhaust_sensor_array.ino
@@ -61,7 +61,7 @@
   log_file = SD.open("log.csv", FILE_WRITE);

   //read from sensors
-  for(unsigned int i=0; i < 6; ++i) array[i] = analogRead(i);
+  for(unsigned int i=0; i < 6; ++i) sensor_array[i] = analogRead(i);

   // update GPS
   while(gps_port.available()) gps.encode(gps_port.read());


piccoli fix

piccoli fix

--- prova/src/provavoltage.ino
+++ prova/src/provavoltage.ino
@@ -16,17 +16,13 @@
 int watch_dog_counter = 2;
 volatile byte reg_position = 0;
 const byte reg_size = sizeof(cv.dati); //dati son il valore della tensione vedi checkvoltage.ino
-/*volatile uint8_t i2c_regs[] =
-{
-    0xDE,
-    0xAD,
-    0xBE,
-    0xEF,
-};*/
 void setup(){
+  delay(300);
   pinMode(pinLed,OUTPUT);
   cv.begin();
+  cv.readVcc();
   setup_watchdog(9); // approximately 8 seconds sleep
+  reg_position = 0;
   TinyWireS.begin(I2C_SLAVE_ADDRESS);
   TinyWireS.onReceive(receiveEvent);
   TinyWireS.onRequest(requestEvent);
@@ -34,11 +30,10 @@
 void loop(){
   if (watch_dog_counter>=2) {  // 90*8 sec =13 min : wait for timed out watchdog / flag is set when a watchdog timeout occurs
     watch_dog_counter=0;        // reset flag
-    powerESP();
+    digitalWrite(pinLed,HIGH);  // let led blink -> esp-01 power on
   }
   TinyWireS_stop_check();
 }
-
 void requestEvent()
 {
   TinyWireS.send(cv.dati[reg_position]);
@@ -65,26 +60,6 @@
     reg_position = TinyWireS.receive();
     if(reg_position == 20) powerDownEsp();
 }
-
-void powerESP()
-{
-cv.readVcc();
-  //cv.readVcc();
-  digitalWrite(pinLed,HIGH);  // let led blink -> esp-01 power on
-  //tws_delay(50);
-
-
-  //reg_position = 0;
-  //uint16_t  sumvolt = 0;
-  //for (int i=0; i = 2; i++){
-  //Checkvoltage cv;
-
-  //  sumvolt = sumvolt +cv.volt;
-  //}
-  //sumvolt = sumvolt / 3;
-  //cv.dati[0]=sumvolt & 0xff;
-  //cv.dati[1]=(sumvolt >> 8);
-}
 void powerDownEsp(){
   tws_delay(50);
   digitalWrite(pinLed,LOW);   // esp-01  power off


デバッグ用出力

デバッグ用出力

--- 2_example/example61u_dash/promiscuous.ino
+++ 2_example/example61u_dash/promiscuous.ino
@@ -52,10 +52,9 @@
 	int len = p->rx_ctrl.sig_len;
 	len -= sizeof(WifiMgmtHdr);
 	if (len < 0){
-		Serial.println("Received 0");
+		if(DEBUG_MAC) Serial.println("Received 0");
 		return;
 	}
-
 	if(memcmp(mac->sa,mac->bssid,6)==0)return;	// ビーコンの除去
 	if(_mac_prev_n && !memcmp(_mac_prev,mac->sa,6)){
 		if( _mac_fc_hold || _fc_prev == mac->fctl){
@@ -69,6 +68,18 @@

 	if(!_mac_read_i) memcpy(_recieved_mac,mac->sa,6);
 	_mac_read_i++;
+
+	if( DEBUG_MAC ){
+		Serial.printf("FC=%04x from=%02x:%02x:%02x:%02x:%02x:%02x\n",
+			_fc_prev,
+			mac->sa[0],
+			mac->sa[1],
+			mac->sa[2],
+			mac->sa[3],
+			mac->sa[4],
+			mac->sa[5]
+		);
+	}
 }

 int promiscuous_get_mac(byte *mac){
@@ -85,7 +96,7 @@

 void promiscuous_start(byte channel){
 	if( DEBUG_MAC ){
-		Serial.print("ESP8266 promiscuous mode started. Channel: ");
+		Serial.print("ESP32 promiscuous mode started. Channel: ");
 		Serial.println(channel);
 		Serial.println("Please turn on your wi-fi STA or push Amazon Dash Button");
 	}


adding discovery timer

adding discovery timer

--- glass/glass.ino
+++ glass/glass.ino
@@ -26,12 +26,17 @@
 int ledPin = 8;

 struct XBeePacket XBeePacketArr[20];
+char XBeeReturnIDs[20];
+int XBeeReturnCount;
+
 char message[50];
 enum mode {
   BTMode,
-  XBeeMode
+  XBeeMode,
+  WaitMode
 };
 mode m;
+unsigned long start_time;

 void setup()
 {
@@ -41,6 +46,7 @@
   BT.begin(57600);
   delay(300);
   m = BTMode;
+  XBeeReturnCount = 0;
   Serial.print("system begins");
 }

@@ -58,11 +64,10 @@
         DEBUG_PRINT("[INIT] Sending IR: ");
         DEBUG_PRINTLN(session_id);
         irsend.sendSony(session_id, 16);
-        m = XBeeMode;
+        XBeeReturnCount = 0;
+        start_time = millis();
+        m = WaitMode;
         XBee.begin(9600);
-        // TODO
-        // better wait for a while before ending XBee session
-        //
       }
       else {
         XBee.begin(9600);
@@ -81,5 +86,29 @@
       m = BTMode;
     }
   }
+  else if (m == WaitMode) {
+    if (XBee.available()) {
+      if (XBeeReturnCount >= 1) {
+        XBeeReturnIDs[XBeeReturnCount*3-2] = ':';
+      }
+      readStringfromSerial(&XBee, message);
+      XBeeReturnIDs[XBeeReturnCount*3] = message[0];
+      XBeeReturnIDs[XBeeReturnCount*3+1] = message[1];
+      XBeeReturnCount++;
+    }
+    if (millis() - start_time > 1000) {
+      if (XBeeReturnCount > 0)
+        XBeeReturnIDs[XBeeReturnCount*3-1] = '\0';
+      else
+        XBeeReturnIDs[0] = '\0';
+      DEBUG_PRINT("IDs list:");
+      DEBUG_PRINTLN(XBeeReturnIDs);
+      DEBUG_PRINT("IDs counts:");
+      DEBUG_PRINTLN(XBeeReturnCount);
+      BT.print(XBeeReturnIDs);
+      m = BTMode;
+      BT.begin(57600);
+    }
+  }
   delay(10);
 }


optimzed

optimzed

--- optimizedThird/optimizedThird.ino
+++ optimizedThird/optimizedThird.ino
@@ -9,6 +9,86 @@
 #define CLOSE 'c'

 SoftwareSerial mySerial(10, 11);
+
+int x, y, z, emg1, emg2, emgsignal_counter, jointexcess_prevention, jointcounter, grippercounter ;
+int emgcounter = 0;
+int i = 2148;
+int j = 2048;
+int k = 2048;
+int joint = 2;
+
+void checkSum(){
+  int infoPk[24];
+  }
+
+void movements(){
+  checkSum();
+
+  while(y > 600 && emg1 < 150 && emg2 < 150 && z > 300 && z < 700){         //Tilting the head to the right moves joint 1 to the right
+  i = i + 10;
+  Dynamixel.setNGoalPositions(i, -1, -1, -1, -1);
+  break;
+}
+while(y < 400 && emg1 < 150 && emg2 < 150 && z > 300 && z < 700){         //Tilting the head to the left moves joint 1 to the left
+  i = i - 10;
+  Dynamixel.setNGoalPositions(i, -1, -1, -1, -1);
+  break;
+}
+
+  while(emg1 > 150 && emg1 < 600 && emgsignal_counter==0 && jointcounter==0 && y < 700 && y > 300 && z > 300 && z < 700){    //Set the emg1 to move the joints up in a cycle from 2 to 3
+  joint++;
+  //jointexcess_prevention++;
+  jointcounter++;
+  emgsignal_counter++;
+  break;
+  }
+while(emg1 > 150 && emg1 < 600 && emgsignal_counter==0 && jointcounter==1 && y < 700 && y > 300 && z > 300 && z < 700){    //Set the emg1 to move the joints up in a cycle from 2 to 3
+  joint--;
+  //jointexcess_prevention--;
+  jointcounter--;
+  emgsignal_counter++;
+  break;
+  }
+
+  while(joint == 2 && z > 550 && y < 700 && y > 300 && emg1 < 100 && emg2 < 100){            //Tilting forward moves joint 2 down
+  j = j + 10;
+  Dynamixel.setNGoalPositions(-1, j, -1, -1, -1);
+  break;
+}
+while(joint == 2 && z < 300 && y < 700 && y > 300 && emg1 < 100 && emg2 < 100){            //Tilting backward moves joint 2 up
+  j = j - 10;
+  Dynamixel.setNGoalPositions(-1, j, -1, -1, -1);
+  break;
+}
+while(joint == 3 && z > 550 && y < 700 && y > 300 && emg1 < 100 && emg2 < 100){            //Tilting forward moves joint 3 down
+  k = k + 10;
+  Dynamixel.setNGoalPositions(-1, -1, k, -1, -1);
+  break;
+}
+while(joint == 3 && z  < 300 && y < 700 && y > 300 && emg1 < 100 && emg2 < 100){           //Tilting backward moves joint 3 up
+  k = k - 10;
+  Dynamixel.setNGoalPositions(-1, -1, k, -1, -1);
+  break;
+}
+
+  while(emg2 > 0 && emg2 < 600 && emgsignal_counter==0 && emgcounter==0 && grippercounter==0 && y < 700 && y > 300 && emg1 < 100 && z > 300 && z < 700){   //Opens the gripper using the Emg2
+Dynamixel.gripper(OPEN);
+emgsignal_counter++;
+emgcounter++;
+grippercounter++;
+break;
+}
+while(emg2 > 0 && emg2 < 600 && emgsignal_counter==0 && emgcounter==1 && grippercounter==1 && y < 700 && y > 300 && emg1 < 100 && z > 300 && z < 700){   //Closes the gripper using the Emg2
+Dynamixel.gripper(CLOSE);
+emgsignal_counter++;
+emgcounter--;
+grippercounter--;
+break;
+}
+if(emg1 < 100 && emg2 == 0){                                         //Set the emg2 to open and close the gripper
+  emgsignal_counter=0;
+}
+}

 void setup(){
   Serial1.begin(xBEE_SET_Baudrate);
@@ -38,3 +118,7 @@
   Dynamixel.setProfileVelocity(0x04, 100);
   Dynamixel.setProfileVelocity(0x05, 100);
   }
+
+void loop(){
+  movements();
+  }


Poperly combine the three synth together

The synths are combined using a volume parameter, rhoughly equal to
the roll/pitch.

--- nuncha/nuncha.ino
+++ nuncha/nuncha.ino
@@ -10,25 +10,27 @@
 #define UP 2

 int bumpy_input = 0;
+int constrain_input = 0;

 int rollpitch = 0;

 #include <Oscil.h> // oscillator template
 #include <tables/sin2048_int8.h> // sine table for oscillator
 #include <tables/triangle2048_int8.h> // triangle table for oscillator
-#include <tables/saw2048_int8.h> // saw table for oscillator
-#include <RollingAverage.h>
+#include <tables/triangle_analogue512_int8.h> // saw table for oscillator

 // use: Oscil <table_size, update_rate> oscilName (wavetable), look in .h file of table #included above
 Oscil <SIN2048_NUM_CELLS, AUDIO_RATE> aSin(SIN2048_DATA);
 Oscil <TRIANGLE2048_NUM_CELLS, AUDIO_RATE> aTri(TRIANGLE2048_DATA);
-Oscil <SAW2048_NUM_CELLS, AUDIO_RATE> aSaw(SAW2048_DATA);
+Oscil <TRIANGLE_ANALOGUE512_NUM_CELLS, AUDIO_RATE> aSaw(TRIANGLE_ANALOGUE512_DATA);

+// Average the input signals
+#include <RollingAverage.h>
 // use: RollingAverage <number_type, how_many_to_average> myThing
 // how_many_to_average has to be power of 2
-RollingAverage <float, 8> rollLAverage;
-RollingAverage <float, 8> rollRAverage;
-RollingAverage <float, 8> pitchAverage;
+RollingAverage <float, 16> rollLAverage;
+RollingAverage <float, 16> rollRAverage;
+RollingAverage <float, 16> pitchAverage;
 RollingAverage <float, 4> xAverage;
 RollingAverage <float, 4> yAverage;
 int rollLeft;
@@ -37,12 +39,18 @@
 int xStick;
 int yStick;

+unsigned char volumeLeft;
+unsigned char volumeRight;
+unsigned char volumePitch;
+
 int play = 0;

 void setup(){
   uint8_t error;

   error = Nunchuck.begin ();
+
+  //Serial.begin(19200);

   /*if ( error )
   {
@@ -54,9 +62,9 @@
   startMozzi(CONTROL_RATE); // set a control rate of 64 (powers of 2 please)

   // set the frequency
-  aSin.setFreq(440);
-  aTri.setFreq(440);
-  aSaw.setFreq(440);
+  aSin.setFreq(0);
+  aTri.setFreq(0);
+  aSaw.setFreq(0);
 }

 void updateControl(){
@@ -64,21 +72,35 @@

    Nunchuck.update();

-   if ( !Nunchuck.getZButton() )
+   //Serial.print(Nunchuck . getRaw()->yStick);
+   //Serial.print(' ');
+   //Serial.println((int)volume);
+
+   if ( Nunchuck.getZButton() )
    {
-     bumpy_input = constrain(Nunchuck . getRoll(), -180, -1);
-     bumpy_input = map(-bumpy_input, 0, 180, 0, 800);
+     constrain_input = constrain(Nunchuck . getRoll(), -180, -1);
+     bumpy_input = map(-constrain_input, 0, 180, 0, 800);
+     constrain_input = constrain(-constrain_input, 0, 100);
+     volumeLeft = map(constrain_input, 0, 100, 0, 255);
      rollLeft = rollLAverage.next(bumpy_input);
-     bumpy_input = constrain(Nunchuck . getRoll(), 0, 180);
-     bumpy_input = map(bumpy_input, 0, 180, 0, 800);
+     constrain_input = constrain(Nunchuck . getRoll(), 0, 180);
+     bumpy_input = map(constrain_input, 0, 180, 0, 800);
+     constrain_input = constrain(constrain_input, 0, 100);
+     volumeRight = map(constrain_input, 0, 100, 0, 255);
      rollRight = rollRAverage.next(bumpy_input);
-     bumpy_input = constrain(Nunchuck . getPitch(), 100, 174);
-     bumpy_input = map(bumpy_input, 100, 174, 0, 800);
+     constrain_input = constrain(Nunchuck . getPitch(), 100, 130);
+     bumpy_input = map(constrain_input, 100, 174, 0, 800);
+     constrain_input = constrain(constrain_input, 100, 144);
+     volumePitch = map(constrain_input, 100, 144, 0, 150);
      pitch = pitchAverage.next(bumpy_input);
+
+     constrain_input = constrain(Nunchuck . getRaw()->yStick, 31, 129);
+     bumpy_input = map(-constrain_input, -129, -31, 200, 1000);
+     yStick = yAverage.next(bumpy_input);

-     aSin.setFreq(rollLeft);
+     aSin.setFreq(pitch);
      aTri.setFreq(rollRight);
-     aSaw.setFreq(pitch);
+     aSaw.setFreq(rollLeft);

      play = 1;
    }
@@ -90,34 +112,8 @@
 int updateAudio(){
   if (play)
   {
-    if ( pitch >= rollLeft)
-    {
-      if ( pitch >= rollRight)
-      { return aSaw.next(); }
-      else
-      { return aTri.next(); }
-    }
-    else if ( pitch >= rollRight)
-    {
-      if ( pitch >= rollLeft)
-      { return aSaw.next(); }
-      else
-      { return aSin.next(); }
-    }
-    else if ( rollRight >= rollLeft)
-    {
-      if ( pitch >= rollRight)
-      { return aSaw.next(); }
-      else
-      { return aTri.next(); }
-    }
-    else if ( rollLeft >= rollRight)
-    {
-      if ( pitch >= rollLeft)
-      { return aSaw.next(); }
-      else
-      { return aSin.next(); }
-    }
+    int synth = (((int)aSaw.next() * volumeLeft) + ((int)aTri.next() * volumeRight) + ((int)aSin.next() * volumePitch))>>8;
+    return synth;
   }

   return 0;


表示間隔の変更

表示間隔の変更

--- 2_example/example28_lcdkey/example28_lcdkey.ino
+++ 2_example/example28_lcdkey/example28_lcdkey.ino
@@ -147,7 +147,7 @@

     client = server.available();            // 接続されたTCPクライアントを生成
     if(!client){                            // TCPクライアントが無かった場合
-        if(time%300 < 1){                   // 300msに一回
+        if(time%250 < 1){                   // 250msに一回
 		    if(time%86400000ul==0){         // 24時間に1回
 		        TIME=getNtp();              // NTP時刻を取得
 		        TIME-=millis()/1000;


updated arduino program

updated arduino program

changed gain settings for current and voltage
changed initial splurge output
input switch statement for setting current gain
changed voltage rang to +/- 2V
changed current range to +/i 0.256V (i.e. +/- 256 uA with middle uCurrent gain setting)

--- software/arduino/light-current-read/light-current-read.ino
+++ software/arduino/light-current-read/light-current-read.ino
@@ -5,6 +5,8 @@
 // Adafruit_ADS1015 ads;     /* Use thi for the 12-bit version */

 unsigned char bh1750_address = 35;
+
+unsigned int current_gain = 16;

 void setup(void)
 {
@@ -14,7 +16,7 @@
   Wire.begin();        // join i2c bus (address optional for master)

   Serial.println("Getting differential reading from AIN0 (P) and AIN1 (N)");
-  Serial.println("ADC Range:  +/- 1.024V  1 bit = 0.015625mV");
+  //Serial.println("ADC Range:  +/- 1.024V  1 bit = 0.015625mV");

   // The ADC input range (or gain) can be changed via the following
   // functions, but be careful never to exceed VDD +0.3V max, or to
@@ -22,10 +24,10 @@
   // Setting these values incorrectly may destroy your ADC!
   //                                                                ADS1015  ADS1115
   //                                                                -------  -------
-  // ads.setGain(GAIN_TWOTHIRDS);  // 2/3x gain +/- 6.144V  1 bit = 3mV      0.1875mV (default)
+   ads.setGain(GAIN_TWOTHIRDS);  // 2/3x gain +/- 6.144V  1 bit = 3mV      0.1875mV (default)
   // ads.setGain(GAIN_ONE);        // 1x gain   +/- 4.096V  1 bit = 2mV      0.125mV
   // ads.setGain(GAIN_TWO);        // 2x gain   +/- 2.048V  1 bit = 1mV      0.0625mV
-   ads.setGain(GAIN_FOUR);       // 4x gain   +/- 1.024V  1 bit = 0.5mV    0.03125mV
+  // ads.setGain(GAIN_FOUR);       // 4x gain   +/- 1.024V  1 bit = 0.5mV    0.03125mV
   // ads.setGain(GAIN_EIGHT);      // 8x gain   +/- 0.512V  1 bit = 0.25mV   0.015625mV
   // ads.setGain(GAIN_SIXTEEN);    // 16x gain  +/- 0.256V  1 bit = 0.125mV  0.0078125mV

@@ -45,26 +47,45 @@
   Serial.print("," );

   int16_t results, results1;
+  float multiplier;

   /* Be sure to update this value based on the IC and the gain settings! */
   // float   multiplier = 3.0F;    /* ADS1015 @ +/- 6.144V gain (12-bit results) */
   //float multiplier = 0.1875F; /* ADS1115  @ +/- 6.144V gain (16-bit results) */
   //  float   multiplier = 0.0078125F;    /* ADS1115 @ +/- 0.256V gain (16-bit results) */
   // float   multiplier = 0.015625F;    /* ADS1115 @ +/- 0.512V gain (16-bit results) */
-  float   multiplier = 0.03125F;    /* ADS1115 @ +/- 1.024V gain (16-bit results) */
-  float   multiplier1 = 0.1875F;    /* ADS1115 @ +/- 1.024V gain (16-bit results) */

-  ads.setGain(GAIN_FOUR);       // 4x gain   +/- 1.024V  1 bit = 0.03125mV
+  // read current
+ switch (current_gain) {
+    case 4:
+      ads.setGain(GAIN_FOUR);       // 4x gain   +/- 1.024V  1 bit = 0.03125mV
+      multiplier = 0.03125F;  // 4x gain   +/- 1.024V  1 bit = 0.03125mV
+      break;
+    case 8:
+      ads.setGain(GAIN_EIGHT);      // 8x gain   +/- 0.512V  1 bit = 0.015625mV
+      multiplier = 0.015625F;    // 8x gain   +/- 0.512V  1 bit = 0.015625mV
+      break;
+    case 16:
+      ads.setGain(GAIN_SIXTEEN);    // 16x gain  +/- 0.256V  1 bit = 0.0078125mV
+      multiplier = 0.0078125F;    // 16x gain  +/- 0.256V  1 bit = 0.0078125mV
+      break;
+    default:
+      ads.setGain(GAIN_TWOTHIRDS);       // 2/3x gain +/- 6.144V  1 bit = 0.1875mV (default)
+      multiplier = 0.03125F;    // 2/3x gain +/- 6.144V  1 bit = 0.1875mV (default)
+      break;
+  }
   results = ads.readADC_Differential_0_1();

-  ads.setGain(GAIN_TWOTHIRDS);  // 2/3x gain +/- 6.144V  1 bit = 0.1875mV (default)
+  // Read voltage
+  ads.setGain(GAIN_TWO);  // 2x gain   +/- 2.048V  1 bit = 0.0625mV
+  float   multiplier1 = 0.0625F;    // 2x gain   +/- 2.048V  1 bit = 0.0625mV
   results1 = ads.readADC_Differential_2_3();

   //Serial.print("Differential: "); Serial.print(results); Serial.print("("); Serial.print(results * multiplier); Serial.println("mV)");
   //Serial.println(results);
-  Serial.print(results * multiplier);
+  Serial.print(results * multiplier); // current
   Serial.print(",");
-  Serial.println(results1 * multiplier1);
-  delay(1000);
+  Serial.println(results1 * multiplier1); // voltage
+  delay(5000);
 }


added support for type C (Intertechno)

added support for type C (Intertechno)

--- ArduinoWsServer/ArduinoWsServer.ino
+++ ArduinoWsServer/ArduinoWsServer.ino
@@ -16,8 +16,10 @@

 RCSwitch mySwitch = RCSwitch();

-byte mac[] = { 0x52, 0x4F, 0x43, 0x4B, 0x45, 0x54 };
-byte ip[] = { 192, 168, 10 , 200 };
+byte mac[] = {
+  0x52, 0x4F, 0x43, 0x4B, 0x45, 0x54 };
+byte ip[] = {
+  192, 168, 10 , 200 };

 // Create a Websocket server
 WebSocket wsServer;
@@ -26,16 +28,20 @@
   Serial.println("onConnect called");
 }

+void onDisconnect(WebSocket &socket) {
+  Serial.println("onDisconnect called");
+}
+
 // You must have at least one function with the following signature.
 // It will be called by the server when a data frame is received.
 void onData(WebSocket &socket, char* dataString, byte frameLength) {
-
+
 #ifdef DEBUG
   Serial.print("Got data: ");
   Serial.write((unsigned char*)dataString, frameLength);
   Serial.println();
 #endif
-
+
   if (frameLength == 13)
   {
     Serial.println("Type A: 10 pole DIP switches");
@@ -49,18 +55,22 @@
   else if (frameLength == 7)
   {
     Serial.println("Type C: Intertechno");
+    switchTypeC(dataString);
   }
-
+
   // Just echo back data for fun.
   socket.send(dataString, frameLength);
 }

+/*
+ * Type A: 10 pole DIP switches
+ */
 void switchTypeA(char* dataString)
 {
   char* state = strtok(dataString, ",");
   char* systemcode = strtok(NULL, ",");
   char* unitcode = strtok(NULL, ",");
-
+
   if (dataString[0] == '1')
   {
     Serial.print("On: ");
@@ -71,12 +81,15 @@
     Serial.print("Off: ");
     mySwitch.switchOff(systemcode, unitcode);
   }
-
+
   Serial.print(systemcode);
   Serial.print(",");
   Serial.println(unitcode);
 }

+/*
+ * Type B: Two rotary/sliding switches
+ */
 void switchTypeB(char* dataString)
 {
   if (dataString[0] == '1')
@@ -89,14 +102,33 @@
     Serial.print("Off: ");
     mySwitch.switchOff(int(dataString[2]), int(dataString[4]));
   }
-
+
   Serial.print(dataString[2]);
   Serial.print(",");
   Serial.println(dataString[4]);
 }

-void onDisconnect(WebSocket &socket) {
-  Serial.println("onDisconnect called");
+/*
+ * Type C: Intertechno
+ */
+void switchTypeC(char* dataString)
+{
+  if (dataString[0] == '1')
+  {
+    Serial.print("On: ");
+    mySwitch.switchOn(dataString[2], int(dataString[4]), int(dataString[6]));
+  }
+  else
+  {
+    Serial.print("Off: ");
+    mySwitch.switchOn(dataString[2], int(dataString[4]), int(dataString[6]));
+  }
+
+  Serial.print(dataString[2]);
+  Serial.print(",");
+  Serial.println(dataString[4]);
+  Serial.print(",");
+  Serial.println(dataString[6]);
 }

 void setup() {
@@ -104,19 +136,19 @@
   Serial.begin(57600);
 #endif
   Ethernet.begin(mac, ip);
-
+
   wsServer.registerConnectCallback(&onConnect);
   wsServer.registerDataCallback(&onData);
   wsServer.registerDisconnectCallback(&onDisconnect);
   wsServer.begin();
-
+
   delay(100); // Give Ethernet time to get ready
-
+
   //mySwitch.enableReceive(0);  // Receiver on inerrupt 0 => that is pin #2 (pin #3 on Arduino Leonardo)
   mySwitch.enableTransmit(8);  // Using Pin #8
-
-  Serial.println("Arduino Websocket Server started.");
-
+
+    Serial.println("Arduino Websocket Server started.");
+
   //enable watchdog timer (2 seconds)
   wdt_enable(WDTO_8S);
 }
@@ -124,13 +156,15 @@
 void loop() {
   // Should be called for each loop.
   wsServer.listen();
-
+
   // Do other stuff here, but don't hang or cause long delays.
   delay(100);
   //if (wsServer.isConnected()) {
-    //wsServer.send("abc123", 6);
+  //wsServer.send("abc123", 6);
   //}
-
+
   //reset watchdog timer
   wdt_reset();
 }
+
+


Another Analog Button Bugfix

Another Analog Button Bugfix

Hopefully the final bugfix

--- ps2_controller/ps2_controller.ino
+++ ps2_controller/ps2_controller.ino
@@ -541,6 +541,27 @@
     digitalWrite(buttonAnalog, HIGH);
   }
   digitalWrite(buttonAnalog, HIGH);
+
+  //Serial.print("analogLedVal=");
+  //Serial.println(analogLedVal);
+  if (analogLedVal > 108)
+  {
+    //Serial.println("Analog is OFF");
+  }
+  if (analogLedVal < 80)
+  {
+    //Serial.println("Analog is OFF");
+  }
+  if ((analogLedVal >= 80) && (analogLedVal <= 87))
+  {
+    //Serial.println("Analog is ON");
+    delay(powerRelayDelay);
+    digitalWrite(buttonAnalog, LOW);
+    delay(powerRelayDelay);
+    digitalWrite(buttonAnalog, HIGH);
+  }
+  //Serial.print("analogLedVal=");
+  //Serial.println(analogLedVal);
 }

 void loop() {


better timing

better timing

--- HumanRoulette.ino
+++ HumanRoulette.ino
@@ -13,9 +13,9 @@
 #define PULSE_LENGTH 170
 #define REPEAT_TRANSMIT 2

-#define START_BUTTON_PIN 10
-#define FUNCTION_BUTTON_PIN 11
-#define START_BUTTON_LIGHT 12
+#define START_BUTTON_PIN 11
+#define FUNCTION_BUTTON_PIN 10
+#define START_BUTTON_LIGHT 7
 #define FUNCTION_BUTTON_LIGHT 6

 Button startButton = Button(START_BUTTON_PIN, BUTTON_PULLUP, false, 0);
@@ -32,10 +32,10 @@

 char sendStrings[4][13] = {
-  "FFFFFFFF0rgb",
   "1FFFFFFF0rgb",
   "F1FFFFFF0rgb",
-  "FF1FFFFF0rgb"
+  "FF1FFFFF0rgb",
+  "FFF1FFFF0rgb"
 };

 boolean startButtonLightOn = false;
@@ -117,6 +117,7 @@
   switch(currentStep)
   {
     case Start:
+      Serial.println("Start....");
       currentStep = WaitingForButton;
       lastTime = newTime;
       break;
@@ -125,7 +126,7 @@
       functionButton.process();

       if(startButton.isPressed()){
-        currentStep = Waiting;
+        currentStep = InitializeSending;
         lastTime = newTime;
         digitalWrite(START_BUTTON_LIGHT, LOW);
         digitalWrite(FUNCTION_BUTTON_LIGHT, LOW);
@@ -162,7 +163,7 @@
       // reset all hats
       for(int i=0; i<4; i++)
         SetColor(i, false, false, false);
-      Send();
+      Send(-1);

       // randomize the number of laps around
       winningHat = random(0,3);
@@ -180,9 +181,9 @@
       currentStep = Waiting;
       break;
     case Waiting:
-      Serial.print("Waiting......elapsed: ");
-      Serial.println(elapsedTime);
-      if(elapsedTime > 5000)
+      //Serial.print("Waiting......elapsed: ");
+      //Serial.println(elapsedTime);
+      if(elapsedTime > 500)
       {
         lastTime = newTime;
         currentStep = SendingRed;
@@ -248,9 +249,9 @@
       }
       break;
     case Finished:
-      Serial.print("Finished....elapsed: ");
-      Serial.println(elapsedTime);
-      if(elapsedTime > 10000)
+      //Serial.print("Finished....elapsed: ");
+      //Serial.println(elapsedTime);
+      if(elapsedTime > 5000)
       {
         lastTime = newTime;
         currentStep = Start;
@@ -272,7 +273,7 @@
       SetColor(i, false, false, false);
   }

-  Send();
+  Send(hat);

   hat++;
   Serial.print("Hat: ");
@@ -293,28 +294,33 @@
     case 0:
     case 1:
     case 2:
-      sendStrings[hatNo][9] = red ? '1' : '0';
-      sendStrings[hatNo][10] = green ? '1' : '0';
-      sendStrings[hatNo][11] = blue ? '1' : '0';
+      sendStrings[hatNo][11] = red ? '1' : '0';
+      sendStrings[hatNo][9] = green ? '1' : '0';
+      sendStrings[hatNo][10] = blue ? '1' : '0';
       break;
     case 3:
       sendStrings[hatNo][9] = red ? '1' : '0';
-      sendStrings[hatNo][10] = green ? '1' : '0';
-      sendStrings[hatNo][11] = blue ? '1' : '0';
-      break;
-  }
-}
-
-
-void Send()
+      sendStrings[hatNo][11] = green ? '1' : '0';
+      sendStrings[hatNo][10] = blue ? '1' : '0';
+      break;
+  }
+}
+
+
+void Send(int hatWithColor)
 {
   for(int i=0; i<4; i++)
   {
-    Serial.print("Sending: ");
-    Serial.println(sendStrings[i]);
-
-    mySwitch.sendTriState(sendStrings[i]);
-    delay(100);
-  }
-
-}
+    if(i!=hatWithColor)
+    {
+      Serial.print("Sending: ");
+      Serial.println(sendStrings[i]);
+
+      mySwitch.sendTriState(sendStrings[i]);
+      delay(10);
+    }
+  }
+
+  // always sends hat with color last
+  mySwitch.sendTriState(sendStrings[hatWithColor]);
+}


Hardware based on WeMos D1 R2 & mini

Hardware based on WeMos D1 R2 & mini

--- projects/clock/clock.ino
+++ projects/clock/clock.ino
@@ -1,3 +1,6 @@
+/**
+ * Hardware based on WeMos D1 R2 & mini - https://github.com/esp8266/arduino#installing-with-boards-manager
+ */
 #include <NTPClient.h>            // https://github.com/arduino-libraries/NTPClient
 #include <ESP8266WiFi.h>          // https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WiFi
 #include <WiFiUdp.h>              // https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WiFi


Prepare NEXA example for ATtiny.

Prepare NEXA example for ATtiny.

--- examples/Sandbox/CosaNEXAreceiver/CosaNEXAreceiver.ino
+++ examples/Sandbox/CosaNEXAreceiver/CosaNEXAreceiver.ino
@@ -30,22 +30,31 @@
 #include "Cosa/Driver/NEXA.hh"
 #include "Cosa/RTC.hh"
 #include "Cosa/Watchdog.hh"
+
+#if !defined(__ARDUINO_TINYX5__)
 #include "Cosa/Trace.hh"
 #include "Cosa/IOStream/Driver/UART.hh"
 #include "Cosa/Memory.h"
+#endif

 OutputPin led(Board::LED);
 NEXA::Receiver receiver(Board::EXT0);

 void setup()
 {
+#if !defined(__ARDUINO_TINYX5__)
   uart.begin(9600);
   trace.begin(&uart, PSTR("CosaNEXAreceiver: started"));
   TRACE(free_memory());
+#endif
   RTC::begin();
   Watchdog::begin(16, SLEEP_MODE_IDLE, Watchdog::push_timeout_events);
   led.toggle();
+#if !defined(__ARDUINO_TINYX5__)
   trace << receiver.read_code() << endl;
+#else
+  NEXA::code_t code = receiver.read_code();
+#endif
   led.toggle();
   receiver.enable();
 }
@@ -58,7 +67,11 @@
   Event::Handler* handler = event.get_target();
   if ((type == Event::READ_COMPLETED_TYPE) && (handler == &receiver)) {
     led.toggle();
+#if !defined(__ARDUINO_TINYX5__)
     trace << receiver.get_code() << endl;
+#else
+    NEXA::code_t code = receiver.get_code();
+#endif
     led.toggle();
   }
 }


updated comment

updated comment

--- examples/LatchPulseTest/LatchPulseTest.ino
+++ examples/LatchPulseTest/LatchPulseTest.ino
@@ -6,7 +6,7 @@
 // open source (see LICENSE file)
 //
 // notes:
-// * for the Tlc59711 library, this test will be added to Tlc59711Test
+// * for the Tlc59711 library, this test is part of Tlc59711Test
 // * for this test
 //  - the red LEDs should be constant on
 //  - the green and blue LEDs should blink (1s on, 1s off)


Fixed mapping of minutes and seconds to decimal hour.

--- moonSimtask.ino
+++ moonSimtask.ino
@@ -9,7 +9,7 @@
     struct tm timeinfo;
     gmtime_r( &now, &timeinfo ); /* moon phase is calculated using UTC! */

-    double hour = timeinfo.tm_hour + mapFloat( ( timeinfo.tm_min * 60 ) + timeinfo.tm_sec, 1, 3600, 0, 1 );
+    double hour = timeinfo.tm_hour + mapFloat( ( timeinfo.tm_min * 60 ) + timeinfo.tm_sec, 0, 3600, 0, 1 );

     moonData = MoonPhase.getInfo( 1900 + timeinfo.tm_year, timeinfo.tm_mon + 1, timeinfo.tm_mday, hour );


add xbee sleep

add xbee sleep

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

--- WeatherSensor_rev2/WeatherSensor_rev2.ino
+++ WeatherSensor_rev2/WeatherSensor_rev2.ino
@@ -22,28 +22,23 @@
 const byte STAT_BLUE = 7;
 const byte STAT_GREEN = 8;

-const byte REFERENCE_3V3 = A3;
-const byte LIGHT = A1;
-const byte BATT = A2;
-
 int counter=10;

 //Global Variables
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 long lastSecond; //The millis counter to see when a second rolls by

+const int XBee_wake = 9;
+
 void setup()
 {
 	//wdt_enable(WDTO_8S);

-	Serial1.begin(57600);
-	Serial1.println("Weather Shield Example");
+	Serial.begin(57600);
+	Serial.println("Weather Shield Example");

 	pinMode(STAT_BLUE, OUTPUT); //Status LED Blue
 	pinMode(STAT_GREEN, OUTPUT); //Status LED Green
-
-	pinMode(REFERENCE_3V3, INPUT);
-	pinMode(LIGHT, INPUT);

 	//Configure the pressure sensor
 	myPressure.begin(); // Get sensor online
@@ -55,7 +50,7 @@

 	lastSecond = millis();

-	Serial1.println("Weather Shield online!");
+	Serial.println("Weather Shield online!");
 }

 void loop()
@@ -77,45 +72,53 @@
 		//power_all_enable();
 		//delay(5);

+		// wake up the XBee
+		pinMode(XBee_wake, OUTPUT);
+		digitalWrite(XBee_wake, LOW);
+
 		//Check Pressure Sensor
 		float pressure = myPressure.readPressure();

-		Serial1.print("$WBP:");
-		Serial1.print(counter);
-		Serial1.print(":Pres:");
-		Serial1.print(pressure);
-		Serial1.println("Pa*");
+		Serial.print("$WBP:");
+		Serial.print(counter);
+		Serial.print(":Pres:");
+		Serial.print(pressure);
+		Serial.println("Pa*");

 		//Check Temperature Sensor
 		float tempc = sensor.readTemperature();
 		if (tempc <= 100) {
 			float tempf = ((tempc * 1.8)+32);
-			Serial1.print("$WBT:");
-			Serial1.print(counter);
-			Serial1.print(":TempF:");
-			Serial1.print(tempf, 2);
-			Serial1.println("F*");
+			Serial.print("$WBT:");
+			Serial.print(counter);
+			Serial.print(":TempF:");
+			Serial.print(tempf, 2);
+			Serial.println("F*");
 			endofline=1;
 		} else {
-			Serial1.println("WBT:FAILURE");
+			Serial.println("WBT:FAILURE");
 		}

 		//Check Humidity Sensor
 		float humidity = sensor.readHumidity();
 		if (humidity <= 100) {
-			Serial1.print("$WBH:");
-			Serial1.print(counter);
-			Serial1.print(":Humid:");
-			Serial1.print(humidity);
-			Serial1.println("P*");
+			Serial.print("$WBH:");
+			Serial.print(counter);
+			Serial.print(":Humid:");
+			Serial.print(humidity);
+			Serial.println("P*");
 			endofline=1;
 		} else {
-			Serial1.println("WBH:FAILURE");
+			Serial.println("WBH:FAILURE");
 		}

 		if ( endofline == 1) {
-			Serial1.println("");
+			Serial.println("");
 		}
+
+		// put the XBee to sleep
+		pinMode(XBee_wake, INPUT); // put pin in a high impedence state
+		digitalWrite(XBee_wake, HIGH);

 		counter++;
 		if (counter == 100)
@@ -129,15 +132,3 @@
 	delay(100);
 }

-//void goto_sleep()
-//{
-//	//power_all_disable();
-//	set_sleep_mode(SLEEP_MODE_PWR_DOWN);
-//	sleep_mode();
-//}
-
-//ISR(WDT_vect)
-//{
-//	watchdog_counter++;
-//}
-


prevent recursive call of timer interrupts

--- arduino/ConstantSpeedMega/ConstantSpeedMega.ino
+++ arduino/ConstantSpeedMega/ConstantSpeedMega.ino
@@ -27,6 +27,8 @@
 // interrupt variables
 boolean stateX;
 boolean stateY;
+boolean interruptXBusy;
+boolean interruptYBusy;

 // variables for reading in speed
 String str;
@@ -55,21 +57,29 @@

     stateX = false;
     stateY = false;
+    interruptXBusy = false;
+    interruptYBusy = false;
 }

 void stepperInterruptX(void) {
     if (moveX >= 0) {
+            if (interruptXBusy) return;
+            interruptXBusy = true;
             stateX = !stateX;
             digitalWrite(X_DIR_PIN, moveX == 0 ? LOW : HIGH);
             digitalWrite(X_STEP_PIN, stateX);
+            interruptXBusy = false;
     }
 }

 void stepperInterruptY(void) {
     if (moveY >= 0) {
+          if (interruptYBusy) return;
+          interruptYBusy = true;
           stateY = !stateY;
           digitalWrite(Y_DIR_PIN, moveY == 0 ? LOW : HIGH);
           digitalWrite(Y_STEP_PIN, stateY);
+          interruptYBusy = false;
     }
 }


Make blue LED not so bright

Make blue LED not so bright

--- RouterReset_Yun/RouterReset_Yun.ino
+++ RouterReset_Yun/RouterReset_Yun.ino
@@ -15,8 +15,9 @@
 const int redLED     = 6;
 const int greenLED   = 5;
 const int yellowLED  = 3;
-const int routerPin1 = 8;
-const int routerPin2 = 9;
+const int routerPin = 8;
+const int routerLED = 9;
+const int routerLEDlevel = 100;
 const int resetRouterTimeSec = 30;
 const int secBetweenPings_Up = 5;
 const int secBetweenPings_Down = 1;
@@ -29,10 +30,10 @@
     pinMode(redLED, OUTPUT);
     pinMode(greenLED, OUTPUT);
     pinMode(yellowLED, OUTPUT);
-    pinMode(routerPin1, OUTPUT);
-    pinMode(routerPin2, OUTPUT);
-    digitalWrite(routerPin1, HIGH);
-    digitalWrite(routerPin2, HIGH);
+    pinMode(routerPin, OUTPUT);
+    pinMode(routerLED, OUTPUT);
+    digitalWrite(routerPin, HIGH);
+    analogWrite(routerLED, routerLEDlevel);
     pinMode(switchPin, INPUT);
     digitalWrite(switchPin, HIGH);

@@ -74,16 +75,16 @@
 void resetRouter() {
   if(digitalRead(switchPin) == HIGH) {

-    digitalWrite(routerPin1, LOW);
-    digitalWrite(routerPin2, LOW);
+    digitalWrite(routerPin, LOW);
+    digitalWrite(routerLED, LOW);

     for(int i=0; i<resetRouterTimeSec; i++) {
       if(digitalRead(switchPin) == LOW) break;
       delay(1000);
     }

-    digitalWrite(routerPin1, HIGH);
-    digitalWrite(routerPin2, HIGH);
+    digitalWrite(routerPin, HIGH);
+    analogWrite(routerLED, routerLEDlevel);

     delay(resetRouterTimeSec*1000);
   }