Started on other modes

Started on other modes

Set up a mode to rotate whatever pattern in set in the mode select.
Moved a few things around. Removed some Serial prints.

--- InfinityGoggles.ino
+++ InfinityGoggles.ino
@@ -10,12 +10,10 @@
 // Eye color varies with orientation of the magnetometer
 #include <Wire.h>
 #include <SPI.h>
-
 #include <Adafruit_Sensor.h>
 #include <Adafruit_LSM9DS0.h>
 #include <Adafruit_Simple_AHRS.h>
 #include <FastLED.h>
-

 #define DATAPIN_LEFT    0
 #define CLOCKPIN_LEFT   1
@@ -44,7 +42,7 @@
 long gestureStart = 0;
 long gestureHoldTime = 3000;

-int modeNumber = 0;
+int modeNumber = 4;

 bool pendulum = true;
 bool antiGravity = true;  // The pendulum will anti-gravitate to the top.
@@ -55,6 +53,21 @@
 // Pi for calculations - not the raspberry type
 const float Pi = 3.14159;

+void setup(void)
+{
+  FastLED.addLeds<APA102, DATAPIN_LEFT, CLOCKPIN_LEFT>(leftLense, NUM_LEDS);
+  FastLED.addLeds<APA102, DATAPIN_RIGHT, CLOCKPIN_RIGHT>(rightLense, NUM_LEDS);
+
+  // Try to initialise
+  if (!lsm.begin())
+  {
+    while (1);
+  }
+  setupSensor();
+  resetModes();
+  setDisplayMode();
+}
+
 void setupSensor()
 {
   // 1.) Set the accelerometer range
@@ -63,33 +76,21 @@
   // 2.) Set the magnetometer sensitivity
   lsm.setupMag(lsm.LSM9DS0_MAGGAIN_2GAUSS); //2GAUSS,4GAUSS,8GAUSS,12GAUSS

-  // 3.) Setup the gyroscope
-  lsm.setupGyro(lsm.LSM9DS0_GYROSCALE_245DPS); // 245DPS,500DPS,2000DPS
-}
-
-void setup(void)
-{
-  FastLED.addLeds<APA102, DATAPIN_LEFT, CLOCKPIN_LEFT>(leftLense, NUM_LEDS);
-  FastLED.addLeds<APA102, DATAPIN_RIGHT, CLOCKPIN_RIGHT>(rightLense, NUM_LEDS);
-
-  // Try to initialise
-  if (!lsm.begin())
-  {
-    while (1);
-  }
-  setupSensor();
-  resetModes();
-}
-
-int test = 0;
-// main processing loop
+  // 3.) Setup the gyroscope. Options are: 245DPS,500DPS,2000DPS
+  lsm.setupGyro(lsm.LSM9DS0_GYROSCALE_245DPS);
+}
+
 void loop(void)
 {
   // Read the magnetometer and determine the compass heading:
   lsm.getEvent(&accel, &mag, &gyro, &temp);
+
+//  Serial.println(accel.acceleration.x);
+
   // Check for mode change commands
   checkForGestures(accel);
-
+
+  // Get a color based off of direction
   CRGB magHeadingBasedColor = convertHeadingToColor(fabs(round(mag.magnetic.z * 100)));

   if(pendulum == true)
@@ -98,16 +99,11 @@
   }
   else
   {
-    staticMode(magHeadingBasedColor);
-  }
-
-}
-
-void staticMode(CRGB color)
-{
-  fill_solid(&(rightLense[0]), NUM_LEDS, color);
-  fill_solid(&(leftLense[0]), NUM_LEDS, color);
-  FastLED.show();
+    shift(leftLense, NUM_LEDS, false);
+    shift(rightLense, NUM_LEDS, false);
+    FastLED.show();
+  }
+
 }

 void pendulumMode(CRGB color)
@@ -173,6 +169,7 @@
     {
       leftLense[leftIndex] = CRGB(0, 0, 0);
       rightLense[rightIndex] = CRGB(0, 0, 0);
+      FastLED.show();
     }
   }
   FastLED.show();
@@ -210,7 +207,7 @@
       activateGestureModeSelect();
     }
   }
-  else     // no nods in progress
+  else
   {
     gestureStart = millis(); // reset timer
   }
@@ -232,19 +229,16 @@
 void cycleModeForward()
 {
   modeNumber++;
-  Serial.print("Forward to mode : ");
-  Serial.println(modeNumber);
-  setDisplayMode();
 }

 void cycleModeBack()
 {
   modeNumber--;
-  Serial.print("Back to mode : ");
-  Serial.println(modeNumber);
-  setDisplayMode();
-}
-
+}
+
+// Will update global variables on modeNumber change
+// Sets appropriate global variables, and sets any
+// static patterns that will be animated sequentially in the loop
 void setDisplayMode()
 {
   int numberOfModes = 4;
@@ -277,9 +271,9 @@
       antiGravity = true;
       mirroredEyes = true;
       break;
-    case 4: //Some preset pattern? How do?
-      Serial.println("Setting pendulum to false right fucking now!");
+    case 4:
       pendulum = false;
+      lowKeyRainbow();
       break;
     default:
       Serial.println("Oops, got into the default :()");
@@ -313,11 +307,13 @@
     if(accel.acceleration.z > 0.70)
     {
       cycleModeForward();
+      setDisplayMode();
       break;
     }
     if(accel.acceleration.z < -0.70)
     {
       cycleModeBack();
+      setDisplayMode();
       break;
     }
   }
@@ -365,7 +361,36 @@
     }
   }
 }
-
-
-
-
+/********************************************************************
+ * These are static patterns that rely on a mthod like shift to
+ * move them around one step at a time. As to not busy the
+ * arduino from checking for sensor input.
+ *******************************************************************/
+//Check out the memmove function to maybe do it more quickly
+//Also, if we dont want to pass the size, could technically do sizeof(strip)/sizeof(CRGB)
+void shift(CRGB strip[], int stripLength, bool changeDirection) {
+  CRGB wrapAroundPixel;
+  if (changeDirection == true) {
+    wrapAroundPixel = strip[stripLength - 1];
+    for (int i = stripLength - 1; i > 0; i--) {
+      strip[i] = strip[i - 1];
+    }
+    strip[0] = wrapAroundPixel;
+  } else {
+    wrapAroundPixel = strip[0];
+    for (int i = 0; i < stripLength; i++) {
+      strip[i] = strip[i + 1];
+    }
+    strip[stripLength - 1] = wrapAroundPixel;
+  }
+}
+
+void lowKeyRainbow()
+{
+  for(int i=0;i<NUM_LEDS;i++) {
+    leftLense[i] = CHSV(12.75*i, 255, 60);
+    rightLense[i] = CHSV(12.75*i, 255, 60);
+  }
+  FastLED.show();
+}
+


-Temperature is now returned with 3 digits precision.

--- webservertask.ino
+++ webservertask.ino
@@ -291,7 +291,7 @@
       {
         for ( uint8_t sensorNumber = 0; sensorNumber < numberOfFoundSensors; sensorNumber++ )
         {
-          charCount += snprintf( content + charCount, sizeof( content ) - charCount, "%s,%.1f\n", sensor[sensorNumber].name, sensor[sensorNumber].temp / 16 );
+          charCount += snprintf( content + charCount, sizeof( content ) - charCount, "%s,%.3f\n", sensor[sensorNumber].name, sensor[sensorNumber].temp / 16 );
         }
       }
     }


identation rework Added Vcc printout

identation rework
Added Vcc printout

--- ard-dht/ard-dht.ino
+++ ard-dht/ard-dht.ino
@@ -1,12 +1,12 @@
 /*
- * https://github.com/r2d2/ard-stuff
- * Temperature and humidity sensor / Oregon sender
- * Uses a DHT series temperature and humidity sensor and an RF transmitter
- * Requires the following Arduino libraries to be installed in the libraries directory:
- * - DHT from https://github.com/markruys/arduino-DHT
- * - LowPower lib from https://github.com/rocketscream/Low-Power
- * - oregon lib from https://github.com/r2d2/ard-stuff/ard-libraries
- */
+   https://github.com/r2d2/ard-stuff
+   Temperature and humidity sensor / Oregon sender
+   Uses a DHT series temperature and humidity sensor and an RF transmitter
+   Requires the following Arduino libraries to be installed in the libraries directory:
+   - DHT from https://github.com/markruys/arduino-DHT
+   - LowPower lib from https://github.com/rocketscream/Low-Power
+   - oregon lib from https://github.com/r2d2/ard-stuff/ard-libraries
+*/

 #include <DHT.h>
 #include <LowPower.h>
@@ -22,15 +22,15 @@

 void setup()
 {
-  byte oregon_type[2] = {0x1A,0x2D};
+  byte oregon_type[2] = {0x1A, 0x2D};
   byte oregon_channel = 0x10; // 10 : 1, 20 : 2... -> 70 : 7
-  byte oregon_id = oregon_id;
-
+  byte oregon_id = oregon_id;
+
   sensor.setup(sensorPin);
-  oregon.setup(oregon_type,oregon_channel,0xBB);
-
-  pinMode(ledPin, OUTPUT);
-
+  oregon.setup(oregon_type, oregon_channel, 0xBB);
+
+  pinMode(ledPin, OUTPUT);
+
   Serial.begin(9600);
   Serial.println("Temperature and Humidity Sender");
 }
@@ -38,24 +38,24 @@
 long readVcc() {
   // Read 1.1V reference against AVcc
   // set the reference to Vcc and the measurement to the internal 1.1V reference
-  #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
-    ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
-  #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
-    ADMUX = _BV(MUX5) | _BV(MUX0);
-  #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
-    ADMUX = _BV(MUX3) | _BV(MUX2);
-  #else
-    ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
-  #endif
+#if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
+  ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
+#elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
+  ADMUX = _BV(MUX5) | _BV(MUX0);
+#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
+  ADMUX = _BV(MUX3) | _BV(MUX2);
+#else
+  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
+#endif

   delay(2); // Wait for Vref to settle
   ADCSRA |= _BV(ADSC); // Start conversion
-  while (bit_is_set(ADCSRA,ADSC)); // measuring
+  while (bit_is_set(ADCSRA, ADSC)); // measuring

-  uint8_t low  = ADCL; // must read ADCL first - it then locks ADCH
+  uint8_t low  = ADCL; // must read ADCL first - it then locks ADCH
   uint8_t high = ADCH; // unlocks both

-  long result = (high<<8) | low;
+  long result = (high << 8) | low;

   result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
   return result; // Vcc in millivolts
@@ -65,7 +65,7 @@
 void loop()
 {
   byte index;
-
+  int Vcc = readVcc();
   double t = sensor.getTemperature();
   double h = sensor.getHumidity();

@@ -74,11 +74,13 @@
   Serial.print("C ");
   Serial.print(h);
   Serial.println("%");
-
-  oregon.send(t, h, readVcc()>1200?1:0); // send the sensor readings
+  Serial.print(Vcc);
+  Serial.println("mV");
+
+  oregon.send(t, h, Vcc > 1200 * 2 ? 1 : 0); // send the sensor readings

   // Wait for one minute
-  for( index = 0 ; index < 60/8 ; index++ )
+  for ( index = 0 ; index < 60 / 8 ; index++ )
   {
     // Sleep for 8 s with ADC module and BOD module off
     LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
@@ -90,7 +92,8 @@
 void blinkLed()
 {
   digitalWrite(ledPin, HIGH);
-  delay(30);
+  delay(30);
   digitalWrite(ledPin, LOW);
 }

+


Updated arduino code

Updated arduino code

--- arduino/arduino.ino
+++ arduino/arduino.ino
@@ -44,9 +44,9 @@
   send_message.concat(message);

   // Add and calculate checksum
-  byte byteBuf[send_length+5];
+  byte byteBuf[send_length+4];
   send_message.getBytes(byteBuf, send_length+4);
-  byte checksum = CRC8(byteBuf, send_length+4);
+  byte checksum = CRC8(byteBuf, send_length+3);
   send_message.concat(char(checksum));

   char charBuf[send_length+5];


Enable sntp code again.

Enable sntp code again.

--- Time.ino
+++ Time.ino
@@ -47,15 +47,13 @@
 // which in turn has roots in Arduino UdpNTPClient tutorial.
 time_t getNtpTime(void) {

-  return 1;
-
   Adafruit_CC3000_Client client;
   Adafruit_CC3000* cc3000 = getCC3000();

   uint8_t       buf[48];
   unsigned long ip, startTime, t = 0L;

-  Serial.print(F("time"));
+  Serial.print(F("sntp "));

   // Hostname to IP lookup; use NTP pool (rotates through servers)
   if(cc3000->getHostByName(NTP_SERVER, &ip)) {


arduino client memory optimization

arduino client memory optimization

--- src/arduino_iot_cli/arduino_iot_cli.ino
+++ src/arduino_iot_cli/arduino_iot_cli.ino
@@ -10,7 +10,6 @@
 #include <VirtualWire.h>

 const byte receive_pin = 4;
-
 byte mac[] = {  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
 IPAddress myIp(192, 168, 1, 150);
 IPAddress serverIp(192, 168, 1, 134);
@@ -21,12 +20,11 @@
 CBC<AES256> cbcaes256;
 SHA256 sha256;
 char packet[192];
-byte iv[16];
 byte padded[48];
 long counter = 0;
-char tmp1[10] = {0,0,0,0,0,0,0,0,0,0};
+char tmp1[10];
 long tmp1c = 0;
-char tmp2[10] = {0,0,0,0,0,0,0,0,0,0};
+char tmp2[10];
 long tmp2c = 0;
 long c = 0;

@@ -43,6 +41,8 @@
   Udp.begin(2345);

   Serial.begin(9600);
+  tmp1[0] = 0;
+  tmp2[0] = 0;

   //uncomment to reset EEPROM counter
   //EEPROM.write(0, 0);  EEPROM.write(1, 0);  EEPROM.write(2, 0);  EEPROM.write(3, 0);
@@ -52,7 +52,7 @@
 void loop() {
     c++;
     radioReceive();
-    if (c%1000 == 0 && (tmp1[0] != 0 || tmp2[0] != 0)) {
+    if (c%3000 == 0 && (tmp1[0] != 0 || tmp2[0] != 0)) {
         if (tmp1[0] !=0 && tmp2[0] == 0)
         {
             sprintf((char*)padded, "{\"values\":{\"t1\":%s}}", tmp1);
@@ -69,29 +69,24 @@

         //encrypt and sign
         byte srclen = strlen((char*)padded);
-        Serial.println(srclen);
         byte padnum = 16 - (srclen % 16);
-        //memcpy(padded, payloadStr, strlen(payloadStr));
         memset(padded+srclen, padnum, padnum);
-
         int paddedLen = srclen + padnum;
-        Serial.println(paddedLen);

-        memset(iv, 0, 16);
-        iv[0] = counter & 0xFF;
-        iv[1] = (counter & 0xFF00) >> 8;
-        iv[3] = (counter & 0xFF0000) >> 16;
-        iv[4] = (counter & 0xFF000000) >> 24;
+        memset(packet+56, 0, 16);
+        packet[56] = counter & 0xFF;
+        packet[57] = (counter & 0xFF00) >> 8;
+        packet[58] = (counter & 0xFF0000) >> 16;
+        packet[59] = (counter & 0xFF000000) >> 24;
         cbcaes256.clear();
         cbcaes256.setKey(key, 32);
-        cbcaes256.setIV(iv, 16);
+        cbcaes256.setIV((uint8_t *)(packet+56), 16);
         memcpy(packet, "IOT\0", 4);
         packet[36] = 1;
         packet[37] = 1;
         packet[38] = 0;
         packet[39] = 0;
         memcpy(packet+40, deviceId, 16);
-        memcpy(packet+56, iv, 16);
         cbcaes256.encrypt(((uint8_t*)packet)+72, (uint8_t*)padded, paddedLen);
         int len = 72+paddedLen;
         sha256.resetHMAC(key, 32);


Update IMU6050.ino

Update IMU6050.ino

--- code/IMU6050.ino
+++ code/IMU6050.ino
@@ -90,12 +90,18 @@
 void printMPUValues(void)
 {
   Serial.print(gyroRate[XAXIS]); Serial.print('\t');
+  myFile.print(gyroRate[XAXIS]); myFile.print('\t');
   Serial.print(gyroRate[YAXIS]);Serial.print('\t');
+  myFile.print(gyroRate[YAXIS]);Serial.print('\t');
   Serial.print(gyroRate[ZAXIS]); Serial.print('\t');
+  myFile.print(gyroRate[ZAXIS]); Serial.print('\t');

   Serial.print(accelRate[XAXIS]); Serial.print('\t');
+myFile.print(accelRate[XAXIS]); myFile.print('\t');
   Serial.print(accelRate[YAXIS]);Serial.print('\t');
+myFile.print(accelRate[YAXIS]);myFile.print('\t');
   Serial.print(accelRate[ZAXIS]); Serial.print('\t');
+myFile.print(accelRate[ZAXIS]); myFile.print('\t');

   Serial.println((float)temperature / TEMP_DIVIDING_FACTOR + TEMP_OFFSET);Serial.print('\n');
 }


Added filtering feature. The sampling rate of the system is so slow, that it is already filtering the sensor data in. Due to this factor, the filter we implemented doesn't show, unless we go super high, in which case we see a very small effect.

--- ServerSketch/ServerSketch.ino
+++ ServerSketch/ServerSketch.ino
@@ -51,6 +51,8 @@
 #define ANALOG_IN_MAX_VALUE 1024 //4096

 #define DIGITAL_VOLTAGE_THRESHOLD  0.5
+
+#define TOTAL_NUM_OF_PAST_VALUES  10 // Filtering buffer

 //char** g_caaPinNames[20][PIN_LABEL_SIZE];

@@ -68,6 +70,7 @@
   float timer_value;
   int damping;
   boolean connections[TOTAL_NUM_OF_PINS];
+  float past_values[TOTAL_NUM_OF_PAST_VALUES];
 }
 Pin;

@@ -607,6 +610,10 @@
     g_aPins[i].is_inverted = false;
     g_aPins[i].is_visible = true;
     g_aPins[i].value = 0.0;
+
+    for(int j=0; j<TOTAL_NUM_OF_PAST_VALUES; j++)
+      g_aPins[i].past_values[j] = 0.0;
+
     g_aPins[i].is_timer_on = false;
     g_aPins[i].timer_value = 0.0;
     g_aPins[i].damping = 0;
@@ -677,16 +684,10 @@
   {
     if( !g_aPins[i].is_input ) // Process output pins
     {
-      if( g_aPins[i].is_analog ) // Process analog pins
-      {
+      if( g_aPins[i].is_analog ) // Process analog pins
         analogWrite(i, getTotalPinValue(i)*ANALOG_OUT_MAX_VALUE );
-        //analogWrite(i, getTotalPinAnalogValue(i)*ANALOG_OUT_MAX_VALUE );
-      }
-      else // Process digital pins
-      {
+      else // Process digital pins
         digitalWrite(i, getTotalPinValue(i) );
-        //digitalWrite(i, getTotalPinDigitalValue(i) );
-      }
     }
   }
 }
@@ -707,8 +708,9 @@
       if(g_aPins[_iOutPinNum].connections[i])
       {
         iConnCount++;
-        //fPinValSum += g_aPins[i].value;
-        fPinValSum += (g_aPins[i].value - g_aPins[i].input_min)/(g_aPins[i].input_max - g_aPins[i].input_min);  // Adding the Max/Min formula
+
+        //fPinValSum += (g_aPins[i].value - g_aPins[i].input_min)/(g_aPins[i].input_max - g_aPins[i].input_min);  // Adding the Max/Min formula
+        fPinValSum += getScaledPinValue(i);  // Adding the Max/Min formula

        if( !g_aPins[_iOutPinNum].is_analog )
        {
@@ -717,14 +719,6 @@
          else
            fPinValSum = 0.0;
        }
-        /*
-        Serial.print(i); Serial.print(" --> "); Serial.println(_iOutPinNum);
-        Serial.print(" Min: "); Serial.println(g_aPins[i].input_min);
-        Serial.print(" Max: "); Serial.println(g_aPins[i].input_max);
-        Serial.print(" Value: "); Serial.println(g_aPins[i].value);
-        Serial.print(" Scales value: "); Serial.println(g_aPins[i].value - g_aPins[i].input_min)/(g_aPins[i].input_max - g_aPins[i].input_min);
-        Serial.print(" -fPinValSum: "); Serial.println(fPinValSum);
-        */
       }
     }
   }
@@ -740,6 +734,34 @@
   //Serial.print("Analog Pin #: "); Serial.print(_iOutPinNum); Serial.print(" Total Value: "); Serial.println(fPinValSum);

   return fPinValSum;
+}
+
+float getScaledPinValue(int _iInPinNum)
+{
+  //return (g_aPins[_iInPinNum].value - g_aPins[_iInPinNum].input_min)/(g_aPins[_iInPinNum].input_max - g_aPins[_iInPinNum].input_min);
+  return (getFilteredPinValue(_iInPinNum) - g_aPins[_iInPinNum].input_min)/(g_aPins[_iInPinNum].input_max - g_aPins[_iInPinNum].input_min);
+}
+
+float getFilteredPinValue(int _iInPinNum)
+{
+  // Update tap value
+  float fFilterTab = 1.0/(g_aPins[_iInPinNum].damping+1); // The sampling rate is so slow this filter can see it.
+  Serial.print("fFilterTab: "); Serial.println(fFilterTab);
+  // Shift previous values
+  for(int i=0; i<TOTAL_NUM_OF_PAST_VALUES-1; i++)
+  {
+      g_aPins[_iInPinNum].past_values[i+1] = g_aPins[_iInPinNum].past_values[i];
+  }
+
+  // Add new data
+  g_aPins[_iInPinNum].past_values[0] = g_aPins[_iInPinNum].value;
+    Serial.print("value: "); Serial.println(g_aPins[_iInPinNum].value);
+  // Multiply and accumulate
+  float fMultAndAccum = 0.0;
+  for(int i=0; i<=g_aPins[_iInPinNum].damping; i++)
+      fMultAndAccum += fFilterTab*g_aPins[_iInPinNum].past_values[i];
+  Serial.print("MultAndAccum: "); Serial.println(fMultAndAccum);
+  return fMultAndAccum;
 }

 float getTotalPinAnalogValue(int _iPinNum)
@@ -1072,9 +1094,12 @@
 //        g_aPins[i].timer_value = poTimerValue->valuefloat;

       aJsonObject *poDamping = aJson.getObjectItem(poPinVals, "damping");
-      if (poDamping)
+      if (poDamping){
         g_aPins[i].damping = poDamping->valueint;
-
+        Serial.print("poDamping->valueint: "); Serial.println(poDamping->valueint);
+        Serial.print("poDamping->valuefloat: "); Serial.println(poDamping->valuefloat);
+       // Serial.print("poDamping->valuestring: "); Serial.println(poDamping->valuestring);
+      }
     }
   }
 }


long comment

long comment

--- vibrate_alarm_clock.ino
+++ vibrate_alarm_clock.ino
@@ -429,7 +429,7 @@

   int batteryRange = MAX_BATTERY_MILLIVOLT - MIN_BATTERY_MILLIVOLT;

-  //Cast to long as Arduino int is only 16 bits wide. Not enough to
+  //Cast to long as Arduino int is only 16 bits wide. Not enough to hold this result
   long numerator =  ((long) ((batteryMilliVolt - MIN_BATTERY_MILLIVOLT))) * 100;
   int batteryPercent = numerator / batteryRange;


Feinschliff

Feinschliff

--- plant-monitor/plant-monitor.ino
+++ plant-monitor/plant-monitor.ino
@@ -22,10 +22,11 @@
 // moisture sensor
 const int soildThresholdLow = 500;
 const int soildThresholdHigh = 3500;
-const int soilPower = D4;
-const int soilSensor1 = A0;
-const int soilSensor2 = A1;
-const int soilSensor3 = A2;
+struct SoilSensor {
+  int sensor;
+  int power;
+};
+SoilSensor soilSensors[3] = {{ A0, D4 }, { A1, D5 }, { A2, D6 }};
 int soil1 = 2048, soil2 = 2048, soil3 = 2048;

 // SparkFun phant library
@@ -40,16 +41,14 @@
 elapsedMillis lastMeasurement;
 elapsedMillis lastPost;

-void setup()
-{
+void setup() {
+  Serial.begin(9600);
+
   pinMode(led, OUTPUT);
-  pinMode(soilSensor1, INPUT);
-  pinMode(soilSensor2, INPUT);
-  pinMode(soilSensor3, INPUT);
-  pinMode(soilPower, OUTPUT);
-  digitalWrite(soilPower, LOW);
-
-  Serial.begin(9600);
+  for (unsigned int i = 0; i < sizeof(soilSensors); i++) {
+    pinMode(soilSensors[i].sensor, INPUT);
+    pinMode(soilSensors[i].power, OUTPUT);
+  }

   if (!bme.begin()) {
     Serial.println("Could not find a valid BME280 sensor, check wiring!");
@@ -70,11 +69,11 @@
     if (lastMeasurement > MEASUREMENT_RATE) {
       int bmeSensorStatus = readBMESensor();
       delay(200);
-      int soil1SensorStatus = readSoilSensor(soilSensor1, soil1);
+      int soil1SensorStatus = readSoilSensor(soilSensors[0].sensor, soilSensors[0].power, soil1);
       delay(200);
-      int soil2SensorStatus = readSoilSensor(soilSensor2, soil2);
+      int soil2SensorStatus = readSoilSensor(soilSensors[1].sensor, soilSensors[1].power, soil2);
       delay(200);
-      int soil3SensorStatus = readSoilSensor(soilSensor3, soil3);
+      int soil3SensorStatus = readSoilSensor(soilSensors[2].sensor, soilSensors[2].power, soil3);

       // calc overall sensor status
       currentSensorStatus = (bmeSensorStatus << 6) + (soil1SensorStatus << 4) +
@@ -103,15 +102,15 @@
     lastSensorStatus = currentSensorStatus;
 }

-int postToParticle() {
+// post to Particle cloud
+void postToParticle() {
   sprintf(publishString,"{\"status\": %d, \"temp\": %0.2f, \"pressure\": %0.2f, \"humidity\": %0.2f, \"soil1\": %u, \"soil2\": %u, \"soil3\": %u}",
     currentSensorStatus, temperature, pressure, humidity, soil1, soil2, soil3);
   Particle.publish("sensor",publishString);
-  return 1;
 }

+// post to SparkFun phant cloud storage
 int postToPhant() {
-  // add variables
   phant.add("status", currentSensorStatus);
   phant.add("temp", temperature, 2);
   phant.add("pressure", pressure, 2);
@@ -147,12 +146,12 @@
 }

 // read soil sensor data
-int readSoilSensor(int soilSensor, int &soilValue) {
+int readSoilSensor(const int soilSensor, const int soilSensorPower, int &soilValue) {
     digitalWrite(led, HIGH);
-    digitalWrite(soilPower, HIGH); //turn sensor power on
+    digitalWrite(soilSensorPower, HIGH); //turn sensor power on
     delay(10); // give some time to settle
     soilValue = analogRead(soilSensor);
-    digitalWrite(soilPower, LOW); //turn sensor power off
+    digitalWrite(soilSensorPower, LOW); //turn sensor power off
     delay(190);
     digitalWrite(led, LOW);


implement alerts for soil and temperature

--- plant-monitor/plant-monitor.ino
+++ plant-monitor/plant-monitor.ino
@@ -11,6 +11,7 @@
 // main status
 int lastSensorStatus = 0, currentSensorStatus = 0;
 char publishString[128];
+char eventString[10];

 // BME280 sensor
 Adafruit_BME280 bme;
@@ -18,10 +19,11 @@
 double pressure = 0;
 double altitude = 0;
 double humidity = 0;
+const double TEMPERATURE_THRESHOLD_LOW = 0; // used for alerts if temp is blow this value

 // moisture sensor
-const int soildThresholdLow = 500;
-const int soildThresholdHigh = 3500;
+const int SOIL_THRESHOLD_LOW = 500;
+const int SOIL_THRESHOLD_HIGH = 3500;
 struct SoilSensor {
   int sensor;
   int power;
@@ -37,12 +39,16 @@

 // interval counters for measurement and post
 const unsigned int MEASUREMENT_RATE = 60000; // read sensor data every 60 sec
-const unsigned int POST_RATE = 15 * 60000; // post data every 15 minutes
+const unsigned int POST_RATE = 60 * 60000; // post data every 60 minutes
 elapsedMillis lastMeasurement;
 elapsedMillis lastPost;

+const unsigned int PUBLISHEVENT_TIME_HOUR = 15; // send events ~ 3pm
+boolean publishEvents = true;
+
 void setup() {
   Serial.begin(9600);
+  Time.zone(1);

   pinMode(led, OUTPUT);
   for (unsigned int i = 0; i < sizeof(soilSensors); i++) {
@@ -83,11 +89,21 @@
           lastMeasurement = 0;
           postToParticle();
           dumpSerial();
+
+          // send events to particle cloud used to trigger IFTTT push notification
+          if (Time.hour() == PUBLISHEVENT_TIME_HOUR && publishEvents == true) {
+            postSoilEventToParticle();
+            publishEvents = false;
+          }
+          if (Time.hour() > PUBLISHEVENT_TIME_HOUR) {
+            publishEvents = true;
+          }
       }
     }

     // update cloud on timer or sensor data changes
     if (lastPost > POST_RATE || currentSensorStatus != lastSensorStatus) {
+      postBMEEventToParticle();
       while (postToPhant() <= 0) { // publish to phant
         Serial.println("Phant post failed. Trying again.");
 				// Delay 1s, so we don't flood the server. Little delay's allow the Photon time
@@ -109,6 +125,26 @@
   Particle.publish("sensor",publishString);
 }

+// post to Particle cloud
+void postSoilEventToParticle() {
+  if (soil1 < SOIL_THRESHOLD_LOW) {
+    Particle.publish("plant_alert", "1");
+  }
+  if (soil2 < SOIL_THRESHOLD_LOW) {
+    Particle.publish("plant_alert", "2");
+  }
+  if (soil3 < SOIL_THRESHOLD_LOW) {
+    Particle.publish("plant_alert", "3");
+  }
+}
+
+void postBMEEventToParticle() {
+  if (temperature < TEMPERATURE_THRESHOLD_LOW) {
+    sprintf(eventString, "%0.2f °C", temperature);
+    Particle.publish("temp_alert", eventString);
+  }
+}
+
 // post to SparkFun phant cloud storage
 int postToPhant() {
   phant.add("status", currentSensorStatus);
@@ -155,9 +191,9 @@
     delay(190);
     digitalWrite(led, LOW);

-    if (soilValue < soildThresholdLow) {
+    if (soilValue < SOIL_THRESHOLD_LOW) {
       return 1; // indicate soil is to low
-    } else if (soilValue > soildThresholdHigh) {
+    } else if (soilValue > SOIL_THRESHOLD_HIGH) {
       return 2; // indicate soil is to high
     } else {
       return 0; // indicate normal reading


delete some empty space

delete some empty space


Changes timer library on the Arduino

Changes timer library on the Arduino


saying 'robot' is not longer required

saying 'robot' is not longer required

--- arduino/VPD/VPD.ino
+++ arduino/VPD/VPD.ino
@@ -11,7 +11,7 @@
 EasyVR easyvr(easy_vr_ser);

 int8_t bits = 4;
-int8_t set = 0;
+int8_t set = 2;
 int8_t group = 0;
 uint32_t mask = 0;
 uint8_t train = 0;


motor_1.ino is now accepting data over I2C

--- arduino/motor_1.ino
+++ arduino/motor_1.ino
@@ -1,13 +1,11 @@
 #include <Wire.h>
-double potcurval;    // variable to read the value from the analog pin
-int angel; //Integer value of angle
+volatile double potcurval;    // variable to read the value from the analog pin
+volatile int angel; //Integer value of angle
  double angle =0;
-
- double curangle,kP=30.00,kI=0,kD=0,Last=0;
- double P=0,I=0,D=0,Drive,Error=0,Integral=0;
+volatile int x;
+ volatile double curangle,kP=30.00,kI=0,kD=0,Last=0;
+ volatile double P=0,I=0,D=0,Drive,Error=0,Integral=0;

- String inputString = "";         // a string to hold incoming data
-boolean stringComplete = false;  // whether the string is complete

  void backward()
  {
@@ -32,7 +30,6 @@
   Serial.begin(9600);
   pinMode(11,OUTPUT);
   pinMode(13, OUTPUT);
-  inputString.reserve(5);
   Wire.begin(1);
   Wire.onReceive(receiveEvent);
 }
@@ -44,9 +41,25 @@

                 Error = curangle-angle;
  }
+
+ void receiveEvent(int howMany)
+  {
+
+    if(Wire.available()>0)
+    {
+  x = Wire.read();
+  if(x == 40)
+  digitalWrite(13, HIGH);
+  else digitalWrite(13, LOW);
+ angle = (double) x;
+    }
+}
+
+
+
 void loop()
-{
-
+{
+
                  Errorcalc();
                 if (abs(Error) <2.2){ // prevent integral 'windup'
                 Integral = Integral + Error; // accumulate the error integral
@@ -99,12 +112,3 @@

 }

-void receiveEvent(int howMany)
-{
-  int x = Wire.read();
-  angle = (double) x;
-  Serial.print("got: ");
-  Serial.println(angle);
-  if(angle == 40) digitalWrite(13, HIGH);
-  else digitalWrite(13, LOW);
-}


Update mpxv6115v.ino

Update mpxv6115v.ino

--- example/mpxv6115v.ino
+++ example/mpxv6115v.ino
@@ -21,7 +21,7 @@
 int tolerance=25;

-float isivoltage,degreeC,degreeF;			//Isı değişkenlerinin tanımlanması
+float isivoltage,degreeC,degreeF;				//Isı değişkenlerinin tanımlanması

 const unsigned long delaytime=250;
@@ -34,35 +34,20 @@
 		  pinMode(down,INPUT);
 		  Serial.begin(9600);
 		  while(!Serial);
-		  driver.attachMotorA(inputA1,inputA2);				//DRV8833 için motor bağlı olup olmadığını test etmek amaçlı
+		  driver.attachMotorA(inputA1,inputA2);		//DRV8833 için motor bağlı olup olmadığını test etmek amaçlı
 		  Serial.println("hazir");
-		  Serial.println("\n");
-	  //  attachInterrupt(digitalPinToInterrupt(up),upset,CHANGE)
+		  Serial.println("\n")			        //  attachInterrupt(digitalPinToInterrupt(up),upset,CHANGE)

 }

 void loop()
 {
-
-	// BUTON İLE ARTTIRMA AZALTMA
-	// digitalRead(up);
-	// digitalRead(down);

 		measure();
 		test();
 		set();
 		monitor();
-
-
-
-
-
-
-	driver.motorAStop();
-
-
-
-
+		temp_measure();
 }

@@ -91,4 +76,12 @@
 {

 }
+void temp_measure()
+{
+	voltage = analogRead(temperatureAnalogInputPin) * 0.004882814;
+	degreesC = (voltage - 0.5) * 100.0;
+        //degreesF = degreesC * (9.0/5.0) + 32.0;
+  	return degreesC;
+

+}


Arrumando para testar

Arrumando para testar

--- seguidorSolar/seguidorSolar.ino
+++ seguidorSolar/seguidorSolar.ino
@@ -30,7 +30,11 @@
 /**********CONTROLADOR DE PLACA SOLAR**********/
 SeguidorSolar seguidor;

+String inputString = "";         // a string to hold incoming data
+
+
 void setup () {
+  inputString.reserve(3);
   //inicia
   Serial.begin(9600);
   /**********INSERE OS PARÂMETROS DOS OBEJTOS**********/
@@ -51,6 +55,7 @@
   //seguidor.autoVerificacao(&eixoDiario);
 }

+
 void loop () {
   static uint8_t pos;
   static uint8_t lastPos;
@@ -59,14 +64,29 @@
   unsigned long currentMillis = millis();

   if (Serial.available()) {
-    pos = Serial.parseInt();
-    if (abs(lastPos - pos) >= 5) {
-      seguidor.moveParaPosicao(&eixoDiario, pos);
-      eixoDiario.posicao.minima = eixoDiario.posicao.atual - 5;
-      eixoDiario.posicao.maxima = eixoDiario.posicao.atual + 5;
-      lastPos = pos;
+    // get the new byte:
+    char inChar = (char)Serial.read();
+    // add it to the inputString:
+
+    Serial.print(inChar);
+    if (inChar != '\n')inputString += inChar;
+
+    // if the incoming character is a newline, set a flag
+    // so the main loop can do something about it:
+    if (inChar == '\n') {
+      if (inputString.length() >= 1) {
+        pos = inputString.toInt();
+        if (abs(lastPos - pos) >= 5) {
+          seguidor.moveParaPosicao(&eixoDiario, pos);
+          eixoDiario.posicao.minima = eixoDiario.posicao.atual - 5;
+          eixoDiario.posicao.maxima = eixoDiario.posicao.atual + 5;
+          lastPos = pos;
+        }
+      }
+      inputString = "";
     }
   }
+

   if (currentMillis - previousMillis >= interval) {
     previousMillis = currentMillis;


BT Manual control

BT Manual control

--- manualcontrol/manualcontrol.ino
+++ manualcontrol/manualcontrol.ino
@@ -1,3 +1,9 @@
+#include <SoftwareSerial.h>
+
+String buffer = "";
+char c;
+
+SoftwareSerial btSerial(2, 3); // RX, TX

 // Motor control pins.
 const int E1 = 5;       // R
@@ -13,12 +19,31 @@
 const int rightTrigPin = 9;
 const int rightEchoPin = 8;

+
+/*
+ * Converts String to int.
+ */
+int stringToInt(String s) {
+    char buf[100];
+    s.toCharArray(buf, 100);
+    return atoi(buf);
+}
+
+char streamRead()
+{
+  return btSerial.read();
+}
+
 /*
  * Performs one-time initialization.
  * Setups pin modes and serial communication.
  */
 void setup() {
   Serial.begin(9600);
+  Serial.println("Goodnight moon!");
+
+  // set the data rate for the SoftwareSerial port
+  btSerial.begin(9600);

   pinMode(M1, OUTPUT);
   pinMode(M2, OUTPUT);
@@ -31,12 +56,69 @@
   pinMode(rightEchoPin, INPUT);
 }

+void parseCommand(String raw_cmd) {
+    String cmd[5];
+    for (int ii=0; ii<5; ii++) cmd[ii] = String("");
+
+    int j = 0;
+    for (int i=0; i < raw_cmd.length(); i++) {
+        char c = raw_cmd.charAt(i);
+        if (c == ':')
+            j++;
+        else
+            cmd[j] += String(c);
+    }
+
+    if (cmd[0] == "F") {
+      int speedd = stringToInt(cmd[1]);
+      goForward(speedd / 256.0f);
+    }
+    else if (cmd[0] == "B") {
+      int speedd = stringToInt(cmd[1]);
+      goBackward(speedd / 256.0f);
+    }
+    else if (cmd[0] == "L") {
+      int speedd = stringToInt(cmd[1]);
+      goLeft(speedd / 256.0f);
+    }
+    else if (cmd[0] == "R") {
+      int speedd = stringToInt(cmd[1]);
+      goRight(speedd / 256.0f);
+    }
+}
+
+void readStream() {
+  while (btSerial.available() > 0) {
+    c = streamRead();
+
+    if (c == '<') {
+      buffer = "";
+      // Accumulate buffer until c == '>'
+      while (c != '>') {
+        if (btSerial.available() > 0) {
+          c = streamRead();
+          if (c != '>') {
+            buffer += c;
+          }
+        }
+      }
+
+      // Parse command
+      //Serial.print("cmd: ");
+      //Serial.println(buffer);
+      parseCommand(buffer);
+    }
+  }
+}
+
 /*
  * Main loop.
  */
 void loop() {
   //readInputs();
-  goRight();
+  //goForward(0.7);
+  readStream();
+  delay(10);
 }

 void readInputs(){
@@ -63,7 +145,6 @@
  analogWrite(E2, (int)(135 * x));
  analogWrite(E1, (int)(255 * x));
 }
-

 void goForward(float x) {
  digitalWrite(M1,LOW);


Delete I2C.ino

Delete I2C.ino

--- MPU_GameController_Blog/I2C.ino
+++ MPU_GameController_Blog/I2C.ino
@@ -1,63 +0,0 @@
-/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
-
- This software may be distributed and modified under the terms of the GNU
- General Public License version 2 (GPL2) as published by the Free Software
- Foundation and appearing in the file GPL2.TXT included in the packaging of
- this file. Please note that GPL2 Section 2[b] requires that all works based
- on this software must also be made publicly available under the terms of
- the GPL2 ("Copyleft").
-
- Contact information
- -------------------
-
- Kristian Lauszus, TKJ Electronics
- Web      :  http://www.tkjelectronics.com
- e-mail   :  kristianl@tkjelectronics.com
- */
-
-const uint8_t IMUAddress = 0x68; // AD0 is logic low on the PCB
-const uint16_t I2C_TIMEOUT = 1000; // Used to check for errors in I2C communication
-
-uint8_t i2cWrite(uint8_t registerAddress, uint8_t data, bool sendStop) {
-  return i2cWrite(registerAddress, &data, 1, sendStop); // Returns 0 on success
-}
-
-uint8_t i2cWrite(uint8_t registerAddress, uint8_t *data, uint8_t length, bool sendStop) {
-  Wire.beginTransmission(IMUAddress);
-  Wire.write(registerAddress);
-  Wire.write(data, length);
-  uint8_t rcode = Wire.endTransmission(sendStop); // Returns 0 on success
-  if (rcode) {
-    Serial.print(F("i2cWrite failed: "));
-    Serial.println(rcode);
-  }
-  return rcode; // See: http://arduino.cc/en/Reference/WireEndTransmission
-}
-
-uint8_t i2cRead(uint8_t registerAddress, uint8_t *data, uint8_t nbytes) {
-  uint32_t timeOutTimer;
-  Wire.beginTransmission(IMUAddress);
-  Wire.write(registerAddress);
-  uint8_t rcode = Wire.endTransmission(false); // Don't release the bus
-  if (rcode) {
-    Serial.print(F("i2cRead failed: "));
-    Serial.println(rcode);
-    return rcode; // See: http://arduino.cc/en/Reference/WireEndTransmission
-  }
-  Wire.requestFrom(IMUAddress, nbytes, (uint8_t)true); // Send a repeated start and then release the bus after reading
-  for (uint8_t i = 0; i < nbytes; i++) {
-    if (Wire.available())
-      data[i] = Wire.read();
-    else {
-      timeOutTimer = micros();
-      while (((micros() - timeOutTimer) < I2C_TIMEOUT) && !Wire.available());
-      if (Wire.available())
-        data[i] = Wire.read();
-      else {
-        Serial.println(F("i2cRead timeout"));
-        return 5; // This error value is not already taken by endTransmission
-      }
-    }
-  }
-  return 0; // Success
-}


src: use mac address for mqtt id

src: use mac address for mqtt id

- each mqtt client needs to use a unique id when it connects.
  Use the mac address instead of a hard coded value.

--- Mqtt433Bridge/Mqtt433Bridge.ino
+++ Mqtt433Bridge/Mqtt433Bridge.ino
@@ -20,6 +20,8 @@
 //#include "ArduinoTHSensor2.h"

 #define RX_433_PIN D4
+
+char macAddress[] = "00:00:00:00:00:00";

 void callback(char* topic, uint8_t* message, unsigned int length) {};

@@ -72,6 +74,18 @@
   // receiver.registerDevice(new ArduinoTHSensor2(&client, "esp/house/arduinoTHSensor"));
   // turn of the Access Point as we are not using it
   wifi.mode(WIFI_STA);
+
+  // get the mac address to be used as a unique id for connecting to the mqtt server
+  byte macRaw[6];
+  WiFi.macAddress(macRaw);
+  sprintf(macAddress,
+          "%02.2X:%02.2X:%02.2X:%02.2X:%02.2X:%02.2X",
+          macRaw[0],
+          macRaw[1],
+          macRaw[2],
+          macRaw[3],
+          macRaw[4],
+          macRaw[5]);
 }

 void loop() {
@@ -88,10 +102,12 @@
       return;
     }
   }
-
+
   if (!client.connected()) {
-    if (client.connect("cottage-443rx1")) {
-      Serial.println("mqtt connected\n");
+    if (client.connect(macAddress)) {
+      Serial.println("mqtt connected:");
+      Serial.println(macAddress);
+      Serial.println("\n");
     }
   }


parser bug squash, move queue for command

the parser now actually works for G codes
for a single G command, the list of servo movies is constructed as a command queue
when the entire G line is finished parsing, the command queue is executed with the last
	move updating the display and using the current 'wait' state for the G command
error conditions will void the entire G command and report a single error (the first)
	and no further communications will be made
all commands return a single line of status
	for many commands the status is OK
	for reporting functions, e.g. M commands the line may be the report
	for all functions that can produce an error provide a single line description
		of the error and no further lines of output shall be provided

--- uArm.ino
+++ uArm.ino
@@ -11,8 +11,6 @@

 #include <VarSpeedServo.h>

-#include "uartWIFI.h"
-
 // MicroView
 int SCREEN_WIDTH = uView.getLCDWidth();
 int SCREEN_HEIGHT = uView.getLCDHeight();
@@ -20,15 +18,15 @@

 // Servos
-const int servoPinL = 2;
-const int servoPinR = 3;
-const int servoPinRot = 5;
-const int servoPinHRot = 6;
-const int servoPinH = A0;
-const int slowSweepSpeed = 20;
+const uint8_t servoPinL = 2;
+const uint8_t servoPinR = 3;
+const uint8_t servoPinRot = 5;
+const uint8_t servoPinHRot = 6;
+const uint8_t servoPinH = A0;
+const uint8_t slowSweepSpeed = 20;
 VarSpeedServo servoL, servoR, servoRot, servoHRot, servoH;
-const int defaultServoPos = 90;
-int servoSpeed = slowSweepSpeed;
+const uint8_t defaultServoPos = 90;
+uint8_t servoSpeed = slowSweepSpeed;

 void moveServo(VarSpeedServo &servo, MicroViewWidget *widget, uint8_t degrees, uint8_t servoSpeed, bool wait, bool updateDisplay) {
 	if (degrees >= 0 && degrees <= 180) {
@@ -39,18 +37,33 @@
 	}
 }

-#define	moveServoL(degrees, servoSpeed, wait, updateDisplay)	moveServo(servoL, widgetL, degrees, servoSpeed, wait, updateDisplay)
-#define	moveServoR(degrees, servoSpeed, wait, updateDisplay)	moveServo(servoR, widgetR, degrees, servoSpeed, wait, updateDisplay)
-#define	moveServoRot(degrees, servoSpeed, wait, updateDisplay)	moveServo(servoRot, widgetRot, degrees, servoSpeed, wait, updateDisplay)
-#define	moveServoHRot(degrees, servoSpeed, wait, updateDisplay)	moveServo(servoHRot, widgetHRot, degrees, servoSpeed, wait, updateDisplay)
-#define	moveServoH(degrees, servoSpeed, wait, updateDisplay)	moveServo(servoH, widgetH, degrees, servoSpeed, wait, updateDisplay)
-
-// ESP8266
-#define SSID		"ssid"
-#define PASSWORD	"password"
-#define SERVER_PORT	2222
-WIFI wifi;
-extern int8_t chlID;
+typedef struct servoMove {
+	void (*moveServoFuncPtr)(uint8_t, uint8_t, bool, bool);
+	uint8_t pos;
+	uint8_t servoSpeed;
+} servoMoves_t;
+
+#define MAX_CMD_SERVO_MOVES	5
+uint8_t servoMoveCount;
+bool servoMoveError;
+servoMoves_t servoMoves[MAX_CMD_SERVO_MOVES];
+
+// these are functions vs macros so we can use a function pointer during parsing
+void moveServoL(uint8_t degrees, uint8_t servoSpeed, bool wait, bool updateDisplay) {
+	moveServo(servoL, widgetL, degrees, servoSpeed, wait, updateDisplay);
+}
+void moveServoR(uint8_t degrees, uint8_t servoSpeed, bool wait, bool updateDisplay) {
+	moveServo(servoR, widgetR, degrees, servoSpeed, wait, updateDisplay);
+}
+void moveServoRot(uint8_t degrees, uint8_t servoSpeed, bool wait, bool updateDisplay) {
+	moveServo(servoRot, widgetRot, degrees, servoSpeed, wait, updateDisplay);
+}
+void moveServoHRot(uint8_t degrees, uint8_t servoSpeed, bool wait, bool updateDisplay) {
+	moveServo(servoHRot, widgetHRot, degrees, servoSpeed, wait, updateDisplay);
+}
+void moveServoH(uint8_t degrees, uint8_t servoSpeed, bool wait, bool updateDisplay) {
+	moveServo(servoH, widgetH, degrees, servoSpeed, wait, updateDisplay);
+}

 // helper functions
 void softwareReset(void) {
@@ -95,14 +108,10 @@
 	servoH.detach();
 }

-void setupESP8266(void) {
-	while (!wifi.begin());
-	wifi.Initialize(AP_STA, SSID, PASSWORD);
-	wifi.confMux(1);
-	wifi.confServer(1, SERVER_PORT);
-}
-
 void setup() {
+	// setup serial port
+	Serial.begin(9600);
+
 	// setup MicroView
 	setupMicroView();

@@ -115,8 +124,6 @@
 	moveServoRot(defaultServoPos, servoSpeed, false, false);
 	moveServoHRot(defaultServoPos, servoSpeed, false, false);
 	moveServoH(defaultServoPos, servoSpeed, true, true);
-
-	setupESP8266();
 }

 /*
@@ -131,134 +138,91 @@
 ** MXXX
 **	XXX = 100; reset
 **	XXX = 101; print free memory
+**	XXX = 102; report current servo desination positions
 **	XXX = 112; emergency stop
 */

-bool parseCommandGServo(char **buf, boolean speedControl, boolean wait) {
-	char *endptr;
-	uint8_t pos, i, len;
+bool parseCommandGServo(char **buf, bool speedControl, bool wait) {
+	char *endptr, servoShortName;
+	uint8_t pos;
 	int servoSpeedLocal = servoSpeed;
+	void (*moveServoFuncPtr)(uint8_t, uint8_t, bool, bool) = NULL;

 	if (!speedControl)
 		servoSpeedLocal = 0;

-	wifi.Send(chlID,F("parseCommandGServo"));
-	wifi.Send(chlID,*buf);
-	wifi.Send(chlID,String(*buf[0]));
-
-	if (*buf[0] == '\0')
+	if (*buf[0] == '\0' || *buf[0] == '\n' || *buf[0] == '\r')
 		return false;

-	switch(*buf[0]) {
+	// should this display an error?
+	if (servoMoveCount == MAX_CMD_SERVO_MOVES) {
+		return false;
+	}
+
+	servoShortName = *buf[0];
+	switch(servoShortName) {
 		case 'L': case 'l':
-			pos = strtoul(buf[1], &endptr, 10);
-			if (buf[1] != endptr) {
-				len = strlen(*buf);
-				for (i = 0; i < len; ++i) {
-					if (*buf[i] != ' ' && *buf[i] != '\t' && *buf[i] != '\0')
-						break;
-				}
-				if (i == len) {
-					moveServoL(defaultServoPos, servoSpeedLocal, wait, true);
-				} else {
-					moveServoL(defaultServoPos, servoSpeedLocal, false, false);
-				}
-			} else {
-				wifi.Send(chlID,F("ERROR: invalid servoL position"));
-			}
-			return true;
+			moveServoFuncPtr = &moveServoL;
+			break;
 		case 'R': case 'r':
-			pos = strtoul(buf[1], &endptr, 10);
-			if (buf[1] != endptr) {
-				len = strlen(*buf);
-				for (i = 0; i < len; ++i) {
-					if (*buf[i] != ' ' && *buf[i] != '\t' && *buf[i] != '\0')
-						break;
-				}
-				if (i == len) {
-					moveServoR(defaultServoPos, servoSpeedLocal, wait, true);
-				} else {
-					moveServoR(defaultServoPos, servoSpeedLocal, false, false);
-				}
-			} else {
-				wifi.Send(chlID,F("ERROR: invalid servoR position"));
-			}
-			return true;
+			moveServoFuncPtr = &moveServoR;
+			break;
 		case 'O': case 'o':
-			pos = strtoul(buf[1], &endptr, 10);
-			if (buf[1] != endptr) {
-				len = strlen(*buf);
-				for (i = 0; i < len; ++i) {
-					if (*buf[i] != ' ' && *buf[i] != '\t' && *buf[i] != '\0')
-						break;
-				}
-				if (i == len) {
-					moveServoRot(defaultServoPos, servoSpeedLocal, wait, true);
-				} else {
-					moveServoRot(defaultServoPos, servoSpeedLocal, false, false);
-				}
-			} else {
-				wifi.Send(chlID,F("ERROR: invalid servoRot position"));
-			}
-			return true;
+			moveServoFuncPtr = &moveServoRot;
+			break;
 		case 'T': case 't':
-			pos = strtoul(buf[1], &endptr, 10);
-			if (buf[1] != endptr) {
-				len = strlen(*buf);
-				for (i = 0; i < len; ++i) {
-					if (*buf[i] != ' ' && *buf[i] != '\t' && *buf[i] != '\0')
-						break;
-				}
-				if (i == len) {
-					moveServoHRot(defaultServoPos, servoSpeedLocal, wait, true);
-				} else {
-					moveServoHRot(defaultServoPos, servoSpeedLocal, false, false);
-				}
-			} else {
-				wifi.Send(chlID,F("ERROR: invalid servoHRot position"));
-			}
-			return true;
+			moveServoFuncPtr = &moveServoHRot;
+			break;
 		case 'H': case 'h':
-			pos = strtoul(buf[1], &endptr, 10);
-			if (buf[1] != endptr) {
-				len = strlen(*buf);
-				for (i = 0; i < len; ++i) {
-					if (*buf[i] != ' ' && *buf[i] != '\t' && *buf[i] != '\0')
-						break;
-				}
-				if (i == len) {
-					moveServoH(defaultServoPos, servoSpeedLocal, wait, true);
-				} else {
-					moveServoH(defaultServoPos, servoSpeedLocal, false, false);
-				}
-			} else {
-				wifi.Send(chlID,F("ERROR: invalid servoH position"));
-			}
-			return true;
-		default:
-			wifi.Send(chlID,F("ERROR: invalid servo identifier"));
-			return false;
+			moveServoFuncPtr = &moveServoH;
+			break;
 	};
+
+	if (moveServoFuncPtr != NULL) {
+		(*buf)++;
+		pos = strtoul(*buf, &endptr, 10);
+		if (*buf != endptr && pos >= 0 && pos <= 180) {
+			for (; **buf == ' ' || **buf == '\t'; (*buf)++);
+			servoMoves[servoMoveCount].moveServoFuncPtr = moveServoFuncPtr;
+			servoMoves[servoMoveCount].pos = pos;
+			servoMoves[servoMoveCount].servoSpeed = servoSpeedLocal;
+			servoMoveCount++;
+		} else {
+			servoMoveError = true;
+			if (*buf == endptr) {
+				Serial.print(F("ERROR: missing servo position for servo "));
+				Serial.println(servoShortName);
+			} else {
+				Serial.print(F("ERROR: missing servo position for servo "));
+				Serial.print(servoShortName);
+				Serial.print(F(": "));
+				Serial.println(pos, DEC);
+			}
+		}
+		*buf = endptr;
+		return true;
+	} else {
+		servoMoveError = true;
+		Serial.print(F("ERROR: invalid servo identifier: "));
+		Serial.println(servoShortName);
+	}
 	return false;
 }

 bool processCommand(char *cmd) {
 	char *endptr, *buf = cmd;
-	uint8_t len = strlen(buf);
-	uint8_t code;
+	uint8_t i, len = strlen(buf);
+	int code;
 	bool speedControl = true;
 	bool wait;

 	if (len == 0) return false;
-
-	wifi.Send(chlID,F("processCommand"));
-	wifi.Send(chlID,cmd);

 	switch (buf[0]) {
 		case 'G': case 'g':
 			code = strtoul(&buf[1], &endptr, 10);
 			if (endptr == &buf[1]) {
-				wifi.Send(chlID,F("ERROR: missing G command code"));
+				Serial.println(F("ERROR: missing G command code"));
 				return false;
 			}
 			if (code == 0) {
@@ -268,7 +232,7 @@
 				// speed control move
 				speedControl = true;
 			} else {
-				wifi.Send(chlID,F("ERROR: invalid G command code"));
+				Serial.println(F("ERROR: invalid G command code"));
 				return false;
 			}
 			// absorb spaces
@@ -284,71 +248,120 @@
 					} else if (code == 1) {
 						wait = true;
 					} else {
-						wifi.Send(chlID,F("ERROR: invalid G command wait flag (bad number)"));
+						Serial.print(F("ERROR: invalid G command wait flag, bad value: "));
+						Serial.println(code, DEC);
 						return false;
 					}
 				} else {
-					wifi.Send(chlID,F("ERROR: invalid G command wait flag (no number)"));
+					Serial.println(F("ERROR: invalid G command wait flag (missing value)"));
 					return false;
 				}
 			}
+			servoMoveCount = 0;
+			servoMoveError = false;
 			do {
 				// absorb spaces
 				for (; *endptr == ' ' || *endptr == '\t'; ++endptr);
-				wifi.Send(chlID,endptr);
-			} while (parseCommandGServo(&endptr, speedControl, wait));
+			} while (parseCommandGServo(&endptr, speedControl, wait) && !servoMoveError);
+			for (i = 0; !servoMoveError && i < servoMoveCount; ++i) {
+				// perform this move, if the last move in the list, use the wait variable value and update display
+				servoMoves[i].moveServoFuncPtr(servoMoves[i].pos, servoMoves[i].servoSpeed,
+					(i == servoMoveCount - 1 ? false : wait), (i == servoMoveCount - 1 ? true : false));
+			}
+			if (i != 0)
+				Serial.println(F("OK"));
 			break;
 		case 'F': case 'f':
 			code = strtoul(&buf[1], &endptr, 10);
 			if (endptr == &buf[1]) {
-				wifi.Send(chlID,F("ERROR: missing F speed parameter"));
+				Serial.println(F("ERROR: missing F speed parameter"));
 				return false;
 			}
 			if (code >= 0 && code <= 255) {
 				servoSpeed = code;
-				wifi.Send(chlID,F("OK"));
+				Serial.println(F("OK"));
 				return true;
 			} else {
-				wifi.Send(chlID,F("ERROR: invalid F speed parameter"));
+				Serial.print(F("ERROR: invalid F speed parameter: "));
+				Serial.println(code, DEC);
 				return false;
 			}
 			break;
 		case 'M': case 'm':
 			code = strtoul(&buf[1], &endptr, 10);
 			if (endptr == &buf[1]) {
-				wifi.Send(chlID,F("ERROR: missing M address parameter"));
+				Serial.println(F("ERROR: missing M address parameter"));
 				return false;
 			}
 			switch (code) {
 				case 100:
-					wifi.Send(chlID,F("OK"));
+					Serial.println(F("OK"));
 					softwareReset();
 					break;
 				case 101:
-					wifi.Send(chlID,String(freeRam(), DEC));
+					Serial.println(freeRam(), DEC);
+					break;
+				case 102:
+					Serial.print(F("L"));
+					Serial.print(servoL.read(), DEC);
+					Serial.print(F(" R"));
+					Serial.print(servoR.read(), DEC);
+					Serial.print(F(" O"));
+					Serial.print(servoRot.read(), DEC);
+					Serial.print(F(" T"));
+					Serial.print(servoHRot.read(), DEC);
+					Serial.print(F(" H"));
+					Serial.println(servoH.read(), DEC);
 					break;
 				case 112:
 					detachServos();
-					wifi.Send(chlID,F("OK"));
-					break;
+					Serial.println(F("OK"));
+					break;
+				case 113:
+					attachServos();
+					Serial.println(F("OK"));
+					break;
+
 				default:
-					wifi.Send(chlID,F("ERROR: invalid M address parameter"));
+					Serial.print(F("ERROR: invalid M address parameter: "));
+					Serial.println(code, DEC);
 					return false;
 			};
 			break;
 		default:
-			wifi.Send(chlID,F("ERROR: invalid command"));
+			Serial.print(F("ERROR: invalid command: "));
+			Serial.println(buf[0]);
 			return false;
 	};
 }

+// main loop
 const uint8_t MAX_CMD_LEN = 128;
 char buf[MAX_CMD_LEN + 1], c;
-uint8_t len = 0;
+bool suspendStore = false;
+uint8_t len = 0, cidx = 0;

 void loop() {
-	len = wifi.ReceiveMessage(buf);
-	if (len > 0) {
-		processCommand(buf);
+	// read to newline
+	// ignore any line that has over 32 characters
+	if (Serial.available() > 0) {
+		c = Serial.read();
+		if (c == '\n' || c == '\r') {
+			if (suspendStore == false) {
+				buf[cidx] = '\0';
+				processCommand(buf);
+			} else {
+				suspendStore = false;
+			}
+			cidx = 0;
+		} else {
+			if (cidx < MAX_CMD_LEN) {
+				buf[cidx] = c;
+				++cidx;
+			} else {
+				Serial.println(F("ERROR: command line too long"));
+				suspendStore = true;
+			}
+		}
 	}
 }


Update RIODuino codebase

Update RIODuino codebase

--- RIODuino/RIODuino.ino
+++ RIODuino/RIODuino.ino
@@ -1,12 +1,18 @@
+/*
+ * This program uses the third-party library NeoPixel.
+ * You must download and install this library in order to compile and upload the code.
+ * You can download it for free at http://github.com/adafruit/Adafruit_NeoPixel
+ */
+
 #include <Adafruit_NeoPixel.h>
 #include <Wire.h>

 #define LED_PIN 8
 #define LED_COUNT 60

-#define DEVICE_ADDRESS 0
-#define STACK_HEIGHT_REGISTER 0
-#define ALLIANCE_REGISTER 1
+#define DEVICE_ADDRESS 1
+#define STACK_HEIGHT_REGISTER 1
+#define ALLIANCE_REGISTER 2

 #define BLUE_ALLIANCE 0
 #define RED_ALLIANCE 1


fix return()

fix return()

--- sketchbook/printer/printer.ino
+++ sketchbook/printer/printer.ino
@@ -18,7 +18,7 @@
 void setPos(int & pos, Motor & motor) {
     if (!configured) {
         errConf();
-        return();
+        return;
     }
     int to = Serial.parseInt();
     motor.rotateSteps(to - pos);


Bug fixes for Automatic Motor Readings

Bug fixes for Automatic Motor Readings

--- ps2_controller/ps2_controller.ino
+++ ps2_controller/ps2_controller.ino
@@ -499,7 +499,6 @@

   for (serial_rx_buffer_counter = 0; serial_rx_buffer_counter < sizeof(serial_rx_buffer_reset_controller); serial_rx_buffer_counter++) {
     //  Write back data as a way to tell the Status changed correctly
-    serial_rx_buffer_change_motors_status[serial_rx_buffer_counter] = serial_rx_buffer[serial_rx_buffer_counter];
     Serial.write(serial_rx_buffer_change_motors_status[serial_rx_buffer_counter]);
   }
   Serial.flush();


Update Razor_AHRS.ino

Update Razor_AHRS.ino

--- sandbox/Razor_AHRS/Razor_AHRS.ino
+++ sandbox/Razor_AHRS/Razor_AHRS.ino
@@ -73,7 +73,7 @@
       "#oat" - Output CALIBRATED SENSOR data of accelerometer and gyros in TEXT format.
                One frame consist of three lines - one for RPY, accel, gyro
       "#oab" - Output CALIBRATED SENSOR data of accelerometer and gyros in BINARY format.
-               One frame consist of two 3x3 float values and one RPY 3x4 (24 bytes + 12 bytes = bytes long)
+               One frame consist of two 3x3 float values and one RPY 3x4 (24 bytes + 12 bytes = 36 bytes long)

       // Error message output
       "#oe0" - Disable ERROR message output.


Fast final

Fast final

--- slave_receiver/slave_receiver.ino
+++ slave_receiver/slave_receiver.ino
@@ -56,27 +56,27 @@
    Serial.println("So weit, so gut");
    for(i=0;i<50;i++){
    test += data[i];}
-  Serial.println(test);
-   f_new_s = test.substring(1,indices[0]);
+  //Serial.println(test);
+   f_new_s = test.substring(2,indices[0]+1);
    f_new = f_new_s.toInt();
-   Serial.println(f_new);
-  amp1_s = test.substring(indices[1]+1,indices[2]);
+   //Serial.println(f_new_s);
+  amp1_s = test.substring(indices[1]+3,indices[2]+1);
   amp1 = amp1_s.toFloat();
-  amp2_s = test.substring(indices[2]+1, indices[3]);
+  amp2_s = test.substring(indices[2]+3, indices[3]+1);
   amp2 = amp2_s.toFloat();
-  duration_s = test.substring(indices[3]+1,indices[4]);
+  duration_s = test.substring(indices[3]+3,indices[4]+1);
   duration = duration_s.toInt();
-  pause_t_s = test.substring(indices[4]+1,indices[5]);
+  pause_t_s = test.substring(indices[4]+3,indices[5]+1);
   pause_t =  pause_t_s.toInt();
-  Serial.println(pause_t);
+  /*Serial.println(amp1);
+  Serial.println(amp2);
   Serial.println(duration);
-  Serial.println(amp2);
-  Serial.println(amp1);
+  Serial.println(pause_t);*/
   Timer1.start();
   delayMicroseconds(duration);
   Timer1.stop();
   delayMicroseconds(pause_t);
-  f_new_s = test.substring(indices[0]+1,indices[1]);
+  f_new_s = test.substring(indices[0]+3,indices[1]+1);
    f_new = f_new_s.toInt();
   Timer2.start();
   delayMicroseconds(duration);


Change to python style serialisation, invert enable pin (hardware docs were wrong), move the stepper a bit faster.

--- test/PoE-test/spacedeur-asis-2017/spacedeur-asis-2017.ino
+++ test/PoE-test/spacedeur-asis-2017/spacedeur-asis-2017.ino
@@ -1,4 +1,4 @@
-/* Spacedeur 2 - 'as is' configuration which should be near identical
+/* Spacedeur 2-'as is' configuration which should be near identical
     to the existing setup late 2017.
 */

@@ -10,7 +10,7 @@
 #define ETH_PHY_POWER     17
 #define ETH_PHY_TYPE      ETH_PHY_LAN8720

-// Labelling as per `blue' RFID MFRC522 - MSL 1471 'fixed'
+// Labelling as per `blue' RFID MFRC522-MSL 1471 'fixed'
 //
 #define MFRC522_SDA     (15)
 #define MFRC522_SCK     (14)
@@ -21,11 +21,14 @@
 #define MFRC522_RSTO    (32)
 #define MFRC522_3V3     /* 3v3 */

-// Stepper motor - Pololu / A4988
+// Stepper motor-Pololu / A4988
 //
 #define STEPPER_DIR       (2)
 #define STEPPER_ENABLE    (4)
 #define STEPPER_STEP      (5)
+
+#define STEPPER_MAXSPEED 750
+#define STEPPER_ACCESS 300

 #define LED_AART          (16)

@@ -58,7 +61,7 @@
 MFRC522 mfrc522(MFRC522_SDA, MFRC522_RSTO, &spirfid, spiSettings);

 // Simple overlay of the AccelStepper that configures for the A4988
-// driver of a 4 wire stepper - including the additional enable wire.
+// driver of a 4 wire stepper-including the additional enable wire.
 //
 class PololuStepper : public AccelStepper
 {
@@ -70,21 +73,26 @@
   : AccelStepper(AccelStepper::DRIVER, step_pin, dir_pin)
 {
   pinMode(STEPPER_ENABLE, OUTPUT);
-  digitalWrite(STEPPER_ENABLE, HIGH); // dis-able stepper first.
+  digitalWrite(STEPPER_ENABLE, LOW); // dis-able stepper first.
+  setPinsInverted(false, false, true);
   setEnablePin(enable_pin);
 }

 PololuStepper stepper = PololuStepper(STEPPER_STEP, STEPPER_DIR, STEPPER_ENABLE);

+#ifdef LOCALMQTT
+const IPAddress mqtt_host = LOCALMQTT;
+#else
 const char mqtt_host[] = "space.vijn.org";
+#endif
 const unsigned short mqtt_port = 1883;

 extern void callback(char* topic, byte * payload, unsigned int length);

 bool caching = false;

-#define PREFIX "test/"
+#define PREFIX ""

 const char rfid_topic[] = PREFIX "deur/space2/rfid";
 const char door_topic[] = PREFIX "deur/space2/open";
@@ -102,19 +110,11 @@
   if (ota)
     return;

-  // Port defaults to 3232
-  // ArduinoOTA.setPort(3232);
-
-  // Hostname defaults to esp3232-[MAC]
+  ArduinoOTA.setPort(3232);
   ArduinoOTA.setHostname(pname);
-
-  // No authentication by default
-  // ArduinoOTA.setPassword("admin");
-
-  // Password can be set with it's md5 value as well
-  // MD5(admin)=21232f297a57a5a743894a0e4a801fc3
-  // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");
-
+#ifdef LOCALOTA
+  ArduinoOTA.setPasswordHash(LOCALOTA);
+#endif

   ArduinoOTA.onStart([]() {
     String type;
@@ -123,7 +123,7 @@
         type = "Firmware";
         break;
       case U_SPIFFS:
-          type = "SPIFFS";
+        type = "SPIFFS";
         break;
       default: {
           const char buff[] = "Unknown type of reprogramming attempt. Rejecting.";
@@ -152,7 +152,7 @@

   ArduinoOTA.onEnd([]() {
     char buff[256];
-    snprintf(buff, sizeof(buff), "[%s] OTA re - programming completed. Rebooting.", pname);
+    snprintf(buff, sizeof(buff), "[%s] OTA re-programming completed. Rebooting.", pname);

     Serial.println(buff);
     client.publish(log_topic, buff);
@@ -175,10 +175,10 @@
     int p = progress / (total / 10);
     if (p != lp) Serial.printf("Progress: %u %%\n", p * 10);
     lp = p;
-    digitalWrite(LED_AART, (millis() >> 7) & 3 == 0);
+    digitalWrite(LED_AART, ((millis() >> 7) & 3) == 0);
   });

-  // Unfortunately - deep in OTA it auto defaults to Wifi. So we
+  // Unfortunately-deep in OTA it auto defaults to Wifi. So we
   // force it to ETH -- requires pull RQ https://github.com/espressif/arduino-esp32/issues/944
   // and https://github.com/espressif/esp-idf/issues/1431.
   //
@@ -199,7 +199,7 @@
 String connectionDetailsString() {
   return "Wired Ethernet: " + ETH.macAddress() +
          ", IPv4: " + DisplayIP4Address(ETH.localIP()) + ", " +
-         ((ETH.fullDuplex()) ? "full" : "half") + " - duplex, " +
+         ((ETH.fullDuplex()) ? "full" : "half") + "-duplex, " +
          String(ETH.linkSpeed()) + " Mbps.";
 }

@@ -258,7 +258,7 @@

 boolean reconnect() {
   if (!client.connect(pname)) {
-    // Do not log this to the MQTT bus - as it may have been us posting too much
+    // Do not log this to the MQTT bus-as it may have been us posting too much
     // or some other loop-ish thing that triggered our disconnect.
     //
     Serial.println("Failed to reconnect to MQTT bus.");
@@ -304,7 +304,7 @@

   Serial.println("MFRC522 IRQ and callback setup.");
   mfrc522.PCD_Init();   // Init MFRC522
-  mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
+  mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD-MFRC522 Card Reader details

   pinMode(MFRC522_IRQ, INPUT_PULLUP);
   attachInterrupt(digitalPinToInterrupt(MFRC522_IRQ), readCard, FALLING);
@@ -317,8 +317,8 @@
   client.setCallback(callback);

   Serial.println("Setup of Stepper motor");
-  stepper.setMaxSpeed(300);  // divide by 3 to get rpm
-  stepper.setAcceleration(100);
+  stepper.setMaxSpeed(STEPPER_MAXSPEED);  // divide by 3 to get rpm
+  stepper.setAcceleration(STEPPER_ACCESS);
   stepper.moveTo(DOOR_CLOSED);

   stepper.run();
@@ -327,7 +327,7 @@

   Serial.println("SPIFF setup");
   if (!SPIFFS.begin()) {
-    Serial.println("SPIFFS Mount Failed - reformatting");
+    Serial.println("SPIFFS Mount Failed-reformatting");
     wipeCache();
   } else {
     caching = true;
@@ -389,7 +389,7 @@
 };

 String uid2path(MFRC522::Uid uid) {
-  String path = " / uid - ";
+  String path = " / uid-";
   for (int i = 0; i < uid.size; i++) {
     path += String(uid.uidByte[i], DEC);
     if (i == 0)
@@ -440,7 +440,7 @@
 String uidToString(MFRC522::Uid uid) {
   String uidStr = "";
   for (int i = 0; i < uid.size; i++) {
-    if (i) uidStr += " - ";
+    if (i) uidStr += "-";
     uidStr += String(uid.uidByte[i], DEC);
   };
   return uidStr;
@@ -451,7 +451,7 @@

   if (strcmp(topic, door_topic)) {
     Serial.printf("Received an unexepcted %d byte message on topic <%s>, ignoring.", length, topic);
-    // We intentinally do not log this message to a MQTT channel - as to reduce the
+    // We intentinally do not log this message to a MQTT channel-as to reduce the
     // risk of (amplification) loops due to a misconfiguration. We do increase the counter
     // so indirectly this does show up in the MQTT log.
     //
@@ -510,7 +510,7 @@
       snprintf(msg, sizeof(msg), "[%s] Purged cache of UID <%s> (payload %s)", pname, uidToString(uid).c_str(), ptag);
       setCache(uid, false);
     } else {
-      snprintf(msg, sizeof(msg), "[%s] Ignored purge request for uid - payload <%s> ", pname, ptag);
+      snprintf(msg, sizeof(msg), "[%s] Ignored purge request for uid-payload <%s> ", pname, ptag);
       cnt_mqttfails ++;
     }
     client.publish(log_topic, msg);
@@ -546,8 +546,8 @@
 void reportStats() {
   char buff[255];
   snprintf(buff, sizeof(buff),
-           "[%s] alive - uptime %02ld : %02ld : "
-           "swipes %ld, opens %ld, closes %ld, fails %ld, mis - swipes %ld, mqtt reconnects %ld, mqtt fails %ld, stepper %s at %ld (target %ld)",
+           "[%s] alive-uptime %02ld : %02ld : "
+           "swipes %ld, opens %ld, closes %ld, fails %ld, mis-swipes %ld, mqtt reconnects %ld, mqtt fails %ld, stepper %s at %ld (target %ld)",
            pname, cnt_minutes / 60, (cnt_minutes % 60),
            cnt_cards,
            cnt_opens, cnt_closes, cnt_fails, cnt_misreads, cnt_reconnects, cnt_mqttfails,
@@ -654,7 +654,7 @@
   if ((millis() - last_doorstatechange > 10 * DOOR_OPEN_DELAY) && ((doorstate != CLOSED) || (!isClosed()))) {
     closeDoor();
     char msg[256];
-    snprintf(msg, sizeof(msg), "[%s] Door in an odd state - forcing close.", pname);
+    snprintf(msg, sizeof(msg), "[%s] Door in an odd state-forcing close.", pname);
     Serial.println(msg);
     client.publish(log_topic, msg);
     cnt_fails ++;
@@ -674,8 +674,15 @@
       uid = mfrc522.uid;
       String uidStr = uidToString(uid);

+      String pyStr = "[";
+      for (int i = 0; i < uid.size; i++) {
+        if (i) pyStr += ", ";
+        pyStr += String(uid.uidByte[i], DEC);
+      };
+      pyStr += "]";
+
       cnt_cards++;
-      client.publish(rfid_topic, uidStr.c_str());
+      client.publish(rfid_topic, pyStr.c_str());

       char msg[256];
       snprintf(msg, sizeof(msg), "[%s] Tag <%s> (len=%d) swiped", pname, uidStr.c_str(), uid.size);


fix string transmission

fix string transmission

--- TX/TX.ino
+++ TX/TX.ino
@@ -25,7 +25,7 @@
   Radio.SetTxPower(0);

   // put strbuf into txbuf
-  for (i = 0; i < sizeof(strbuf) - 1; i++)
+  for (i = 0; i < strbuf[i] != '\0'; i++)
     txbuf[i] = (byte)strbuf[i];
   txsize = i;
 }
@@ -35,8 +35,13 @@
   Radio.SendData(txbuf, txsize);

   // tell computer we transmitted
-  Serial.print("Transmit #");
+  Serial.print("Transmit (");
+  Serial.print(strbuf);
+  Serial.print(") #");
   Serial.println(txnum);
+
+  // increment number
+  txnum++;

   // wait for next transmission
   delay(100);


Fix LEDs ports numbers

Fix LEDs ports numbers

--- meteo_in/meteo_in.ino
+++ meteo_in/meteo_in.ino
@@ -15,10 +15,10 @@
 +------+-------------------+-------------------------------+
 |   2  |            DHT22  | Temp & Humid sensor           |
 |   3  |       temp in IND | PWN - temp in indicator       |
-|   4  |  low pressure LED |                               |
 |   5  |      humid in IND | PWN - humid in indicator      |
 |   6  |      pressure IND | PWM - air pressure indicator  |
-|   7  | high pressure LED |                               |
+|   8  |  low pressure LED |                               |
+|   9  | high pressure LED |                               |
 +------+-------------------+-------------------------------+
 |  A5  |      BMP180 (SCL) | Air pressure sensor (SCL)     |
 |  A4  |      BMP180 (SDA) | Air pressure sensor (SDA)     |
@@ -33,8 +33,8 @@

 // LEDs
 #define DEBUG_LED          13
-#define LOW_PRESSURE_LED   4
-#define HIGH_PRESSURE_LED  7
+#define LOW_PRESSURE_LED   8
+#define HIGH_PRESSURE_LED  9

 // INDICATORS (need PWM)
@@ -82,7 +82,7 @@
     digitalWrite(LOW_PRESSURE_LED,  HIGH);
     digitalWrite(HIGH_PRESSURE_LED, HIGH);
     int tab[]       = {IND_TEMP_IN, IND_HUMID_IN, IND_PRESSURE, -1};
-    int tab_calib[] = {calib_max_temp, calib_max_humid, calib_max_press, -1}
+    int tab_calib[] = {calib_max_temp, calib_max_humid, calib_max_press, -1};
     diagnostic_setup(tab, tab_calib);
     digitalWrite(LOW_PRESSURE_LED,  LOW);
     digitalWrite(HIGH_PRESSURE_LED, LOW);


Battery tweek

Battery tweek

--- alan/alan.ino
+++ alan/alan.ino
@@ -110,7 +110,7 @@
 int whiskers_timer = 0; // Stores the timer used for the whiskers.

 // Battery configuration
-unsigned long battery_delay = 15000; // Number of milliseconds to wait before next battery reading
+unsigned long battery_delay = 10000; // Number of milliseconds to wait before next battery reading

 // Sound configuration
 const byte sound_pin = 2;
@@ -164,7 +164,7 @@
   A_WHISKERSEARCH_RIGHT,
   A_DANCE1,
   A_DANCE2,
-  A_BORED,
+  A_SAD,
   A_HAPPY,
 };
 // The curent action state.
@@ -204,11 +204,13 @@
   digitalWrite(motorA_brake, LOW);   // Disengage the Brake for Channel A
   digitalWrite(motorB_brake, LOW);   // Disengage the Brake for Channel B

+  timer.setTimeout(500, soundPause);
+
   int timer_battery = timer.setInterval(battery_delay, batteryLevel);
   Serial.print("Battery tick started id=");
   Serial.println(timer_battery);

-  timer.setTimeout(500, soundPause);
+

   actionStop();
   batteryLevel();
@@ -373,7 +375,8 @@
       actionDance2StateMachine(motion_state);
       break;

-    case A_BORED:
+    case A_SAD:
+      actionSadStateMachine(motion_state);
       break;

     case A_HAPPY:
@@ -516,7 +519,7 @@
 }

 /**
- * Happy
+ * Happy :)
  */
 void actionHappy()
 {
@@ -559,6 +562,59 @@
         // Spin left for random amount of time
         actionTimeoutStart(random(500,700));
         motionRotateLeft(255);
+      }
+      break;
+
+    default:
+      break;
+  }
+
+}
+
+/**
+ * Sad :(
+ */
+void actionSad()
+{
+  if (action_state != A_SAD) {
+    Serial.println("Sad");
+
+    // Set the state, so the action can be handled by the state machine.
+    action_state = A_SAD;
+
+    actionTimeoutStart(random(500,700));
+    motionRev(200);
+  }
+}
+
+void actionSadStateMachine(byte motion_state)
+{
+  static byte count = 0;
+
+  // Loop through left & right a few times.
+  if (count > 3) {
+    count = 0;
+    Serial.println("Sad done");
+    actionStop();
+  }
+
+  switch (motion_state) {
+
+    case M_REV:
+      if (action_done) {
+        count++;
+        // Spin right for random amount of time
+        actionTimeoutStart(random(500,700));
+        motionFwd(200);
+      }
+      break;
+
+    case M_FWD:
+      if (action_done) {
+        count++;
+        // Spin left for random amount of time
+        actionTimeoutStart(random(500,700));
+        motionRev(200);
       }
       break;

@@ -1008,6 +1064,7 @@
     /* Received code is for the number 5 button */
   case 0xFF38C7:
     strcpy (CodeName, "5");
+    actionSad();
     break;
     /* Received code is for the number 6 button */
   case 0xFF5AA5:


More target control and such

More target control and such

--- testjig/production/production.ino
+++ testjig/production/production.ino
@@ -9,6 +9,17 @@
 #include "arm_kinetis_debug.h"
 #include "arm_kinetis_reg.h"
 #include "firmware_data.h"
+
+#define CFLAG_NO_DITHERING      (1 << 0)
+#define CFLAG_NO_INTERPOLATION  (1 << 1)
+#define CFLAG_NO_ACTIVITY_LED   (1 << 2)
+#define CFLAG_LED_CONTROL       (1 << 3)
+#define LUT_CH_SIZE             257
+#define LUT_TOTAL_SIZE          (LUT_CH_SIZE * 3)
+#define PIXELS_PER_PACKET       21
+#define LUTENTRIES_PER_PACKET   31
+#define PACKETS_PER_FRAME       25
+#define PACKETS_PER_LUT         25

 const unsigned buttonPin = 2;
 const unsigned ledPin = 13;
@@ -23,6 +34,63 @@
     pinMode(ledPin, OUTPUT);
     pinMode(buttonPin, INPUT_PULLUP);
     Serial.begin(115200);
+}
+
+bool fbInit()
+{
+    // Install a trivial identity-mapping LUT, writing directly to the firmware's LUT buffer.
+    for (unsigned channel = 0; channel < 3; channel++) {
+        for (unsigned index = 0; index < LUT_CH_SIZE; index++) {
+            unsigned value = index << 8;
+            if (value > 0xFFFF)
+                value = 0xFFFF;
+            if (!target.memStoreHalf(fw_pLUT + 2*(index + channel*LUT_CH_SIZE), value))
+                return false;
+        }
+    }
+
+    // Control flags: Disable interpolation so only fbNext is in use, and use manual LED control
+    uint8_t control = CFLAG_NO_ACTIVITY_LED | CFLAG_NO_INTERPOLATION;
+    return target.memStoreByte(fw_pFlags, control);;
+
+    return true;
+}
+
+bool fbWrite(unsigned id, int red, int green, int blue)
+{
+    // Write one pixel directly into the fbNext framebuffer on the target.
+
+    uint32_t idPacket = id / PIXELS_PER_PACKET;
+    uint32_t idOffset = fw_usbPacketBufOffset + 1 + (id % PIXELS_PER_PACKET) * 3;
+
+    uint32_t fb;        // Address of the current fcFramebuffer bound to fbNext
+    uint32_t packet;    // Pointer to usb_packet in question
+
+    return
+        target.memLoad(fw_pFbNext, fb) &&
+        target.memLoad(fb + idPacket*4, packet) &&
+        target.memStoreByte(packet + idOffset + 0, constrain(red, 0, 255)) &&
+        target.memStoreByte(packet + idOffset + 1, constrain(green, 0, 255)) &&
+        target.memStoreByte(packet + idOffset + 2, constrain(blue, 0, 255));
+}
+
+bool installFirmware()
+{
+    bool blink = false;
+    ARMKinetisDebug::FlashProgrammer programmer(target, fw_data, fw_sectorCount);
+
+    if (!programmer.begin())
+        return false;
+
+    while (!programmer.isComplete()) {
+        blink = !blink;
+        if (!programmer.next()) return false;
+        if (!target.pinMode(targetLedPin, OUTPUT)) return false;
+        if (!target.digitalWrite(targetLedPin, blink)) return false;
+        digitalWrite(ledPin, blink);
+    }
+
+    return true;
 }

 void loop()
@@ -41,23 +109,29 @@
     }
     digitalWrite(ledPin, HIGH);

+    // Start debugging the target
     if (!target.begin(swclkPin, swdioPin))
         return;
     if (!target.startup())
         return;

-    // Program firmware
-#if 0
-    if (!target.flashEraseAndProgram(firmwareData, firmwareSectorCount))
+    // Program firmware, blinking both LEDs in unison for status.
+    if (!installFirmware())
         return;
-#endif

-    /*
-     * Try blinking an LED on the target!
-     */
+    // Run the new firmware, and let it boot
+    if (!target.reset())
+        return;
+    delay(50);

-    target.pinMode(targetLedPin, OUTPUT);
-    while (target.digitalWrite(targetLedPin, !target.digitalRead(targetLedPin))) {
-        delay(100);
+    // Initialize direct access to the firmware's framebuffer
+    if (!fbInit())
+        return;
+
+    // Green and blue throbbing means success!
+    while (1) {
+        float x = sin(millis() * 0.008);
+        if (!fbWrite(0, 0, 0xc + 0x10 * x, 0)) return;
+        if (!fbWrite(1, 0, 0, 0xc - 0x10 * x)) return;
     }
 }


current init

current init

--- init.ino
+++ init.ino
@@ -95,9 +95,9 @@
 void led_man_queue() {
 	// manually queue animations for startup

-	// thread_handler.queue(new Animation_Simple_DeskWhitePurpleFade());
-	thread_handler.queue(new Animation_Static_Indiv_ThirdDimAmbient(&desk1));
-	thread_handler.queue(new Animation_Static_Indiv_ThirdDimAmbient(&desk2));
+	thread_handler.queue(new Animation_Simple_DeskWhitePurpleFade());
+	// thread_handler.queue(new Animation_Static_Indiv_ThirdDimAmbient(&desk1));
+	// thread_handler.queue(new Animation_Static_Indiv_ThirdDimAmbient(&desk2));
 	// thread_handler.queue(new Animation_Simple_Indiv_RainbowCycle(&desk2));

 	// thread_handler.queue(new Animation_Holiday_Halloween_WinAllHalloweenSparkle());
@@ -106,13 +106,29 @@
 	// thread_handler.queue(new Animation_Seasonal_Indiv_Winter_WindowSnow(&window2));
 	// thread_handler.queue(new Animation_Seasonal_Indiv_Winter_WindowSnow(&window3));

-	// thread_handler.queue(new Animation_Simple_Indiv_CalmPurpleFade(&window1));
+	// thread_handler.queue(new Animation_Seasonal_Indiv_Weather_WindowLightRain(&window1));
 	// thread_handler.queue(new Animation_Simple_Indiv_CalmPurpleFade(&window2));
-	// thread_handler.queue(new Animation_Simple_Indiv_CalmPurpleFade(&window3));
+	// thread_handler.queue(new Animation_Seasonal_Indiv_Weather_WindowLightRain(&window3));

 	// thread_handler.queue(new Animation_Simple_Indiv_RainbowCycle(&window1));
 	// thread_handler.queue(new Animation_Simple_Indiv_RainbowCycle(&window2));
 	// thread_handler.queue(new Animation_Simple_Indiv_RainbowCycle(&window3));

+	// thread_handler.queue(new Animation_Static_TransFlagWindows());
+
 	thread_handler.queue(new Animation_Advanced_Audio_MaxEqualizerWindow());
+
+	thread_handler.queue(new Animation_Seasonal_Indiv_Spring_ColorWipe(&window1));
+	thread_handler.queue(new Animation_Seasonal_Indiv_Spring_WindowColors(&window2));
+	thread_handler.queue(new Animation_Seasonal_Indiv_Spring_ColorWipe(&window3));
+
+	// thread_handler.queue(new Animation_Seasonal_Indiv_Weather_WindowLightRain(&window1));
+	// thread_handler.queue(new Animation_Seasonal_Indiv_Weather_WindowLightRain(&window2));
+	// thread_handler.queue(new Animation_Seasonal_Indiv_Weather_WindowLightRain(&window3));
+
+	// thread_handler.queue(new Animation_Simple_Indiv_ColorFade(&window1, COLOR_BLUE));
+	// thread_handler.queue(new Animation_Simple_Indiv_ColorFade(&window2, COLOR_GREEN));
+	// thread_handler.queue(new Animation_Simple_Indiv_ColorFade(&window3, COLOR_BLUE));
+
+	thread_handler.queue(new Animation_Holiday_EarthDay_WinAllFade());
 }


Adding scheme for days before workdays

Adding scheme for days before workdays

Adding scheme for days before workdays and adding a device timer for
days before workdays.

--- elfi/elfi.ino
+++ elfi/elfi.ino
@@ -116,6 +116,7 @@
 // DeviceTimer activities
 const uint8_t allDays[7] = {1, 1, 1, 1, 1, 1, 1};
 const uint8_t weekDays[7] = {0, 1, 1, 1, 1, 1, 0};
+const uint8_t beforeWorkday[7] = {1, 1, 1, 1, 1, 0, 0};
 const uint8_t weekendDays[7] = {1, 0, 0, 0, 0, 0, 1};

 const uint8_t all = -1;
@@ -127,12 +128,13 @@
   FunctionTimer(weekDays,   6, 40,  0, &update_RTC),   //  1 Update the RTC
 };

-DeviceTimer deviceTimers[5] = {
-  DeviceTimer(weekDays,     6, 40,  0, all, on),       //  1 Weekday morning on
-  DeviceTimer(weekDays,     7, 25,  0, all, off),      //  2 Weekday morning off
-  DeviceTimer(weekDays,    22, 30,  0, all, off),      //  3 Weekday night off
-  DeviceTimer(weekendDays,  8, 30,  0, all, on),       //  4 Weekend morning on
-  DeviceTimer(allDays,     23, 30,  0, all, off)       //  5 All days night off
+DeviceTimer deviceTimers[6] = {
+  DeviceTimer(weekDays,       6, 30,  0, all, on),     //  1 Weekday morning on
+  DeviceTimer(weekDays,       6, 40,  0, all, on),     //  2 Weekday morning on
+  DeviceTimer(weekDays,       7, 25,  0, all, off),    //  3 Weekday morning off
+  DeviceTimer(beforeWorkday, 22, 30,  0, all, off),    //  4 Before workday night off
+  DeviceTimer(weekendDays,    8, 30,  0, all, on),     //  5 Weekend morning on
+  DeviceTimer(allDays,       23, 30,  0, all, off)     //  6 All days night off
 };

 // DHCP, ethernet and web server -----------------------------------------------


add reference voltage

add reference voltage

--- Vsens/src/sketch.ino
+++ Vsens/src/sketch.ino
@@ -9,7 +9,7 @@
 #define activityLED 13

 // *** declare constants
-const float ref5V = 5.0;    // reference: 5.0V on measurePin == 1023.0
+const float ref5V = 5.14;   // reference: 5.0V on measurePin == 1023.0
 const float R1 = 100000.0;  // Resistor value used for R1
 const float R2 = 10000.0;   // Resistor value used for R2


Il testo delle chiamate in arrivo è ora settato a size 1

--- WerCA_nightly/WerCA_nightly.ino
+++ WerCA_nightly/WerCA_nightly.ino
@@ -469,6 +469,7 @@

             if(gotCallerNum && gotCallerID){
               display.clearDisplay();
+              display.setTextSize(1);
               display.drawBitmap(33, 0, incoming_16x22, 16, 22, BLACK);
               display.setCursor(2,22);
               display.print(F("Incoming call:"));


timestamp added

timestamp added

Using a timestamp to avoid reacting to interrupts cause by the
debounce-effect.

--- btnLed/src/sketch.ino
+++ btnLed/src/sketch.ino
@@ -12,40 +12,26 @@
 #define onoffPIN 3

 volatile int flag = LOW;
+unsigned long timestamp = 0;

 void setup()
 {
   pinMode(onoffPIN, OUTPUT);       // An LED to signal on or off state
-  attachInterrupt(0, ISRbutton, RISING); // Interrupt when button is pressed
-  //pinMode(pushbuttonPIN, INPUT);  // A button to switch the LED
+  attachInterrupt(0, interrupt, HIGH); // Interrupt when button is pressed
+}
+
+void interrupt()
+{
+  // Only change the flag if more than 1000 ms has passed since previous IRQ
+  // to avoid debouncing.
+  if ( (timestamp + 1000) < millis() )
+  {
+    flag = !flag;
+  }
+  timestamp = millis();
 }

 void loop()
 {
   digitalWrite(onoffPIN, flag);
-  // wait for a button press
-/*
-  if ((digitalRead(pushbuttonPIN) == HIGH) && (flag == LOW))
-  {
-    flag = HIGH;
-    digitalWrite(onoffLED, HIGH);
-    delay(500);
-    //digitalWrite(onoffLED,LOW);
-  }
-  if ((digitalRead(pushbuttonPIN) == HIGH) && (flag == HIGH))
-  {
-    flag = LOW;
-    digitalWrite(onoffLED, LOW);
-    delay(500);
-    //digitalWrite(onoffLED,LOW);
-  }
-*/
 }
-
-
-// toggles LED when interrupt pin changes state
-
-void ISRbutton()
-{
-  flag = !flag;
-}


unnecessary functions commented in code

unnecessary functions commented in code

--- hal100/hal100.ino
+++ hal100/hal100.ino
@@ -52,18 +52,18 @@
 char input; //buffer for input characters for calculations
 // char dataPrintout[10];

-float tuningFreqCalc = 0;   // float for value C calculation
-float KHz;                  // KHz constant
-float PlanckTime;           // Planck constant
-float pi;                   // π constant
-float valueC1 = 0;           // calculated value C float
-float valueCEffective = 0;  // calculated value C float
-float valueL = 0;           // calculated value L float
-float valueC1Corr = 0;      // calculated value C1 float
-float valueC2Corr = 0;      // calculated value C1 float
-float valueLcorr = 0;       // calculated value L float
-float Cmult;                // constant multiplier to calculate C value
-float Lmult;                // constant multiplier to calculate L value
+// float tuningFreqCalc = 0;   // float for value C calculation
+// float KHz;                  // KHz constant
+// float PlanckTime;           // Planck constant
+// float pi;                   // π constant
+// float valueC1 = 0;           // calculated value C float
+// float valueCEffective = 0;  // calculated value C float
+// float valueL = 0;           // calculated value L float
+// float valueC1Corr = 0;      // calculated value C1 float
+// float valueC2Corr = 0;      // calculated value C1 float
+// float valueLcorr = 0;       // calculated value L float
+// float Cmult;                // constant multiplier to calculate C value
+// float Lmult;                // constant multiplier to calculate L value
 float valueRotateC1;
 float valueRotateC2;
 float valueRotateL;
@@ -71,8 +71,8 @@

 boolean presentValue = false;

-String EnteredFreqString, TuningFreqString;
-String DisplayValueLstring;
+ String EnteredFreqString, TuningFreqString;
+ String DisplayValueLstring;

 int i;

@@ -168,70 +168,70 @@
   keypad.addEventListener(keypadEvent);             //add an event listener for this keypad
 }

-void SetFrequencyStage1() {
+//void SetFrequencyStage1() {
 	// STAGE 1 tuning process
-	calculateC();                                     // calculate C value at selected frequency
-	calculateStepsC();                                // calculate steps needed to move C to value C
-	CmoveStage1();                                    // send command to nano to move motor "C" to C step value
-	calculateL();                                     // calculate L value at given frequency and C value
-	calculateStepsL();                                // calculate steps needed to move C to value L
-	LmoveStage1();                                    // send command to nano to move motor "L" to L step value
-	EraseDisplayC1(), EraseDisplayL();                 // clear previous values L and C at display
-	displayC1(), displayL();                           // display current values L and C at display
-	mechSetPosition(round (valueRotateL), round (valueRotateC1), round (valueRotateC2));
+//	calculateC();                                     // calculate C value at selected frequency
+//	calculateStepsC();                                // calculate steps needed to move C to value C
+//	CmoveStage1();                                    // send command to nano to move motor "C" to C step value
+//	calculateL();                                     // calculate L value at given frequency and C value
+//	calculateStepsL();                                // calculate steps needed to move C to value L
+//	LmoveStage1();                                    // send command to nano to move motor "L" to L step value
+//	EraseDisplayC1(), EraseDisplayL();                 // clear previous values L and C at display
+//	displayC1(), displayL();                           // display current values L and C at display
+//	mechSetPosition(round (valueRotateL), round (valueRotateC1), round (valueRotateC2));
 	// End STAGE 1 tuning process
-}
-
-void SetFrequency() {                               // when # pressed - sets frequency value at the top of the screen
-  // Pre-STAGE 1 (coarse tuning process) cleanups and displays
+//}
+
+// Pre-STAGE 1 (coarse tuning process) cleanups and displays - will be used later
+void SetFrequency() {                               // when # pressed - sets frequency value at the bottom of the screen
   eraseFreqTopScreen();                             // clear previously entered drequesncy at display top
   eraseEnteredFrequency();                          // clear entered frequency at display bottom
   displayFreqTopScreen();                           // display desired frequesncy at display top
-  SetFrequencyStage1();
-}
-
-
-void incL(float diff) {
+//  SetFrequencyStage1();
+}
+
+
+void incL(float diff) {                             // rotate motor L with number of steps
   EraseDisplayL();
   valueRotateL = valueRotateL + diff;
   displayL();
   mechSetPosition(round (valueRotateL), round (valueRotateC1), round (valueRotateC2));
 }

-void incC1(float diff) {
+void incC1(float diff) {                            // rotate motor C1 Cold with number of steps
   EraseDisplayC1();
   valueRotateC1 = valueRotateC1 + diff;
   displayC1();
   mechSetPosition(round (valueRotateL), round (valueRotateC1), round (valueRotateC2));
 }

-void incC2(float diff) {
+void incC2(float diff) {                            // rotate motor C2 Hot with number of steps
   EraseDisplayC2();
   valueRotateC2 = valueRotateC2 + diff;
   displayC2();
   mechSetPosition(round (valueRotateL), round (valueRotateC1), round (valueRotateC2));
 }

-void incLCorr(float diff) {
-    if (tuningFreqCalc != 0.0) {
-      valueLcorr = valueLcorr + diff;
-      SetFrequencyStage1();
-    }
-}
-
-void incC1Corr(float diff) {
-    if (tuningFreqCalc != 0.0) {
-      valueC1Corr = valueC1Corr + diff;
-      SetFrequencyStage1();
-    }
-}
-
-void incC2Corr(float diff) {
-    if (tuningFreqCalc != 0.0) {
-      valueC2Corr = valueC2Corr + diff;
-      SetFrequencyStage1();
-    }
-}
+// void incLCorr(float diff) {
+//    if (tuningFreqCalc != 0.0) {
+//      valueLcorr = valueLcorr + diff;
+//      SetFrequencyStage1();
+//    }
+//}
+
+//void incC1Corr(float diff) {
+//    if (tuningFreqCalc != 0.0) {
+//      valueC1Corr = valueC1Corr + diff;
+//      SetFrequencyStage1();
+//    }
+//}
+
+//void incC2Corr(float diff) {
+//    if (tuningFreqCalc != 0.0) {
+//      valueC2Corr = valueC2Corr + diff;
+//      SetFrequencyStage1();
+//    }
+//}

 void eraseFreqTopScreen() {                      // erases frequency value from top of display
   TFTscreen.stroke(0, 20, 30);
@@ -326,84 +326,71 @@
   TFTscreen.text(enteredFreq, 50, 110);
 }

-void tuningDisplay() {
-  for (i = 0; i < 4; i++) {
-    TFTscreen.stroke(255, 255, 0);
-    TFTscreen.setTextSize(1);
-    TFTscreen.text("TUNING", 50, 45);
-    delay(1000);
-    TFTscreen.stroke(0, 20, 30);
-    TFTscreen.text("TUNING", 50, 45);
-    delay(500);
-  }
-}
-
-void calibrateMotors() {                         // when K pressed - calibrates and display "calibrating" on the screen
-  for (i = 0; i < 4; i++) {
-    TFTscreen.stroke(255, 255, 0);
-    TFTscreen.setTextSize(1);
-    TFTscreen.text("CALIBRATING", 40, 45);
-    delay(1000);
-    TFTscreen.stroke(0, 20, 30);
-    TFTscreen.text("CALIBRATING", 40, 45);
-    delay(500);
-  }
-}
-
-void calculateC() {                             // Calculate value C from entered frequency: C = 299792458 / (tuningFreq * 1000)
-  Serial.println(tuningFreq);
-  tuningFreqCalc = atof(tuningFreq);  // convert Freq input character array to a float
-  KHz = 1000;
-  PlanckTime = 299792458;
-  Cmult = 1.5;
-  valueCEffective = PlanckTime / ( tuningFreqCalc * KHz ) * Cmult;
-  valueC1 = valueCEffective + valueC1Corr;
-  Serial.print("Value C1 pF=");
-  Serial.println(valueC1);
-}
-
-void calculateL () {                            // Calculate "L" value from formula L=((1/(2*π*f*C))/(2*π*f))*1000000000000 (where f in KHz and C in pF)
-  pi = 3.14159;
-  Lmult = 1000000000000;
-  valueL = ((1 / (2 * pi * tuningFreqCalc * (valueCEffective))) / (2 * pi * tuningFreqCalc)) * Lmult + valueLcorr;
-  Serial.print("Value L uH=");
-  Serial.println(valueL);
-}
-
-void calculateStepsC() {                        // calculate needed steps for C
+//void tuningDisplay() {
+//  for (i = 0; i < 4; i++) {
+//    TFTscreen.stroke(255, 255, 0);
+//    TFTscreen.setTextSize(1);
+//    TFTscreen.text("TUNING", 50, 45);
+//    delay(1000);
+//    TFTscreen.stroke(0, 20, 30);
+//    TFTscreen.text("TUNING", 50, 45);
+//    delay(500);
+//  }
+//}
+
+//void calculateC() {                             // Calculate value C from entered frequency: C = 299792458 / (tuningFreq * 1000)
+//  Serial.println(tuningFreq);
+//  tuningFreqCalc = atof(tuningFreq);  // convert Freq input character array to a float
+//  KHz = 1000;
+//  PlanckTime = 299792458;
+//  Cmult = 1.5;
+//  valueCEffective = PlanckTime / ( tuningFreqCalc * KHz ) * Cmult;
+//  valueC1 = valueCEffective + valueC1Corr;
+//  Serial.print("Value C1 pF=");
+//  Serial.println(valueC1);
+//}
+
+//void calculateL () {                            // Calculate "L" value from formula L=((1/(2*π*f*C))/(2*π*f))*1000000000000 (where f in KHz and C in pF)
+//  pi = 3.14159;
+//  Lmult = 1000000000000;
+//  valueL = ((1 / (2 * pi * tuningFreqCalc * (valueCEffective))) / (2 * pi * tuningFreqCalc)) * Lmult + valueLcorr;
+//  Serial.print("Value L uH=");
+//  Serial.println(valueL);
+//}
+
+//void calculateStepsC() {                        // calculate needed steps for C
   // Process for linear capacitor with 44-408 pF - need to ajust or change for different capacitor
-  float totalStepsC = 2964;
-  float pFmin = 20;
-  float pFmax = 200;
-  float pFtotalValue = pFmax - pFmin;
-  Serial.println(pFtotalValue);
-  float pFperStep = pFtotalValue / ( totalStepsC / 2 );
-  Serial.println(pFperStep);
-  valueRotateC1 = ( valueC1 - pFmin ) / pFperStep;
-  Serial.print("steps C to rotate=");
-  Serial.println(valueRotateC1);
-}
-
-void CmoveStage1() {                            // Send commandn to move motor C
+//  float totalStepsC = 2964;
+//  float pFmin = 20;
+//  float pFmax = 200;
+// float pFtotalValue = pFmax - pFmin;
+//  Serial.println(pFtotalValue);
+//  float pFperStep = pFtotalValue / ( totalStepsC / 2 );
+//  Serial.println(pFperStep);
+//  valueRotateC1 = ( valueC1 - pFmin ) / pFperStep;
+//  Serial.print("steps C to rotate=");
+//  Serial.println(valueRotateC1);
+//}
+
+//void CmoveStage1() {                            // Send commandn to move motor C
 //  send syntax '2,valueRotateC;' to Nano
-}
-
-void calculateStepsL() {                        // calculate needed steps for L
+//}
+
+//void calculateStepsL() {                        // calculate needed steps for L
  // Process for non-linear variable inductor - need to ajust or change for different inductor
  // y = -0.0299x2 + 1.3867x + 0.5894
- float totalStepsL = 2964;                                                              // total motor steps for 1 rotation
- float LturnsRequred = ( -0.0299 * valueL * valueL ) + ( 1.3867 * valueL ) + 0.5894;    // poly math
- valueRotateL = LturnsRequred * totalStepsL;
- Serial.print("L turns requred=");
- Serial.println(LturnsRequred);
- Serial.print("steps L to rotate=");
- Serial.println(valueRotateL);
-
-}
-
-void LmoveStage1() {                            // Send commandn to move motor L
+// float totalStepsL = 2964;                                                              // total motor steps for 1 rotation
+// float LturnsRequred = ( -0.0299 * valueL * valueL ) + ( 1.3867 * valueL ) + 0.5894;    // poly math
+// valueRotateL = LturnsRequred * totalStepsL;
+// Serial.print("L turns requred=");
+// Serial.println(LturnsRequred);
+// Serial.print("steps L to rotate=");
+// Serial.println(valueRotateL);
+//}
+
+//void LmoveStage1() {                            // Send commandn to move motor L
 //  send syntax '1,valueRotateL;' to Nano
-}
+//}

 //Keypad events
 void keypadEvent(KeypadEvent eKey) {


struggling a bit with proper RSSI display

--- projects/rnw/watcher/watcher.ino
+++ projects/rnw/watcher/watcher.ino
@@ -66,10 +66,10 @@
         oled.print('b');

         // RSSI as dB
-        int rssi = 255 - rf.rssi;
         oled.setCursor(42, yPos);
-        oled.print(-rssi/2);
-        oled.print(rssi & 1 ? ".5dB" : ".0dB");
+        oled.print('-');
+        oled.print(rf.rssi/2);
+        oled.print(rf.rssi & 1 ? ".5dB" : ".0dB");

         // AFC as signed offset
         int afc = rf.afc;


- change startup animation - cleanup

- change startup animation
- cleanup

--- arduino-neopixel.ino
+++ arduino-neopixel.ino
@@ -1,7 +1,6 @@
 #include <Adafruit_NeoPixel.h>
-#define MAX_VAL 64  // 0 to 255 for brightness
-#define DELAY_TIME 50
-#define DELAY_TIME2 20
+#define MAX_VAL 64 // 0 to 255 for brightness 多くのLEDを制御した場合に、色が安定しない問題を解決するために設けた制限
+#define DELAY_TIME 10

 // Parameter 1 = number of pixels in strip
 // Parameter 2 = pin number (most are valid)
@@ -15,61 +14,19 @@
 char input[11];   // 文字列格納用
 String input_str;   // 文字列格納用
 int i = 0;  // 文字数のカウンタ
-boolean serialAvailable = true;

 void setup() {
   strip.begin();
   strip.show(); // Initialize all pixels to 'off'
   Serial.begin(9600);
-  colorWipe(strip.Color(MAX_VAL, MAX_VAL, MAX_VAL), DELAY_TIME2); // White
-  colorWipe(0, DELAY_TIME2);

-//  colorWipe(strip.Color(100, 250, 100), DELAY_TIME2);
-//  color(strip.Color(200,100,100));
-//  for (int i=0; i < strip.numPixels(); i++) {
-//    if(i < 30) {
-//      strip.setPixelColor(i, limitedColor(200,100,100));
-//    }
-//    else {
-//      strip.setPixelColor(i, limitedColor(200,100,100));
-//    }
-//  }
-//  strip.show();
+  // startup animation
+  rainbow(2);
+  colorWipe(strip.Color(MAX_VAL, MAX_VAL, MAX_VAL), DELAY_TIME); // White
+  colorWipe(0, DELAY_TIME);
 }

 void loop() {
-
-//  for (int i=0; i < strip.numPixels(); i++) {
-//    strip.setPixelColor(i, 0);
-//  }
-//  Serial.println(strip.getPixelColor(1));
-
-  // OKだった
-//  for(int i=0; i<strip.numPixels(); i++) {
-////    if(i < 59) {
-//      strip.setPixelColor(i, strip.Color(250, 100, 100));
-////    }
-////    else {
-////      strip.setPixelColor(i, strip.Color(255, 0, 0));
-////    }
-//
-//  }
-//  strip.show();
-
-
-//  strip.show();
-//  delay(100);
-//  for(int i=0; i<strip.numPixels(); i++) {
-//    strip.setPixelColor(i, strip.Color(250,100,100));
-//  }
-//  strip.show();
-//  color(strip.Color(255,0,0));
-
-  // しばらくすると赤になる
-//  color(strip.Color(200,100,100));
-//  color(strip.Color(255,100,100));
-//  color(strip.Color(250,100,100));
-
   if (0<Serial.available()) {
     String str = Serial.readStringUntil('\n');
     int r = str.substring(0,3).toInt();


commit

commit

--- watermeter/core.ino
+++ watermeter/core.ino
@@ -44,9 +44,9 @@
   } else {
     Vcc = "Battery: ";
     voltInt = analogRead(BAT_VOLT_PIN);
-    volt = (3300/1024*voltInt);
+    volt = 3300/1024*voltInt;
   }
-  Serial.printf("voltInt: %d\n", voltInt);
+/*  Serial.printf("voltInt: %d\n", voltInt);*/

     v += volt;


resistance measurement PoC

resistance measurement PoC


Add note set switching capabilities

Add note set switching capabilities

--- Guzheng/Guzheng.ino
+++ Guzheng/Guzheng.ino
@@ -1,11 +1,10 @@
 /* Code for laser guzheng
  * Copyright (C) 2016 Jason Lu
  *
- */
-
-
+ */
+
 // Some defines
-#define THRESHOLD 700
+#define THRESHOLD 500
 #define VOLUME 0x7F
 #define LASTPORT 4
 #define DELAY 10
@@ -16,7 +15,7 @@
 #define CHANGEINSTRUMENT 0xC0

 // Values for different notes
-int note8 = 0x68;
+int note8 = 0x48;
 int note7 = 0x47;
 int note6 = 0x45;
 int note5 = 0x43;
@@ -24,6 +23,8 @@
 int note3 = 0x40;
 int note2 = 0x3E;
 int note1 = 0x3C;
+
+int noteSet = 1;

 void setup()
 {
@@ -35,73 +36,77 @@
   // 0xC0 is the change instrument command
   // 0x39 is the instrument ID in hex
   Serial.write(CHANGEINSTRUMENT);
-  Serial.write(0x39);
+  Serial.write(0x68);
 }

 // Function for playing note based on ID
 void musicOn(int ID) {
-  switch (ID) {
-  case 1:
-    noteOn(NOTEON, note1, VOLUME);
-    break;
-  case 2:
-    noteOn(NOTEON, note2, VOLUME);
-    break;
-  case 3:
-    noteOn(NOTEON, note3, VOLUME);
-    break;
-  case 4:
-    noteOn(NOTEON, note4, VOLUME);
-    break;
-  case 5:
-    noteOn(NOTEON, note5, VOLUME);
-    break;
-  case 6:
-    noteOn(NOTEON, note6, VOLUME);
-    break;
-  case 7:
-    noteOn(NOTEON, note7, VOLUME);
-    break;
-  case 8:
-    noteOn(NOTEON, note8, VOLUME);
-    break;
-  default:
-    noteOn(NOTEOFF, note1, 0x00);
-    break;
+  if (noteSet == 1) {
+    switch (ID) {
+      case 1:
+        noteOn(NOTEON, note1, VOLUME);
+        break;
+      case 2:
+        noteOn(NOTEON, note2, VOLUME);
+        break;
+      case 3:
+        noteOn(NOTEON, note3, VOLUME);
+        break;
+      case 4:
+        noteOn(NOTEON, note4, VOLUME);
+        break;
+    }
+  } else if (noteSet == 2) {
+    switch (ID) {
+      case 1:
+        noteOn(NOTEON, note5, VOLUME);
+        break;
+      case 2:
+        noteOn(NOTEON, note6, VOLUME);
+        break;
+      case 3:
+        noteOn(NOTEON, note7, VOLUME);
+        break;
+      case 4:
+        noteOn(NOTEON, note8, VOLUME);
+        break;
+    }
   }
 }

 // Function for turning off a specific note based on ID
 // Just a slightly modified version of musicOn()
 void musicOff(int ID) {
-  switch (ID) {
-  case 1:
-    noteOn(NOTEOFF, note1, 0x7F);
-    break;
-  case 2:
-    noteOn(NOTEOFF, note2, 0x7F);
-    break;
-  case 3:
-    noteOn(NOTEOFF, note3, 0x7F);
-    break;
-  case 4:
-    noteOn(NOTEOFF, note4, 0x7F);
-    break;
-  case 5:
-    noteOn(NOTEOFF, note5, 0x7F);
-    break;
-  case 6:
-    noteOn(NOTEOFF, note6, 0x7F);
-    break;
-  case 7:
-    noteOn(NOTEOFF, note7, 0x7F);
-    break;
-  case 8:
-    noteOn(NOTEOFF, note8, 0x7F);
-    break;
-  default:
-    noteOn(NOTEOFF, note1, 0x00);
-    break;
+  if (noteSet == 1) {
+    switch (ID) {
+      case 1:
+        noteOn(NOTEOFF, note1, VOLUME);
+        break;
+      case 2:
+        noteOn(NOTEOFF, note2, VOLUME);
+        break;
+      case 3:
+        noteOn(NOTEOFF, note3, VOLUME);
+        break;
+      case 4:
+        noteOn(NOTEOFF, note4, VOLUME);
+        break;
+    }
+  } else if (noteSet == 2) {
+    switch (ID) {
+      case 1:
+        noteOn(NOTEOFF, note5, VOLUME);
+        break;
+      case 2:
+        noteOn(NOTEOFF, note6, VOLUME);
+        break;
+      case 3:
+        noteOn(NOTEOFF, note7, VOLUME);
+        break;
+      case 4:
+        noteOn(NOTEOFF, note8, VOLUME);
+        break;
+    }
   }
 }

@@ -113,7 +118,15 @@
     if(analogRead(i) > THRESHOLD) {
       // Beam has been cut
       // i+1 is because i is 0 indexed, but the ID starts with 1
-      musicOn(i + 1);
+      if (i < 4) {
+        musicOn(i + 1);
+      } else {
+        if (noteSet == 1) {
+          noteSet = 2;
+        } else {
+          noteSet = 1;
+        }
+      }
     } else {
       // Hand is gone. Stop the sound
       musicOff(i + 1);


less tiny wait for telnet codes

less tiny wait for telnet codes

git-svn-id: d8bfcd070c2c81762cca1b3912331324182919ba@20658 0d6f1817-ed0e-0410-87c9-987e46238f29

--- zimodem/pet2asc.ino
+++ zimodem/pet2asc.ino
@@ -117,7 +117,7 @@
 {
   int ct=0;
   while((stream->available()==0)
-  &&(ct++)<1000)
+  &&(ct++)<250)
     delay(1);
   return stream->read();
 }


Removed SPI include in 2x sketch

Removed SPI include in 2x sketch

--- sketches/OpenROV2x/OpenROV2x.ino
+++ sketches/OpenROV2x/OpenROV2x.ino
@@ -1,6 +1,5 @@
 // Includes
 #include <EEPROM.h>
-#include <SPI.h>

 #include "NArduinoManager.h"
 #include "NConfigManager.h"


Remove test code and songs

Remove test code and songs

--- EmotionalClothing.ino
+++ EmotionalClothing.ino
@@ -7,8 +7,6 @@
 #include "ColorUtil.h"

 LiquidCrystal lcd(1, 0, 9, 8, 7, 6);
-
-String fileNames[4] = {"BUGS2.WAV", "DAFFY1.WAV", "BUGS1.WAV", "DAFFY2.WAV"};

 const int button = A3;

@@ -47,7 +45,6 @@
   setupRGBSensor(tcs);
   lcd.begin(16, 2);
   lcd.clear();
-  lcd.print("Before");
   pinMode(button, INPUT);
 }

@@ -55,15 +52,10 @@
   root.rewind();
   FatReader file;

-  for (int i = 0; i < 4; i++) {
-    char fileName[fileNames[i].length() + 1];
-    fileNames[i].toCharArray(fileName, fileNames[i].length() + 1);
-
-    file.open(root, fileName);
-    wave.create(file);
-    wave.play();
-    while (wave.isplaying) delay(100);
-  }
+  file.open(root, "MACNTOSH.WAV");
+  wave.create(file);
+  wave.play();
+  while(wave.isplaying) delay(100);
 }

 void loop() {


added author information to demo code

added author information to demo code

--- examples/LTR303Example/LTR303Example.ino
+++ examples/LTR303Example/LTR303Example.ino
@@ -1,4 +1,6 @@
-/* LTR303-ALS library example sketch
+/*
+	LTR303-ALS library example sketch
+	Lovelesh, thingTronics

 This sketch shows how to use the LTR303 library to read the Lite-On LTR303-ALS light sensor.