semicolon

semicolon

--- examples/pwm-teensy/pwm-teensy.ino
+++ examples/pwm-teensy/pwm-teensy.ino
@@ -15,7 +15,7 @@
 {
   analogWrite(PWM_PIN, dutyCycle);
   Serial.begin(115200);
-  Serial.println("Enter h/l to change frequency and f/s to change duty cycle")
+  Serial.println("Enter h/l to change frequency and f/s to change duty cycle");
 }

 void loop()


Update simple_GET.ino

Update simple_GET.ino

--- examples/simple_GET/simple_GET.ino
+++ examples/simple_GET/simple_GET.ino
@@ -1,6 +1,6 @@
 /* RestClient simple GET request
  *
- * by Chris Continanza (csquared)
+ * by Rex St John
  */

 #include <WiFi.h>
@@ -9,8 +9,11 @@

 char ssid[] = "YOUR_SSID";            //  your network SSID (name)
 char pass[] = "YOUR_WIFI_PW";         // your network password
-int status = WL_IDLE_STATUS;          // the Wifi radio's status
-RestClient client = RestClient("google.com", ssid, pass);
+char host[] = "www.google.com";      // target for your REST queries
+int status = WL_IDLE_STATUS;         // the Wifi radio's status
+
+// Create your WiFi RestClient, pass in the ssid and password.
+RestClient client = RestClient(host, ssid, pass);

 String response;
 void setup() {
@@ -19,10 +22,8 @@
   Serial.begin(9600);
   Serial.println("Starting REST client over Wi-Fi");
   if(client.connect() == WL_CONNECTED){
-
-    Serial.println("Starting REST client over Wi-Fi");
     response = "";
-    int statusCode = client.get("/?search=arduino", &response);
+    int statusCode = client.get("/q=tacos", &response);
     Serial.print("Status code from server: ");
     Serial.println(statusCode);
     Serial.print("Response body from server: ");
@@ -32,5 +33,5 @@
 }

 void loop(){
+  //
 }
-


broken down into functions, tested

broken down into functions, tested

--- YaesuTest/YaesuTest.ino
+++ YaesuTest/YaesuTest.ino
@@ -8,8 +8,11 @@

 #define DEBUG

-#include "CATutil.h"
-#include "YaesuCAT.h"
+#include <CATutil.h>
+#include <YaesuCAT.h>
+
+/** LED which indicates that TX loop is 'locked'. */
+#define TX_LOCKED_LED     13

 #ifdef DEBUG
  // http://arduiniana.org/libraries/streaming/
@@ -35,7 +38,7 @@
 */
 #include <SoftwareSerial.h>

-SoftwareSerial txSerial(8, 9); // RX, TX
+SoftwareSerial txSerial(8, 9); // RX(or), TX(rd)
 #else
  // use RX3,TX3 on the Teensy 3.1/3.2 board, Serial1 is identical to Serial and wired to USB
  #define txSerial  Serial3
@@ -47,7 +50,10 @@
 #endif // (__AVR__)

 void setup() {
-
+
+  pinMode(TX_LOCKED_LED, OUTPUT);
+  digitalWrite(TX_LOCKED_LED, LOW);
+
 #ifdef DEBUG
   /* Initialize serial output at UART_BAUD_RATE bps */
   Serial.begin(UART_BAUD_RATE);
@@ -64,29 +70,91 @@

 YaesuCAT FT817(txSerial);

+/** Request TX frequency and mode settings from time to time. */
+static void txRequestFrequencyAndMode(YaesuCAT& ft817,unsigned long interval=200) {
+
+  static unsigned long r_time = millis();
+
+  if ( (millis() - r_time) > interval ) {
+
+    ft817.requestFrequencyAndMode();
+
+    r_time = millis();
+  }
+}
+
+/** Set the desired frequency and mode of the TX (one quantity at a time). */
+static void txSetFrequencyAndMode(YaesuCAT& ft817,
+                                  uint32_t& desired_frequency,
+                                  byte& desired_mode,
+                                  unsigned long interval=500) {
+
+  static unsigned long s_time = millis();
+
+  uint32_t frequency = ft817.getFrequency();
+  byte mode = ft817.getMode();
+
+  // send message to the rig
+  if ( millis() - s_time > interval ) {
+
+    s_time = millis();
+
+    if ( frequency != desired_frequency )
+      ft817.writeFrequency(desired_frequency);
+    else if ( mode != desired_mode )
+      ft817.writeMode(desired_mode);
+  }
+}
+
+// the program's main loop
 void loop() {

   uint32_t frequency = FT817.getFrequency();
   byte mode = FT817.getMode();
-
+
+  static byte txState = 0;
+
   static unsigned long loop_init = millis();
-
-#if 1
-  // request frequency and mode settings...
-  static unsigned long r_time = millis();
-
-  if ( (frequency == YaesuCAT::ILLEGAL_FREQ || mode == YaesuCAT::ILLEGAL_MODE)
-       && (millis() - r_time > 200 ) ) {
-
-    FT817.requestFrequencyAndMode();
-
-    r_time = millis();
-  }
-#endif
+  static unsigned long tx_init = millis();

   uint32_t desired_frequency = 28175000; // 70.175 MHz transverted into 10m Band
   byte desired_mode = YaesuCAT::eModeUSB;

+  // set the rxState appropriately
+  if ( frequency == YaesuCAT::ILLEGAL_FREQ || mode == YaesuCAT::ILLEGAL_MODE )
+    txState = 0;
+  else if ( frequency != desired_frequency || mode != desired_mode )
+    txState = 1;
+  else
+    txState = 2;
+
+  switch ( txState ) {
+
+    case 0:
+      txRequestFrequencyAndMode(FT817, 200);
+      break;
+
+    case 1:
+      txSetFrequencyAndMode(FT817, desired_frequency, desired_mode, 500);
+      txRequestFrequencyAndMode(FT817, 200);
+      break;
+
+    case 2:
+      if ( (millis() - tx_init) > 5000 ) {
+        FT817.requestFrequencyAndMode();
+        tx_init = millis();
+      }
+      break;
+
+    default:
+      ;
+  }
+
+  if ( txState == 2 )
+    digitalWrite(TX_LOCKED_LED, HIGH);
+  else
+    digitalWrite(TX_LOCKED_LED, LOW);
+
 #if defined (__AVR__)
   txSerial.listen();
 #endif // (__AVR__)
@@ -97,42 +165,13 @@
     FT817.read();

   } // txSerial.available()
-
-#if 1
-  // set desired frequency and mode (one quantity at a time)
-  static unsigned long s_time = millis();
-
-  // send message to the rig
-  if ( millis() - s_time > 500 ) {
-
-    s_time = millis();
-
-    if ( frequency != desired_frequency )
-      FT817.writeFrequency(desired_frequency);
-    else if ( mode != desired_mode )
-      FT817.writeMode(desired_mode);
-  }
-#endif
-
-#if 1
-  // when everything is settled, read frequency/mode from time to time
-  static unsigned long p_time = millis();
-
-  if ( frequency == desired_frequency && mode == desired_mode
-       && ( millis() - p_time) > 5000 ) {
-
-    FT817.requestFrequencyAndMode();
-
-    p_time = millis();
-  }
-#endif

   // display of frequency and mode from time to time
   if ( millis() - loop_init > 2000 ) {

     loop_init = millis();

-    Serial //<< F("OP mode ") << operation_mode
+    Serial << F("txState ") << txState
            //<< F(" fOK ") << rxFrequencyOK(Icom706)
            //<< F(" mOK ") << rxModeOK(Icom706)
            << F(": Frequency = ") << frequency
@@ -164,4 +203,4 @@
 #endif
 }
 #endif // (__AVR__)
-
+


Formatting

Formatting

--- computer_box/computer_box.ino
+++ computer_box/computer_box.ino
@@ -13,7 +13,7 @@
 const int ds18_01_pin = 2;
 const int num_ds18 = 3; // Number of DS18B20 Sensors

-//const int LED_BUILTIN = 13;
+//const int LED_BUILTIN = 13;
 int led_value = LOW;

 uint8_t sensors_address[num_ds18][8];
@@ -42,7 +42,7 @@
   int x, c = 0;
   for (x = 0; x < num_ds18; x++) {
     if (sensor_bus.search(sensors_address[x]))
-    c++;
+      c++;
   }
 }

@@ -56,13 +56,13 @@
   //      Example serial input:
   //           4,1   # Turn fan on
   //          13,0   # Turn led off
-  while(Serial.available() > 0){
+  while (Serial.available() > 0) {
     int pin_num = Serial.parseInt();
     int pin_status = Serial.parseInt();

-    switch(pin_num){
-      case fan_pin:
-      case LED_BUILTIN:
+    switch (pin_num) {
+    case fan_pin:
+    case LED_BUILTIN:
       digitalWrite(pin_num, pin_status);
       break;
     }


Resolve SSTV example issues

Resolve SSTV example issues

--- examples/SSTV/SSTV.ino
+++ examples/SSTV/SSTV.ino
@@ -51,7 +51,7 @@

 void loop() {
-     if(radio.waitForChannel(1000,2000, rssi)) {        // Wait forever for calling frequency to open, then wait 2 seconds for breakers
+     if(radio.waitForChannel(1000,2000, -90)) {        // Wait forever for calling frequency to open, then wait 2 seconds for breakers
        radio.setModeTransmit();                   // Turn on the transmitter
        delay(250);                               // Wait a moment
        radio.SSTVTestPattern(MARTIN1);            // send a MARTIN1 test pattern


Switch to exponential ADSR curves, move constants to defines, and remove gate display.

--- examples/adsr/adsr.ino
+++ examples/adsr/adsr.ino
@@ -24,6 +24,12 @@
 #include <du-ino_interface.h>
 #include <TimerOne.h>

+#define ENV_PEAK              5.0
+#define ENV_SATURATION        1.581976
+#define ENV_DECAY_COEFF       -2.0
+#define ENV_RELEASE_COEFF     -2.0
+#define ENV_RELEASE_HOLD      3
+
 struct DU_ADSR_Values {
   uint16_t A;  // ms
   uint16_t D;  // ms
@@ -68,18 +74,13 @@
         if(elapsed < adsr_values.A)
         {
           // attack
-          cv_current = (float(elapsed) / float(adsr_values.A)) * 10.0;
-        }
-        else if(elapsed < adsr_values.A + adsr_values.D)
-        {
-          // decay
-          cv_current = adsr_values.S + (1.0 - float(elapsed - adsr_values.A) / float(adsr_values.D))
-                       * (10.0 - adsr_values.S);
+          cv_current = ENV_PEAK * ENV_SATURATION * (1.0 - exp(-(float(elapsed) / float(adsr_values.A))));
         }
         else
         {
-          // sustain
-          cv_current = adsr_values.S;
+          // decay/sustain
+          cv_current = adsr_values.S + (ENV_PEAK - adsr_values.S)
+              * exp(ENV_DECAY_COEFF * (float(elapsed - adsr_values.A) / float(adsr_values.D)));
         }
       }
       else
@@ -87,10 +88,10 @@
         if(release_time)
         {
           uint16_t elapsed = millis() - release_time;
-          if(elapsed < adsr_values.R)
+          if(elapsed < adsr_values.R * ENV_RELEASE_HOLD)
           {
             // release
-            cv_current = (1.0 - float(elapsed) / float(adsr_values.R)) * cv_released;
+            cv_current = exp(ENV_RELEASE_COEFF * (float(elapsed) / float(adsr_values.R))) * cv_released;
           }
           else
           {
@@ -110,7 +111,7 @@
     }
     else if(gate)
     {
-      gate_time = millis() - (unsigned long)((cv_current / 10.0) * float(adsr_values.A));
+      gate_time = millis() - (unsigned long)((cv_current / ENV_PEAK) * float(adsr_values.A));
     }
   }

@@ -127,7 +128,6 @@
   {
     // initialize interface
     selected = 0;
-    gate_last = false;
     display_changed = false;

     // initialize ADSR values
@@ -137,13 +137,12 @@
     v[3] = v_last[3] = 5;
     adsr_values.A = uint16_t(v[0]) * 24;
     adsr_values.D = uint16_t(v[1]) * 24;
-    adsr_values.S = (float(v[2]) / 46.0) * 10.0;
+    adsr_values.S = (float(v[2]) / 46.0) * ENV_PEAK;
     adsr_values.R = uint16_t(v[3]) * 24;

     // draw top line
     display->draw_du_logo_sm(0, 0, DUINO_SSD1306::White);
     display->draw_text(16, 0, "ADSR/VCA", DUINO_SSD1306::White);
-    display->draw_text(100, 0, "GATE", DUINO_SSD1306::White);

     // draw sliders
     for(uint8_t i = 0; i < 4; ++i)
@@ -200,7 +199,7 @@
           adsr_values.D = uint16_t(v[selected]) * 24;
           break;
         case 2:
-          adsr_values.S = (float(v[selected]) / 46.0) * 10.0;
+          adsr_values.S = (float(v[selected]) / 46.0) * ENV_PEAK;
           break;
         case 3:
           adsr_values.R = uint16_t(v[selected]) * 24;
@@ -210,15 +209,6 @@
       v_last[selected] = v[selected];
     }

-    // display gate state
-    if(gate != gate_last)
-    {
-      display->fill_rect(98, 0, 28, 7, gate ? DUINO_SSD1306::White : DUINO_SSD1306::Black);
-      display->draw_text(100, 0, "GATE", DUINO_SSD1306::Inverse);
-      display_changed = true;
-      gate_last = gate;
-    }
-
     if(display_changed)
     {
       display->display();
@@ -227,14 +217,9 @@
   }

  private:
-  void display_gate()
-  {
-
-  }
-
   uint8_t selected;
   int8_t v[4], v_last[4];
-  bool gate_last, display_changed;
+  bool display_changed;
 };

 DU_ADSR_Function * function;


Reified LED-Pin-numbers

Reified LED-Pin-numbers

--- arduino/djenko/djenko.ino
+++ arduino/djenko/djenko.ino
@@ -1,15 +1,16 @@
 int incomingByte = 0; // for incoming serial data
+
+int PIN_GREEN = 4;
+int PIN_YELLOW = 3;
+int PIN_RED = 2;

 void setup() {

-  // Green
-  pinMode(12, OUTPUT);
-  // Yellow
-  pinMode(11, OUTPUT);
-  // Red
-  pinMode(10, OUTPUT);
+  pinMode(PIN_GREEN, OUTPUT);
+  pinMode(PIN_YELLOW, OUTPUT);
+  pinMode(PIN_RED, OUTPUT);

-  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
+  Serial.begin(9600);

 }

@@ -35,36 +36,36 @@

 void green() {

-  digitalWrite(12, HIGH);
-  digitalWrite(11, LOW);
-  digitalWrite(10, LOW);
+  digitalWrite(PIN_GREEN, HIGH);
+  digitalWrite(PIN_YELLOW, LOW);
+  digitalWrite(PIN_RED, LOW);
   delay(1000);

 }

 void yellow() {

-  digitalWrite(12, LOW);
-  digitalWrite(11, HIGH);
-  digitalWrite(10, LOW);
+  digitalWrite(PIN_GREEN, LOW);
+  digitalWrite(PIN_YELLOW, HIGH);
+  digitalWrite(PIN_RED, LOW);
   delay(1000);

 }

 void red() {

-  digitalWrite(12, LOW);
-  digitalWrite(11, LOW);
-  digitalWrite(10, HIGH);
+  digitalWrite(PIN_GREEN, LOW);
+  digitalWrite(PIN_YELLOW, LOW);
+  digitalWrite(PIN_RED, HIGH);
   delay(1000);

 }

 void all() {

-  digitalWrite(12, HIGH);
-  digitalWrite(11, HIGH);
-  digitalWrite(10, HIGH);
+  digitalWrite(PIN_GREEN, HIGH);
+  digitalWrite(PIN_YELLOW, HIGH);
+  digitalWrite(PIN_RED, HIGH);
   delay(1000);

 }


check for double Pixy init

check for double Pixy init

--- examples/RoseBot/RoseBotFirmata/RoseBotFirmata.ino
+++ examples/RoseBot/RoseBotFirmata/RoseBotFirmata.ino
@@ -143,6 +143,7 @@
 void interruptFunctionRight() {
   interruptCountRight++;
 }
+

 /* Pixy Support */
 Pixy* pixyPtr = NULL;
@@ -755,8 +756,10 @@
       break;
     case PIXY_CONFIG:
       if (argv[0] == PIXY_INIT) {
-        pixyPtr = new Pixy();
-        pixyPtr->init();
+        if (pixyPtr == NULL) {
+          pixyPtr = new Pixy();
+          pixyPtr->init();
+        }
         // mark pins as Pixy so they are ignore in non Pixy data requests
         setPinModeCallback(PIN_PIXY_MOSI, PIXY);
         setPinModeCallback(PIN_PIXY_MISO, PIXY);
@@ -939,6 +942,7 @@
   isResetting = true;
   encoderIsReporting = false;
   pixyIsReporting = false;
+  pixyPtr = NULL;

   // initialize a defalt state
   // TODO: option to load config from EEPROM instead of default
@@ -1122,7 +1126,7 @@
       enableInterrupt(encoderPin1, interruptFunctionLeft, RISING);
       enableInterrupt(encoderPin2, interruptFunctionRight, RISING);
     }
-    if (pixyIsReporting) {
+    if (pixyIsReporting && pixyPtr != NULL) {
       numPixyBlocks = pixyPtr->getBlocks();
       // Only send Pixy data if a block was found.


Current working version

Current working version

--- Robot_Lights_Display/Robot_Lights_Display.ino
+++ Robot_Lights_Display/Robot_Lights_Display.ino
@@ -40,10 +40,10 @@
   rotatingCogsUp(YELLOW, BLUE);
   rotatingCogsDown(YELLOW, BLUE);
   displayColor(YELLOW);
-  for (int c = 4; c > 0; c--) {
+  for (int c = 3; c > 0; c--) {
     cylon(YELLOW, BLUE);
   }
-  for (int c = 25; c > 0; c--) {
+  for (int c = 20; c > 0; c--) {
     alternate(YELLOW, BLUE);
   }
   expandMiddle(YELLOW, BLUE);
@@ -51,7 +51,7 @@

 void rotatingCogsUp(CRGB colorOne, CRGB colorTwo) {
   FastLED.show();
-  for (int i = 0; i < 40; i++) {
+  for (int i = 0; i < 30; i++) {
     for (int c = 0; c < COG_SIZE; c++) {
       moveCogsUp();
       delay(100);
@@ -62,11 +62,11 @@

 void rotatingCogsDown(CRGB colorOne, CRGB colorTwo) {
   FastLED.show();
-  for (int i = 0; i < 40; i++) {
+  for (int i = 0; i < 30; i++) {
     for (int c = 0; c < COG_SIZE; c++) {
       moveCogsDown();
-      FastLED.show();
       delay(100);
+      FastLED.show();
     }
   }
 }


SDListFilesReadWrite

SDListFilesReadWrite

Signed-off-by: Haohua Li <8fdee70a717c450a70da61cd9ccac783a32c73c6@gmail.com>

--- SDListFilesReadWrite/SDListFilesReadWrite.ino
+++ SDListFilesReadWrite/SDListFilesReadWrite.ino
@@ -1,7 +1,7 @@
 /*
-  SD card read/write
+  SD card basic file example

- This example shows how to read and write data to and from an SD card file
+ This example shows how to create and destroy an SD card file
  The circuit:
  * SD card attached to SPI bus as follows:
  ** MOSI - pin 11
@@ -17,14 +17,15 @@
  This example code is in the public domain.

  */
-
 #include <SD.h>
+#define BLOCK 512

+File root;
 File myFile;

 void setup()
 {
- // Open serial communications and wait for port to open:
+  // Open serial communications and wait for port to open:
   Serial.begin(9600);
    while (!Serial) {
     ; // wait for serial port to connect. Needed for Leonardo only
@@ -36,36 +37,86 @@
   // Note that even if it's not used as the CS pin, the hardware SS pin
   // (10 on most Arduino boards, 53 on the Mega) must be left as an output
   // or the SD library functions will not work.
-   pinMode(10, OUTPUT);
-
+  pinMode(10, OUTPUT);
+
   if (!SD.begin(4)) {
     Serial.println("initialization failed!");
     return;
   }
   Serial.println("initialization done.");
+
+  root = SD.open("/");

-  // open the file. note that only one file can be open at a time,
+  printDirectory(root, 0);
+
+  Serial.println("done!");
+
+    // open the file. note that only one file can be open at a time,
   // so you have to close this one before opening another.
+  myFile = SD.open("test.txt", FILE_WRITE);
+
+  // if the file opened okay, write to it:
+  if (myFile) {
+    Serial.print("Writing to test.txt...");
+    myFile.println("testing 1, 2, 3.");
+	// close the file:
+    myFile.close();
+    Serial.println("done.");
+  } else {
+    // if the file didn't open, print an error:
+    Serial.println("error opening test.txt");
+  }
   // re-open the file for reading:
-  myFile = SD.open("PUTTY.exe");
+  myFile = SD.open("HYPER.RAR");
   if (myFile) {
-    Serial.println("iToolsSetup_1.8.4.0.zip");
+    Serial.println("HYPER.RAR:");
+    long count = 0;
+    char buf[BLOCK];
+
     // read from the file until there's nothing else in it:
     while (myFile.available()) {
-        myFile.read();
-    	Serial.write("r");
+        long c = myFile.read(buf, BLOCK);
+        count += c;
+    	Serial.println(count);
+//        if (count > BLOCK * 100l) break;
     }
     // close the file:
     myFile.close();
+    Serial.println("read done.");
   } else {
   	// if the file didn't open, print an error:
     Serial.println("error opening test.txt");
   }
+
 }

 void loop()
 {
-	// nothing happens after setup
+  // nothing happens after setup finishes.
 }

+void printDirectory(File dir, int numTabs) {
+   while(true) {
+
+     File entry =  dir.openNextFile();
+     if (! entry) {
+       // no more files
+       //Serial.println("**nomorefiles**");
+       break;
+     }
+     for (uint8_t i=0; i<numTabs; i++) {
+       Serial.print('\t');
+     }
+     Serial.print(entry.name());
+     if (entry.isDirectory()) {
+       Serial.println("/");
+       printDirectory(entry, numTabs+1);
+     } else {
+       // files have sizes, directories do not
+       Serial.print("\t\t");
+       Serial.println(entry.size(), DEC);
+     }
+     entry.close();
+   }
+}


omission of unnecesary code

omission of unnecesary code

removed code that has been commented out for a long time

--- WVO_Controller_0.6.3/WVO_Controller_0.6.3.ino
+++ WVO_Controller_0.6.3/WVO_Controller_0.6.3.ino
@@ -1115,11 +1115,6 @@
   temp = (-1.4591 * v6 + 21.784 * v5 - 125.74 * v4 + 350.06 * v3 - 473.05 * v2 + 216.06 * voltage + 267.96) * 0.93;
   // polynomial approximation of signal voltages vs temperature of temp sender with experimentally determined correction factor of 0.93.
   // see excel sheet for more info.       C:\Users\Max\Google Drive\Sync\Bub\WVO Controller\Oil Temp gage values
-  //float voltage, degreesC, degreesF;      // calculate temperature reading based on voltages
-  //voltage = getVoltage(temperaturePin);
-  //degreesC = (voltage - 0.5) * 100.0;
-  //degreesF = degreesC * (9.0/5.0) + 32.0;
-  // subtract the last reading:
   total = total - readings[index];              // read from the sensor:
   readings[index] = temp;                       // add the reading to the total:
   total = total + readings[index];              // advance to the next position in the array:


first state publisher: works only once...

--- arduino/catdoor/catdoor.ino
+++ arduino/catdoor/catdoor.ino
@@ -1,6 +1,7 @@
 #include <ESP8266WiFi.h>
+#include <EEPROM.h>
+#include <Ticker.h>
 #include <PubSubClient.h>
-#include <Ticker.h>

 #include "Adafruit_VCNL4010.h"

@@ -18,6 +19,13 @@

 uint16_t proxim_samples[NB_PROXIM_SAMPLES];
 bool event_detected = false;
+
+const uint8_t MAX_STRING_LENGTH = 32;
+const char *MQTT_SERVER = "172.16.0.11";
+const uint16_t MQTT_PORT = 1883;
+
+WiFiClient espWifiClient;
+PubSubClient mqttClient(espWifiClient);

 void heartbeat() {
   Serial.print("average promimity = ");
@@ -65,15 +73,71 @@
   }
 }

+void publish_state(int8_t state) {
+  char payload[8];
+  if (state) {
+    strcpy(payload, "open");
+  }
+  else {
+    strcpy(payload, "closed");
+  }
+  while (!mqttClient.connected()) {
+    Serial.print("Attempting MQTT connection...");
+    if (mqttClient.connect("MistyDoor")) {
+      Serial.println("connected");
+      payload[0] = static_cast<char>(state);
+      mqttClient.publish("/catdoor/state", payload);
+    } else {
+      Serial.print("failed, rc=");
+      Serial.print(mqttClient.state());
+      Serial.println(" try again in 5 seconds");
+      // Wait 5 seconds before retrying
+      delay(5000);
+    }
+  }
+}
+
 void door_opened() {
   Serial.println("Cat door opened");
+  publish_state(1);
 }

 void door_closed() {
   Serial.println("Cat door closed.");
+  publish_state(0);
+}
+
+void eeprom2str(uint16_t addr, char *str) {
+  for (uint8_t c = 0; c < MAX_STRING_LENGTH; c++) {
+    str[c] = EEPROM.read(addr + c);
+  }
+}
+
+void setup_wifi() {
+  // Get SSID and password from EEPROM
+  EEPROM.begin(MAX_STRING_LENGTH * 2);
+  char ssid[MAX_STRING_LENGTH];
+  char pass[MAX_STRING_LENGTH];
+  eeprom2str(0, ssid);
+  eeprom2str(MAX_STRING_LENGTH, pass);
+  delay(100);   // not sure why, but examples work like this
+  Serial.println();
+  Serial.print("Connecting to network with SSID = ");
+  Serial.println(ssid);
+
+  // Connect to Wifi
+  while (WiFi.status() != WL_CONNECTED) {
+    delay(500);
+    Serial.print(".");
+  }
+  Serial.println();
+  Serial.println("WiFi connected");
+  Serial.println("IP address: ");
+  Serial.println(WiFi.localIP());
 }

 void setup() {
+  // Sensor
   for (uint16_t i = 0; i < NB_PROXIM_SAMPLES; i++) {
     proxim_samples[i] = proxim_nominal;
   }
@@ -86,6 +150,11 @@
     Serial.println("Connected to Proximity Sensor.");
   }

+  // Network
+  setup_wifi();
+  mqttClient.setServer(MQTT_SERVER, MQTT_PORT);
+
+  // Schedulers
   tickerHeartbeat.attach(10, heartbeat);
   tickerUpdate.attach_ms(100, update);

@@ -101,6 +170,10 @@
     door_closed();
     raised = false;
   }
+  // Let the MQTT client do some work
+  mqttClient.loop();
+
+  // Let the ESP Wifi do some work?
   yield();
 }


Losing some precision here...

Losing some precision here...

--- arduino/impetus/impetus.ino
+++ arduino/impetus/impetus.ino
@@ -107,7 +107,7 @@

 void loop() {
   if (sample) {
-    int tt = readTemp();
+    float tt = readTemp();
     int tv = readVol();
     if (tt > temp)
       temp = tt;


More memory saving changes, otherwise can't process control server responses

--- arduino/autogarten_probe/autogarten_probe.ino
+++ arduino/autogarten_probe/autogarten_probe.ino
@@ -9,8 +9,7 @@
  *    * Arduino WIFI Shield (R3)
  *    * Arduino v1.0.4+ (tested with 1.0.5)
  *    * Arduino WiFi library
- *    * OneWire library: http://playground.arduino.cc/Learning/OneWire
- *
+ *    * (1-Wire) OneWire library: http://playground.arduino.cc/Learning/OneWire
  *
  *  !!! Important -- Reserved PINs !!!
  *
@@ -33,9 +32,9 @@
  *   103   Must specify the OneWire pin.
  *   104   Too many OneWire devices. Increase maxOneWireDevices.
  *   105   Invalid sensor type
- *   200   No 1-wire devices found
+ *   200   No Onewire devices found
  *   201   Invalid CRC
- *   202   Unsupported 1-wire device type
+ *   202   Unsupported OneWire device type
  *
  *
  * https://github.com/lbracken/autogarten
@@ -44,30 +43,28 @@
 #include <WiFi.h>
 #include <OneWire.h>

-const int SENSOR_TYPE_ANALOG_GENERIC = 1;
-const int SENSOR_TYPE_DIGITAL_GENERIC = 2;
-const int SENSOR_TYPE_ONEWIRE_TEMP = 3;
-
-const int ERROR_VALUE = -1000;
-
-const int oneWirePin = 9;
-const int maxOneWireDevices = 2;  // Adjust to number of 1-Wire devices
-int oneWireDeviceCount = 0;
+const byte SENSOR_TYPE_ANALOG_GENERIC  = 1;
+const byte SENSOR_TYPE_DIGITAL_GENERIC = 2;
+const byte SENSOR_TYPE_ONEWIRE_TEMP    = 3;
+const byte ERROR_VALUE = -1000;
+const byte maxConnectionAttempts = 10;  // To WiFi and Control Server
+
+/* OneWire variables */
+const byte oneWirePin = 9;
+const byte maxOneWireDevices = 2;  // Adjust to number of OneWire devices
+byte oneWireDeviceCount = 0;
 OneWire oneWire(oneWirePin);

 /* WiFi variables */
-const int wifiConnectionWait = 10000;  // In ms
-const int maxWiFiConnectionAttempts = 10;
+const byte wifiConnectionWaitInSeconds = 10;
 WiFiClient wifiClient;
-int wifiStatus = WL_IDLE_STATUS;
-int wifiStatusLEDPin;
+byte wifiStatus = WL_IDLE_STATUS;
 boolean wifiPersistConnection;
 char *wifiSSID;
 char *wifiPassword;

 /* Probe and Control Server variables */
-const int maxControlServerConnectionAttempts = 10;
 char *probeId;
 char *controlServerAddress;
 int  controlServerPort;
@@ -75,18 +72,16 @@
 int  controlServerSyncCount = 1;

 /* Sensor indices */
-char *sensorIds[19];
+char *sensorIds[19];  // Digital Pins 0-13 + Analog A0 - A5
 char *oneWireSensorIds[maxOneWireDevices];
-
-
-

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

   // Initialize the probe and wifi configuration
-  initProbe("autogarten_probe", "-----", 5000, "changeme");
-  initWiFi("-----", "-----", false);
+  initProbe("PROBE-NAME", "CTRL-SRVR-IP, 5000, "changeme");
+  initWiFi("WIFI-SSID", "WIFI-PASSWORD", true);

   // Add any sensors
   addSensor("light_level_1", A0, SENSOR_TYPE_ANALOG_GENERIC);
@@ -96,7 +91,8 @@
   addSensor("air_temp", oneWirePin, SENSOR_TYPE_ONEWIRE_TEMP);

   // Add any actuators
-  // TODO...
+  // TODO...
+  printFreeMemory();
 }

@@ -104,8 +100,7 @@
   delay(5000);

   Serial.println();
-  Serial.print("Mem:");
-  Serial.println(memoryFree());
+  printFreeMemory();

   readAnalogGenericSensor("light_level_1");
   readAnalogGenericSensor("light_level_2");
@@ -113,7 +108,8 @@
   readOneWireTempSensor("soil_temp");
   readOneWireTempSensor("air_temp");

-  //syncWithControlServer();
+  syncWithControlServer();
+  printFreeMemory();
 }

@@ -164,31 +160,32 @@
     return;
   }

-  int connectionAttempts = 0;
+  byte connectionAttempts = 0;
   while (wifiStatus != WL_CONNECTED) {

     // Increment, then verify within allowable connection attempts...
     connectionAttempts++;
-    if (connectionAttempts > maxWiFiConnectionAttempts) {
-      Serial.println("failure");
+    if (connectionAttempts > maxConnectionAttempts) {
+      Serial.println(F("Failure"));
       return;
     }

     // Log the attempt to connect...
-    Serial.print("Conn to ");
+    Serial.print(F("Connecting to "));
     Serial.print(wifiSSID);
-    Serial.print(" Attempt ");
+    Serial.print(F(" Attempt "));
     Serial.println(connectionAttempts);

     // Connect to WiFi, wait a few seconds for connection to establish...
+    // Uses DHCP settings from WiFi router, otherwise use WiFi.config()
     wifiStatus = WiFi.begin(wifiSSID, wifiPassword);
-    delay(wifiConnectionWait);
+    delay(wifiConnectionWaitInSeconds * 1000);
   }

   // Once connected, print connection information
-  Serial.print("success. IP:");
+  Serial.print(F("Success. IP:"));
   Serial.print(WiFi.localIP());
-  Serial.print(" RSSI:");
+  Serial.print(F(" RSSI:"));
   Serial.println(WiFi.RSSI());
 }

@@ -216,36 +213,36 @@
   wifiClient.stop();
   wifiClient.flush();

-  int connectionAttempts = 0;
-  while (connectionAttempts <= maxControlServerConnectionAttempts) {
+  byte connectionAttempts = 0;
+  while (connectionAttempts <= maxConnectionAttempts) {
     connectionAttempts++;

     // Log the attempt to connect...
-    Serial.print("Conn to ");
+    Serial.print(F("Connecting to "));
     Serial.print(controlServerAddress);
     Serial.print(":");
     Serial.print(controlServerPort);
-    Serial.print(" Attempt ");
+    Serial.print(F(" Attempt "));
     Serial.println(connectionAttempts);

     // Connect to control server
     if (wifiClient.connect(controlServerAddress, controlServerPort)) {
-      Serial.println("sync'ing");
+      Serial.println(F("Synchronizing..."));
       String requestBody = createProbeSyncRequest(connectionAttempts);
-      Serial.println(requestBody);
+      //Serial.println(requestBody);

       // Setup HTTP Request Headers
-      wifiClient.println("POST /probe_sync HTTP/1.1");
-      wifiClient.println("User-Agent: Arduino/1.0");
-      wifiClient.println("Connection: close");
-      wifiClient.println("Content-Type: application/json");
-      wifiClient.print("Content-Length: ");
+      wifiClient.println(F("POST /probe_sync HTTP/1.1"));
+      wifiClient.println(F("User-Agent: Arduino/1.0"));
+      wifiClient.println(F("Connection: close"));
+      wifiClient.println(F("Content-Type: application/json"));
+      wifiClient.print(F("Content-Length: "));
       wifiClient.println(requestBody.length());
       wifiClient.println();

       // Set request body and send request
       wifiClient.println(requestBody);
-      Serial.println("done");
+      Serial.println(F("... sync complete"));

       // TODO: If WiFi persistent connections are off, then we should disconnect here once request has been sent.

@@ -254,18 +251,15 @@
     }
   }

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

 /**
  * Construct the body of a probe sync request to the control server
  */
 String createProbeSyncRequest(int connectionAttempts) {
-
-  // TODO: Start using a proper JSON library here.  Some options could include..
-  //  * https://github.com/not404/json-arduino
-  //  * https://github.com/interactive-matter/aJson
-
+
   String syncRequest = "{\"probe_id\":\"";
   syncRequest += probeId;
   syncRequest += "\",";
@@ -291,10 +285,10 @@
 /*
  * Adds the given sensor to this probe
  */
-boolean addSensor(char *sensorId, int pin, int sensorType) {
+boolean addSensor(char *sensorId, byte pin, byte sensorType) {

   // Verify a reserved PIN isn't being used...
-  if (pin == 7 || pin == 10 || pin == 11 || pin == 12 || pin ==13) {
+  if (pin == 7 || pin == 10 || pin == 11 || pin == 12 || pin == 13) {
     printErrorCode(100);
     return false;
   }
@@ -327,7 +321,7 @@
         return false;
       }

-      // 1-wire devices share a pin, so set the sensorId in the 1-wire array
+      // OneWire devices share a pin, so set the sensorId in the OneWire array
       oneWireSensorIds[oneWireDeviceCount++] = sensorId;
       break;

@@ -337,9 +331,9 @@
   }

   sensorIds[pin] = sensorId;
-  Serial.print("+");
+  Serial.print('+');
   Serial.print(sensorIds[pin]);
-  Serial.print(":");
+  Serial.print(':');
   Serial.println(pin);
   return true;
 }
@@ -349,8 +343,7 @@
  * Returns the pin for the given sensorId
  */
 int getPinForSensorId(char *sensorId) {
-  int ctr;
-  for (ctr=0; ctr < sizeof(sensorIds)/sizeof(char); ctr++) {
+  for (byte ctr=0; ctr < sizeof(sensorIds)/sizeof(char); ctr++) {
     if (sensorIds[ctr] == sensorId) {
       return ctr;
     }
@@ -381,7 +374,7 @@
  *  + ...
  */
 float readAnalogGenericSensor(char *sensorId) {
-  int pin = getPinForSensorId(sensorId);
+  byte pin = getPinForSensorId(sensorId);
   float value = analogRead(pin);

   printSensorResult(sensorId, pin, value);
@@ -394,9 +387,9 @@
  *  + Switches
  *  + ...
  */
-int readDigitalGenericSensor(char *sensorId) {
-  int pin = getPinForSensorId(sensorId);
-  int value = digitalRead(pin);
+byte readDigitalGenericSensor(char *sensorId) {
+  byte pin = getPinForSensorId(sensorId);
+  byte value = digitalRead(pin);

   printSensorResult(sensorId, pin, value);
   return value;
@@ -404,12 +397,12 @@

 /*
- * Using the OneWire library, reads temperature from a 1-wire device.
+ * Using the OneWire library, reads temperature from a OneWire device.
  * See: http://playground.arduino.cc/Learning/OneWire
  *
  * !! Important !!
  *     This function has been streamlined to ONLY support a DS18S20 digital thermometer
- *     running in non-parasitic power mode.  If using another 1-wire device then changes
+ *     running in non-parasitic power mode.  If using another OneWire device then changes
  *     are required. See the Arduino OneWire page for details and code.
  *
  *     Note that multiple DS18S20 devices can be wired together on the same bus.
@@ -420,7 +413,7 @@
  */
 float readOneWireTempSensor(char *sensorId) {

-  int deviceCount = 0;
+  byte deviceCount = 0;
   byte addr[8];

   // Iterate over all devices on the OneWire bus
@@ -454,20 +447,20 @@
       return ERROR_VALUE;
     }

-    // Reset the 1-Wire bus, select a device then start a conversion
+    // Reset the OneWire bus, select a device then start a conversion
     oneWire.reset();
     oneWire.select(addr);
     oneWire.write(0x44);
     delay(800);

-    // Reset the 1-Wire bus, select a device then read scratchpad
+    // Reset the OneWire bus, select a device then read scratchpad
     oneWire.reset();
     oneWire.select(addr);
     oneWire.write(0xBE);

     // Read the data on the bus (9 bytes)
     byte data[12];
-    for (int i = 0; i < 9; i++) {
+    for (byte i = 0; i < 9; i++) {
       data[i] = oneWire.read();
     }

@@ -490,9 +483,9 @@
  */
 void printSensorResult(char *sensorId, int pin, float value) {
   Serial.print(sensorId);
-  Serial.print(":");
+  Serial.print(':');
   Serial.print(pin);
-  Serial.print("=");
+  Serial.print('=');
   Serial.println(value);
 }

@@ -501,7 +494,7 @@
  * Prints our an error code.  Putting into function to optimize space
  */
 void printErrorCode(int errorCode) {
-  Serial.print("ERROR ");
+  Serial.print(F("ERROR "));
   Serial.println(errorCode);
 }

@@ -529,3 +522,8 @@
   return freeValue;
 }

+void printFreeMemory() {
+  Serial.print(F("Free Memory:"));
+  Serial.println(memoryFree());
+}
+


Bugfix on autoResetControllerData()

Bugfix on autoResetControllerData()

--- ps2_controller/ps2_controller.ino
+++ ps2_controller/ps2_controller.ino
@@ -1565,11 +1565,11 @@
       serial_rx_buffer_controller[10] = 0x00; // Delay Byte 1
       serial_rx_buffer_controller[11] = 0x01; // Postamble

-      if (autoResetControllerDataStatus == 0) {
-        for (serial_rx_buffer_counter = 0; serial_rx_buffer_counter < sizeof(serial_rx_buffer); serial_rx_buffer_counter++) {
+      for (serial_rx_buffer_counter = 0; serial_rx_buffer_counter < sizeof(serial_rx_buffer); serial_rx_buffer_counter++) {
+        if (autoResetControllerDataStatus == 0) {
           Serial.write(serial_rx_buffer_controller[serial_rx_buffer_counter]); //  This line writes the serial data back to the computer as a way to check if the Arduino isn't interpreting wrong values
-          serial_rx_buffer_inverted_controller[serial_rx_buffer_counter] = (255 - serial_rx_buffer_controller[serial_rx_buffer_counter]); //  Invert 0 to 255 and vice versa to make it easier to determine which commands to enable or not, and their values
         }
+        serial_rx_buffer_inverted_controller[serial_rx_buffer_counter] = (255 - serial_rx_buffer_controller[serial_rx_buffer_counter]); //  Invert 0 to 255 and vice versa to make it easier to determine which commands to enable or not, and their values
       }

       //  First 8 buttons, Buffer Array Element 1


Update HelloWorld.ino

Update HelloWorld.ino

--- examples/HelloWorld/HelloWorld.ino
+++ examples/HelloWorld/HelloWorld.ino
@@ -63,7 +63,7 @@
   // As usual, we will output debugging information to the normal
   // serial port, the wifi runs on SoftwareSerial using the pins
   // set above so it does not interfere with your normal debugging.
-  Serial.begin(115200);
+  Serial.begin(115200); // Reduce this if your Arduino has trouble talking so fast
   Serial.println("ESP8266 Demo Sketch");

   // Set the baud rate, this depends on your ESP8266's previous setup
@@ -184,4 +184,4 @@
   //   force it to avoid chunked encoding with no particular detriment.

   delay(5000);
-}+}


still more tweaks

still more tweaks

--- examples/attiny84/frankenmeter.ino
+++ examples/attiny84/frankenmeter.ino
@@ -9,12 +9,6 @@

 #include <Interrupted.h>

-#define THERMISTOR	7
-#define SWITCH		1
-#define DIVIDER_GND 	2
-#define A_PIN 		4
-#define TIMER 		0
-
 // thermistor parameters
 const double r0 = 10000;
 const double beta = 3977.0;
@@ -25,12 +19,16 @@
 const double tzero = 25 + zeroC;

 typedef enum { cent, fahr, abso } units_t;
-units_t units = cent;
-boolean sleeping = false;

 #define IDLE		10000L
 #define DIGIT		500L
 #define DEBOUNCE	250L
+
+#define THERMISTOR	7
+#define SWITCH		1
+#define DIVIDER_GND 	2
+#define A_PIN 		4
+#define TIMER 		0

 Analog thermistor(THERMISTOR, vcc);
 PinChangeGroup pins(PB);
@@ -130,6 +128,8 @@

 void loop(void)
 {
+	static units_t units = cent;
+	static bool sleeping = false;
 	static uint8_t buf[8], *p = buf;
 	static double curr_temp = 0.0;
 	static uint32_t last;


Formating changes

Formating changes

--- time/time.ino
+++ time/time.ino
@@ -21,12 +21,12 @@

 #include <Wire.h>
 #include <LiquidCrystal_I2C.h>
+LiquidCrystal_I2C lcd(0x27,16,2);

-LiquidCrystal_I2C lcd(0x27,16,2);

 #define DS1302_SCLK_PIN   11    // Arduino pin for the Serial Clock
 #define DS1302_IO_PIN     12    // Arduino pin for the Data I/O
-#define DS1302_CE_PIN     13   // Arduino pin for the Chip Enable
+#define DS1302_CE_PIN     13    // Arduino pin for the Chip Enable
 #define bcd2bin(h,l)    (((h)*10) + (l))
 #define bin2bcd_h(x)   ((x)/10)
 #define bin2bcd_l(x)    ((x)%10)
@@ -69,33 +69,32 @@
 #define DS1302_TCS1  DS1302_D5
 #define DS1302_TCS2  DS1302_D6
 #define DS1302_TCS3  DS1302_D7
-typedef struct ds1302_struct{uint8_t Seconds:4;uint8_t Seconds10:3;uint8_t CH:1;uint8_t Minutes:4;uint8_t Minutes10:3;uint8_t reserved1:1;union{struct{uint8_t Hour:4;uint8_t Hour10:2;uint8_t reserved2:1;uint8_t hour_12_24:1;}h24;struct{uint8_t Hour:4;uint8_t Hour10:1;uint8_t AM_PM:1;uint8_t reserved2:1;uint8_t hour_12_24:1;}h12;};uint8_t Date:4;uint8_t Date10:2;uint8_t reserved3:2;uint8_t Month:4;uint8_t Month10:1;uint8_t reserved4:3;uint8_t Day:3;uint8_t reserved5:5;uint8_t Year:4;uint8_t Year10:4;uint8_t reserved6:7;uint8_t WP:1;};void DS1302_clock_burst_read( uint8_t *p){int i;_DS1302_start();_DS1302_togglewrite( DS1302_CLOCK_BURST_READ, true);for( i=0; i<8; i++){*p++ = _DS1302_toggleread();}_DS1302_stop();}void DS1302_clock_burst_write( uint8_t *p){int i;_DS1302_start();_DS1302_togglewrite( DS1302_CLOCK_BURST_WRITE, false);for( i=0; i<8; i++){_DS1302_togglewrite( *p++, false);}_DS1302_stop();}uint8_t DS1302_read(int address){uint8_t data;bitSet( address, DS1302_READBIT);_DS1302_start();_DS1302_togglewrite( address, true);data = _DS1302_toggleread();_DS1302_stop();return (data);}void DS1302_write( int address, uint8_t data){bitClear( address, DS1302_READBIT);_DS1302_start();_DS1302_togglewrite( address, false);_DS1302_togglewrite( data, false);_DS1302_stop();}void _DS1302_start( void){digitalWrite( DS1302_CE_PIN, LOW);pinMode( DS1302_CE_PIN, OUTPUT);digitalWrite( DS1302_SCLK_PIN, LOW);pinMode( DS1302_SCLK_PIN, OUTPUT);pinMode( DS1302_IO_PIN, OUTPUT);digitalWrite( DS1302_CE_PIN, HIGH);delayMicroseconds( 4);}void _DS1302_stop(void){digitalWrite( DS1302_CE_PIN, LOW);delayMicroseconds( 4);}uint8_t _DS1302_toggleread( void){uint8_t i, data;data = 0;for( i = 0; i <= 7; i++){digitalWrite( DS1302_SCLK_PIN, HIGH);delayMicroseconds( 1);digitalWrite( DS1302_SCLK_PIN, LOW);delayMicroseconds( 1);bitWrite( data, i, digitalRead( DS1302_IO_PIN));}return( data);}void _DS1302_togglewrite( uint8_t data, uint8_t release){int i;for( i = 0; i <= 7; i++){digitalWrite( DS1302_IO_PIN, bitRead(data, i));delayMicroseconds( 1);digitalWrite( DS1302_SCLK_PIN, HIGH);delayMicroseconds( 1);if( release && i == 7){pinMode( DS1302_IO_PIN, INPUT);}else{digitalWrite( DS1302_SCLK_PIN, LOW);delayMicroseconds( 1);}}}void ds1302_init(){DS1302_write (DS1302_ENABLE, 0);DS1302_write (DS1302_TRICKLE, 0x00);}
+typedef struct ds1302_struct{uint8_t Seconds:4;uint8_t Seconds10:3;uint8_t CH:1;uint8_t Minutes:4;uint8_t Minutes10:3;uint8_t reserved1:1;union{struct{uint8_t Hour:4;uint8_t Hour10:2;uint8_t reserved2:1;uint8_t hour_12_24:1;}h24;struct{uint8_t Hour:4;uint8_t Hour10:1;uint8_t AM_PM:1;uint8_t reserved2:1;uint8_t hour_12_24:1;}h12;};uint8_t Date:4;uint8_t Date10:2;uint8_t reserved3:2;uint8_t Month:4;uint8_t Month10:1;uint8_t reserved4:3;uint8_t Day:3;uint8_t reserved5:5;uint8_t Year:4;uint8_t Year10:4;uint8_t reserved6:7;uint8_t WP:1;};void DS1302_clock_burst_read( uint8_t *p){int i;_DS1302_start();_DS1302_togglewrite( DS1302_CLOCK_BURST_READ, true);for( i=0; i<8; i++){*p++ = _DS1302_toggleread();}_DS1302_stop();}void DS1302_clock_burst_write( uint8_t *p){int i;_DS1302_start();_DS1302_togglewrite( DS1302_CLOCK_BURST_WRITE, false);for( i=0; i<8; i++){_DS1302_togglewrite( *p++, false);}_DS1302_stop();}uint8_t DS1302_read(int address){uint8_t data;bitSet( address, DS1302_READBIT);_DS1302_start();_DS1302_togglewrite( address, true);data = _DS1302_toggleread();_DS1302_stop();return (data);}void DS1302_write( int address, uint8_t data){bitClear( address, DS1302_READBIT);_DS1302_start();_DS1302_togglewrite( address, false);_DS1302_togglewrite( data, false);_DS1302_stop();}void _DS1302_start( void){digitalWrite( DS1302_CE_PIN, LOW);pinMode( DS1302_CE_PIN, OUTPUT);digitalWrite( DS1302_SCLK_PIN, LOW);pinMode( DS1302_SCLK_PIN, OUTPUT);pinMode( DS1302_IO_PIN, OUTPUT);digitalWrite( DS1302_CE_PIN, HIGH);delayMicroseconds( 4);}void _DS1302_stop(void){digitalWrite( DS1302_CE_PIN, LOW);delayMicroseconds( 4);}uint8_t _DS1302_toggleread( void){uint8_t i, data;data = 0;for( i = 0; i <= 7; i++){digitalWrite( DS1302_SCLK_PIN, HIGH);delayMicroseconds( 1);digitalWrite( DS1302_SCLK_PIN, LOW);delayMicroseconds( 1);bitWrite( data, i, digitalRead( DS1302_IO_PIN));}return( data);}void _DS1302_togglewrite( uint8_t data, uint8_t release){int i;for( i = 0; i <= 7; i++){digitalWrite( DS1302_IO_PIN, bitRead(data, i));delayMicroseconds( 1);digitalWrite( DS1302_SCLK_PIN, HIGH);delayMicroseconds( 1);if( release && i == 7){pinMode( DS1302_IO_PIN, INPUT);}else{digitalWrite( DS1302_SCLK_PIN, LOW);delayMicroseconds( 1);}}}void ds1302_init(){DS1302_write (DS1302_ENABLE, 0);DS1302_write (DS1302_TRICKLE, 0x00);}ds1302_struct rtc;

 void setup() {
   ds1302_init();

   lcd.init();
   lcd.backlight();
-  lcd.print("     Hello!");
+  lcd.print("     Hello!     ");

   delay(1500);
 }

 void loop() {
-  ds1302_struct rtc;
   DS1302_clock_burst_read( (uint8_t *) &rtc);

   char buffer[15];

-  sprintf( buffer, "    %02d:%02d:%02d", \
+  sprintf( buffer, "    %02d:%02d:%02d    ", \
     bcd2bin( rtc.h24.Hour10, rtc.h24.Hour), \
     bcd2bin( rtc.Minutes10, rtc.Minutes), \
     bcd2bin( rtc.Seconds10, rtc.Seconds));
   lcd.setCursor(0, 0);
   lcd.print(buffer);

-  sprintf(buffer, "   %02d.%02d.%04d", \
+  sprintf(buffer, "   %02d.%02d.%04d   ", \
     bcd2bin( rtc.Date10, rtc.Date), \
     bcd2bin( rtc.Month10, rtc.Month), \
     2000 + bcd2bin( rtc.Year10, rtc.Year));


Minor corrections to the comments.

Minor corrections to the comments.

--- examples/hello_menu/hello_menu.ino
+++ examples/hello_menu/hello_menu.ino
@@ -37,12 +37,12 @@
  *
  */

-// The official LCD library
+// The LCD library
 #include <LiquidCrystal.h>
-// This library
+// The menu wrapper library
 #include <LiquidMenu.h>

-// Pin mapping for the display
+// Pin mapping for the display:
 const byte LCD_RS = 12;
 const byte LCD_E = 11;
 const byte LCD_D4 = 5;
@@ -134,8 +134,8 @@
   }

   // Periodic switching to the next screen.
-  if (millis() - lastMs_next > period_next) {
-    lastMs_next = millis();
+  if (millis() - lastMs_nextScreen > period_nextScreen) {
+    lastMs_nextScreen = millis();
     menu.next_screen();
   }
 }


Testing Z comp

Testing Z comp

--- gps_arduino/gps_arduino.ino
+++ gps_arduino/gps_arduino.ino
@@ -4,7 +4,9 @@
 #include <TinyGPS.h>
 #include <Wire.h>
 #include <Adafruit_Sensor.h>
-#include <Adafruit_HMC5883_U.h>
+#include <Adafruit_LSM303_U.h>
+#include <Adafruit_L3GD20_U.h>
+#include <Adafruit_9DOF.h>
 #include <SabertoothSimplified.h>

 // tiny gps library code
@@ -14,7 +16,14 @@
 SoftwareSerial mySerial(2, 255);    //used for gps rx and tx pins in use

 //Compass Stuff
-Adafruit_HMC5883_Unified mag = Adafruit_HMC5883_Unified(12345);
+/* Assign a unique ID to the sensors */
+Adafruit_9DOF                dof   = Adafruit_9DOF();
+Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(30301);
+Adafruit_LSM303_Mag_Unified   mag   = Adafruit_LSM303_Mag_Unified(30302);
+
+/* Update this with the correct SLP for accurate altitude measurements */
+float seaLevelPressure = SENSORS_PRESSURE_SEALEVELHPA;
+
 float compassHeading;

 //LCD stuff
@@ -85,9 +94,14 @@
     mySerial.begin(9600);

     /* Initialise the compass */
+    if(!accel.begin()){
+    /* There was a problem detecting the LSM303 ... check your connections */
+    lcd.println(F("Ooops, no LSM303 detected ... Check your wiring!"));
+    while(1);
+   }
     if(!mag.begin()){
       /* There was a problem detecting the HMC5883 ... check your connections */
-      Serial.println("Ooops, no HMC5883 detected ... Check your wiring!");
+      lcd.println("Ooops, no HMC5883 detected ... Check your wiring!");
       while(1);
     }
     //Setup test waypoint
@@ -116,7 +130,13 @@
   void updateHeading(){
     /* Get a new sensor event */
     sensors_event_t event;
+    sensors_event_t accel_event;
+    accel.getEvent(&accel_event);
     mag.getEvent(&event);
+
+//    if(!dof.magTiltCompensation(SENSOR_AXIS_Z, &event, &accel_event)){
+//      return;
+//    }

     // Hold the module so that Z is pointing 'up' and you can measure the heading with x&y
     // Calculate heading when the magnetometer is level, then correct for signs of axis.


SS_SD_PINを削除してSD_CHIP_SELECT_PINに統一

--- examples/Serial2TFT/Serial2TFT.ino
+++ examples/Serial2TFT/Serial2TFT.ino
@@ -5,7 +5,7 @@
 #include "SWTFT.h" // Hardware-specific library
 #include "TFTKanji.h"

-#define SD_SS_PIN 10
+// 小伝馬町16
 #define kanji_file "GONZN16X.TLF"
 #define ank_file   "GONHN16X.TLF"

@@ -34,7 +34,7 @@
 TFTKanji tftkanji;

 int init_sd() {
-  if (!sd.begin(SD_SS_PIN)) {
+  if (!sd.begin(SD_CHIP_SELECT_PIN)) {
     sd.initErrorHalt();
     return -1;
   }
@@ -48,7 +48,7 @@
   while (!Serial) { // これがないとIDEからの書き込みがエラーになる
     // wait for Leonardo
   }
-  pinMode(SD_SS_PIN, OUTPUT);
+  pinMode(SD_CHIP_SELECT_PIN, OUTPUT);

   tft.reset();
   uint16_t identifier = tft.readID();


switching to buffer based sending engine

--- arduino/arduino.ino
+++ arduino/arduino.ino
@@ -57,7 +57,7 @@
   #endif
 #endif

-#if defined(USE_WIFI_SHIELD)
+#ifdef USE_WIFI_SHIELD
   #include <WiFi.h>
   #ifdef USE_STROMBEWUSST_SERVER
     #include <WiFiUdp.h>
@@ -93,7 +93,7 @@
 #ifdef USE_NETWORK
   char readBuffer[13];
   char headerBuffer[10];
-  char sendBuffer[128];
+  char sendBuffer[160];
 #endif

 #ifdef USE_STROMBEWUSST_SERVER
@@ -392,13 +392,11 @@
   Serial.print(F("[network] HTTP request "));
   Serial.println(url);

+
   if (client.connect(ip, 80))
   {
-    client.print(F("GET "));
-    client.print(url);
-    client.println(F(" HTTP/1.0"));
-    client.println(F("Connection: close"));
-    client.println();
+    String request = "GET "+url+" HTTP/1.0\r\nConnection: close\r\n\r\n";
+    client.print(request);
     return true;
   } else
   {


loop for PR values

loop for PR values

--- arduino-program/MILaserCourseController.ino
+++ arduino-program/MILaserCourseController.ino
@@ -101,8 +101,9 @@
   }
 }
 String constructSerialTx() {
-  return finishPushed + "_" + startPushed + "_" + lasersOn
-    + "_" + pr1Val + "_" + pr2Val + "_" + pr3Val + "_" + pr4Val
-    + "_" + pr5Val + "_" + pr6Val + "_" + pr7Val + "_" + pr8Val
-    + "_" + pr9Val + "_" + pr10Val;
+  serialTx += finishPushed + "_" + startPushed + "_" + lasersOn;
+  for(int i=0; i < numPrPins; i++) {
+      serialTx += prValues[i];
+  }
+  return serialTx;
 }


servo problem totaly solved

servo problem totaly solved

servo problem totaly solved and tested

--- arduino/medox/medox.ino
+++ arduino/medox/medox.ino
@@ -40,10 +40,11 @@
 #include <Servo.h>
 Servo drawerServo;// create servo object to control a servo
 Servo warehouseServo;// create servo object to control a servo
-#define drawerServoOpen     90
+#define drawerServoOpen     100
 #define drawerServoClose    0
-#define WarehouseServoOpen  90
+#define WarehouseServoOpen  100
 #define WarehouseServoClose 10
+#define servoPositionDelay  500 //to wait until servo reaches position

 //variables definition
 char  serialData;             //for storing serial string
@@ -174,24 +175,28 @@
 void openDoor(){
   drawerServo.attach(drawer);        // attaches the doorServo on pin Arduino pin
   drawerServo.write(drawerServoOpen);
+  delay(servoPositionDelay); //waits servo to reach position
   drawerServo.detach(); //detaches the doorServo
 }

 void openWarehouse(){
   warehouseServo.attach(warehouse);  // attaches the warehouseServo on pin Arduino pin
   warehouseServo.write(WarehouseServoOpen);
+  delay(servoPositionDelay); //waits servo to reach position
   warehouseServo.detach(); //detaches the warehouseServo
 }

 void closeDoor(){
   drawerServo.attach(drawer);        // attaches the doorServo on pin Arduino pin
   drawerServo.write(drawerServoClose);
+  delay(servoPositionDelay); //waits servo to reach position
   drawerServo.detach(); //detaches the doorServo
 }

 void closeWarehouse(){
   warehouseServo.attach(warehouse);  // attaches the warehouseServo on pin Arduino pin
   warehouseServo.write(WarehouseServoClose);
+  delay(servoPositionDelay); //waits servo to reach position
   warehouseServo.detach(); //detaches the warehouseServo
 }


Calculating and displaying averaged (smoothed) sample value

--- ArduinoAudioSpectrumAnalyzer.ino
+++ ArduinoAudioSpectrumAnalyzer.ino
@@ -30,6 +30,7 @@
   // Use this initializer (uncomment) if you're using a 1.44" TFT
   tft.initR(ST7735_INITR_144GREENTAB);   // initialize a ST7735S chip, black tab
   tft.fillScreen(ST7735_BLACK);
+  tft.setTextWrap(false);
 }

 void setupADC()
@@ -66,6 +67,7 @@

 volatile uint16_t maxSampleValue = 0;
 volatile uint16_t minSampleValue = 65535;
+volatile uint16_t averageSampleValue = 0;

 constexpr uint16_t SamplingWindowSize = FHT_N;
 volatile bool samplingWindowFull = false;
@@ -82,6 +84,9 @@
 #endif

   ++currentSampleIndex;
+
+  constexpr uint16_t k = 8;
+  averageSampleValue = (averageSampleValue * (k - 1) + sample) / k;

   if (currentSampleIndex == SamplingWindowSize)
   {
@@ -124,8 +129,12 @@
   tft.print(minSampleValue);

   tft.setTextColor(RGB_to_565(255, 0, 10));
-  tft.setCursor(64, 0);
+  tft.setCursor(45, 0);
   tft.print(maxSampleValue);
+
+  tft.setTextColor(RGB_to_565(0, 255, 10));
+  tft.setCursor(90, 0);
+  tft.print(averageSampleValue);

   assert(FHT_N == 256);
   for (int i = 1; i < 128; ++i) // What's the deal with bin 0?


Almost rewritten receiver firmware. Arduino sleep missing.

--- sw/receiver/receiver.ino
+++ sw/receiver/receiver.ino
@@ -26,12 +26,12 @@
 const byte request[2] = {0x00, 0xFA};
 byte packet[8];

-bool timeout;
+bool timeout, rx, tx, fail;

 void setup(void) {
   Serial.begin(115200);

-  Serial.print("Setup -> "); delay(10);
+  Serial.print("Setup -> ");

   // Turn down unneeded peripherals
   power_adc_disable();
@@ -64,7 +64,7 @@
   radio.openWritingPipe(RF24_PIPE);

   // Power down nrf24
-  radio.powerDown();
+  //radio.powerDown();

   // Attach interrupt
   attachInterrupt(1, checkRadio, FALLING);
@@ -72,73 +72,104 @@
   // Init motor pins
   pinMode(MOTOR_1, OUTPUT);
   pinMode(MOTOR_2, OUTPUT);
-}
-
-void loop(void) {
-  goToSleep(false); Serial.println();
-
-  // Here is passed around a second.
-  Serial.print("Wake -> ");
-
-  radio.powerUp();
-
+
+  Serial.println("Ready.");
+}
+
+void loop(void) {
+  // Replace this with Arduino sleep + WDT timeout
+  delay(3000);
+
+  radio.powerUp(); //delay(50);
+
+  Serial.print("Request ");
+
+  // Reset flags
+  tx = false; fail = false;
+
   // Send status request to base. This command power up the radio
-  Serial.print("Request ");
-  int res = radio.write(request, 2);
-
-  Serial.print(res); Serial.print(" -> ");
-
-  // Put nrf24 in receive mode
-  radio.startListening();
-
-  // Sleep the MCU while waiting for response
-  goToSleep(true);
-
-  Serial.print(" -> Wake -> Got ");
-
-  if(timeout) {
-    Serial.print("nothing");
-
+  radio.startWrite(request, 2);
+
+  // Replace this with Arduino sleep
+  while(!tx && !fail) { delay(10); }
+
+  if(tx) {
+    // Transmission was successful, now wait a reply
+
+    Serial.print(" -> Listening ");
+
+    // Put nrf24 in receive mode
+    radio.startListening();
+
+    // Reset flags
+    rx = false; fail = false;
+
+    // Wait for nrf24 to do its magic
+    // TODO:Replace this with Arduino sleep + WDT timeout
+    int retries = 0;
+    while(!rx || !fail) {
+      delay(10); retries++;
+      if(retries == 20) break;
+    }
+
+    if(rx) {
+      // We got something
+
+      // Read it
+      radio.read(packet, RF24_PAYLOAD);
+
+      Serial.print("-> Got ");
+
+      for(int i = 0; i < RF24_PAYLOAD; i++) {
+        Serial.print(packet[i], HEX); Serial.print(" ");
+      }
+      Serial.println();
+
+      // TODO: do something here
+    } else {
+      // RX timed out. Restart from scratch.
+      Serial.println(" -> Rx timeout");
+    }
+
+    radio.stopListening();
+
+  } else {
+    Serial.println(" -> Tx Error");
+  }
+
+  // It's done. Now, rest.
+  radio.powerDown();
+}
+
+void checkRadio(void) {
+  // What happened?
+  radio.whatHappened(tx,fail,rx);
+
+  if(tx || fail)
     radio.powerDown();
-
-  } else {
-    // checkRadio() has been executed, do stuff.
-    for(int i = 0; i < RF24_PAYLOAD; i++) {
-      Serial.print(packet[i], HEX); Serial.print(" ");
-    }
-  }
-
-  radio.stopListening();
-
-  Serial.print(" -> ");
-}
-
-
+
+  Serial.print("[tx:");
+  Serial.print(tx);
+  Serial.print(" rx: ");
+  Serial.print(rx);
+  Serial.print("fail: ");
+  Serial.print(fail);
+  Serial.print("]" );
+}
+
+/*
 void goToSleep(bool isTimeout) {
   Serial.print("Sleep"); delay(10);
+
+  timeout = true;
+
+  delay(3000);

   // Enable interupt timeout
-  setWdt(isTimeout);
+  //setWdt(isTimeout);

   // Go to sleep
-  sleep_mode();
-}
-
-void checkRadio(void) {
-  wdt_disable();
-
-  // What happened?
-  bool tx,fail,rx;
-  radio.whatHappened(tx,fail,rx);
-
-  // Did we receive a message?
-  if (rx) {
-    // Power down nrf24
-    radio.powerDown();
-
-    // Read the last packet
-    radio.read(packet, RF24_PAYLOAD);
-  }
+  //sleep_mode();
 }

 void setWdt(bool isTimeout) {
@@ -148,7 +179,7 @@
   byte bits;

   if(isTimeout) {
-    bits = (1<<WDP2) /*| (1<<WDP1)*/;
+    bits = (1<<WDP2) | (1<<WDP1);
     timeout = false;
   } else {
     bits = (1<<WDP3) | (1<<WDP0);
@@ -174,3 +205,4 @@

   sei();
 }
+*/


modified ir_receiver_demo to print 1 when signal reads active-low

--- demos/ir_receiver_demo/ir_receiver_demo.ino
+++ demos/ir_receiver_demo/ir_receiver_demo.ino
@@ -18,8 +18,11 @@
   int ir_receiver_reading = digitalRead(IR_RECEIVER_PIN);

   //display the reading
-  Serial.println(ir_receiver_reading);
-
+  if (ir_receiver_reading==LOW) //active low
+    Serial.println("1");
+  else
+    Serial.println("0");
+
   //wait 30 miliseconds
   delay(30);
 }


add playground/ESP32/Blink/Blink.ino

add playground/ESP32/Blink/Blink.ino

--- playground/ESP32/Blink/Blink.ino
+++ playground/ESP32/Blink/Blink.ino
@@ -1,4 +1,4 @@
-/*
+    /*
   Blink

   Turns an LED on for one second, then off for one second, repeatedly.


Fixed interrupts, working on high-level display

--- PixelVFO.ino
+++ PixelVFO.ino
@@ -1,4 +1,4 @@
-/***************************************************
+/****************************************************
  * PixelVFO - a digital VFO driven by touchscreen.
  *
  * VK4FAWR - rzzzwilson@gmail.com
@@ -29,7 +29,8 @@
 // The XPT2046 uses hardware SPI, #4 is CS with #3 for interrupts
 #define TS_CS       4
 #define TS_IRQ      3
-XPT2046_Touchscreen ts(TS_CS, TS_IRQ);
+//XPT2046_Touchscreen ts(TS_CS, TS_IRQ);
+XPT2046_Touchscreen ts(TS_CS);

 // The display also uses hardware SPI, plus #9 & #10
 #define TFT_RST     8
@@ -55,6 +56,7 @@
 #define SCREEN_BG1          ILI9341_BLACK
 #define FREQ_FG             ILI9341_BLUE
 #define FREQ_BG             ILI9341_WHITE
+#define FREQ_SEL_BG         ILI9341_GREEN
 #define BOTTOM_BG           ILI9341_WHITE

 // touchscreen stuff
@@ -67,6 +69,9 @@
 char freq_display[NUM_F_CHAR];          // digits of frequency, as binary values [0-9]
 unsigned long frequency;                // frequency as a long integer
 uint16_t char_x_offset[NUM_F_CHAR + 1]; // x offset for start/end of each character on display
+
+// index of selected digit in frequency display
+int sel_digit = -1;

 uint32_t volatile msraw = 0x80000000;
 #define MIN_REPEAT_PERIOD   2
@@ -102,10 +107,12 @@

   if (digitalRead(TS_IRQ) == 0)
   { // pen DOWN
+    if (!PenDown)
+    {
+      ts_read(&last_x, &last_y);
+      event_push(event_Down, last_x, last_y);
+    }
     PenDown = true;
-    ts_read(&last_x, &last_y);
-    Serial.printf("After ts_read(): last_x=%d, last_y=%d\n", last_x, last_y);
-    event_push(event_Down, last_x, last_y);
   }
   else
   { // pen UP
@@ -156,9 +163,11 @@
   tft.fillScreen(SCREEN_BG2);
   tft.setTextWrap(false);
   tft.fillRect(0, 0, tft.width(), DEPTH_FREQ_DISPLAY, FREQ_BG);
+#if 0
   tft.drawRect(0, 0, tft.width(), DEPTH_FREQ_DISPLAY, SCREEN_BG1);
   tft.drawRect(1, 1, tft.width()-2, DEPTH_FREQ_DISPLAY-2, SCREEN_BG2);
   tft.drawRect(2, 2, tft.width()-4, DEPTH_FREQ_DISPLAY-4, SCREEN_BG3);
+#endif
   tft.setCursor(MHZ_OFFSET_X, FREQ_OFFSET_Y);
   tft.setTextColor(FREQ_FG);
   tft.print("Hz");
@@ -205,25 +214,27 @@
   // Scale from ~0->4000 to tft.width using the calibration #'s
   *x = map(p.x, TS_MINX, TS_MAXX, 0, tft.width());
   *y = map(p.y, TS_MINY, TS_MAXY, 0, tft.height());
-  Serial.print("New x="); Serial.print(*x);
-  Serial.print(", y="); Serial.println(*y);

   return true;
 }

 //-----------------------------------------------
 // Draw the frequency byte buffer to the screen.
+//     select  index of digit to highlight
 // Updates all digits on the screen.  Skips leading zeros.
 //-----------------------------------------------

-void display_frequency(void)
+void display_frequency(int select=-1)
 {
   bool leading_space = true;

   for (int i = 0; i < NUM_F_CHAR; ++i)
   {
-    tft.fillRect(freq_display[i]-1, FREQ_OFFSET_Y-CHAR_HEIGHT-1,
-                 CHAR_WIDTH+2, CHAR_HEIGHT+2, FREQ_BG);
+    if (i == select)
+      tft.fillRect(char_x_offset[i], 2, CHAR_WIDTH+2, DEPTH_FREQ_DISPLAY-4, FREQ_SEL_BG);
+    else
+      tft.fillRect(char_x_offset[i], 2, CHAR_WIDTH+2, DEPTH_FREQ_DISPLAY-4, FREQ_BG);
+
     if ((freq_display[i] != '0') || !leading_space)
     {
       tft.drawChar(char_x_offset[i], FREQ_OFFSET_Y, freq_display[i], FREQ_FG, FREQ_BG, 1);
@@ -233,19 +244,15 @@
 }

 //-----------------------------------------------
+// Setup the whole shebang.
 //-----------------------------------------------
 void setup(void)
 {
   Serial.begin(115200);
   Serial.printf("PixelVFO %s.%s\n", MAJOR_VERSION, MINOR_VERSION);

-  // initialize the touchscreen pins, mode and level
-//  pinMode(TS_CS, OUTPUT);
-//  digitalWrite(TS_CS, HIGH);
-//  pinMode(TS_IRQ, INPUT_PULLUP);
-
   // link the TS_IRQ pin to its interrupt handler
-  //attachInterrupt(digitalPinToInterrupt(TS_IRQ), touch_irq, CHANGE);
+  attachInterrupt(digitalPinToInterrupt(TS_IRQ), touch_irq, CHANGE);

   // set up the VFO frequency data structures
   frequency = 1000000L;
@@ -259,6 +266,7 @@
     x_offset += CHAR_WIDTH;
   }

+  // start handling devices
   SPI.begin();

   tft.begin();
@@ -268,21 +276,12 @@
   ts.begin();
   ts_setRotation(1);

-//  tft.fillScreen(ILI9341_BLACK);
   // draw the basic screen
   draw_screen();

   // draw the 'thousands' markers
   draw_thousands();
-
-  // draw the 'edge of digits' markers
-  for (int i = 0; i < NUM_F_CHAR; ++i)
-  {
-    uint16_t x = char_x_offset[i];
-
-    tft.drawFastVLine(x, 44, 6, ILI9341_RED);
-  }
-
+
   // show the frequency
   display_frequency();
 }
@@ -291,9 +290,45 @@
 //-----------------------------------------------
 void loop()
 {
-  int x = 0;
-  int y = 0;
-
-  if (ts_read(&x, &y))
-    tft.fillCircle(x, y, 5, ILI9341_RED);
-}
+  // handle all events in the queue
+  while (true)
+  {
+    // get next event and handle it
+    VFOEvent *event = event_pop();
+
+    if (event->event == event_None)
+      break;
+
+    uint16_t x = event->x;
+    uint16_t y = event->y;
+
+    Serial.printf("Event %s\n", event2display(event));
+
+    switch (event->event)
+    {
+      case event_Down:
+        // see if DOWN is on a VFO frequency digit
+        if (y < DEPTH_FREQ_DISPLAY + 30)    // a bit of 'slop' allowed
+        {
+          for (int i = 0; i < NUM_F_CHAR; ++i)
+          {
+            if ((x > char_x_offset[i]) && (x < char_x_offset[i+1]))
+            {
+              // within char 'bucket'
+              sel_digit = i;
+              display_frequency(i);
+              break;
+            }
+          }
+        }
+        break;
+      case event_Up:
+//        display_frequency();
+        break;
+      case event_Drag:
+        break;
+      default:
+        abort("Unrecognized event!?");
+    }
+  }
+}


Update sem_v1.ino

Update sem_v1.ino

--- Arduino/sem_v1.ino
+++ Arduino/sem_v1.ino
@@ -1,3 +1,45 @@
+
+ /*-------------------------------------------- LICENSE (MIT) -------------------------------------------------
+
+         				                        Copyright (c) 2015 Conor Walsh
+         			                        Website: http://www.conorwalsh.net
+                                    GitHub:  https://github.com/conorwalsh
+                             Project: Smart Environment Monitoring system (S.E.M.)
+
+        		Permission is hereby granted, free of charge, to any person obtaining a copy
+        		of this software and associated documentation files (the "Software"), to deal
+        		in the Software without restriction, including without limitation the rights
+        		to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+        		copies of the Software, and to permit persons to whom the Software is
+        		furnished to do so, subject to the following conditions:
+
+        		The above copyright notice and this permission notice shall be included in all
+        		copies or substantial portions of the Software.
+
+        		THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+        		IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+        		FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+        		AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+        		LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+        		OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+        		SOFTWARE.
+        	   __  __   ____                        __        __    _     _       ____   ___  _ ____
+        	  / /__\ \ / ___|___  _ __   ___  _ __  \ \      / /_ _| |___| |__   |___ \ / _ \/ | ___|
+        	 | |/ __| | |   / _ \| '_ \ / _ \| '__|  \ \ /\ / / _` | / __| '_ \    __) | | | | |___ \
+        	 | | (__| | |__| (_) | | | | (_) | |      \ V  V / (_| | \__ \ | | |  / __/| |_| | |___) |
+        	 | |\___| |\____\___/|_| |_|\___/|_|       \_/\_/ \__,_|_|___/_| |_| |_____|\___/|_|____/
+        	  \_\  /_/
+
+ ----------------------------------------------- LICENSE END -----------------------------------------------*/
+
+ /*---------------------------------------------- CODE INFO --------------------------------------------------
+
+             	This code runs on an Arduino Yún and sends sensor data to a MySQL database
+             	every 3 minutes.
+
+ ---------------------------------------------- CODE INFO END ----------------------------------------------*/
+
+
 #include <Bridge.h>
 #include <HttpClient.h>
 #include "DHT.h"


remote control

remote control

--- Arduino/EndNode_1_SWITCH_ESP32_X_NEO/EndNode_1_SWITCH_ESP32_X_NEO.ino
+++ Arduino/EndNode_1_SWITCH_ESP32_X_NEO/EndNode_1_SWITCH_ESP32_X_NEO.ino
@@ -72,6 +72,8 @@

 NextionPicture pdummy(nex, 0, 73, "pDummy"); //used to simulate triggers on numeric valiable
 NextionPicture psettings(nex, 0, 67, "p0"); //settings icon
+NextionPicture ptv(nex, 0, 14, "tv"); //settings icon
+NextionPicture pac(nex, 0, 9, "ac"); //settings icon

 NextionPicture bgroup(nex, 0, 19, "g0");
 NextionPicture iwifi(nex, 0, 72, "i_wifi");
@@ -119,6 +121,7 @@
 NextionPicture actempdown(nex, 1, 10, "ptd");
 NextionPicture acswing(nex, 1, 14, "ps");
 NextionPicture acmode(nex, 1, 13, "pm");
+NextionPicture bbackac(nex, 1, 8, "p1");

 //----- TV ----------------------------//
 NextionPicture tvon(nex, 2, 7, "pon");
@@ -129,6 +132,7 @@
 NextionPicture tvsource(nex, 2, 14, "px");
 NextionPicture tvok(nex, 2, 13, "pok");
 NextionPicture tvret(nex, 2, 15, "pret");
+NextionPicture bbacktv(nex, 2, 8, "p1");

 //----- Group select ----------------------------//
 NextionRadioButton r_t0(nex, 5, 13, "g0");
@@ -231,6 +235,8 @@
   bdimmer.attachCallback(&_bdimmer); //dimmer control
   pdummy.attachCallback(&_pdummy); //default light
   psettings.attachCallback(&_psettings); //settings icon
+  ptv.attachCallback(&_ptv); //tv icon
+  pac.attachCallback(&_pac); //ac icon

   bgroup.attachCallback(&_bgroup);
   blight1.attachCallback(&_blight1);
@@ -240,7 +246,6 @@
   blight5.attachCallback(&_blight5);
   blight6.attachCallback(&_blight6);
   bback.attachCallback(&_bback);
-  //t_t1.attachCallback(&_t_t1);

   r_t0.attachCallback(&_r_t0);
   r_t1.attachCallback(&_r_t1);
@@ -274,6 +279,7 @@
   actempdown.attachCallback(&_actempdown);
   acswing.attachCallback(&_acswing);
   acmode.attachCallback(&_acmode);
+  bbackac.attachCallback(&_bbackac);

   //----- TV ----------------------------//
   tvon.attachCallback(&_tvon);
@@ -284,6 +290,7 @@
   tvsource.attachCallback(&_tvsource);
   tvok.attachCallback(&_tvok);
   tvret.attachCallback(&_tvret);
+  bbacktv.attachCallback(&_bbacktv);

   nex.init();
   delay(1000);
@@ -312,7 +319,6 @@
   getStatusLight();
   enableTask();
 }
-

 // *******************************************************//
 // Functions  NEXTION                                            //
@@ -550,8 +556,6 @@
           sendCommand(setValue.c_str());
           setValue = "vl" + String(i) + ".val=" + int(aLights[i].value); //value
           sendCommand(setValue.c_str());
-          //setValue = "cx" + String(i) + ".val=" + int(aLights[i].color); //color
-          //sendCommand(setValue.c_str());
         }
         break;
       case 1:
@@ -595,7 +599,6 @@
           else {
             aLights[c_light].value = 0;
           }
-
         }
         break;
       case 3:
@@ -617,7 +620,6 @@
           else {
             aLights[c_light].value = 0;
           }
-
         }
         break;
       case 4:
@@ -639,7 +641,6 @@
           else {
             aLights[c_light].value = 0;
           }
-
         }
         break;
       case 5:
@@ -712,10 +713,7 @@
         sendCommand(setValue.c_str());
         setValue = "vl" + String(i) + ".val=" + int(aLights[i].value); //value
         sendCommand(setValue.c_str());
-        //setValue = "cx" + String(i) + ".val=" + int(aLights[i].color); //color
-        //sendCommand(setValue.c_str());
       }
-
       break;
     case 1:
       aLights[c_light].status = vst1.getValue();
@@ -843,6 +841,32 @@
   pTic();
 }

+
+void _bbacktv(NextionEventType type, INextionTouchable * widget)
+{
+  //read global variables
+  c_light = vdeflight.getValue();
+  c_switch_mode = vdefmainsw.getValue();
+  nex.poll();
+  refreshScreen();
+  nex.poll();
+  runningTimer = true;
+  pTic();
+}
+
+
+void _bbackac(NextionEventType type, INextionTouchable * widget)
+{
+  //read global variables
+  c_light = vdeflight.getValue();
+  c_switch_mode = vdefmainsw.getValue();
+  nex.poll();
+  refreshScreen();
+  nex.poll();
+  runningTimer = true;
+  pTic();
+}
+
 void _btradfri(NextionEventType type, INextionTouchable * widget)
 {
   char buffer_ip[40];
@@ -857,7 +881,6 @@
       tradfriParams_ip[i] = buffer_ip[i];
       tradfriParams_key[i] = buffer_key[i];
     }
-
     putTradfriParams();
   }
 }
@@ -988,6 +1011,18 @@
   runningTimer = false;
 }

+void _ptv(NextionEventType type, INextionTouchable * widget)
+{
+  pTic();
+  runningTimer = false;
+}
+
+void _pac(NextionEventType type, INextionTouchable * widget)
+{
+  pTic();
+  runningTimer = false;
+}
+
 //-----------------------------------------------------//
 // 3 colors bulbs
 //-----------------------------------------------------//


Delete Rollup_logic.ino

Delete Rollup_logic.ino

--- Rollup_logic/Rollup_logic.ino
+++ Rollup_logic/Rollup_logic.ino
@@ -1,257 +0,0 @@
-#include <OneWire.h>
-#include <DallasTemperature.h>
-
-#define Open 1
-#define Close 0
-
-#define LIMITSWITCH 2
-#define ONE_WIRE_BUS 3
-#define ROLLUP1_OPEN  10//relais on/off - moteur1
-#define ROLLUP1_CLOSE  9 //relais gauche/droite - moteur1
-#define FAN  8 //relais ventilation forcée
-#define CHAUFFAGE1 7 //relais fournaise1
-#define CHAUFFAGE2 6 // relais fournaise2
-
-OneWire oneWire(ONE_WIRE_BUS);
-// Pass our oneWire reference to Dallas Temperature.
-DallasTemperature sensors(&oneWire);
-
-const int ON = HIGH;
-const int OFF = LOW;
-
-byte opened = 100;
-byte openTarget = 0;
-
-boolean heating1 = false;                     //fournaise 1 éteinte par défaut
-boolean heating2 = false;                     //fournaise 2 éteinte par défaut
-boolean fan = false;                          //VENTilation forcée éteinte par défaut
-float greenhouseTemperature = 20.0;               //température par défaut : 20C (ajusté après un cycle)
-
-int TEMP_CIBLE = 20;          //température cible par défaut : 20C (ajustée après un cycle))
-//temp cible pour équipement chauffage/refroidissement
-int TEMP_ROLLUP1 = TEMP_CIBLE+1;
-int TEMP_ROLLUP2 = TEMP_CIBLE+2;
-int TEMP_ROLLUP3 = TEMP_CIBLE+3;
-int TEMP_ROLLUP4 = TEMP_CIBLE+4;
-int TEMP_VENTILATION = TEMP_CIBLE+5;
-int TEMP_FOURNAISE1 = TEMP_CIBLE-2;
-int TEMP_FOURNAISE2 = TEMP_CIBLE-4;
-
-byte HYST_ROLLUP = 1;           //hysteresis rollup
-byte HYST_VENT = 1;             //hysteresis ventilation
-byte HYST_FOURNAISE1 = 2;       //hysteresis fournaise 1
-byte HYST_FOURNAISE2 = 2;       //hysteresis fournaise 2
-
-long OPENING_TIME = 3000;       //temps de rotation des moteurs pour ouvrir d'un quart de tour(en mili-secondes)
-long CLOSING_TIME = 2000;       //temps de rotation des moteurs pour fermer d'un quart de tour(en mili-secondes)
-long PAUSE_TIME = 1000;         //temps d'arrêt entre chaque ouverture/fermeture(en mili-secondes)
-//incréments d'ouverture(nombre d'incréments d'ouverture = PCT_OPEN/NB_OF_STEPS_IN_ANIMATION = 25/5 = 5 incréments d'ouverture)
-const int PCT_OPEN = 25;
-const int NB_OF_STEPS_IN_ANIMATION = 5; //doit être un divisible de PCT_OPEN
-//Autres variables
-const int SLEEPTIME = 900; //temps de pause entre chaque exécution du programme(en mili-secondes)
-
-volatile byte rollupState = HIGH;
-
-void setup() {
-  // put your setup code here, to run once:
-  Serial.begin(9600);
-  sensors.begin();
-  pinMode(LIMITSWITCH, INPUT_PULLUP);
-  pinMode(ROLLUP1_OPEN, OUTPUT);
-  digitalWrite(ROLLUP1_OPEN, LOW);
-  pinMode(ROLLUP1_CLOSE, OUTPUT);
-  digitalWrite(ROLLUP1_CLOSE, LOW);
-  pinMode(CHAUFFAGE1, OUTPUT);
-  digitalWrite(CHAUFFAGE1, LOW);
-  pinMode(CHAUFFAGE2, OUTPUT);
-  digitalWrite(CHAUFFAGE2, LOW);
-  pinMode(FAN, OUTPUT);
-  digitalWrite(FAN, LOW);
-  attachInterrupt(digitalPinToInterrupt(2), confirmOpening, CHANGE);
-
-  //Remise à niveau des rollup
-  //Reset();
-}
-
-void loop() {
-  // put your main code here, to run repeatedly:
-  //--------------DS18B20--------------------
-  sensors.requestTemperatures();
-  greenhouseTemperature = sensors.getTempCByIndex(0);
-  Serial.println(greenhouseTemperature);
-  //--------------Relais--------------------
-
-  //Programme d'ouverture/fermeture des rollups à 4 paliers
-  if ((opened == 0)&&(greenhouseTemperature > TEMP_ROLLUP1)){
-    openTarget = 25;
-    openSides();
-  }
-  else if ((opened == 25)&&(greenhouseTemperature < (TEMP_ROLLUP1 - HYST_ROLLUP))) {
-    openTarget = 0;
-    closeSides();
-  }
-  else if ((opened == 25)&&(greenhouseTemperature > TEMP_ROLLUP2)){
-    openTarget = 50;
-    openSides();
-  }
-  else if ((opened == 50)&&(greenhouseTemperature < (TEMP_ROLLUP2 - HYST_ROLLUP))) {
-    openTarget = 25;
-    closeSides();
-  }
-  else if ((opened == 50)&&(greenhouseTemperature > TEMP_ROLLUP3)){
-    openTarget = 75;
-    openSides();
-  }
-  else if ((opened == 75)&&(greenhouseTemperature < (TEMP_ROLLUP3 - HYST_ROLLUP))) {
-    openTarget = 50;
-    closeSides();
-  }
-  else if ((opened == 75)&&(greenhouseTemperature > TEMP_ROLLUP4)){
-    openTarget = 100;
-    openSides();
-  }
-  else if ((opened == 100)&&(greenhouseTemperature < (TEMP_ROLLUP4 - HYST_ROLLUP))) {
-    openTarget = 75;
-    closeSides();
-  }
-
-
-  //Programme fournaise1
-  if (greenhouseTemperature < TEMP_FOURNAISE1) {
-    setHeater1(ON);
-  }
-  else if (greenhouseTemperature > (TEMP_FOURNAISE1 + HYST_FOURNAISE1)) {
-    setHeater1(OFF);
-  }
-  //Programme fournaise2
-  if (greenhouseTemperature < TEMP_FOURNAISE2) {
-    setHeater2(ON);
-  }
-  else if (greenhouseTemperature > (TEMP_FOURNAISE2 + HYST_FOURNAISE2)) {
-    setHeater2(OFF);
-  }
-  //Programme ventilation forcée
-  if ((greenhouseTemperature > TEMP_VENTILATION)&&(rollupState == HIGH)) {
-    setFan(ON);
-  } else if ((greenhouseTemperature < (TEMP_VENTILATION - HYST_VENT))||(rollupState == LOW)) {
-    setFan(OFF);
-  }
-  delay(1000);
-}
-
-
-
-void Reset(){
-    Serial.println(F("Resetting position"));
-  for (int i = 0; i < 5; i++) {
-    closeSides();
-  }
-  Serial.println(F("Resetting done"));
-}
-
-//Affichage du % d'ouverture des rollup
-void setOpenedStatus(int pctIncrease) {
-  opened += pctIncrease;
-  if (opened < 0) {
-    opened = 0;
-  } else if (opened > 100) {
-    opened = 100;
-  }
-  Serial.print(F("    "));
-  Serial.println(opened);
-}
-
-//Exécution de la séquence d'ouverture/fermeture
-void animate(int movement, int action) {
-  for (int i = 0; i < NB_OF_STEPS_IN_ANIMATION; i++) {
-    if (action == Open){
-      delay(OPENING_TIME / NB_OF_STEPS_IN_ANIMATION);}
-    else if (action == Close){
-      delay(CLOSING_TIME / NB_OF_STEPS_IN_ANIMATION);}
-    setOpenedStatus(movement * PCT_OPEN / NB_OF_STEPS_IN_ANIMATION);
-  }
-}
-
-//Programme d'ouverture des rollup
-void openSides() {
-  if (opened < 100) {
-    Serial.println(opened);
-    Serial.println(F(""));
-    Serial.println(F("  Opening"));
-    digitalWrite(ROLLUP1_OPEN, ON);
-    //digitalWrite(ROLLUP2_OPEN, ON);
-    animate(1, Open);
-    digitalWrite(ROLLUP1_OPEN, OFF);
-    //digitalWrite(ROLLUP2_OPEN, OFF);
-    Serial.println(F("  Done opening"));
-    delay(PAUSE_TIME);
-  }
-}
-
-//Programme de fermeture des rollups
-void closeSides() {
-  if (opened > 0) {
-    Serial.println(opened);
-    Serial.println(F(""));
-    Serial.println(F("  Closing"));
-    digitalWrite(ROLLUP1_CLOSE, ON);
-    animate(-1, Close);
-    digitalWrite(ROLLUP1_CLOSE, OFF);
-    //digitalWrite(ROLLUP2_CLOSE, OFF);
-    Serial.println(F("  Done closing"));
-    delay(PAUSE_TIME);
-  }
-}
-
-
-//État de la première fournaise
-void setHeater1(int heaterCommand1) {
-  if ((heaterCommand1 == ON) && (heating1 == false)) {
-    Serial.println(F(""));
-    Serial.println(F("  Start heating1"));
-    heating1 = true;
-    digitalWrite(CHAUFFAGE1, ON);
-  } else if ((heaterCommand1 == OFF) && (heating1 == true)) {
-    Serial.println(F(""));
-    Serial.println(F("  Stop heating1"));
-    heating1 = false;
-    digitalWrite(CHAUFFAGE1, OFF);
-  }
-}
-
-//État de la deuxième fournaise
-void setHeater2(int heaterCommand2) {
-  if ((heaterCommand2 == ON) && (heating2 == false)) {
-    Serial.println(F(""));
-    Serial.println(F("  Start heating2"));
-    heating2 = true;
-    digitalWrite(CHAUFFAGE2, ON);
-  } else if ((heaterCommand2 == OFF) && (heating2 == true)) {
-    Serial.println(F(""));
-    Serial.println(F("  Stop heating2"));
-    heating2 = false;
-    digitalWrite(CHAUFFAGE2, OFF);
-  }
-}
-
-//État de la ventilation
-void setFan(int fanCommand) {
-  if ((fanCommand == ON) && (fan == false)) {
-    Serial.println(F(""));
-    Serial.println(F("  Start fan"));
-    fan = true;
-    digitalWrite(FAN, ON);
-  } else if ((fanCommand == OFF) && (fan == true)) {
-    Serial.println(F(""));
-    Serial.println(F("  Stop fan"));
-    fan = false;
-    digitalWrite(FAN, OFF);
-  }
-}
-
-void confirmOpening() {
-  rollupState =! rollupState;
-  opened = 100;
-  digitalWrite(ROLLUP1_OPEN, LOW);
-}


light refactoring

light refactoring

--- Firmware/Robot.ino
+++ Firmware/Robot.ino
@@ -2,38 +2,48 @@
 // Robot.ino
 //
 //
-//   Wheel 4               Wheel 1
+//   Wheel 3               Wheel 0
 //     +--------------------+
 //     |                    |
 //     |               Arm  | -->
 //     |                    |
 //     +--------------------+
-//   Wheel 3               Wheel 2
+//   Wheel 2               Wheel 1
 //

-#define DEBUG     0
-#define BUS_SPEED 1000  // 1Mbaud
+#include <CAN.h>
+#include <SPI.h>

-void robot_init()
+#define DEBUGMODE 0
+#define CAN_BUS_SPEED 1000  // 1Mbaud
+
+void robot_begin()
+{
+    robot_initCAN(CAN_BUS_SPEED);
+
+    for (int wheel = 0; wheel < 4; wheel++)
+    {
+        robot_initWheel(wheel);
+    }
+
+    #if DEBUGMODE
+    Serial.println("@E01: Robot movement is ready.");
+    #endif
+}
+
+void robot_initCAN(uint16_t baudrate)
 {
     CAN.begin();
-    CAN.baudConfig(BUS_SPEED);
+    CAN.baudConfig(baudrate);
     CAN.setMode(NORMAL);
     delay(100);
+}

-    for (int i = 0; i < 4; i++)
-    {
-        robot_initNode(robot_nodeAdress(i));
-
-        #if DEBUG
-        Serial.print("# Init node ");
-        Serial.println(i + 1);
-        #endif
-    }
-
-    #if DEBUG
-    Serial.println("# All nodes ready");
-    #endif
+void robot_initWheel(uint8_t wheel)
+{
+    robot_velocityMode(wheel);
+    robot_motorPowerOn(wheel);
+    robot_motorStart(wheel);
 }

 byte robot_nodeAdress(uint8_t wheel)
@@ -42,17 +52,9 @@
     return nodeAdress[wheel];
 }

-void robot_initNode(uint8_t wheel)
-{
-    robot_velocityMode(wheel);
-    robot_motorPowerOn(wheel);
-    robot_motorStart(wheel);
-    robot_setMotorSpeed(wheel, 0);
-}
-
 void robot_velocityMode(uint8_t wheel)
 {
-    #if DEBUG
+    #if DEBUGMODE
     Serial.println("# Motor velocity mode");
     #endif

@@ -69,7 +71,7 @@

 void robot_motorPowerOn(uint8_t wheel)
 {
-    #if DEBUG
+    #if DEBUGMODE
     Serial.println("# Motor power on");
     #endif

@@ -89,7 +91,7 @@

 void robot_motorStart(uint8_t wheel)
 {
-    #if DEBUG
+    #if DEBUGMODE
     Serial.println("# Motor start");
     #endif

@@ -116,7 +118,7 @@

 void robot_setMotorSpeed(uint8_t wheel, int16_t speed)
 {
-    #if DEBUG
+    #if DEBUGMODE
     Serial.print("# Motor speed: "); Serial.println(speed);
     #endif

@@ -131,7 +133,7 @@

 void robot_quickStop(uint8_t wheel)
 {
-    #if DEBUG
+    #if DEBUGMODE
     Serial.println("# Motor quickstop");
     #endif

@@ -156,7 +158,7 @@
     CAN.send_0();
     delay(10);

-    #if DEBUG
+    #if DEBUGMODE
     for (int i = 0; i < 8; i++)
     {
         Serial.print(data[i], HEX);


pitch*4 is really bad

pitch*4 is really bad

--- nuncha/nuncha.ino
+++ nuncha/nuncha.ino
@@ -135,7 +135,7 @@

    if ( stickUp )
    {
-      pitch = pitch *4;
+      pitch = pitch *2;
    }
    if ( stickDn )
    {


Rename setTime to setDuration for clarity

--- Dremelfuge.ino
+++ Dremelfuge.ino
@@ -24,7 +24,7 @@
 const uint8_t POT_PIN = A5;

-//*** No magic numbers! Using case statements, enum will provide readable, self-documenting code for when switching modes
+//:: ***No magic numbers! Using case statements, enum will provide readable, self-documenting code for when switching modes
 enum class Mode
 {
   SETTING_TIME,
@@ -63,7 +63,7 @@
                                                       //    their values persist even after function ends, as long as the program is still running
                                                       //*** also, static local variables still only have local scope
                                                       //*** perform operations with data of the same type, so as to boost performance by not needing to typecast
-  static unsigned long countdown;                     // the duration the centrifuge should run
+  static unsigned long setDuration;                     // the duration that the centrifuge should run
   static unsigned long spinningStartTime;             // point on the timeline where the countdown starts, i.e. when wpb is pressed the second time
   static uint8_t motorSpeed;

@@ -71,11 +71,11 @@
   {
     case Mode::SETTING_TIME:
     {
-      countdown = map(analogRead(POT_PIN), 0, 1024, 0, 901);
+      setDuration = map(analogRead(POT_PIN), 0, 1024, 0, 901);

       lcd.setCursor(0, 1);
       lcd.print(F("Set time: <"));
-      lcdPrintFormattedSecs(countdown);
+      lcdPrintFormattedSecs(setDuration);
       lcd.print(F(">   "));

       if(wpb.pressed())
@@ -85,10 +85,10 @@

         // Erase <> selector braces
         lcd.setCursor(10, 1);
-        lcdPrintFormattedSecs(countdown);
+        lcdPrintFormattedSecs(setDuration);
         lcd.print(F("    "));

-        countdown*= (long)1000;                       //*** to save space, the ATmega328P chip of UNO uses 2-byte ints, which can hold at max 32 767; operator*(int, int) will still return an int, but in this case an overflowed int;
+        setDuration*= (long)1000;                       //*** to save space, the ATmega328P chip of UNO uses 2-byte ints, which can hold at max 32 767; operator*(int, int) will still return an int, but in this case an overflowed int;
                                                       //*** initSetTime, a long, will just be assigned the overflowed value--it won't force operator*(int, int) to return a long.
                                                       //*** so, by typecasting 1000 or using 1000L, you make the compiler promote analogRead() to a long, so operator*(long, long) will return the expected value, within range of sizeof long
         mode = Mode::SETTING_SPEED;
@@ -134,7 +134,7 @@
         changedUIString = true;               //*** this block becomes unreachable after this, because this true value is remembered
       }

-      unsigned long secondsLeft = (countdown - (millis() - spinningStartTime))/1000;  //*** save RAM AND flash memory by only doing this calculation once per case in loop()
+      unsigned long secondsLeft = (setDuration - (millis() - spinningStartTime))/1000;  //*** save RAM AND flash memory by only doing this calculation once per case in loop()
       analogWrite(MOTOR_PIN, motorSpeed);

       lcd.setCursor(13, 1);


Add a clarifying comment

Add a clarifying comment

--- Dremelfuge.ino
+++ Dremelfuge.ino
@@ -144,7 +144,7 @@
       if(wpb.pressed() || secondsLeft == 0)
       {
         digitalWrite(MOTOR_PIN, LOW);
-        changedUIString = false;
+        changedUIString = false;              // UI string will be changed back!
         mode = Mode::SETTING_TIME;
       }
       break;


Bug fix

Bug fix

--- Arduino/KAKUSender/KAKUSender.ino
+++ Arduino/KAKUSender/KAKUSender.ino
@@ -68,7 +68,7 @@

 // Websocket message handler
 void onData(SocketIOClient client, char *data) {
-  if (strstr(data, "Time:")) {
+  if (strstr(data, "time")) {
     timeUpdate(data + 5);
   }
   else {
@@ -187,9 +187,9 @@
 // The used format is "hours,minutes,seconds,day,month,year"
 void timeUpdate(char *timeString) {
   Serial.print("Update time to: ");
-  Serial.println(timeString);
-
-  char *p = timeString;
+  Serial.println(timeString+28);
+
+  char *p = timeString+28;
   char *str;
   byte second, minute, hour, day, month;
   short year;


change subscription targets to match the Service

--- Charger/WebSocketTest.ino
+++ Charger/WebSocketTest.ino
@@ -43,7 +43,8 @@
                    "<id>Spaces</id>"
                    "<Object>"
                      "<id>EVSpace1</id>"
-                     "<InfoItem name=\"OpenLid\"/>"
+                     "<InfoItem name=\"LidStatus\"/>"
+                     "<InfoItem name=\"Available\"/>"
                    "</Object>"
                  "</Object>"
                "</Object>"


dippins

dippins

--- MTM_MODULE.ino
+++ MTM_MODULE.ino
@@ -1,16 +1,113 @@
 //MTM_MODULE.ino

-int led = 13;
-
-void setup() {
-  // put your setup code here, to run once:
-  pinMode(led, OUTPUT);
+#include <Wire.h>
+#define commandSize 6
+#define returnSize  3
+#define IN1PIN      3
+#define IN2PIN      5
+#define IN3PIN      6
+#define IN4PIN      9
+#define M12SET      0
+#define M1BRAKE     1
+#define M2BRAKE     2
+#define addrSize    3
+#define ADDR1		0
+#define ADDR2		1
+#define ADDR3		2
+//byte dipPins[]={4,7,8,12};
+byte inPins[]={IN1PIN,IN2PIN,IN3PIN,IN4PIN};
+byte addr[]={ADDR1, ADDR2, ADDR3}
+byte inData[commandSize]={};
+byte outData[returnSize]={};
+byte curData[commandSize]={};
+boolean readyData;
+byte motor1Speed=0;
+byte motor2Speed=0;
+char motor1Status;
+char motor2Status;
+void setup(){
+    noInterrupts();
+    //Serial.begin(9600);
+    // for(int i=0;i<dip;i++){
+    //     pinMode(dipPins[i],INPUT);
+    //     digitalWrite(dipPins[i],HIGH);
+    // }
+    for(int i=0;i<4;i++){			//configures inPins
+        pinMode(inPins[i],OUTPUT);
+    }
+    for(int i=0;i<addrSize;i++){	//join I2C bus
+    	Wire.begin(addr[i]);
+    }
+    //addr=address();
+    readyData=false;
+    Wire.onRequest(requestHandler);
+    Wire.onReceive(receiveHandler);
 }
-
-void loop() {
-  // put your main code here, to run repeatedly:
-    digitalWrite(led, HIGH);  // turn the LED on (HIGH is the voltage level)
-    delay(100);               // wait for a second
-    digitalWrite(led, LOW);   // turn the LED off by making the voltage LOW
-    delay(200);               // wait for a second
+byte address(){
+    byte j=0;
+    for(int i=0;i<dip;i++){
+        j=(j<<1)|digitalRead(dipPins[i]);
+    }
+    return j;
 }
+void requestHandler()
+{
+    Wire.write(outData,commandSize);
+}
+void receiveHandler(int numBytes)
+{
+    int i=0;
+    while(Wire.available())
+    {
+        inData[i]=Wire.read();
+        i++;
+    }
+    readyData=true;
+}
+void loop()
+{
+    if(readyData)
+    {
+        for(int i=0;i<6;i++)
+            curData[i]=inData[i];
+        readyData=false;
+    }
+    command();
+}
+void command()
+{
+    switch(curData[0])
+    {
+        case 0:
+            if(curData[1])
+                motorForward(0,curData[2]);
+            else
+                motorBackward(0,curData[2]);
+            if(curData[3])
+                motorForward(1,curData[4]);
+            else
+                motorBackward(1,curData[4]);
+        break;
+        case 1:
+            motorBrake(0);
+        break;
+        case 2:
+            motorBrake(1);
+        break;
+    }
+}
+void motorForward(int motor,byte speed)
+{
+    analogWrite(inPins[motor*2],0);
+    analogWrite(inPins[motor*2+1],speed);
+}
+void motorBackward(int motor,byte speed)
+{
+    analogWrite(inPins[motor*2],speed);
+    analogWrite(inPins[motor*2+1],0);
+}
+void motorBrake(int motor)
+{
+    analogWrite(inPins[motor],255);
+    analogWrite(inPins[motor+1],255);
+}


Cleaned Formatting

Cleaned Formatting

--- Pan_Tilt_laser/Pan_Tilt_laser.ino
+++ Pan_Tilt_laser/Pan_Tilt_laser.ino
@@ -147,7 +147,7 @@

   tempVal *=funcChangeVal;

-return tempVal;
+  return tempVal;

 }


Added random seed

Added random seed

--- Pan_Tilt_laser/Pan_Tilt_laser.ino
+++ Pan_Tilt_laser/Pan_Tilt_laser.ino
@@ -77,6 +77,7 @@

 void loop() {
+  randomSeed(analogRead(0));
   static unsigned long timePassed;
   static int changeVal;
   static int markovShakeState;
@@ -89,6 +90,7 @@

   panTilt.updateAngles();
+
   if(markovShakeState == 2){
     shake();
   }


TA: Remove extra debug

TA: Remove extra debug

--- conductor/conductor.ino
+++ conductor/conductor.ino
@@ -62,8 +62,8 @@
 // Fill the dots one after the other with a color
 void displayMedallion(unsigned char flags, uint32_t color) {

-    Serial.print("FLAGS: ");
-    Serial.println(flags);
+//    Serial.print("FLAGS: ");
+//    Serial.println(flags);

     checkPixelOn(flags, 0, PIXEL_0, color);
     checkPixelOn(flags, 1, PIXEL_1, color);


Removed unused imports

Removed unused imports

--- TeensyQuad.ino
+++ TeensyQuad.ino
@@ -1,8 +1,6 @@
 #include <Wire.h>
 //#include <EEPROM.h>

-//#include "TeensyQuad.h"
-//#include "PID.h"
 #include "Config.h"

 #include <L3G.h>


Replace the digitalRead with interrupt-based triggers.

--- code/oakpowerboard/oakpowerboard.ino
+++ code/oakpowerboard/oakpowerboard.ino
@@ -11,6 +11,13 @@

 #define PULSES_PER_KWH 375
 #define WH_PER_PULSE (1000.0F / PULSES_PER_KWH)
+
+#define BTN_1 9
+#define BTN_2 8
+#define BTN_3 7
+#define BTN_4 6
+#define PULSE_PIN 5
+#define DEBUG_LED 10

 int pulse_count_current_kwh;

@@ -46,6 +53,32 @@

 bool isConnected = false;

+bool b1_pressed = false;
+bool b2_pressed = false;
+bool b3_pressed = false;
+bool b4_pressed = false;
+bool pulse_triggered = false;
+
+void toggle_b1() {
+  b1_pressed = true;
+}
+
+void toggle_b2() {
+  b2_pressed = true;
+}
+
+void toggle_b3() {
+  b3_pressed = true;
+}
+
+void toggle_b4() {
+  b4_pressed = true;
+}
+
+void trigger_pulse() {
+  pulse_triggered = true;
+}
+
 void setup() {
   ui.setTargetFPS(30);
   ui.setActiveSymbole(activeSymbole);
@@ -73,20 +106,43 @@
   // put your setup code here, to run once:
   // initialize the digital pin as an output.
   pinMode(1, OUTPUT); //LED on Model A
-  pinMode(6, INPUT);//Button pin
+  attachInterrupt(digitalPinToInterrupt(PULSE_PIN), trigger_pulse, FALLING);
+  pinMode(DEBUG_LED, OUTPUT);//Debugging LED
+  attachInterrupt(digitalPinToInterrupt(BTN_1), toggle_b1, FALLING);
+  attachInterrupt(digitalPinToInterrupt(BTN_2), toggle_b2, FALLING);
+  attachInterrupt(digitalPinToInterrupt(BTN_3), toggle_b3, FALLING);
+  attachInterrupt(digitalPinToInterrupt(BTN_4), toggle_b4, FALLING);
 }

 bool btn_state = false;

 void loop() {
   int remainingTimeBudget = ui.update();
+  yield();
+  long deadline = millis() + remainingTimeBudget;
   if (remainingTimeBudget > 0) {
-    // You can do some work here
-    // Don't do stuff if you are below your
-    // time budget.
-    bool curr_btn_state = (digitalRead(6) == LOW) ? false : true;
-    if(curr_btn_state != btn_state) {
-      if(curr_btn_state == false) {//PULSE FINISHED
+
+    if(b1_pressed == true) {
+      ui.nextFrame();
+      b1_pressed = false;
+    }
+
+    if(b2_pressed == true) {
+      ui.previousFrame();
+      b2_pressed = false;
+    }
+
+    if(b3_pressed == true) {
+      //handle b3
+      b3_pressed = false;
+    }
+
+    if(b4_pressed = true) {
+      //handle b4
+      b4_pressed = false;
+    }
+
+    if(pulse_triggered == true) {
         pulse_count_current_kwh++;
         if(pulse_count_current_kwh == PULSES_PER_KWH) {
           consumption_total++;
@@ -96,11 +152,9 @@
         dtostrf(consumption_total + ((((float)pulse_count_current_kwh) * WH_PER_PULSE) / 1000.0F), 6, 2, consumption_total_str);
         dtostrf(consumption_current, 4, 0, consumption_current_str);
         time_since_last_pulse = millis();
-      }
-      digitalWrite(1, curr_btn_state ? HIGH : LOW);
-      btn_state = curr_btn_state;
-    }
-    //if(millis() < deadline)
+    }
+
+    digitalWrite(DEBUG_LED, millis() < deadline ? HIGH : LOW);
     //  Particle.delay(millis() - deadline);
   }
 }


Fix typo in enum

Fix typo in enum

--- ED_BMSdiag/ED_BMSdiag.ino
+++ ED_BMSdiag/ED_BMSdiag.ino
@@ -308,13 +308,13 @@
   // If the EEPROM hasn't been programmed yet, program it
   if (force_write || EEPROM.read(EE_Signature) != kMagicSignature) {
     Serial.println("Setting factory defaults");
-    EEPROM.update(EE_IntialDumpAll, 1);
+    EEPROM.update(EE_InitialDumpAll, 1);
     EEPROM.update(EE_logging, 0);
     EEPROM.update(EE_logInterval, 30);
     EEPROM.update(EE_Experimental, 0);
     EEPROM.update(EE_Signature, kMagicSignature);
   }
-  config->initialDump = (EEPROM.read(EE_IntialDumpAll) > 0);
+  config->initialDump = (EEPROM.read(EE_InitialDumpAll) > 0);
   config->logging = (EEPROM.read(EE_logging) > 0);
   config->timer = EEPROM.read(EE_logInterval);
   config->experimental = (EEPROM.read(EE_Experimental) > 0);